import { createContext, DomainError } from "@tailor-platform/erp-kit/app"; import { createResolver, t } from "@tailor-platform/sdk"; import { getDB } from "@/generated/kysely-tailordb"; import { arModulesExport } from "@/modules"; /** * cancelIncomingPayment — cancel a DRAFT incoming payment. * * Cancellation discards an unposted payment (its draft settlements are kept as * append-only history) and moves it DRAFT -> CANCELLED. It never touches the * general ledger — a POSTED payment must be reversed (reverseIncomingPayment), * not cancelled. `id` is the IncomingPayment id. This is the AR mirror of * `cancelOutgoingPayment`. */ export default createResolver({ name: "cancelIncomingPayment", operation: "mutation", input: { id: t.string().description("Incoming payment ID"), }, body: async (context) => { const ctx = createContext(context); const db = getDB("main-db"); return db .transaction() .execute(async (trx) => { const result = await arModulesExport.commands.cancelIncomingPayment( trx, { id: context.input.id }, ctx, ); if (!result.ok) { switch (result.error.code) { case "ACCOUNT_RECEIVABLE_INCOMING_PAYMENT_NOT_FOUND": throw new DomainError(`Incoming payment not found: ${context.input.id}`); case "ACCOUNT_RECEIVABLE_INCOMING_PAYMENT_INVALID_STATUS": throw new DomainError(`Only a DRAFT payment can be cancelled: ${context.input.id}`); 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.incomingPayment.id, status: result.value.incomingPayment.status, }; }) .catch((err: unknown) => { if (err instanceof DomainError) throw err; throw new Error("Failed to cancel the incoming payment", { cause: err }); }); }, output: t .object({ id: t.string().description("Cancelled incoming payment ID"), status: t.string().description("Lifecycle status (CANCELLED after cancellation)"), }) .description("Cancelled incoming payment"), });