feat(procurement): add partial goods receipts and QC inspections #9
|
|
@ -32,8 +32,9 @@ Identity: see [API contract](docs/identity-api.md) and [setup/release guide](doc
|
|||
Phase 1C adds catalog, private addresses and inventory. See [commerce API](docs/commerce-api.md), [errors](docs/error-contract.md), [migrations](docs/migrations.md), [security preparation](docs/vapt-readiness.md) and [verification](docs/verification.md).
|
||||
Phase 1D adds versioned carts, coupons, atomic checkout and private order snapshots. See [checkout API and pricing boundary](docs/checkout-api.md). Payment remains disabled until tax, shipping and payment rules are finalized.
|
||||
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). Purchase orders, receipts, QC and production remain later milestones.
|
||||
Phase 2B adds [purchase-order drafts and issuance](docs/purchase-orders-api.md). Goods receipts, QC, invoices, payments and stock movements remain later milestones.
|
||||
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.
|
||||
|
||||
### Swagger UI
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,16 @@
|
|||
# Phase 2C: goods receipts and quality inspection
|
||||
|
||||
All routes are under `/api/v1` and require a bearer token. Read routes require `procurement.read`; writes require `procurement.manage`. Records are scoped to the signed-in organization.
|
||||
|
||||
| Method | Route | Purpose |
|
||||
| ------ | ------------------------------------ | -------------------------------------------------- |
|
||||
| GET | `/purchase-orders/:orderId/receipts` | List up to 100 receipts for an order |
|
||||
| POST | `/purchase-orders/:orderId/receipts` | Record a partial delivery against an issued order |
|
||||
| GET | `/goods-receipts/:id` | Read a receipt with its QC decisions |
|
||||
| POST | `/goods-receipts/:id/inspect` | Make one atomic QC decision for every receipt line |
|
||||
|
||||
Create a receipt with `{"deliveryNote":"DN-001","lines":[{"purchaseOrderLineId":"<uuid>","quantity":"2.000"}]}`. The delivery note is optional. Quantity strings use exactly three decimal places. Each line must belong to the order. A receipt cannot exceed outstanding quantity: previously accepted goods and goods awaiting QC consume the ordered quantity; rejected goods do not. This permits a replacement delivery after rejection.
|
||||
|
||||
Inspect with `{"lines":[{"receiptLineId":"<uuid>","acceptedQuantity":"1.000","rejectedQuantity":"1.000","rejectionReason":"Damaged packaging"}]}`. Every receipt line must be included exactly once. Accepted and rejected quantities must sum to the received quantity; rejected goods need a reason. Decisions and receipt records are immutable. The transaction records an audit event for creation and inspection.
|
||||
|
||||
This phase records receipt and QC evidence. Material on-hand balances, invoices, and supplier payments are separate future phases. Receipt creation is not idempotent; clients should read the order's receipts before retrying an uncertain write.
|
||||
|
|
@ -15,5 +15,6 @@
|
|||
"20260913140451_supplier_materials": "c1f59e082ddf97443c17d52745068d9e6cbafb3d4e1088126a150f555c1cf0a1",
|
||||
"20260913173146_purchase_orders": "1e226f158e57af94c03b8f749349d06a874a8e82c32094ebd638d0ec41dc762a",
|
||||
"20260923000116_purchase_order_integrity": "ed14ce76d1b29c8de890a89c8dd84216edd002e43732b75d0cdeab4fd8f51fb8",
|
||||
"20260923001040_purchase_order_reconciliation": "63ddf7618ff14916512597cc16af2de07e0c093d345bb35e607ed830d3ef067e"
|
||||
"20260923001040_purchase_order_reconciliation": "63ddf7618ff14916512597cc16af2de07e0c093d345bb35e607ed830d3ef067e",
|
||||
"20260928123638_goods_receipts_qc": "a09646d8a3a1f520495ddbe611c61437ddfcec4585486f94fc383d9b1312006c"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,69 @@
|
|||
CREATE UNIQUE INDEX "purchase_order_lines_id_purchase_order_id_organization_id_key" ON "purchase_order_lines"("id", "purchase_order_id", "organization_id");
|
||||
|
||||
CREATE TABLE "goods_receipts" (
|
||||
"id" UUID NOT NULL,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"purchase_order_id" UUID NOT NULL,
|
||||
"created_by_id" UUID NOT NULL,
|
||||
"delivery_note" VARCHAR(80),
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "goods_receipts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
CREATE UNIQUE INDEX "goods_receipts_id_purchase_order_id_organization_id_key" ON "goods_receipts"("id", "purchase_order_id", "organization_id");
|
||||
CREATE INDEX "goods_receipts_organization_id_purchase_order_id_created_at_idx" ON "goods_receipts"("organization_id", "purchase_order_id", "created_at", "id");
|
||||
ALTER TABLE "goods_receipts" ADD CONSTRAINT "goods_receipts_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "goods_receipts" ADD CONSTRAINT "goods_receipts_purchase_order_id_organization_id_fkey" FOREIGN KEY ("purchase_order_id", "organization_id") REFERENCES "purchase_orders"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "goods_receipts" ADD CONSTRAINT "goods_receipts_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 "goods_receipt_lines" (
|
||||
"id" UUID NOT NULL,
|
||||
"receipt_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,
|
||||
CONSTRAINT "goods_receipt_lines_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "goods_receipt_lines_quantity" CHECK ("quantity" > 0)
|
||||
);
|
||||
CREATE UNIQUE INDEX "goods_receipt_lines_receipt_id_purchase_order_line_id_key" ON "goods_receipt_lines"("receipt_id", "purchase_order_line_id");
|
||||
CREATE UNIQUE INDEX "goods_receipt_lines_id_organization_id_key" ON "goods_receipt_lines"("id", "organization_id");
|
||||
CREATE INDEX "goods_receipt_lines_organization_id_purchase_order_line_id_idx" ON "goods_receipt_lines"("organization_id", "purchase_order_line_id");
|
||||
ALTER TABLE "goods_receipt_lines" ADD CONSTRAINT "goods_receipt_lines_receipt_id_purchase_order_id_organizat_fkey" FOREIGN KEY ("receipt_id", "purchase_order_id", "organization_id") REFERENCES "goods_receipts"("id", "purchase_order_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "goods_receipt_lines" ADD CONSTRAINT "goods_receipt_lines_purchase_order_line_id_purchase_order__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 "receipt_inspections" (
|
||||
"id" UUID NOT NULL,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"receipt_line_id" UUID NOT NULL,
|
||||
"inspected_by_id" UUID NOT NULL,
|
||||
"accepted_quantity" DECIMAL(12,3) NOT NULL,
|
||||
"rejected_quantity" DECIMAL(12,3) NOT NULL,
|
||||
"rejection_reason" VARCHAR(500),
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "receipt_inspections_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "receipt_inspections_quantities" CHECK ("accepted_quantity" >= 0 AND "rejected_quantity" >= 0 AND ("rejected_quantity" = 0 OR "rejection_reason" IS NOT NULL))
|
||||
);
|
||||
CREATE UNIQUE INDEX "receipt_inspections_receipt_line_id_key" ON "receipt_inspections"("receipt_line_id");
|
||||
CREATE UNIQUE INDEX "receipt_inspections_receipt_line_id_organization_id_key" ON "receipt_inspections"("receipt_line_id", "organization_id");
|
||||
ALTER TABLE "receipt_inspections" ADD CONSTRAINT "receipt_inspections_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "receipt_inspections" ADD CONSTRAINT "receipt_inspections_receipt_line_id_organization_id_fkey" FOREIGN KEY ("receipt_line_id", "organization_id") REFERENCES "goods_receipt_lines"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE "receipt_inspections" ADD CONSTRAINT "receipt_inspections_inspected_by_id_organization_id_fkey" FOREIGN KEY ("inspected_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
CREATE FUNCTION verify_receipt_inspection() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
IF NEW.accepted_quantity + NEW.rejected_quantity <> (SELECT quantity FROM goods_receipt_lines WHERE id = NEW.receipt_line_id) THEN
|
||||
RAISE EXCEPTION 'Inspection quantities must equal receipt quantity';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
CREATE TRIGGER receipt_inspection_quantity BEFORE INSERT ON receipt_inspections FOR EACH ROW EXECUTE FUNCTION verify_receipt_inspection();
|
||||
|
||||
CREATE FUNCTION reject_receipt_mutation() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'Receipt records are immutable';
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
CREATE TRIGGER goods_receipts_immutable BEFORE UPDATE OR DELETE ON goods_receipts FOR EACH ROW EXECUTE FUNCTION reject_receipt_mutation();
|
||||
CREATE TRIGGER goods_receipt_lines_immutable BEFORE UPDATE OR DELETE ON goods_receipt_lines FOR EACH ROW EXECUTE FUNCTION reject_receipt_mutation();
|
||||
CREATE TRIGGER receipt_inspections_immutable BEFORE UPDATE OR DELETE ON receipt_inspections FOR EACH ROW EXECUTE FUNCTION reject_receipt_mutation();
|
||||
|
|
@ -82,6 +82,7 @@ model PurchaseOrder {
|
|||
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||
lines PurchaseOrderLine[]
|
||||
receipts GoodsReceipt[]
|
||||
@@unique([organizationId, reference])
|
||||
@@unique([id, organizationId])
|
||||
@@index([organizationId, status, createdAt, id])
|
||||
|
|
@ -102,7 +103,9 @@ model PurchaseOrderLine {
|
|||
lineTotal Decimal @map("line_total") @db.Decimal(12,2)
|
||||
purchaseOrder PurchaseOrder @relation(fields: [purchaseOrderId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
receiptLines GoodsReceiptLine[]
|
||||
@@unique([purchaseOrderId, materialId])
|
||||
@@unique([id, purchaseOrderId, organizationId])
|
||||
@@index([materialId, organizationId])
|
||||
@@map("purchase_order_lines")
|
||||
}
|
||||
|
|
@ -125,3 +128,51 @@ model SupplierMaterial {
|
|||
@@index([materialId, organizationId, active])
|
||||
@@map("supplier_materials")
|
||||
}
|
||||
|
||||
model GoodsReceipt {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
purchaseOrderId String @map("purchase_order_id") @db.Uuid
|
||||
createdById String @map("created_by_id") @db.Uuid
|
||||
deliveryNote String? @map("delivery_note") @db.VarChar(80)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||
purchaseOrder PurchaseOrder @relation(fields: [purchaseOrderId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
lines GoodsReceiptLine[]
|
||||
@@unique([id, purchaseOrderId, organizationId])
|
||||
@@index([organizationId, purchaseOrderId, createdAt, id])
|
||||
@@map("goods_receipts")
|
||||
}
|
||||
|
||||
model GoodsReceiptLine {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
receiptId String @map("receipt_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)
|
||||
receipt GoodsReceipt @relation(fields: [receiptId, purchaseOrderId, organizationId], references: [id, purchaseOrderId, organizationId], onDelete: Restrict)
|
||||
purchaseOrderLine PurchaseOrderLine @relation(fields: [purchaseOrderLineId, purchaseOrderId, organizationId], references: [id, purchaseOrderId, organizationId], onDelete: Restrict)
|
||||
inspection ReceiptInspection?
|
||||
@@unique([receiptId, purchaseOrderLineId])
|
||||
@@unique([id, organizationId])
|
||||
@@index([organizationId, purchaseOrderLineId])
|
||||
@@map("goods_receipt_lines")
|
||||
}
|
||||
|
||||
model ReceiptInspection {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
receiptLineId String @unique @map("receipt_line_id") @db.Uuid
|
||||
inspectedById String @map("inspected_by_id") @db.Uuid
|
||||
acceptedQuantity Decimal @map("accepted_quantity") @db.Decimal(12,3)
|
||||
rejectedQuantity Decimal @map("rejected_quantity") @db.Decimal(12,3)
|
||||
rejectionReason String? @map("rejection_reason") @db.VarChar(500)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||
receiptLine GoodsReceiptLine @relation(fields: [receiptLineId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
inspectedBy User @relation(fields: [inspectedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([receiptLineId, organizationId])
|
||||
@@map("receipt_inspections")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,8 @@ model Organization {
|
|||
suppliers Supplier[]
|
||||
materials Material[]
|
||||
purchaseOrders PurchaseOrder[]
|
||||
goodsReceipts GoodsReceipt[]
|
||||
receiptInspections ReceiptInspection[]
|
||||
@@map("organizations")
|
||||
}
|
||||
model User {
|
||||
|
|
@ -45,6 +47,8 @@ model User {
|
|||
recoveryTokens RecoveryToken[]
|
||||
addresses Address[]
|
||||
purchaseOrders PurchaseOrder[]
|
||||
goodsReceipts GoodsReceipt[]
|
||||
receiptInspections ReceiptInspection[]
|
||||
stockEntries StockLedger[]
|
||||
stockReservations StockReservation[]
|
||||
carts Cart[]
|
||||
|
|
|
|||
|
|
@ -116,4 +116,44 @@ export const COMMERCE_ERRORS = {
|
|||
'Order quantity is below the supplier minimum',
|
||||
'Supplier material minimum order quantity rejected',
|
||||
],
|
||||
RECEIPT_NOT_FOUND: [
|
||||
404,
|
||||
'Goods receipt not found',
|
||||
'Scoped goods receipt lookup failed',
|
||||
],
|
||||
RECEIPT_ORDER_STATE: [
|
||||
409,
|
||||
'Only issued purchase orders can receive goods',
|
||||
'Receipt rejected for non-issued order',
|
||||
],
|
||||
RECEIPT_LINE_INVALID: [
|
||||
409,
|
||||
'Receipt line does not belong to this purchase order',
|
||||
'Receipt purchase-order line mismatch',
|
||||
],
|
||||
RECEIPT_QUANTITY_LIMIT: [
|
||||
409,
|
||||
'Received quantity exceeds the outstanding order quantity',
|
||||
'Receipt outstanding quantity exceeded',
|
||||
],
|
||||
RECEIPT_ALREADY_INSPECTED: [
|
||||
409,
|
||||
'Goods receipt has already been inspected',
|
||||
'Duplicate receipt inspection rejected',
|
||||
],
|
||||
INSPECTION_LINES_INVALID: [
|
||||
409,
|
||||
'Inspect every receipt line exactly once',
|
||||
'Inspection receipt-line set mismatch',
|
||||
],
|
||||
INSPECTION_QUANTITY_INVALID: [
|
||||
409,
|
||||
'Accepted and rejected quantities must equal the received quantity',
|
||||
'Inspection quantity reconciliation failed',
|
||||
],
|
||||
INSPECTION_REASON_REQUIRED: [
|
||||
409,
|
||||
'Give a reason for rejected goods',
|
||||
'Rejected receipt quantity lacked a reason',
|
||||
],
|
||||
} as const;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,48 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
const quantity = z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/);
|
||||
export const receiptSchema = z
|
||||
.object({
|
||||
deliveryNote: z.string().trim().min(1).max(80).optional(),
|
||||
lines: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
purchaseOrderLineId: z.uuid(),
|
||||
quantity: quantity.refine((value) => value !== '0.000'),
|
||||
})
|
||||
.strict(),
|
||||
)
|
||||
.min(1)
|
||||
.max(100)
|
||||
.refine(
|
||||
(lines) =>
|
||||
new Set(lines.map((line) => line.purchaseOrderLineId)).size ===
|
||||
lines.length,
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
export const inspectionSchema = z
|
||||
.object({
|
||||
lines: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
receiptLineId: z.uuid(),
|
||||
acceptedQuantity: quantity,
|
||||
rejectedQuantity: quantity,
|
||||
rejectionReason: z.string().trim().min(1).max(500).optional(),
|
||||
})
|
||||
.strict(),
|
||||
)
|
||||
.min(1)
|
||||
.max(100)
|
||||
.refine(
|
||||
(lines) =>
|
||||
new Set(lines.map((line) => line.receiptLineId)).size ===
|
||||
lines.length,
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
export type ReceiptInput = z.infer<typeof receiptSchema>;
|
||||
export type InspectionInput = z.infer<typeof inspectionSchema>;
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
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 { InspectionInput, ReceiptInput } from './goods-receipt.schemas';
|
||||
import { scaled } from './purchase-order-money';
|
||||
|
||||
const quantity = (value: string) => scaled(value, 3);
|
||||
const receiptView = {
|
||||
lines: { include: { inspection: true }, orderBy: { id: 'asc' as const } },
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class GoodsReceiptStore {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly access: AccessStore,
|
||||
) {}
|
||||
|
||||
async list(actor: Principal, orderId: string) {
|
||||
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.goodsReceipt.findMany({
|
||||
where: { organizationId: actor.organizationId, purchaseOrderId: orderId },
|
||||
include: receiptView,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
take: 100,
|
||||
});
|
||||
}
|
||||
|
||||
async find(actor: Principal, id: string) {
|
||||
const receipt = await this.db.goodsReceipt.findFirst({
|
||||
where: { id, organizationId: actor.organizationId },
|
||||
include: receiptView,
|
||||
});
|
||||
if (!receipt) throw new AppError('RECEIPT_NOT_FOUND');
|
||||
return receipt;
|
||||
}
|
||||
|
||||
create(actor: Principal, orderId: string, input: ReceiptInput) {
|
||||
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('RECEIPT_ORDER_STATE');
|
||||
const orderLines = new Map(order.lines.map((line) => [line.id, line]));
|
||||
const prior = await tx.goodsReceiptLine.findMany({
|
||||
where: {
|
||||
organizationId: actor.organizationId,
|
||||
purchaseOrderId: orderId,
|
||||
},
|
||||
include: { inspection: true },
|
||||
});
|
||||
for (const line of input.lines) {
|
||||
const ordered = orderLines.get(line.purchaseOrderLineId);
|
||||
if (!ordered) throw new AppError('RECEIPT_LINE_INVALID');
|
||||
const consumed = prior
|
||||
.filter(
|
||||
(entry) => entry.purchaseOrderLineId === line.purchaseOrderLineId,
|
||||
)
|
||||
.reduce(
|
||||
(sum, entry) =>
|
||||
sum +
|
||||
quantity(
|
||||
entry.inspection?.acceptedQuantity.toFixed(3) ??
|
||||
entry.quantity.toFixed(3),
|
||||
),
|
||||
0n,
|
||||
);
|
||||
if (
|
||||
consumed + quantity(line.quantity) >
|
||||
quantity(ordered.quantity.toFixed(3))
|
||||
)
|
||||
throw new AppError('RECEIPT_QUANTITY_LIMIT');
|
||||
}
|
||||
const receipt = await tx.goodsReceipt.create({
|
||||
data: {
|
||||
organizationId: actor.organizationId,
|
||||
purchaseOrderId: orderId,
|
||||
createdById: actor.userId,
|
||||
deliveryNote: input.deliveryNote,
|
||||
},
|
||||
});
|
||||
await tx.goodsReceiptLine.createMany({
|
||||
data: input.lines.map((line) => ({
|
||||
organizationId: actor.organizationId,
|
||||
purchaseOrderId: orderId,
|
||||
receiptId: receipt.id,
|
||||
purchaseOrderLineId: line.purchaseOrderLineId,
|
||||
quantity: line.quantity,
|
||||
})),
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'goods_receipt.created',
|
||||
receipt.id,
|
||||
);
|
||||
return tx.goodsReceipt.findUniqueOrThrow({
|
||||
where: { id: receipt.id },
|
||||
include: receiptView,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
inspect(actor: Principal, id: string, input: InspectionInput) {
|
||||
return this.access.mutate(actor, 'procurement.manage', async (tx) => {
|
||||
const receipt = await tx.goodsReceipt.findFirst({
|
||||
where: { id, organizationId: actor.organizationId },
|
||||
include: receiptView,
|
||||
});
|
||||
if (!receipt) throw new AppError('RECEIPT_NOT_FOUND');
|
||||
if (receipt.lines.some((line) => line.inspection))
|
||||
throw new AppError('RECEIPT_ALREADY_INSPECTED');
|
||||
const lines = new Map(receipt.lines.map((line) => [line.id, line]));
|
||||
if (
|
||||
input.lines.length !== lines.size ||
|
||||
input.lines.some((line) => !lines.has(line.receiptLineId))
|
||||
)
|
||||
throw new AppError('INSPECTION_LINES_INVALID');
|
||||
for (const decision of input.lines) {
|
||||
const received = lines.get(decision.receiptLineId)!;
|
||||
if (
|
||||
quantity(decision.acceptedQuantity) +
|
||||
quantity(decision.rejectedQuantity) !==
|
||||
quantity(received.quantity.toFixed(3))
|
||||
)
|
||||
throw new AppError('INSPECTION_QUANTITY_INVALID');
|
||||
if (
|
||||
quantity(decision.rejectedQuantity) > 0n &&
|
||||
!decision.rejectionReason
|
||||
)
|
||||
throw new AppError('INSPECTION_REASON_REQUIRED');
|
||||
}
|
||||
await tx.receiptInspection.createMany({
|
||||
data: input.lines.map((line) => ({
|
||||
organizationId: actor.organizationId,
|
||||
receiptLineId: line.receiptLineId,
|
||||
inspectedById: actor.userId,
|
||||
acceptedQuantity: line.acceptedQuantity,
|
||||
rejectedQuantity: line.rejectedQuantity,
|
||||
rejectionReason: line.rejectionReason,
|
||||
})),
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'goods_receipt.inspected',
|
||||
id,
|
||||
);
|
||||
return tx.goodsReceipt.findUniqueOrThrow({
|
||||
where: { id },
|
||||
include: receiptView,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
} from '@nestjs/common';
|
||||
import { SchemaPipe } from '../common/validation.pipe';
|
||||
import {
|
||||
CurrentPrincipal,
|
||||
RequirePermission,
|
||||
} from '../identity/access.decorator';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { GoodsReceiptStore } from './goods-receipt.store';
|
||||
import {
|
||||
receiptSchema,
|
||||
inspectionSchema,
|
||||
type ReceiptInput,
|
||||
type InspectionInput,
|
||||
} from './goods-receipt.schemas';
|
||||
|
||||
@Controller('purchase-orders/:orderId/receipts')
|
||||
export class GoodsReceiptsController {
|
||||
constructor(private readonly receipts: GoodsReceiptStore) {}
|
||||
@Get()
|
||||
@RequirePermission('procurement.read')
|
||||
list(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('orderId', ParseUUIDPipe) orderId: string,
|
||||
) {
|
||||
return this.receipts.list(actor, orderId);
|
||||
}
|
||||
@Post()
|
||||
@RequirePermission('procurement.manage')
|
||||
create(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('orderId', ParseUUIDPipe) orderId: string,
|
||||
@Body(new SchemaPipe(receiptSchema)) input: ReceiptInput,
|
||||
) {
|
||||
return this.receipts.create(actor, orderId, input);
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('goods-receipts')
|
||||
export class ReceiptInspectionController {
|
||||
constructor(private readonly receipts: GoodsReceiptStore) {}
|
||||
@Get(':id')
|
||||
@RequirePermission('procurement.read')
|
||||
get(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
) {
|
||||
return this.receipts.find(actor, id);
|
||||
}
|
||||
@Post(':id/inspect')
|
||||
@RequirePermission('procurement.manage')
|
||||
inspect(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(inspectionSchema)) input: InspectionInput,
|
||||
) {
|
||||
return this.receipts.inspect(actor, id, input);
|
||||
}
|
||||
}
|
||||
|
|
@ -5,10 +5,20 @@ import { ProcurementController } from './procurement.controller';
|
|||
import { ProcurementStore } from './procurement.store';
|
||||
import { PurchaseOrdersController } from './purchase-orders.controller';
|
||||
import { PurchaseOrderStore } from './purchase-order.store';
|
||||
import { GoodsReceiptStore } from './goods-receipt.store';
|
||||
import {
|
||||
GoodsReceiptsController,
|
||||
ReceiptInspectionController,
|
||||
} from './goods-receipts.controller';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, IdentityModule],
|
||||
providers: [ProcurementStore, PurchaseOrderStore],
|
||||
controllers: [ProcurementController, PurchaseOrdersController],
|
||||
providers: [ProcurementStore, PurchaseOrderStore, GoodsReceiptStore],
|
||||
controllers: [
|
||||
ProcurementController,
|
||||
PurchaseOrdersController,
|
||||
GoodsReceiptsController,
|
||||
ReceiptInspectionController,
|
||||
],
|
||||
})
|
||||
export class ProcurementModule {}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { AppError } from '../common/errors/app-error';
|
||||
|
||||
function scaled(value: string, scale: number): bigint {
|
||||
export function scaled(value: string, scale: number): bigint {
|
||||
const [whole, fraction] = value.split('.');
|
||||
if (!whole || !fraction || fraction.length !== scale)
|
||||
throw new AppError('DATA_CONSTRAINT');
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ 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 { lineTotal, totalOf } from './purchase-order-money';
|
||||
import { lineTotal, scaled, totalOf } from './purchase-order-money';
|
||||
import type {
|
||||
PurchaseOrderInput,
|
||||
PurchaseOrderQuery,
|
||||
|
|
@ -71,8 +71,8 @@ export class PurchaseOrderStore {
|
|||
if (!source || !source.material.active)
|
||||
throw new AppError('SUPPLIER_MATERIAL_NOT_FOUND');
|
||||
if (
|
||||
BigInt(line.quantity.replace('.', '')) <
|
||||
BigInt(source.minOrderQuantity.toFixed(3).replace('.', ''))
|
||||
scaled(line.quantity, 3) <
|
||||
scaled(source.minOrderQuantity.toFixed(3), 3)
|
||||
)
|
||||
throw new AppError('PURCHASE_ORDER_MINIMUM');
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,246 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||
|
||||
describe('goods receipt and QC 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();
|
||||
});
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
it('allows partial receipts, reconciles QC, and permits replacement of rejected goods', async () => {
|
||||
const purchase = await order();
|
||||
const path = `/api/v1/purchase-orders/${purchase.id}/receipts`;
|
||||
const first = await ctx
|
||||
.api()
|
||||
.post(path)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
deliveryNote: 'DN-001',
|
||||
lines: [{ purchaseOrderLineId: purchase.lineId, quantity: '2.000' }],
|
||||
})
|
||||
.expect(201);
|
||||
const over = await ctx
|
||||
.api()
|
||||
.post(path)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
lines: [{ purchaseOrderLineId: purchase.lineId, quantity: '2.000' }],
|
||||
})
|
||||
.expect(409);
|
||||
expect(over.body.code).toBe('RECEIPT_QUANTITY_LIMIT');
|
||||
const badQc = await ctx
|
||||
.api()
|
||||
.post(`/api/v1/goods-receipts/${first.body.id}/inspect`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
lines: [
|
||||
{
|
||||
receiptLineId: first.body.lines[0].id,
|
||||
acceptedQuantity: '1.000',
|
||||
rejectedQuantity: '0.000',
|
||||
},
|
||||
],
|
||||
})
|
||||
.expect(409);
|
||||
expect(badQc.body.code).toBe('INSPECTION_QUANTITY_INVALID');
|
||||
const checked = await ctx
|
||||
.api()
|
||||
.post(`/api/v1/goods-receipts/${first.body.id}/inspect`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
lines: [
|
||||
{
|
||||
receiptLineId: first.body.lines[0].id,
|
||||
acceptedQuantity: '1.000',
|
||||
rejectedQuantity: '1.000',
|
||||
rejectionReason: 'Cracked container',
|
||||
},
|
||||
],
|
||||
})
|
||||
.expect(201);
|
||||
expect(checked.body.lines[0].inspection.acceptedQuantity).toBe('1');
|
||||
const duplicate = await ctx
|
||||
.api()
|
||||
.post(`/api/v1/goods-receipts/${first.body.id}/inspect`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
lines: [
|
||||
{
|
||||
receiptLineId: first.body.lines[0].id,
|
||||
acceptedQuantity: '2.000',
|
||||
rejectedQuantity: '0.000',
|
||||
},
|
||||
],
|
||||
})
|
||||
.expect(409);
|
||||
expect(duplicate.body.code).toBe('RECEIPT_ALREADY_INSPECTED');
|
||||
await ctx
|
||||
.api()
|
||||
.post(path)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
lines: [{ purchaseOrderLineId: purchase.lineId, quantity: '2.000' }],
|
||||
})
|
||||
.expect(201);
|
||||
const list = await ctx.api().get(path).auth(ctx.token, auth).expect(200);
|
||||
expect(list.body).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('enforces scoped receipt lookups', async () => {
|
||||
const purchase = await order();
|
||||
const receipt = await ctx
|
||||
.api()
|
||||
.post(`/api/v1/purchase-orders/${purchase.id}/receipts`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
lines: [{ purchaseOrderLineId: purchase.lineId, quantity: '1.000' }],
|
||||
})
|
||||
.expect(201);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.get(`/api/v1/goods-receipts/${receipt.body.id}`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(200)
|
||||
).body.id,
|
||||
).toBe(receipt.body.id);
|
||||
await ctx
|
||||
.api()
|
||||
.get(`/api/v1/goods-receipts/${randomUUID()}`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(404);
|
||||
});
|
||||
|
||||
it('rejects draft orders, unrelated lines, and rejected goods without a reason', async () => {
|
||||
const draft = await order(false);
|
||||
const path = `/api/v1/purchase-orders/${draft.id}/receipts`;
|
||||
const payload = {
|
||||
lines: [{ purchaseOrderLineId: draft.lineId, quantity: '1.000' }],
|
||||
};
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(path)
|
||||
.auth(ctx.token, auth)
|
||||
.send(payload)
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('RECEIPT_ORDER_STATE');
|
||||
await ctx
|
||||
.api()
|
||||
.post(`/api/v1/purchase-orders/${draft.id}/issue`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(201);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(path)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
lines: [{ purchaseOrderLineId: randomUUID(), quantity: '1.000' }],
|
||||
})
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('RECEIPT_LINE_INVALID');
|
||||
const receipt = await ctx
|
||||
.api()
|
||||
.post(path)
|
||||
.auth(ctx.token, auth)
|
||||
.send(payload)
|
||||
.expect(201);
|
||||
const inspect = `/api/v1/goods-receipts/${receipt.body.id}/inspect`;
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post(inspect)
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
lines: [
|
||||
{
|
||||
receiptLineId: receipt.body.lines[0].id,
|
||||
acceptedQuantity: '0.000',
|
||||
rejectedQuantity: '1.000',
|
||||
},
|
||||
],
|
||||
})
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('INSPECTION_REASON_REQUIRED');
|
||||
expect(
|
||||
await ctx.db.receiptInspection.count({
|
||||
where: { receiptLineId: receipt.body.lines[0].id },
|
||||
}),
|
||||
).toBe(0);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue