import { createContext, DomainError } from "@tailor-platform/erp-kit/app"; import { createResolver, t } from "@tailor-platform/sdk"; import { getDB } from "@/generated/kysely-tailordb"; import { purchaseModules } from "@/modules"; export default createResolver({ name: "closePurchaseOrder", operation: "mutation", input: { id: t.string().description("Purchase order ID"), closeReason: t.string({ optional: true }).description("Reason for closing the order"), writeOffRemaining: t .bool({ optional: true }) .description("Write off remaining open quantities"), }, body: async (context) => { const ctx = createContext(context); const db = getDB("main-db"); return db .transaction() .execute(async (trx) => { const result = await purchaseModules.commands.closePurchaseOrder( trx, { id: context.input.id, closeReason: context.input.closeReason ?? undefined, writeOffRemaining: context.input.writeOffRemaining ?? undefined, }, ctx, ); if (!result.ok) { switch (result.error.code) { case "PURCHASE_PURCHASE_ORDER_NOT_FOUND": throw new DomainError(`Purchase order not found: ${context.input.id}`); case "PURCHASE_PURCHASE_ORDER_NOT_CLOSABLE": throw new DomainError( `Purchase order cannot be closed in its current status: ${context.input.id}`, ); case "PURCHASE_OPEN_QUANTITY_REMAINS": throw new DomainError( `Open quantity remains on one or more lines; set writeOffRemaining to close anyway`, ); case "PURCHASE_CLOSE_REASON_REQUIRED": throw new DomainError( `A close reason is required when writing off remaining quantities`, ); case "INVENTORY_INVENTORY_SUPPLY_PLAN_NOT_FOUND": throw new DomainError("A related supply plan was not found."); case "INVENTORY_SUPPLY_PLAN_NOT_OPEN": throw new DomainError("A related supply plan is not open."); case "UNAUTHENTICATED": throw new DomainError("Authentication is required"); case "INSUFFICIENT_PERMISSION": throw new DomainError("You do not have permission to perform this action"); default: throw result.error satisfies never; } } return { id: result.value.purchaseOrderId, // A successful transition implies the target status. status: "CLOSED", }; }) .catch((err: unknown) => { if (err instanceof DomainError) throw err; throw new Error("Failed to close the purchase order", { cause: err }); }); }, output: t .object({ id: t.string().description("Purchase order ID"), status: t.string().description("New order status"), }) .description("ClosePurchaseOrder response"), });