import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { DuplicateWorkRegimeKeyError, WorkRegimeNotFoundError } from "../lib/errors.generated"; export type UpdateWorkRegimeInput = { id: string; } & { key?: string; displayName?: string; }; /** * Function: updateWorkRegime * Description: Corrects an work-regime catalog entry's key or displayName in * place. A key change that collides with another entry in the same company is * rejected. companyId and status are not changed here (status via * deactivate/reactivate). */ export async function run(db: Transaction, input: UpdateWorkRegimeInput, _ctx: CommandContext) { const workRegime = await db .selectFrom("WorkRegime") .selectAll() .where("id", "=", input.id) .forUpdate() .executeTakeFirst(); if (!workRegime) { return err(new WorkRegimeNotFoundError(input.id)); } if (input.key !== undefined && input.key !== workRegime.key) { const duplicate = await db .selectFrom("WorkRegime") .selectAll() .where("companyId", "=", workRegime.companyId) .where("key", "=", input.key) .where("id", "!=", input.id) .forUpdate() .executeTakeFirst(); if (duplicate) { return err(new DuplicateWorkRegimeKeyError(`${workRegime.companyId}:${input.key}`)); } } const updates: { key?: string; displayName?: string } = {}; if (input.key !== undefined) updates.key = input.key; if (input.displayName !== undefined) updates.displayName = input.displayName; const updated = await db .updateTable("WorkRegime") .set(updates) .where("id", "=", input.id) .returningAll() .executeTakeFirstOrThrow(); return ok({ workRegime: updated }); }