feat(procurement): match supplier invoices to accepted receipts #10

Merged
mihir merged 1 commits from feat/supplier-invoices into main 2026-09-28 14:56:17 +05:30
17 changed files with 906 additions and 62 deletions

View File

@ -34,7 +34,8 @@ Phase 1D adds versioned carts, coupons, atomic checkout and private order snapsh
Phase 1E provides a [provider-independent blueprint and test matrix](docs/phase1e-blueprint.md), configurable pricing snapshots and an [operational outbox/API](docs/operations-api.md). No real gateway or message delivery is enabled.
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 2C adds [partial goods receipts and quality inspection](docs/goods-receipts-api.md). Invoices, supplier payments, material stock movements, and production remain later milestones.
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.
### Swagger UI

View File

@ -14,6 +14,11 @@ Source: Mani Candles Commerce Platform specification and project pack created in
Suppliers, material/urli classification and compatibility, procurement, purchase orders, partial goods receipts, QC, invoices, supplier payments, private versioned documents and validation, BOM, production batches, consumption, wastage, packaging BOM and costing.
- 2A (implemented): supplier and material master data with supplier-material quotes.
- 2B (implemented): purchase-order drafts, issuance, and immutable price snapshots.
- 2C (implemented): partial goods receipts and QC decisions.
- 2D (implemented): supplier invoice matching and auditable voids. Tax rules, payments, and documents remain separate milestones.
## Phase 3: B2B and white label
Business verification, price lists, MOQ, quotations, credit policies, samples, branding/artwork approvals, partner purchase orders, partial payments, custom candle requests and partner reporting.

View File

@ -0,0 +1,18 @@
# Phase 2D: supplier invoices
All routes are under `/api/v1` and require a bearer token. Read routes require `procurement.read`; writes require `procurement.manage`. All records are scoped to the signed-in organization.
| Method | Route | Purpose |
| ------ | ------------------------------------ | ---------------------------------------------------------- |
| GET | `/purchase-orders/:orderId/invoices` | Page through invoices for an order, including void records |
| POST | `/purchase-orders/:orderId/invoices` | Record an invoice matched to QC-accepted goods |
| GET | `/supplier-invoices/:id` | Read an invoice and its lines |
| POST | `/supplier-invoices/:id/void` | Void an invoice with a reason |
Create with `{"invoiceNumber":"INV-001","invoiceDate":"2026-09-28","taxAmount":"18.00","shippingAmount":"5.00","lines":[{"purchaseOrderLineId":"<uuid>","quantity":"1.000"}]}`. Shipping defaults to `0.00`; tax must be provided explicitly. Invoice numbers are normalized to uppercase and remain reserved for the supplier even after voiding. Quantity uses exactly three decimal places and money uses exactly two.
The list accepts `limit` (default 25, maximum 100) and `offset` (default 0) query parameters.
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.

View File

@ -16,5 +16,6 @@
"20260913173146_purchase_orders": "1e226f158e57af94c03b8f749349d06a874a8e82c32094ebd638d0ec41dc762a",
"20260923000116_purchase_order_integrity": "ed14ce76d1b29c8de890a89c8dd84216edd002e43732b75d0cdeab4fd8f51fb8",
"20260923001040_purchase_order_reconciliation": "63ddf7618ff14916512597cc16af2de07e0c093d345bb35e607ed830d3ef067e",
"20260928123638_goods_receipts_qc": "a09646d8a3a1f520495ddbe611c61437ddfcec4585486f94fc383d9b1312006c"
"20260928123638_goods_receipts_qc": "a09646d8a3a1f520495ddbe611c61437ddfcec4585486f94fc383d9b1312006c",
"20260928130714_supplier_invoices": "63945cff1725929e90fe73ade79348480e04a36976dbdb2a021a574569c35049"
}

View File

@ -0,0 +1,110 @@
CREATE UNIQUE INDEX "purchase_orders_id_supplier_id_organization_id_key" ON "purchase_orders"("id", "supplier_id", "organization_id");
CREATE TABLE "supplier_invoices" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"purchase_order_id" UUID NOT NULL,
"supplier_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"invoice_number" VARCHAR(64) NOT NULL,
"invoice_date" DATE NOT NULL,
"currency" CHAR(3) NOT NULL,
"merchandise_total" DECIMAL(12,2) NOT NULL,
"tax_amount" DECIMAL(12,2) NOT NULL,
"shipping_amount" DECIMAL(12,2) NOT NULL,
"payable_total" DECIMAL(12,2) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_invoices_pkey" PRIMARY KEY ("id"),
CONSTRAINT "supplier_invoices_amounts" CHECK (
"merchandise_total" >= 0 AND "tax_amount" >= 0 AND "shipping_amount" >= 0
AND "payable_total" = "merchandise_total" + "tax_amount" + "shipping_amount"
AND "invoice_number" ~ '^[A-Z0-9][A-Z0-9._/-]{0,63}$'
)
);
CREATE UNIQUE INDEX "supplier_invoices_organization_id_supplier_id_invoice_numbe_key" ON "supplier_invoices"("organization_id", "supplier_id", "invoice_number");
CREATE UNIQUE INDEX "supplier_invoices_id_purchase_order_id_organization_id_key" ON "supplier_invoices"("id", "purchase_order_id", "organization_id");
CREATE UNIQUE INDEX "supplier_invoices_id_organization_id_key" ON "supplier_invoices"("id", "organization_id");
CREATE INDEX "supplier_invoices_order_created_idx" ON "supplier_invoices"("organization_id", "purchase_order_id", "created_at", "id");
ALTER TABLE "supplier_invoices" ADD CONSTRAINT "supplier_invoices_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_invoices" ADD CONSTRAINT "supplier_invoices_order_scope_fkey" FOREIGN KEY ("purchase_order_id", "supplier_id", "organization_id") REFERENCES "purchase_orders"("id", "supplier_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_invoices" ADD CONSTRAINT "supplier_invoices_supplier_id_organization_id_fkey" FOREIGN KEY ("supplier_id", "organization_id") REFERENCES "suppliers"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_invoices" ADD CONSTRAINT "supplier_invoices_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_invoice_lines" (
"id" UUID NOT NULL,
"invoice_id" UUID NOT NULL,
"purchase_order_id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"purchase_order_line_id" UUID NOT NULL,
"quantity" DECIMAL(12,3) NOT NULL,
"unit_price" DECIMAL(12,2) NOT NULL,
"line_total" DECIMAL(12,2) NOT NULL,
CONSTRAINT "supplier_invoice_lines_pkey" PRIMARY KEY ("id"),
CONSTRAINT "supplier_invoice_lines_amounts" CHECK ("quantity" > 0 AND "unit_price" >= 0 AND "line_total" = ROUND("quantity" * "unit_price", 2))
);
CREATE UNIQUE INDEX "supplier_invoice_lines_invoice_id_purchase_order_line_id_key" ON "supplier_invoice_lines"("invoice_id", "purchase_order_line_id");
CREATE INDEX "supplier_invoice_lines_organization_id_purchase_order_line__idx" ON "supplier_invoice_lines"("organization_id", "purchase_order_line_id");
ALTER TABLE "supplier_invoice_lines" ADD CONSTRAINT "supplier_invoice_lines_invoice_scope_fkey" FOREIGN KEY ("invoice_id", "purchase_order_id", "organization_id") REFERENCES "supplier_invoices"("id", "purchase_order_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_invoice_lines" ADD CONSTRAINT "supplier_invoice_lines_order_line_scope_fkey" FOREIGN KEY ("purchase_order_line_id", "purchase_order_id", "organization_id") REFERENCES "purchase_order_lines"("id", "purchase_order_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "supplier_invoice_voids" (
"invoice_id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"voided_by_id" UUID NOT NULL,
"reason" VARCHAR(500) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_invoice_voids_pkey" PRIMARY KEY ("invoice_id"),
CONSTRAINT "supplier_invoice_voids_reason" CHECK (LENGTH(TRIM("reason")) > 0)
);
CREATE UNIQUE INDEX "supplier_invoice_voids_invoice_id_organization_id_key" ON "supplier_invoice_voids"("invoice_id", "organization_id");
ALTER TABLE "supplier_invoice_voids" ADD CONSTRAINT "supplier_invoice_voids_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_invoice_voids" ADD CONSTRAINT "supplier_invoice_voids_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_invoice_voids" ADD CONSTRAINT "supplier_invoice_voids_voided_by_id_organization_id_fkey" FOREIGN KEY ("voided_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION check_supplier_invoice_order() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM purchase_orders WHERE id = NEW.purchase_order_id AND status = 'ISSUED' AND currency = NEW.currency) THEN
RAISE EXCEPTION 'Invoice requires an issued order in matching currency';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER supplier_invoice_order_check BEFORE INSERT ON supplier_invoices FOR EACH ROW EXECUTE FUNCTION check_supplier_invoice_order();
CREATE FUNCTION reconcile_supplier_invoice() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE target_id UUID; expected NUMERIC; actual NUMERIC; line_count INTEGER;
BEGIN
IF TG_TABLE_NAME = 'supplier_invoices' THEN target_id := NEW.id; ELSE target_id := NEW.invoice_id; END IF;
SELECT merchandise_total INTO expected FROM supplier_invoices WHERE id = target_id;
SELECT COALESCE(SUM(line_total), 0), COUNT(*) INTO actual, line_count FROM supplier_invoice_lines WHERE invoice_id = target_id;
IF expected IS DISTINCT FROM actual OR line_count = 0 THEN RAISE EXCEPTION 'Invoice merchandise total does not match lines'; END IF;
RETURN NULL;
END;
$$;
CREATE CONSTRAINT TRIGGER supplier_invoice_reconcile_header AFTER INSERT ON supplier_invoices DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reconcile_supplier_invoice();
CREATE CONSTRAINT TRIGGER supplier_invoice_reconcile_line AFTER INSERT ON supplier_invoice_lines DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reconcile_supplier_invoice();
CREATE FUNCTION verify_supplier_invoice_line() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE accepted NUMERIC; billed NUMERIC; expected_price NUMERIC;
BEGIN
SELECT unit_price INTO expected_price FROM purchase_order_lines WHERE id = NEW.purchase_order_line_id;
IF NEW.unit_price <> expected_price THEN RAISE EXCEPTION 'Invoice unit price differs from purchase order'; END IF;
SELECT COALESCE(SUM(ri.accepted_quantity), 0) INTO accepted
FROM goods_receipt_lines grl JOIN receipt_inspections ri ON ri.receipt_line_id = grl.id
WHERE grl.purchase_order_line_id = NEW.purchase_order_line_id;
SELECT COALESCE(SUM(sil.quantity), 0) INTO billed
FROM supplier_invoice_lines sil JOIN supplier_invoices si ON si.id = sil.invoice_id
LEFT JOIN supplier_invoice_voids siv ON siv.invoice_id = si.id
WHERE sil.purchase_order_line_id = NEW.purchase_order_line_id AND siv.invoice_id IS NULL;
IF billed > accepted THEN RAISE EXCEPTION 'Invoice quantity exceeds accepted goods'; END IF;
RETURN NULL;
END;
$$;
CREATE CONSTRAINT TRIGGER supplier_invoice_line_quantity AFTER INSERT ON supplier_invoice_lines DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_supplier_invoice_line();
CREATE FUNCTION reject_supplier_invoice_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'Supplier invoice records are immutable'; END;
$$;
CREATE TRIGGER supplier_invoices_immutable BEFORE UPDATE OR DELETE ON supplier_invoices FOR EACH ROW EXECUTE FUNCTION reject_supplier_invoice_mutation();
CREATE TRIGGER supplier_invoice_lines_immutable BEFORE UPDATE OR DELETE ON supplier_invoice_lines FOR EACH ROW EXECUTE FUNCTION reject_supplier_invoice_mutation();
CREATE TRIGGER supplier_invoice_voids_immutable BEFORE UPDATE OR DELETE ON supplier_invoice_voids FOR EACH ROW EXECUTE FUNCTION reject_supplier_invoice_mutation();

View File

@ -38,6 +38,7 @@ model Supplier {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
materials SupplierMaterial[]
purchaseOrders PurchaseOrder[]
invoices SupplierInvoice[]
@@unique([organizationId, code])
@@unique([id, organizationId])
@ -83,8 +84,10 @@ model PurchaseOrder {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
lines PurchaseOrderLine[]
receipts GoodsReceipt[]
invoices SupplierInvoice[]
@@unique([organizationId, reference])
@@unique([id, organizationId])
@@unique([id, supplierId, organizationId])
@@index([organizationId, status, createdAt, id])
@@map("purchase_orders")
}
@ -104,6 +107,7 @@ model PurchaseOrderLine {
purchaseOrder PurchaseOrder @relation(fields: [purchaseOrderId, organizationId], references: [id, organizationId], onDelete: Restrict)
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
receiptLines GoodsReceiptLine[]
invoiceLines SupplierInvoiceLine[]
@@unique([purchaseOrderId, materialId])
@@unique([id, purchaseOrderId, organizationId])
@@index([materialId, organizationId])
@ -176,3 +180,59 @@ model ReceiptInspection {
@@unique([receiptLineId, organizationId])
@@map("receipt_inspections")
}
model SupplierInvoice {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
purchaseOrderId String @map("purchase_order_id") @db.Uuid
supplierId String @map("supplier_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
invoiceNumber String @map("invoice_number") @db.VarChar(64)
invoiceDate DateTime @map("invoice_date") @db.Date
currency String @db.Char(3)
merchandiseTotal Decimal @map("merchandise_total") @db.Decimal(12,2)
taxAmount Decimal @map("tax_amount") @db.Decimal(12,2)
shippingAmount Decimal @map("shipping_amount") @db.Decimal(12,2)
payableTotal Decimal @map("payable_total") @db.Decimal(12,2)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
purchaseOrder PurchaseOrder @relation(fields: [purchaseOrderId, supplierId, organizationId], references: [id, supplierId, organizationId], onDelete: Restrict, map: "supplier_invoices_order_scope_fkey")
supplier Supplier @relation(fields: [supplierId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines SupplierInvoiceLine[]
void SupplierInvoiceVoid?
@@unique([organizationId, supplierId, invoiceNumber])
@@unique([id, purchaseOrderId, organizationId])
@@unique([id, organizationId])
@@index([organizationId, purchaseOrderId, createdAt, id], map: "supplier_invoices_order_created_idx")
@@map("supplier_invoices")
}
model SupplierInvoiceLine {
id String @id @default(uuid()) @db.Uuid
invoiceId String @map("invoice_id") @db.Uuid
purchaseOrderId String @map("purchase_order_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
purchaseOrderLineId String @map("purchase_order_line_id") @db.Uuid
quantity Decimal @db.Decimal(12,3)
unitPrice Decimal @map("unit_price") @db.Decimal(12,2)
lineTotal Decimal @map("line_total") @db.Decimal(12,2)
invoice SupplierInvoice @relation(fields: [invoiceId, purchaseOrderId, organizationId], references: [id, purchaseOrderId, organizationId], onDelete: Restrict, map: "supplier_invoice_lines_invoice_scope_fkey")
purchaseOrderLine PurchaseOrderLine @relation(fields: [purchaseOrderLineId, purchaseOrderId, organizationId], references: [id, purchaseOrderId, organizationId], onDelete: Restrict, map: "supplier_invoice_lines_order_line_scope_fkey")
@@unique([invoiceId, purchaseOrderLineId])
@@index([organizationId, purchaseOrderLineId])
@@map("supplier_invoice_lines")
}
model SupplierInvoiceVoid {
invoiceId String @id @map("invoice_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
voidedById String @map("voided_by_id") @db.Uuid
reason String @db.VarChar(500)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
invoice SupplierInvoice @relation(fields: [invoiceId, organizationId], references: [id, organizationId], onDelete: Restrict)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
voidedBy User @relation(fields: [voidedById, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([invoiceId, organizationId])
@@map("supplier_invoice_voids")
}

View File

@ -29,6 +29,8 @@ model Organization {
purchaseOrders PurchaseOrder[]
goodsReceipts GoodsReceipt[]
receiptInspections ReceiptInspection[]
supplierInvoices SupplierInvoice[]
supplierInvoiceVoids SupplierInvoiceVoid[]
@@map("organizations")
}
model User {
@ -49,6 +51,8 @@ model User {
purchaseOrders PurchaseOrder[]
goodsReceipts GoodsReceipt[]
receiptInspections ReceiptInspection[]
supplierInvoices SupplierInvoice[]
supplierInvoiceVoids SupplierInvoiceVoid[]
stockEntries StockLedger[]
stockReservations StockReservation[]
carts Cart[]

View File

@ -156,4 +156,44 @@ export const COMMERCE_ERRORS = {
'Give a reason for rejected goods',
'Rejected receipt quantity lacked a reason',
],
INVOICE_NOT_FOUND: [
404,
'Supplier invoice not found',
'Scoped supplier invoice lookup failed',
],
INVOICE_ORDER_STATE: [
409,
'Only issued purchase orders can be invoiced',
'Supplier invoice rejected for non-issued order',
],
INVOICE_LINE_INVALID: [
409,
'Invoice line does not belong to this purchase order',
'Supplier invoice order-line mismatch',
],
INVOICE_QC_REQUIRED: [
409,
'Goods must pass quality inspection before invoicing',
'Supplier invoice line has no accepted receipt quantity',
],
INVOICE_QUANTITY_LIMIT: [
409,
'Invoice quantity exceeds accepted, uninvoiced goods',
'Supplier invoice accepted quantity exceeded',
],
INVOICE_NUMBER_CONFLICT: [
409,
'Invoice number is already recorded for this supplier',
'Supplier invoice number duplicate',
],
INVOICE_AMOUNT_LIMIT: [
409,
'Invoice amount exceeds the supported limit',
'Supplier invoice money column limit exceeded',
],
INVOICE_ALREADY_VOID: [
409,
'Supplier invoice is already void',
'Duplicate supplier invoice void rejected',
],
} as const;

View File

@ -6,6 +6,11 @@ import { ProcurementStore } from './procurement.store';
import { PurchaseOrdersController } from './purchase-orders.controller';
import { PurchaseOrderStore } from './purchase-order.store';
import { GoodsReceiptStore } from './goods-receipt.store';
import { SupplierInvoiceStore } from './supplier-invoice.store';
import {
OrderInvoicesController,
SupplierInvoicesController,
} from './supplier-invoices.controller';
import {
GoodsReceiptsController,
ReceiptInspectionController,
@ -13,12 +18,19 @@ import {
@Module({
imports: [DatabaseModule, IdentityModule],
providers: [ProcurementStore, PurchaseOrderStore, GoodsReceiptStore],
providers: [
ProcurementStore,
PurchaseOrderStore,
GoodsReceiptStore,
SupplierInvoiceStore,
],
controllers: [
ProcurementController,
PurchaseOrdersController,
GoodsReceiptsController,
ReceiptInspectionController,
OrderInvoicesController,
SupplierInvoicesController,
],
})
export class ProcurementModule {}

View File

@ -0,0 +1,36 @@
import { AppError } from '../common/errors/app-error';
import { lineTotal, scaled, totalOf } from './purchase-order-money';
const max = 999999999999n;
export function invoiceLineTotal(quantity: string, unitPrice: string): string {
try {
return lineTotal(quantity, unitPrice);
} catch (error) {
if (error instanceof AppError && error.code === 'DATA_CONSTRAINT')
throw new AppError('INVOICE_AMOUNT_LIMIT');
throw error;
}
}
export function invoiceTotals(
lines: readonly { lineTotal: string }[],
taxAmount: string,
shippingAmount: string,
) {
let merchandiseTotal: string;
try {
merchandiseTotal = totalOf(lines);
} catch (error) {
if (error instanceof AppError && error.code === 'DATA_CONSTRAINT')
throw new AppError('INVOICE_AMOUNT_LIMIT');
throw error;
}
const payable =
scaled(merchandiseTotal, 2) +
scaled(taxAmount, 2) +
scaled(shippingAmount, 2);
if (payable > max) throw new AppError('INVOICE_AMOUNT_LIMIT');
return {
merchandiseTotal,
payableTotal: `${payable / 100n}.${(payable % 100n).toString().padStart(2, '0')}`,
};
}

View File

@ -0,0 +1,39 @@
import { z } from 'zod';
const quantity = z
.string()
.regex(/^(0|[1-9]\d{0,8})\.\d{3}$/)
.refine((value) => value !== '0.000');
const amount = z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/);
export const supplierInvoiceSchema = z
.object({
invoiceNumber: z
.string()
.trim()
.min(1)
.max(64)
.regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/)
.transform((value) => value.toUpperCase()),
invoiceDate: z.iso
.date()
.transform((value) => new Date(`${value}T00:00:00.000Z`)),
taxAmount: amount,
shippingAmount: amount.default('0.00'),
lines: z
.array(z.object({ purchaseOrderLineId: z.uuid(), quantity }).strict())
.min(1)
.max(100)
.refine(
(lines) =>
new Set(lines.map((line) => line.purchaseOrderLineId)).size ===
lines.length,
),
})
.strict();
export const supplierInvoiceVoidSchema = z
.object({ reason: z.string().trim().min(1).max(500) })
.strict();
export type SupplierInvoiceInput = z.infer<typeof supplierInvoiceSchema>;
export type SupplierInvoiceVoidInput = z.infer<
typeof supplierInvoiceVoidSchema
>;

View File

@ -0,0 +1,185 @@
import { Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { DatabaseService } from '../database/database.service';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { Principal } from '../identity/identity.types';
import type { PageInput } from '../identity/identity.schemas';
import { invoiceLineTotal, invoiceTotals } from './supplier-invoice-money';
import type {
SupplierInvoiceInput,
SupplierInvoiceVoidInput,
} from './supplier-invoice.schemas';
import { scaled } from './purchase-order-money';
const invoiceView = { lines: { orderBy: { id: 'asc' as const } }, void: true };
const addQuantity = (totals: Map<string, bigint>, id: string, amount: string) =>
totals.set(id, (totals.get(id) ?? 0n) + scaled(amount, 3));
@Injectable()
export class SupplierInvoiceStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async list(actor: Principal, orderId: string, query: PageInput) {
const order = await this.db.purchaseOrder.findFirst({
where: { id: orderId, organizationId: actor.organizationId },
select: { id: true },
});
if (!order) throw new AppError('PURCHASE_ORDER_NOT_FOUND');
return this.db.supplierInvoice.findMany({
where: { organizationId: actor.organizationId, purchaseOrderId: orderId },
include: invoiceView,
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit,
skip: query.offset,
});
}
async find(actor: Principal, id: string) {
const invoice = await this.db.supplierInvoice.findFirst({
where: { id, organizationId: actor.organizationId },
include: invoiceView,
});
if (!invoice) throw new AppError('INVOICE_NOT_FOUND');
return invoice;
}
create(actor: Principal, orderId: string, input: SupplierInvoiceInput) {
return this.access.mutate(actor, 'procurement.manage', async (tx) => {
const order = await tx.purchaseOrder.findFirst({
where: { id: orderId, organizationId: actor.organizationId },
include: { lines: true },
});
if (!order) throw new AppError('PURCHASE_ORDER_NOT_FOUND');
if (order.status !== 'ISSUED') throw new AppError('INVOICE_ORDER_STATE');
const duplicate = await tx.supplierInvoice.findFirst({
where: {
organizationId: actor.organizationId,
supplierId: order.supplierId,
invoiceNumber: input.invoiceNumber,
},
select: { id: true },
});
if (duplicate) throw new AppError('INVOICE_NUMBER_CONFLICT');
const orderLines = new Map(order.lines.map((line) => [line.id, line]));
const receipts = await tx.goodsReceiptLine.findMany({
where: {
organizationId: actor.organizationId,
purchaseOrderId: orderId,
},
include: { inspection: true },
});
const accepted = new Map<string, bigint>();
for (const receipt of receipts)
if (receipt.inspection)
addQuantity(
accepted,
receipt.purchaseOrderLineId,
receipt.inspection.acceptedQuantity.toFixed(3),
);
const prior = await tx.supplierInvoice.findMany({
where: {
organizationId: actor.organizationId,
purchaseOrderId: orderId,
void: { is: null },
},
include: { lines: true },
});
const billed = new Map<string, bigint>();
for (const invoice of prior)
for (const line of invoice.lines)
addQuantity(
billed,
line.purchaseOrderLineId,
line.quantity.toFixed(3),
);
const lines = input.lines.map((line) => {
const ordered = orderLines.get(line.purchaseOrderLineId);
if (!ordered) throw new AppError('INVOICE_LINE_INVALID');
const available = accepted.get(line.purchaseOrderLineId) ?? 0n;
if (available === 0n) throw new AppError('INVOICE_QC_REQUIRED');
if (
(billed.get(line.purchaseOrderLineId) ?? 0n) +
scaled(line.quantity, 3) >
available
)
throw new AppError('INVOICE_QUANTITY_LIMIT');
const unitPrice = ordered.unitPrice.toFixed(2);
return {
organizationId: actor.organizationId,
purchaseOrderId: orderId,
purchaseOrderLineId: ordered.id,
quantity: line.quantity,
unitPrice,
lineTotal: invoiceLineTotal(line.quantity, unitPrice),
};
});
const totals = invoiceTotals(
lines,
input.taxAmount,
input.shippingAmount,
);
const invoice = await tx.supplierInvoice.create({
data: {
organizationId: actor.organizationId,
purchaseOrderId: orderId,
supplierId: order.supplierId,
createdById: actor.userId,
invoiceNumber: input.invoiceNumber,
invoiceDate: input.invoiceDate,
currency: order.currency,
taxAmount: input.taxAmount,
shippingAmount: input.shippingAmount,
...totals,
},
});
await tx.supplierInvoiceLine.createMany({
data: lines.map((line) => ({ ...line, invoiceId: invoice.id })),
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'supplier_invoice.created',
invoice.id,
);
return tx.supplierInvoice.findUniqueOrThrow({
where: { id: invoice.id },
include: invoiceView,
});
});
}
void(actor: Principal, id: string, input: SupplierInvoiceVoidInput) {
return this.access.mutate(actor, 'procurement.manage', async (tx) => {
const invoice = await tx.supplierInvoice.findFirst({
where: { id, organizationId: actor.organizationId },
include: { void: true },
});
if (!invoice) throw new AppError('INVOICE_NOT_FOUND');
if (invoice.void) throw new AppError('INVOICE_ALREADY_VOID');
await tx.supplierInvoiceVoid.create({
data: {
invoiceId: id,
organizationId: actor.organizationId,
voidedById: actor.userId,
reason: input.reason,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'supplier_invoice.voided',
id,
);
return tx.supplierInvoice.findUniqueOrThrow({
where: { id },
include: invoiceView,
});
});
}
}

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 type { Principal } from '../identity/identity.types';
import { pageSchema, type PageInput } from '../identity/identity.schemas';
import { SupplierInvoiceStore } from './supplier-invoice.store';
import {
supplierInvoiceSchema,
supplierInvoiceVoidSchema,
type SupplierInvoiceInput,
type SupplierInvoiceVoidInput,
} from './supplier-invoice.schemas';
@Controller('purchase-orders/:orderId/invoices')
export class OrderInvoicesController {
constructor(private readonly invoices: SupplierInvoiceStore) {}
@Get()
@RequirePermission('procurement.read')
list(
@CurrentPrincipal() actor: Principal,
@Param('orderId', ParseUUIDPipe) orderId: string,
@Query(new SchemaPipe(pageSchema)) query: PageInput,
) {
return this.invoices.list(actor, orderId, query);
}
@Post()
@RequirePermission('procurement.manage')
create(
@CurrentPrincipal() actor: Principal,
@Param('orderId', ParseUUIDPipe) orderId: string,
@Body(new SchemaPipe(supplierInvoiceSchema)) input: SupplierInvoiceInput,
) {
return this.invoices.create(actor, orderId, input);
}
}
@Controller('supplier-invoices')
export class SupplierInvoicesController {
constructor(private readonly invoices: SupplierInvoiceStore) {}
@Get(':id')
@RequirePermission('procurement.read')
get(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.invoices.find(actor, id);
}
@Post(':id/void')
@RequirePermission('procurement.manage')
void(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(supplierInvoiceVoidSchema))
input: SupplierInvoiceVoidInput,
) {
return this.invoices.void(actor, id, input);
}
}

View File

@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { seedPurchaseOrder } from './helpers/procurement';
describe('goods receipt and QC API', () => {
let ctx: IdentityApp;
@ -14,65 +15,7 @@ describe('goods receipt and QC API', () => {
await ctx.clearLimits();
});
async function order(issue = true) {
const code = randomUUID().slice(0, 8);
const supplier = await ctx
.api()
.post('/api/v1/suppliers')
.auth(ctx.token, auth)
.send({
name: `Supplier ${code}`,
code: `S-${code}`,
contactName: 'Asha Shah',
email: `${code}@example.com`,
phone: '+919876543210',
})
.expect(201);
const material = await ctx
.api()
.post('/api/v1/materials')
.auth(ctx.token, auth)
.send({
name: `Wax ${code}`,
code: `M-${code}`,
kind: 'WAX',
unit: 'KILOGRAM',
})
.expect(201);
await ctx
.api()
.put(
`/api/v1/suppliers/${supplier.body.id}/materials/${material.body.id}`,
)
.auth(ctx.token, auth)
.send({
supplierSku: `SKU-${code}`,
leadTimeDays: 7,
minOrderQuantity: '1.000',
unitPrice: '120.00',
currency: 'INR',
})
.expect(200);
const purchase = await ctx
.api()
.post('/api/v1/purchase-orders')
.auth(ctx.token, auth)
.send({
supplierId: supplier.body.id,
lines: [{ materialId: material.body.id, quantity: '3.000' }],
})
.expect(201);
if (issue)
await ctx
.api()
.post(`/api/v1/purchase-orders/${purchase.body.id}/issue`)
.auth(ctx.token, auth)
.expect(201);
return {
id: purchase.body.id as string,
lineId: purchase.body.lines[0].id as string,
};
}
const order = (issue = true) => seedPurchaseOrder(ctx, issue);
it('allows partial receipts, reconciles QC, and permits replacement of rejected goods', async () => {
const purchase = await order();

View File

@ -0,0 +1,90 @@
import { randomUUID } from 'node:crypto';
import type { IdentityApp } from './identity-app';
const auth = { type: 'bearer' as const };
export async function seedPurchaseOrder(ctx: IdentityApp, issue = true) {
const code = randomUUID().slice(0, 8);
const supplier = await ctx
.api()
.post('/api/v1/suppliers')
.auth(ctx.token, auth)
.send({
name: `Supplier ${code}`,
code: `S-${code}`,
contactName: 'Asha Shah',
email: `${code}@example.com`,
phone: '+919876543210',
})
.expect(201);
const material = await ctx
.api()
.post('/api/v1/materials')
.auth(ctx.token, auth)
.send({
name: `Wax ${code}`,
code: `M-${code}`,
kind: 'WAX',
unit: 'KILOGRAM',
})
.expect(201);
await ctx
.api()
.put(`/api/v1/suppliers/${supplier.body.id}/materials/${material.body.id}`)
.auth(ctx.token, auth)
.send({
supplierSku: `SKU-${code}`,
leadTimeDays: 7,
minOrderQuantity: '1.000',
unitPrice: '120.00',
currency: 'INR',
})
.expect(200);
const purchase = await ctx
.api()
.post('/api/v1/purchase-orders')
.auth(ctx.token, auth)
.send({
supplierId: supplier.body.id,
lines: [{ materialId: material.body.id, quantity: '3.000' }],
})
.expect(201);
if (issue)
await ctx
.api()
.post(`/api/v1/purchase-orders/${purchase.body.id}/issue`)
.auth(ctx.token, auth)
.expect(201);
return {
id: purchase.body.id as string,
lineId: purchase.body.lines[0].id as string,
supplierId: supplier.body.id as string,
};
}
export async function receiveAccepted(
ctx: IdentityApp,
order: { id: string; lineId: string },
quantity: string,
) {
const receipt = await ctx
.api()
.post(`/api/v1/purchase-orders/${order.id}/receipts`)
.auth(ctx.token, auth)
.send({ lines: [{ purchaseOrderLineId: order.lineId, quantity }] })
.expect(201);
await ctx
.api()
.post(`/api/v1/goods-receipts/${receipt.body.id}/inspect`)
.auth(ctx.token, auth)
.send({
lines: [
{
receiptLineId: receipt.body.lines[0].id,
acceptedQuantity: quantity,
rejectedQuantity: '0.000',
},
],
})
.expect(201);
return receipt.body;
}

View File

@ -0,0 +1,23 @@
import {
invoiceLineTotal,
invoiceTotals,
} from '../src/procurement/supplier-invoice-money';
describe('supplier invoice money', () => {
it('rounds line money and adds declared charges exactly', () => {
const line = invoiceLineTotal('0.125', '120.03');
expect(line).toBe('15.00');
expect(invoiceTotals([{ lineTotal: line }], '2.70', '1.05')).toEqual({
merchandiseTotal: '15.00',
payableTotal: '18.75',
});
});
it('rejects column overflow with a distinct invoice error', () => {
expect(() => invoiceLineTotal('999999999.999', '9999999999.99')).toThrow(
expect.objectContaining({ code: 'INVOICE_AMOUNT_LIMIT' }),
);
expect(() =>
invoiceTotals([{ lineTotal: '9999999999.00' }], '1.00', '0.00'),
).toThrow(expect.objectContaining({ code: 'INVOICE_AMOUNT_LIMIT' }));
});
});

View File

@ -0,0 +1,208 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { seedPurchaseOrder, receiveAccepted } from './helpers/procurement';
import { secondActor } from './helpers/commerce';
describe('supplier invoice 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 payload = (
lineId: string,
invoiceNumber: string,
quantity = '1.000',
) => ({
invoiceNumber,
invoiceDate: '2026-09-28',
taxAmount: '18.00',
shippingAmount: '5.00',
lines: [{ purchaseOrderLineId: lineId, quantity }],
});
it('matches accepted goods, computes exact totals, and releases quantity on void', async () => {
const order = await seedPurchaseOrder(ctx);
await receiveAccepted(ctx, order, '2.000');
const path = `/api/v1/purchase-orders/${order.id}/invoices`;
const first = await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payload(order.lineId, 'inv-001'))
.expect(201);
expect(first.body).toMatchObject({
invoiceNumber: 'INV-001',
currency: 'INR',
merchandiseTotal: '120',
taxAmount: '18',
shippingAmount: '5',
payableTotal: '143',
});
const duplicate = await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payload(order.lineId, 'INV-001'))
.expect(409);
expect(duplicate.body.code).toBe('INVOICE_NUMBER_CONFLICT');
const over = await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payload(order.lineId, 'INV-002', '2.000'))
.expect(409);
expect(over.body.code).toBe('INVOICE_QUANTITY_LIMIT');
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payload(order.lineId, 'INV-002'))
.expect(201);
const voided = await ctx
.api()
.post(`/api/v1/supplier-invoices/${first.body.id}/void`)
.auth(ctx.token, auth)
.send({ reason: 'Supplier cancelled the document' })
.expect(201);
expect(voided.body.void.reason).toBe('Supplier cancelled the document');
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payload(order.lineId, 'INV-003'))
.expect(201);
expect(
(await ctx.api().get(path).auth(ctx.token, auth).expect(200)).body,
).toHaveLength(3);
expect(
(
await ctx
.api()
.get(`${path}?limit=1&offset=1`)
.auth(ctx.token, auth)
.expect(200)
).body,
).toHaveLength(1);
expect(
(
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payload(order.lineId, 'INV-001'))
.expect(409)
).body.code,
).toBe('INVOICE_NUMBER_CONFLICT');
});
it('rejects draft orders, uninspected goods, and unrelated order lines', async () => {
const order = await seedPurchaseOrder(ctx, false);
const path = `/api/v1/purchase-orders/${order.id}/invoices`;
expect(
(
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payload(order.lineId, 'INV-DRAFT'))
.expect(409)
).body.code,
).toBe('INVOICE_ORDER_STATE');
await ctx
.api()
.post(`/api/v1/purchase-orders/${order.id}/issue`)
.auth(ctx.token, auth)
.expect(201);
expect(
(
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payload(order.lineId, 'INV-NO-QC'))
.expect(409)
).body.code,
).toBe('INVOICE_QC_REQUIRED');
await receiveAccepted(ctx, order, '1.000');
expect(
(
await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payload(randomUUID(), 'INV-WRONG'))
.expect(409)
).body.code,
).toBe('INVOICE_LINE_INVALID');
});
it('enforces read and manage permissions, organization scope, and one-time void', async () => {
const order = await seedPurchaseOrder(ctx);
await receiveAccepted(ctx, order, '1.000');
const path = `/api/v1/purchase-orders/${order.id}/invoices`;
const invoice = await ctx
.api()
.post(path)
.auth(ctx.token, auth)
.send(payload(order.lineId, 'INV-SCOPE'))
.expect(201);
const reader = await secondActor(ctx, true, ['procurement.read']);
await ctx
.api()
.get(`/api/v1/supplier-invoices/${invoice.body.id}`)
.auth(reader.token, auth)
.expect(200);
await ctx
.api()
.post(path)
.auth(reader.token, auth)
.send(payload(order.lineId, 'INV-DENIED'))
.expect(403);
const foreign = await secondActor(ctx, false, [
'procurement.read',
'procurement.manage',
]);
expect(
(
await ctx
.api()
.get(`/api/v1/supplier-invoices/${invoice.body.id}`)
.auth(foreign.token, auth)
.expect(404)
).body.code,
).toBe('INVOICE_NOT_FOUND');
const voidPath = `/api/v1/supplier-invoices/${invoice.body.id}/void`;
await ctx
.api()
.post(voidPath)
.auth(ctx.token, auth)
.send({ reason: 'Wrong invoice' })
.expect(201);
expect(
(
await ctx
.api()
.post(voidPath)
.auth(ctx.token, auth)
.send({ reason: 'Again' })
.expect(409)
).body.code,
).toBe('INVOICE_ALREADY_VOID');
expect(
await ctx.db.auditEvent.count({
where: {
organizationId: ctx.owner.organizationId,
action: 'supplier_invoice.voided',
targetId: invoice.body.id,
},
}),
).toBe(1);
});
});