From 9c5eb2eeeae441c86aee81948ba7cfc50c85e952 Mon Sep 17 00:00:00 2001 From: mihir Date: Tue, 29 Sep 2026 01:18:37 +0530 Subject: [PATCH] feat(production): add independent packaging BOM revisions --- README.md | 1 + docs/packaging-boms-api.md | 15 ++ docs/roadmap.md | 1 + prisma/bom.prisma | 8 +- prisma/migration-checksums.json | 3 +- .../migration.sql | 42 ++++ src/common/errors/commerce-errors.ts | 10 + src/identity/permissions.ts | 2 + src/procurement/bom.store.ts | 79 ++++++-- src/procurement/packaging-boms.controller.ts | 79 ++++++++ src/procurement/packaging-policy.ts | 7 + src/procurement/procurement.module.ts | 6 + src/production/batch.store.ts | 1 + test/packaging-boms.spec.ts | 179 ++++++++++++++++++ test/packaging-policy.spec.ts | 10 + 15 files changed, 428 insertions(+), 15 deletions(-) create mode 100644 docs/packaging-boms-api.md create mode 100644 prisma/migrations/20260928193354_packaging_boms/migration.sql create mode 100644 src/procurement/packaging-boms.controller.ts create mode 100644 src/procurement/packaging-policy.ts create mode 100644 test/packaging-boms.spec.ts create mode 100644 test/packaging-policy.spec.ts diff --git a/README.md b/README.md index 0f52c9f..0cdfc50 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ Phase 2F adds [private versioned supplier documents and review](docs/supplier-do 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). +Phase 2J adds [versioned packaging BOMs](docs/packaging-boms-api.md). For a development owner, see [local admin setup](docs/local-admin.md). ### Swagger UI diff --git a/docs/packaging-boms-api.md b/docs/packaging-boms-api.md new file mode 100644 index 0000000..7713376 --- /dev/null +++ b/docs/packaging-boms-api.md @@ -0,0 +1,15 @@ +# Packaging bills of materials (Phase 2J) + +Packaging BOMs describe boxes, labels and other packaging materials required for a product variant. They reuse the production BOM revision model but have an independent revision sequence and active revision. Existing production BOMs remain `PRODUCTION`; packaging BOMs are `PACKAGING`. Both use immutable material name, code, unit and quantity snapshots. + +| Method | Path | Permission | Purpose | +| ------ | ------------------------------------------------------------------- | ------------------ | ----------------------------------------------------------- | +| GET | `/api/v1/variants/:variantId/packaging-boms?status=&limit=&offset=` | `packaging.read` | List packaging revisions | +| GET | `/api/v1/variants/:variantId/packaging-boms/active` | `packaging.read` | Get active packaging recipe | +| POST | `/api/v1/variants/:variantId/packaging-boms` | `packaging.manage` | Create a complete draft | +| GET | `/api/v1/packaging-boms/:id` | `packaging.read` | Get one revision and its lines | +| POST | `/api/v1/packaging-boms/:id/activate` | `packaging.manage` | Activate a draft and supersede the previous active revision | + +Creation uses the same body as the production BOM API: `outputQuantity` is the number of finished pieces yielded, and `lines` is an array of distinct `{ "materialId": "", "quantity": "10.000" }` entries. Quantities use each material's native unit and exactly three decimal places. Packaging BOMs accept only active materials of kind `PACKAGING` or `LABEL`. Activation rechecks that those materials and the product variant remain active and compatible. + +The database enforces independent sequential revisions, at most one active BOM of each kind per variant, immutable BOM kind and lines, and allowed lifecycle transitions. Production batches require a `PRODUCTION` BOM and reject packaging BOM IDs. Packaging usage, physical stock deduction and costing remain later milestones; creating or activating a packaging BOM does not move inventory. diff --git a/docs/roadmap.md b/docs/roadmap.md index acf00a7..45a4b43 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -23,6 +23,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase - 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. +- 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. ## Phase 3: B2B and white label diff --git a/prisma/bom.prisma b/prisma/bom.prisma index 5b6ed8f..eb64a09 100644 --- a/prisma/bom.prisma +++ b/prisma/bom.prisma @@ -4,12 +4,18 @@ enum BomStatus { SUPERSEDED } +enum BomKind { + PRODUCTION + PACKAGING +} + model ProductBom { id String @id @default(uuid()) @db.Uuid organizationId String @map("organization_id") @db.Uuid variantId String @map("variant_id") @db.Uuid createdById String @map("created_by_id") @db.Uuid revision Int + kind BomKind @default(PRODUCTION) outputQuantity Int @map("output_quantity") status BomStatus @default(DRAFT) createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) @@ -19,7 +25,7 @@ model ProductBom { createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict) lines ProductBomLine[] batches ProductionBatch[] - @@unique([variantId, revision]) + @@unique([variantId, kind, revision]) @@unique([id, organizationId]) @@index([organizationId, variantId, createdAt, id]) @@map("product_boms") diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index cb70bc1..e809be0 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -22,5 +22,6 @@ "20260928151912_supplier_documents": "65ec974aa6bd0e8f85dc0dbde00f5ef5d9ab81811aba17d89299b6464d4ee6c1", "20260928153219_product_boms": "b548e6e5c2f11b52374ba0ad3eedbc127244b2752f07cdcd8bf951641d4525a1", "20260928183508_production_batches": "53b3fbabe17d3270ae3c5d74393a07abb28858ca2af8d3a1aa19c92686c84a0a", - "20260928190933_material_usage": "950a2f1861e88c052b1e4d40aff178524c3a7c198e9fb27a3c47cb77fb984e1e" + "20260928190933_material_usage": "950a2f1861e88c052b1e4d40aff178524c3a7c198e9fb27a3c47cb77fb984e1e", + "20260928193354_packaging_boms": "1f78a1f42b905ea7d371fadba6180a9f756fc4c360a04b92d58b37ec1dd2bad3" } diff --git a/prisma/migrations/20260928193354_packaging_boms/migration.sql b/prisma/migrations/20260928193354_packaging_boms/migration.sql new file mode 100644 index 0000000..c763383 --- /dev/null +++ b/prisma/migrations/20260928193354_packaging_boms/migration.sql @@ -0,0 +1,42 @@ +CREATE TYPE "BomKind" AS ENUM ('PRODUCTION', 'PACKAGING'); +ALTER TABLE "product_boms" ADD COLUMN "kind" "BomKind" NOT NULL DEFAULT 'PRODUCTION'; + +DROP INDEX "product_boms_variant_id_revision_key"; +CREATE UNIQUE INDEX "product_boms_variant_id_kind_revision_key" ON "product_boms"("variant_id", "kind", "revision"); +DROP INDEX "product_boms_one_active_idx"; +CREATE UNIQUE INDEX "product_boms_one_active_idx" ON "product_boms"("variant_id", "kind") WHERE "status" = 'ACTIVE'; + +CREATE OR REPLACE FUNCTION check_product_bom_revision() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE previous_revision INTEGER; +BEGIN + PERFORM id FROM product_variants WHERE id = NEW.variant_id FOR UPDATE; + SELECT COALESCE(MAX(revision), 0) INTO previous_revision FROM product_boms WHERE variant_id = NEW.variant_id AND kind = NEW.kind; + IF NEW.revision <> previous_revision + 1 THEN RAISE EXCEPTION 'Product BOM revision must be sequential within kind'; END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION guard_product_bom_kind() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.kind <> OLD.kind THEN RAISE EXCEPTION 'Product BOM kind is immutable'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER product_boms_kind_guard BEFORE UPDATE ON product_boms FOR EACH ROW EXECUTE FUNCTION guard_product_bom_kind(); + +CREATE OR REPLACE FUNCTION guard_product_bom_line() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Product BOM lines are immutable'; END IF; + IF NOT EXISTS (SELECT 1 FROM product_boms WHERE id = NEW.bom_id AND organization_id = NEW.organization_id AND status = 'DRAFT') + THEN RAISE EXCEPTION 'Product BOM lines require a draft'; END IF; + IF EXISTS ( + SELECT 1 FROM product_boms b JOIN materials m ON m.id = NEW.material_id AND m.organization_id = NEW.organization_id + WHERE b.id = NEW.bom_id AND b.organization_id = NEW.organization_id + AND b.kind = 'PACKAGING' AND m.kind NOT IN ('PACKAGING', 'LABEL') + ) THEN RAISE EXCEPTION 'Packaging BOM requires packaging or label material'; END IF; + RETURN NEW; +END; +$$; + +UPDATE "roles" SET "permissions" = array_append(array_append("permissions", 'packaging.read'), 'packaging.manage') +WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('packaging.read' = ANY("permissions")); diff --git a/src/common/errors/commerce-errors.ts b/src/common/errors/commerce-errors.ts index bd50b99..80377c3 100644 --- a/src/common/errors/commerce-errors.ts +++ b/src/common/errors/commerce-errors.ts @@ -341,6 +341,11 @@ export const COMMERCE_ERRORS = { 'A newer BOM revision is already active', 'BOM activation order rejected', ], + PACKAGING_MATERIAL_KIND: [ + 409, + 'Packaging BOM lines must use packaging or label materials', + 'Packaging BOM material kind rejected', + ], BATCH_NOT_FOUND: [ 404, 'Production batch not found', @@ -356,6 +361,11 @@ export const COMMERCE_ERRORS = { 'An active BOM is required', 'Production batch BOM eligibility failed', ], + BATCH_BOM_KIND: [ + 409, + 'Production batches require a production BOM', + 'Production batch BOM kind rejected', + ], BATCH_VARIANT_INACTIVE: [ 409, 'The variant is inactive', diff --git a/src/identity/permissions.ts b/src/identity/permissions.ts index 4833f86..8d0b9f2 100644 --- a/src/identity/permissions.ts +++ b/src/identity/permissions.ts @@ -28,6 +28,8 @@ export const PERMISSIONS = [ 'supplier_document.validate', 'bom.read', 'bom.manage', + 'packaging.read', + 'packaging.manage', 'production.read', 'production.manage', 'production.material.record', diff --git a/src/procurement/bom.store.ts b/src/procurement/bom.store.ts index 3a971df..66e8235 100644 --- a/src/procurement/bom.store.ts +++ b/src/procurement/bom.store.ts @@ -5,8 +5,19 @@ import { AccessStore } from '../identity/access.store'; import { recordAudit } from '../identity/audit'; import type { Principal } from '../identity/identity.types'; import type { BomListQuery, CreateBomInput } from './bom.schemas'; +import { + isPackagingMaterial, + PACKAGING_MATERIAL_KINDS, +} from './packaging-policy'; const bomView = { lines: { orderBy: { materialCode: 'asc' as const } } }; +type BomKind = 'PRODUCTION' | 'PACKAGING'; +const permissionFor = (kind: BomKind) => + kind === 'PACKAGING' + ? ('packaging.manage' as const) + : ('bom.manage' as const); +const auditFor = (kind: BomKind, action: 'created' | 'activated') => + `${kind === 'PACKAGING' ? 'packaging_bom' : 'bom'}.${action}`; @Injectable() export class BomStore { @@ -15,12 +26,18 @@ export class BomStore { private readonly access: AccessStore, ) {} - async list(actor: Principal, variantId: string, query: BomListQuery) { + async list( + actor: Principal, + variantId: string, + query: BomListQuery, + kind: BomKind = 'PRODUCTION', + ) { await this.requireVariant(actor, variantId); return this.db.productBom.findMany({ where: { organizationId: actor.organizationId, variantId, + kind, ...(query.status ? { status: query.status } : {}), }, orderBy: { revision: 'desc' }, @@ -29,21 +46,26 @@ export class BomStore { }); } - async find(actor: Principal, id: string) { + async find(actor: Principal, id: string, kind: BomKind = 'PRODUCTION') { const bom = await this.db.productBom.findFirst({ - where: { id, organizationId: actor.organizationId }, + where: { id, organizationId: actor.organizationId, kind }, include: bomView, }); if (!bom) throw new AppError('BOM_NOT_FOUND'); return bom; } - async active(actor: Principal, variantId: string) { + async active( + actor: Principal, + variantId: string, + kind: BomKind = 'PRODUCTION', + ) { await this.requireVariant(actor, variantId); const bom = await this.db.productBom.findFirst({ where: { organizationId: actor.organizationId, variantId, + kind, status: 'ACTIVE', }, include: bomView, @@ -52,8 +74,13 @@ export class BomStore { return bom; } - create(actor: Principal, variantId: string, input: CreateBomInput) { - return this.access.mutate(actor, 'bom.manage', async (tx) => { + create( + actor: Principal, + variantId: string, + input: CreateBomInput, + kind: BomKind = 'PRODUCTION', + ) { + return this.access.mutate(actor, permissionFor(kind), async (tx) => { const variant = await tx.productVariant.findFirst({ where: { id: variantId, organizationId: actor.organizationId }, select: { active: true }, @@ -66,23 +93,36 @@ export class BomStore { id: { in: materialIds }, organizationId: actor.organizationId, }, - select: { id: true, name: true, code: true, unit: true, active: true }, + select: { + id: true, + name: true, + code: true, + unit: true, + kind: true, + active: true, + }, }); if (materials.length !== materialIds.length) throw new AppError('BOM_MATERIAL_MISSING'); if (materials.some((material) => !material.active)) throw new AppError('BOM_MATERIAL_INACTIVE'); + if ( + kind === 'PACKAGING' && + materials.some((material) => !isPackagingMaterial(material.kind)) + ) + throw new AppError('PACKAGING_MATERIAL_KIND'); const byId = new Map( materials.map((material) => [material.id, material]), ); const revision = await tx.productBom.count({ - where: { organizationId: actor.organizationId, variantId }, + where: { organizationId: actor.organizationId, variantId, kind }, }); if (revision >= 100) throw new AppError('BOM_REVISION_LIMIT'); const bom = await tx.productBom.create({ data: { organizationId: actor.organizationId, variantId, + kind, createdById: actor.userId, revision: revision + 1, outputQuantity: input.outputQuantity, @@ -106,7 +146,7 @@ export class BomStore { tx, actor.organizationId, actor.userId, - 'bom.created', + auditFor(kind, 'created'), bom.id, ); return tx.productBom.findUniqueOrThrow({ @@ -116,10 +156,10 @@ export class BomStore { }); } - activate(actor: Principal, id: string) { - return this.access.mutate(actor, 'bom.manage', async (tx) => { + activate(actor: Principal, id: string, kind: BomKind = 'PRODUCTION') { + return this.access.mutate(actor, permissionFor(kind), async (tx) => { const bom = await tx.productBom.findFirst({ - where: { id, organizationId: actor.organizationId }, + where: { id, organizationId: actor.organizationId, kind }, include: { lines: { select: { materialId: true } } }, }); if (!bom) throw new AppError('BOM_NOT_FOUND'); @@ -128,6 +168,7 @@ export class BomStore { where: { organizationId: actor.organizationId, variantId: bom.variantId, + kind, revision: { gt: bom.revision }, status: { not: 'DRAFT' }, }, @@ -148,10 +189,22 @@ export class BomStore { }); if (activeMaterials !== bom.lines.length) throw new AppError('BOM_MATERIAL_INACTIVE'); + if (kind === 'PACKAGING') { + const compatible = await tx.material.count({ + where: { + organizationId: actor.organizationId, + id: { in: bom.lines.map((line) => line.materialId) }, + kind: { in: [...PACKAGING_MATERIAL_KINDS] }, + }, + }); + if (compatible !== bom.lines.length) + throw new AppError('PACKAGING_MATERIAL_KIND'); + } await tx.productBom.updateMany({ where: { organizationId: actor.organizationId, variantId: bom.variantId, + kind, status: 'ACTIVE', }, data: { status: 'SUPERSEDED' }, @@ -165,7 +218,7 @@ export class BomStore { tx, actor.organizationId, actor.userId, - 'bom.activated', + auditFor(kind, 'activated'), id, ); return result; diff --git a/src/procurement/packaging-boms.controller.ts b/src/procurement/packaging-boms.controller.ts new file mode 100644 index 0000000..f52fa92 --- /dev/null +++ b/src/procurement/packaging-boms.controller.ts @@ -0,0 +1,79 @@ +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 { BomStore } from './bom.store'; +import { + bomListQuery, + createBomSchema, + type BomListQuery, + type CreateBomInput, +} from './bom.schemas'; + +@Controller('variants/:variantId/packaging-boms') +export class VariantPackagingBomsController { + constructor(private readonly boms: BomStore) {} + + @Get() + @RequirePermission('packaging.read') + list( + @CurrentPrincipal() actor: Principal, + @Param('variantId', ParseUUIDPipe) variantId: string, + @Query(new SchemaPipe(bomListQuery)) query: BomListQuery, + ) { + return this.boms.list(actor, variantId, query, 'PACKAGING'); + } + + @Get('active') + @RequirePermission('packaging.read') + active( + @CurrentPrincipal() actor: Principal, + @Param('variantId', ParseUUIDPipe) variantId: string, + ) { + return this.boms.active(actor, variantId, 'PACKAGING'); + } + + @Post() + @RequirePermission('packaging.manage') + create( + @CurrentPrincipal() actor: Principal, + @Param('variantId', ParseUUIDPipe) variantId: string, + @Body(new SchemaPipe(createBomSchema)) input: CreateBomInput, + ) { + return this.boms.create(actor, variantId, input, 'PACKAGING'); + } +} + +@Controller('packaging-boms') +export class PackagingBomsController { + constructor(private readonly boms: BomStore) {} + + @Get(':id') + @RequirePermission('packaging.read') + find( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + ) { + return this.boms.find(actor, id, 'PACKAGING'); + } + + @Post(':id/activate') + @RequirePermission('packaging.manage') + activate( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + ) { + return this.boms.activate(actor, id, 'PACKAGING'); + } +} diff --git a/src/procurement/packaging-policy.ts b/src/procurement/packaging-policy.ts new file mode 100644 index 0000000..dbc1ddb --- /dev/null +++ b/src/procurement/packaging-policy.ts @@ -0,0 +1,7 @@ +import type { MaterialKind } from '../generated/prisma/client'; + +export const PACKAGING_MATERIAL_KINDS = ['PACKAGING', 'LABEL'] as const; + +export function isPackagingMaterial(kind: MaterialKind): boolean { + return PACKAGING_MATERIAL_KINDS.some((allowed) => allowed === kind); +} diff --git a/src/procurement/procurement.module.ts b/src/procurement/procurement.module.ts index ece102c..3f90a31 100644 --- a/src/procurement/procurement.module.ts +++ b/src/procurement/procurement.module.ts @@ -11,6 +11,10 @@ import { SupplierPaymentStore } from './supplier-payment.store'; import { SupplierDocumentStore } from './supplier-document.store'; import { BomStore } from './bom.store'; import { BomsController, VariantBomsController } from './boms.controller'; +import { + PackagingBomsController, + VariantPackagingBomsController, +} from './packaging-boms.controller'; import { SupplierDocumentsController, SupplierDocumentController, @@ -54,6 +58,8 @@ import { SupplierDocumentVersionsController, VariantBomsController, BomsController, + VariantPackagingBomsController, + PackagingBomsController, ], }) export class ProcurementModule {} diff --git a/src/production/batch.store.ts b/src/production/batch.store.ts index b467ee6..fd694b1 100644 --- a/src/production/batch.store.ts +++ b/src/production/batch.store.ts @@ -85,6 +85,7 @@ export class BatchStore { include: { variant: { select: { active: true } }, lines: true }, }); if (!bom) throw new AppError('BOM_NOT_FOUND'); + if (bom.kind !== 'PRODUCTION') throw new AppError('BATCH_BOM_KIND'); if (bom.status !== 'ACTIVE') throw new AppError('BATCH_BOM_NOT_ACTIVE'); if (!bom.variant.active) throw new AppError('BATCH_VARIANT_INACTIVE'); if (input.plannedQuantity % bom.outputQuantity !== 0) diff --git a/test/packaging-boms.spec.ts b/test/packaging-boms.spec.ts new file mode 100644 index 0000000..be08035 --- /dev/null +++ b/test/packaging-boms.spec.ts @@ -0,0 +1,179 @@ +import { randomUUID } from 'node:crypto'; +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { secondActor, seedProduct } from './helpers/commerce'; + +describe('packaging BOM API', () => { + let ctx: IdentityApp; + const auth = { type: 'bearer' as const }; + const material = async ( + kind: 'PACKAGING' | 'LABEL' | 'WAX', + unit = 'PIECE', + ) => { + const code = `${kind[0]}-${randomUUID().slice(0, 8)}`; + const row = await ctx + .api() + .post('/api/v1/materials') + .auth(ctx.token, auth) + .send({ name: `${kind} item`, code, kind, unit }) + .expect(201); + return { id: row.body.id as string, code }; + }; + const create = (variantId: string, materialId: string) => + ctx + .api() + .post(`/api/v1/variants/${variantId}/packaging-boms`) + .auth(ctx.token, auth) + .send({ + outputQuantity: 10, + lines: [{ materialId, quantity: '10.000' }], + }); + + beforeAll(async () => { + ctx = await identityApp(); + }, 60000); + afterAll(async () => { + await ctx?.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + + it('keeps packaging and production revisions and activations independent', async () => { + const { variant } = await seedProduct(ctx); + const box = await material('PACKAGING'); + const wax = await material('WAX', 'GRAM'); + const production = await ctx + .api() + .post(`/api/v1/variants/${variant.id}/boms`) + .auth(ctx.token, auth) + .send({ + outputQuantity: 10, + lines: [{ materialId: wax.id, quantity: '125.000' }], + }) + .expect(201); + const packaging = await create(variant.id, box.id).expect(201); + expect(production.body).toMatchObject({ kind: 'PRODUCTION', revision: 1 }); + expect(packaging.body).toMatchObject({ kind: 'PACKAGING', revision: 1 }); + await ctx + .api() + .post(`/api/v1/boms/${production.body.id}/activate`) + .auth(ctx.token, auth) + .expect(201); + await ctx + .api() + .post(`/api/v1/packaging-boms/${packaging.body.id}/activate`) + .auth(ctx.token, auth) + .expect(201); + const next = await create(variant.id, box.id).expect(201); + expect(next.body.revision).toBe(2); + await ctx + .api() + .post(`/api/v1/packaging-boms/${next.body.id}/activate`) + .auth(ctx.token, auth) + .expect(201); + const activePackaging = await ctx + .api() + .get(`/api/v1/variants/${variant.id}/packaging-boms/active`) + .auth(ctx.token, auth) + .expect(200); + const activeProduction = await ctx + .api() + .get(`/api/v1/variants/${variant.id}/boms/active`) + .auth(ctx.token, auth) + .expect(200); + expect(activePackaging.body.id).toBe(next.body.id); + expect(activeProduction.body.id).toBe(production.body.id); + await ctx + .api() + .get(`/api/v1/boms/${packaging.body.id}`) + .auth(ctx.token, auth) + .expect(404); + const former = await ctx + .api() + .get(`/api/v1/packaging-boms/${packaging.body.id}`) + .auth(ctx.token, auth) + .expect(200); + expect(former.body.status).toBe('SUPERSEDED'); + const batch = await ctx + .api() + .post('/api/v1/production-batches') + .auth(ctx.token, auth) + .send({ + bomId: next.body.id, + plannedQuantity: 10, + reference: `B-${randomUUID().slice(0, 8)}`, + }) + .expect(409); + expect(batch.body.code).toBe('BATCH_BOM_KIND'); + }); + + it('requires packaging or label materials and rechecks at activation', async () => { + const { variant } = await seedProduct(ctx); + const wax = await material('WAX', 'GRAM'); + const wrong = await create(variant.id, wax.id).expect(409); + expect(wrong.body.code).toBe('PACKAGING_MATERIAL_KIND'); + const label = await material('LABEL'); + const draft = await create(variant.id, label.id).expect(201); + await ctx + .api() + .put(`/api/v1/materials/${label.id}`) + .auth(ctx.token, auth) + .send({ + name: 'Changed label', + code: label.code, + kind: 'WAX', + unit: 'PIECE', + }) + .expect(200); + const changed = await ctx + .api() + .post(`/api/v1/packaging-boms/${draft.body.id}/activate`) + .auth(ctx.token, auth) + .expect(409); + expect(changed.body.code).toBe('PACKAGING_MATERIAL_KIND'); + }); + + it('uses separate permissions and hides other organizations', async () => { + const { variant } = await seedProduct(ctx); + const box = await material('PACKAGING'); + const packaging = await create(variant.id, box.id).expect(201); + const reader = await secondActor(ctx, true, ['packaging.read']); + await ctx + .api() + .get(`/api/v1/packaging-boms/${packaging.body.id}`) + .auth(reader.token, auth) + .expect(200); + await ctx + .api() + .get(`/api/v1/boms/${packaging.body.id}`) + .auth(reader.token, auth) + .expect(403); + await ctx + .api() + .post(`/api/v1/packaging-boms/${packaging.body.id}/activate`) + .auth(reader.token, auth) + .expect(403); + const outsider = await secondActor(ctx, false, [ + 'packaging.read', + 'packaging.manage', + ]); + const hidden = await ctx + .api() + .get(`/api/v1/packaging-boms/${packaging.body.id}`) + .auth(outsider.token, auth) + .expect(404); + expect(hidden.body.code).toBe('BOM_NOT_FOUND'); + }); + + it('keeps BOM kind immutable in PostgreSQL', async () => { + const { variant } = await seedProduct(ctx); + const box = await material('PACKAGING'); + const packaging = await create(variant.id, box.id).expect(201); + await expect( + ctx.db.productBom.update({ + where: { id: packaging.body.id }, + data: { kind: 'PRODUCTION', status: 'ACTIVE', activatedAt: new Date() }, + }), + ).rejects.toThrow(); + }); +}); diff --git a/test/packaging-policy.spec.ts b/test/packaging-policy.spec.ts new file mode 100644 index 0000000..19b1106 --- /dev/null +++ b/test/packaging-policy.spec.ts @@ -0,0 +1,10 @@ +import { isPackagingMaterial } from '../src/procurement/packaging-policy'; + +describe('packaging material eligibility', () => { + it('accepts packaging and label materials only', () => { + expect(isPackagingMaterial('PACKAGING')).toBe(true); + expect(isPackagingMaterial('LABEL')).toBe(true); + expect(isPackagingMaterial('WAX')).toBe(false); + expect(isPackagingMaterial('VESSEL')).toBe(false); + }); +}); -- 2.40.1