feat(production): post material usage to warehouse stock #21
|
|
@ -51,3 +51,4 @@ Packaging execution: see [Phase 2K API guide](docs/packaging-execution-api.md).
|
||||||
Cost estimates: see [Phase 2L API guide](docs/costing-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).
|
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).
|
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).
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
| Method | Path | Permission |
|
||||||
|
| ------ | ------------------------------------------------------------ | ------------------ |
|
||||||
|
| GET | `/api/v1/production-batches/:batchId/material-stock-posting` | `inventory.read` |
|
||||||
|
| POST | `/api/v1/production-batches/:batchId/material-stock-posting` | `inventory.manage` |
|
||||||
|
|
||||||
|
POST body: `{ "warehouseId": "<uuid>", "idempotencyKey": "<uuid>" }`. The posting returns one negative ledger entry per recorded production material usage event. A batch can be posted only once. Repeating the same key and request returns the original posting; changing the warehouse with that key returns `PRODUCTION_STOCK_REPLAY_CONFLICT`. A new key for an already posted batch returns `PRODUCTION_STOCK_ALREADY_POSTED`.
|
||||||
|
|
||||||
|
The requested warehouse must contain enough of every material for the batch's **total** consumed plus wasted quantity. Otherwise `PRODUCTION_STOCK_INSUFFICIENT` is returned and neither the posting nor any ledger entry is committed. Posting, ledger entries and balance changes share one database transaction. PostgreSQL independently checks the batch state, the usage event and material/warehouse relationship, exact signed quantity, and nonnegative balance. Posting headers and ledger entries cannot be edited or deleted.
|
||||||
|
|
@ -28,6 +28,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase
|
||||||
- 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.
|
- 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.
|
- 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.
|
- 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.
|
||||||
|
|
||||||
## Phase 3: B2B and white label
|
## Phase 3: B2B and white label
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ model Warehouse {
|
||||||
items StockItem[]
|
items StockItem[]
|
||||||
materialItems MaterialStockItem[]
|
materialItems MaterialStockItem[]
|
||||||
materialReceiptPostings MaterialReceiptPosting[]
|
materialReceiptPostings MaterialReceiptPosting[]
|
||||||
|
productionStockPostings ProductionStockPosting[]
|
||||||
@@unique([organizationId, name])
|
@@unique([organizationId, name])
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
@@map("warehouses")
|
@@map("warehouses")
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
enum MaterialStockKind {
|
enum MaterialStockKind {
|
||||||
RECEIPT_ACCEPTED
|
RECEIPT_ACCEPTED
|
||||||
|
PRODUCTION_CONSUMED
|
||||||
|
PRODUCTION_WASTED
|
||||||
}
|
}
|
||||||
|
|
||||||
model MaterialStockItem {
|
model MaterialStockItem {
|
||||||
|
|
@ -38,19 +40,43 @@ model MaterialReceiptPosting {
|
||||||
@@map("material_receipt_postings")
|
@@map("material_receipt_postings")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model ProductionStockPosting {
|
||||||
|
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
|
||||||
|
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)
|
||||||
|
batch ProductionBatch @relation(fields: [batchId, 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([batchId, organizationId])
|
||||||
|
@@unique([id, organizationId])
|
||||||
|
@@map("production_stock_postings")
|
||||||
|
}
|
||||||
|
|
||||||
model MaterialStockLedger {
|
model MaterialStockLedger {
|
||||||
id String @id @default(uuid()) @db.Uuid
|
id String @id @default(uuid()) @db.Uuid
|
||||||
organizationId String @map("organization_id") @db.Uuid
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
stockItemId String @map("stock_item_id") @db.Uuid
|
stockItemId String @map("stock_item_id") @db.Uuid
|
||||||
materialId String @map("material_id") @db.Uuid
|
materialId String @map("material_id") @db.Uuid
|
||||||
postingId String @map("posting_id") @db.Uuid
|
postingId String? @map("posting_id") @db.Uuid
|
||||||
receiptLineId String @unique @map("receipt_line_id") @db.Uuid
|
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
|
||||||
kind MaterialStockKind
|
kind MaterialStockKind
|
||||||
delta Decimal @db.Decimal(12,3)
|
delta Decimal @db.Decimal(12,3)
|
||||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(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")
|
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")
|
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")
|
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")
|
||||||
@@index([organizationId, stockItemId, createdAt, id], map: "material_stock_ledger_item_created_idx")
|
@@index([organizationId, stockItemId, createdAt, id], map: "material_stock_ledger_item_created_idx")
|
||||||
@@unique([receiptLineId, organizationId])
|
@@unique([receiptLineId, organizationId])
|
||||||
@@map("material_stock_ledger")
|
@@map("material_stock_ledger")
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,7 @@ model ProductionMaterialUsage {
|
||||||
batch ProductionBatch @relation(fields: [batchId, bomId, organizationId], references: [id, bomId, organizationId], onDelete: Restrict, map: "production_material_usage_batch_scope_fkey")
|
batch ProductionBatch @relation(fields: [batchId, bomId, organizationId], references: [id, bomId, organizationId], onDelete: Restrict, map: "production_material_usage_batch_scope_fkey")
|
||||||
bomLine ProductBomLine @relation(fields: [bomLineId, bomId, organizationId], references: [id, bomId, organizationId], onDelete: Restrict, map: "production_material_usage_line_scope_fkey")
|
bomLine ProductBomLine @relation(fields: [bomLineId, bomId, organizationId], references: [id, bomId, organizationId], onDelete: Restrict, map: "production_material_usage_line_scope_fkey")
|
||||||
recordedBy User @relation(fields: [recordedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "production_material_usage_actor_scope_fkey")
|
recordedBy User @relation(fields: [recordedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "production_material_usage_actor_scope_fkey")
|
||||||
|
stockEntry MaterialStockLedger?
|
||||||
@@unique([organizationId, idempotencyKey], map: "production_material_usage_idempotency_key")
|
@@unique([organizationId, idempotencyKey], map: "production_material_usage_idempotency_key")
|
||||||
@@index([organizationId, batchId, createdAt, id], map: "production_material_usage_batch_created_idx")
|
@@index([organizationId, batchId, createdAt, id], map: "production_material_usage_batch_created_idx")
|
||||||
@@map("production_material_usage")
|
@@map("production_material_usage")
|
||||||
|
|
|
||||||
|
|
@ -27,5 +27,6 @@
|
||||||
"20260929013000_packaging_execution": "63c0fb096c769478ba9422fb606fd421188abd70eeef1375dd07bef2cbc731c1",
|
"20260929013000_packaging_execution": "63c0fb096c769478ba9422fb606fd421188abd70eeef1375dd07bef2cbc731c1",
|
||||||
"20260929132000_material_cost_rates": "b7a9068407b6caf5f2c226969929c8e435ca37cc4e7fd7632da1140f79f77b0c",
|
"20260929132000_material_cost_rates": "b7a9068407b6caf5f2c226969929c8e435ca37cc4e7fd7632da1140f79f77b0c",
|
||||||
"20260929170000_batch_cost_snapshots": "ef59558614f6bfe7fe07a095a4bafef2d3ffdb0ea514dfb1761a02d8d4da0bab",
|
"20260929170000_batch_cost_snapshots": "ef59558614f6bfe7fe07a095a4bafef2d3ffdb0ea514dfb1761a02d8d4da0bab",
|
||||||
"20260929171600_material_warehouse_stock": "47645ff022037ea486ca82902bdf09ca36ebf05a94500b160dcd57c2d812eab8"
|
"20260929171600_material_warehouse_stock": "47645ff022037ea486ca82902bdf09ca36ebf05a94500b160dcd57c2d812eab8",
|
||||||
|
"20260929173800_production_material_stock": "68f5755167f87a646901835be9fe6318a3ae6bb9a3d70d8a722915d1eff3c7a4"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,84 @@
|
||||||
|
ALTER TABLE "material_stock_ledger" DROP CONSTRAINT "material_stock_ledger_quantity";
|
||||||
|
ALTER TYPE "MaterialStockKind" RENAME TO "MaterialStockKind_old";
|
||||||
|
CREATE TYPE "MaterialStockKind" AS ENUM ('RECEIPT_ACCEPTED', 'PRODUCTION_CONSUMED', 'PRODUCTION_WASTED');
|
||||||
|
ALTER TABLE "material_stock_ledger" ALTER COLUMN "kind" TYPE "MaterialStockKind" USING "kind"::text::"MaterialStockKind";
|
||||||
|
DROP TYPE "MaterialStockKind_old";
|
||||||
|
|
||||||
|
CREATE TABLE "production_stock_postings" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"organization_id" UUID NOT NULL,
|
||||||
|
"batch_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 "production_stock_postings_pkey" PRIMARY KEY ("id"),
|
||||||
|
CONSTRAINT "production_stock_postings_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX "production_stock_postings_batch_id_key" ON "production_stock_postings"("batch_id");
|
||||||
|
CREATE UNIQUE INDEX "production_stock_postings_batch_id_organization_id_key" ON "production_stock_postings"("batch_id", "organization_id");
|
||||||
|
CREATE UNIQUE INDEX "production_stock_postings_organization_id_idempotency_key_key" ON "production_stock_postings"("organization_id", "idempotency_key");
|
||||||
|
CREATE UNIQUE INDEX "production_stock_postings_id_organization_id_key" ON "production_stock_postings"("id", "organization_id");
|
||||||
|
ALTER TABLE "production_stock_postings" ADD CONSTRAINT "production_stock_postings_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "production_stock_postings" ADD CONSTRAINT "production_stock_postings_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 "production_stock_postings" ADD CONSTRAINT "production_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 "production_stock_postings" ADD CONSTRAINT "production_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" ALTER COLUMN "posting_id" DROP NOT NULL;
|
||||||
|
ALTER TABLE "material_stock_ledger" ALTER COLUMN "receipt_line_id" DROP NOT NULL;
|
||||||
|
ALTER TABLE "material_stock_ledger" ADD COLUMN "production_posting_id" UUID;
|
||||||
|
ALTER TABLE "material_stock_ledger" ADD COLUMN "usage_event_id" UUID;
|
||||||
|
CREATE UNIQUE INDEX "material_stock_ledger_usage_event_id_key" ON "material_stock_ledger"("usage_event_id");
|
||||||
|
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_production_scope_fkey" FOREIGN KEY ("production_posting_id", "organization_id") REFERENCES "production_stock_postings"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_usage_fkey" FOREIGN KEY ("usage_event_id") REFERENCES "production_material_usage"("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)
|
||||||
|
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)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE FUNCTION guard_production_stock_posting() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Production stock postings are immutable'; END IF;
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM production_batches b WHERE b.id = NEW.batch_id
|
||||||
|
AND b.organization_id = NEW.organization_id AND b.status = 'COMPLETED'
|
||||||
|
) THEN RAISE EXCEPTION 'Production batch must be completed before stock posting'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER production_stock_postings_guard BEFORE INSERT OR UPDATE OR DELETE ON production_stock_postings FOR EACH ROW EXECUTE FUNCTION guard_production_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;
|
||||||
|
ELSE
|
||||||
|
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;
|
||||||
|
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;
|
||||||
|
$$;
|
||||||
|
|
@ -24,6 +24,7 @@ model ProductionBatch {
|
||||||
materialUsage ProductionMaterialUsage[]
|
materialUsage ProductionMaterialUsage[]
|
||||||
packagingRun PackagingRun?
|
packagingRun PackagingRun?
|
||||||
costSnapshot BatchCostSnapshot?
|
costSnapshot BatchCostSnapshot?
|
||||||
|
stockPosting ProductionStockPosting?
|
||||||
@@unique([organizationId, reference])
|
@@unique([organizationId, reference])
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
@@unique([id, bomId, organizationId])
|
@@unique([id, bomId, organizationId])
|
||||||
|
|
|
||||||
|
|
@ -46,6 +46,7 @@ model Organization {
|
||||||
batchCostSnapshots BatchCostSnapshot[]
|
batchCostSnapshots BatchCostSnapshot[]
|
||||||
materialStockItems MaterialStockItem[]
|
materialStockItems MaterialStockItem[]
|
||||||
materialReceiptPostings MaterialReceiptPosting[]
|
materialReceiptPostings MaterialReceiptPosting[]
|
||||||
|
productionStockPostings ProductionStockPosting[]
|
||||||
@@map("organizations")
|
@@map("organizations")
|
||||||
}
|
}
|
||||||
model User {
|
model User {
|
||||||
|
|
@ -82,6 +83,7 @@ model User {
|
||||||
materialCostRates MaterialCostRate[]
|
materialCostRates MaterialCostRate[]
|
||||||
batchCostSnapshots BatchCostSnapshot[]
|
batchCostSnapshots BatchCostSnapshot[]
|
||||||
materialReceiptPostings MaterialReceiptPosting[]
|
materialReceiptPostings MaterialReceiptPosting[]
|
||||||
|
productionStockPostings ProductionStockPosting[]
|
||||||
stockEntries StockLedger[]
|
stockEntries StockLedger[]
|
||||||
stockReservations StockReservation[]
|
stockReservations StockReservation[]
|
||||||
carts Cart[]
|
carts Cart[]
|
||||||
|
|
|
||||||
|
|
@ -556,4 +556,34 @@ export const COMMERCE_ERRORS = {
|
||||||
'Warehouse material stock capacity exceeded',
|
'Warehouse material stock capacity exceeded',
|
||||||
'Material stock balance overflow',
|
'Material stock balance overflow',
|
||||||
],
|
],
|
||||||
|
PRODUCTION_STOCK_POSTING_NOT_FOUND: [
|
||||||
|
404,
|
||||||
|
'Production stock posting not found',
|
||||||
|
'Production stock posting scoped lookup failed',
|
||||||
|
],
|
||||||
|
PRODUCTION_STOCK_BATCH_STATE: [
|
||||||
|
409,
|
||||||
|
'Complete the batch before posting material stock',
|
||||||
|
'Production stock batch state rejected',
|
||||||
|
],
|
||||||
|
PRODUCTION_STOCK_USAGE_INCOMPLETE: [
|
||||||
|
409,
|
||||||
|
'Record usage for every production BOM line before posting stock',
|
||||||
|
'Production stock usage reconciliation failed',
|
||||||
|
],
|
||||||
|
PRODUCTION_STOCK_INSUFFICIENT: [
|
||||||
|
409,
|
||||||
|
'Insufficient material stock in this warehouse',
|
||||||
|
'Production stock balance check failed',
|
||||||
|
],
|
||||||
|
PRODUCTION_STOCK_ALREADY_POSTED: [
|
||||||
|
409,
|
||||||
|
'Material stock was already posted for this batch',
|
||||||
|
'Production stock duplicate posting rejected',
|
||||||
|
],
|
||||||
|
PRODUCTION_STOCK_REPLAY_CONFLICT: [
|
||||||
|
409,
|
||||||
|
'Idempotency key was used for different production stock',
|
||||||
|
'Production stock idempotency payload mismatch',
|
||||||
|
],
|
||||||
} as const;
|
} as const;
|
||||||
|
|
|
||||||
|
|
@ -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 {
|
||||||
|
productionStockPostingSchema,
|
||||||
|
type ProductionStockPostingInput,
|
||||||
|
} from './production-stock-posting.schemas';
|
||||||
|
import { ProductionStockPostingStore } from './production-stock-posting.store';
|
||||||
|
|
||||||
|
@Controller('production-batches/:batchId/material-stock-posting')
|
||||||
|
export class ProductionStockPostingController {
|
||||||
|
constructor(private readonly postings: ProductionStockPostingStore) {}
|
||||||
|
|
||||||
|
@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(productionStockPostingSchema))
|
||||||
|
input: ProductionStockPostingInput,
|
||||||
|
) {
|
||||||
|
return this.postings.create(actor, batchId, input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const productionStockPostingSchema = z
|
||||||
|
.object({
|
||||||
|
warehouseId: z.uuid(),
|
||||||
|
idempotencyKey: z.uuid(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export type ProductionStockPostingInput = z.infer<
|
||||||
|
typeof productionStockPostingSchema
|
||||||
|
>;
|
||||||
|
|
@ -0,0 +1,169 @@
|
||||||
|
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 {
|
||||||
|
formatMaterialQuantity,
|
||||||
|
parseMaterialQuantity,
|
||||||
|
} from './batch-quantity';
|
||||||
|
import type { ProductionStockPostingInput } from './production-stock-posting.schemas';
|
||||||
|
|
||||||
|
const postingView = { entries: { orderBy: { usageEventId: 'asc' as const } } };
|
||||||
|
type Posting = Prisma.ProductionStockPostingGetPayload<{
|
||||||
|
include: typeof postingView;
|
||||||
|
}>;
|
||||||
|
function present(posting: Posting) {
|
||||||
|
return {
|
||||||
|
id: posting.id,
|
||||||
|
batchId: posting.batchId,
|
||||||
|
warehouseId: posting.warehouseId,
|
||||||
|
postedById: posting.postedById,
|
||||||
|
createdAt: posting.createdAt,
|
||||||
|
entries: posting.entries.map((entry) => ({
|
||||||
|
id: entry.id,
|
||||||
|
stockItemId: entry.stockItemId,
|
||||||
|
materialId: entry.materialId,
|
||||||
|
usageEventId: entry.usageEventId,
|
||||||
|
kind: entry.kind,
|
||||||
|
delta: entry.delta.toFixed(3),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ProductionStockPostingStore {
|
||||||
|
constructor(
|
||||||
|
private readonly db: DatabaseService,
|
||||||
|
private readonly access: AccessStore,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async find(actor: Principal, batchId: string) {
|
||||||
|
const posting = await this.db.productionStockPosting.findFirst({
|
||||||
|
where: { batchId, organizationId: actor.organizationId },
|
||||||
|
include: postingView,
|
||||||
|
});
|
||||||
|
if (!posting) throw new AppError('PRODUCTION_STOCK_POSTING_NOT_FOUND');
|
||||||
|
return present(posting);
|
||||||
|
}
|
||||||
|
|
||||||
|
create(
|
||||||
|
actor: Principal,
|
||||||
|
batchId: string,
|
||||||
|
input: ProductionStockPostingInput,
|
||||||
|
) {
|
||||||
|
return this.access.mutate(actor, 'inventory.manage', async (tx) => {
|
||||||
|
const hash = createHash('sha256')
|
||||||
|
.update(JSON.stringify({ batchId, warehouseId: input.warehouseId }))
|
||||||
|
.digest('hex');
|
||||||
|
const prior = await tx.productionStockPosting.findFirst({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
idempotencyKey: input.idempotencyKey,
|
||||||
|
},
|
||||||
|
include: postingView,
|
||||||
|
});
|
||||||
|
if (prior) {
|
||||||
|
if (prior.requestHash !== hash)
|
||||||
|
throw new AppError('PRODUCTION_STOCK_REPLAY_CONFLICT');
|
||||||
|
return present(prior);
|
||||||
|
}
|
||||||
|
const batch = await tx.productionBatch.findFirst({
|
||||||
|
where: { id: batchId, organizationId: actor.organizationId },
|
||||||
|
include: {
|
||||||
|
bom: { include: { lines: true } },
|
||||||
|
materialUsage: { include: { bomLine: true }, orderBy: { id: 'asc' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!batch) throw new AppError('BATCH_NOT_FOUND');
|
||||||
|
if (
|
||||||
|
await tx.productionStockPosting.findUnique({
|
||||||
|
where: { batchId },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
)
|
||||||
|
throw new AppError('PRODUCTION_STOCK_ALREADY_POSTED');
|
||||||
|
if (batch.status !== 'COMPLETED')
|
||||||
|
throw new AppError('PRODUCTION_STOCK_BATCH_STATE');
|
||||||
|
if (
|
||||||
|
batch.bom.lines.some(
|
||||||
|
(line) =>
|
||||||
|
!batch.materialUsage.some((usage) => usage.bomLineId === line.id),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new AppError('PRODUCTION_STOCK_USAGE_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 stock = await tx.materialStockItem.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
warehouseId: warehouse.id,
|
||||||
|
materialId: { in: batch.bom.lines.map((line) => line.materialId) },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const byMaterial = new Map(stock.map((item) => [item.materialId, item]));
|
||||||
|
const needed = new Map<string, bigint>();
|
||||||
|
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 posting = await tx.productionStockPosting.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
batchId,
|
||||||
|
warehouseId: warehouse.id,
|
||||||
|
postedById: actor.userId,
|
||||||
|
idempotencyKey: input.idempotencyKey,
|
||||||
|
requestHash: hash,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
for (const usage of batch.materialUsage) {
|
||||||
|
const materialId = usage.bomLine.materialId;
|
||||||
|
await tx.materialStockLedger.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
stockItemId: byMaterial.get(materialId)!.id,
|
||||||
|
materialId,
|
||||||
|
productionPostingId: posting.id,
|
||||||
|
usageEventId: usage.id,
|
||||||
|
kind:
|
||||||
|
usage.kind === 'CONSUMED'
|
||||||
|
? 'PRODUCTION_CONSUMED'
|
||||||
|
: 'PRODUCTION_WASTED',
|
||||||
|
delta: formatMaterialQuantity(
|
||||||
|
-parseMaterialQuantity(usage.quantity.toFixed(3)),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'batch.material_stock_posted',
|
||||||
|
posting.id,
|
||||||
|
);
|
||||||
|
return present(
|
||||||
|
await tx.productionStockPosting.findUniqueOrThrow({
|
||||||
|
where: { id: posting.id },
|
||||||
|
include: postingView,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -7,14 +7,22 @@ import { MaterialUsageController } from './material-usage.controller';
|
||||||
import { MaterialUsageStore } from './material-usage.store';
|
import { MaterialUsageStore } from './material-usage.store';
|
||||||
import { PackagingRunController } from './packaging-run.controller';
|
import { PackagingRunController } from './packaging-run.controller';
|
||||||
import { PackagingRunStore } from './packaging-run.store';
|
import { PackagingRunStore } from './packaging-run.store';
|
||||||
|
import { ProductionStockPostingController } from './production-stock-posting.controller';
|
||||||
|
import { ProductionStockPostingStore } from './production-stock-posting.store';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, IdentityModule],
|
imports: [DatabaseModule, IdentityModule],
|
||||||
providers: [BatchStore, MaterialUsageStore, PackagingRunStore],
|
providers: [
|
||||||
|
BatchStore,
|
||||||
|
MaterialUsageStore,
|
||||||
|
PackagingRunStore,
|
||||||
|
ProductionStockPostingStore,
|
||||||
|
],
|
||||||
controllers: [
|
controllers: [
|
||||||
BatchesController,
|
BatchesController,
|
||||||
MaterialUsageController,
|
MaterialUsageController,
|
||||||
PackagingRunController,
|
PackagingRunController,
|
||||||
|
ProductionStockPostingController,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class ProductionModule {}
|
export class ProductionModule {}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,224 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||||
|
import { secondActor } from './helpers/commerce';
|
||||||
|
import { createBatch, seedActiveBom } from './helpers/production';
|
||||||
|
|
||||||
|
describe('production 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}/material-stock-posting`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send(body);
|
||||||
|
const get = (batchId: string) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.get(`/api/v1/production-batches/${batchId}/material-stock-posting`)
|
||||||
|
.auth(ctx.token, auth);
|
||||||
|
const seed = async (balance = '250.000') => {
|
||||||
|
const bom = await seedActiveBom(ctx);
|
||||||
|
const batch = await createBatch(ctx, bom.bomId).expect(201);
|
||||||
|
const warehouse = await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/inventory/warehouses')
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ name: `Production ${randomUUID().slice(0, 8)}` })
|
||||||
|
.expect(201);
|
||||||
|
const stock = await ctx.db.materialStockItem.create({
|
||||||
|
data: {
|
||||||
|
organizationId: ctx.owner.organizationId,
|
||||||
|
materialId: bom.materialId,
|
||||||
|
warehouseId: warehouse.body.id,
|
||||||
|
onHand: balance,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
...bom,
|
||||||
|
batchId: batch.body.id as string,
|
||||||
|
warehouseId: warehouse.body.id as string,
|
||||||
|
stockId: stock.id,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const use = async (
|
||||||
|
batchId: string,
|
||||||
|
bomLineId: string,
|
||||||
|
kind: 'CONSUMED' | 'WASTED',
|
||||||
|
quantity: string,
|
||||||
|
) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/production-batches/${batchId}/material-usage`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({
|
||||||
|
bomLineId,
|
||||||
|
kind,
|
||||||
|
quantity,
|
||||||
|
...(kind === 'WASTED' ? { reason: 'Spillage' } : {}),
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
const start = (batchId: string) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/production-batches/${batchId}/start`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(201);
|
||||||
|
const complete = (batchId: string) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/production-batches/${batchId}/complete`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ goodQuantity: 20, rejectedQuantity: 0 })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
ctx = await identityApp();
|
||||||
|
}, 60000);
|
||||||
|
afterAll(async () => {
|
||||||
|
await ctx?.close();
|
||||||
|
});
|
||||||
|
beforeEach(async () => {
|
||||||
|
await ctx.clearLimits();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deducts consumed and wasted quantities from the chosen warehouse once', async () => {
|
||||||
|
const data = await seed();
|
||||||
|
await start(data.batchId);
|
||||||
|
await use(data.batchId, data.bomLineId, 'CONSUMED', '200.000');
|
||||||
|
await use(data.batchId, data.bomLineId, 'WASTED', '10.125');
|
||||||
|
await complete(data.batchId);
|
||||||
|
const body = {
|
||||||
|
warehouseId: data.warehouseId,
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
};
|
||||||
|
const result = await post(data.batchId, body).expect(201);
|
||||||
|
expect(
|
||||||
|
result.body.entries.map((entry: { kind: string }) => entry.kind).sort(),
|
||||||
|
).toEqual(['PRODUCTION_CONSUMED', 'PRODUCTION_WASTED']);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx.db.materialStockItem.findUniqueOrThrow({
|
||||||
|
where: { id: data.stockId },
|
||||||
|
})
|
||||||
|
).onHand.toFixed(3),
|
||||||
|
).toBe('39.875');
|
||||||
|
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: { productionPostingId: result.body.id },
|
||||||
|
}),
|
||||||
|
).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects incomplete state, changed retries and duplicate posting', async () => {
|
||||||
|
const data = await seed();
|
||||||
|
const body = {
|
||||||
|
warehouseId: data.warehouseId,
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
};
|
||||||
|
expect((await post(data.batchId, body).expect(409)).body.code).toBe(
|
||||||
|
'PRODUCTION_STOCK_BATCH_STATE',
|
||||||
|
);
|
||||||
|
await start(data.batchId);
|
||||||
|
await complete(data.batchId);
|
||||||
|
expect((await post(data.batchId, body).expect(409)).body.code).toBe(
|
||||||
|
'PRODUCTION_STOCK_USAGE_INCOMPLETE',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
await ctx.db.productionStockPosting.count({
|
||||||
|
where: { batchId: data.batchId },
|
||||||
|
}),
|
||||||
|
).toBe(0);
|
||||||
|
// A separate completed batch with recorded use exercises replay and duplicate guards.
|
||||||
|
const other = await seed();
|
||||||
|
await start(other.batchId);
|
||||||
|
await use(other.batchId, other.bomLineId, 'CONSUMED', '1.000');
|
||||||
|
await complete(other.batchId);
|
||||||
|
const request = {
|
||||||
|
warehouseId: other.warehouseId,
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
};
|
||||||
|
await post(other.batchId, request).expect(201);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await post(other.batchId, {
|
||||||
|
...request,
|
||||||
|
warehouseId: data.warehouseId,
|
||||||
|
}).expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('PRODUCTION_STOCK_REPLAY_CONFLICT');
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await post(other.batchId, {
|
||||||
|
...request,
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
}).expect(409)
|
||||||
|
).body.code,
|
||||||
|
).toBe('PRODUCTION_STOCK_ALREADY_POSTED');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an insufficient warehouse atomically and enforces tenant scope', async () => {
|
||||||
|
const data = await seed('5.000');
|
||||||
|
await start(data.batchId);
|
||||||
|
await use(data.batchId, data.bomLineId, 'CONSUMED', '5.000');
|
||||||
|
await use(data.batchId, data.bomLineId, 'WASTED', '0.001');
|
||||||
|
await complete(data.batchId);
|
||||||
|
const body = {
|
||||||
|
warehouseId: data.warehouseId,
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
};
|
||||||
|
expect((await post(data.batchId, body).expect(409)).body.code).toBe(
|
||||||
|
'PRODUCTION_STOCK_INSUFFICIENT',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
await ctx.db.productionStockPosting.count({
|
||||||
|
where: { batchId: data.batchId },
|
||||||
|
}),
|
||||||
|
).toBe(0);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx.db.materialStockItem.findUniqueOrThrow({
|
||||||
|
where: { id: data.stockId },
|
||||||
|
})
|
||||||
|
).onHand.toFixed(3),
|
||||||
|
).toBe('5.000');
|
||||||
|
const reader = await secondActor(ctx, true, ['inventory.read']);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/production-batches/${data.batchId}/material-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}/material-stock-posting`)
|
||||||
|
.auth(outsider.token, auth)
|
||||||
|
.expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects direct alteration of a posted ledger entry', async () => {
|
||||||
|
const data = await seed();
|
||||||
|
await start(data.batchId);
|
||||||
|
await use(data.batchId, data.bomLineId, 'CONSUMED', '1.000');
|
||||||
|
await complete(data.batchId);
|
||||||
|
const result = await post(data.batchId, {
|
||||||
|
warehouseId: data.warehouseId,
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
}).expect(201);
|
||||||
|
await expect(
|
||||||
|
ctx.db.materialStockLedger.update({
|
||||||
|
where: { id: result.body.entries[0].id },
|
||||||
|
data: { delta: '-2.000' },
|
||||||
|
}),
|
||||||
|
).rejects.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue