diff --git a/README.md b/README.md index 10eb1fd..6c743e6 100644 --- a/README.md +++ b/README.md @@ -50,3 +50,4 @@ Open http://localhost:3000/api/docs in development to browse and test the API. S Packaging execution: see [Phase 2K API guide](docs/packaging-execution-api.md). 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). diff --git a/docs/material-warehouse-stock-api.md b/docs/material-warehouse-stock-api.md new file mode 100644 index 0000000..bc9880e --- /dev/null +++ b/docs/material-warehouse-stock-api.md @@ -0,0 +1,15 @@ +# Warehouse material stock (Phase 2N) + +Raw-material balances are tracked per organization, material and warehouse. Use the existing `/api/v1/inventory/warehouses` endpoints to create and list warehouses. A goods receipt affects stock only after every line has a QC decision and an operator explicitly posts its accepted quantities to one warehouse. Rejected quantities never enter on-hand stock. + +| Method | Path | Permission | +| ------ | -------------------------------------------------------------------------------- | ------------------ | +| GET | `/api/v1/inventory/material-stock-items?warehouseId=&materialId=&limit=&offset=` | `inventory.read` | +| GET | `/api/v1/inventory/material-stock-items/:id` | `inventory.read` | +| GET | `/api/v1/inventory/material-stock-items/:id/ledger?limit=&offset=` | `inventory.read` | +| GET | `/api/v1/goods-receipts/:receiptId/stock-posting` | `inventory.read` | +| POST | `/api/v1/goods-receipts/:receiptId/stock-posting` | `inventory.manage` | + +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. diff --git a/docs/roadmap.md b/docs/roadmap.md index aed4dd5..44babd7 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -27,6 +27,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase - 2K (implemented): immutable packaging execution for completed batches, with BOM-line reconciliation, quantity variance, and idempotent retries. Physical stock posting and costing remain later milestones. - 2L (implemented): append-only standard material cost rates by currency and live production/packaging BOM cost estimates with exact decimal arithmetic. Batch actual costing and physical stock posting remain later milestones. - 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. ## Phase 3: B2B and white label @@ -46,4 +47,4 @@ Small cohesive files; no duplicated business rules; unit tests for success, fail ## Decisions still needed -Provider accounts; deployment target and PostgreSQL service; tax/invoice and retention rules; stock location model; approval thresholds; Etsy sync direction; launch feature cut. Resolve each before its dependent milestone. +Provider accounts; deployment target and PostgreSQL service; tax/invoice and retention rules; approval thresholds; Etsy sync direction; launch feature cut. Raw-material and finished-goods stock use organization-scoped warehouses, with an explicit warehouse selected for each posting. diff --git a/prisma/inventory.prisma b/prisma/inventory.prisma index b0be7a3..9c92608 100644 --- a/prisma/inventory.prisma +++ b/prisma/inventory.prisma @@ -9,6 +9,8 @@ model Warehouse { name String @db.VarChar(100) organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict) items StockItem[] + materialItems MaterialStockItem[] + materialReceiptPostings MaterialReceiptPosting[] @@unique([organizationId, name]) @@unique([id, organizationId]) @@map("warehouses") diff --git a/prisma/material-stock.prisma b/prisma/material-stock.prisma new file mode 100644 index 0000000..b6b7986 --- /dev/null +++ b/prisma/material-stock.prisma @@ -0,0 +1,57 @@ +enum MaterialStockKind { + RECEIPT_ACCEPTED +} + +model MaterialStockItem { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + materialId String @map("material_id") @db.Uuid + warehouseId String @map("warehouse_id") @db.Uuid + onHand Decimal @default(0) @map("on_hand") @db.Decimal(12,3) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict) + material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict) + warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict) + entries MaterialStockLedger[] + @@unique([materialId, warehouseId]) + @@unique([id, materialId, organizationId]) + @@index([organizationId, warehouseId, materialId], map: "material_stock_items_scope_idx") + @@map("material_stock_items") +} + +model MaterialReceiptPosting { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + receiptId String @unique @map("receipt_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) + receipt GoodsReceipt @relation(fields: [receiptId, 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([receiptId, organizationId]) + @@unique([id, organizationId]) + @@map("material_receipt_postings") +} + +model MaterialStockLedger { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + stockItemId String @map("stock_item_id") @db.Uuid + materialId String @map("material_id") @db.Uuid + postingId String @map("posting_id") @db.Uuid + receiptLineId String @unique @map("receipt_line_id") @db.Uuid + kind MaterialStockKind + delta Decimal @db.Decimal(12,3) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + stockItem MaterialStockItem @relation(fields: [stockItemId, materialId, organizationId], references: [id, materialId, organizationId], onDelete: Restrict, map: "material_stock_ledger_item_scope_fkey") + posting MaterialReceiptPosting @relation(fields: [postingId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_posting_scope_fkey") + receiptLine GoodsReceiptLine @relation(fields: [receiptLineId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_receipt_scope_fkey") + @@index([organizationId, stockItemId, createdAt, id], map: "material_stock_ledger_item_created_idx") + @@unique([receiptLineId, organizationId]) + @@map("material_stock_ledger") +} diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index 990ba3a..3e65ea1 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -26,5 +26,6 @@ "20260928193354_packaging_boms": "1f78a1f42b905ea7d371fadba6180a9f756fc4c360a04b92d58b37ec1dd2bad3", "20260929013000_packaging_execution": "63c0fb096c769478ba9422fb606fd421188abd70eeef1375dd07bef2cbc731c1", "20260929132000_material_cost_rates": "b7a9068407b6caf5f2c226969929c8e435ca37cc4e7fd7632da1140f79f77b0c", - "20260929170000_batch_cost_snapshots": "ef59558614f6bfe7fe07a095a4bafef2d3ffdb0ea514dfb1761a02d8d4da0bab" + "20260929170000_batch_cost_snapshots": "ef59558614f6bfe7fe07a095a4bafef2d3ffdb0ea514dfb1761a02d8d4da0bab", + "20260929171600_material_warehouse_stock": "47645ff022037ea486ca82902bdf09ca36ebf05a94500b160dcd57c2d812eab8" } diff --git a/prisma/migrations/20260929171600_material_warehouse_stock/migration.sql b/prisma/migrations/20260929171600_material_warehouse_stock/migration.sql new file mode 100644 index 0000000..78873e3 --- /dev/null +++ b/prisma/migrations/20260929171600_material_warehouse_stock/migration.sql @@ -0,0 +1,95 @@ +CREATE TYPE "MaterialStockKind" AS ENUM ('RECEIPT_ACCEPTED'); +CREATE UNIQUE INDEX "goods_receipts_id_organization_id_key" ON "goods_receipts"("id", "organization_id"); + +CREATE TABLE "material_stock_items" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "material_id" UUID NOT NULL, + "warehouse_id" UUID NOT NULL, + "on_hand" DECIMAL(12,3) NOT NULL DEFAULT 0, + CONSTRAINT "material_stock_items_pkey" PRIMARY KEY ("id"), + CONSTRAINT "material_stock_items_balance" CHECK ("on_hand" BETWEEN 0 AND 999999999.999) +); +CREATE UNIQUE INDEX "material_stock_items_material_id_warehouse_id_key" ON "material_stock_items"("material_id", "warehouse_id"); +CREATE UNIQUE INDEX "material_stock_items_id_material_id_organization_id_key" ON "material_stock_items"("id", "material_id", "organization_id"); +CREATE INDEX "material_stock_items_scope_idx" ON "material_stock_items"("organization_id", "warehouse_id", "material_id"); +ALTER TABLE "material_stock_items" ADD CONSTRAINT "material_stock_items_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "material_stock_items" ADD CONSTRAINT "material_stock_items_material_id_organization_id_fkey" FOREIGN KEY ("material_id", "organization_id") REFERENCES "materials"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "material_stock_items" ADD CONSTRAINT "material_stock_items_warehouse_id_organization_id_fkey" FOREIGN KEY ("warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE TABLE "material_receipt_postings" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "receipt_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 "material_receipt_postings_pkey" PRIMARY KEY ("id"), + CONSTRAINT "material_receipt_postings_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$') +); +CREATE UNIQUE INDEX "material_receipt_postings_receipt_id_key" ON "material_receipt_postings"("receipt_id"); +CREATE UNIQUE INDEX "material_receipt_postings_receipt_id_organization_id_key" ON "material_receipt_postings"("receipt_id", "organization_id"); +CREATE UNIQUE INDEX "material_receipt_postings_organization_id_idempotency_key_key" ON "material_receipt_postings"("organization_id", "idempotency_key"); +CREATE UNIQUE INDEX "material_receipt_postings_id_organization_id_key" ON "material_receipt_postings"("id", "organization_id"); +ALTER TABLE "material_receipt_postings" ADD CONSTRAINT "material_receipt_postings_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "material_receipt_postings" ADD CONSTRAINT "material_receipt_postings_receipt_id_organization_id_fkey" FOREIGN KEY ("receipt_id", "organization_id") REFERENCES "goods_receipts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "material_receipt_postings" ADD CONSTRAINT "material_receipt_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 "material_receipt_postings" ADD CONSTRAINT "material_receipt_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; + +CREATE TABLE "material_stock_ledger" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "stock_item_id" UUID NOT NULL, + "material_id" UUID NOT NULL, + "posting_id" UUID NOT NULL, + "receipt_line_id" UUID NOT NULL, + "kind" "MaterialStockKind" NOT NULL, + "delta" DECIMAL(12,3) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "material_stock_ledger_pkey" PRIMARY KEY ("id"), + CONSTRAINT "material_stock_ledger_quantity" CHECK ("kind" = 'RECEIPT_ACCEPTED' AND "delta" > 0) +); +CREATE UNIQUE INDEX "material_stock_ledger_receipt_line_id_key" ON "material_stock_ledger"("receipt_line_id"); +CREATE UNIQUE INDEX "material_stock_ledger_receipt_line_id_organization_id_key" ON "material_stock_ledger"("receipt_line_id", "organization_id"); +CREATE INDEX "material_stock_ledger_item_created_idx" ON "material_stock_ledger"("organization_id", "stock_item_id", "created_at", "id"); +ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_item_scope_fkey" FOREIGN KEY ("stock_item_id", "material_id", "organization_id") REFERENCES "material_stock_items"("id", "material_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_posting_scope_fkey" FOREIGN KEY ("posting_id", "organization_id") REFERENCES "material_receipt_postings"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_receipt_scope_fkey" FOREIGN KEY ("receipt_line_id", "organization_id") REFERENCES "goods_receipt_lines"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE FUNCTION guard_material_receipt_posting() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material receipt postings are immutable'; END IF; + IF EXISTS ( + SELECT 1 FROM goods_receipt_lines l WHERE l.receipt_id = NEW.receipt_id + AND l.organization_id = NEW.organization_id AND NOT EXISTS ( + SELECT 1 FROM receipt_inspections i WHERE i.receipt_line_id = l.id AND i.organization_id = NEW.organization_id + ) + ) THEN RAISE EXCEPTION 'Receipt requires complete QC before stock posting'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER material_receipt_postings_guard BEFORE INSERT OR UPDATE OR DELETE ON material_receipt_postings FOR EACH ROW EXECUTE FUNCTION guard_material_receipt_posting(); + +CREATE 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 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; + 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 <= 999999999.999; + IF NOT FOUND THEN RAISE EXCEPTION 'Material stock capacity exceeded'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER material_stock_ledger_guard BEFORE INSERT OR UPDATE OR DELETE ON material_stock_ledger FOR EACH ROW EXECUTE FUNCTION guard_material_stock_ledger(); diff --git a/prisma/procurement.prisma b/prisma/procurement.prisma index 0c5fc4d..3a8108d 100644 --- a/prisma/procurement.prisma +++ b/prisma/procurement.prisma @@ -70,6 +70,7 @@ model Material { purchaseOrderLines PurchaseOrderLine[] bomLines ProductBomLine[] costRates MaterialCostRate[] + stockItems MaterialStockItem[] @@unique([organizationId, code]) @@unique([id, organizationId]) @@ -155,7 +156,9 @@ model GoodsReceipt { purchaseOrder PurchaseOrder @relation(fields: [purchaseOrderId, organizationId], references: [id, organizationId], onDelete: Restrict) createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict) lines GoodsReceiptLine[] + stockPosting MaterialReceiptPosting? @@unique([id, purchaseOrderId, organizationId]) + @@unique([id, organizationId]) @@index([organizationId, purchaseOrderId, createdAt, id]) @@map("goods_receipts") } @@ -170,6 +173,7 @@ model GoodsReceiptLine { 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? + stockEntry MaterialStockLedger? @@unique([receiptId, purchaseOrderLineId]) @@unique([id, organizationId]) @@index([organizationId, purchaseOrderLineId]) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 3d6ff44..b9c0f43 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -44,6 +44,8 @@ model Organization { packagingRuns PackagingRun[] materialCostRates MaterialCostRate[] batchCostSnapshots BatchCostSnapshot[] + materialStockItems MaterialStockItem[] + materialReceiptPostings MaterialReceiptPosting[] @@map("organizations") } model User { @@ -79,6 +81,7 @@ model User { packagingRuns PackagingRun[] materialCostRates MaterialCostRate[] batchCostSnapshots BatchCostSnapshot[] + materialReceiptPostings MaterialReceiptPosting[] stockEntries StockLedger[] stockReservations StockReservation[] carts Cart[] diff --git a/src/common/errors/commerce-errors.ts b/src/common/errors/commerce-errors.ts index 00cb5c9..42a8384 100644 --- a/src/common/errors/commerce-errors.ts +++ b/src/common/errors/commerce-errors.ts @@ -526,4 +526,34 @@ export const COMMERCE_ERRORS = { 'Idempotency key was used for different batch costing', 'Batch cost idempotency payload mismatch', ], + MATERIAL_STOCK_NOT_FOUND: [ + 404, + 'Warehouse material stock item not found', + 'Material stock scoped lookup failed', + ], + MATERIAL_POSTING_NOT_FOUND: [ + 404, + 'Receipt stock posting not found', + 'Material receipt posting scoped lookup failed', + ], + MATERIAL_RECEIPT_QC_INCOMPLETE: [ + 409, + 'Inspect every receipt line before posting stock', + 'Material receipt stock QC gate failed', + ], + MATERIAL_RECEIPT_ALREADY_POSTED: [ + 409, + 'Receipt stock was already posted', + 'Material receipt duplicate stock posting rejected', + ], + MATERIAL_RECEIPT_REPLAY_CONFLICT: [ + 409, + 'Idempotency key was used for different receipt stock', + 'Material receipt stock idempotency payload mismatch', + ], + MATERIAL_STOCK_CAPACITY: [ + 409, + 'Warehouse material stock capacity exceeded', + 'Material stock balance overflow', + ], } as const; diff --git a/src/inventory/inventory.module.ts b/src/inventory/inventory.module.ts index e78ab12..2d8d476 100644 --- a/src/inventory/inventory.module.ts +++ b/src/inventory/inventory.module.ts @@ -7,6 +7,10 @@ import { ReservationStore } from './reservation.store'; import { ReservationTransitionStore } from './reservation-transition.store'; import { StockController } from './stock.controller'; import { ReservationsController } from './reservations.controller'; +import { MaterialStockController } from './material-stock.controller'; +import { MaterialStockStore } from './material-stock.store'; +import { MaterialReceiptPostingController } from './material-receipt-posting.controller'; +import { MaterialReceiptPostingStore } from './material-receipt-posting.store'; @Module({ imports: [DatabaseModule, IdentityModule], @@ -15,7 +19,14 @@ import { ReservationsController } from './reservations.controller'; AdjustmentStore, ReservationStore, ReservationTransitionStore, + MaterialStockStore, + MaterialReceiptPostingStore, + ], + controllers: [ + StockController, + ReservationsController, + MaterialStockController, + MaterialReceiptPostingController, ], - controllers: [StockController, ReservationsController], }) export class InventoryModule {} diff --git a/src/inventory/material-receipt-posting.controller.ts b/src/inventory/material-receipt-posting.controller.ts new file mode 100644 index 0000000..64eb105 --- /dev/null +++ b/src/inventory/material-receipt-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 { + receiptStockPostingSchema, + type ReceiptStockPostingInput, +} from './material-stock.schemas'; +import { MaterialReceiptPostingStore } from './material-receipt-posting.store'; + +@Controller('goods-receipts/:receiptId/stock-posting') +export class MaterialReceiptPostingController { + constructor(private readonly postings: MaterialReceiptPostingStore) {} + + @Get() + @RequirePermission('inventory.read') + find( + @CurrentPrincipal() actor: Principal, + @Param('receiptId', ParseUUIDPipe) receiptId: string, + ) { + return this.postings.find(actor, receiptId); + } + + @Post() + @RequirePermission('inventory.manage') + create( + @CurrentPrincipal() actor: Principal, + @Param('receiptId', ParseUUIDPipe) receiptId: string, + @Body(new SchemaPipe(receiptStockPostingSchema)) + input: ReceiptStockPostingInput, + ) { + return this.postings.create(actor, receiptId, input); + } +} diff --git a/src/inventory/material-receipt-posting.store.ts b/src/inventory/material-receipt-posting.store.ts new file mode 100644 index 0000000..6b6b87d --- /dev/null +++ b/src/inventory/material-receipt-posting.store.ts @@ -0,0 +1,156 @@ +import { createHash } from 'node:crypto'; +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 { parseMaterialQuantity } from '../production/batch-quantity'; +import type { ReceiptStockPostingInput } from './material-stock.schemas'; + +const MAX_BALANCE = 999999999999n; +const postingView = { entries: { orderBy: { receiptLineId: 'asc' as const } } }; +type Posting = Prisma.MaterialReceiptPostingGetPayload<{ + include: typeof postingView; +}>; +function present(posting: Posting) { + return { + id: posting.id, + receiptId: posting.receiptId, + warehouseId: posting.warehouseId, + postedById: posting.postedById, + createdAt: posting.createdAt, + entries: posting.entries.map((entry) => ({ + id: entry.id, + stockItemId: entry.stockItemId, + materialId: entry.materialId, + receiptLineId: entry.receiptLineId, + kind: entry.kind, + delta: entry.delta.toFixed(3), + })), + }; +} + +@Injectable() +export class MaterialReceiptPostingStore { + constructor( + private readonly db: DatabaseService, + private readonly access: AccessStore, + ) {} + + async find(actor: Principal, receiptId: string) { + const posting = await this.db.materialReceiptPosting.findFirst({ + where: { receiptId, organizationId: actor.organizationId }, + include: postingView, + }); + if (!posting) throw new AppError('MATERIAL_POSTING_NOT_FOUND'); + return present(posting); + } + + create(actor: Principal, receiptId: string, input: ReceiptStockPostingInput) { + return this.access.mutate(actor, 'inventory.manage', async (tx) => { + const hash = createHash('sha256') + .update( + JSON.stringify({ + receiptId, + warehouseId: input.warehouseId, + }), + ) + .digest('hex'); + const prior = await tx.materialReceiptPosting.findFirst({ + where: { + organizationId: actor.organizationId, + idempotencyKey: input.idempotencyKey, + }, + include: postingView, + }); + if (prior) { + if (prior.requestHash !== hash) + throw new AppError('MATERIAL_RECEIPT_REPLAY_CONFLICT'); + return present(prior); + } + const receipt = await tx.goodsReceipt.findFirst({ + where: { id: receiptId, organizationId: actor.organizationId }, + include: { + lines: { include: { inspection: true, purchaseOrderLine: true } }, + }, + }); + if (!receipt) throw new AppError('RECEIPT_NOT_FOUND'); + if ( + await tx.materialReceiptPosting.findUnique({ + where: { receiptId }, + select: { id: true }, + }) + ) + throw new AppError('MATERIAL_RECEIPT_ALREADY_POSTED'); + if (receipt.lines.some((line) => !line.inspection)) + throw new AppError('MATERIAL_RECEIPT_QC_INCOMPLETE'); + 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 posting = await tx.materialReceiptPosting.create({ + data: { + organizationId: actor.organizationId, + receiptId, + warehouseId: warehouse.id, + postedById: actor.userId, + idempotencyKey: input.idempotencyKey, + requestHash: hash, + }, + }); + for (const line of receipt.lines) { + const accepted = line.inspection!.acceptedQuantity.toFixed(3); + if (accepted === '0.000') continue; + const materialId = line.purchaseOrderLine.materialId; + let stock = await tx.materialStockItem.findFirst({ + where: { + organizationId: actor.organizationId, + warehouseId: warehouse.id, + materialId, + }, + }); + if (!stock) + stock = await tx.materialStockItem.create({ + data: { + organizationId: actor.organizationId, + warehouseId: warehouse.id, + materialId, + }, + }); + if ( + parseMaterialQuantity(stock.onHand.toFixed(3)) + + parseMaterialQuantity(accepted) > + MAX_BALANCE + ) + throw new AppError('MATERIAL_STOCK_CAPACITY'); + await tx.materialStockLedger.create({ + data: { + organizationId: actor.organizationId, + stockItemId: stock.id, + materialId, + postingId: posting.id, + receiptLineId: line.id, + kind: 'RECEIPT_ACCEPTED', + delta: accepted, + }, + }); + } + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'receipt.material_stock_posted', + posting.id, + ); + return present( + await tx.materialReceiptPosting.findUniqueOrThrow({ + where: { id: posting.id }, + include: postingView, + }), + ); + }); + } +} diff --git a/src/inventory/material-stock.controller.ts b/src/inventory/material-stock.controller.ts new file mode 100644 index 0000000..229e1b8 --- /dev/null +++ b/src/inventory/material-stock.controller.ts @@ -0,0 +1,46 @@ +import { Controller, Get, Param, ParseUUIDPipe, Query } from '@nestjs/common'; +import { SchemaPipe } from '../common/validation.pipe'; +import { + CurrentPrincipal, + RequirePermission, +} from '../identity/access.decorator'; +import type { Principal } from '../identity/identity.types'; +import { pageSchema, type PageInput } from '../identity/identity.schemas'; +import { + materialStockQuery, + type MaterialStockQuery, +} from './material-stock.schemas'; +import { MaterialStockStore } from './material-stock.store'; + +@Controller('inventory/material-stock-items') +export class MaterialStockController { + constructor(private readonly stock: MaterialStockStore) {} + + @Get() + @RequirePermission('inventory.read') + list( + @CurrentPrincipal() actor: Principal, + @Query(new SchemaPipe(materialStockQuery)) query: MaterialStockQuery, + ) { + return this.stock.list(actor, query); + } + + @Get(':id') + @RequirePermission('inventory.read') + find( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + ) { + return this.stock.find(actor, id); + } + + @Get(':id/ledger') + @RequirePermission('inventory.read') + ledger( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + @Query(new SchemaPipe(pageSchema)) page: PageInput, + ) { + return this.stock.ledger(actor, id, page); + } +} diff --git a/src/inventory/material-stock.schemas.ts b/src/inventory/material-stock.schemas.ts new file mode 100644 index 0000000..261ae28 --- /dev/null +++ b/src/inventory/material-stock.schemas.ts @@ -0,0 +1,19 @@ +import { z } from 'zod'; +import { pageSchema } from '../identity/identity.schemas'; + +export const materialStockQuery = pageSchema + .extend({ + warehouseId: z.uuid().optional(), + materialId: z.uuid().optional(), + }) + .strict(); +export const receiptStockPostingSchema = z + .object({ + warehouseId: z.uuid(), + idempotencyKey: z.uuid(), + }) + .strict(); +export type MaterialStockQuery = z.infer; +export type ReceiptStockPostingInput = z.infer< + typeof receiptStockPostingSchema +>; diff --git a/src/inventory/material-stock.store.ts b/src/inventory/material-stock.store.ts new file mode 100644 index 0000000..e15349e --- /dev/null +++ b/src/inventory/material-stock.store.ts @@ -0,0 +1,56 @@ +import { Injectable } from '@nestjs/common'; +import { AppError } from '../common/errors/app-error'; +import { DatabaseService } from '../database/database.service'; +import type { Principal } from '../identity/identity.types'; +import type { PageInput } from '../identity/identity.schemas'; +import type { MaterialStockQuery } from './material-stock.schemas'; + +const itemView = { material: true, warehouse: true }; +function present( + item: T, +) { + return { ...item, onHand: item.onHand.toFixed(3) }; +} + +@Injectable() +export class MaterialStockStore { + constructor(private readonly db: DatabaseService) {} + + async list(actor: Principal, query: MaterialStockQuery) { + const items = await this.db.materialStockItem.findMany({ + where: { + organizationId: actor.organizationId, + ...(query.warehouseId ? { warehouseId: query.warehouseId } : {}), + ...(query.materialId ? { materialId: query.materialId } : {}), + }, + include: itemView, + orderBy: { id: 'asc' }, + take: query.limit, + skip: query.offset, + }); + return items.map(present); + } + + async find(actor: Principal, id: string) { + const item = await this.db.materialStockItem.findFirst({ + where: { id, organizationId: actor.organizationId }, + include: itemView, + }); + if (!item) throw new AppError('MATERIAL_STOCK_NOT_FOUND'); + return present(item); + } + + async ledger(actor: Principal, id: string, page: PageInput) { + await this.find(actor, id); + const entries = await this.db.materialStockLedger.findMany({ + where: { stockItemId: id, organizationId: actor.organizationId }, + orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], + take: page.limit, + skip: page.offset, + }); + return entries.map((entry) => ({ + ...entry, + delta: entry.delta.toFixed(3), + })); + } +} diff --git a/test/material-warehouse-stock.spec.ts b/test/material-warehouse-stock.spec.ts new file mode 100644 index 0000000..55bc270 --- /dev/null +++ b/test/material-warehouse-stock.spec.ts @@ -0,0 +1,186 @@ +import { randomUUID } from 'node:crypto'; +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { secondActor } from './helpers/commerce'; +import { receiveAccepted, seedPurchaseOrder } from './helpers/procurement'; + +describe('warehouse material stock posting', () => { + let ctx: IdentityApp; + const auth = { type: 'bearer' as const }; + const warehouse = async () => + ( + await ctx + .api() + .post('/api/v1/inventory/warehouses') + .auth(ctx.token, auth) + .send({ name: `Materials ${randomUUID().slice(0, 8)}` }) + .expect(201) + ).body.id as string; + const post = (receiptId: string, body: object) => + ctx + .api() + .post(`/api/v1/goods-receipts/${receiptId}/stock-posting`) + .auth(ctx.token, auth) + .send(body); + const listing = (warehouseId: string) => + ctx + .api() + .get(`/api/v1/inventory/material-stock-items?warehouseId=${warehouseId}`) + .auth(ctx.token, auth); + + beforeAll(async () => { + ctx = await identityApp(); + }, 60000); + afterAll(async () => { + await ctx?.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + + it('posts accepted QC into the chosen warehouse and keeps a scoped ledger', async () => { + const order = await seedPurchaseOrder(ctx); + const firstReceipt = await receiveAccepted(ctx, order, '1.000'); + const secondReceipt = await receiveAccepted(ctx, order, '1.000'); + const firstWarehouse = await warehouse(); + const secondWarehouse = await warehouse(); + const body = { warehouseId: firstWarehouse, idempotencyKey: randomUUID() }; + const first = await post(firstReceipt.id, body).expect(201); + expect(first.body.entries).toHaveLength(1); + expect(first.body.entries[0].delta).toBe('1.000'); + const retry = await post(firstReceipt.id, body).expect(201); + expect(retry.body.id).toBe(first.body.id); + await post(secondReceipt.id, { + warehouseId: secondWarehouse, + idempotencyKey: randomUUID(), + }).expect(201); + const stock1 = await listing(firstWarehouse).expect(200); + const stock2 = await listing(secondWarehouse).expect(200); + expect(stock1.body).toHaveLength(1); + expect(stock2.body).toHaveLength(1); + expect(stock1.body[0].onHand).toBe('1.000'); + expect(stock2.body[0].onHand).toBe('1.000'); + const ledger = await ctx + .api() + .get(`/api/v1/inventory/material-stock-items/${stock1.body[0].id}/ledger`) + .auth(ctx.token, auth) + .expect(200); + expect(ledger.body[0]).toMatchObject({ + kind: 'RECEIPT_ACCEPTED', + delta: '1.000', + }); + }); + + it('requires completed QC and posts only accepted material', async () => { + const order = await seedPurchaseOrder(ctx); + const receipt = await ctx + .api() + .post(`/api/v1/purchase-orders/${order.id}/receipts`) + .auth(ctx.token, auth) + .send({ + lines: [{ purchaseOrderLineId: order.lineId, quantity: '1.000' }], + }) + .expect(201); + const warehouseId = await warehouse(); + const body = { warehouseId, idempotencyKey: randomUUID() }; + const pending = await post(receipt.body.id, body).expect(409); + expect(pending.body.code).toBe('MATERIAL_RECEIPT_QC_INCOMPLETE'); + await ctx + .api() + .post(`/api/v1/goods-receipts/${receipt.body.id}/inspect`) + .auth(ctx.token, auth) + .send({ + lines: [ + { + receiptLineId: receipt.body.lines[0].id, + acceptedQuantity: '0.750', + rejectedQuantity: '0.250', + rejectionReason: 'Damaged', + }, + ], + }) + .expect(201); + await post(receipt.body.id, body).expect(201); + const stock = await listing(warehouseId).expect(200); + expect(stock.body[0].onHand).toBe('0.750'); + }); + + it('rejects changed retries, duplicate receipt posting and capacity overflow', async () => { + const order = await seedPurchaseOrder(ctx); + const receipt = await receiveAccepted(ctx, order, '1.000'); + const warehouseId = await warehouse(); + const body = { warehouseId, idempotencyKey: randomUUID() }; + await post(receipt.id, body).expect(201); + const changed = await post(receipt.id, { + ...body, + warehouseId: await warehouse(), + }).expect(409); + expect(changed.body.code).toBe('MATERIAL_RECEIPT_REPLAY_CONFLICT'); + const duplicate = await post(receipt.id, { + warehouseId, + idempotencyKey: randomUUID(), + }).expect(409); + expect(duplicate.body.code).toBe('MATERIAL_RECEIPT_ALREADY_POSTED'); + const next = await receiveAccepted(ctx, order, '1.000'); + const stock = (await listing(warehouseId).expect(200)).body[0]; + await ctx.db.materialStockItem.update({ + where: { id: stock.id }, + data: { onHand: '999999999.500' }, + }); + const capacity = await post(next.id, { + warehouseId, + idempotencyKey: randomUUID(), + }).expect(409); + expect(capacity.body.code).toBe('MATERIAL_STOCK_CAPACITY'); + expect( + await ctx.db.materialReceiptPosting.count({ + where: { receiptId: next.id }, + }), + ).toBe(0); + }); + + it('enforces posting permission and hides another organization', async () => { + const order = await seedPurchaseOrder(ctx); + const receipt = await receiveAccepted(ctx, order, '1.000'); + const warehouseId = await warehouse(); + const reader = await secondActor(ctx, true, ['inventory.read']); + await ctx + .api() + .post(`/api/v1/goods-receipts/${receipt.id}/stock-posting`) + .auth(reader.token, auth) + .send({ warehouseId, idempotencyKey: randomUUID() }) + .expect(403); + await post(receipt.id, { + warehouseId, + idempotencyKey: randomUUID(), + }).expect(201); + const outsider = await secondActor(ctx, false, [ + 'inventory.read', + 'inventory.manage', + ]); + await ctx + .api() + .get(`/api/v1/goods-receipts/${receipt.id}/stock-posting`) + .auth(outsider.token, auth) + .expect(404); + await ctx + .api() + .get(`/api/v1/inventory/material-stock-items?warehouseId=${warehouseId}`) + .auth(outsider.token, auth) + .expect(200, []); + }); + + it('keeps stock ledger entries immutable in PostgreSQL', async () => { + const order = await seedPurchaseOrder(ctx); + const receipt = await receiveAccepted(ctx, order, '1.000'); + const posting = await post(receipt.id, { + warehouseId: await warehouse(), + idempotencyKey: randomUUID(), + }).expect(201); + await expect( + ctx.db.materialStockLedger.update({ + where: { id: posting.body.entries[0].id }, + data: { delta: '2.000' }, + }), + ).rejects.toThrow(); + }); +});