Merge pull request 'feat(inventory): transfer material stock between warehouses' (#24) from feat/material-warehouse-transfers into main
Reviewed-on: #24
This commit is contained in:
commit
06ef0df5f5
|
|
@ -54,3 +54,4 @@ Warehouse material stock: see [Phase 2N API guide](docs/material-warehouse-stock
|
||||||
Production material stock posting: see [Phase 2O API guide](docs/production-material-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).
|
Packaging material stock posting: see [Phase 2P API guide](docs/packaging-material-stock-api.md).
|
||||||
Finished-goods receipts: see [Phase 2Q API guide](docs/finished-goods-receipt-api.md).
|
Finished-goods receipts: see [Phase 2Q API guide](docs/finished-goods-receipt-api.md).
|
||||||
|
Material warehouse transfers: see [Phase 2R API guide](docs/material-transfers-api.md).
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
# Material warehouse transfers (Phase 2R)
|
||||||
|
|
||||||
|
Move a material's on-hand quantity between two organization-scoped warehouses. The transfer posts one negative ledger entry to the source and one equal positive entry to the destination in a single transaction. It creates the destination material-stock item when needed. It never changes the organization's total quantity of that material.
|
||||||
|
|
||||||
|
| Method | Path | Permission |
|
||||||
|
| ------ | ------------------------------------------------------------------------------------------------- | ------------------ |
|
||||||
|
| GET | `/api/v1/inventory/material-transfers?materialId=&fromWarehouseId=&toWarehouseId=&limit=&offset=` | `inventory.read` |
|
||||||
|
| GET | `/api/v1/inventory/material-transfers/:id` | `inventory.read` |
|
||||||
|
| POST | `/api/v1/inventory/material-transfers` | `inventory.manage` |
|
||||||
|
|
||||||
|
POST body: `{ "materialId": "<uuid>", "fromWarehouseId": "<uuid>", "toWarehouseId": "<uuid>", "quantity": "0.600", "idempotencyKey": "<uuid>" }`. Quantity is positive, in the material's native unit, with exactly three decimal places. Source and destination must differ. A same-key, same-request retry returns the original transfer; a changed request returns `MATERIAL_TRANSFER_REPLAY_CONFLICT`.
|
||||||
|
|
||||||
|
The full quantity must be on hand in the source, and the destination balance must remain within the supported limit. Otherwise the entire transfer rolls back. PostgreSQL verifies the transfer's material and warehouse relationships, both exact signed ledger entries, and each balance bound. Transfer records and ledger entries cannot be edited or deleted. Manual material adjustments are a separate milestone.
|
||||||
|
|
@ -12,4 +12,4 @@ Raw-material balances are tracked per organization, material and warehouse. Use
|
||||||
|
|
||||||
POST body: `{ "warehouseId": "<uuid>", "idempotencyKey": "<uuid>" }`. 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.
|
POST body: `{ "warehouseId": "<uuid>", "idempotencyKey": "<uuid>" }`. 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 are documented separately. 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, packaging and warehouse transfer operations are documented separately. Manual material adjustments remain a later stock milestone.
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase
|
||||||
- 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.
|
- 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.
|
- 2P (implemented): atomic per-warehouse packaging and label stock deduction from recorded packaging use and wastage. Transfers, adjustments and finished-goods output remain later milestones.
|
||||||
- 2Q (implemented): single, idempotent finished-goods receipt per completed and stock-posted batch, crediting only good units to an organization-scoped warehouse variant balance. Material transfers and adjustments remain later milestones.
|
- 2Q (implemented): single, idempotent finished-goods receipt per completed and stock-posted batch, crediting only good units to an organization-scoped warehouse variant balance. Material transfers and adjustments remain later milestones.
|
||||||
|
- 2R (implemented): atomic, idempotent warehouse-to-warehouse material transfers with balanced append-only ledger entries and scoped history. Manual material adjustments remain a later milestone.
|
||||||
|
|
||||||
## Phase 3: B2B and white label
|
## Phase 3: B2B and white label
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,8 @@ model Warehouse {
|
||||||
productionStockPostings ProductionStockPosting[]
|
productionStockPostings ProductionStockPosting[]
|
||||||
packagingStockPostings PackagingStockPosting[]
|
packagingStockPostings PackagingStockPosting[]
|
||||||
finishedGoodsReceipts FinishedGoodsReceipt[]
|
finishedGoodsReceipts FinishedGoodsReceipt[]
|
||||||
|
transferSources MaterialStockTransfer[] @relation("MaterialTransferSourceWarehouse")
|
||||||
|
transferDestinations MaterialStockTransfer[] @relation("MaterialTransferDestinationWarehouse")
|
||||||
@@unique([organizationId, name])
|
@@unique([organizationId, name])
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
@@map("warehouses")
|
@@map("warehouses")
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ enum MaterialStockKind {
|
||||||
PRODUCTION_WASTED
|
PRODUCTION_WASTED
|
||||||
PACKAGING_USED
|
PACKAGING_USED
|
||||||
PACKAGING_WASTED
|
PACKAGING_WASTED
|
||||||
|
TRANSFER_OUT
|
||||||
|
TRANSFER_IN
|
||||||
}
|
}
|
||||||
|
|
||||||
model MaterialStockItem {
|
model MaterialStockItem {
|
||||||
|
|
@ -16,6 +18,8 @@ model MaterialStockItem {
|
||||||
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
entries MaterialStockLedger[]
|
entries MaterialStockLedger[]
|
||||||
|
transferSources MaterialStockTransfer[] @relation("MaterialTransferSource")
|
||||||
|
transferDestinations MaterialStockTransfer[] @relation("MaterialTransferDestination")
|
||||||
@@unique([materialId, warehouseId])
|
@@unique([materialId, warehouseId])
|
||||||
@@unique([id, materialId, organizationId])
|
@@unique([id, materialId, organizationId])
|
||||||
@@index([organizationId, warehouseId, materialId], map: "material_stock_items_scope_idx")
|
@@index([organizationId, warehouseId, materialId], map: "material_stock_items_scope_idx")
|
||||||
|
|
@ -82,6 +86,33 @@ model PackagingStockPosting {
|
||||||
@@map("packaging_stock_postings")
|
@@map("packaging_stock_postings")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model MaterialStockTransfer {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
|
materialId String @map("material_id") @db.Uuid
|
||||||
|
fromWarehouseId String @map("from_warehouse_id") @db.Uuid
|
||||||
|
toWarehouseId String @map("to_warehouse_id") @db.Uuid
|
||||||
|
fromStockItemId String @map("from_stock_item_id") @db.Uuid
|
||||||
|
toStockItemId String @map("to_stock_item_id") @db.Uuid
|
||||||
|
postedById String @map("posted_by_id") @db.Uuid
|
||||||
|
quantity Decimal @db.Decimal(12,3)
|
||||||
|
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)
|
||||||
|
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
fromWarehouse Warehouse @relation("MaterialTransferSourceWarehouse", fields: [fromWarehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
toWarehouse Warehouse @relation("MaterialTransferDestinationWarehouse", fields: [toWarehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
fromStockItem MaterialStockItem @relation("MaterialTransferSource", fields: [fromStockItemId, materialId, organizationId], references: [id, materialId, organizationId], onDelete: Restrict, map: "material_stock_transfers_from_stock_scope_fkey")
|
||||||
|
toStockItem MaterialStockItem @relation("MaterialTransferDestination", fields: [toStockItemId, materialId, organizationId], references: [id, materialId, organizationId], onDelete: Restrict, map: "material_stock_transfers_to_stock_scope_fkey")
|
||||||
|
postedBy User @relation(fields: [postedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
entries MaterialStockLedger[]
|
||||||
|
@@unique([organizationId, idempotencyKey])
|
||||||
|
@@unique([id, organizationId])
|
||||||
|
@@index([organizationId, materialId, createdAt, id], map: "material_stock_transfers_scope_idx")
|
||||||
|
@@map("material_stock_transfers")
|
||||||
|
}
|
||||||
|
|
||||||
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
|
||||||
|
|
@ -93,6 +124,7 @@ model MaterialStockLedger {
|
||||||
usageEventId String? @unique @map("usage_event_id") @db.Uuid
|
usageEventId String? @unique @map("usage_event_id") @db.Uuid
|
||||||
packagingPostingId String? @map("packaging_posting_id") @db.Uuid
|
packagingPostingId String? @map("packaging_posting_id") @db.Uuid
|
||||||
packagingRunLineId String? @map("packaging_run_line_id") @db.Uuid
|
packagingRunLineId String? @map("packaging_run_line_id") @db.Uuid
|
||||||
|
transferId String? @map("transfer_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)
|
||||||
|
|
@ -103,8 +135,10 @@ model MaterialStockLedger {
|
||||||
usageEvent ProductionMaterialUsage? @relation(fields: [usageEventId], references: [id], onDelete: Restrict, map: "material_stock_ledger_usage_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")
|
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")
|
packagingRunLine PackagingRunLine? @relation(fields: [packagingRunLineId], references: [id], onDelete: Restrict, map: "material_stock_ledger_packaging_line_fkey")
|
||||||
|
transfer MaterialStockTransfer? @relation(fields: [transferId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_transfer_scope_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])
|
||||||
@@unique([packagingRunLineId, kind])
|
@@unique([packagingRunLineId, kind])
|
||||||
|
@@unique([transferId, kind])
|
||||||
@@map("material_stock_ledger")
|
@@map("material_stock_ledger")
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -30,5 +30,6 @@
|
||||||
"20260929171600_material_warehouse_stock": "47645ff022037ea486ca82902bdf09ca36ebf05a94500b160dcd57c2d812eab8",
|
"20260929171600_material_warehouse_stock": "47645ff022037ea486ca82902bdf09ca36ebf05a94500b160dcd57c2d812eab8",
|
||||||
"20260929173800_production_material_stock": "68f5755167f87a646901835be9fe6318a3ae6bb9a3d70d8a722915d1eff3c7a4",
|
"20260929173800_production_material_stock": "68f5755167f87a646901835be9fe6318a3ae6bb9a3d70d8a722915d1eff3c7a4",
|
||||||
"20260929195800_packaging_material_stock": "2b11c19499d917bcdd53ade20175235ef83cc64cdafda2118ea2dac2096a6f8d",
|
"20260929195800_packaging_material_stock": "2b11c19499d917bcdd53ade20175235ef83cc64cdafda2118ea2dac2096a6f8d",
|
||||||
"20260929203400_finished_goods_receipt": "7745c23f9037d7bb0de7bdfaf94610794b83213f041583c0f9678c4e837f53f0"
|
"20260929203400_finished_goods_receipt": "7745c23f9037d7bb0de7bdfaf94610794b83213f041583c0f9678c4e837f53f0",
|
||||||
|
"20260930002200_material_warehouse_transfers": "0f193ecd186971e19fdc823944312be70646b348a1a846ab41703d269936e21a"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,84 @@
|
||||||
|
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', 'TRANSFER_OUT', 'TRANSFER_IN');
|
||||||
|
ALTER TABLE "material_stock_ledger" ALTER COLUMN "kind" TYPE "MaterialStockKind" USING "kind"::text::"MaterialStockKind";
|
||||||
|
DROP TYPE "MaterialStockKind_old";
|
||||||
|
|
||||||
|
CREATE TABLE "material_stock_transfers" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"organization_id" UUID NOT NULL,
|
||||||
|
"material_id" UUID NOT NULL,
|
||||||
|
"from_warehouse_id" UUID NOT NULL,
|
||||||
|
"to_warehouse_id" UUID NOT NULL,
|
||||||
|
"from_stock_item_id" UUID NOT NULL,
|
||||||
|
"to_stock_item_id" UUID NOT NULL,
|
||||||
|
"posted_by_id" UUID NOT NULL,
|
||||||
|
"quantity" DECIMAL(12,3) NOT NULL,
|
||||||
|
"idempotency_key" UUID NOT NULL,
|
||||||
|
"request_hash" CHAR(64) NOT NULL,
|
||||||
|
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT "material_stock_transfers_pkey" PRIMARY KEY ("id"),
|
||||||
|
CONSTRAINT "material_stock_transfers_quantity" CHECK ("quantity" BETWEEN 0.001 AND 999999999.999),
|
||||||
|
CONSTRAINT "material_stock_transfers_different_warehouses" CHECK ("from_warehouse_id" <> "to_warehouse_id" AND "from_stock_item_id" <> "to_stock_item_id"),
|
||||||
|
CONSTRAINT "material_stock_transfers_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX "material_stock_transfers_organization_id_idempotency_key_key" ON "material_stock_transfers"("organization_id", "idempotency_key");
|
||||||
|
CREATE UNIQUE INDEX "material_stock_transfers_id_organization_id_key" ON "material_stock_transfers"("id", "organization_id");
|
||||||
|
CREATE INDEX "material_stock_transfers_scope_idx" ON "material_stock_transfers"("organization_id", "material_id", "created_at", "id");
|
||||||
|
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_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_transfers" ADD CONSTRAINT "material_stock_transfers_from_warehouse_id_organization_id_fkey" FOREIGN KEY ("from_warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_to_warehouse_id_organization_id_fkey" FOREIGN KEY ("to_warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_from_stock_scope_fkey" FOREIGN KEY ("from_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_transfers" ADD CONSTRAINT "material_stock_transfers_to_stock_scope_fkey" FOREIGN KEY ("to_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_transfers" ADD CONSTRAINT "material_stock_transfers_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 "transfer_id" UUID;
|
||||||
|
CREATE UNIQUE INDEX "material_stock_ledger_transfer_id_kind_key" ON "material_stock_ledger"("transfer_id", "kind");
|
||||||
|
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_transfer_scope_fkey" FOREIGN KEY ("transfer_id", "organization_id") REFERENCES "material_stock_transfers"("id", "organization_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 AND "transfer_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 AND "transfer_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 AND "transfer_id" IS NULL)
|
||||||
|
OR ("kind" IN ('TRANSFER_OUT', 'TRANSFER_IN') 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 NULL AND "packaging_run_line_id" IS NULL AND "transfer_id" IS NOT NULL)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE FUNCTION guard_material_stock_transfer() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material stock transfers are immutable'; END IF;
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM material_stock_items src
|
||||||
|
JOIN material_stock_items dst ON dst.id = NEW.to_stock_item_id AND dst.organization_id = NEW.organization_id
|
||||||
|
WHERE src.id = NEW.from_stock_item_id AND src.organization_id = NEW.organization_id
|
||||||
|
AND src.material_id = NEW.material_id AND dst.material_id = NEW.material_id
|
||||||
|
AND src.warehouse_id = NEW.from_warehouse_id AND dst.warehouse_id = NEW.to_warehouse_id
|
||||||
|
) THEN RAISE EXCEPTION 'Material transfer stock items do not match the selected warehouses'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER material_stock_transfers_guard BEFORE INSERT OR UPDATE OR DELETE ON material_stock_transfers FOR EACH ROW EXECUTE FUNCTION guard_material_stock_transfer();
|
||||||
|
|
||||||
|
CREATE FUNCTION guard_material_transfer_ledger() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM material_stock_transfers t
|
||||||
|
WHERE t.id = NEW.transfer_id AND t.organization_id = NEW.organization_id
|
||||||
|
AND t.material_id = NEW.material_id
|
||||||
|
AND ((NEW.kind = 'TRANSFER_OUT' AND NEW.stock_item_id = t.from_stock_item_id AND NEW.delta = -t.quantity)
|
||||||
|
OR (NEW.kind = 'TRANSFER_IN' AND NEW.stock_item_id = t.to_stock_item_id AND NEW.delta = t.quantity))
|
||||||
|
) THEN RAISE EXCEPTION 'Material transfer stock entry does not match its transfer'; 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 transfer stock balance outside bounds'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
DROP TRIGGER material_stock_ledger_guard ON material_stock_ledger;
|
||||||
|
CREATE TRIGGER material_stock_ledger_existing_insert BEFORE INSERT ON material_stock_ledger FOR EACH ROW
|
||||||
|
WHEN (NEW.kind IN ('RECEIPT_ACCEPTED', 'PRODUCTION_CONSUMED', 'PRODUCTION_WASTED', 'PACKAGING_USED', 'PACKAGING_WASTED'))
|
||||||
|
EXECUTE FUNCTION guard_material_stock_ledger();
|
||||||
|
CREATE TRIGGER material_stock_ledger_transfer_insert BEFORE INSERT ON material_stock_ledger FOR EACH ROW
|
||||||
|
WHEN (NEW.kind IN ('TRANSFER_OUT', 'TRANSFER_IN')) EXECUTE FUNCTION guard_material_transfer_ledger();
|
||||||
|
CREATE TRIGGER material_stock_ledger_immutable BEFORE UPDATE OR DELETE ON material_stock_ledger FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION guard_material_stock_ledger();
|
||||||
|
|
@ -71,6 +71,7 @@ model Material {
|
||||||
bomLines ProductBomLine[]
|
bomLines ProductBomLine[]
|
||||||
costRates MaterialCostRate[]
|
costRates MaterialCostRate[]
|
||||||
stockItems MaterialStockItem[]
|
stockItems MaterialStockItem[]
|
||||||
|
stockTransfers MaterialStockTransfer[]
|
||||||
|
|
||||||
@@unique([organizationId, code])
|
@@unique([organizationId, code])
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
|
|
|
||||||
|
|
@ -49,6 +49,7 @@ model Organization {
|
||||||
productionStockPostings ProductionStockPosting[]
|
productionStockPostings ProductionStockPosting[]
|
||||||
packagingStockPostings PackagingStockPosting[]
|
packagingStockPostings PackagingStockPosting[]
|
||||||
finishedGoodsReceipts FinishedGoodsReceipt[]
|
finishedGoodsReceipts FinishedGoodsReceipt[]
|
||||||
|
materialStockTransfers MaterialStockTransfer[]
|
||||||
@@map("organizations")
|
@@map("organizations")
|
||||||
}
|
}
|
||||||
model User {
|
model User {
|
||||||
|
|
@ -88,6 +89,7 @@ model User {
|
||||||
productionStockPostings ProductionStockPosting[]
|
productionStockPostings ProductionStockPosting[]
|
||||||
packagingStockPostings PackagingStockPosting[]
|
packagingStockPostings PackagingStockPosting[]
|
||||||
finishedGoodsReceipts FinishedGoodsReceipt[]
|
finishedGoodsReceipts FinishedGoodsReceipt[]
|
||||||
|
materialStockTransfers MaterialStockTransfer[]
|
||||||
stockEntries StockLedger[]
|
stockEntries StockLedger[]
|
||||||
stockReservations StockReservation[]
|
stockReservations StockReservation[]
|
||||||
carts Cart[]
|
carts Cart[]
|
||||||
|
|
|
||||||
|
|
@ -656,4 +656,44 @@ export const COMMERCE_ERRORS = {
|
||||||
'Idempotency key is already used for another stock entry',
|
'Idempotency key is already used for another stock entry',
|
||||||
'Finished-goods stock ledger idempotency key conflict',
|
'Finished-goods stock ledger idempotency key conflict',
|
||||||
],
|
],
|
||||||
|
MATERIAL_TRANSFER_NOT_FOUND: [
|
||||||
|
404,
|
||||||
|
'Material transfer not found',
|
||||||
|
'Material transfer scoped lookup failed',
|
||||||
|
],
|
||||||
|
MATERIAL_TRANSFER_REPLAY_CONFLICT: [
|
||||||
|
409,
|
||||||
|
'Idempotency key was used for a different material transfer',
|
||||||
|
'Material transfer idempotency payload mismatch',
|
||||||
|
],
|
||||||
|
MATERIAL_TRANSFER_SAME_WAREHOUSE: [
|
||||||
|
400,
|
||||||
|
'Choose different source and destination warehouses',
|
||||||
|
'Material transfer identical warehouses rejected',
|
||||||
|
],
|
||||||
|
MATERIAL_TRANSFER_SOURCE_WAREHOUSE_NOT_FOUND: [
|
||||||
|
404,
|
||||||
|
'Source warehouse not found',
|
||||||
|
'Material transfer source warehouse scoped lookup failed',
|
||||||
|
],
|
||||||
|
MATERIAL_TRANSFER_DESTINATION_WAREHOUSE_NOT_FOUND: [
|
||||||
|
404,
|
||||||
|
'Destination warehouse not found',
|
||||||
|
'Material transfer destination warehouse scoped lookup failed',
|
||||||
|
],
|
||||||
|
MATERIAL_TRANSFER_SOURCE_STOCK_NOT_FOUND: [
|
||||||
|
404,
|
||||||
|
'Material has no stock in the source warehouse',
|
||||||
|
'Material transfer source stock scoped lookup failed',
|
||||||
|
],
|
||||||
|
MATERIAL_TRANSFER_INSUFFICIENT: [
|
||||||
|
409,
|
||||||
|
'Insufficient material in the source warehouse',
|
||||||
|
'Material transfer source balance check failed',
|
||||||
|
],
|
||||||
|
MATERIAL_TRANSFER_DESTINATION_CAPACITY: [
|
||||||
|
409,
|
||||||
|
'Destination material stock capacity exceeded',
|
||||||
|
'Material transfer destination balance overflow',
|
||||||
|
],
|
||||||
} as const;
|
} as const;
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,8 @@ import { MaterialStockController } from './material-stock.controller';
|
||||||
import { MaterialStockStore } from './material-stock.store';
|
import { MaterialStockStore } from './material-stock.store';
|
||||||
import { MaterialReceiptPostingController } from './material-receipt-posting.controller';
|
import { MaterialReceiptPostingController } from './material-receipt-posting.controller';
|
||||||
import { MaterialReceiptPostingStore } from './material-receipt-posting.store';
|
import { MaterialReceiptPostingStore } from './material-receipt-posting.store';
|
||||||
|
import { MaterialTransferController } from './material-transfer.controller';
|
||||||
|
import { MaterialTransferStore } from './material-transfer.store';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, IdentityModule],
|
imports: [DatabaseModule, IdentityModule],
|
||||||
|
|
@ -21,12 +23,14 @@ import { MaterialReceiptPostingStore } from './material-receipt-posting.store';
|
||||||
ReservationTransitionStore,
|
ReservationTransitionStore,
|
||||||
MaterialStockStore,
|
MaterialStockStore,
|
||||||
MaterialReceiptPostingStore,
|
MaterialReceiptPostingStore,
|
||||||
|
MaterialTransferStore,
|
||||||
],
|
],
|
||||||
controllers: [
|
controllers: [
|
||||||
StockController,
|
StockController,
|
||||||
ReservationsController,
|
ReservationsController,
|
||||||
MaterialStockController,
|
MaterialStockController,
|
||||||
MaterialReceiptPostingController,
|
MaterialReceiptPostingController,
|
||||||
|
MaterialTransferController,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class InventoryModule {}
|
export class InventoryModule {}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,54 @@
|
||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
ParseUUIDPipe,
|
||||||
|
Post,
|
||||||
|
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 {
|
||||||
|
materialTransferQuery,
|
||||||
|
materialTransferSchema,
|
||||||
|
type MaterialTransferInput,
|
||||||
|
type MaterialTransferQuery,
|
||||||
|
} from './material-transfer.schemas';
|
||||||
|
import { MaterialTransferStore } from './material-transfer.store';
|
||||||
|
|
||||||
|
@Controller('inventory/material-transfers')
|
||||||
|
export class MaterialTransferController {
|
||||||
|
constructor(private readonly transfers: MaterialTransferStore) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@RequirePermission('inventory.read')
|
||||||
|
list(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Query(new SchemaPipe(materialTransferQuery)) query: MaterialTransferQuery,
|
||||||
|
) {
|
||||||
|
return this.transfers.list(actor, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':id')
|
||||||
|
@RequirePermission('inventory.read')
|
||||||
|
find(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
) {
|
||||||
|
return this.transfers.find(actor, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@RequirePermission('inventory.manage')
|
||||||
|
create(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Body(new SchemaPipe(materialTransferSchema)) input: MaterialTransferInput,
|
||||||
|
) {
|
||||||
|
return this.transfers.create(actor, input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { pageSchema } from '../identity/identity.schemas';
|
||||||
|
|
||||||
|
export const materialTransferSchema = z
|
||||||
|
.object({
|
||||||
|
materialId: z.uuid(),
|
||||||
|
fromWarehouseId: z.uuid(),
|
||||||
|
toWarehouseId: z.uuid(),
|
||||||
|
quantity: z.string().regex(/^(?:0\.(?!000)\d{3}|[1-9]\d{0,8}\.\d{3})$/),
|
||||||
|
idempotencyKey: z.uuid(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export const materialTransferQuery = pageSchema
|
||||||
|
.extend({
|
||||||
|
materialId: z.uuid().optional(),
|
||||||
|
fromWarehouseId: z.uuid().optional(),
|
||||||
|
toWarehouseId: z.uuid().optional(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export type MaterialTransferInput = z.infer<typeof materialTransferSchema>;
|
||||||
|
export type MaterialTransferQuery = z.infer<typeof materialTransferQuery>;
|
||||||
|
|
@ -0,0 +1,193 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import { commandHash } from '../common/idempotency';
|
||||||
|
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 '../production/batch-quantity';
|
||||||
|
import type {
|
||||||
|
MaterialTransferInput,
|
||||||
|
MaterialTransferQuery,
|
||||||
|
} from './material-transfer.schemas';
|
||||||
|
|
||||||
|
const MAX_BALANCE = 999999999999n;
|
||||||
|
const transferView = { entries: { orderBy: { kind: 'asc' as const } } };
|
||||||
|
type Transfer = Prisma.MaterialStockTransferGetPayload<{
|
||||||
|
include: typeof transferView;
|
||||||
|
}>;
|
||||||
|
function present(transfer: Transfer) {
|
||||||
|
return {
|
||||||
|
id: transfer.id,
|
||||||
|
materialId: transfer.materialId,
|
||||||
|
fromWarehouseId: transfer.fromWarehouseId,
|
||||||
|
toWarehouseId: transfer.toWarehouseId,
|
||||||
|
fromStockItemId: transfer.fromStockItemId,
|
||||||
|
toStockItemId: transfer.toStockItemId,
|
||||||
|
quantity: transfer.quantity.toFixed(3),
|
||||||
|
postedById: transfer.postedById,
|
||||||
|
createdAt: transfer.createdAt,
|
||||||
|
entries: transfer.entries.map((entry) => ({
|
||||||
|
id: entry.id,
|
||||||
|
stockItemId: entry.stockItemId,
|
||||||
|
kind: entry.kind,
|
||||||
|
delta: entry.delta.toFixed(3),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MaterialTransferStore {
|
||||||
|
constructor(
|
||||||
|
private readonly db: DatabaseService,
|
||||||
|
private readonly access: AccessStore,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async list(actor: Principal, query: MaterialTransferQuery) {
|
||||||
|
const transfers = await this.db.materialStockTransfer.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
...(query.materialId ? { materialId: query.materialId } : {}),
|
||||||
|
...(query.fromWarehouseId
|
||||||
|
? { fromWarehouseId: query.fromWarehouseId }
|
||||||
|
: {}),
|
||||||
|
...(query.toWarehouseId ? { toWarehouseId: query.toWarehouseId } : {}),
|
||||||
|
},
|
||||||
|
include: transferView,
|
||||||
|
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||||
|
take: query.limit,
|
||||||
|
skip: query.offset,
|
||||||
|
});
|
||||||
|
return transfers.map(present);
|
||||||
|
}
|
||||||
|
|
||||||
|
async find(actor: Principal, id: string) {
|
||||||
|
const transfer = await this.db.materialStockTransfer.findFirst({
|
||||||
|
where: { id, organizationId: actor.organizationId },
|
||||||
|
include: transferView,
|
||||||
|
});
|
||||||
|
if (!transfer) throw new AppError('MATERIAL_TRANSFER_NOT_FOUND');
|
||||||
|
return present(transfer);
|
||||||
|
}
|
||||||
|
|
||||||
|
create(actor: Principal, input: MaterialTransferInput) {
|
||||||
|
return this.access.mutate(actor, 'inventory.manage', async (tx) => {
|
||||||
|
const hash = commandHash(
|
||||||
|
input.materialId,
|
||||||
|
input.fromWarehouseId,
|
||||||
|
input.toWarehouseId,
|
||||||
|
input.quantity,
|
||||||
|
);
|
||||||
|
const prior = await tx.materialStockTransfer.findFirst({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
idempotencyKey: input.idempotencyKey,
|
||||||
|
},
|
||||||
|
include: transferView,
|
||||||
|
});
|
||||||
|
if (prior) {
|
||||||
|
if (prior.requestHash !== hash)
|
||||||
|
throw new AppError('MATERIAL_TRANSFER_REPLAY_CONFLICT');
|
||||||
|
return present(prior);
|
||||||
|
}
|
||||||
|
if (input.fromWarehouseId === input.toWarehouseId)
|
||||||
|
throw new AppError('MATERIAL_TRANSFER_SAME_WAREHOUSE');
|
||||||
|
const sourceWarehouse = await tx.warehouse.findFirst({
|
||||||
|
where: {
|
||||||
|
id: input.fromWarehouseId,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (!sourceWarehouse)
|
||||||
|
throw new AppError('MATERIAL_TRANSFER_SOURCE_WAREHOUSE_NOT_FOUND');
|
||||||
|
const destinationWarehouse = await tx.warehouse.findFirst({
|
||||||
|
where: {
|
||||||
|
id: input.toWarehouseId,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (!destinationWarehouse)
|
||||||
|
throw new AppError('MATERIAL_TRANSFER_DESTINATION_WAREHOUSE_NOT_FOUND');
|
||||||
|
const source = await tx.materialStockItem.findFirst({
|
||||||
|
where: {
|
||||||
|
materialId: input.materialId,
|
||||||
|
warehouseId: sourceWarehouse.id,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!source)
|
||||||
|
throw new AppError('MATERIAL_TRANSFER_SOURCE_STOCK_NOT_FOUND');
|
||||||
|
const quantity = parseMaterialQuantity(input.quantity);
|
||||||
|
if (parseMaterialQuantity(source.onHand.toFixed(3)) < quantity)
|
||||||
|
throw new AppError('MATERIAL_TRANSFER_INSUFFICIENT');
|
||||||
|
let destination = await tx.materialStockItem.findFirst({
|
||||||
|
where: {
|
||||||
|
materialId: input.materialId,
|
||||||
|
warehouseId: destinationWarehouse.id,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!destination)
|
||||||
|
destination = await tx.materialStockItem.create({
|
||||||
|
data: {
|
||||||
|
materialId: input.materialId,
|
||||||
|
warehouseId: destinationWarehouse.id,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
parseMaterialQuantity(destination.onHand.toFixed(3)) + quantity >
|
||||||
|
MAX_BALANCE
|
||||||
|
)
|
||||||
|
throw new AppError('MATERIAL_TRANSFER_DESTINATION_CAPACITY');
|
||||||
|
const transfer = await tx.materialStockTransfer.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
materialId: input.materialId,
|
||||||
|
fromWarehouseId: sourceWarehouse.id,
|
||||||
|
toWarehouseId: destinationWarehouse.id,
|
||||||
|
fromStockItemId: source.id,
|
||||||
|
toStockItemId: destination.id,
|
||||||
|
postedById: actor.userId,
|
||||||
|
quantity: input.quantity,
|
||||||
|
idempotencyKey: input.idempotencyKey,
|
||||||
|
requestHash: hash,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
for (const [kind, stockItemId, delta] of [
|
||||||
|
['TRANSFER_OUT', source.id, formatMaterialQuantity(-quantity)],
|
||||||
|
['TRANSFER_IN', destination.id, input.quantity],
|
||||||
|
] as const) {
|
||||||
|
await tx.materialStockLedger.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
materialId: input.materialId,
|
||||||
|
stockItemId,
|
||||||
|
transferId: transfer.id,
|
||||||
|
kind,
|
||||||
|
delta,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'material.stock_transferred',
|
||||||
|
transfer.id,
|
||||||
|
);
|
||||||
|
return present(
|
||||||
|
await tx.materialStockTransfer.findUniqueOrThrow({
|
||||||
|
where: { id: transfer.id },
|
||||||
|
include: transferView,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,238 @@
|
||||||
|
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('material warehouse transfers', () => {
|
||||||
|
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: `Transfer ${randomUUID().slice(0, 8)}` })
|
||||||
|
.expect(201)
|
||||||
|
).body.id as string;
|
||||||
|
const post = (body: object) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/inventory/material-transfers')
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send(body);
|
||||||
|
const ready = async () => {
|
||||||
|
const order = await seedPurchaseOrder(ctx);
|
||||||
|
const line = await ctx.db.purchaseOrderLine.findUniqueOrThrow({
|
||||||
|
where: { id: order.lineId },
|
||||||
|
});
|
||||||
|
const receipt = await receiveAccepted(ctx, order, '1.000');
|
||||||
|
const fromWarehouseId = await warehouse();
|
||||||
|
const toWarehouseId = await warehouse();
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/goods-receipts/${receipt.id}/stock-posting`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ warehouseId: fromWarehouseId, idempotencyKey: randomUUID() })
|
||||||
|
.expect(201);
|
||||||
|
const source = await ctx.db.materialStockItem.findFirstOrThrow({
|
||||||
|
where: { materialId: line.materialId, warehouseId: fromWarehouseId },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
materialId: line.materialId,
|
||||||
|
fromWarehouseId,
|
||||||
|
toWarehouseId,
|
||||||
|
sourceId: source.id,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const request = (
|
||||||
|
data: Awaited<ReturnType<typeof ready>>,
|
||||||
|
quantity = '0.600',
|
||||||
|
) => ({
|
||||||
|
materialId: data.materialId,
|
||||||
|
fromWarehouseId: data.fromWarehouseId,
|
||||||
|
toWarehouseId: data.toWarehouseId,
|
||||||
|
quantity,
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
ctx = await identityApp();
|
||||||
|
}, 60000);
|
||||||
|
afterAll(async () => {
|
||||||
|
await ctx?.close();
|
||||||
|
});
|
||||||
|
beforeEach(async () => {
|
||||||
|
await ctx.clearLimits();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('conserves material across warehouses and exposes both ledger entries', async () => {
|
||||||
|
const data = await ready();
|
||||||
|
const body = request(data);
|
||||||
|
const transfer = await post(body).expect(201);
|
||||||
|
expect(transfer.body).toMatchObject({
|
||||||
|
materialId: data.materialId,
|
||||||
|
fromWarehouseId: data.fromWarehouseId,
|
||||||
|
toWarehouseId: data.toWarehouseId,
|
||||||
|
quantity: '0.600',
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
transfer.body.entries
|
||||||
|
.map((entry: { kind: string; delta: string }) => [
|
||||||
|
entry.kind,
|
||||||
|
entry.delta,
|
||||||
|
])
|
||||||
|
.sort(),
|
||||||
|
).toEqual([
|
||||||
|
['TRANSFER_IN', '0.600'],
|
||||||
|
['TRANSFER_OUT', '-0.600'],
|
||||||
|
]);
|
||||||
|
const source = await ctx.db.materialStockItem.findUniqueOrThrow({
|
||||||
|
where: { id: data.sourceId },
|
||||||
|
});
|
||||||
|
const destination = await ctx.db.materialStockItem.findUniqueOrThrow({
|
||||||
|
where: { id: transfer.body.toStockItemId },
|
||||||
|
});
|
||||||
|
expect(source.onHand.toFixed(3)).toBe('0.400');
|
||||||
|
expect(destination.onHand.toFixed(3)).toBe('0.600');
|
||||||
|
expect((await post(body).expect(201)).body.id).toBe(transfer.body.id);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get(`/api/v1/inventory/material-transfers/${transfer.body.id}`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(200)
|
||||||
|
).body.id,
|
||||||
|
).toBe(transfer.body.id);
|
||||||
|
const listing = await ctx
|
||||||
|
.api()
|
||||||
|
.get(`/api/v1/inventory/material-transfers?materialId=${data.materialId}`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(200);
|
||||||
|
expect(
|
||||||
|
listing.body.some((item: { id: string }) => item.id === transfer.body.id),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects changed retries, an empty quantity and the same warehouse', async () => {
|
||||||
|
const data = await ready();
|
||||||
|
const body = request(data, '0.001');
|
||||||
|
await post(body).expect(201);
|
||||||
|
expect(
|
||||||
|
(await post({ ...body, quantity: '0.002' }).expect(409)).body.code,
|
||||||
|
).toBe('MATERIAL_TRANSFER_REPLAY_CONFLICT');
|
||||||
|
await post({ ...request(data), quantity: '0.000' }).expect(400);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await post({
|
||||||
|
...request(data),
|
||||||
|
toWarehouseId: data.fromWarehouseId,
|
||||||
|
}).expect(400)
|
||||||
|
).body.code,
|
||||||
|
).toBe('MATERIAL_TRANSFER_SAME_WAREHOUSE');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects insufficient source stock and destination overflow atomically', async () => {
|
||||||
|
const data = await ready();
|
||||||
|
const short = await post(request(data, '1.001')).expect(409);
|
||||||
|
expect(short.body.code).toBe('MATERIAL_TRANSFER_INSUFFICIENT');
|
||||||
|
expect(
|
||||||
|
await ctx.db.materialStockTransfer.count({
|
||||||
|
where: { materialId: data.materialId },
|
||||||
|
}),
|
||||||
|
).toBe(0);
|
||||||
|
const destination = await ctx.db.materialStockItem.create({
|
||||||
|
data: {
|
||||||
|
organizationId: ctx.owner.organizationId,
|
||||||
|
materialId: data.materialId,
|
||||||
|
warehouseId: data.toWarehouseId,
|
||||||
|
onHand: '999999999.700',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const capacity = await post(request(data, '0.500')).expect(409);
|
||||||
|
expect(capacity.body.code).toBe('MATERIAL_TRANSFER_DESTINATION_CAPACITY');
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx.db.materialStockItem.findUniqueOrThrow({
|
||||||
|
where: { id: data.sourceId },
|
||||||
|
})
|
||||||
|
).onHand.toFixed(3),
|
||||||
|
).toBe('1.000');
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx.db.materialStockItem.findUniqueOrThrow({
|
||||||
|
where: { id: destination.id },
|
||||||
|
})
|
||||||
|
).onHand.toFixed(3),
|
||||||
|
).toBe('999999999.700');
|
||||||
|
expect(
|
||||||
|
await ctx.db.materialStockTransfer.count({
|
||||||
|
where: { materialId: data.materialId },
|
||||||
|
}),
|
||||||
|
).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires scoped warehouses and prevents cross-organization reads or writes', async () => {
|
||||||
|
const data = await ready();
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await post({ ...request(data), fromWarehouseId: randomUUID() }).expect(
|
||||||
|
404,
|
||||||
|
)
|
||||||
|
).body.code,
|
||||||
|
).toBe('MATERIAL_TRANSFER_SOURCE_WAREHOUSE_NOT_FOUND');
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await post({ ...request(data), toWarehouseId: randomUUID() }).expect(
|
||||||
|
404,
|
||||||
|
)
|
||||||
|
).body.code,
|
||||||
|
).toBe('MATERIAL_TRANSFER_DESTINATION_WAREHOUSE_NOT_FOUND');
|
||||||
|
const reader = await secondActor(ctx, true, ['inventory.read']);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/inventory/material-transfers')
|
||||||
|
.auth(reader.token, auth)
|
||||||
|
.send(request(data))
|
||||||
|
.expect(403);
|
||||||
|
const transfer = await post(request(data)).expect(201);
|
||||||
|
const outsider = await secondActor(ctx, false, [
|
||||||
|
'inventory.read',
|
||||||
|
'inventory.manage',
|
||||||
|
]);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get(`/api/v1/inventory/material-transfers/${transfer.body.id}`)
|
||||||
|
.auth(outsider.token, auth)
|
||||||
|
.expect(404);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/inventory/material-transfers')
|
||||||
|
.auth(outsider.token, auth)
|
||||||
|
.expect(200, []);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/inventory/material-transfers')
|
||||||
|
.auth(outsider.token, auth)
|
||||||
|
.send(request(data))
|
||||||
|
.expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the transfer and ledger immutable in PostgreSQL', async () => {
|
||||||
|
const data = await ready();
|
||||||
|
const transfer = await post(request(data)).expect(201);
|
||||||
|
await expect(
|
||||||
|
ctx.db.materialStockTransfer.update({
|
||||||
|
where: { id: transfer.body.id },
|
||||||
|
data: { quantity: '0.100' },
|
||||||
|
}),
|
||||||
|
).rejects.toThrow();
|
||||||
|
await expect(
|
||||||
|
ctx.db.materialStockLedger.update({
|
||||||
|
where: { id: transfer.body.entries[0].id },
|
||||||
|
data: { delta: '0.100' },
|
||||||
|
}),
|
||||||
|
).rejects.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue