import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { PositionNotFoundError, PositionAlreadyAbolishedError, PositionHasOpenAssignmentError, } from "../lib/errors.generated"; export interface AbolishPositionInput { id: string; effectiveEnd: Date; } /** Function: run Description: Closes the current generation of a Position (sets effectiveEnd) when the post is eliminated. */ export async function run(db: Transaction, input: AbolishPositionInput, _ctx: CommandContext) { const position = await db .selectFrom("Position") .selectAll() .where("id", "=", input.id) .forUpdate() .executeTakeFirst(); if (!position) return err(new PositionNotFoundError(input.id)); if (position.effectiveEnd !== null) return err(new PositionAlreadyAbolishedError(input.id)); const openAssignment = await db .selectFrom("Assignment") .select("id") .where("positionId", "=", input.id) .where("effectiveEnd", "is", null) .executeTakeFirst(); if (openAssignment) return err(new PositionHasOpenAssignmentError(input.id)); const updated = await db .updateTable("Position") .set({ effectiveEnd: input.effectiveEnd }) .where("id", "=", input.id) .returningAll() .executeTakeFirstOrThrow(); return ok({ position: updated }); }