diff --git a/README.md b/README.md index a60bafb..3502d86 100644 --- a/README.md +++ b/README.md @@ -55,3 +55,4 @@ Production material stock posting: see [Phase 2O API guide](docs/production-mate 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). Material warehouse transfers: see [Phase 2R API guide](docs/material-transfers-api.md). +Manual material-stock adjustments: see [Phase 2S API guide](docs/material-adjustments-api.md). diff --git a/docs/material-adjustments-api.md b/docs/material-adjustments-api.md new file mode 100644 index 0000000..686b8cb --- /dev/null +++ b/docs/material-adjustments-api.md @@ -0,0 +1,13 @@ +# Manual material-stock adjustments (Phase 2S) + +Authorized inventory adjusters can correct a material's on-hand quantity in one organization-scoped warehouse. Every correction requires a reason and creates one immutable signed ledger entry. Use goods receipts, production or packaging postings, and warehouse transfers for their normal movements; adjustments are for counted discrepancies or corrections. + +| Method | Path | Permission | +| ------ | -------------------------------------------------------------------------------- | ------------------ | +| GET | `/api/v1/inventory/material-adjustments?materialId=&warehouseId=&limit=&offset=` | `inventory.read` | +| GET | `/api/v1/inventory/material-adjustments/:id` | `inventory.read` | +| POST | `/api/v1/inventory/material-adjustments` | `inventory.adjust` | + +POST body: `{ "materialId": "", "warehouseId": "", "delta": "-0.250", "reason": "Counted physical inventory", "idempotencyKey": "" }`. Delta must be nonzero, signed if negative, and have exactly three decimal places in the material's native unit. Reason is trimmed and must contain 3–200 characters. A positive adjustment creates the warehouse material-stock item when missing; a negative adjustment requires existing, sufficient stock. + +The API rejects adjustments that would make on-hand stock negative or exceed the supported balance. A retry with the same key and request returns the original adjustment; a changed request returns `MATERIAL_ADJUSTMENT_REPLAY_CONFLICT`. The database independently checks the material, warehouse, signed quantity and ledger kind, then changes the balance in the same transaction. Adjustment records and ledger entries cannot be edited or deleted. diff --git a/docs/material-warehouse-stock-api.md b/docs/material-warehouse-stock-api.md index ae02773..dce644a 100644 --- a/docs/material-warehouse-stock-api.md +++ b/docs/material-warehouse-stock-api.md @@ -12,4 +12,4 @@ Raw-material balances are tracked per organization, material and warehouse. Use POST body: `{ "warehouseId": "", "idempotencyKey": "" }`. A receipt can be posted once. A retry with the same key and warehouse returns the original posting; a changed retry returns `MATERIAL_RECEIPT_REPLAY_CONFLICT`. Posting again with a different key returns `MATERIAL_RECEIPT_ALREADY_POSTED`. The response lists one ledger entry for each line with a positive accepted quantity. A fully rejected receipt can be posted with no entries. -Balances and ledger deltas use each material's native unit and three decimal places. Posting is atomic: either all accepted lines reach the selected warehouse or none do. PostgreSQL checks that ledger entries match the receipt's QC decisions and updates balances in the same transaction. The ledger and receipt posting are append-only. Production, packaging and warehouse transfer operations are documented separately. Manual material adjustments remain a later stock milestone. +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, transfer and manual adjustment operations are documented separately. diff --git a/docs/roadmap.md b/docs/roadmap.md index 5145ea2..83a0536 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -32,6 +32,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase - 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. - 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. +- 2S (implemented): reasoned, permission-gated manual material-stock adjustments with signed immutable ledger entries, idempotent retries and nonnegative warehouse balances. ## Phase 3: B2B and white label diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cdd4805..a5f3e16 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,7 @@ overrides: '@prisma/config>deepmerge-ts': 8.0.0 prisma>mysql2: 3.23.1 '@nestjs/platform-express>multer': 2.4.0 + '@nestjs/swagger>js-yaml': 5.4.1 importers: @@ -2086,8 +2087,8 @@ packages: resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==} hasBin: true - js-yaml@5.3.0: - resolution: {integrity: sha512-muutsYr+e2+d3rTgUGslq5rxbBlUy3cJ61IsHag2QNDQV+7zXWjkUpmALIajhrlLlrgRUiymj6U3zUr/TMK84Q==} + js-yaml@5.4.1: + resolution: {integrity: sha512-28R/k+NAjeuf7+CKlTxWZVExJGwVVLwY06DgEnOMz2gEpfNkDcD7QvyiVPT0xy0XXhU8vHsd4Ot42OOPdJG7dQ==} hasBin: true jsesc@3.1.0: @@ -3463,7 +3464,7 @@ snapshots: '@nestjs/common': 11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1) '@nestjs/core': 11.2.3(@nestjs/common@11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(@nestjs/platform-express@11.2.3)(reflect-metadata@0.2.2)(rxjs@7.8.2) '@nestjs/mapped-types': 2.1.1(@nestjs/common@11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(reflect-metadata@0.2.2) - js-yaml: 5.3.0 + js-yaml: 5.4.1 lodash: 4.18.1 path-to-regexp: 8.4.2 reflect-metadata: 0.2.2 @@ -5085,7 +5086,7 @@ snapshots: argparse: 1.0.10 esprima: 4.0.1 - js-yaml@5.3.0: + js-yaml@5.4.1: dependencies: argparse: 2.0.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 945894c..6b7436e 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -9,3 +9,4 @@ overrides: '@prisma/config>deepmerge-ts': 8.0.0 'prisma>mysql2': 3.23.1 '@nestjs/platform-express>multer': 2.4.0 + '@nestjs/swagger>js-yaml': 5.4.1 diff --git a/prisma/inventory.prisma b/prisma/inventory.prisma index 5742be1..688b969 100644 --- a/prisma/inventory.prisma +++ b/prisma/inventory.prisma @@ -16,6 +16,7 @@ model Warehouse { finishedGoodsReceipts FinishedGoodsReceipt[] transferSources MaterialStockTransfer[] @relation("MaterialTransferSourceWarehouse") transferDestinations MaterialStockTransfer[] @relation("MaterialTransferDestinationWarehouse") + materialStockAdjustments MaterialStockAdjustment[] @@unique([organizationId, name]) @@unique([id, organizationId]) @@map("warehouses") diff --git a/prisma/material-stock.prisma b/prisma/material-stock.prisma index 1b8c1ba..d3db3a0 100644 --- a/prisma/material-stock.prisma +++ b/prisma/material-stock.prisma @@ -6,6 +6,8 @@ enum MaterialStockKind { PACKAGING_WASTED TRANSFER_OUT TRANSFER_IN + ADJUSTMENT_IN + ADJUSTMENT_OUT } model MaterialStockItem { @@ -20,6 +22,7 @@ model MaterialStockItem { entries MaterialStockLedger[] transferSources MaterialStockTransfer[] @relation("MaterialTransferSource") transferDestinations MaterialStockTransfer[] @relation("MaterialTransferDestination") + adjustments MaterialStockAdjustment[] @@unique([materialId, warehouseId]) @@unique([id, materialId, organizationId]) @@index([organizationId, warehouseId, materialId], map: "material_stock_items_scope_idx") @@ -113,6 +116,30 @@ model MaterialStockTransfer { @@map("material_stock_transfers") } +model MaterialStockAdjustment { + 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 + stockItemId String @map("stock_item_id") @db.Uuid + adjustedById String @map("adjusted_by_id") @db.Uuid + delta Decimal @db.Decimal(12,3) + reason String @db.VarChar(200) + 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) + warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict) + stockItem MaterialStockItem @relation(fields: [stockItemId, materialId, organizationId], references: [id, materialId, organizationId], onDelete: Restrict, map: "material_stock_adjustments_item_scope_fkey") + adjustedBy User @relation(fields: [adjustedById, organizationId], references: [id, organizationId], onDelete: Restrict) + entry MaterialStockLedger? + @@unique([organizationId, idempotencyKey]) + @@unique([id, organizationId]) + @@index([organizationId, materialId, createdAt, id], map: "material_stock_adjustments_scope_idx") + @@map("material_stock_adjustments") +} + model MaterialStockLedger { id String @id @default(uuid()) @db.Uuid organizationId String @map("organization_id") @db.Uuid @@ -125,6 +152,7 @@ model MaterialStockLedger { packagingPostingId String? @map("packaging_posting_id") @db.Uuid packagingRunLineId String? @map("packaging_run_line_id") @db.Uuid transferId String? @map("transfer_id") @db.Uuid + adjustmentId String? @unique @map("adjustment_id") @db.Uuid kind MaterialStockKind delta Decimal @db.Decimal(12,3) createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) @@ -136,9 +164,11 @@ model MaterialStockLedger { 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") transfer MaterialStockTransfer? @relation(fields: [transferId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_transfer_scope_fkey") + adjustment MaterialStockAdjustment? @relation(fields: [adjustmentId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_adjustment_scope_fkey") @@index([organizationId, stockItemId, createdAt, id], map: "material_stock_ledger_item_created_idx") @@unique([receiptLineId, organizationId]) @@unique([packagingRunLineId, kind]) @@unique([transferId, kind]) + @@unique([adjustmentId, organizationId]) @@map("material_stock_ledger") } diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index 55b1fe7..ebcdd09 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -31,5 +31,6 @@ "20260929173800_production_material_stock": "68f5755167f87a646901835be9fe6318a3ae6bb9a3d70d8a722915d1eff3c7a4", "20260929195800_packaging_material_stock": "2b11c19499d917bcdd53ade20175235ef83cc64cdafda2118ea2dac2096a6f8d", "20260929203400_finished_goods_receipt": "7745c23f9037d7bb0de7bdfaf94610794b83213f041583c0f9678c4e837f53f0", - "20260930002200_material_warehouse_transfers": "0f193ecd186971e19fdc823944312be70646b348a1a846ab41703d269936e21a" + "20260930002200_material_warehouse_transfers": "0f193ecd186971e19fdc823944312be70646b348a1a846ab41703d269936e21a", + "20260930003800_material_stock_adjustments": "2002d6826f34da5a999a0098a7191aa00f5fdc4ca54446b776270021d48ef5eb" } diff --git a/prisma/migrations/20260930003800_material_stock_adjustments/migration.sql b/prisma/migrations/20260930003800_material_stock_adjustments/migration.sql new file mode 100644 index 0000000..8d5dfa0 --- /dev/null +++ b/prisma/migrations/20260930003800_material_stock_adjustments/migration.sql @@ -0,0 +1,83 @@ +DROP TRIGGER material_stock_ledger_existing_insert ON material_stock_ledger; +DROP TRIGGER material_stock_ledger_transfer_insert ON material_stock_ledger; +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', 'ADJUSTMENT_IN', 'ADJUSTMENT_OUT'); +ALTER TABLE "material_stock_ledger" ALTER COLUMN "kind" TYPE "MaterialStockKind" USING "kind"::text::"MaterialStockKind"; +DROP TYPE "MaterialStockKind_old"; + +CREATE TABLE "material_stock_adjustments" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "material_id" UUID NOT NULL, + "warehouse_id" UUID NOT NULL, + "stock_item_id" UUID NOT NULL, + "adjusted_by_id" UUID NOT NULL, + "delta" DECIMAL(12,3) NOT NULL, + "reason" VARCHAR(200) 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_adjustments_pkey" PRIMARY KEY ("id"), + CONSTRAINT "material_stock_adjustments_delta" CHECK ("delta" <> 0 AND "delta" BETWEEN -999999999.999 AND 999999999.999), + CONSTRAINT "material_stock_adjustments_reason" CHECK (char_length(btrim("reason")) BETWEEN 3 AND 200), + CONSTRAINT "material_stock_adjustments_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$') +); +CREATE UNIQUE INDEX "material_stock_adjustments_organization_id_idempotency_key_key" ON "material_stock_adjustments"("organization_id", "idempotency_key"); +CREATE UNIQUE INDEX "material_stock_adjustments_id_organization_id_key" ON "material_stock_adjustments"("id", "organization_id"); +CREATE INDEX "material_stock_adjustments_scope_idx" ON "material_stock_adjustments"("organization_id", "material_id", "created_at", "id"); +ALTER TABLE "material_stock_adjustments" ADD CONSTRAINT "material_stock_adjustments_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "material_stock_adjustments" ADD CONSTRAINT "material_stock_adjustments_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_adjustments" ADD CONSTRAINT "material_stock_adjustments_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_stock_adjustments" ADD CONSTRAINT "material_stock_adjustments_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_adjustments" ADD CONSTRAINT "material_stock_adjustments_adjusted_by_id_organization_id_fkey" FOREIGN KEY ("adjusted_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; + +ALTER TABLE "material_stock_ledger" ADD COLUMN "adjustment_id" UUID; +CREATE UNIQUE INDEX "material_stock_ledger_adjustment_id_key" ON "material_stock_ledger"("adjustment_id"); +CREATE UNIQUE INDEX "material_stock_ledger_adjustment_id_organization_id_key" ON "material_stock_ledger"("adjustment_id", "organization_id"); +ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_adjustment_scope_fkey" FOREIGN KEY ("adjustment_id", "organization_id") REFERENCES "material_stock_adjustments"("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 AND "adjustment_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 AND "adjustment_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 AND "adjustment_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 AND "adjustment_id" IS NULL) + OR ("kind" IN ('ADJUSTMENT_IN', 'ADJUSTMENT_OUT') 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 NULL AND "adjustment_id" IS NOT NULL) +); + +CREATE FUNCTION guard_material_stock_adjustment() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material stock adjustments are immutable'; END IF; + IF NOT EXISTS ( + SELECT 1 FROM material_stock_items s + WHERE s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id + AND s.material_id = NEW.material_id AND s.warehouse_id = NEW.warehouse_id + ) THEN RAISE EXCEPTION 'Material adjustment stock item does not match the warehouse'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER material_stock_adjustments_guard BEFORE INSERT OR UPDATE OR DELETE ON material_stock_adjustments FOR EACH ROW EXECUTE FUNCTION guard_material_stock_adjustment(); + +CREATE FUNCTION guard_material_adjustment_ledger() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM material_stock_adjustments a + WHERE a.id = NEW.adjustment_id AND a.organization_id = NEW.organization_id + AND a.material_id = NEW.material_id AND a.stock_item_id = NEW.stock_item_id + AND a.delta = NEW.delta + AND ((NEW.kind = 'ADJUSTMENT_IN' AND a.delta > 0) + OR (NEW.kind = 'ADJUSTMENT_OUT' AND a.delta < 0)) + ) THEN RAISE EXCEPTION 'Material adjustment stock entry does not match its adjustment'; 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 adjustment stock balance outside bounds'; END IF; + RETURN NEW; +END; +$$; +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_adjustment_insert BEFORE INSERT ON material_stock_ledger FOR EACH ROW + WHEN (NEW.kind IN ('ADJUSTMENT_IN', 'ADJUSTMENT_OUT')) EXECUTE FUNCTION guard_material_adjustment_ledger(); diff --git a/prisma/procurement.prisma b/prisma/procurement.prisma index 603b469..f0f4dc9 100644 --- a/prisma/procurement.prisma +++ b/prisma/procurement.prisma @@ -72,6 +72,7 @@ model Material { costRates MaterialCostRate[] stockItems MaterialStockItem[] stockTransfers MaterialStockTransfer[] + stockAdjustments MaterialStockAdjustment[] @@unique([organizationId, code]) @@unique([id, organizationId]) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index f400e74..c1aad39 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -50,6 +50,7 @@ model Organization { packagingStockPostings PackagingStockPosting[] finishedGoodsReceipts FinishedGoodsReceipt[] materialStockTransfers MaterialStockTransfer[] + materialStockAdjustments MaterialStockAdjustment[] @@map("organizations") } model User { @@ -90,6 +91,7 @@ model User { packagingStockPostings PackagingStockPosting[] finishedGoodsReceipts FinishedGoodsReceipt[] materialStockTransfers MaterialStockTransfer[] + materialStockAdjustments MaterialStockAdjustment[] stockEntries StockLedger[] stockReservations StockReservation[] carts Cart[] diff --git a/src/common/errors/commerce-errors.ts b/src/common/errors/commerce-errors.ts index 07b10df..768b23c 100644 --- a/src/common/errors/commerce-errors.ts +++ b/src/common/errors/commerce-errors.ts @@ -696,4 +696,29 @@ export const COMMERCE_ERRORS = { 'Destination material stock capacity exceeded', 'Material transfer destination balance overflow', ], + MATERIAL_ADJUSTMENT_NOT_FOUND: [ + 404, + 'Material stock adjustment not found', + 'Material adjustment scoped lookup failed', + ], + MATERIAL_ADJUSTMENT_REPLAY_CONFLICT: [ + 409, + 'Idempotency key was used for a different material adjustment', + 'Material adjustment idempotency payload mismatch', + ], + MATERIAL_ADJUSTMENT_STOCK_NOT_FOUND: [ + 404, + 'No material stock exists to decrease in this warehouse', + 'Material adjustment negative balance target missing', + ], + MATERIAL_ADJUSTMENT_INSUFFICIENT: [ + 409, + 'Material adjustment exceeds warehouse stock', + 'Material adjustment negative balance rejected', + ], + MATERIAL_ADJUSTMENT_CAPACITY: [ + 409, + 'Material adjustment exceeds warehouse stock capacity', + 'Material adjustment positive balance overflow', + ], } as const; diff --git a/src/inventory/inventory.module.ts b/src/inventory/inventory.module.ts index 4485f62..3f786e1 100644 --- a/src/inventory/inventory.module.ts +++ b/src/inventory/inventory.module.ts @@ -13,6 +13,8 @@ import { MaterialReceiptPostingController } from './material-receipt-posting.con import { MaterialReceiptPostingStore } from './material-receipt-posting.store'; import { MaterialTransferController } from './material-transfer.controller'; import { MaterialTransferStore } from './material-transfer.store'; +import { MaterialAdjustmentController } from './material-adjustment.controller'; +import { MaterialAdjustmentStore } from './material-adjustment.store'; @Module({ imports: [DatabaseModule, IdentityModule], @@ -24,6 +26,7 @@ import { MaterialTransferStore } from './material-transfer.store'; MaterialStockStore, MaterialReceiptPostingStore, MaterialTransferStore, + MaterialAdjustmentStore, ], controllers: [ StockController, @@ -31,6 +34,7 @@ import { MaterialTransferStore } from './material-transfer.store'; MaterialStockController, MaterialReceiptPostingController, MaterialTransferController, + MaterialAdjustmentController, ], }) export class InventoryModule {} diff --git a/src/inventory/material-adjustment.controller.ts b/src/inventory/material-adjustment.controller.ts new file mode 100644 index 0000000..fca420f --- /dev/null +++ b/src/inventory/material-adjustment.controller.ts @@ -0,0 +1,56 @@ +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 { + materialAdjustmentQuery, + materialAdjustmentSchema, + type MaterialAdjustmentInput, + type MaterialAdjustmentQuery, +} from './material-adjustment.schemas'; +import { MaterialAdjustmentStore } from './material-adjustment.store'; + +@Controller('inventory/material-adjustments') +export class MaterialAdjustmentController { + constructor(private readonly adjustments: MaterialAdjustmentStore) {} + + @Get() + @RequirePermission('inventory.read') + list( + @CurrentPrincipal() actor: Principal, + @Query(new SchemaPipe(materialAdjustmentQuery)) + query: MaterialAdjustmentQuery, + ) { + return this.adjustments.list(actor, query); + } + + @Get(':id') + @RequirePermission('inventory.read') + find( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + ) { + return this.adjustments.find(actor, id); + } + + @Post() + @RequirePermission('inventory.adjust') + create( + @CurrentPrincipal() actor: Principal, + @Body(new SchemaPipe(materialAdjustmentSchema)) + input: MaterialAdjustmentInput, + ) { + return this.adjustments.create(actor, input); + } +} diff --git a/src/inventory/material-adjustment.schemas.ts b/src/inventory/material-adjustment.schemas.ts new file mode 100644 index 0000000..2e12710 --- /dev/null +++ b/src/inventory/material-adjustment.schemas.ts @@ -0,0 +1,24 @@ +import { z } from 'zod'; +import { pageSchema } from '../identity/identity.schemas'; + +const signedQuantity = z + .string() + .regex(/^-?(?:0|[1-9]\d{0,8})\.\d{3}$/) + .refine((value) => value !== '0.000' && value !== '-0.000'); +export const materialAdjustmentSchema = z + .object({ + materialId: z.uuid(), + warehouseId: z.uuid(), + delta: signedQuantity, + reason: z.string().trim().min(3).max(200), + idempotencyKey: z.uuid(), + }) + .strict(); +export const materialAdjustmentQuery = pageSchema + .extend({ + materialId: z.uuid().optional(), + warehouseId: z.uuid().optional(), + }) + .strict(); +export type MaterialAdjustmentInput = z.infer; +export type MaterialAdjustmentQuery = z.infer; diff --git a/src/inventory/material-adjustment.store.ts b/src/inventory/material-adjustment.store.ts new file mode 100644 index 0000000..5cf8669 --- /dev/null +++ b/src/inventory/material-adjustment.store.ts @@ -0,0 +1,164 @@ +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 { + MaterialAdjustmentInput, + MaterialAdjustmentQuery, +} from './material-adjustment.schemas'; + +const MAX_BALANCE = 999999999999n; +const adjustmentView = { entry: true }; +type Adjustment = Prisma.MaterialStockAdjustmentGetPayload<{ + include: typeof adjustmentView; +}>; +function present(adjustment: Adjustment) { + return { + id: adjustment.id, + materialId: adjustment.materialId, + warehouseId: adjustment.warehouseId, + stockItemId: adjustment.stockItemId, + delta: adjustment.delta.toFixed(3), + reason: adjustment.reason, + adjustedById: adjustment.adjustedById, + createdAt: adjustment.createdAt, + ledgerEntryId: adjustment.entry?.id, + }; +} +function scaledDelta(value: string) { + return value.startsWith('-') + ? -parseMaterialQuantity(value.slice(1)) + : parseMaterialQuantity(value); +} + +@Injectable() +export class MaterialAdjustmentStore { + constructor( + private readonly db: DatabaseService, + private readonly access: AccessStore, + ) {} + + async list(actor: Principal, query: MaterialAdjustmentQuery) { + const adjustments = await this.db.materialStockAdjustment.findMany({ + where: { + organizationId: actor.organizationId, + ...(query.materialId ? { materialId: query.materialId } : {}), + ...(query.warehouseId ? { warehouseId: query.warehouseId } : {}), + }, + include: adjustmentView, + orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], + take: query.limit, + skip: query.offset, + }); + return adjustments.map(present); + } + + async find(actor: Principal, id: string) { + const adjustment = await this.db.materialStockAdjustment.findFirst({ + where: { id, organizationId: actor.organizationId }, + include: adjustmentView, + }); + if (!adjustment) throw new AppError('MATERIAL_ADJUSTMENT_NOT_FOUND'); + return present(adjustment); + } + + create(actor: Principal, input: MaterialAdjustmentInput) { + return this.access.mutate(actor, 'inventory.adjust', async (tx) => { + const hash = commandHash( + input.materialId, + input.warehouseId, + input.delta, + input.reason, + ); + const prior = await tx.materialStockAdjustment.findFirst({ + where: { + organizationId: actor.organizationId, + idempotencyKey: input.idempotencyKey, + }, + include: adjustmentView, + }); + if (prior) { + if (prior.requestHash !== hash) + throw new AppError('MATERIAL_ADJUSTMENT_REPLAY_CONFLICT'); + return present(prior); + } + const material = await tx.material.findFirst({ + where: { id: input.materialId, organizationId: actor.organizationId }, + select: { id: true }, + }); + if (!material) throw new AppError('MATERIAL_NOT_FOUND'); + 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 delta = scaledDelta(input.delta); + let stock = await tx.materialStockItem.findFirst({ + where: { + materialId: material.id, + warehouseId: warehouse.id, + organizationId: actor.organizationId, + }, + }); + if (!stock) { + if (delta < 0n) + throw new AppError('MATERIAL_ADJUSTMENT_STOCK_NOT_FOUND'); + stock = await tx.materialStockItem.create({ + data: { + materialId: material.id, + warehouseId: warehouse.id, + organizationId: actor.organizationId, + }, + }); + } + const next = parseMaterialQuantity(stock.onHand.toFixed(3)) + delta; + if (next < 0n) throw new AppError('MATERIAL_ADJUSTMENT_INSUFFICIENT'); + if (next > MAX_BALANCE) + throw new AppError('MATERIAL_ADJUSTMENT_CAPACITY'); + const adjustment = await tx.materialStockAdjustment.create({ + data: { + organizationId: actor.organizationId, + materialId: material.id, + warehouseId: warehouse.id, + stockItemId: stock.id, + adjustedById: actor.userId, + delta: formatMaterialQuantity(delta), + reason: input.reason, + idempotencyKey: input.idempotencyKey, + requestHash: hash, + }, + }); + await tx.materialStockLedger.create({ + data: { + organizationId: actor.organizationId, + materialId: material.id, + stockItemId: stock.id, + adjustmentId: adjustment.id, + kind: delta > 0n ? 'ADJUSTMENT_IN' : 'ADJUSTMENT_OUT', + delta: formatMaterialQuantity(delta), + }, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'material.stock_adjusted', + adjustment.id, + ); + return present( + await tx.materialStockAdjustment.findUniqueOrThrow({ + where: { id: adjustment.id }, + include: adjustmentView, + }), + ); + }); + } +} diff --git a/test/material-stock-adjustments.spec.ts b/test/material-stock-adjustments.spec.ts new file mode 100644 index 0000000..eefc42e --- /dev/null +++ b/test/material-stock-adjustments.spec.ts @@ -0,0 +1,201 @@ +import { randomUUID } from 'node:crypto'; +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { secondActor } from './helpers/commerce'; + +describe('manual material stock adjustments', () => { + let ctx: IdentityApp; + const auth = { type: 'bearer' as const }; + const post = (body: object) => + ctx + .api() + .post('/api/v1/inventory/material-adjustments') + .auth(ctx.token, auth) + .send(body); + const ready = async () => { + const code = randomUUID().slice(0, 8); + const material = await ctx + .api() + .post('/api/v1/materials') + .auth(ctx.token, auth) + .send({ + code: `ADJ-${code}`, + name: `Adjustment wax ${code}`, + kind: 'WAX', + unit: 'GRAM', + }) + .expect(201); + const warehouse = await ctx + .api() + .post('/api/v1/inventory/warehouses') + .auth(ctx.token, auth) + .send({ name: `Adjustment ${code}` }) + .expect(201); + return { + materialId: material.body.id as string, + warehouseId: warehouse.body.id as string, + }; + }; + const request = (data: Awaited>, delta: string) => ({ + ...data, + delta, + reason: 'Counted physical inventory', + idempotencyKey: randomUUID(), + }); + + beforeAll(async () => { + ctx = await identityApp(); + }, 60000); + afterAll(async () => { + await ctx?.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + + it('creates positive stock, deducts a later correction and keeps signed ledger entries', async () => { + const data = await ready(); + const add = request(data, '1.250'); + const first = await post(add).expect(201); + expect(first.body).toMatchObject({ + materialId: data.materialId, + warehouseId: data.warehouseId, + delta: '1.250', + reason: add.reason, + }); + expect((await post(add).expect(201)).body.id).toBe(first.body.id); + const second = await post(request(data, '-0.250')).expect(201); + const stock = await ctx.db.materialStockItem.findUniqueOrThrow({ + where: { id: first.body.stockItemId }, + }); + expect(stock.onHand.toFixed(3)).toBe('1.000'); + const entries = await ctx.db.materialStockLedger.findMany({ + where: { + stockItemId: stock.id, + kind: { in: ['ADJUSTMENT_IN', 'ADJUSTMENT_OUT'] }, + }, + orderBy: { kind: 'asc' }, + }); + expect( + entries.map((entry) => [entry.kind, entry.delta.toFixed(3)]), + ).toEqual([ + ['ADJUSTMENT_IN', '1.250'], + ['ADJUSTMENT_OUT', '-0.250'], + ]); + expect( + ( + await ctx + .api() + .get(`/api/v1/inventory/material-adjustments/${second.body.id}`) + .auth(ctx.token, auth) + .expect(200) + ).body.ledgerEntryId, + ).toBe(entries[1].id); + const listing = await ctx + .api() + .get( + `/api/v1/inventory/material-adjustments?materialId=${data.materialId}`, + ) + .auth(ctx.token, auth) + .expect(200); + expect(listing.body).toHaveLength(2); + }); + + it('rejects missing stock, insufficient stock and capacity overflow without posting', async () => { + const data = await ready(); + expect((await post(request(data, '-0.001')).expect(404)).body.code).toBe( + 'MATERIAL_ADJUSTMENT_STOCK_NOT_FOUND', + ); + await post(request(data, '1.000')).expect(201); + expect((await post(request(data, '-1.001')).expect(409)).body.code).toBe( + 'MATERIAL_ADJUSTMENT_INSUFFICIENT', + ); + const stock = await ctx.db.materialStockItem.findFirstOrThrow({ + where: { materialId: data.materialId, warehouseId: data.warehouseId }, + }); + await ctx.db.materialStockItem.update({ + where: { id: stock.id }, + data: { onHand: '999999999.999' }, + }); + expect((await post(request(data, '0.001')).expect(409)).body.code).toBe( + 'MATERIAL_ADJUSTMENT_CAPACITY', + ); + expect( + await ctx.db.materialStockAdjustment.count({ + where: { materialId: data.materialId }, + }), + ).toBe(1); + expect( + ( + await ctx.db.materialStockItem.findUniqueOrThrow({ + where: { id: stock.id }, + }) + ).onHand.toFixed(3), + ).toBe('999999999.999'); + }); + + it('requires a reason and nonzero quantity and rejects a changed retry', async () => { + const data = await ready(); + await post(request(data, '0.000')).expect(400); + await post(request(data, '-0.000')).expect(400); + await post({ ...request(data, '1.000'), reason: ' ' }).expect(400); + const body = request(data, '1.000'); + await post(body).expect(201); + expect( + (await post({ ...body, reason: 'Different stock count' }).expect(409)) + .body.code, + ).toBe('MATERIAL_ADJUSTMENT_REPLAY_CONFLICT'); + }); + + it('enforces adjustment permission and hides another organization', async () => { + const data = await ready(); + const body = request(data, '1.000'); + const reader = await secondActor(ctx, true, [ + 'inventory.read', + 'inventory.manage', + ]); + await ctx + .api() + .post('/api/v1/inventory/material-adjustments') + .auth(reader.token, auth) + .send(body) + .expect(403); + const adjustment = await post(body).expect(201); + const outsider = await secondActor(ctx, false, [ + 'inventory.read', + 'inventory.adjust', + ]); + await ctx + .api() + .get(`/api/v1/inventory/material-adjustments/${adjustment.body.id}`) + .auth(outsider.token, auth) + .expect(404); + await ctx + .api() + .get('/api/v1/inventory/material-adjustments') + .auth(outsider.token, auth) + .expect(200, []); + await ctx + .api() + .post('/api/v1/inventory/material-adjustments') + .auth(outsider.token, auth) + .send(request(data, '1.000')) + .expect(404); + }); + + it('keeps adjustment records and linked ledger entries immutable', async () => { + const data = await ready(); + const adjustment = await post(request(data, '1.000')).expect(201); + await expect( + ctx.db.materialStockAdjustment.update({ + where: { id: adjustment.body.id }, + data: { reason: 'Changed reason' }, + }), + ).rejects.toThrow(); + await expect( + ctx.db.materialStockLedger.update({ + where: { id: adjustment.body.ledgerEntryId }, + data: { delta: '2.000' }, + }), + ).rejects.toThrow(); + }); +});