diff --git a/README.md b/README.md index 4936f9e..730af39 100644 --- a/README.md +++ b/README.md @@ -53,3 +53,4 @@ Batch cost snapshots: see [Phase 2M API guide](docs/batch-cost-api.md). Warehouse material stock: see [Phase 2N API guide](docs/material-warehouse-stock-api.md). Production material stock posting: see [Phase 2O API guide](docs/production-material-stock-api.md). Packaging material stock posting: see [Phase 2P API guide](docs/packaging-material-stock-api.md). +Finished-goods receipts: see [Phase 2Q API guide](docs/finished-goods-receipt-api.md). diff --git a/docs/finished-goods-receipt-api.md b/docs/finished-goods-receipt-api.md new file mode 100644 index 0000000..25ed2ad --- /dev/null +++ b/docs/finished-goods-receipt-api.md @@ -0,0 +1,12 @@ +# Finished-goods receipt (Phase 2Q) + +Once a production batch is completed, packaging is recorded, and both production and packaging materials have been posted to stock, receive the batch's **good quantity** into a chosen warehouse. Rejected pieces never enter finished-goods stock. The receipt creates the variant's warehouse stock item when needed and appends a `PRODUCTION_OUTPUT` entry to the existing finished-goods stock ledger. + +| Method | Path | Permission | +| ------ | ------------------------------------------------------------ | ------------------ | +| GET | `/api/v1/production-batches/:batchId/finished-goods-receipt` | `inventory.read` | +| POST | `/api/v1/production-batches/:batchId/finished-goods-receipt` | `inventory.manage` | + +POST body: `{ "warehouseId": "", "idempotencyKey": "" }`. A batch can be received once. A retry with the same key and warehouse returns the original receipt; a changed retry returns `FINISHED_GOODS_REPLAY_CONFLICT`. A new key for an already received batch returns `FINISHED_GOODS_ALREADY_POSTED`. + +The response includes batch, variant, warehouse, stock-item and ledger-entry IDs plus the received quantity. The database independently verifies the completed batch and good quantity, both material-stock postings, source variant and warehouse. The ledger insert updates on-hand stock in the same transaction, with a capacity bound. Receipt and ledger records are immutable. Existing inventory availability and reservation endpoints then include the newly received units. diff --git a/docs/packaging-material-stock-api.md b/docs/packaging-material-stock-api.md index d0c48a8..60eedc9 100644 --- a/docs/packaging-material-stock-api.md +++ b/docs/packaging-material-stock-api.md @@ -9,4 +9,4 @@ An operator can post an immutable packaging record's used and wasted material qu POST body: `{ "warehouseId": "", "idempotencyKey": "" }`. A packaging record can be posted once. A same-key, same-request retry returns the original posting; reusing the key for another warehouse returns `PACKAGING_STOCK_REPLAY_CONFLICT`. A new key for an already posted record returns `PACKAGING_STOCK_ALREADY_POSTED`. The response identifies the source packaging line, material, kind and signed quantity for every ledger entry. -The selected warehouse must have enough of every packaging or label material for the **sum** of used and wasted quantities. `PACKAGING_STOCK_INSUFFICIENT` rejects the entire posting if any material is short. The database verifies each entry's source line, material, warehouse, kind and exact signed quantity, and prevents negative balances. Posting headers and ledger entries are append-only. Finished-goods stock output, transfers and adjustments are separate milestones. +The selected warehouse must have enough of every packaging or label material for the **sum** of used and wasted quantities. `PACKAGING_STOCK_INSUFFICIENT` rejects the entire posting if any material is short. The database verifies each entry's source line, material, warehouse, kind and exact signed quantity, and prevents negative balances. Posting headers and ledger entries are append-only. Finished-goods output is documented separately; material transfers and adjustments remain later milestones. diff --git a/docs/roadmap.md b/docs/roadmap.md index a48dd7c..6ab6834 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -30,6 +30,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase - 2N (implemented): per-warehouse raw-material balances and append-only stock postings from QC-accepted goods receipts. Production and packaging stock deduction, transfers, adjustments and finished-goods output remain later milestones. - 2O (implemented): atomic per-warehouse production material stock deduction from completed-batch consumption and wastage events. Packaging stock deduction, transfers, adjustments and finished-goods output remain later milestones. - 2P (implemented): atomic per-warehouse packaging and label stock deduction from recorded packaging use and wastage. Transfers, adjustments and finished-goods output remain later milestones. +- 2Q (implemented): single, idempotent finished-goods receipt per completed and stock-posted batch, crediting only good units to an organization-scoped warehouse variant balance. Material transfers and adjustments remain later milestones. ## Phase 3: B2B and white label diff --git a/prisma/inventory.prisma b/prisma/inventory.prisma index 7f4e632..f4d153e 100644 --- a/prisma/inventory.prisma +++ b/prisma/inventory.prisma @@ -13,6 +13,7 @@ model Warehouse { materialReceiptPostings MaterialReceiptPosting[] productionStockPostings ProductionStockPosting[] packagingStockPostings PackagingStockPosting[] + finishedGoodsReceipts FinishedGoodsReceipt[] @@unique([organizationId, name]) @@unique([id, organizationId]) @@map("warehouses") @@ -27,6 +28,7 @@ model StockItem { warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict) entries StockLedger[] reservations StockReservation[] + finishedGoodsReceipts FinishedGoodsReceipt[] @@unique([variantId, warehouseId]) @@unique([id, organizationId]) @@index([organizationId, id]) @@ -42,9 +44,12 @@ model StockLedger { reason String @db.VarChar(200) idempotencyKey String @map("idempotency_key") @db.Uuid requestHash String @map("request_hash") @db.Char(64) + finishedGoodsReceiptId String? @unique @map("finished_goods_receipt_id") @db.Uuid createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) stockItem StockItem @relation(fields: [stockItemId, organizationId], references: [id, organizationId], onDelete: Restrict) + finishedGoodsReceipt FinishedGoodsReceipt? @relation(fields: [finishedGoodsReceiptId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "stock_ledger_finished_goods_scope_fkey") @@unique([organizationId, idempotencyKey]) + @@unique([finishedGoodsReceiptId, organizationId]) @@index([stockItemId, createdAt, id]) @@map("stock_ledger") } @@ -68,3 +73,26 @@ model StockReservation { @@index([userId, organizationId]) @@map("stock_reservations") } + +model FinishedGoodsReceipt { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + batchId String @unique @map("batch_id") @db.Uuid + warehouseId String @map("warehouse_id") @db.Uuid + stockItemId String @map("stock_item_id") @db.Uuid + postedById String @map("posted_by_id") @db.Uuid + quantity Int + idempotencyKey String @map("idempotency_key") @db.Uuid + requestHash String @map("request_hash") @db.Char(64) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict) + batch ProductionBatch @relation(fields: [batchId, organizationId], references: [id, organizationId], onDelete: Restrict) + warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict) + stockItem StockItem @relation(fields: [stockItemId, organizationId], references: [id, organizationId], onDelete: Restrict) + postedBy User @relation(fields: [postedById, organizationId], references: [id, organizationId], onDelete: Restrict) + entry StockLedger? + @@unique([organizationId, idempotencyKey]) + @@unique([batchId, organizationId]) + @@unique([id, organizationId]) + @@map("finished_goods_receipts") +} diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index d2fd1a0..0f24cb5 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -29,5 +29,6 @@ "20260929170000_batch_cost_snapshots": "ef59558614f6bfe7fe07a095a4bafef2d3ffdb0ea514dfb1761a02d8d4da0bab", "20260929171600_material_warehouse_stock": "47645ff022037ea486ca82902bdf09ca36ebf05a94500b160dcd57c2d812eab8", "20260929173800_production_material_stock": "68f5755167f87a646901835be9fe6318a3ae6bb9a3d70d8a722915d1eff3c7a4", - "20260929195800_packaging_material_stock": "2b11c19499d917bcdd53ade20175235ef83cc64cdafda2118ea2dac2096a6f8d" + "20260929195800_packaging_material_stock": "2b11c19499d917bcdd53ade20175235ef83cc64cdafda2118ea2dac2096a6f8d", + "20260929203400_finished_goods_receipt": "7745c23f9037d7bb0de7bdfaf94610794b83213f041583c0f9678c4e837f53f0" } diff --git a/prisma/migrations/20260929203400_finished_goods_receipt/migration.sql b/prisma/migrations/20260929203400_finished_goods_receipt/migration.sql new file mode 100644 index 0000000..9b14c81 --- /dev/null +++ b/prisma/migrations/20260929203400_finished_goods_receipt/migration.sql @@ -0,0 +1,68 @@ +CREATE TABLE "finished_goods_receipts" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "batch_id" UUID NOT NULL, + "warehouse_id" UUID NOT NULL, + "stock_item_id" UUID NOT NULL, + "posted_by_id" UUID NOT NULL, + "quantity" INTEGER NOT NULL, + "idempotency_key" UUID NOT NULL, + "request_hash" CHAR(64) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "finished_goods_receipts_pkey" PRIMARY KEY ("id"), + CONSTRAINT "finished_goods_receipts_quantity" CHECK ("quantity" BETWEEN 1 AND 2000000000), + CONSTRAINT "finished_goods_receipts_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$') +); +CREATE UNIQUE INDEX "finished_goods_receipts_batch_id_key" ON "finished_goods_receipts"("batch_id"); +CREATE UNIQUE INDEX "finished_goods_receipts_batch_id_organization_id_key" ON "finished_goods_receipts"("batch_id", "organization_id"); +CREATE UNIQUE INDEX "finished_goods_receipts_organization_id_idempotency_key_key" ON "finished_goods_receipts"("organization_id", "idempotency_key"); +CREATE UNIQUE INDEX "finished_goods_receipts_id_organization_id_key" ON "finished_goods_receipts"("id", "organization_id"); +ALTER TABLE "finished_goods_receipts" ADD CONSTRAINT "finished_goods_receipts_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "finished_goods_receipts" ADD CONSTRAINT "finished_goods_receipts_batch_id_organization_id_fkey" FOREIGN KEY ("batch_id", "organization_id") REFERENCES "production_batches"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "finished_goods_receipts" ADD CONSTRAINT "finished_goods_receipts_warehouse_id_organization_id_fkey" FOREIGN KEY ("warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "finished_goods_receipts" ADD CONSTRAINT "finished_goods_receipts_stock_item_id_organization_id_fkey" FOREIGN KEY ("stock_item_id", "organization_id") REFERENCES "stock_items"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "finished_goods_receipts" ADD CONSTRAINT "finished_goods_receipts_posted_by_id_organization_id_fkey" FOREIGN KEY ("posted_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; + +ALTER TABLE "stock_ledger" ADD COLUMN "finished_goods_receipt_id" UUID; +CREATE UNIQUE INDEX "stock_ledger_finished_goods_receipt_id_key" ON "stock_ledger"("finished_goods_receipt_id"); +CREATE UNIQUE INDEX "stock_ledger_finished_goods_receipt_id_organization_id_key" ON "stock_ledger"("finished_goods_receipt_id", "organization_id"); +ALTER TABLE "stock_ledger" ADD CONSTRAINT "stock_ledger_finished_goods_scope_fkey" FOREIGN KEY ("finished_goods_receipt_id", "organization_id") REFERENCES "finished_goods_receipts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE FUNCTION guard_finished_goods_receipt() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Finished-goods receipts are immutable'; END IF; + IF NOT EXISTS ( + SELECT 1 FROM production_batches b + JOIN production_batch_completions c ON c.batch_id = b.id AND c.organization_id = NEW.organization_id + JOIN product_boms bom ON bom.id = b.bom_id AND bom.organization_id = NEW.organization_id + JOIN packaging_runs r ON r.batch_id = b.id AND r.organization_id = NEW.organization_id + JOIN production_stock_postings ps ON ps.batch_id = b.id AND ps.organization_id = NEW.organization_id + JOIN packaging_stock_postings ks ON ks.run_id = r.id AND ks.organization_id = NEW.organization_id + JOIN stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id + WHERE b.id = NEW.batch_id AND b.organization_id = NEW.organization_id + AND b.status = 'COMPLETED' AND c.good_quantity = NEW.quantity + AND s.variant_id = bom.variant_id AND s.warehouse_id = NEW.warehouse_id + ) THEN RAISE EXCEPTION 'Finished-goods receipt requires completed and stock-posted production and packaging'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER finished_goods_receipts_guard BEFORE INSERT OR UPDATE OR DELETE ON finished_goods_receipts FOR EACH ROW EXECUTE FUNCTION guard_finished_goods_receipt(); + +CREATE FUNCTION post_finished_goods_ledger() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.finished_goods_receipt_id IS NULL THEN RETURN NEW; END IF; + IF NOT EXISTS ( + SELECT 1 FROM finished_goods_receipts r + WHERE r.id = NEW.finished_goods_receipt_id AND r.organization_id = NEW.organization_id + AND r.stock_item_id = NEW.stock_item_id AND r.posted_by_id = NEW.actor_id + AND r.quantity = NEW.delta AND r.idempotency_key = NEW.idempotency_key + AND r.request_hash = NEW.request_hash AND NEW.reason = 'PRODUCTION_OUTPUT' + ) THEN RAISE EXCEPTION 'Finished-goods stock entry does not match its receipt'; END IF; + UPDATE stock_items SET on_hand = on_hand + NEW.delta + WHERE id = NEW.stock_item_id AND organization_id = NEW.organization_id + AND on_hand <= 2000000000 - NEW.delta; + IF NOT FOUND THEN RAISE EXCEPTION 'Finished-goods stock capacity exceeded'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER stock_ledger_finished_goods_post BEFORE INSERT ON stock_ledger FOR EACH ROW EXECUTE FUNCTION post_finished_goods_ledger(); diff --git a/prisma/production.prisma b/prisma/production.prisma index fb7f0bb..adb134f 100644 --- a/prisma/production.prisma +++ b/prisma/production.prisma @@ -25,6 +25,7 @@ model ProductionBatch { packagingRun PackagingRun? costSnapshot BatchCostSnapshot? stockPosting ProductionStockPosting? + finishedGoodsReceipt FinishedGoodsReceipt? @@unique([organizationId, reference]) @@unique([id, organizationId]) @@unique([id, bomId, organizationId]) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index bb68636..1002054 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -48,6 +48,7 @@ model Organization { materialReceiptPostings MaterialReceiptPosting[] productionStockPostings ProductionStockPosting[] packagingStockPostings PackagingStockPosting[] + finishedGoodsReceipts FinishedGoodsReceipt[] @@map("organizations") } model User { @@ -86,6 +87,7 @@ model User { materialReceiptPostings MaterialReceiptPosting[] productionStockPostings ProductionStockPosting[] packagingStockPostings PackagingStockPosting[] + finishedGoodsReceipts FinishedGoodsReceipt[] stockEntries StockLedger[] stockReservations StockReservation[] carts Cart[] diff --git a/src/common/errors/commerce-errors.ts b/src/common/errors/commerce-errors.ts index ed2492d..531fe96 100644 --- a/src/common/errors/commerce-errors.ts +++ b/src/common/errors/commerce-errors.ts @@ -606,4 +606,54 @@ export const COMMERCE_ERRORS = { 'Idempotency key was used for different packaging stock', 'Packaging stock idempotency payload mismatch', ], + FINISHED_GOODS_RECEIPT_NOT_FOUND: [ + 404, + 'Finished-goods receipt not found', + 'Finished-goods receipt scoped lookup failed', + ], + FINISHED_GOODS_REPLAY_CONFLICT: [ + 409, + 'Idempotency key was used for different finished goods', + 'Finished-goods receipt idempotency payload mismatch', + ], + FINISHED_GOODS_ALREADY_POSTED: [ + 409, + 'Finished goods were already received for this batch', + 'Finished-goods duplicate receipt rejected', + ], + FINISHED_GOODS_BATCH_STATE: [ + 409, + 'Complete the batch before receiving finished goods', + 'Finished-goods batch state rejected', + ], + FINISHED_GOODS_NO_OUTPUT: [ + 409, + 'This batch has no good finished goods to receive', + 'Finished-goods zero output rejected', + ], + FINISHED_GOODS_PACKAGING_REQUIRED: [ + 409, + 'Record packaging before receiving finished goods', + 'Finished-goods packaging record missing', + ], + FINISHED_GOODS_PRODUCTION_STOCK_REQUIRED: [ + 409, + 'Post production material stock before receiving finished goods', + 'Finished-goods production stock gate failed', + ], + FINISHED_GOODS_PACKAGING_STOCK_REQUIRED: [ + 409, + 'Post packaging material stock before receiving finished goods', + 'Finished-goods packaging stock gate failed', + ], + FINISHED_GOODS_STOCK_CAPACITY: [ + 409, + 'Finished-goods warehouse stock capacity exceeded', + 'Finished-goods stock integer bound exceeded', + ], + FINISHED_GOODS_KEY_CONFLICT: [ + 409, + 'Idempotency key is already used for another stock entry', + 'Finished-goods stock ledger idempotency key conflict', + ], } as const; diff --git a/src/production/finished-goods-receipt.controller.ts b/src/production/finished-goods-receipt.controller.ts new file mode 100644 index 0000000..8ef2c61 --- /dev/null +++ b/src/production/finished-goods-receipt.controller.ts @@ -0,0 +1,44 @@ +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 { + materialStockPostingSchema, + type MaterialStockPostingInput, +} from './material-stock-posting.schemas'; +import { FinishedGoodsReceiptStore } from './finished-goods-receipt.store'; + +@Controller('production-batches/:batchId/finished-goods-receipt') +export class FinishedGoodsReceiptController { + constructor(private readonly receipts: FinishedGoodsReceiptStore) {} + + @Get() + @RequirePermission('inventory.read') + find( + @CurrentPrincipal() actor: Principal, + @Param('batchId', ParseUUIDPipe) batchId: string, + ) { + return this.receipts.find(actor, batchId); + } + + @Post() + @RequirePermission('inventory.manage') + create( + @CurrentPrincipal() actor: Principal, + @Param('batchId', ParseUUIDPipe) batchId: string, + @Body(new SchemaPipe(materialStockPostingSchema)) + input: MaterialStockPostingInput, + ) { + return this.receipts.create(actor, batchId, input); + } +} diff --git a/src/production/finished-goods-receipt.store.ts b/src/production/finished-goods-receipt.store.ts new file mode 100644 index 0000000..35051b0 --- /dev/null +++ b/src/production/finished-goods-receipt.store.ts @@ -0,0 +1,167 @@ +import { Injectable } from '@nestjs/common'; +import { AppError } from '../common/errors/app-error'; +import { DatabaseService } from '../database/database.service'; +import type { Prisma } from '../generated/prisma/client'; +import { AccessStore } from '../identity/access.store'; +import { recordAudit } from '../identity/audit'; +import type { Principal } from '../identity/identity.types'; +import { stockPostingHash } from './material-stock-posting.helpers'; +import type { MaterialStockPostingInput } from './material-stock-posting.schemas'; + +const MAX_STOCK = 2_000_000_000; +const receiptView = { + entry: true, + batch: { include: { bom: { select: { variantId: true } } } }, +}; +type Receipt = Prisma.FinishedGoodsReceiptGetPayload<{ + include: typeof receiptView; +}>; +function present(receipt: Receipt) { + return { + id: receipt.id, + batchId: receipt.batchId, + variantId: receipt.batch.bom.variantId, + warehouseId: receipt.warehouseId, + stockItemId: receipt.stockItemId, + quantity: receipt.quantity, + postedById: receipt.postedById, + createdAt: receipt.createdAt, + ledgerEntryId: receipt.entry?.id, + }; +} + +@Injectable() +export class FinishedGoodsReceiptStore { + constructor( + private readonly db: DatabaseService, + private readonly access: AccessStore, + ) {} + + async find(actor: Principal, batchId: string) { + const receipt = await this.db.finishedGoodsReceipt.findFirst({ + where: { batchId, organizationId: actor.organizationId }, + include: receiptView, + }); + if (!receipt) throw new AppError('FINISHED_GOODS_RECEIPT_NOT_FOUND'); + return present(receipt); + } + + create(actor: Principal, batchId: string, input: MaterialStockPostingInput) { + return this.access.mutate(actor, 'inventory.manage', async (tx) => { + const hash = stockPostingHash(batchId, input.warehouseId); + const prior = await tx.finishedGoodsReceipt.findFirst({ + where: { + organizationId: actor.organizationId, + idempotencyKey: input.idempotencyKey, + }, + include: receiptView, + }); + if (prior) { + if (prior.requestHash !== hash) + throw new AppError('FINISHED_GOODS_REPLAY_CONFLICT'); + return present(prior); + } + const batch = await tx.productionBatch.findFirst({ + where: { id: batchId, organizationId: actor.organizationId }, + include: { + bom: { select: { variantId: true } }, + completion: true, + packagingRun: { + select: { id: true, stockPosting: { select: { id: true } } }, + }, + stockPosting: { select: { id: true } }, + }, + }); + if (!batch) throw new AppError('BATCH_NOT_FOUND'); + if ( + await tx.finishedGoodsReceipt.findUnique({ + where: { batchId }, + select: { id: true }, + }) + ) + throw new AppError('FINISHED_GOODS_ALREADY_POSTED'); + if (batch.status !== 'COMPLETED' || !batch.completion) + throw new AppError('FINISHED_GOODS_BATCH_STATE'); + const quantity = batch.completion.goodQuantity; + if (quantity === 0) throw new AppError('FINISHED_GOODS_NO_OUTPUT'); + if (!batch.packagingRun) + throw new AppError('FINISHED_GOODS_PACKAGING_REQUIRED'); + if (!batch.stockPosting) + throw new AppError('FINISHED_GOODS_PRODUCTION_STOCK_REQUIRED'); + if (!batch.packagingRun.stockPosting) + throw new AppError('FINISHED_GOODS_PACKAGING_STOCK_REQUIRED'); + const warehouse = await tx.warehouse.findFirst({ + where: { id: input.warehouseId, organizationId: actor.organizationId }, + select: { id: true }, + }); + if (!warehouse) throw new AppError('WAREHOUSE_NOT_FOUND'); + const variantId = batch.bom.variantId; + let stock = await tx.stockItem.findFirst({ + where: { + organizationId: actor.organizationId, + warehouseId: warehouse.id, + variantId, + }, + }); + if (!stock) + stock = await tx.stockItem.create({ + data: { + organizationId: actor.organizationId, + warehouseId: warehouse.id, + variantId, + }, + }); + await tx.$queryRaw`SELECT id FROM stock_items WHERE id = ${stock.id}::uuid FOR UPDATE`; + stock = await tx.stockItem.findUniqueOrThrow({ where: { id: stock.id } }); + if (stock.onHand > MAX_STOCK - quantity) + throw new AppError('FINISHED_GOODS_STOCK_CAPACITY'); + if ( + await tx.stockLedger.findFirst({ + where: { + organizationId: actor.organizationId, + idempotencyKey: input.idempotencyKey, + }, + select: { id: true }, + }) + ) + throw new AppError('FINISHED_GOODS_KEY_CONFLICT'); + const receipt = await tx.finishedGoodsReceipt.create({ + data: { + organizationId: actor.organizationId, + batchId, + warehouseId: warehouse.id, + stockItemId: stock.id, + postedById: actor.userId, + quantity, + idempotencyKey: input.idempotencyKey, + requestHash: hash, + }, + }); + await tx.stockLedger.create({ + data: { + organizationId: actor.organizationId, + stockItemId: stock.id, + actorId: actor.userId, + delta: quantity, + reason: 'PRODUCTION_OUTPUT', + idempotencyKey: input.idempotencyKey, + requestHash: hash, + finishedGoodsReceiptId: receipt.id, + }, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'batch.finished_goods_received', + receipt.id, + ); + return present( + await tx.finishedGoodsReceipt.findUniqueOrThrow({ + where: { id: receipt.id }, + include: receiptView, + }), + ); + }); + } +} diff --git a/src/production/production.module.ts b/src/production/production.module.ts index 1853e23..84e37ed 100644 --- a/src/production/production.module.ts +++ b/src/production/production.module.ts @@ -11,6 +11,8 @@ import { ProductionStockPostingController } from './production-stock-posting.con import { ProductionStockPostingStore } from './production-stock-posting.store'; import { PackagingStockPostingController } from './packaging-stock-posting.controller'; import { PackagingStockPostingStore } from './packaging-stock-posting.store'; +import { FinishedGoodsReceiptController } from './finished-goods-receipt.controller'; +import { FinishedGoodsReceiptStore } from './finished-goods-receipt.store'; @Module({ imports: [DatabaseModule, IdentityModule], @@ -20,6 +22,7 @@ import { PackagingStockPostingStore } from './packaging-stock-posting.store'; PackagingRunStore, ProductionStockPostingStore, PackagingStockPostingStore, + FinishedGoodsReceiptStore, ], controllers: [ BatchesController, @@ -27,6 +30,7 @@ import { PackagingStockPostingStore } from './packaging-stock-posting.store'; PackagingRunController, ProductionStockPostingController, PackagingStockPostingController, + FinishedGoodsReceiptController, ], }) export class ProductionModule {} diff --git a/test/finished-goods-receipt.spec.ts b/test/finished-goods-receipt.spec.ts new file mode 100644 index 0000000..4280301 --- /dev/null +++ b/test/finished-goods-receipt.spec.ts @@ -0,0 +1,295 @@ +import { randomUUID } from 'node:crypto'; +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { secondActor } from './helpers/commerce'; +import { + completeCostBatch, + packageCostBatch, + prepareCostBatch, + recordCostUsage, + startCostBatch, +} from './helpers/batch-cost'; + +describe('finished-goods receipt', () => { + let ctx: IdentityApp; + const auth = { type: 'bearer' as const }; + const post = (batchId: string, body: object) => + ctx + .api() + .post(`/api/v1/production-batches/${batchId}/finished-goods-receipt`) + .auth(ctx.token, auth) + .send(body); + const get = (batchId: string) => + ctx + .api() + .get(`/api/v1/production-batches/${batchId}/finished-goods-receipt`) + .auth(ctx.token, auth); + const warehouse = async () => + ( + await ctx + .api() + .post('/api/v1/inventory/warehouses') + .auth(ctx.token, auth) + .send({ name: `Output ${randomUUID().slice(0, 8)}` }) + .expect(201) + ).body.id as string; + const prepare = async () => { + const batch = await prepareCostBatch(ctx); + const warehouseId = await warehouse(); + await ctx.db.materialStockItem.createMany({ + data: [ + { + organizationId: ctx.owner.organizationId, + warehouseId, + materialId: batch.productionMaterialId, + onHand: '250.000', + }, + { + organizationId: ctx.owner.organizationId, + warehouseId, + materialId: batch.packagingMaterialId, + onHand: '25.000', + }, + ], + }); + return { ...batch, warehouseId }; + }; + const complete = async ( + batch: Awaited>, + goodQuantity = 20, + ) => { + await startCostBatch(ctx, batch.batchId); + await recordCostUsage( + ctx, + batch.batchId, + batch.productionLineId, + 'CONSUMED', + '200.000', + ); + await completeCostBatch(ctx, batch.batchId, goodQuantity); + await packageCostBatch( + ctx, + batch.batchId, + batch.packagingBomId, + batch.packagingLineId, + ); + }; + const postMaterials = async (batch: Awaited>) => { + await ctx + .api() + .post( + `/api/v1/production-batches/${batch.batchId}/material-stock-posting`, + ) + .auth(ctx.token, auth) + .send({ warehouseId: batch.warehouseId, idempotencyKey: randomUUID() }) + .expect(201); + await ctx + .api() + .post( + `/api/v1/production-batches/${batch.batchId}/packaging-stock-posting`, + ) + .auth(ctx.token, auth) + .send({ warehouseId: batch.warehouseId, idempotencyKey: randomUUID() }) + .expect(201); + }; + const ready = async (goodQuantity = 20) => { + const batch = await prepare(); + await complete(batch, goodQuantity); + await postMaterials(batch); + return batch; + }; + + beforeAll(async () => { + ctx = await identityApp(); + }, 60000); + afterAll(async () => { + await ctx?.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + + it('receives only good completed units into the selected warehouse once', async () => { + const batch = await ready(10); + const otherWarehouse = await warehouse(); + const body = { + warehouseId: batch.warehouseId, + idempotencyKey: randomUUID(), + }; + const receipt = await post(batch.batchId, body).expect(201); + expect(receipt.body).toMatchObject({ + batchId: batch.batchId, + variantId: batch.variantId, + warehouseId: batch.warehouseId, + quantity: 10, + }); + const stock = await ctx.db.stockItem.findUniqueOrThrow({ + where: { id: receipt.body.stockItemId }, + }); + expect(stock.onHand).toBe(10); + expect( + await ctx.db.stockItem.count({ + where: { variantId: batch.variantId, warehouseId: otherWarehouse }, + }), + ).toBe(0); + const entry = await ctx.db.stockLedger.findUniqueOrThrow({ + where: { finishedGoodsReceiptId: receipt.body.id }, + }); + expect(entry).toMatchObject({ + delta: 10, + reason: 'PRODUCTION_OUTPUT', + stockItemId: stock.id, + }); + expect((await post(batch.batchId, body).expect(201)).body.id).toBe( + receipt.body.id, + ); + expect((await get(batch.batchId).expect(200)).body.ledgerEntryId).toBe( + entry.id, + ); + }); + + it('requires packaging and both material postings before receiving output', async () => { + const batch = await prepare(); + const body = { + warehouseId: batch.warehouseId, + idempotencyKey: randomUUID(), + }; + expect((await post(batch.batchId, body).expect(409)).body.code).toBe( + 'FINISHED_GOODS_BATCH_STATE', + ); + await startCostBatch(ctx, batch.batchId); + await recordCostUsage( + ctx, + batch.batchId, + batch.productionLineId, + 'CONSUMED', + '200.000', + ); + await completeCostBatch(ctx, batch.batchId); + expect((await post(batch.batchId, body).expect(409)).body.code).toBe( + 'FINISHED_GOODS_PACKAGING_REQUIRED', + ); + await packageCostBatch( + ctx, + batch.batchId, + batch.packagingBomId, + batch.packagingLineId, + ); + expect((await post(batch.batchId, body).expect(409)).body.code).toBe( + 'FINISHED_GOODS_PRODUCTION_STOCK_REQUIRED', + ); + await ctx + .api() + .post( + `/api/v1/production-batches/${batch.batchId}/material-stock-posting`, + ) + .auth(ctx.token, auth) + .send({ warehouseId: batch.warehouseId, idempotencyKey: randomUUID() }) + .expect(201); + expect((await post(batch.batchId, body).expect(409)).body.code).toBe( + 'FINISHED_GOODS_PACKAGING_STOCK_REQUIRED', + ); + expect( + await ctx.db.finishedGoodsReceipt.count({ + where: { batchId: batch.batchId }, + }), + ).toBe(0); + }); + + it('does not receive a fully rejected batch', async () => { + const batch = await prepare(); + await startCostBatch(ctx, batch.batchId); + await completeCostBatch(ctx, batch.batchId, 0); + expect( + ( + await post(batch.batchId, { + warehouseId: batch.warehouseId, + idempotencyKey: randomUUID(), + }).expect(409) + ).body.code, + ).toBe('FINISHED_GOODS_NO_OUTPUT'); + }); + + it('rejects changed retries, duplicate receipt and capacity overflow', async () => { + const batch = await ready(); + const body = { + warehouseId: batch.warehouseId, + idempotencyKey: randomUUID(), + }; + await post(batch.batchId, body).expect(201); + expect( + ( + await post(batch.batchId, { + ...body, + warehouseId: await warehouse(), + }).expect(409) + ).body.code, + ).toBe('FINISHED_GOODS_REPLAY_CONFLICT'); + expect( + ( + await post(batch.batchId, { + ...body, + idempotencyKey: randomUUID(), + }).expect(409) + ).body.code, + ).toBe('FINISHED_GOODS_ALREADY_POSTED'); + const another = await ready(); + const stock = await ctx.db.stockItem.create({ + data: { + organizationId: ctx.owner.organizationId, + warehouseId: another.warehouseId, + variantId: another.variantId, + onHand: 2_000_000_000, + }, + }); + expect( + ( + await post(another.batchId, { + warehouseId: another.warehouseId, + idempotencyKey: randomUUID(), + }).expect(409) + ).body.code, + ).toBe('FINISHED_GOODS_STOCK_CAPACITY'); + expect( + await ctx.db.finishedGoodsReceipt.count({ + where: { batchId: another.batchId }, + }), + ).toBe(0); + expect( + (await ctx.db.stockItem.findUniqueOrThrow({ where: { id: stock.id } })) + .onHand, + ).toBe(2_000_000_000); + }); + + it('enforces permission, tenant scope and an immutable source receipt', async () => { + const batch = await ready(); + const body = { + warehouseId: batch.warehouseId, + idempotencyKey: randomUUID(), + }; + const reader = await secondActor(ctx, true, ['inventory.read']); + await ctx + .api() + .post( + `/api/v1/production-batches/${batch.batchId}/finished-goods-receipt`, + ) + .auth(reader.token, auth) + .send(body) + .expect(403); + const outsider = await secondActor(ctx, false, [ + 'inventory.read', + 'inventory.manage', + ]); + await ctx + .api() + .get(`/api/v1/production-batches/${batch.batchId}/finished-goods-receipt`) + .auth(outsider.token, auth) + .expect(404); + const receipt = await post(batch.batchId, body).expect(201); + await expect( + ctx.db.finishedGoodsReceipt.update({ + where: { id: receipt.body.id }, + data: { quantity: 21 }, + }), + ).rejects.toThrow(); + }); +}); diff --git a/test/helpers/batch-cost.ts b/test/helpers/batch-cost.ts index 26ddf00..547d602 100644 --- a/test/helpers/batch-cost.ts +++ b/test/helpers/batch-cost.ts @@ -34,6 +34,7 @@ export async function prepareCostBatch(ctx: IdentityApp) { const batch = await createBatch(ctx, production.bomId).expect(201); return { batchId: batch.body.id as string, + variantId: production.variantId, productionLineId: production.bomLineId, productionMaterialId: production.materialId, packagingBomId: packaging.body.id as string,