feat(production): record packaging execution for completed batches

This commit is contained in:
mihir 2026-09-29 11:51:23 +05:30
parent d726102435
commit a90b30df7c
16 changed files with 626 additions and 3 deletions

View File

@ -47,3 +47,4 @@ For a development owner, see [local admin setup](docs/local-admin.md).
### Swagger UI ### 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. 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).

View File

@ -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": "<active packaging BOM uuid>",
"idempotencyKey": "<uuid>",
"lines": [
{
"bomLineId": "<packaging BOM line uuid>",
"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.

View File

@ -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. - 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. - 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. - 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 ## Phase 3: B2B and white label

View File

@ -25,6 +25,7 @@ model ProductBom {
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict) createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines ProductBomLine[] lines ProductBomLine[]
batches ProductionBatch[] batches ProductionBatch[]
packagingRuns PackagingRun[]
@@unique([variantId, kind, revision]) @@unique([variantId, kind, revision])
@@unique([id, organizationId]) @@unique([id, organizationId])
@@index([organizationId, variantId, createdAt, id]) @@index([organizationId, variantId, createdAt, id])
@ -43,6 +44,7 @@ model ProductBomLine {
bom ProductBom @relation(fields: [bomId, organizationId], references: [id, organizationId], onDelete: Restrict) bom ProductBom @relation(fields: [bomId, organizationId], references: [id, organizationId], onDelete: Restrict)
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict) material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
materialUsage ProductionMaterialUsage[] materialUsage ProductionMaterialUsage[]
packagingRunLines PackagingRunLine[]
@@unique([bomId, materialId]) @@unique([bomId, materialId])
@@unique([id, bomId, organizationId]) @@unique([id, bomId, organizationId])
@@index([organizationId, materialId]) @@index([organizationId, materialId])

View File

@ -23,5 +23,6 @@
"20260928153219_product_boms": "b548e6e5c2f11b52374ba0ad3eedbc127244b2752f07cdcd8bf951641d4525a1", "20260928153219_product_boms": "b548e6e5c2f11b52374ba0ad3eedbc127244b2752f07cdcd8bf951641d4525a1",
"20260928183508_production_batches": "53b3fbabe17d3270ae3c5d74393a07abb28858ca2af8d3a1aa19c92686c84a0a", "20260928183508_production_batches": "53b3fbabe17d3270ae3c5d74393a07abb28858ca2af8d3a1aa19c92686c84a0a",
"20260928190933_material_usage": "950a2f1861e88c052b1e4d40aff178524c3a7c198e9fb27a3c47cb77fb984e1e", "20260928190933_material_usage": "950a2f1861e88c052b1e4d40aff178524c3a7c198e9fb27a3c47cb77fb984e1e",
"20260928193354_packaging_boms": "1f78a1f42b905ea7d371fadba6180a9f756fc4c360a04b92d58b37ec1dd2bad3" "20260928193354_packaging_boms": "1f78a1f42b905ea7d371fadba6180a9f756fc4c360a04b92d58b37ec1dd2bad3",
"20260929013000_packaging_execution": "63c0fb096c769478ba9422fb606fd421188abd70eeef1375dd07bef2cbc731c1"
} }

View File

@ -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"));

View File

@ -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")
}

View File

@ -22,6 +22,7 @@ model ProductionBatch {
completion ProductionBatchCompletion? completion ProductionBatchCompletion?
cancellation ProductionBatchCancellation? cancellation ProductionBatchCancellation?
materialUsage ProductionMaterialUsage[] materialUsage ProductionMaterialUsage[]
packagingRun PackagingRun?
@@unique([organizationId, reference]) @@unique([organizationId, reference])
@@unique([id, organizationId]) @@unique([id, organizationId])
@@unique([id, bomId, organizationId]) @@unique([id, bomId, organizationId])

View File

@ -41,6 +41,7 @@ model Organization {
productionBatchCompletions ProductionBatchCompletion[] productionBatchCompletions ProductionBatchCompletion[]
productionBatchCancellations ProductionBatchCancellation[] productionBatchCancellations ProductionBatchCancellation[]
productionMaterialUsage ProductionMaterialUsage[] productionMaterialUsage ProductionMaterialUsage[]
packagingRuns PackagingRun[]
@@map("organizations") @@map("organizations")
} }
model User { model User {
@ -73,6 +74,7 @@ model User {
productionBatchCompletions ProductionBatchCompletion[] productionBatchCompletions ProductionBatchCompletion[]
productionBatchCancellations ProductionBatchCancellation[] productionBatchCancellations ProductionBatchCancellation[]
productionMaterialUsage ProductionMaterialUsage[] productionMaterialUsage ProductionMaterialUsage[]
packagingRuns PackagingRun[]
stockEntries StockLedger[] stockEntries StockLedger[]
stockReservations StockReservation[] stockReservations StockReservation[]
carts Cart[] carts Cart[]

View File

@ -431,4 +431,44 @@ export const COMMERCE_ERRORS = {
'Idempotency key was used for different material usage', 'Idempotency key was used for different material usage',
'Production material usage idempotency payload mismatch', '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; } as const;

View File

@ -30,6 +30,7 @@ export const PERMISSIONS = [
'bom.manage', 'bom.manage',
'packaging.read', 'packaging.read',
'packaging.manage', 'packaging.manage',
'packaging.record',
'production.read', 'production.read',
'production.manage', 'production.manage',
'production.material.record', 'production.material.record',

View File

@ -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);
}
}

View File

@ -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<typeof packagingRunSchema>;

View File

@ -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,
}),
);
});
}
}

View File

@ -5,10 +5,16 @@ import { BatchStore } from './batch.store';
import { BatchesController } from './batches.controller'; import { BatchesController } from './batches.controller';
import { MaterialUsageController } from './material-usage.controller'; import { MaterialUsageController } from './material-usage.controller';
import { MaterialUsageStore } from './material-usage.store'; import { MaterialUsageStore } from './material-usage.store';
import { PackagingRunController } from './packaging-run.controller';
import { PackagingRunStore } from './packaging-run.store';
@Module({ @Module({
imports: [DatabaseModule, IdentityModule], imports: [DatabaseModule, IdentityModule],
providers: [BatchStore, MaterialUsageStore], providers: [BatchStore, MaterialUsageStore, PackagingRunStore],
controllers: [BatchesController, MaterialUsageController], controllers: [
BatchesController,
MaterialUsageController,
PackagingRunController,
],
}) })
export class ProductionModule {} export class ProductionModule {}

187
test/packaging-run.spec.ts Normal file
View File

@ -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();
});
});