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: "cancelPurchaseOrder", operation: "mutation", input: { id: t.string().description("Purchase order ID"), }, body: async (context) => { const ctx = createContext(context); const db = getDB("main-db"); return db .transaction() .execute(async (trx) => { const result = await purchaseModules.commands.cancelPurchaseOrder( trx, { id: context.input.id }, 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_CANCELLABLE": throw new DomainError( `Purchase order cannot be cancelled in its current status: ${context.input.id}`, ); case "PURCHASE_PURCHASE_ORDER_ALREADY_FULFILLED": throw new DomainError( `Cannot cancel: posted receipts or matched bills exist for this order`, ); 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: "CANCELLED", }; }) .catch((err: unknown) => { if (err instanceof DomainError) throw err; throw new Error("Failed to cancel the purchase order", { cause: err }); }); }, output: t .object({ id: t.string().description("Purchase order ID"), status: t.string().description("New order status"), }) .description("CancelPurchaseOrder response"), });