import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { TimeEntryCodeInUseError, TimeEntryCodeNotFoundError } from "../lib/errors.generated"; export interface DeleteTimeEntryCodeInput { id: string; } /** * Function: deleteTimeEntryCode * Description: Removes a TimeEntryCode only when it is referenced by no * WorkRule premium-category pin, preserving historical calculated results whose * traceability depends on the code's key. (EligibilityRule no longer grants * TimeEntryCodes — the TIME_ENTRY_CODE grant kind was dropped in #39 — so * there is no eligibility reference to check.) */ export async function run(db: Transaction, input: DeleteTimeEntryCodeInput, _ctx: CommandContext) { const timeEntryCode = await db .selectFrom("TimeEntryCode") .selectAll() .where("id", "=", input.id) .forUpdate() .executeTakeFirst(); if (!timeEntryCode) { return err(new TimeEntryCodeNotFoundError(input.id)); } const workRules = await db.selectFrom("WorkRule").selectAll().execute(); const referencedByWorkRule = workRules.some((workRule) => (workRule.premiumRatePercent ?? []).some((rate) => rate.key === timeEntryCode.key), ); if (referencedByWorkRule) { return err(new TimeEntryCodeInUseError(input.id)); } await db.deleteFrom("TimeEntryCode").where("id", "=", input.id).execute(); return ok({}); }