From 76e7d416b0ac836b1db04645bb9d5bc28ac42e5b Mon Sep 17 00:00:00 2001 From: mihir Date: Tue, 29 Sep 2026 00:58:02 +0530 Subject: [PATCH] feat(production): record material consumption and wastage --- README.md | 1 + docs/material-usage-api.md | 24 +++ docs/roadmap.md | 1 + prisma/bom.prisma | 2 + prisma/material-usage.prisma | 26 +++ prisma/migration-checksums.json | 3 +- .../migration.sql | 45 +++++ prisma/production.prisma | 2 + prisma/schema.prisma | 2 + src/common/errors/commerce-errors.ts | 25 +++ src/identity/permissions.ts | 1 + src/production/batch-quantity.ts | 24 ++- src/production/material-usage-summary.ts | 54 ++++++ src/production/material-usage.controller.ts | 47 +++++ src/production/material-usage.schemas.ts | 19 ++ src/production/material-usage.store.ts | 147 +++++++++++++++ src/production/production.module.ts | 6 +- test/helpers/production.ts | 56 ++++++ test/material-usage-summary.spec.ts | 48 +++++ test/material-usage.spec.ts | 175 ++++++++++++++++++ test/production-batches.spec.ts | 43 +---- 21 files changed, 702 insertions(+), 49 deletions(-) create mode 100644 docs/material-usage-api.md create mode 100644 prisma/material-usage.prisma create mode 100644 prisma/migrations/20260928190933_material_usage/migration.sql create mode 100644 src/production/material-usage-summary.ts create mode 100644 src/production/material-usage.controller.ts create mode 100644 src/production/material-usage.schemas.ts create mode 100644 src/production/material-usage.store.ts create mode 100644 test/helpers/production.ts create mode 100644 test/material-usage-summary.spec.ts create mode 100644 test/material-usage.spec.ts diff --git a/README.md b/README.md index 8d21fbe..0f52c9f 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ Phase 2E adds [supplier payment records and reversals](docs/supplier-payments-ap Phase 2F adds [private versioned supplier documents and review](docs/supplier-documents-api.md). Phase 2G adds [versioned product bills of materials](docs/bom-api.md). Phase 2H adds [production batches](docs/production-batches-api.md). +Phase 2I adds [material consumption and wastage records](docs/material-usage-api.md). For a development owner, see [local admin setup](docs/local-admin.md). ### Swagger UI diff --git a/docs/material-usage-api.md b/docs/material-usage-api.md new file mode 100644 index 0000000..2bee6e1 --- /dev/null +++ b/docs/material-usage-api.md @@ -0,0 +1,24 @@ +# Production material usage (Phase 2I) + +Usage events record material consumed into a batch or wasted while it is `IN_PROGRESS`. Each event references a material line in that batch's immutable BOM revision. Events are append-only and organization scoped. They document actual usage; they do not deduct inventory or price the material. + +| Method | Path | Permission | Purpose | +| ------ | ------------------------------------------------------------------- | ---------------------------- | ------------------------------------------------------- | +| GET | `/api/v1/production-batches/:batchId/material-usage?limit=&offset=` | `production.read` | Get paginated events and full plan-versus-actual totals | +| POST | `/api/v1/production-batches/:batchId/material-usage` | `production.material.record` | Record consumption or wastage | + +Example record: + +```json +{ + "bomLineId": "", + "kind": "WASTED", + "quantity": "0.125", + "reason": "Spill during pouring", + "idempotencyKey": "" +} +``` + +`kind` is `CONSUMED` or `WASTED`. Quantity is positive with exactly three decimal places, in the BOM material's unit. Waste requires a reason. A batch accepts at most 500 usage events. Retrying the same request with the same idempotency key returns the original event, even after the batch closes; reusing the key with changed content returns `USAGE_REPLAY_CONFLICT`. + +The GET response includes `total`, an `events` page and a `materials` summary for every BOM line. For each line, `varianceQuantity = plannedQuantity − consumedQuantity − wastedQuantity`; a negative number shows overuse. Totals use exact decimal arithmetic and include all events, regardless of pagination. A completed batch need not have usage records because the earlier batch lifecycle does not require them. Stock-location policy, physical stock posting, reconciliation and costing are later decisions. diff --git a/docs/roadmap.md b/docs/roadmap.md index ffa82a9..acf00a7 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -22,6 +22,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase - 2F (implemented): private PDF versions for supplier documents, independent validation, and gated downloads. Retention and malware scanning remain deployment decisions. - 2G (implemented): versioned, organization-scoped product BOM drafts and activation with material snapshots. Production batches, consumption, wastage, packaging BOM and costing remain later milestones. - 2H (implemented): production batch planning, lifecycle, yield reconciliation and immutable completion/cancellation records. Material consumption, stock posting, wastage, packaging BOM and costing remain later milestones. +- 2I (implemented): append-only material consumption and wastage events with plan-versus-actual summaries and idempotent retries. Physical stock posting, packaging BOM and costing remain later milestones. ## Phase 3: B2B and white label diff --git a/prisma/bom.prisma b/prisma/bom.prisma index f109d48..5b6ed8f 100644 --- a/prisma/bom.prisma +++ b/prisma/bom.prisma @@ -36,7 +36,9 @@ model ProductBomLine { quantity Decimal @db.Decimal(12,3) bom ProductBom @relation(fields: [bomId, organizationId], references: [id, organizationId], onDelete: Restrict) material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict) + materialUsage ProductionMaterialUsage[] @@unique([bomId, materialId]) + @@unique([id, bomId, organizationId]) @@index([organizationId, materialId]) @@map("product_bom_lines") } diff --git a/prisma/material-usage.prisma b/prisma/material-usage.prisma new file mode 100644 index 0000000..608c02d --- /dev/null +++ b/prisma/material-usage.prisma @@ -0,0 +1,26 @@ +enum MaterialUsageKind { + CONSUMED + WASTED +} + +model ProductionMaterialUsage { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + batchId String @map("batch_id") @db.Uuid + bomId String @map("bom_id") @db.Uuid + bomLineId String @map("bom_line_id") @db.Uuid + recordedById String @map("recorded_by_id") @db.Uuid + kind MaterialUsageKind + quantity Decimal @db.Decimal(12,3) + reason String? @db.VarChar(500) + 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, 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") + recordedBy User @relation(fields: [recordedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "production_material_usage_actor_scope_fkey") + @@unique([organizationId, idempotencyKey], map: "production_material_usage_idempotency_key") + @@index([organizationId, batchId, createdAt, id], map: "production_material_usage_batch_created_idx") + @@map("production_material_usage") +} diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index 4e740f1..cb70bc1 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -21,5 +21,6 @@ "20260928145745_supplier_payments": "012ff1c33c1afa8e6fd883925616f014e7cfdac258fac37ac2ae56739e95bf6d", "20260928151912_supplier_documents": "65ec974aa6bd0e8f85dc0dbde00f5ef5d9ab81811aba17d89299b6464d4ee6c1", "20260928153219_product_boms": "b548e6e5c2f11b52374ba0ad3eedbc127244b2752f07cdcd8bf951641d4525a1", - "20260928183508_production_batches": "53b3fbabe17d3270ae3c5d74393a07abb28858ca2af8d3a1aa19c92686c84a0a" + "20260928183508_production_batches": "53b3fbabe17d3270ae3c5d74393a07abb28858ca2af8d3a1aa19c92686c84a0a", + "20260928190933_material_usage": "950a2f1861e88c052b1e4d40aff178524c3a7c198e9fb27a3c47cb77fb984e1e" } diff --git a/prisma/migrations/20260928190933_material_usage/migration.sql b/prisma/migrations/20260928190933_material_usage/migration.sql new file mode 100644 index 0000000..f7884d8 --- /dev/null +++ b/prisma/migrations/20260928190933_material_usage/migration.sql @@ -0,0 +1,45 @@ +CREATE TYPE "MaterialUsageKind" AS ENUM ('CONSUMED', 'WASTED'); + +CREATE UNIQUE INDEX "production_batches_id_bom_id_organization_id_key" ON "production_batches"("id", "bom_id", "organization_id"); +CREATE UNIQUE INDEX "product_bom_lines_id_bom_id_organization_id_key" ON "product_bom_lines"("id", "bom_id", "organization_id"); + +CREATE TABLE "production_material_usage" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "batch_id" UUID NOT NULL, + "bom_id" UUID NOT NULL, + "bom_line_id" UUID NOT NULL, + "recorded_by_id" UUID NOT NULL, + "kind" "MaterialUsageKind" NOT NULL, + "quantity" DECIMAL(12,3) NOT NULL, + "reason" VARCHAR(500), + "idempotency_key" UUID NOT NULL, + "request_hash" CHAR(64) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "production_material_usage_pkey" PRIMARY KEY ("id"), + CONSTRAINT "production_material_usage_values" CHECK ( + "quantity" > 0 AND "request_hash" ~ '^[a-f0-9]{64}$' + AND ("kind" = 'CONSUMED' OR ("reason" IS NOT NULL AND LENGTH(TRIM("reason")) > 0)) + ) +); +CREATE UNIQUE INDEX "production_material_usage_idempotency_key" ON "production_material_usage"("organization_id", "idempotency_key"); +CREATE INDEX "production_material_usage_batch_created_idx" ON "production_material_usage"("organization_id", "batch_id", "created_at", "id"); +ALTER TABLE "production_material_usage" ADD CONSTRAINT "production_material_usage_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "production_material_usage" ADD CONSTRAINT "production_material_usage_batch_scope_fkey" FOREIGN KEY ("batch_id", "bom_id", "organization_id") REFERENCES "production_batches"("id", "bom_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "production_material_usage" ADD CONSTRAINT "production_material_usage_line_scope_fkey" FOREIGN KEY ("bom_line_id", "bom_id", "organization_id") REFERENCES "product_bom_lines"("id", "bom_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "production_material_usage" ADD CONSTRAINT "production_material_usage_actor_scope_fkey" FOREIGN KEY ("recorded_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE FUNCTION guard_production_material_usage() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Production material usage is immutable'; END IF; + IF NOT EXISTS ( + SELECT 1 FROM production_batches + WHERE id = NEW.batch_id AND bom_id = NEW.bom_id AND organization_id = NEW.organization_id AND status = 'IN_PROGRESS' + ) THEN RAISE EXCEPTION 'Material usage requires a started batch'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER production_material_usage_guard BEFORE INSERT OR UPDATE OR DELETE ON production_material_usage FOR EACH ROW EXECUTE FUNCTION guard_production_material_usage(); + +UPDATE "roles" SET "permissions" = array_append("permissions", 'production.material.record') +WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('production.material.record' = ANY("permissions")); diff --git a/prisma/production.prisma b/prisma/production.prisma index 40cf16f..6b87ad9 100644 --- a/prisma/production.prisma +++ b/prisma/production.prisma @@ -21,8 +21,10 @@ model ProductionBatch { createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict) completion ProductionBatchCompletion? cancellation ProductionBatchCancellation? + materialUsage ProductionMaterialUsage[] @@unique([organizationId, reference]) @@unique([id, organizationId]) + @@unique([id, bomId, organizationId]) @@index([organizationId, status, createdAt, id]) @@index([organizationId, bomId]) @@map("production_batches") diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 997402d..5d985f2 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -40,6 +40,7 @@ model Organization { productionBatches ProductionBatch[] productionBatchCompletions ProductionBatchCompletion[] productionBatchCancellations ProductionBatchCancellation[] + productionMaterialUsage ProductionMaterialUsage[] @@map("organizations") } model User { @@ -71,6 +72,7 @@ model User { productionBatches ProductionBatch[] productionBatchCompletions ProductionBatchCompletion[] productionBatchCancellations ProductionBatchCancellation[] + productionMaterialUsage ProductionMaterialUsage[] stockEntries StockLedger[] stockReservations StockReservation[] carts Cart[] diff --git a/src/common/errors/commerce-errors.ts b/src/common/errors/commerce-errors.ts index f9814da..bd50b99 100644 --- a/src/common/errors/commerce-errors.ts +++ b/src/common/errors/commerce-errors.ts @@ -396,4 +396,29 @@ export const COMMERCE_ERRORS = { 'Give a reason for rejected pieces', 'Production batch completion rejection lacked reason', ], + USAGE_LINE_NOT_FOUND: [ + 404, + 'BOM material line not found for this batch', + 'Production material line scope lookup failed', + ], + USAGE_BATCH_STATE: [ + 409, + 'Material usage requires a started batch', + 'Production material usage state rejected', + ], + USAGE_WASTE_REASON_REQUIRED: [ + 400, + 'Give a reason for wasted material', + 'Production material wastage lacked reason', + ], + USAGE_EVENT_LIMIT: [ + 409, + 'Material usage event limit reached', + 'Production material usage resource quota exceeded', + ], + USAGE_REPLAY_CONFLICT: [ + 409, + 'Idempotency key was used for different material usage', + 'Production material usage idempotency payload mismatch', + ], } as const; diff --git a/src/identity/permissions.ts b/src/identity/permissions.ts index 405f0d8..4833f86 100644 --- a/src/identity/permissions.ts +++ b/src/identity/permissions.ts @@ -30,5 +30,6 @@ export const PERMISSIONS = [ 'bom.manage', 'production.read', 'production.manage', + 'production.material.record', ] as const; export type Permission = (typeof PERMISSIONS)[number]; diff --git a/src/production/batch-quantity.ts b/src/production/batch-quantity.ts index 87aca1d..a898cb1 100644 --- a/src/production/batch-quantity.ts +++ b/src/production/batch-quantity.ts @@ -2,17 +2,27 @@ import { AppError } from '../common/errors/app-error'; const MAX_SCALED_QUANTITY = 999999999999n; +export function parseMaterialQuantity(quantity: string): bigint { + const match = /^(0|[1-9]\d{0,8})(?:\.(\d{1,3}))?$/.exec(quantity); + if (!match) throw new AppError('DATA_CONSTRAINT'); + return ( + BigInt(match[1]) * 1000n + BigInt((match[2] ?? '').padEnd(3, '0') || '0') + ); +} + +export function formatMaterialQuantity(scaled: bigint): string { + const sign = scaled < 0n ? '-' : ''; + const absolute = scaled < 0n ? -scaled : scaled; + return `${sign}${absolute / 1000n}.${(absolute % 1000n).toString().padStart(3, '0')}`; +} + export function plannedMaterialQuantity( quantity: string, factor: number, ): string { - const match = /^(0|[1-9]\d{0,8})(?:\.(\d{1,3}))?$/.exec(quantity); - if (!match || !Number.isSafeInteger(factor) || factor < 1) + if (!Number.isSafeInteger(factor) || factor < 1) throw new AppError('DATA_CONSTRAINT'); - const scaled = - (BigInt(match[1]) * 1000n + - BigInt((match[2] ?? '').padEnd(3, '0') || '0')) * - BigInt(factor); + const scaled = parseMaterialQuantity(quantity) * BigInt(factor); if (scaled > MAX_SCALED_QUANTITY) throw new AppError('BATCH_MATERIAL_LIMIT'); - return `${scaled / 1000n}.${(scaled % 1000n).toString().padStart(3, '0')}`; + return formatMaterialQuantity(scaled); } diff --git a/src/production/material-usage-summary.ts b/src/production/material-usage-summary.ts new file mode 100644 index 0000000..e86b6de --- /dev/null +++ b/src/production/material-usage-summary.ts @@ -0,0 +1,54 @@ +import { + formatMaterialQuantity, + parseMaterialQuantity, + plannedMaterialQuantity, +} from './batch-quantity'; + +type Quantity = { toString(): string }; +type BomLine = { + id: string; + materialId: string; + materialName: string; + materialCode: string; + unit: string; + quantity: Quantity; +}; +type Usage = { + bomLineId: string; + kind: 'CONSUMED' | 'WASTED'; + quantity: Quantity; +}; + +export function summarizeMaterialUsage( + lines: BomLine[], + events: Usage[], + factor: number, +) { + const totals = new Map(); + for (const event of events) { + const current = totals.get(event.bomLineId) ?? { consumed: 0n, wasted: 0n }; + current[event.kind === 'CONSUMED' ? 'consumed' : 'wasted'] += + parseMaterialQuantity(event.quantity.toString()); + totals.set(event.bomLineId, current); + } + return lines.map((line) => { + const planned = plannedMaterialQuantity(line.quantity.toString(), factor); + const { consumed, wasted } = totals.get(line.id) ?? { + consumed: 0n, + wasted: 0n, + }; + return { + bomLineId: line.id, + materialId: line.materialId, + materialName: line.materialName, + materialCode: line.materialCode, + unit: line.unit, + plannedQuantity: planned, + consumedQuantity: formatMaterialQuantity(consumed), + wastedQuantity: formatMaterialQuantity(wasted), + varianceQuantity: formatMaterialQuantity( + parseMaterialQuantity(planned) - consumed - wasted, + ), + }; + }); +} diff --git a/src/production/material-usage.controller.ts b/src/production/material-usage.controller.ts new file mode 100644 index 0000000..1329268 --- /dev/null +++ b/src/production/material-usage.controller.ts @@ -0,0 +1,47 @@ +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 { + materialUsageQuery, + materialUsageSchema, + type MaterialUsageInput, + type MaterialUsageQuery, +} from './material-usage.schemas'; +import { MaterialUsageStore } from './material-usage.store'; + +@Controller('production-batches/:batchId/material-usage') +export class MaterialUsageController { + constructor(private readonly usage: MaterialUsageStore) {} + + @Get() + @RequirePermission('production.read') + list( + @CurrentPrincipal() actor: Principal, + @Param('batchId', ParseUUIDPipe) batchId: string, + @Query(new SchemaPipe(materialUsageQuery)) query: MaterialUsageQuery, + ) { + return this.usage.list(actor, batchId, query); + } + + @Post() + @RequirePermission('production.material.record') + record( + @CurrentPrincipal() actor: Principal, + @Param('batchId', ParseUUIDPipe) batchId: string, + @Body(new SchemaPipe(materialUsageSchema)) input: MaterialUsageInput, + ) { + return this.usage.record(actor, batchId, input); + } +} diff --git a/src/production/material-usage.schemas.ts b/src/production/material-usage.schemas.ts new file mode 100644 index 0000000..e362a13 --- /dev/null +++ b/src/production/material-usage.schemas.ts @@ -0,0 +1,19 @@ +import { z } from 'zod'; +import { pageSchema } from '../identity/identity.schemas'; + +export const materialUsageSchema = z + .object({ + bomLineId: z.uuid(), + kind: z.enum(['CONSUMED', 'WASTED']), + quantity: z + .string() + .regex(/^(0|[1-9]\d{0,8})\.\d{3}$/) + .refine((value) => value !== '0.000'), + reason: z.string().trim().min(1).max(500).optional(), + idempotencyKey: z.uuid(), + }) + .strict(); + +export const materialUsageQuery = pageSchema.strict(); +export type MaterialUsageInput = z.infer; +export type MaterialUsageQuery = z.infer; diff --git a/src/production/material-usage.store.ts b/src/production/material-usage.store.ts new file mode 100644 index 0000000..272d394 --- /dev/null +++ b/src/production/material-usage.store.ts @@ -0,0 +1,147 @@ +import { createHash } from 'node:crypto'; +import { Injectable } from '@nestjs/common'; +import { AppError } from '../common/errors/app-error'; +import { DatabaseService } from '../database/database.service'; +import { AccessStore } from '../identity/access.store'; +import { recordAudit } from '../identity/audit'; +import type { Principal } from '../identity/identity.types'; +import type { + MaterialUsageInput, + MaterialUsageQuery, +} from './material-usage.schemas'; +import { summarizeMaterialUsage } from './material-usage-summary'; + +const MAX_USAGE_EVENTS = 500; +const usageSelect = { + id: true, + organizationId: true, + batchId: true, + bomLineId: true, + recordedById: true, + kind: true, + quantity: true, + reason: true, + idempotencyKey: true, + createdAt: true, +} as const; + +function requestHash(batchId: string, input: MaterialUsageInput) { + return createHash('sha256') + .update( + JSON.stringify({ + batchId, + bomLineId: input.bomLineId, + kind: input.kind, + quantity: input.quantity, + reason: input.reason ?? null, + }), + ) + .digest('hex'); +} + +@Injectable() +export class MaterialUsageStore { + constructor( + private readonly db: DatabaseService, + private readonly access: AccessStore, + ) {} + + async list(actor: Principal, batchId: string, query: MaterialUsageQuery) { + const batch = await this.db.productionBatch.findFirst({ + where: { id: batchId, organizationId: actor.organizationId }, + include: { + bom: { include: { lines: { orderBy: { materialCode: 'asc' } } } }, + }, + }); + if (!batch) throw new AppError('BATCH_NOT_FOUND'); + const events = await this.db.productionMaterialUsage.findMany({ + where: { organizationId: actor.organizationId, batchId }, + orderBy: [{ createdAt: 'asc' }, { id: 'asc' }], + select: usageSelect, + }); + return { + batchId, + total: events.length, + materials: summarizeMaterialUsage( + batch.bom.lines, + events, + batch.plannedQuantity / batch.bom.outputQuantity, + ), + events: events.slice(query.offset, query.offset + query.limit), + }; + } + + record(actor: Principal, batchId: string, input: MaterialUsageInput) { + return this.access.mutate( + actor, + 'production.material.record', + async (tx) => { + const batch = await tx.productionBatch.findFirst({ + where: { id: batchId, organizationId: actor.organizationId }, + select: { bomId: true, status: true }, + }); + if (!batch) throw new AppError('BATCH_NOT_FOUND'); + const hash = requestHash(batchId, input); + const previous = await tx.productionMaterialUsage.findFirst({ + where: { + organizationId: actor.organizationId, + idempotencyKey: input.idempotencyKey, + }, + select: { id: true, requestHash: true }, + }); + if (previous) { + if (previous.requestHash !== hash) + throw new AppError('USAGE_REPLAY_CONFLICT'); + return tx.productionMaterialUsage.findUniqueOrThrow({ + where: { id: previous.id }, + select: usageSelect, + }); + } + if (batch.status !== 'IN_PROGRESS') + throw new AppError('USAGE_BATCH_STATE'); + if (input.kind === 'WASTED' && !input.reason) + throw new AppError('USAGE_WASTE_REASON_REQUIRED'); + const line = await tx.productBomLine.findFirst({ + where: { + id: input.bomLineId, + bomId: batch.bomId, + organizationId: actor.organizationId, + }, + select: { id: true }, + }); + if (!line) throw new AppError('USAGE_LINE_NOT_FOUND'); + if ( + (await tx.productionMaterialUsage.count({ + where: { organizationId: actor.organizationId, batchId }, + })) >= MAX_USAGE_EVENTS + ) + throw new AppError('USAGE_EVENT_LIMIT'); + const event = await tx.productionMaterialUsage.create({ + data: { + organizationId: actor.organizationId, + batchId, + bomId: batch.bomId, + bomLineId: input.bomLineId, + recordedById: actor.userId, + kind: input.kind, + quantity: input.quantity, + reason: input.reason, + idempotencyKey: input.idempotencyKey, + requestHash: hash, + }, + select: usageSelect, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + input.kind === 'WASTED' + ? 'batch.material_wasted' + : 'batch.material_consumed', + event.id, + ); + return event; + }, + ); + } +} diff --git a/src/production/production.module.ts b/src/production/production.module.ts index 6bfaeed..70b3867 100644 --- a/src/production/production.module.ts +++ b/src/production/production.module.ts @@ -3,10 +3,12 @@ import { DatabaseModule } from '../database/database.module'; import { IdentityModule } from '../identity/identity.module'; import { BatchStore } from './batch.store'; import { BatchesController } from './batches.controller'; +import { MaterialUsageController } from './material-usage.controller'; +import { MaterialUsageStore } from './material-usage.store'; @Module({ imports: [DatabaseModule, IdentityModule], - providers: [BatchStore], - controllers: [BatchesController], + providers: [BatchStore, MaterialUsageStore], + controllers: [BatchesController, MaterialUsageController], }) export class ProductionModule {} diff --git a/test/helpers/production.ts b/test/helpers/production.ts new file mode 100644 index 0000000..aaf5d8f --- /dev/null +++ b/test/helpers/production.ts @@ -0,0 +1,56 @@ +import { randomUUID } from 'node:crypto'; +import type { IdentityApp } from './identity-app'; +import { seedProduct } from './commerce'; + +const auth = { type: 'bearer' as const }; + +export async function seedActiveBom(ctx: IdentityApp) { + const { variant } = await seedProduct(ctx); + const material = await ctx + .api() + .post('/api/v1/materials') + .auth(ctx.token, auth) + .send({ + code: `W-${randomUUID().slice(0, 8)}`, + name: 'Soy Wax', + kind: 'WAX', + unit: 'GRAM', + }) + .expect(201); + const bom = await ctx + .api() + .post(`/api/v1/variants/${variant.id}/boms`) + .auth(ctx.token, auth) + .send({ + outputQuantity: 10, + lines: [{ materialId: material.body.id, quantity: '125.000' }], + }) + .expect(201); + await ctx + .api() + .post(`/api/v1/boms/${bom.body.id}/activate`) + .auth(ctx.token, auth) + .expect(201); + return { + bomId: bom.body.id as string, + bomLineId: bom.body.lines[0].id as string, + materialId: material.body.id as string, + variantId: variant.id as string, + }; +} + +export function createBatch( + ctx: IdentityApp, + bomId: string, + plannedQuantity = 20, +) { + return ctx + .api() + .post('/api/v1/production-batches') + .auth(ctx.token, auth) + .send({ + bomId, + plannedQuantity, + reference: `B-${randomUUID().slice(0, 8)}`, + }); +} diff --git a/test/material-usage-summary.spec.ts b/test/material-usage-summary.spec.ts new file mode 100644 index 0000000..141bf12 --- /dev/null +++ b/test/material-usage-summary.spec.ts @@ -0,0 +1,48 @@ +import { summarizeMaterialUsage } from '../src/production/material-usage-summary'; +import { materialUsageSchema } from '../src/production/material-usage.schemas'; +import { randomUUID } from 'node:crypto'; + +describe('material usage arithmetic and input', () => { + const line = { + id: randomUUID(), + materialId: randomUUID(), + materialName: 'Wax', + materialCode: 'WAX', + unit: 'GRAM', + quantity: '125.000', + }; + it('uses exact three-decimal arithmetic and shows negative variance', () => { + const summary = summarizeMaterialUsage( + [line], + [ + { bomLineId: line.id, kind: 'CONSUMED', quantity: '250.001' }, + { bomLineId: line.id, kind: 'WASTED', quantity: '0.125' }, + ], + 2, + ); + expect(summary[0]).toMatchObject({ + plannedQuantity: '250.000', + consumedQuantity: '250.001', + wastedQuantity: '0.125', + varianceQuantity: '-0.126', + }); + }); + it('rejects zero, excessive precision and unknown fields', () => { + const input = { + bomLineId: line.id, + kind: 'CONSUMED', + quantity: '1.000', + idempotencyKey: randomUUID(), + }; + expect(materialUsageSchema.safeParse(input).success).toBe(true); + expect( + materialUsageSchema.safeParse({ ...input, quantity: '0.000' }).success, + ).toBe(false); + expect( + materialUsageSchema.safeParse({ ...input, quantity: '1.0001' }).success, + ).toBe(false); + expect( + materialUsageSchema.safeParse({ ...input, extra: true }).success, + ).toBe(false); + }); +}); diff --git a/test/material-usage.spec.ts b/test/material-usage.spec.ts new file mode 100644 index 0000000..08f55cb --- /dev/null +++ b/test/material-usage.spec.ts @@ -0,0 +1,175 @@ +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 usage API', () => { + let ctx: IdentityApp; + const auth = { type: 'bearer' as const }; + const seedStartedBatch = async () => { + const bom = await seedActiveBom(ctx); + const batch = await createBatch(ctx, bom.bomId).expect(201); + await ctx + .api() + .post(`/api/v1/production-batches/${batch.body.id}/start`) + .auth(ctx.token, auth) + .expect(201); + return { ...bom, batchId: batch.body.id as string }; + }; + const postUsage = (batchId: string, input: Record) => + ctx + .api() + .post(`/api/v1/production-batches/${batchId}/material-usage`) + .auth(ctx.token, auth) + .send(input); + + beforeAll(async () => { + ctx = await identityApp(); + }, 60000); + afterAll(async () => { + await ctx?.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + + it('records consumed and wasted material and summarizes plan versus actual', async () => { + const { batchId, bomLineId } = await seedStartedBatch(); + const consumed = await postUsage(batchId, { + bomLineId, + kind: 'CONSUMED', + quantity: '200.125', + idempotencyKey: randomUUID(), + }).expect(201); + expect(consumed.body).toMatchObject({ + kind: 'CONSUMED', + bomLineId, + quantity: '200.125', + }); + const wasted = await postUsage(batchId, { + bomLineId, + kind: 'WASTED', + quantity: '10.000', + reason: 'Spill', + idempotencyKey: randomUUID(), + }).expect(201); + expect(wasted.body.reason).toBe('Spill'); + const report = await ctx + .api() + .get( + `/api/v1/production-batches/${batchId}/material-usage?limit=1&offset=1`, + ) + .auth(ctx.token, auth) + .expect(200); + expect(report.body.total).toBe(2); + expect(report.body.events).toHaveLength(1); + expect(report.body.materials[0]).toMatchObject({ + plannedQuantity: '250.000', + consumedQuantity: '200.125', + wastedQuantity: '10.000', + varianceQuantity: '39.875', + }); + }); + + it('returns an idempotent retry but rejects a changed payload', async () => { + const { batchId, bomLineId } = await seedStartedBatch(); + const input = { + bomLineId, + kind: 'CONSUMED', + quantity: '125.000', + idempotencyKey: randomUUID(), + }; + const first = await postUsage(batchId, input).expect(201); + await ctx + .api() + .post(`/api/v1/production-batches/${batchId}/complete`) + .auth(ctx.token, auth) + .send({ goodQuantity: 20, rejectedQuantity: 0 }) + .expect(201); + const retry = await postUsage(batchId, input).expect(201); + expect(retry.body.id).toBe(first.body.id); + const conflict = await postUsage(batchId, { + ...input, + quantity: '126.000', + }).expect(409); + expect(conflict.body.code).toBe('USAGE_REPLAY_CONFLICT'); + expect( + await ctx.db.productionMaterialUsage.count({ where: { batchId } }), + ).toBe(1); + }); + + it('rejects wrong state, foreign BOM lines and missing waste reasons', async () => { + const bom = await seedActiveBom(ctx); + const batch = await createBatch(ctx, bom.bomId).expect(201); + const input = { + bomLineId: bom.bomLineId, + kind: 'CONSUMED', + quantity: '1.000', + idempotencyKey: randomUUID(), + }; + const draft = await postUsage(batch.body.id, input).expect(409); + expect(draft.body.code).toBe('USAGE_BATCH_STATE'); + await ctx + .api() + .post(`/api/v1/production-batches/${batch.body.id}/start`) + .auth(ctx.token, auth) + .expect(201); + const wrongLine = await postUsage(batch.body.id, { + ...input, + bomLineId: randomUUID(), + }).expect(404); + expect(wrongLine.body.code).toBe('USAGE_LINE_NOT_FOUND'); + const noReason = await postUsage(batch.body.id, { + ...input, + kind: 'WASTED', + }).expect(400); + expect(noReason.body.code).toBe('USAGE_WASTE_REASON_REQUIRED'); + }); + + it('separates recording permission and organization scope', async () => { + const { batchId, bomLineId } = await seedStartedBatch(); + const reader = await secondActor(ctx, true, ['production.read']); + await ctx + .api() + .get(`/api/v1/production-batches/${batchId}/material-usage`) + .auth(reader.token, auth) + .expect(200); + await ctx + .api() + .post(`/api/v1/production-batches/${batchId}/material-usage`) + .auth(reader.token, auth) + .send({ + bomLineId, + kind: 'CONSUMED', + quantity: '1.000', + idempotencyKey: randomUUID(), + }) + .expect(403); + const outsider = await secondActor(ctx, false, [ + 'production.read', + 'production.material.record', + ]); + const hidden = await ctx + .api() + .get(`/api/v1/production-batches/${batchId}/material-usage`) + .auth(outsider.token, auth) + .expect(404); + expect(hidden.body.code).toBe('BATCH_NOT_FOUND'); + }); + + it('keeps recorded usage immutable in PostgreSQL', async () => { + const { batchId, bomLineId } = await seedStartedBatch(); + const event = await postUsage(batchId, { + bomLineId, + kind: 'CONSUMED', + quantity: '1.000', + idempotencyKey: randomUUID(), + }).expect(201); + await expect( + ctx.db.productionMaterialUsage.update({ + where: { id: event.body.id }, + data: { quantity: '2.000' }, + }), + ).rejects.toThrow(); + }); +}); diff --git a/test/production-batches.spec.ts b/test/production-batches.spec.ts index 6146988..9912297 100644 --- a/test/production-batches.spec.ts +++ b/test/production-batches.spec.ts @@ -1,49 +1,14 @@ import { randomUUID } from 'node:crypto'; import { identityApp, type IdentityApp } from './helpers/identity-app'; -import { secondActor, seedProduct } from './helpers/commerce'; +import { secondActor } from './helpers/commerce'; +import { createBatch as makeBatch, seedActiveBom } from './helpers/production'; describe('production batch API', () => { let ctx: IdentityApp; const auth = { type: 'bearer' as const }; - const createActiveBom = async () => { - const { variant } = await seedProduct(ctx); - const material = await ctx - .api() - .post('/api/v1/materials') - .auth(ctx.token, auth) - .send({ - code: `W-${randomUUID().slice(0, 8)}`, - name: 'Soy Wax', - kind: 'WAX', - unit: 'GRAM', - }) - .expect(201); - const bom = await ctx - .api() - .post(`/api/v1/variants/${variant.id}/boms`) - .auth(ctx.token, auth) - .send({ - outputQuantity: 10, - lines: [{ materialId: material.body.id, quantity: '125.000' }], - }) - .expect(201); - await ctx - .api() - .post(`/api/v1/boms/${bom.body.id}/activate`) - .auth(ctx.token, auth) - .expect(201); - return { bomId: bom.body.id as string, variantId: variant.id as string }; - }; + const createActiveBom = () => seedActiveBom(ctx); const createBatch = (bomId: string, plannedQuantity = 20) => - ctx - .api() - .post('/api/v1/production-batches') - .auth(ctx.token, auth) - .send({ - bomId, - plannedQuantity, - reference: `B-${randomUUID().slice(0, 8)}`, - }); + makeBatch(ctx, bomId, plannedQuantity); beforeAll(async () => { ctx = await identityApp();