From a90b30df7c9bda8765edc5d09aabe4927d3e21b9 Mon Sep 17 00:00:00 2001 From: mihir Date: Tue, 29 Sep 2026 11:51:23 +0530 Subject: [PATCH 1/2] feat(production): record packaging execution for completed batches --- README.md | 1 + docs/packaging-execution-api.md | 29 +++ docs/roadmap.md | 1 + prisma/bom.prisma | 2 + prisma/migration-checksums.json | 3 +- .../migration.sql | 66 +++++++ prisma/packaging-run.prisma | 35 ++++ prisma/production.prisma | 1 + prisma/schema.prisma | 2 + src/common/errors/commerce-errors.ts | 40 ++++ src/identity/permissions.ts | 1 + src/production/packaging-run.controller.ts | 43 ++++ src/production/packaging-run.schemas.ts | 23 +++ src/production/packaging-run.store.ts | 185 +++++++++++++++++ src/production/production.module.ts | 10 +- test/packaging-run.spec.ts | 187 ++++++++++++++++++ 16 files changed, 626 insertions(+), 3 deletions(-) create mode 100644 docs/packaging-execution-api.md create mode 100644 prisma/migrations/20260929013000_packaging_execution/migration.sql create mode 100644 prisma/packaging-run.prisma create mode 100644 src/production/packaging-run.controller.ts create mode 100644 src/production/packaging-run.schemas.ts create mode 100644 src/production/packaging-run.store.ts create mode 100644 test/packaging-run.spec.ts diff --git a/README.md b/README.md index 0cdfc50..8dcbdd6 100644 --- a/README.md +++ b/README.md @@ -47,3 +47,4 @@ For a development owner, see [local admin setup](docs/local-admin.md). ### Swagger UI Open http://localhost:3000/api/docs in development to browse and test the API. See [API explorer](docs/swagger.md) for authentication and configuration. +Packaging execution: see [Phase 2K API guide](docs/packaging-execution-api.md). diff --git a/docs/packaging-execution-api.md b/docs/packaging-execution-api.md new file mode 100644 index 0000000..a4b10fc --- /dev/null +++ b/docs/packaging-execution-api.md @@ -0,0 +1,29 @@ +# Packaging execution (Phase 2K) + +After a production batch is completed, record the packaging and label materials used for its good output. One immutable record is allowed per batch. The selected packaging BOM must be active for the batch's variant when recorded; its revision and line identities remain attached afterward. + +| Method | Path | Permission | +| ------ | ----------------------------------------------- | ------------------ | +| GET | `/api/v1/production-batches/:batchId/packaging` | `packaging.read` | +| POST | `/api/v1/production-batches/:batchId/packaging` | `packaging.record` | + +Example POST: + +```json +{ + "bomId": "", + "idempotencyKey": "", + "lines": [ + { + "bomLineId": "", + "usedQuantity": "19.000", + "wastedQuantity": "1.000", + "wasteReason": "Torn box" + } + ] +} +``` + +Submit every BOM line exactly once. Quantities are nonnegative, use exactly three decimal places, and use the line's material unit. Waste needs a reason. Good output must be a positive multiple of the packaging BOM output quantity. The response provides planned, used, wasted, and variance quantities for each line. An exact idempotent retry returns the existing record; a changed request with the same key returns `PACKAGING_REPLAY_CONFLICT`. + +Packaging records are operational observations. They do not deduct physical stock or calculate costs. Those remain separate milestones pending a stock-location and costing policy. diff --git a/docs/roadmap.md b/docs/roadmap.md index 45a4b43..3e8f4c3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -24,6 +24,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase - 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. - 2J (implemented): separate versioned packaging BOMs for packaging and label materials, with independent activation and permissions. Packaging execution, physical stock posting and costing remain later milestones. +- 2K (implemented): immutable packaging execution for completed batches, with BOM-line reconciliation, quantity variance, and idempotent retries. Physical stock posting and costing remain later milestones. ## Phase 3: B2B and white label diff --git a/prisma/bom.prisma b/prisma/bom.prisma index eb64a09..1f5bfbb 100644 --- a/prisma/bom.prisma +++ b/prisma/bom.prisma @@ -25,6 +25,7 @@ model ProductBom { createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict) lines ProductBomLine[] batches ProductionBatch[] + packagingRuns PackagingRun[] @@unique([variantId, kind, revision]) @@unique([id, organizationId]) @@index([organizationId, variantId, createdAt, id]) @@ -43,6 +44,7 @@ model ProductBomLine { bom ProductBom @relation(fields: [bomId, organizationId], references: [id, organizationId], onDelete: Restrict) material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict) materialUsage ProductionMaterialUsage[] + packagingRunLines PackagingRunLine[] @@unique([bomId, materialId]) @@unique([id, bomId, organizationId]) @@index([organizationId, materialId]) diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index e809be0..26fd099 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -23,5 +23,6 @@ "20260928153219_product_boms": "b548e6e5c2f11b52374ba0ad3eedbc127244b2752f07cdcd8bf951641d4525a1", "20260928183508_production_batches": "53b3fbabe17d3270ae3c5d74393a07abb28858ca2af8d3a1aa19c92686c84a0a", "20260928190933_material_usage": "950a2f1861e88c052b1e4d40aff178524c3a7c198e9fb27a3c47cb77fb984e1e", - "20260928193354_packaging_boms": "1f78a1f42b905ea7d371fadba6180a9f756fc4c360a04b92d58b37ec1dd2bad3" + "20260928193354_packaging_boms": "1f78a1f42b905ea7d371fadba6180a9f756fc4c360a04b92d58b37ec1dd2bad3", + "20260929013000_packaging_execution": "63c0fb096c769478ba9422fb606fd421188abd70eeef1375dd07bef2cbc731c1" } diff --git a/prisma/migrations/20260929013000_packaging_execution/migration.sql b/prisma/migrations/20260929013000_packaging_execution/migration.sql new file mode 100644 index 0000000..23a4154 --- /dev/null +++ b/prisma/migrations/20260929013000_packaging_execution/migration.sql @@ -0,0 +1,66 @@ +CREATE TABLE "packaging_runs" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "batch_id" UUID NOT NULL, + "bom_id" UUID NOT NULL, + "recorded_by_id" UUID NOT NULL, + "idempotency_key" UUID NOT NULL, + "request_hash" CHAR(64) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "packaging_runs_pkey" PRIMARY KEY ("id"), + CONSTRAINT "packaging_runs_hash_check" CHECK ("request_hash" ~ '^[a-f0-9]{64}$') +); +CREATE UNIQUE INDEX "packaging_runs_batch_id_key" ON "packaging_runs"("batch_id"); +CREATE UNIQUE INDEX "packaging_runs_batch_id_organization_id_key" ON "packaging_runs"("batch_id", "organization_id"); +CREATE UNIQUE INDEX "packaging_runs_organization_id_idempotency_key_key" ON "packaging_runs"("organization_id", "idempotency_key"); +CREATE UNIQUE INDEX "packaging_runs_id_bom_id_organization_id_key" ON "packaging_runs"("id", "bom_id", "organization_id"); +CREATE INDEX "packaging_runs_organization_id_created_at_id_idx" ON "packaging_runs"("organization_id", "created_at", "id"); +ALTER TABLE "packaging_runs" ADD CONSTRAINT "packaging_runs_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "packaging_runs" ADD CONSTRAINT "packaging_runs_batch_id_organization_id_fkey" FOREIGN KEY ("batch_id", "organization_id") REFERENCES "production_batches"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "packaging_runs" ADD CONSTRAINT "packaging_runs_bom_id_organization_id_fkey" FOREIGN KEY ("bom_id", "organization_id") REFERENCES "product_boms"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "packaging_runs" ADD CONSTRAINT "packaging_runs_recorded_by_id_organization_id_fkey" FOREIGN KEY ("recorded_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE TABLE "packaging_run_lines" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "run_id" UUID NOT NULL, + "bom_id" UUID NOT NULL, + "bom_line_id" UUID NOT NULL, + "used_quantity" DECIMAL(12,3) NOT NULL, + "wasted_quantity" DECIMAL(12,3) NOT NULL, + "waste_reason" VARCHAR(500), + CONSTRAINT "packaging_run_lines_pkey" PRIMARY KEY ("id"), + CONSTRAINT "packaging_run_lines_values" CHECK ( + "used_quantity" >= 0 AND "wasted_quantity" >= 0 + AND ("wasted_quantity" = 0 OR ("waste_reason" IS NOT NULL AND LENGTH(TRIM("waste_reason")) > 0)) + ) +); +CREATE UNIQUE INDEX "packaging_run_lines_run_id_bom_line_id_key" ON "packaging_run_lines"("run_id", "bom_line_id"); +ALTER TABLE "packaging_run_lines" ADD CONSTRAINT "packaging_run_lines_run_id_bom_id_organization_id_fkey" FOREIGN KEY ("run_id", "bom_id", "organization_id") REFERENCES "packaging_runs"("id", "bom_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "packaging_run_lines" ADD CONSTRAINT "packaging_run_lines_bom_line_id_bom_id_organization_id_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; + +CREATE FUNCTION guard_packaging_run() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Packaging runs are immutable'; END IF; + IF NOT EXISTS ( + SELECT 1 FROM production_batches b JOIN product_boms p ON p.id = NEW.bom_id AND p.organization_id = NEW.organization_id + WHERE b.id = NEW.batch_id AND b.organization_id = NEW.organization_id + AND b.status = 'COMPLETED' AND p.kind = 'PACKAGING' AND p.variant_id = ( + SELECT variant_id FROM product_boms WHERE id = b.bom_id + ) + ) THEN RAISE EXCEPTION 'Packaging run requires a completed matching production batch'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER packaging_runs_guard BEFORE INSERT OR UPDATE OR DELETE ON packaging_runs FOR EACH ROW EXECUTE FUNCTION guard_packaging_run(); + +CREATE FUNCTION guard_packaging_run_line() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Packaging run lines are immutable'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER packaging_run_lines_guard BEFORE INSERT OR UPDATE OR DELETE ON packaging_run_lines FOR EACH ROW EXECUTE FUNCTION guard_packaging_run_line(); + +UPDATE "roles" SET "permissions" = array_append("permissions", 'packaging.record') +WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('packaging.record' = ANY("permissions")); diff --git a/prisma/packaging-run.prisma b/prisma/packaging-run.prisma new file mode 100644 index 0000000..e198c0c --- /dev/null +++ b/prisma/packaging-run.prisma @@ -0,0 +1,35 @@ +model PackagingRun { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + batchId String @unique @map("batch_id") @db.Uuid + bomId String @map("bom_id") @db.Uuid + recordedById String @map("recorded_by_id") @db.Uuid + idempotencyKey String @map("idempotency_key") @db.Uuid + requestHash String @map("request_hash") @db.Char(64) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict) + batch ProductionBatch @relation(fields: [batchId, organizationId], references: [id, organizationId], onDelete: Restrict) + bom ProductBom @relation(fields: [bomId, organizationId], references: [id, organizationId], onDelete: Restrict) + recordedBy User @relation(fields: [recordedById, organizationId], references: [id, organizationId], onDelete: Restrict) + lines PackagingRunLine[] + @@unique([organizationId, idempotencyKey]) + @@unique([batchId, organizationId]) + @@unique([id, bomId, organizationId]) + @@index([organizationId, createdAt, id]) + @@map("packaging_runs") +} + +model PackagingRunLine { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + runId String @map("run_id") @db.Uuid + bomId String @map("bom_id") @db.Uuid + bomLineId String @map("bom_line_id") @db.Uuid + usedQuantity Decimal @map("used_quantity") @db.Decimal(12,3) + wastedQuantity Decimal @map("wasted_quantity") @db.Decimal(12,3) + wasteReason String? @map("waste_reason") @db.VarChar(500) + run PackagingRun @relation(fields: [runId, bomId, organizationId], references: [id, bomId, organizationId], onDelete: Restrict) + bomLine ProductBomLine @relation(fields: [bomLineId, bomId, organizationId], references: [id, bomId, organizationId], onDelete: Restrict) + @@unique([runId, bomLineId]) + @@map("packaging_run_lines") +} diff --git a/prisma/production.prisma b/prisma/production.prisma index 6b87ad9..1e8f0a6 100644 --- a/prisma/production.prisma +++ b/prisma/production.prisma @@ -22,6 +22,7 @@ model ProductionBatch { completion ProductionBatchCompletion? cancellation ProductionBatchCancellation? materialUsage ProductionMaterialUsage[] + packagingRun PackagingRun? @@unique([organizationId, reference]) @@unique([id, organizationId]) @@unique([id, bomId, organizationId]) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 5d985f2..0236501 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -41,6 +41,7 @@ model Organization { productionBatchCompletions ProductionBatchCompletion[] productionBatchCancellations ProductionBatchCancellation[] productionMaterialUsage ProductionMaterialUsage[] + packagingRuns PackagingRun[] @@map("organizations") } model User { @@ -73,6 +74,7 @@ model User { productionBatchCompletions ProductionBatchCompletion[] productionBatchCancellations ProductionBatchCancellation[] productionMaterialUsage ProductionMaterialUsage[] + packagingRuns PackagingRun[] stockEntries StockLedger[] stockReservations StockReservation[] carts Cart[] diff --git a/src/common/errors/commerce-errors.ts b/src/common/errors/commerce-errors.ts index 80377c3..47878b4 100644 --- a/src/common/errors/commerce-errors.ts +++ b/src/common/errors/commerce-errors.ts @@ -431,4 +431,44 @@ export const COMMERCE_ERRORS = { 'Idempotency key was used for different material usage', 'Production material usage idempotency payload mismatch', ], + PACKAGING_RUN_NOT_FOUND: [ + 404, + 'Packaging record not found', + 'Packaging run scoped lookup failed', + ], + PACKAGING_BATCH_STATE: [ + 409, + 'Packaging requires a completed batch', + 'Packaging batch state rejected', + ], + PACKAGING_BOM_MISMATCH: [ + 409, + 'Packaging BOM must be active for this variant', + 'Packaging BOM eligibility failed', + ], + PACKAGING_YIELD_MISMATCH: [ + 409, + 'Good quantity must be a multiple of packaging BOM yield', + 'Packaging yield mismatch', + ], + PACKAGING_LINES_MISMATCH: [ + 400, + 'Provide every packaging BOM line exactly once', + 'Packaging line reconciliation failed', + ], + PACKAGING_WASTE_REASON_REQUIRED: [ + 400, + 'Give a reason for wasted packaging', + 'Packaging waste reason missing', + ], + PACKAGING_ALREADY_RECORDED: [ + 409, + 'Packaging is already recorded for this batch', + 'Packaging batch duplicate rejected', + ], + PACKAGING_REPLAY_CONFLICT: [ + 409, + 'Idempotency key was used for different packaging', + 'Packaging idempotency payload mismatch', + ], } as const; diff --git a/src/identity/permissions.ts b/src/identity/permissions.ts index 8d0b9f2..5acc22c 100644 --- a/src/identity/permissions.ts +++ b/src/identity/permissions.ts @@ -30,6 +30,7 @@ export const PERMISSIONS = [ 'bom.manage', 'packaging.read', 'packaging.manage', + 'packaging.record', 'production.read', 'production.manage', 'production.material.record', diff --git a/src/production/packaging-run.controller.ts b/src/production/packaging-run.controller.ts new file mode 100644 index 0000000..7614473 --- /dev/null +++ b/src/production/packaging-run.controller.ts @@ -0,0 +1,43 @@ +import { + Body, + Controller, + Get, + Param, + ParseUUIDPipe, + Post, +} from '@nestjs/common'; +import { SchemaPipe } from '../common/validation.pipe'; +import { + CurrentPrincipal, + RequirePermission, +} from '../identity/access.decorator'; +import type { Principal } from '../identity/identity.types'; +import { + packagingRunSchema, + type PackagingRunInput, +} from './packaging-run.schemas'; +import { PackagingRunStore } from './packaging-run.store'; + +@Controller('production-batches/:batchId/packaging') +export class PackagingRunController { + constructor(private readonly runs: PackagingRunStore) {} + + @Get() + @RequirePermission('packaging.read') + find( + @CurrentPrincipal() actor: Principal, + @Param('batchId', ParseUUIDPipe) batchId: string, + ) { + return this.runs.find(actor, batchId); + } + + @Post() + @RequirePermission('packaging.record') + record( + @CurrentPrincipal() actor: Principal, + @Param('batchId', ParseUUIDPipe) batchId: string, + @Body(new SchemaPipe(packagingRunSchema)) input: PackagingRunInput, + ) { + return this.runs.record(actor, batchId, input); + } +} diff --git a/src/production/packaging-run.schemas.ts b/src/production/packaging-run.schemas.ts new file mode 100644 index 0000000..6034e04 --- /dev/null +++ b/src/production/packaging-run.schemas.ts @@ -0,0 +1,23 @@ +import { z } from 'zod'; + +const quantity = z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/); +export const packagingRunSchema = z + .object({ + bomId: z.uuid(), + idempotencyKey: z.uuid(), + lines: z + .array( + z + .object({ + bomLineId: z.uuid(), + usedQuantity: quantity, + wastedQuantity: quantity, + wasteReason: z.string().trim().min(1).max(500).optional(), + }) + .strict(), + ) + .min(1) + .max(100), + }) + .strict(); +export type PackagingRunInput = z.infer; diff --git a/src/production/packaging-run.store.ts b/src/production/packaging-run.store.ts new file mode 100644 index 0000000..a0fa026 --- /dev/null +++ b/src/production/packaging-run.store.ts @@ -0,0 +1,185 @@ +import { createHash } from 'node:crypto'; +import { Injectable } from '@nestjs/common'; +import { AppError } from '../common/errors/app-error'; +import { DatabaseService } from '../database/database.service'; +import type { Prisma } from '../generated/prisma/client'; +import { AccessStore } from '../identity/access.store'; +import { recordAudit } from '../identity/audit'; +import type { Principal } from '../identity/identity.types'; +import { + formatMaterialQuantity, + parseMaterialQuantity, + plannedMaterialQuantity, +} from './batch-quantity'; +import type { PackagingRunInput } from './packaging-run.schemas'; + +const runView = { + lines: { include: { bomLine: true }, orderBy: { bomLineId: 'asc' as const } }, + bom: true, + batch: { include: { completion: true } }, +}; + +function requestHash(batchId: string, input: PackagingRunInput) { + return createHash('sha256') + .update( + JSON.stringify({ + batchId, + bomId: input.bomId, + lines: [...input.lines] + .sort((a, b) => a.bomLineId.localeCompare(b.bomLineId)) + .map((line) => ({ + bomLineId: line.bomLineId, + usedQuantity: line.usedQuantity, + wastedQuantity: line.wastedQuantity, + wasteReason: line.wasteReason ?? null, + })), + }), + ) + .digest('hex'); +} + +type RunView = Prisma.PackagingRunGetPayload<{ include: typeof runView }>; +function present(run: RunView) { + const factor = run.batch.completion!.goodQuantity / run.bom.outputQuantity; + return { + id: run.id, + organizationId: run.organizationId, + batchId: run.batchId, + bomId: run.bomId, + recordedById: run.recordedById, + createdAt: run.createdAt, + lines: run.lines.map((line) => { + const planned = plannedMaterialQuantity( + line.bomLine.quantity.toString(), + factor, + ); + return { + bomLineId: line.bomLineId, + materialId: line.bomLine.materialId, + materialCode: line.bomLine.materialCode, + materialName: line.bomLine.materialName, + unit: line.bomLine.unit, + plannedQuantity: planned, + usedQuantity: formatMaterialQuantity( + parseMaterialQuantity(line.usedQuantity.toString()), + ), + wastedQuantity: formatMaterialQuantity( + parseMaterialQuantity(line.wastedQuantity.toString()), + ), + wasteReason: line.wasteReason, + varianceQuantity: formatMaterialQuantity( + parseMaterialQuantity(planned) - + parseMaterialQuantity(line.usedQuantity.toString()) - + parseMaterialQuantity(line.wastedQuantity.toString()), + ), + }; + }), + }; +} + +@Injectable() +export class PackagingRunStore { + constructor( + private readonly db: DatabaseService, + private readonly access: AccessStore, + ) {} + + async find(actor: Principal, batchId: string) { + const run = await this.db.packagingRun.findFirst({ + where: { batchId, organizationId: actor.organizationId }, + include: runView, + }); + if (!run) throw new AppError('PACKAGING_RUN_NOT_FOUND'); + return present(run); + } + + record(actor: Principal, batchId: string, input: PackagingRunInput) { + return this.access.mutate(actor, 'packaging.record', async (tx) => { + const hash = requestHash(batchId, input); + const previous = await tx.packagingRun.findFirst({ + where: { + organizationId: actor.organizationId, + idempotencyKey: input.idempotencyKey, + }, + include: runView, + }); + if (previous) { + if (previous.requestHash !== hash) + throw new AppError('PACKAGING_REPLAY_CONFLICT'); + return present(previous); + } + const batch = await tx.productionBatch.findFirst({ + where: { id: batchId, organizationId: actor.organizationId }, + include: { bom: { select: { variantId: true } }, completion: true }, + }); + if (!batch) throw new AppError('BATCH_NOT_FOUND'); + if (batch.status !== 'COMPLETED' || !batch.completion) + throw new AppError('PACKAGING_BATCH_STATE'); + if ( + await tx.packagingRun.findUnique({ + where: { batchId }, + select: { id: true }, + }) + ) + throw new AppError('PACKAGING_ALREADY_RECORDED'); + const bom = await tx.productBom.findFirst({ + where: { id: input.bomId, organizationId: actor.organizationId }, + include: { lines: true }, + }); + if ( + !bom || + bom.kind !== 'PACKAGING' || + bom.status !== 'ACTIVE' || + bom.variantId !== batch.bom.variantId + ) + throw new AppError('PACKAGING_BOM_MISMATCH'); + if ( + batch.completion.goodQuantity === 0 || + batch.completion.goodQuantity % bom.outputQuantity !== 0 + ) + throw new AppError('PACKAGING_YIELD_MISMATCH'); + const ids = new Set(input.lines.map((line) => line.bomLineId)); + if ( + ids.size !== bom.lines.length || + input.lines.length !== bom.lines.length || + bom.lines.some((line) => !ids.has(line.id)) + ) + throw new AppError('PACKAGING_LINES_MISMATCH'); + for (const line of input.lines) { + if (line.wastedQuantity !== '0.000' && !line.wasteReason) + throw new AppError('PACKAGING_WASTE_REASON_REQUIRED'); + } + const run = await tx.packagingRun.create({ + data: { + organizationId: actor.organizationId, + batchId, + bomId: bom.id, + recordedById: actor.userId, + idempotencyKey: input.idempotencyKey, + requestHash: hash, + }, + }); + await tx.packagingRunLine.createMany({ + data: input.lines.map((line) => ({ + ...line, + organizationId: actor.organizationId, + runId: run.id, + bomId: bom.id, + })), + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'batch.packaging_recorded', + run.id, + ); + return present( + await tx.packagingRun.findUniqueOrThrow({ + where: { id: run.id }, + include: runView, + }), + ); + }); + } +} diff --git a/src/production/production.module.ts b/src/production/production.module.ts index 70b3867..fb59d1d 100644 --- a/src/production/production.module.ts +++ b/src/production/production.module.ts @@ -5,10 +5,16 @@ import { BatchStore } from './batch.store'; import { BatchesController } from './batches.controller'; import { MaterialUsageController } from './material-usage.controller'; import { MaterialUsageStore } from './material-usage.store'; +import { PackagingRunController } from './packaging-run.controller'; +import { PackagingRunStore } from './packaging-run.store'; @Module({ imports: [DatabaseModule, IdentityModule], - providers: [BatchStore, MaterialUsageStore], - controllers: [BatchesController, MaterialUsageController], + providers: [BatchStore, MaterialUsageStore, PackagingRunStore], + controllers: [ + BatchesController, + MaterialUsageController, + PackagingRunController, + ], }) export class ProductionModule {} diff --git a/test/packaging-run.spec.ts b/test/packaging-run.spec.ts new file mode 100644 index 0000000..fc406cf --- /dev/null +++ b/test/packaging-run.spec.ts @@ -0,0 +1,187 @@ +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('packaging execution API', () => { + let ctx: IdentityApp; + const auth = { type: 'bearer' as const }; + const seed = async () => { + const production = await seedActiveBom(ctx); + const material = await ctx + .api() + .post('/api/v1/materials') + .auth(ctx.token, auth) + .send({ + code: `P-${randomUUID().slice(0, 8)}`, + name: 'Gift box', + kind: 'PACKAGING', + unit: 'PIECE', + }) + .expect(201); + const bom = await ctx + .api() + .post(`/api/v1/variants/${production.variantId}/packaging-boms`) + .auth(ctx.token, auth) + .send({ + outputQuantity: 10, + lines: [{ materialId: material.body.id, quantity: '10.000' }], + }) + .expect(201); + await ctx + .api() + .post(`/api/v1/packaging-boms/${bom.body.id}/activate`) + .auth(ctx.token, auth) + .expect(201); + const batch = await createBatch(ctx, production.bomId).expect(201); + return { + batchId: batch.body.id as string, + bomId: bom.body.id as string, + lineId: bom.body.lines[0].id as string, + }; + }; + const complete = async (batchId: string, goodQuantity = 20) => { + await ctx + .api() + .post(`/api/v1/production-batches/${batchId}/start`) + .auth(ctx.token, auth) + .expect(201); + await ctx + .api() + .post(`/api/v1/production-batches/${batchId}/complete`) + .auth(ctx.token, auth) + .send({ + goodQuantity, + rejectedQuantity: 20 - goodQuantity, + ...(goodQuantity < 20 ? { rejectionReason: 'Damaged' } : {}), + }) + .expect(201); + }; + const input = (bomId: string, lineId: string) => ({ + bomId, + idempotencyKey: randomUUID(), + lines: [ + { + bomLineId: lineId, + usedQuantity: '19.000', + wastedQuantity: '1.000', + wasteReason: 'Torn', + }, + ], + }); + const record = (batchId: string, body: object) => + ctx + .api() + .post(`/api/v1/production-batches/${batchId}/packaging`) + .auth(ctx.token, auth) + .send(body); + + beforeAll(async () => { + ctx = await identityApp(); + }, 60000); + afterAll(async () => { + await ctx?.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + + it('records immutable packaging use and exact plan variance', async () => { + const { batchId, bomId, lineId } = await seed(); + await complete(batchId); + const body = input(bomId, lineId); + const first = await record(batchId, body).expect(201); + expect(first.body.lines[0]).toMatchObject({ + plannedQuantity: '20.000', + usedQuantity: '19.000', + wastedQuantity: '1.000', + varianceQuantity: '0.000', + }); + const retry = await record(batchId, body).expect(201); + expect(retry.body.id).toBe(first.body.id); + const found = await ctx + .api() + .get(`/api/v1/production-batches/${batchId}/packaging`) + .auth(ctx.token, auth) + .expect(200); + expect(found.body.id).toBe(first.body.id); + }); + + it('rejects wrong state, mismatched BOM, missing lines and waste reason', async () => { + const { batchId, bomId, lineId } = await seed(); + const draft = await record(batchId, input(bomId, lineId)).expect(409); + expect(draft.body.code).toBe('PACKAGING_BATCH_STATE'); + await complete(batchId); + const wrongBom = await record(batchId, input(randomUUID(), lineId)).expect( + 409, + ); + expect(wrongBom.body.code).toBe('PACKAGING_BOM_MISMATCH'); + const wrongLines = await record(batchId, { + ...input(bomId, lineId), + lines: [ + { + bomLineId: randomUUID(), + usedQuantity: '1.000', + wastedQuantity: '0.000', + }, + ], + }).expect(400); + expect(wrongLines.body.code).toBe('PACKAGING_LINES_MISMATCH'); + const noReason = await record(batchId, { + ...input(bomId, lineId), + lines: [ + { bomLineId: lineId, usedQuantity: '1.000', wastedQuantity: '1.000' }, + ], + }).expect(400); + expect(noReason.body.code).toBe('PACKAGING_WASTE_REASON_REQUIRED'); + }); + + it('rejects output that cannot be scaled to the packaging BOM yield', async () => { + const { batchId, bomId, lineId } = await seed(); + await complete(batchId, 19); + const response = await record(batchId, input(bomId, lineId)).expect(409); + expect(response.body.code).toBe('PACKAGING_YIELD_MISMATCH'); + }); + + it('enforces one record, idempotency payload, permission and organization scope', async () => { + const { batchId, bomId, lineId } = await seed(); + await complete(batchId); + const reader = await secondActor(ctx, true, ['packaging.read']); + await ctx + .api() + .post(`/api/v1/production-batches/${batchId}/packaging`) + .auth(reader.token, auth) + .send(input(bomId, lineId)) + .expect(403); + const outsider = await secondActor(ctx, false, ['packaging.read']); + await ctx + .api() + .get(`/api/v1/production-batches/${batchId}/packaging`) + .auth(outsider.token, auth) + .expect(404); + const body = input(bomId, lineId); + await record(batchId, body).expect(201); + const changed = await record(batchId, { + ...body, + lines: [{ ...body.lines[0], usedQuantity: '18.000' }], + }).expect(409); + expect(changed.body.code).toBe('PACKAGING_REPLAY_CONFLICT'); + const duplicate = await record(batchId, input(bomId, lineId)).expect(409); + expect(duplicate.body.code).toBe('PACKAGING_ALREADY_RECORDED'); + }); + + it('keeps packaging records immutable in PostgreSQL', async () => { + const { batchId, bomId, lineId } = await seed(); + await complete(batchId); + const run = await record(batchId, input(bomId, lineId)).expect(201); + const line = await ctx.db.packagingRunLine.findFirstOrThrow({ + where: { runId: run.body.id }, + }); + await expect( + ctx.db.packagingRunLine.update({ + where: { id: line.id }, + data: { usedQuantity: '1.000' }, + }), + ).rejects.toThrow(); + }); +}); -- 2.40.1 From 6eca98866471a8f452476b13a99fe1b2e9c15aaa Mon Sep 17 00:00:00 2001 From: mihir Date: Tue, 29 Sep 2026 12:41:07 +0530 Subject: [PATCH 2/2] fix(deps): update vulnerable mailer and upload packages --- package.json | 2 +- pnpm-lock.yaml | 69 +++++++-------------------------------------- pnpm-workspace.yaml | 2 +- 3 files changed, 12 insertions(+), 61 deletions(-) diff --git a/package.json b/package.json index c29c1ca..a275eb0 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,7 @@ "@prisma/client": "^7.0.0", "dotenv": "^17.0.0", "helmet": "^8.0.0", - "nodemailer": "^10.0.1", + "nodemailer": "^10.0.2", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.2", "zod": "^4.0.0" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 03f8410..cdd4805 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,7 +7,7 @@ settings: overrides: '@prisma/config>deepmerge-ts': 8.0.0 prisma>mysql2: 3.23.1 - '@nestjs/platform-express>multer': 2.3.0 + '@nestjs/platform-express>multer': 2.4.0 importers: @@ -38,8 +38,8 @@ importers: specifier: ^8.0.0 version: 8.3.0 nodemailer: - specifier: ^10.0.1 - version: 10.0.1 + specifier: ^10.0.2 + version: 10.0.11 reflect-metadata: specifier: ^0.2.2 version: 0.2.2 @@ -1360,9 +1360,6 @@ packages: bser@2.1.1: resolution: {integrity: sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==} - buffer-from@1.1.2: - resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} - busboy@1.6.0: resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==} engines: {node: '>=10.16.0'} @@ -1449,10 +1446,6 @@ packages: component-emitter@1.3.1: resolution: {integrity: sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==} - concat-stream@2.0.0: - resolution: {integrity: sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==} - engines: {'0': node >= 6.0} - confbox@0.2.4: resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==} @@ -2224,8 +2217,8 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - multer@2.3.0: - resolution: {integrity: sha512-cjNbm3sttszgZeGfJR124D+jFEfkXCVAsoPBmFn9X7UxmDSFHWqE2CoEj0vrmSpuAFnqWR1Szcm9QTsiHr60Xw==} + multer@2.4.0: + resolution: {integrity: sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==} engines: {node: '>= 10.16.0'} mysql2@3.23.1: @@ -2263,8 +2256,8 @@ packages: resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==} engines: {node: '>=18'} - nodemailer@10.0.1: - resolution: {integrity: sha512-c+gU9cL9HLDax3vjxL88kW+6NOgdtEUWaZ+AUtxdJR6LLhf0kGdCLExof7yiKW7zdO9EfXCSIgmhGyFmUM0mYQ==} + nodemailer@10.0.11: + resolution: {integrity: sha512-/c4P7U7aGpiNu2Rl08q525q2zECkUpSaf2zQPgIStCcAjHAkkQQKwD4sTyi3l91mGcLQrKzL1syXPHymo+Ogtw==} engines: {node: '>=20.0.0'} normalize-path@3.0.0: @@ -2494,10 +2487,6 @@ packages: resolution: {integrity: sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==} engines: {node: '>=0.10.0'} - readable-stream@3.6.2: - resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} - engines: {node: '>= 6'} - readdirp@5.1.1: resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==} engines: {node: '>= 20.19.0'} @@ -2542,9 +2531,6 @@ packages: rxjs@7.8.2: resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==} - safe-buffer@5.2.1: - resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} - safe-regex2@5.1.1: resolution: {integrity: sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==} hasBin: true @@ -2652,9 +2638,6 @@ packages: resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} engines: {node: '>=12'} - string_decoder@1.3.0: - resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} - strip-ansi@6.0.1: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} @@ -2764,9 +2747,6 @@ packages: resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} engines: {node: '>= 18'} - typedarray@0.0.6: - resolution: {integrity: sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==} - typescript@5.9.3: resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} engines: {node: '>=14.17'} @@ -2801,9 +2781,6 @@ packages: peerDependencies: browserslist: '>= 4.21.0' - util-deprecate@1.0.2: - resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} - v8-to-istanbul@9.3.0: resolution: {integrity: sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==} engines: {node: '>=10.12.0'} @@ -3474,7 +3451,7 @@ snapshots: '@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) cors: 2.8.6 express: 5.2.1(supports-color@8.1.1) - multer: 2.3.0 + multer: 2.4.0 path-to-regexp: 8.4.2 tslib: 2.8.1 transitivePeerDependencies: @@ -4198,8 +4175,6 @@ snapshots: dependencies: node-int64: 0.4.0 - buffer-from@1.1.2: {} - busboy@1.6.0: dependencies: streamsearch: 1.1.0 @@ -4278,13 +4253,6 @@ snapshots: component-emitter@1.3.1: {} - concat-stream@2.0.0: - dependencies: - buffer-from: 1.1.2 - inherits: 2.0.4 - readable-stream: 3.6.2 - typedarray: 0.0.6 - confbox@0.2.4: {} confbox@0.3.1: {} @@ -5203,11 +5171,10 @@ snapshots: ms@2.1.3: {} - multer@2.3.0: + multer@2.4.0: dependencies: append-field: 1.0.0 busboy: 1.6.0 - concat-stream: 2.0.0 type-is: 1.6.18 mysql2@3.23.1(@types/node@24.13.3): @@ -5242,7 +5209,7 @@ snapshots: node-releases@2.0.54: {} - nodemailer@10.0.1: {} + nodemailer@10.0.11: {} normalize-path@3.0.0: {} @@ -5452,12 +5419,6 @@ snapshots: react@19.2.8: {} - readable-stream@3.6.2: - dependencies: - inherits: 2.0.4 - string_decoder: 1.3.0 - util-deprecate: 1.0.2 - readdirp@5.1.1: {} reflect-metadata@0.2.2: {} @@ -5494,8 +5455,6 @@ snapshots: dependencies: tslib: 2.8.1 - safe-buffer@5.2.1: {} - safe-regex2@5.1.1: dependencies: ret: 0.5.0 @@ -5610,10 +5569,6 @@ snapshots: emoji-regex: 9.2.2 strip-ansi: 7.2.0 - string_decoder@1.3.0: - dependencies: - safe-buffer: 5.2.1 - strip-ansi@6.0.1: dependencies: ansi-regex: 5.0.1 @@ -5724,8 +5679,6 @@ snapshots: media-typer: 1.1.1 mime-types: 3.0.2 - typedarray@0.0.6: {} - typescript@5.9.3: {} uglify-js@3.19.3: @@ -5774,8 +5727,6 @@ snapshots: escalade: 3.2.0 picocolors: 1.1.1 - util-deprecate@1.0.2: {} - v8-to-istanbul@9.3.0: dependencies: '@jridgewell/trace-mapping': 0.3.31 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 3bf832a..945894c 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -8,4 +8,4 @@ allowBuilds: overrides: '@prisma/config>deepmerge-ts': 8.0.0 'prisma>mysql2': 3.23.1 - '@nestjs/platform-express>multer': 2.3.0 + '@nestjs/platform-express>multer': 2.4.0 -- 2.40.1