import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { DuplicateJobProfileCodeError, JobProfileNotFoundError } from "../lib/errors.generated"; export type UpdateJobProfileInput = { id: string; } & { code?: string; jobFamily?: string; gradeReference?: string; requirements?: string | null; }; /** * Function: updateJobProfile * Updates role metadata — job family, grade reference, requirements, or code — on an * existing JobProfile in place. JobProfile is not effective-dated; updates correct the * record rather than creating a new generation. */ export async function run(db: Transaction, input: UpdateJobProfileInput, _ctx: CommandContext) { const jobProfile = await db .selectFrom("JobProfile") .selectAll() .where("id", "=", input.id) .forUpdate() .executeTakeFirst(); if (!jobProfile) { return err(new JobProfileNotFoundError(input.id)); } if (input.code !== undefined && input.code !== jobProfile.code) { const duplicate = await db .selectFrom("JobProfile") .selectAll() .where("code", "=", input.code) .where("id", "!=", input.id) .forUpdate() .executeTakeFirst(); if (duplicate) { return err(new DuplicateJobProfileCodeError(input.code)); } } const updates: { code?: string; jobFamily?: string; gradeReference?: string; requirements?: string | null; } = {}; if (input.code !== undefined) updates.code = input.code; if (input.jobFamily !== undefined) updates.jobFamily = input.jobFamily; if (input.gradeReference !== undefined) updates.gradeReference = input.gradeReference; if (input.requirements !== undefined) updates.requirements = input.requirements; const updated = await db .updateTable("JobProfile") .set(updates) .where("id", "=", input.id) .returningAll() .executeTakeFirstOrThrow(); return ok({ jobProfile: updated }); }