From 6651ed3f4e7223ad973528d1b4cc04416f46fbde Mon Sep 17 00:00:00 2001 From: mihir Date: Tue, 29 Sep 2026 20:09:37 +0530 Subject: [PATCH] feat(production): post packaging use to warehouse stock --- README.md | 1 + docs/material-warehouse-stock-api.md | 2 +- docs/packaging-material-stock-api.md | 12 ++ docs/production-material-stock-api.md | 2 +- docs/roadmap.md | 1 + prisma/inventory.prisma | 1 + prisma/material-stock.prisma | 27 +++ prisma/migration-checksums.json | 3 +- .../migration.sql | 93 ++++++++ prisma/packaging-run.prisma | 3 + prisma/schema.prisma | 2 + src/common/errors/commerce-errors.ts | 20 ++ .../material-stock-posting.helpers.ts | 35 +++ .../material-stock-posting.schemas.ts | 8 + .../packaging-stock-posting.controller.ts | 44 ++++ .../packaging-stock-posting.store.ts | 168 +++++++++++++++ .../production-stock-posting.controller.ts | 10 +- .../production-stock-posting.schemas.ts | 11 - .../production-stock-posting.store.ts | 40 ++-- src/production/production.module.ts | 4 + test/packaging-material-stock.spec.ts | 201 ++++++++++++++++++ 21 files changed, 644 insertions(+), 44 deletions(-) create mode 100644 docs/packaging-material-stock-api.md create mode 100644 prisma/migrations/20260929195800_packaging_material_stock/migration.sql create mode 100644 src/production/material-stock-posting.helpers.ts create mode 100644 src/production/material-stock-posting.schemas.ts create mode 100644 src/production/packaging-stock-posting.controller.ts create mode 100644 src/production/packaging-stock-posting.store.ts delete mode 100644 src/production/production-stock-posting.schemas.ts create mode 100644 test/packaging-material-stock.spec.ts diff --git a/README.md b/README.md index c702a42..4936f9e 100644 --- a/README.md +++ b/README.md @@ -52,3 +52,4 @@ Cost estimates: see [Phase 2L API guide](docs/costing-api.md). 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). diff --git a/docs/material-warehouse-stock-api.md b/docs/material-warehouse-stock-api.md index bc9880e..d809a29 100644 --- a/docs/material-warehouse-stock-api.md +++ b/docs/material-warehouse-stock-api.md @@ -12,4 +12,4 @@ Raw-material balances are tracked per organization, material and warehouse. Use POST body: `{ "warehouseId": "", "idempotencyKey": "" }`. A receipt can be posted once. A retry with the same key and warehouse returns the original posting; a changed retry returns `MATERIAL_RECEIPT_REPLAY_CONFLICT`. Posting again with a different key returns `MATERIAL_RECEIPT_ALREADY_POSTED`. The response lists one ledger entry for each line with a positive accepted quantity. A fully rejected receipt can be posted with no entries. -Balances and ledger deltas use each material's native unit and three decimal places. Posting is atomic: either all accepted lines reach the selected warehouse or none do. PostgreSQL checks that ledger entries match the receipt's QC decisions and updates balances in the same transaction. The ledger and receipt posting are append-only. Production and packaging consumption, manual adjustments, inter-warehouse transfers and finished-goods output are later stock milestones. +Balances and ledger deltas use each material's native unit and three decimal places. Posting is atomic: either all accepted lines reach the selected warehouse or none do. PostgreSQL checks that ledger entries match the receipt's QC decisions and updates balances in the same transaction. The ledger and receipt posting are append-only. Production and packaging consumption are documented separately. Manual adjustments, inter-warehouse transfers and finished-goods output are later stock milestones. diff --git a/docs/packaging-material-stock-api.md b/docs/packaging-material-stock-api.md new file mode 100644 index 0000000..d0c48a8 --- /dev/null +++ b/docs/packaging-material-stock-api.md @@ -0,0 +1,12 @@ +# Packaging material stock (Phase 2P) + +An operator can post an immutable packaging record's used and wasted material quantities to one warehouse. Each positive quantity becomes a separate negative material-stock ledger entry. Zero quantities create no entry. Packaging records do not change stock until explicitly posted. + +| Method | Path | Permission | +| ------ | ------------------------------------------------------------- | ------------------ | +| GET | `/api/v1/production-batches/:batchId/packaging-stock-posting` | `inventory.read` | +| POST | `/api/v1/production-batches/:batchId/packaging-stock-posting` | `inventory.manage` | + +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. diff --git a/docs/production-material-stock-api.md b/docs/production-material-stock-api.md index dad10a3..45c63b9 100644 --- a/docs/production-material-stock-api.md +++ b/docs/production-material-stock-api.md @@ -1,6 +1,6 @@ # Production material stock (Phase 2O) -After a production batch is completed and usage has been recorded for every production BOM line, post its consumed and wasted material to one selected warehouse. Both quantities reduce on-hand stock in each material's native unit. Packaging consumption and finished-goods receipts are separate future milestones. +After a production batch is completed and usage has been recorded for every production BOM line, post its consumed and wasted material to one selected warehouse. Both quantities reduce on-hand stock in each material's native unit. Packaging consumption is documented separately; finished-goods receipts are a later milestone. | Method | Path | Permission | | ------ | ------------------------------------------------------------ | ------------------ | diff --git a/docs/roadmap.md b/docs/roadmap.md index 43089c7..a48dd7c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,6 +29,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase - 2M (implemented): immutable completed-batch standard-cost snapshots from actual material and packaging use, frozen rate revisions, and exact totals. Physical stock posting remains dependent on the stock-location policy. - 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. ## Phase 3: B2B and white label diff --git a/prisma/inventory.prisma b/prisma/inventory.prisma index 7361a2e..7f4e632 100644 --- a/prisma/inventory.prisma +++ b/prisma/inventory.prisma @@ -12,6 +12,7 @@ model Warehouse { materialItems MaterialStockItem[] materialReceiptPostings MaterialReceiptPosting[] productionStockPostings ProductionStockPosting[] + packagingStockPostings PackagingStockPosting[] @@unique([organizationId, name]) @@unique([id, organizationId]) @@map("warehouses") diff --git a/prisma/material-stock.prisma b/prisma/material-stock.prisma index 596d302..a6e2405 100644 --- a/prisma/material-stock.prisma +++ b/prisma/material-stock.prisma @@ -2,6 +2,8 @@ enum MaterialStockKind { RECEIPT_ACCEPTED PRODUCTION_CONSUMED PRODUCTION_WASTED + PACKAGING_USED + PACKAGING_WASTED } model MaterialStockItem { @@ -60,6 +62,26 @@ model ProductionStockPosting { @@map("production_stock_postings") } +model PackagingStockPosting { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + runId String @unique @map("run_id") @db.Uuid + warehouseId String @map("warehouse_id") @db.Uuid + postedById String @map("posted_by_id") @db.Uuid + 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) + run PackagingRun @relation(fields: [runId, organizationId], references: [id, organizationId], onDelete: Restrict) + warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict) + postedBy User @relation(fields: [postedById, organizationId], references: [id, organizationId], onDelete: Restrict) + entries MaterialStockLedger[] + @@unique([organizationId, idempotencyKey]) + @@unique([runId, organizationId]) + @@unique([id, organizationId]) + @@map("packaging_stock_postings") +} + model MaterialStockLedger { id String @id @default(uuid()) @db.Uuid organizationId String @map("organization_id") @db.Uuid @@ -69,6 +91,8 @@ model MaterialStockLedger { receiptLineId String? @unique @map("receipt_line_id") @db.Uuid productionPostingId String? @map("production_posting_id") @db.Uuid usageEventId String? @unique @map("usage_event_id") @db.Uuid + packagingPostingId String? @map("packaging_posting_id") @db.Uuid + packagingRunLineId String? @map("packaging_run_line_id") @db.Uuid kind MaterialStockKind delta Decimal @db.Decimal(12,3) createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) @@ -77,7 +101,10 @@ model MaterialStockLedger { receiptLine GoodsReceiptLine? @relation(fields: [receiptLineId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_receipt_scope_fkey") productionPosting ProductionStockPosting? @relation(fields: [productionPostingId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_production_scope_fkey") usageEvent ProductionMaterialUsage? @relation(fields: [usageEventId], references: [id], onDelete: Restrict, map: "material_stock_ledger_usage_fkey") + packagingPosting PackagingStockPosting? @relation(fields: [packagingPostingId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_packaging_scope_fkey") + packagingRunLine PackagingRunLine? @relation(fields: [packagingRunLineId], references: [id], onDelete: Restrict, map: "material_stock_ledger_packaging_line_fkey") @@index([organizationId, stockItemId, createdAt, id], map: "material_stock_ledger_item_created_idx") @@unique([receiptLineId, organizationId]) + @@unique([packagingRunLineId, kind]) @@map("material_stock_ledger") } diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index dc8c21c..d2fd1a0 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -28,5 +28,6 @@ "20260929132000_material_cost_rates": "b7a9068407b6caf5f2c226969929c8e435ca37cc4e7fd7632da1140f79f77b0c", "20260929170000_batch_cost_snapshots": "ef59558614f6bfe7fe07a095a4bafef2d3ffdb0ea514dfb1761a02d8d4da0bab", "20260929171600_material_warehouse_stock": "47645ff022037ea486ca82902bdf09ca36ebf05a94500b160dcd57c2d812eab8", - "20260929173800_production_material_stock": "68f5755167f87a646901835be9fe6318a3ae6bb9a3d70d8a722915d1eff3c7a4" + "20260929173800_production_material_stock": "68f5755167f87a646901835be9fe6318a3ae6bb9a3d70d8a722915d1eff3c7a4", + "20260929195800_packaging_material_stock": "2b11c19499d917bcdd53ade20175235ef83cc64cdafda2118ea2dac2096a6f8d" } diff --git a/prisma/migrations/20260929195800_packaging_material_stock/migration.sql b/prisma/migrations/20260929195800_packaging_material_stock/migration.sql new file mode 100644 index 0000000..c552f3e --- /dev/null +++ b/prisma/migrations/20260929195800_packaging_material_stock/migration.sql @@ -0,0 +1,93 @@ +ALTER TABLE "material_stock_ledger" DROP CONSTRAINT "material_stock_ledger_source"; +ALTER TYPE "MaterialStockKind" RENAME TO "MaterialStockKind_old"; +CREATE TYPE "MaterialStockKind" AS ENUM ('RECEIPT_ACCEPTED', 'PRODUCTION_CONSUMED', 'PRODUCTION_WASTED', 'PACKAGING_USED', 'PACKAGING_WASTED'); +ALTER TABLE "material_stock_ledger" ALTER COLUMN "kind" TYPE "MaterialStockKind" USING "kind"::text::"MaterialStockKind"; +DROP TYPE "MaterialStockKind_old"; + +CREATE TABLE "packaging_stock_postings" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "run_id" UUID NOT NULL, + "warehouse_id" UUID NOT NULL, + "posted_by_id" UUID NOT NULL, + "idempotency_key" UUID NOT NULL, + "request_hash" CHAR(64) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "packaging_stock_postings_pkey" PRIMARY KEY ("id"), + CONSTRAINT "packaging_stock_postings_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$') +); +CREATE UNIQUE INDEX "packaging_runs_id_organization_id_key" ON "packaging_runs"("id", "organization_id"); +CREATE UNIQUE INDEX "packaging_stock_postings_run_id_key" ON "packaging_stock_postings"("run_id"); +CREATE UNIQUE INDEX "packaging_stock_postings_run_id_organization_id_key" ON "packaging_stock_postings"("run_id", "organization_id"); +CREATE UNIQUE INDEX "packaging_stock_postings_organization_id_idempotency_key_key" ON "packaging_stock_postings"("organization_id", "idempotency_key"); +CREATE UNIQUE INDEX "packaging_stock_postings_id_organization_id_key" ON "packaging_stock_postings"("id", "organization_id"); +ALTER TABLE "packaging_stock_postings" ADD CONSTRAINT "packaging_stock_postings_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "packaging_stock_postings" ADD CONSTRAINT "packaging_stock_postings_run_id_organization_id_fkey" FOREIGN KEY ("run_id", "organization_id") REFERENCES "packaging_runs"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "packaging_stock_postings" ADD CONSTRAINT "packaging_stock_postings_warehouse_id_organization_id_fkey" FOREIGN KEY ("warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "packaging_stock_postings" ADD CONSTRAINT "packaging_stock_postings_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 "material_stock_ledger" ADD COLUMN "packaging_posting_id" UUID; +ALTER TABLE "material_stock_ledger" ADD COLUMN "packaging_run_line_id" UUID; +CREATE UNIQUE INDEX "material_stock_ledger_packaging_run_line_id_kind_key" ON "material_stock_ledger"("packaging_run_line_id", "kind"); +ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_packaging_scope_fkey" FOREIGN KEY ("packaging_posting_id", "organization_id") REFERENCES "packaging_stock_postings"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_packaging_line_fkey" FOREIGN KEY ("packaging_run_line_id") REFERENCES "packaging_run_lines"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_source" CHECK ( + ("kind" = 'RECEIPT_ACCEPTED' AND "delta" > 0 AND "posting_id" IS NOT NULL AND "receipt_line_id" IS NOT NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL) + OR ("kind" IN ('PRODUCTION_CONSUMED', 'PRODUCTION_WASTED') AND "delta" < 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NOT NULL AND "usage_event_id" IS NOT NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL) + OR ("kind" IN ('PACKAGING_USED', 'PACKAGING_WASTED') AND "delta" < 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NOT NULL AND "packaging_run_line_id" IS NOT NULL) +); + +CREATE FUNCTION guard_packaging_stock_posting() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Packaging stock postings are immutable'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER packaging_stock_postings_guard BEFORE INSERT OR UPDATE OR DELETE ON packaging_stock_postings FOR EACH ROW EXECUTE FUNCTION guard_packaging_stock_posting(); + +CREATE OR REPLACE FUNCTION guard_material_stock_ledger() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material stock ledger is immutable'; END IF; + IF NEW.kind = 'RECEIPT_ACCEPTED' THEN + IF NOT EXISTS ( + SELECT 1 FROM material_receipt_postings p + JOIN goods_receipt_lines l ON l.receipt_id = p.receipt_id AND l.id = NEW.receipt_line_id AND l.organization_id = NEW.organization_id + JOIN purchase_order_lines ol ON ol.id = l.purchase_order_line_id AND ol.organization_id = NEW.organization_id + JOIN receipt_inspections i ON i.receipt_line_id = l.id AND i.organization_id = NEW.organization_id + JOIN material_stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id + WHERE p.id = NEW.posting_id AND p.organization_id = NEW.organization_id + AND s.warehouse_id = p.warehouse_id AND s.material_id = ol.material_id + AND NEW.material_id = ol.material_id AND NEW.delta = i.accepted_quantity + ) THEN RAISE EXCEPTION 'Material receipt stock entry does not match accepted QC'; END IF; + ELSIF NEW.kind IN ('PRODUCTION_CONSUMED', 'PRODUCTION_WASTED') THEN + IF NOT EXISTS ( + SELECT 1 FROM production_stock_postings p + JOIN production_material_usage u ON u.batch_id = p.batch_id AND u.id = NEW.usage_event_id AND u.organization_id = NEW.organization_id + JOIN product_bom_lines bl ON bl.id = u.bom_line_id AND bl.bom_id = u.bom_id AND bl.organization_id = NEW.organization_id + JOIN material_stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id + WHERE p.id = NEW.production_posting_id AND p.organization_id = NEW.organization_id + AND s.warehouse_id = p.warehouse_id AND s.material_id = bl.material_id + AND NEW.material_id = bl.material_id AND NEW.delta = -u.quantity + AND ((NEW.kind = 'PRODUCTION_CONSUMED' AND u.kind = 'CONSUMED') OR (NEW.kind = 'PRODUCTION_WASTED' AND u.kind = 'WASTED')) + ) THEN RAISE EXCEPTION 'Production stock entry does not match material usage'; END IF; + ELSE + IF NOT EXISTS ( + SELECT 1 FROM packaging_stock_postings p + JOIN packaging_runs r ON r.id = p.run_id AND r.organization_id = NEW.organization_id + JOIN packaging_run_lines l ON l.run_id = r.id AND l.id = NEW.packaging_run_line_id AND l.organization_id = NEW.organization_id + JOIN product_bom_lines bl ON bl.id = l.bom_line_id AND bl.bom_id = l.bom_id AND bl.organization_id = NEW.organization_id + JOIN material_stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id + WHERE p.id = NEW.packaging_posting_id AND p.organization_id = NEW.organization_id + AND s.warehouse_id = p.warehouse_id AND s.material_id = bl.material_id + AND NEW.material_id = bl.material_id + AND ((NEW.kind = 'PACKAGING_USED' AND NEW.delta = -l.used_quantity AND l.used_quantity > 0) + OR (NEW.kind = 'PACKAGING_WASTED' AND NEW.delta = -l.wasted_quantity AND l.wasted_quantity > 0)) + ) THEN RAISE EXCEPTION 'Packaging stock entry does not match recorded use'; END IF; + END IF; + UPDATE material_stock_items SET on_hand = on_hand + NEW.delta + WHERE id = NEW.stock_item_id AND organization_id = NEW.organization_id + AND on_hand + NEW.delta BETWEEN 0 AND 999999999.999; + IF NOT FOUND THEN RAISE EXCEPTION 'Material stock balance outside bounds'; END IF; + RETURN NEW; +END; +$$; diff --git a/prisma/packaging-run.prisma b/prisma/packaging-run.prisma index e198c0c..a82335d 100644 --- a/prisma/packaging-run.prisma +++ b/prisma/packaging-run.prisma @@ -12,8 +12,10 @@ model PackagingRun { bom ProductBom @relation(fields: [bomId, organizationId], references: [id, organizationId], onDelete: Restrict) recordedBy User @relation(fields: [recordedById, organizationId], references: [id, organizationId], onDelete: Restrict) lines PackagingRunLine[] + stockPosting PackagingStockPosting? @@unique([organizationId, idempotencyKey]) @@unique([batchId, organizationId]) + @@unique([id, organizationId]) @@unique([id, bomId, organizationId]) @@index([organizationId, createdAt, id]) @@map("packaging_runs") @@ -30,6 +32,7 @@ model PackagingRunLine { wasteReason String? @map("waste_reason") @db.VarChar(500) run PackagingRun @relation(fields: [runId, bomId, organizationId], references: [id, bomId, organizationId], onDelete: Restrict) bomLine ProductBomLine @relation(fields: [bomLineId, bomId, organizationId], references: [id, bomId, organizationId], onDelete: Restrict) + stockEntries MaterialStockLedger[] @@unique([runId, bomLineId]) @@map("packaging_run_lines") } diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 99c3bee..bb68636 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -47,6 +47,7 @@ model Organization { materialStockItems MaterialStockItem[] materialReceiptPostings MaterialReceiptPosting[] productionStockPostings ProductionStockPosting[] + packagingStockPostings PackagingStockPosting[] @@map("organizations") } model User { @@ -84,6 +85,7 @@ model User { batchCostSnapshots BatchCostSnapshot[] materialReceiptPostings MaterialReceiptPosting[] productionStockPostings ProductionStockPosting[] + packagingStockPostings PackagingStockPosting[] stockEntries StockLedger[] stockReservations StockReservation[] carts Cart[] diff --git a/src/common/errors/commerce-errors.ts b/src/common/errors/commerce-errors.ts index c3e5272..ed2492d 100644 --- a/src/common/errors/commerce-errors.ts +++ b/src/common/errors/commerce-errors.ts @@ -586,4 +586,24 @@ export const COMMERCE_ERRORS = { 'Idempotency key was used for different production stock', 'Production stock idempotency payload mismatch', ], + PACKAGING_STOCK_POSTING_NOT_FOUND: [ + 404, + 'Packaging stock posting not found', + 'Packaging stock posting scoped lookup failed', + ], + PACKAGING_STOCK_INSUFFICIENT: [ + 409, + 'Insufficient packaging material stock in this warehouse', + 'Packaging stock balance check failed', + ], + PACKAGING_STOCK_ALREADY_POSTED: [ + 409, + 'Packaging stock was already posted for this batch', + 'Packaging stock duplicate posting rejected', + ], + PACKAGING_STOCK_REPLAY_CONFLICT: [ + 409, + 'Idempotency key was used for different packaging stock', + 'Packaging stock idempotency payload mismatch', + ], } as const; diff --git a/src/production/material-stock-posting.helpers.ts b/src/production/material-stock-posting.helpers.ts new file mode 100644 index 0000000..173672e --- /dev/null +++ b/src/production/material-stock-posting.helpers.ts @@ -0,0 +1,35 @@ +import { createHash } from 'node:crypto'; +import { AppError } from '../common/errors/app-error'; +import type { ErrorCode } from '../common/errors/error-catalog'; +import { parseMaterialQuantity } from './batch-quantity'; + +export function stockPostingHash(batchId: string, warehouseId: string) { + return createHash('sha256') + .update(JSON.stringify({ batchId, warehouseId })) + .digest('hex'); +} + +export function requireAvailableMaterials< + T extends { materialId: string; onHand: { toFixed(digits: number): string } }, +>( + stock: T[], + quantities: { materialId: string; quantity: string }[], + errorCode: ErrorCode, +) { + const byMaterial = new Map(stock.map((item) => [item.materialId, item])); + const required = new Map(); + for (const line of quantities) { + required.set( + line.materialId, + (required.get(line.materialId) ?? 0n) + + parseMaterialQuantity(line.quantity), + ); + } + for (const [materialId, quantity] of required) { + if (quantity === 0n) continue; + const item = byMaterial.get(materialId); + if (!item || parseMaterialQuantity(item.onHand.toFixed(3)) < quantity) + throw new AppError(errorCode); + } + return byMaterial; +} diff --git a/src/production/material-stock-posting.schemas.ts b/src/production/material-stock-posting.schemas.ts new file mode 100644 index 0000000..6dbb231 --- /dev/null +++ b/src/production/material-stock-posting.schemas.ts @@ -0,0 +1,8 @@ +import { z } from 'zod'; + +export const materialStockPostingSchema = z + .object({ warehouseId: z.uuid(), idempotencyKey: z.uuid() }) + .strict(); +export type MaterialStockPostingInput = z.infer< + typeof materialStockPostingSchema +>; diff --git a/src/production/packaging-stock-posting.controller.ts b/src/production/packaging-stock-posting.controller.ts new file mode 100644 index 0000000..378072d --- /dev/null +++ b/src/production/packaging-stock-posting.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 { PackagingStockPostingStore } from './packaging-stock-posting.store'; + +@Controller('production-batches/:batchId/packaging-stock-posting') +export class PackagingStockPostingController { + constructor(private readonly postings: PackagingStockPostingStore) {} + + @Get() + @RequirePermission('inventory.read') + find( + @CurrentPrincipal() actor: Principal, + @Param('batchId', ParseUUIDPipe) batchId: string, + ) { + return this.postings.find(actor, batchId); + } + + @Post() + @RequirePermission('inventory.manage') + create( + @CurrentPrincipal() actor: Principal, + @Param('batchId', ParseUUIDPipe) batchId: string, + @Body(new SchemaPipe(materialStockPostingSchema)) + input: MaterialStockPostingInput, + ) { + return this.postings.create(actor, batchId, input); + } +} diff --git a/src/production/packaging-stock-posting.store.ts b/src/production/packaging-stock-posting.store.ts new file mode 100644 index 0000000..854eb9a --- /dev/null +++ b/src/production/packaging-stock-posting.store.ts @@ -0,0 +1,168 @@ +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 { + formatMaterialQuantity, + parseMaterialQuantity, +} from './batch-quantity'; +import { + requireAvailableMaterials, + stockPostingHash, +} from './material-stock-posting.helpers'; +import type { MaterialStockPostingInput } from './material-stock-posting.schemas'; + +const postingView = { + run: { select: { batchId: true } }, + entries: { + orderBy: [{ packagingRunLineId: 'asc' as const }, { kind: 'asc' as const }], + }, +}; +type Posting = Prisma.PackagingStockPostingGetPayload<{ + include: typeof postingView; +}>; +function present(posting: Posting) { + return { + id: posting.id, + batchId: posting.run.batchId, + runId: posting.runId, + warehouseId: posting.warehouseId, + postedById: posting.postedById, + createdAt: posting.createdAt, + entries: posting.entries.map((entry) => ({ + id: entry.id, + stockItemId: entry.stockItemId, + materialId: entry.materialId, + packagingRunLineId: entry.packagingRunLineId, + kind: entry.kind, + delta: entry.delta.toFixed(3), + })), + }; +} + +@Injectable() +export class PackagingStockPostingStore { + constructor( + private readonly db: DatabaseService, + private readonly access: AccessStore, + ) {} + + async find(actor: Principal, batchId: string) { + const posting = await this.db.packagingStockPosting.findFirst({ + where: { organizationId: actor.organizationId, run: { batchId } }, + include: postingView, + }); + if (!posting) throw new AppError('PACKAGING_STOCK_POSTING_NOT_FOUND'); + return present(posting); + } + + 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.packagingStockPosting.findFirst({ + where: { + organizationId: actor.organizationId, + idempotencyKey: input.idempotencyKey, + }, + include: postingView, + }); + if (prior) { + if (prior.requestHash !== hash) + throw new AppError('PACKAGING_STOCK_REPLAY_CONFLICT'); + return present(prior); + } + const batch = await tx.productionBatch.findFirst({ + where: { id: batchId, organizationId: actor.organizationId }, + select: { id: true }, + }); + if (!batch) throw new AppError('BATCH_NOT_FOUND'); + const run = await tx.packagingRun.findFirst({ + where: { batchId, organizationId: actor.organizationId }, + include: { + lines: { include: { bomLine: true }, orderBy: { id: 'asc' } }, + }, + }); + if (!run) throw new AppError('PACKAGING_RUN_NOT_FOUND'); + if ( + await tx.packagingStockPosting.findUnique({ + where: { runId: run.id }, + select: { id: true }, + }) + ) + throw new AppError('PACKAGING_STOCK_ALREADY_POSTED'); + 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 stock = await tx.materialStockItem.findMany({ + where: { + organizationId: actor.organizationId, + warehouseId: warehouse.id, + materialId: { in: run.lines.map((line) => line.bomLine.materialId) }, + }, + }); + const byMaterial = requireAvailableMaterials( + stock, + run.lines.flatMap((line) => [ + { + materialId: line.bomLine.materialId, + quantity: line.usedQuantity.toFixed(3), + }, + { + materialId: line.bomLine.materialId, + quantity: line.wastedQuantity.toFixed(3), + }, + ]), + 'PACKAGING_STOCK_INSUFFICIENT', + ); + const posting = await tx.packagingStockPosting.create({ + data: { + organizationId: actor.organizationId, + runId: run.id, + warehouseId: warehouse.id, + postedById: actor.userId, + idempotencyKey: input.idempotencyKey, + requestHash: hash, + }, + }); + for (const line of run.lines) { + for (const [kind, quantity] of [ + ['PACKAGING_USED', line.usedQuantity.toFixed(3)], + ['PACKAGING_WASTED', line.wastedQuantity.toFixed(3)], + ] as const) { + const scaled = parseMaterialQuantity(quantity); + if (scaled === 0n) continue; + const materialId = line.bomLine.materialId; + await tx.materialStockLedger.create({ + data: { + organizationId: actor.organizationId, + stockItemId: byMaterial.get(materialId)!.id, + materialId, + packagingPostingId: posting.id, + packagingRunLineId: line.id, + kind, + delta: formatMaterialQuantity(-scaled), + }, + }); + } + } + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'batch.packaging_stock_posted', + posting.id, + ); + return present( + await tx.packagingStockPosting.findUniqueOrThrow({ + where: { id: posting.id }, + include: postingView, + }), + ); + }); + } +} diff --git a/src/production/production-stock-posting.controller.ts b/src/production/production-stock-posting.controller.ts index 140970f..740f5ed 100644 --- a/src/production/production-stock-posting.controller.ts +++ b/src/production/production-stock-posting.controller.ts @@ -13,9 +13,9 @@ import { } from '../identity/access.decorator'; import type { Principal } from '../identity/identity.types'; import { - productionStockPostingSchema, - type ProductionStockPostingInput, -} from './production-stock-posting.schemas'; + materialStockPostingSchema, + type MaterialStockPostingInput, +} from './material-stock-posting.schemas'; import { ProductionStockPostingStore } from './production-stock-posting.store'; @Controller('production-batches/:batchId/material-stock-posting') @@ -36,8 +36,8 @@ export class ProductionStockPostingController { create( @CurrentPrincipal() actor: Principal, @Param('batchId', ParseUUIDPipe) batchId: string, - @Body(new SchemaPipe(productionStockPostingSchema)) - input: ProductionStockPostingInput, + @Body(new SchemaPipe(materialStockPostingSchema)) + input: MaterialStockPostingInput, ) { return this.postings.create(actor, batchId, input); } diff --git a/src/production/production-stock-posting.schemas.ts b/src/production/production-stock-posting.schemas.ts deleted file mode 100644 index 9d00bce..0000000 --- a/src/production/production-stock-posting.schemas.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { z } from 'zod'; - -export const productionStockPostingSchema = z - .object({ - warehouseId: z.uuid(), - idempotencyKey: z.uuid(), - }) - .strict(); -export type ProductionStockPostingInput = z.infer< - typeof productionStockPostingSchema ->; diff --git a/src/production/production-stock-posting.store.ts b/src/production/production-stock-posting.store.ts index 89ec0bc..beb2c36 100644 --- a/src/production/production-stock-posting.store.ts +++ b/src/production/production-stock-posting.store.ts @@ -1,4 +1,3 @@ -import { createHash } from 'node:crypto'; import { Injectable } from '@nestjs/common'; import { AppError } from '../common/errors/app-error'; import { DatabaseService } from '../database/database.service'; @@ -10,7 +9,11 @@ import { formatMaterialQuantity, parseMaterialQuantity, } from './batch-quantity'; -import type { ProductionStockPostingInput } from './production-stock-posting.schemas'; +import { + requireAvailableMaterials, + stockPostingHash, +} from './material-stock-posting.helpers'; +import type { MaterialStockPostingInput } from './material-stock-posting.schemas'; const postingView = { entries: { orderBy: { usageEventId: 'asc' as const } } }; type Posting = Prisma.ProductionStockPostingGetPayload<{ @@ -50,15 +53,9 @@ export class ProductionStockPostingStore { return present(posting); } - create( - actor: Principal, - batchId: string, - input: ProductionStockPostingInput, - ) { + create(actor: Principal, batchId: string, input: MaterialStockPostingInput) { return this.access.mutate(actor, 'inventory.manage', async (tx) => { - const hash = createHash('sha256') - .update(JSON.stringify({ batchId, warehouseId: input.warehouseId })) - .digest('hex'); + const hash = stockPostingHash(batchId, input.warehouseId); const prior = await tx.productionStockPosting.findFirst({ where: { organizationId: actor.organizationId, @@ -107,21 +104,14 @@ export class ProductionStockPostingStore { materialId: { in: batch.bom.lines.map((line) => line.materialId) }, }, }); - const byMaterial = new Map(stock.map((item) => [item.materialId, item])); - const needed = new Map(); - for (const usage of batch.materialUsage) { - const materialId = usage.bomLine.materialId; - needed.set( - materialId, - (needed.get(materialId) ?? 0n) + - parseMaterialQuantity(usage.quantity.toFixed(3)), - ); - } - for (const [materialId, quantity] of needed) { - const item = byMaterial.get(materialId); - if (!item || parseMaterialQuantity(item.onHand.toFixed(3)) < quantity) - throw new AppError('PRODUCTION_STOCK_INSUFFICIENT'); - } + const byMaterial = requireAvailableMaterials( + stock, + batch.materialUsage.map((usage) => ({ + materialId: usage.bomLine.materialId, + quantity: usage.quantity.toFixed(3), + })), + 'PRODUCTION_STOCK_INSUFFICIENT', + ); const posting = await tx.productionStockPosting.create({ data: { organizationId: actor.organizationId, diff --git a/src/production/production.module.ts b/src/production/production.module.ts index 8aec1ce..1853e23 100644 --- a/src/production/production.module.ts +++ b/src/production/production.module.ts @@ -9,6 +9,8 @@ import { PackagingRunController } from './packaging-run.controller'; import { PackagingRunStore } from './packaging-run.store'; import { ProductionStockPostingController } from './production-stock-posting.controller'; import { ProductionStockPostingStore } from './production-stock-posting.store'; +import { PackagingStockPostingController } from './packaging-stock-posting.controller'; +import { PackagingStockPostingStore } from './packaging-stock-posting.store'; @Module({ imports: [DatabaseModule, IdentityModule], @@ -17,12 +19,14 @@ import { ProductionStockPostingStore } from './production-stock-posting.store'; MaterialUsageStore, PackagingRunStore, ProductionStockPostingStore, + PackagingStockPostingStore, ], controllers: [ BatchesController, MaterialUsageController, PackagingRunController, ProductionStockPostingController, + PackagingStockPostingController, ], }) export class ProductionModule {} diff --git a/test/packaging-material-stock.spec.ts b/test/packaging-material-stock.spec.ts new file mode 100644 index 0000000..63fb62e --- /dev/null +++ b/test/packaging-material-stock.spec.ts @@ -0,0 +1,201 @@ +import { randomUUID } from 'node:crypto'; +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { secondActor } from './helpers/commerce'; +import { + completeCostBatch, + packageCostBatch, + prepareCostBatch, + startCostBatch, +} from './helpers/batch-cost'; + +describe('packaging material stock posting', () => { + let ctx: IdentityApp; + const auth = { type: 'bearer' as const }; + const post = (batchId: string, body: object) => + ctx + .api() + .post(`/api/v1/production-batches/${batchId}/packaging-stock-posting`) + .auth(ctx.token, auth) + .send(body); + const get = (batchId: string) => + ctx + .api() + .get(`/api/v1/production-batches/${batchId}/packaging-stock-posting`) + .auth(ctx.token, auth); + const warehouse = async () => + ( + await ctx + .api() + .post('/api/v1/inventory/warehouses') + .auth(ctx.token, auth) + .send({ name: `Packaging ${randomUUID().slice(0, 8)}` }) + .expect(201) + ).body.id as string; + const ready = async (balance = '25.000') => { + const batch = await prepareCostBatch(ctx); + const warehouseId = await warehouse(); + const stock = await ctx.db.materialStockItem.create({ + data: { + organizationId: ctx.owner.organizationId, + warehouseId, + materialId: batch.packagingMaterialId, + onHand: balance, + }, + }); + await startCostBatch(ctx, batch.batchId); + await completeCostBatch(ctx, batch.batchId); + await packageCostBatch( + ctx, + batch.batchId, + batch.packagingBomId, + batch.packagingLineId, + ); + return { ...batch, warehouseId, stockId: stock.id }; + }; + + beforeAll(async () => { + ctx = await identityApp(); + }, 60000); + afterAll(async () => { + await ctx?.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + + it('posts used and wasted packaging quantities once to the selected warehouse', async () => { + const data = await ready(); + const otherWarehouse = await warehouse(); + const otherStock = await ctx.db.materialStockItem.create({ + data: { + organizationId: ctx.owner.organizationId, + warehouseId: otherWarehouse, + materialId: data.packagingMaterialId, + onHand: '12.000', + }, + }); + const body = { + warehouseId: data.warehouseId, + idempotencyKey: randomUUID(), + }; + const result = await post(data.batchId, body).expect(201); + expect( + result.body.entries + .map((entry: { kind: string; delta: string }) => [ + entry.kind, + entry.delta, + ]) + .sort(), + ).toEqual([ + ['PACKAGING_USED', '-19.000'], + ['PACKAGING_WASTED', '-1.000'], + ]); + expect( + ( + await ctx.db.materialStockItem.findUniqueOrThrow({ + where: { id: data.stockId }, + }) + ).onHand.toFixed(3), + ).toBe('5.000'); + expect( + ( + await ctx.db.materialStockItem.findUniqueOrThrow({ + where: { id: otherStock.id }, + }) + ).onHand.toFixed(3), + ).toBe('12.000'); + expect((await post(data.batchId, body).expect(201)).body.id).toBe( + result.body.id, + ); + expect((await get(data.batchId).expect(200)).body.id).toBe(result.body.id); + expect( + await ctx.db.materialStockLedger.count({ + where: { packagingPostingId: result.body.id }, + }), + ).toBe(2); + }); + + it('requires a packaging record and rejects changed retries or duplicate posting', async () => { + const batch = await prepareCostBatch(ctx); + const warehouseId = await warehouse(); + const body = { warehouseId, idempotencyKey: randomUUID() }; + expect((await post(batch.batchId, body).expect(404)).body.code).toBe( + 'PACKAGING_RUN_NOT_FOUND', + ); + const data = await ready(); + const request = { + warehouseId: data.warehouseId, + idempotencyKey: randomUUID(), + }; + await post(data.batchId, request).expect(201); + expect( + (await post(data.batchId, { ...request, warehouseId }).expect(409)).body + .code, + ).toBe('PACKAGING_STOCK_REPLAY_CONFLICT'); + expect( + ( + await post(data.batchId, { + ...request, + idempotencyKey: randomUUID(), + }).expect(409) + ).body.code, + ).toBe('PACKAGING_STOCK_ALREADY_POSTED'); + }); + + it('checks total used plus wasted before any stock is deducted', async () => { + const data = await ready('19.000'); + expect( + ( + await post(data.batchId, { + warehouseId: data.warehouseId, + idempotencyKey: randomUUID(), + }).expect(409) + ).body.code, + ).toBe('PACKAGING_STOCK_INSUFFICIENT'); + expect( + await ctx.db.packagingStockPosting.count({ + where: { run: { batchId: data.batchId } }, + }), + ).toBe(0); + expect( + ( + await ctx.db.materialStockItem.findUniqueOrThrow({ + where: { id: data.stockId }, + }) + ).onHand.toFixed(3), + ).toBe('19.000'); + }); + + it('enforces permission, tenant scope and immutable stock entries', async () => { + const data = await ready(); + const body = { + warehouseId: data.warehouseId, + idempotencyKey: randomUUID(), + }; + const reader = await secondActor(ctx, true, ['inventory.read']); + await ctx + .api() + .post( + `/api/v1/production-batches/${data.batchId}/packaging-stock-posting`, + ) + .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/${data.batchId}/packaging-stock-posting`) + .auth(outsider.token, auth) + .expect(404); + const posted = await post(data.batchId, body).expect(201); + await expect( + ctx.db.materialStockLedger.update({ + where: { id: posted.body.entries[0].id }, + data: { delta: '-2.000' }, + }), + ).rejects.toThrow(); + }); +}); -- 2.40.1