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: "updateRole", operation: "mutation", input: { roleId: t.uuid().description("Role ID"), name: t.string({ optional: true }).description("New role name"), description: t.string({ optional: true }).description("New role description"), permissions: t.string({ array: true }).description("Desired permission keys"), }, 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 updateInput: { id: string; name?: string; description?: string | null; permissions?: string[]; } = { id: context.input.roleId, permissions: allPermissions, }; if (context.input.name != null) updateInput.name = context.input.name; if (context.input.description !== undefined) updateInput.description = context.input.description; const updateResult = await umModules.commands.updateRole(trx, updateInput, ctx); if (!updateResult.ok) { switch (updateResult.error.code) { case "USER_MANAGEMENT_ROLE_NOT_FOUND": throw new DomainError(`Role ${context.input.roleId} does not exist`); case "USER_MANAGEMENT_ROLE_ALREADY_EXISTS": throw new DomainError(`A role with name "${context.input.name}" already exists`); case "USER_MANAGEMENT_ROLE_NOT_ACTIVE": throw new DomainError(`Role ${context.input.roleId} is not active`); case "USER_MANAGEMENT_MISSING_REQUIRED_FIELD": throw new DomainError("Role name cannot be empty"); case "USER_MANAGEMENT_INVALID_PERMISSION": throw new DomainError(`Invalid permission format: ${updateResult.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 updateResult.error satisfies never; } } return { roleId: context.input.roleId }; }) .catch((err: unknown) => { if (err instanceof DomainError) throw err; throw new Error("Failed to update the role", { cause: err, }); }); return { roleId: result.roleId }; }, output: t .object({ roleId: t.uuid().description("Role ID"), }) .description("Role update result"), });