import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { DuplicateJobProfileCodeError } from "../lib/errors.generated"; export interface CreateJobProfileInput { code: string; jobFamily: string; gradeReference: string; requirements?: string | null; } /** * Function: createJobProfile * Description: Defines a new role template (job profile) — job family, grade * reference, and requirements — that Positions can share as their role * definition. Rejects when the code is already used by another JobProfile. */ export async function run>( db: Transaction, input: CreateJobProfileInput & CF, _ctx: CommandContext, ) { const { code, jobFamily, gradeReference, requirements, ...customFields } = input; const existing = await db .selectFrom("JobProfile") .selectAll() .where("code", "=", code) .forUpdate() .executeTakeFirst(); if (existing) { return err(new DuplicateJobProfileCodeError(code)); } const jobProfile = await db .insertInto("JobProfile") .values({ ...(customFields as Record), code, jobFamily, gradeReference, requirements: requirements ?? null, }) .returningAll() .executeTakeFirstOrThrow(); return ok({ jobProfile }); }