feat(procurement): record supplier payments and reversals

This commit is contained in:
mihir 2026-09-28 15:14:42 +05:30
parent 6d570c722e
commit 1be408bf4f
21 changed files with 772 additions and 11 deletions

View File

@ -35,7 +35,8 @@ Phase 1E provides a [provider-independent blueprint and test matrix](docs/phase1
Phase 2A adds organization-scoped [supplier and material master data](docs/procurement-api.md). Phase 2A adds organization-scoped [supplier and material master data](docs/procurement-api.md).
Phase 2B adds [purchase-order drafts and issuance](docs/purchase-orders-api.md). Phase 2B adds [purchase-order drafts and issuance](docs/purchase-orders-api.md).
Phase 2C adds [partial goods receipts and quality inspection](docs/goods-receipts-api.md). Phase 2C adds [partial goods receipts and quality inspection](docs/goods-receipts-api.md).
Phase 2D adds [supplier invoice matching and voids](docs/supplier-invoices-api.md). Supplier payments, material stock movements, and production remain later milestones. Phase 2D adds [supplier invoice matching and voids](docs/supplier-invoices-api.md).
Phase 2E adds [supplier payment records and reversals](docs/supplier-payments-api.md). Material stock movements and production remain later milestones.
### Swagger UI ### Swagger UI

View File

@ -18,6 +18,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase
- 2B (implemented): purchase-order drafts, issuance, and immutable price snapshots. - 2B (implemented): purchase-order drafts, issuance, and immutable price snapshots.
- 2C (implemented): partial goods receipts and QC decisions. - 2C (implemented): partial goods receipts and QC decisions.
- 2D (implemented): supplier invoice matching and auditable voids. Tax rules, payments, and documents remain separate milestones. - 2D (implemented): supplier invoice matching and auditable voids. Tax rules, payments, and documents remain separate milestones.
- 2E (implemented): external supplier payment records, partial balances, idempotent retries, and auditable reversals. Bank reconciliation and proof documents remain separate milestones.
## Phase 3: B2B and white label ## Phase 3: B2B and white label

View File

@ -15,4 +15,4 @@ The list accepts `limit` (default 25, maximum 100) and `offset` (default 0) quer
An invoice must refer to one issued purchase order. Each line uses the order's unit price; total merchandise, tax, and shipping charges are added with exact decimal arithmetic. Cumulative active invoice quantity cannot exceed QC-accepted receipt quantity. A voided invoice releases its billed quantity, but its original record and number remain in the audit trail. The database also enforces scoped foreign keys, line and header totals, invoice price matching, accepted-quantity limits, and immutability. An invoice must refer to one issued purchase order. Each line uses the order's unit price; total merchandise, tax, and shipping charges are added with exact decimal arithmetic. Cumulative active invoice quantity cannot exceed QC-accepted receipt quantity. A voided invoice releases its billed quantity, but its original record and number remain in the audit trail. The database also enforces scoped foreign keys, line and header totals, invoice price matching, accepted-quantity limits, and immutability.
Tax and shipping amounts are transcribed from the supplier document. The backend does not calculate tax rules or approve price variances in this phase. Supplier payments, payment status, and document attachments remain future work. No payment should be initiated solely from a recorded invoice until those controls exist. Tax and shipping amounts are transcribed from the supplier document. The backend does not calculate tax rules or approve price variances in this phase. [Supplier payment records](supplier-payments-api.md) can now be attached to invoices, but bank reconciliation and document attachments remain future work.

View File

@ -0,0 +1,18 @@
# Phase 2E: supplier payment records
This API records evidence of payments made outside Mani Candles. It does not initiate a bank transfer, call a payment gateway, or verify settlement with a bank.
All routes are under `/api/v1` and require a bearer token. Reads require `procurement.read`. Recording and reversing a payment require the separate `supplier_payment.manage` permission. Every lookup is scoped to the signed-in organization.
| Method | Route | Purpose |
| ------ | ---------------------------------------- | ---------------------------------------------------------- |
| GET | `/supplier-invoices/:invoiceId/payments` | Page through payments and read paid and outstanding totals |
| POST | `/supplier-invoices/:invoiceId/payments` | Record a partial or full payment |
| GET | `/supplier-payments/:id` | Read a payment and its reversal, if any |
| POST | `/supplier-payments/:id/reverse` | Reverse one payment with a reason |
Record with `{"idempotencyKey":"<uuid>","reference":"UTR-12345","method":"BANK_TRANSFER","amount":"50.00","paidDate":"2026-09-28"}`. Methods are `BANK_TRANSFER`, `UPI`, `CHEQUE`, `CASH`, and `OTHER`. The reference is normalized to uppercase and must be unique within the organization, including after reversal. For cash, use a unique internal voucher reference. Payment amount uses exactly two decimal places and must be positive. Currency comes from the invoice.
Reusing the same idempotency key with the same invoice and payload returns the original payment; a different payload returns `PAYMENT_REPLAY_CONFLICT`. A payment cannot exceed the invoice's outstanding total or be recorded against a void invoice. Reverse with `{"reason":"Bank transfer returned"}`. The reversal is immutable, releases the amount from the invoice balance, and can occur only once. An invoice with an active payment cannot be voided; reverse its payments first. All writes create audit events.
The list accepts `limit` (default 25, maximum 100) and `offset` (default 0). It returns `payableTotal`, `paidTotal`, `outstandingTotal`, `currency`, and the requested page of `payments`. Totals include all active payments regardless of the page. These are recorded accounting amounts, not bank-verified settlement status. Bank reconciliation, proof documents, and approval thresholds remain future work.

View File

@ -17,5 +17,6 @@
"20260923000116_purchase_order_integrity": "ed14ce76d1b29c8de890a89c8dd84216edd002e43732b75d0cdeab4fd8f51fb8", "20260923000116_purchase_order_integrity": "ed14ce76d1b29c8de890a89c8dd84216edd002e43732b75d0cdeab4fd8f51fb8",
"20260923001040_purchase_order_reconciliation": "63ddf7618ff14916512597cc16af2de07e0c093d345bb35e607ed830d3ef067e", "20260923001040_purchase_order_reconciliation": "63ddf7618ff14916512597cc16af2de07e0c093d345bb35e607ed830d3ef067e",
"20260928123638_goods_receipts_qc": "a09646d8a3a1f520495ddbe611c61437ddfcec4585486f94fc383d9b1312006c", "20260928123638_goods_receipts_qc": "a09646d8a3a1f520495ddbe611c61437ddfcec4585486f94fc383d9b1312006c",
"20260928130714_supplier_invoices": "63945cff1725929e90fe73ade79348480e04a36976dbdb2a021a574569c35049" "20260928130714_supplier_invoices": "63945cff1725929e90fe73ade79348480e04a36976dbdb2a021a574569c35049",
"20260928145745_supplier_payments": "012ff1c33c1afa8e6fd883925616f014e7cfdac258fac37ac2ae56739e95bf6d"
} }

View File

@ -0,0 +1,92 @@
CREATE TYPE "SupplierPaymentMethod" AS ENUM ('BANK_TRANSFER', 'UPI', 'CHEQUE', 'CASH', 'OTHER');
CREATE TABLE "supplier_payments" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"invoice_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"reference" VARCHAR(80) NOT NULL,
"method" "SupplierPaymentMethod" NOT NULL,
"currency" CHAR(3) NOT NULL,
"amount" DECIMAL(12,2) NOT NULL,
"paid_at" DATE NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_payments_pkey" PRIMARY KEY ("id"),
CONSTRAINT "supplier_payments_valid" CHECK (
"amount" > 0 AND "reference" ~ '^[A-Z0-9][A-Z0-9._/-]{0,79}$'
AND "request_hash" ~ '^[a-f0-9]{64}$'
)
);
CREATE UNIQUE INDEX "supplier_payments_organization_id_idempotency_key_key" ON "supplier_payments"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "supplier_payments_organization_id_reference_key" ON "supplier_payments"("organization_id", "reference");
CREATE UNIQUE INDEX "supplier_payments_id_organization_id_key" ON "supplier_payments"("id", "organization_id");
CREATE INDEX "supplier_payments_invoice_created_idx" ON "supplier_payments"("organization_id", "invoice_id", "created_at", "id");
ALTER TABLE "supplier_payments" ADD CONSTRAINT "supplier_payments_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_payments" ADD CONSTRAINT "supplier_payments_invoice_id_organization_id_fkey" FOREIGN KEY ("invoice_id", "organization_id") REFERENCES "supplier_invoices"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_payments" ADD CONSTRAINT "supplier_payments_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "supplier_payment_reversals" (
"payment_id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"reversed_by_id" UUID NOT NULL,
"reason" VARCHAR(500) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_payment_reversals_pkey" PRIMARY KEY ("payment_id"),
CONSTRAINT "supplier_payment_reversals_reason" CHECK (LENGTH(TRIM("reason")) > 0)
);
CREATE UNIQUE INDEX "supplier_payment_reversals_payment_id_organization_id_key" ON "supplier_payment_reversals"("payment_id", "organization_id");
ALTER TABLE "supplier_payment_reversals" ADD CONSTRAINT "supplier_payment_reversals_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_payment_reversals" ADD CONSTRAINT "supplier_payment_reversal_payment_scope_fkey" FOREIGN KEY ("payment_id", "organization_id") REFERENCES "supplier_payments"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_payment_reversals" ADD CONSTRAINT "supplier_payment_reversal_actor_scope_fkey" FOREIGN KEY ("reversed_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
UPDATE "roles" SET "permissions" = array_append("permissions", 'supplier_payment.manage')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('supplier_payment.manage' = ANY("permissions"));
CREATE FUNCTION check_supplier_payment() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE payable NUMERIC; invoice_currency CHAR(3); paid NUMERIC;
BEGIN
SELECT payable_total, currency INTO payable, invoice_currency FROM supplier_invoices WHERE id = NEW.invoice_id FOR UPDATE;
IF EXISTS (SELECT 1 FROM supplier_invoice_voids WHERE invoice_id = NEW.invoice_id) THEN
RAISE EXCEPTION 'Cannot pay a void supplier invoice';
END IF;
IF invoice_currency IS DISTINCT FROM NEW.currency THEN
RAISE EXCEPTION 'Supplier payment currency does not match invoice';
END IF;
SELECT COALESCE(SUM(sp.amount), 0) INTO paid
FROM supplier_payments sp LEFT JOIN supplier_payment_reversals sr ON sr.payment_id = sp.id
WHERE sp.invoice_id = NEW.invoice_id AND sr.payment_id IS NULL;
IF paid + NEW.amount > payable THEN
RAISE EXCEPTION 'Supplier payment exceeds invoice balance';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER supplier_payment_balance BEFORE INSERT ON supplier_payments FOR EACH ROW EXECUTE FUNCTION check_supplier_payment();
CREATE FUNCTION check_supplier_invoice_void_payment() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
PERFORM id FROM supplier_invoices WHERE id = NEW.invoice_id FOR UPDATE;
IF EXISTS (
SELECT 1 FROM supplier_payments sp LEFT JOIN supplier_payment_reversals sr ON sr.payment_id = sp.id
WHERE sp.invoice_id = NEW.invoice_id AND sr.payment_id IS NULL
) THEN RAISE EXCEPTION 'Cannot void an invoice with active payments'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER supplier_invoice_void_payment_guard BEFORE INSERT ON supplier_invoice_voids FOR EACH ROW EXECUTE FUNCTION check_supplier_invoice_void_payment();
CREATE FUNCTION lock_supplier_payment_invoice() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
PERFORM id FROM supplier_invoices WHERE id = (SELECT invoice_id FROM supplier_payments WHERE id = NEW.payment_id) FOR UPDATE;
RETURN NEW;
END;
$$;
CREATE TRIGGER supplier_payment_reversal_lock BEFORE INSERT ON supplier_payment_reversals FOR EACH ROW EXECUTE FUNCTION lock_supplier_payment_invoice();
CREATE FUNCTION reject_supplier_payment_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'Supplier payment records are immutable'; END;
$$;
CREATE TRIGGER supplier_payments_immutable BEFORE UPDATE OR DELETE ON supplier_payments FOR EACH ROW EXECUTE FUNCTION reject_supplier_payment_mutation();
CREATE TRIGGER supplier_payment_reversals_immutable BEFORE UPDATE OR DELETE ON supplier_payment_reversals FOR EACH ROW EXECUTE FUNCTION reject_supplier_payment_mutation();

View File

@ -24,6 +24,14 @@ enum PurchaseOrderStatus {
CANCELLED CANCELLED
} }
enum SupplierPaymentMethod {
BANK_TRANSFER
UPI
CHEQUE
CASH
OTHER
}
model Supplier { model Supplier {
id String @id @default(uuid()) @db.Uuid id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid organizationId String @map("organization_id") @db.Uuid
@ -201,6 +209,7 @@ model SupplierInvoice {
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict) createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines SupplierInvoiceLine[] lines SupplierInvoiceLine[]
void SupplierInvoiceVoid? void SupplierInvoiceVoid?
payments SupplierPayment[]
@@unique([organizationId, supplierId, invoiceNumber]) @@unique([organizationId, supplierId, invoiceNumber])
@@unique([id, purchaseOrderId, organizationId]) @@unique([id, purchaseOrderId, organizationId])
@@unique([id, organizationId]) @@unique([id, organizationId])
@ -236,3 +245,40 @@ model SupplierInvoiceVoid {
@@unique([invoiceId, organizationId]) @@unique([invoiceId, organizationId])
@@map("supplier_invoice_voids") @@map("supplier_invoice_voids")
} }
model SupplierPayment {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
invoiceId String @map("invoice_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
reference String @db.VarChar(80)
method SupplierPaymentMethod
currency String @db.Char(3)
amount Decimal @db.Decimal(12,2)
paidAt DateTime @map("paid_at") @db.Date
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
invoice SupplierInvoice @relation(fields: [invoiceId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
reversal SupplierPaymentReversal?
@@unique([organizationId, idempotencyKey])
@@unique([organizationId, reference])
@@unique([id, organizationId])
@@index([organizationId, invoiceId, createdAt, id], map: "supplier_payments_invoice_created_idx")
@@map("supplier_payments")
}
model SupplierPaymentReversal {
paymentId String @id @map("payment_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
reversedById String @map("reversed_by_id") @db.Uuid
reason String @db.VarChar(500)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
payment SupplierPayment @relation(fields: [paymentId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "supplier_payment_reversal_payment_scope_fkey")
reversedBy User @relation(fields: [reversedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "supplier_payment_reversal_actor_scope_fkey")
@@unique([paymentId, organizationId])
@@map("supplier_payment_reversals")
}

View File

@ -31,6 +31,8 @@ model Organization {
receiptInspections ReceiptInspection[] receiptInspections ReceiptInspection[]
supplierInvoices SupplierInvoice[] supplierInvoices SupplierInvoice[]
supplierInvoiceVoids SupplierInvoiceVoid[] supplierInvoiceVoids SupplierInvoiceVoid[]
supplierPayments SupplierPayment[]
supplierPaymentReversals SupplierPaymentReversal[]
@@map("organizations") @@map("organizations")
} }
model User { model User {
@ -53,6 +55,8 @@ model User {
receiptInspections ReceiptInspection[] receiptInspections ReceiptInspection[]
supplierInvoices SupplierInvoice[] supplierInvoices SupplierInvoice[]
supplierInvoiceVoids SupplierInvoiceVoid[] supplierInvoiceVoids SupplierInvoiceVoid[]
supplierPayments SupplierPayment[]
supplierPaymentReversals SupplierPaymentReversal[]
stockEntries StockLedger[] stockEntries StockLedger[]
stockReservations StockReservation[] stockReservations StockReservation[]
carts Cart[] carts Cart[]

View File

@ -196,4 +196,39 @@ export const COMMERCE_ERRORS = {
'Supplier invoice is already void', 'Supplier invoice is already void',
'Duplicate supplier invoice void rejected', 'Duplicate supplier invoice void rejected',
], ],
INVOICE_PAYMENT_EXISTS: [
409,
'Reverse active payments before voiding this invoice',
'Supplier invoice void blocked by active payment',
],
PAYMENT_NOT_FOUND: [
404,
'Supplier payment not found',
'Scoped supplier payment lookup failed',
],
PAYMENT_INVOICE_VOID: [
409,
'Cannot record payment for a void invoice',
'Supplier payment rejected for void invoice',
],
PAYMENT_AMOUNT_LIMIT: [
409,
'Payment exceeds the remaining invoice balance',
'Supplier payment balance exceeded',
],
PAYMENT_REFERENCE_CONFLICT: [
409,
'Payment reference is already recorded',
'Supplier payment reference duplicate',
],
PAYMENT_REPLAY_CONFLICT: [
409,
'Idempotency key was used for a different payment',
'Supplier payment idempotency payload mismatch',
],
PAYMENT_ALREADY_REVERSED: [
409,
'Supplier payment is already reversed',
'Duplicate supplier payment reversal rejected',
],
} as const; } as const;

View File

@ -0,0 +1,9 @@
import { createHash } from 'node:crypto';
import { AppError } from './errors/app-error';
export function commandHash(...parts: (string | number)[]): string {
return createHash('sha256').update(JSON.stringify(parts)).digest('hex');
}
export function assertReplay(expected: string, actual: string): void {
if (expected !== actual) throw new AppError('IDEMPOTENCY_CONFLICT');
}

View File

@ -22,5 +22,6 @@ export const PERMISSIONS = [
'inventory.commit', 'inventory.commit',
'procurement.read', 'procurement.read',
'procurement.manage', 'procurement.manage',
'supplier_payment.manage',
] as const; ] as const;
export type Permission = (typeof PERMISSIONS)[number]; export type Permission = (typeof PERMISSIONS)[number];

View File

@ -1,12 +1,5 @@
import { createHash } from 'node:crypto';
import { AppError } from '../common/errors/app-error'; import { AppError } from '../common/errors/app-error';
export { commandHash, assertReplay } from '../common/idempotency';
export function commandHash(...parts: (string | number)[]): string {
return createHash('sha256').update(JSON.stringify(parts)).digest('hex');
}
export function assertReplay(expected: string, actual: string): void {
if (expected !== actual) throw new AppError('IDEMPOTENCY_CONFLICT');
}
export function adjustedBalance( export function adjustedBalance(
onHand: number, onHand: number,
reserved: number, reserved: number,

View File

@ -7,6 +7,11 @@ import { PurchaseOrdersController } from './purchase-orders.controller';
import { PurchaseOrderStore } from './purchase-order.store'; import { PurchaseOrderStore } from './purchase-order.store';
import { GoodsReceiptStore } from './goods-receipt.store'; import { GoodsReceiptStore } from './goods-receipt.store';
import { SupplierInvoiceStore } from './supplier-invoice.store'; import { SupplierInvoiceStore } from './supplier-invoice.store';
import { SupplierPaymentStore } from './supplier-payment.store';
import {
InvoicePaymentsController,
SupplierPaymentsController,
} from './supplier-payments.controller';
import { import {
OrderInvoicesController, OrderInvoicesController,
SupplierInvoicesController, SupplierInvoicesController,
@ -23,6 +28,7 @@ import {
PurchaseOrderStore, PurchaseOrderStore,
GoodsReceiptStore, GoodsReceiptStore,
SupplierInvoiceStore, SupplierInvoiceStore,
SupplierPaymentStore,
], ],
controllers: [ controllers: [
ProcurementController, ProcurementController,
@ -31,6 +37,8 @@ import {
ReceiptInspectionController, ReceiptInspectionController,
OrderInvoicesController, OrderInvoicesController,
SupplierInvoicesController, SupplierInvoicesController,
InvoicePaymentsController,
SupplierPaymentsController,
], ],
}) })
export class ProcurementModule {} export class ProcurementModule {}

View File

@ -161,6 +161,15 @@ export class SupplierInvoiceStore {
}); });
if (!invoice) throw new AppError('INVOICE_NOT_FOUND'); if (!invoice) throw new AppError('INVOICE_NOT_FOUND');
if (invoice.void) throw new AppError('INVOICE_ALREADY_VOID'); if (invoice.void) throw new AppError('INVOICE_ALREADY_VOID');
const activePayment = await tx.supplierPayment.findFirst({
where: {
organizationId: actor.organizationId,
invoiceId: id,
reversal: { is: null },
},
select: { id: true },
});
if (activePayment) throw new AppError('INVOICE_PAYMENT_EXISTS');
await tx.supplierInvoiceVoid.create({ await tx.supplierInvoiceVoid.create({
data: { data: {
invoiceId: id, invoiceId: id,

View File

@ -0,0 +1,18 @@
import { AppError } from '../common/errors/app-error';
import { scaled } from './purchase-order-money';
const format = (cents: bigint) =>
`${cents / 100n}.${(cents % 100n).toString().padStart(2, '0')}`;
export function paymentBalance(payable: string, paid: string) {
const remaining = scaled(payable, 2) - scaled(paid, 2);
if (remaining < 0n) throw new AppError('PAYMENT_AMOUNT_LIMIT');
return { paidTotal: paid, outstandingTotal: format(remaining) };
}
export function assertCanPay(
payable: string,
paid: string,
amount: string,
): void {
if (scaled(paid, 2) + scaled(amount, 2) > scaled(payable, 2))
throw new AppError('PAYMENT_AMOUNT_LIMIT');
}

View File

@ -0,0 +1,30 @@
import { z } from 'zod';
const amount = z
.string()
.regex(/^(0|[1-9]\d{0,9})\.\d{2}$/)
.refine((value) => value !== '0.00');
export const supplierPaymentSchema = z
.object({
idempotencyKey: z.uuid(),
reference: z
.string()
.trim()
.min(1)
.max(80)
.regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/)
.transform((value) => value.toUpperCase()),
method: z.enum(['BANK_TRANSFER', 'UPI', 'CHEQUE', 'CASH', 'OTHER']),
amount,
paidDate: z.iso
.date()
.transform((value) => new Date(`${value}T00:00:00.000Z`)),
})
.strict();
export const supplierPaymentReversalSchema = z
.object({ reason: z.string().trim().min(1).max(500) })
.strict();
export type SupplierPaymentInput = z.infer<typeof supplierPaymentSchema>;
export type SupplierPaymentReversalInput = z.infer<
typeof supplierPaymentReversalSchema
>;

View File

@ -0,0 +1,171 @@
import { Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { commandHash } from '../common/idempotency';
import { DatabaseService } from '../database/database.service';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { PageInput } from '../identity/identity.schemas';
import type { Principal } from '../identity/identity.types';
import { assertCanPay, paymentBalance } from './supplier-payment-money';
import type {
SupplierPaymentInput,
SupplierPaymentReversalInput,
} from './supplier-payment.schemas';
const paymentView = { reversal: true };
const activePayments = (organizationId: string, invoiceId: string) => ({
organizationId,
invoiceId,
reversal: { is: null },
});
const requestHash = (invoiceId: string, input: SupplierPaymentInput) =>
commandHash(
invoiceId,
input.reference,
input.method,
input.amount,
input.paidDate.toISOString().slice(0, 10),
);
@Injectable()
export class SupplierPaymentStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async list(actor: Principal, invoiceId: string, query: PageInput) {
const invoice = await this.db.supplierInvoice.findFirst({
where: { id: invoiceId, organizationId: actor.organizationId },
});
if (!invoice) throw new AppError('INVOICE_NOT_FOUND');
const [sum, payments] = await Promise.all([
this.db.supplierPayment.aggregate({
where: activePayments(actor.organizationId, invoiceId),
_sum: { amount: true },
}),
this.db.supplierPayment.findMany({
where: { organizationId: actor.organizationId, invoiceId },
include: paymentView,
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit,
skip: query.offset,
}),
]);
return {
invoiceId,
currency: invoice.currency,
payableTotal: invoice.payableTotal.toFixed(2),
...paymentBalance(
invoice.payableTotal.toFixed(2),
sum._sum.amount?.toFixed(2) ?? '0.00',
),
payments,
};
}
async find(actor: Principal, id: string) {
const payment = await this.db.supplierPayment.findFirst({
where: { id, organizationId: actor.organizationId },
include: paymentView,
});
if (!payment) throw new AppError('PAYMENT_NOT_FOUND');
return payment;
}
create(actor: Principal, invoiceId: string, input: SupplierPaymentInput) {
return this.access.mutate(actor, 'supplier_payment.manage', async (tx) => {
const hash = requestHash(invoiceId, input);
const replay = await tx.supplierPayment.findUnique({
where: {
organizationId_idempotencyKey: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
},
include: paymentView,
});
if (replay) {
if (replay.requestHash !== hash)
throw new AppError('PAYMENT_REPLAY_CONFLICT');
return replay;
}
const invoice = await tx.supplierInvoice.findFirst({
where: { id: invoiceId, organizationId: actor.organizationId },
include: { void: true },
});
if (!invoice) throw new AppError('INVOICE_NOT_FOUND');
if (invoice.void) throw new AppError('PAYMENT_INVOICE_VOID');
const duplicate = await tx.supplierPayment.findFirst({
where: {
organizationId: actor.organizationId,
reference: input.reference,
},
select: { id: true },
});
if (duplicate) throw new AppError('PAYMENT_REFERENCE_CONFLICT');
const sum = await tx.supplierPayment.aggregate({
where: activePayments(actor.organizationId, invoiceId),
_sum: { amount: true },
});
assertCanPay(
invoice.payableTotal.toFixed(2),
sum._sum.amount?.toFixed(2) ?? '0.00',
input.amount,
);
const payment = await tx.supplierPayment.create({
data: {
organizationId: actor.organizationId,
invoiceId,
createdById: actor.userId,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
reference: input.reference,
method: input.method,
currency: invoice.currency,
amount: input.amount,
paidAt: input.paidDate,
},
include: paymentView,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'supplier_payment.recorded',
payment.id,
);
return payment;
});
}
reverse(actor: Principal, id: string, input: SupplierPaymentReversalInput) {
return this.access.mutate(actor, 'supplier_payment.manage', async (tx) => {
const payment = await tx.supplierPayment.findFirst({
where: { id, organizationId: actor.organizationId },
include: paymentView,
});
if (!payment) throw new AppError('PAYMENT_NOT_FOUND');
if (payment.reversal) throw new AppError('PAYMENT_ALREADY_REVERSED');
await tx.supplierPaymentReversal.create({
data: {
paymentId: id,
organizationId: actor.organizationId,
reversedById: actor.userId,
reason: input.reason,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'supplier_payment.reversed',
id,
);
return tx.supplierPayment.findUniqueOrThrow({
where: { id },
include: paymentView,
});
});
}
}

View File

@ -0,0 +1,69 @@
import {
Body,
Controller,
Get,
Param,
ParseUUIDPipe,
Post,
Query,
} from '@nestjs/common';
import { SchemaPipe } from '../common/validation.pipe';
import {
CurrentPrincipal,
RequirePermission,
} from '../identity/access.decorator';
import { pageSchema, type PageInput } from '../identity/identity.schemas';
import type { Principal } from '../identity/identity.types';
import { SupplierPaymentStore } from './supplier-payment.store';
import {
supplierPaymentSchema,
supplierPaymentReversalSchema,
type SupplierPaymentInput,
type SupplierPaymentReversalInput,
} from './supplier-payment.schemas';
@Controller('supplier-invoices/:invoiceId/payments')
export class InvoicePaymentsController {
constructor(private readonly payments: SupplierPaymentStore) {}
@Get()
@RequirePermission('procurement.read')
list(
@CurrentPrincipal() actor: Principal,
@Param('invoiceId', ParseUUIDPipe) invoiceId: string,
@Query(new SchemaPipe(pageSchema)) query: PageInput,
) {
return this.payments.list(actor, invoiceId, query);
}
@Post()
@RequirePermission('supplier_payment.manage')
create(
@CurrentPrincipal() actor: Principal,
@Param('invoiceId', ParseUUIDPipe) invoiceId: string,
@Body(new SchemaPipe(supplierPaymentSchema)) input: SupplierPaymentInput,
) {
return this.payments.create(actor, invoiceId, input);
}
}
@Controller('supplier-payments')
export class SupplierPaymentsController {
constructor(private readonly payments: SupplierPaymentStore) {}
@Get(':id')
@RequirePermission('procurement.read')
get(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.payments.find(actor, id);
}
@Post(':id/reverse')
@RequirePermission('supplier_payment.manage')
reverse(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(supplierPaymentReversalSchema))
input: SupplierPaymentReversalInput,
) {
return this.payments.reverse(actor, id, input);
}
}

View File

@ -88,3 +88,23 @@ export async function receiveAccepted(
.expect(201); .expect(201);
return receipt.body; return receipt.body;
} }
export async function seedSupplierInvoice(ctx: IdentityApp) {
const order = await seedPurchaseOrder(ctx);
await receiveAccepted(ctx, order, '1.000');
const invoice = await ctx
.api()
.post(`/api/v1/purchase-orders/${order.id}/invoices`)
.auth(ctx.token, auth)
.send({
invoiceNumber: `INV-${randomUUID().slice(0, 8)}`,
invoiceDate: '2026-09-28',
taxAmount: '0.00',
lines: [{ purchaseOrderLineId: order.lineId, quantity: '1.000' }],
})
.expect(201);
return {
order,
invoice: invoice.body as { id: string; payableTotal: string },
};
}

View File

@ -0,0 +1,23 @@
import {
assertCanPay,
paymentBalance,
} from '../src/procurement/supplier-payment-money';
describe('supplier payment money', () => {
it('computes exact partial and zero balances', () => {
expect(paymentBalance('120.00', '50.01')).toEqual({
paidTotal: '50.01',
outstandingTotal: '69.99',
});
expect(paymentBalance('120.00', '120.00').outstandingTotal).toBe('0.00');
expect(() => assertCanPay('120.00', '50.01', '69.99')).not.toThrow();
});
it('rejects overpayment', () => {
expect(() => assertCanPay('120.00', '50.01', '70.00')).toThrow(
expect.objectContaining({ code: 'PAYMENT_AMOUNT_LIMIT' }),
);
expect(() => paymentBalance('120.00', '120.01')).toThrow(
expect.objectContaining({ code: 'PAYMENT_AMOUNT_LIMIT' }),
);
});
});

View File

@ -0,0 +1,212 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
import { seedSupplierInvoice } from './helpers/procurement';
describe('supplier payment API', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
const payment = (
amount: string,
reference: string,
idempotencyKey = randomUUID(),
) => ({
idempotencyKey,
reference,
method: 'BANK_TRANSFER',
amount,
paidDate: '2026-09-28',
});
it('records partial payments, replays retries once, and prevents overpayment', async () => {
const { invoice } = await seedSupplierInvoice(ctx);
const path = `/api/v1/supplier-invoices/${invoice.id}/payments`;
const firstInput = payment('50.00', 'utr-001');
const first = await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(firstInput)
.expect(201);
expect(first.body).toMatchObject({
reference: 'UTR-001',
amount: '50',
currency: 'INR',
});
expect(
(
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(firstInput)
.expect(201)
).body.id,
).toBe(first.body.id);
expect(
(
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send({ ...firstInput, amount: '60.00' })
.expect(409)
).body.code,
).toBe('PAYMENT_REPLAY_CONFLICT');
expect(
(
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payment('1.00', 'UTR-001'))
.expect(409)
).body.code,
).toBe('PAYMENT_REFERENCE_CONFLICT');
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payment('70.00', 'UTR-002'))
.expect(201);
expect(
(
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payment('0.01', 'UTR-003'))
.expect(409)
).body.code,
).toBe('PAYMENT_AMOUNT_LIMIT');
const list = await ctx
.api()
.get(`${path}?limit=1&offset=1`)
.auth(ctx.token, auth)
.expect(200);
expect(list.body).toMatchObject({
payableTotal: '120.00',
paidTotal: '120.00',
outstandingTotal: '0.00',
});
expect(list.body.payments).toHaveLength(1);
expect(
await ctx.db.auditEvent.count({
where: { targetId: first.body.id, action: 'supplier_payment.recorded' },
}),
).toBe(1);
});
it('reverses once, releases balance, and protects invoice voiding', async () => {
const { invoice } = await seedSupplierInvoice(ctx);
const path = `/api/v1/supplier-invoices/${invoice.id}/payments`;
const input = payment('60.00', 'UTR-VOID');
const created = await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(input)
.expect(201);
const voidPath = `/api/v1/supplier-invoices/${invoice.id}/void`;
expect(
(
await ctx
.api()
.post(voidPath)
.auth(ctx.token, auth)
.send({ reason: 'Wrong invoice' })
.expect(409)
).body.code,
).toBe('INVOICE_PAYMENT_EXISTS');
const reversePath = `/api/v1/supplier-payments/${created.body.id}/reverse`;
const reversed = await ctx
.api()
.post(reversePath)
.auth(ctx.token, auth)
.send({ reason: 'Bank transfer returned' })
.expect(201);
expect(reversed.body.reversal.reason).toBe('Bank transfer returned');
expect(
(
await ctx
.api()
.post(reversePath)
.auth(ctx.token, auth)
.send({ reason: 'Again' })
.expect(409)
).body.code,
).toBe('PAYMENT_ALREADY_REVERSED');
expect(
(await ctx.api().get(path).auth(ctx.token, auth).expect(200)).body
.outstandingTotal,
).toBe('120.00');
await ctx
.api()
.post(voidPath)
.auth(ctx.token, auth)
.send({ reason: 'Wrong invoice' })
.expect(201);
expect(
(
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payment('1.00', 'UTR-AFTER'))
.expect(409)
).body.code,
).toBe('PAYMENT_INVOICE_VOID');
expect(
(await ctx.api().post(path).auth(ctx.token, auth).send(input).expect(201))
.body.id,
).toBe(created.body.id);
});
it('requires payment permission and isolates organizations', async () => {
const { invoice } = await seedSupplierInvoice(ctx);
const path = `/api/v1/supplier-invoices/${invoice.id}/payments`;
const reader = await secondActor(ctx, true, ['procurement.read']);
await ctx.api().get(path).auth(reader.token, auth).expect(200);
await ctx
.api()
.post(path)
.auth(reader.token, auth)
.send(payment('1.00', 'DENIED'))
.expect(403);
const payer = await secondActor(ctx, true, ['supplier_payment.manage']);
const created = await ctx
.api()
.post(path)
.auth(payer.token, auth)
.send(payment('1.00', 'ALLOWED'))
.expect(201);
const foreign = await secondActor(ctx, false, [
'procurement.read',
'supplier_payment.manage',
]);
expect(
(
await ctx
.api()
.get(`/api/v1/supplier-payments/${created.body.id}`)
.auth(foreign.token, auth)
.expect(404)
).body.code,
).toBe('PAYMENT_NOT_FOUND');
await ctx
.api()
.post(`/api/v1/supplier-payments/${created.body.id}/reverse`)
.auth(reader.token, auth)
.send({ reason: 'Denied' })
.expect(403);
});
});