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: "rejectPurchaseOrder", operation: "mutation", input: { id: t.string().description("Purchase order ID"), reason: t.string().description("Rejection reason"), }, body: async (context) => { const ctx = createContext(context); const db = getDB("main-db"); return db .transaction() .execute(async (trx) => { const result = await purchaseModules.commands.rejectPurchaseOrder( trx, { id: context.input.id, reason: context.input.reason, }, 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_SUBMITTED": throw new DomainError( `Purchase order is not in SUBMITTED status: ${context.input.id}`, ); case "PURCHASE_REJECTION_REASON_REQUIRED": throw new DomainError("Rejection reason is required"); 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: "DRAFT", }; }) .catch((err: unknown) => { if (err instanceof DomainError) throw err; throw new Error("Failed to reject the purchase order", { cause: err }); }); }, output: t .object({ id: t.string().description("Purchase order ID"), status: t.string().description("New order status"), }) .description("RejectPurchaseOrder response"), });