import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { DuplicateWorkRegimeKeyError } from "../lib/errors.generated"; export interface CreateWorkRegimeInput { companyId: string; key: string; displayName: string; } /** * Function: createWorkRegime * Description: Registers a company-scoped work-regime catalog entry (key + * displayName), created ACTIVE. The key is unique within its company, so * different companies can define their own work regimes independently. */ export async function run(db: Transaction, input: CreateWorkRegimeInput, _ctx: CommandContext) { const existing = await db .selectFrom("WorkRegime") .selectAll() .where("companyId", "=", input.companyId) .where("key", "=", input.key) .forUpdate() .executeTakeFirst(); if (existing) { return err(new DuplicateWorkRegimeKeyError(`${input.companyId}:${input.key}`)); } const workRegime = await db .insertInto("WorkRegime") .values({ companyId: input.companyId, key: input.key, displayName: input.displayName, status: "ACTIVE", }) .returningAll() .executeTakeFirstOrThrow(); return ok({ workRegime }); }