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: "submitPurchaseOrder", 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.submitPurchaseOrder( 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_DRAFT": throw new DomainError(`Purchase order is not in DRAFT status: ${context.input.id}`); case "PURCHASE_EMPTY_PURCHASE_ORDER_LINES": throw new DomainError("Purchase order has no lines"); // NOTE: erp-kit historically defined // PURCHASE_DUPLICATE_EXTERNAL_SUPPLIER_ORDER_REFERENCE here, enforcing // per-company uniqueness of externalSupplierOrderReference at submit // time. DT deliberately reuses external references across POs and the // field carries no DB constraint, so that guard was wrong for us // (see DT IMS #717). erp-kit#738 removed the guard entirely in // erp-kit 0.42.0, so the error no longer exists and there is // intentionally no case for it. (Before 0.42.0 the guard was stripped // via a local pnpm patch, now retired.) case "PURCHASE_SUPPLIER_NOT_FOUND": throw new DomainError(`Supplier account not found: ${result.error.message}`); case "PURCHASE_SUPPLIER_NOT_ACTIVE": throw new DomainError( `Supplier account or its business partner is not active: ${result.error.message}`, ); case "PURCHASE_SUPPLIER_ACCOUNT_COMPANY_MISMATCH": throw new DomainError("The supplier account belongs to a different company."); 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: "SUBMITTED", }; }) .catch((err: unknown) => { if (err instanceof DomainError) throw err; throw new Error("Failed to submit the purchase order", { cause: err }); }); }, output: t .object({ id: t.string().description("Purchase order ID"), status: t.string().description("New order status"), }) .description("SubmitPurchaseOrder response"), });