import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { WorkerNotFoundError, WorkerCodeTakenError } from "../lib/errors.generated"; /** Function: UpdateWorkerInput * Description: Corrects mutable personal attributes (workerCode) on an existing Worker */ export type UpdateWorkerInput = { id: string; } & { workerCode?: string; }; /** Function: run * Description: Update mutable personal attributes on a Worker without affecting employment or assignment history */ export async function run>( db: Transaction, input: UpdateWorkerInput & Partial, _ctx: CommandContext, ) { const { id, workerCode, ...customFields } = input; const worker = await db .selectFrom("Worker") .selectAll() .where("id", "=", id) .forUpdate() .executeTakeFirst(); if (!worker) return err(new WorkerNotFoundError(id)); if (workerCode !== undefined && workerCode !== worker.workerCode) { const existing = await db .selectFrom("Worker") .select("id") .where("workerCode", "=", workerCode) .where("id", "!=", id) .executeTakeFirst(); if (existing) return err(new WorkerCodeTakenError(workerCode)); } // Host-defined custom fields are updated alongside the builtin workerCode; a builtin column // provided in the input always wins over a custom field of the same name. const updates: Record = { ...(customFields as Record) }; if (workerCode !== undefined) updates.workerCode = workerCode; if (Object.keys(updates).length === 0) { return ok({ worker }); } const updated = await db .updateTable("Worker") .set(updates) .where("id", "=", id) .returningAll() .executeTakeFirstOrThrow(); return ok({ worker: updated }); }