import { createContext, DomainError } from "@tailor-platform/erp-kit/app"; import { createResolver, t } from "@tailor-platform/sdk"; import { getDB } from "@/generated/kysely-tailordb"; import { umModules } from "@/modules"; const AUTO_ASSIGNED_SCOPES = ["user-management:profile"]; export default createResolver({ name: "createRole", operation: "mutation", input: { name: t.string().description("Role name"), description: t.string({ optional: true }).description("Role description"), permissions: t.string({ array: true }).description("Permission keys to assign"), }, body: async (context) => { const ctx = createContext(context); const db = getDB("main-db"); const allPermissions = [...new Set([...context.input.permissions, ...AUTO_ASSIGNED_SCOPES])]; const result = await db .transaction() .execute(async (trx) => { const cmdResult = await umModules.commands.createRole( trx, { name: context.input.name, description: context.input.description ?? undefined, permissions: allPermissions, }, ctx, ); if (!cmdResult.ok) { switch (cmdResult.error.code) { case "USER_MANAGEMENT_ROLE_ALREADY_EXISTS": throw new DomainError(`A role with name "${context.input.name}" already exists`); case "USER_MANAGEMENT_MISSING_REQUIRED_FIELD": throw new DomainError("Role name is required"); case "USER_MANAGEMENT_INVALID_PERMISSION": throw new DomainError(`Invalid permission format: ${cmdResult.error.message}`); case "UNAUTHENTICATED": throw new DomainError("Authentication is required"); case "INSUFFICIENT_PERMISSION": throw new DomainError("You do not have permission to perform this action"); default: throw cmdResult.error satisfies never; } } return { id: cmdResult.value.role.id, name: cmdResult.value.role.name, description: cmdResult.value.role.description ?? "", }; }) .catch((err: unknown) => { if (err instanceof DomainError) throw err; throw new Error("Failed to create the role", { cause: err, }); }); return result; }, output: t .object({ id: t.uuid().description("Role ID"), name: t.string().description("Role name"), description: t.string().description("Role description"), }) .description("Created role"), });