feat/material-bom #13

Merged
mihir merged 2 commits from feat/material-bom into main 2026-09-29 00:01:20 +05:30
17 changed files with 696 additions and 1 deletions
Showing only changes of commit f280df5dd0 - Show all commits

View File

@ -38,6 +38,7 @@ Phase 2C adds [partial goods receipts and quality inspection](docs/goods-receipt
Phase 2D adds [supplier invoice matching and voids](docs/supplier-invoices-api.md).
Phase 2E adds [supplier payment records and reversals](docs/supplier-payments-api.md). Material stock movements and production remain later milestones.
Phase 2F adds [private versioned supplier documents and review](docs/supplier-documents-api.md).
Phase 2G adds [versioned product bills of materials](docs/bom-api.md).
### Swagger UI

24
docs/bom-api.md Normal file
View File

@ -0,0 +1,24 @@
# Product bills of materials (Phase 2G)
Every BOM belongs to one product variant and organization. A revision specifies the number of finished pieces it yields and the required quantity of each material for that yield. Quantities use the material's native unit and exactly three input decimal places. The API does not convert grams to kilograms or assume a wastage rate.
| Method | Path | Permission | Purpose |
| ------ | --------------------------------------------------------- | ------------ | --------------------------------------------------------- |
| GET | `/api/v1/variants/:variantId/boms?status=&limit=&offset=` | `bom.read` | List revision metadata, newest first |
| GET | `/api/v1/variants/:variantId/boms/active` | `bom.read` | Get the current active revision with lines |
| POST | `/api/v1/variants/:variantId/boms` | `bom.manage` | Create a complete draft revision |
| GET | `/api/v1/boms/:id` | `bom.read` | Get one revision with material snapshots |
| POST | `/api/v1/boms/:id/activate` | `bom.manage` | Activate a draft and supersede the former active revision |
Create body:
```json
{
"outputQuantity": 10,
"lines": [{ "materialId": "a-valid-uuid", "quantity": "125.000" }]
}
```
Use an actual UUID for `materialId`. One to 50 distinct active materials are required. The output is 1–100,000 pieces, and a variant can have at most 100 revisions. Only active variants and materials may be used. Material name, code and unit are copied into the revision and do not change when master data changes. Drafts are complete when created; corrections use another revision. Activating an older draft after a newer revision has been activated is rejected. An existing activation remains auditable even if its material master is subsequently deactivated.
All reads and writes are organization scoped. The create and activate paths write audit events. Database constraints and triggers enforce sequential revisions, positive quantities, one active revision per variant, immutable lines, and permitted lifecycle transitions. Production batches, actual consumption, wastage, packaging and costing remain later milestones; a BOM is a planned recipe, not a stock movement.

View File

@ -20,6 +20,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase
- 2D (implemented): supplier invoice matching and auditable voids. Tax rules, payments, and documents remain separate milestones.
- 2E (implemented): external supplier payment records, partial balances, idempotent retries, and auditable reversals. Bank reconciliation and proof documents remain separate milestones.
- 2F (implemented): private PDF versions for supplier documents, independent validation, and gated downloads. Retention and malware scanning remain deployment decisions.
- 2G (implemented): versioned, organization-scoped product BOM drafts and activation with material snapshots. Production batches, consumption, wastage, packaging BOM and costing remain later milestones.
## Phase 3: B2B and white label

41
prisma/bom.prisma Normal file
View File

@ -0,0 +1,41 @@
enum BomStatus {
DRAFT
ACTIVE
SUPERSEDED
}
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
outputQuantity Int @map("output_quantity")
status BomStatus @default(DRAFT)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
activatedAt DateTime? @map("activated_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines ProductBomLine[]
@@unique([variantId, revision])
@@unique([id, organizationId])
@@index([organizationId, variantId, createdAt, id])
@@map("product_boms")
}
model ProductBomLine {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
bomId String @map("bom_id") @db.Uuid
materialId String @map("material_id") @db.Uuid
materialName String @map("material_name") @db.VarChar(160)
materialCode String @map("material_code") @db.VarChar(32)
unit MaterialUnit
quantity Decimal @db.Decimal(12,3)
bom ProductBom @relation(fields: [bomId, organizationId], references: [id, organizationId], onDelete: Restrict)
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([bomId, materialId])
@@index([organizationId, materialId])
@@map("product_bom_lines")
}

View File

@ -37,6 +37,7 @@ model ProductVariant {
stockItems StockItem[]
cartLines CartLine[]
orderLines OrderLine[]
boms ProductBom[]
product Product @relation(fields: [productId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([organizationId, sku])
@@unique([id, organizationId])

View File

@ -19,5 +19,6 @@
"20260928123638_goods_receipts_qc": "a09646d8a3a1f520495ddbe611c61437ddfcec4585486f94fc383d9b1312006c",
"20260928130714_supplier_invoices": "63945cff1725929e90fe73ade79348480e04a36976dbdb2a021a574569c35049",
"20260928145745_supplier_payments": "012ff1c33c1afa8e6fd883925616f014e7cfdac258fac37ac2ae56739e95bf6d",
"20260928151912_supplier_documents": "65ec974aa6bd0e8f85dc0dbde00f5ef5d9ab81811aba17d89299b6464d4ee6c1"
"20260928151912_supplier_documents": "65ec974aa6bd0e8f85dc0dbde00f5ef5d9ab81811aba17d89299b6464d4ee6c1",
"20260928153219_product_boms": "b548e6e5c2f11b52374ba0ad3eedbc127244b2752f07cdcd8bf951641d4525a1"
}

View File

@ -0,0 +1,77 @@
CREATE TYPE "BomStatus" AS ENUM ('DRAFT', 'ACTIVE', 'SUPERSEDED');
CREATE TABLE "product_boms" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"variant_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"revision" INTEGER NOT NULL,
"output_quantity" INTEGER NOT NULL,
"status" "BomStatus" NOT NULL DEFAULT 'DRAFT',
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"activated_at" TIMESTAMPTZ(3),
CONSTRAINT "product_boms_pkey" PRIMARY KEY ("id"),
CONSTRAINT "product_boms_quantity" CHECK ("revision" BETWEEN 1 AND 100 AND "output_quantity" BETWEEN 1 AND 100000),
CONSTRAINT "product_boms_activation" CHECK (("status" = 'DRAFT' AND "activated_at" IS NULL) OR ("status" <> 'DRAFT' AND "activated_at" IS NOT NULL))
);
CREATE UNIQUE INDEX "product_boms_variant_id_revision_key" ON "product_boms"("variant_id", "revision");
CREATE UNIQUE INDEX "product_boms_id_organization_id_key" ON "product_boms"("id", "organization_id");
CREATE UNIQUE INDEX "product_boms_one_active_idx" ON "product_boms"("variant_id") WHERE "status" = 'ACTIVE';
CREATE INDEX "product_boms_organization_id_variant_id_created_at_id_idx" ON "product_boms"("organization_id", "variant_id", "created_at", "id");
ALTER TABLE "product_boms" ADD CONSTRAINT "product_boms_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "product_boms" ADD CONSTRAINT "product_boms_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "product_boms" ADD CONSTRAINT "product_boms_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "product_bom_lines" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"bom_id" UUID NOT NULL,
"material_id" UUID NOT NULL,
"material_name" VARCHAR(160) NOT NULL,
"material_code" VARCHAR(32) NOT NULL,
"unit" "MaterialUnit" NOT NULL,
"quantity" DECIMAL(12,3) NOT NULL,
CONSTRAINT "product_bom_lines_pkey" PRIMARY KEY ("id"),
CONSTRAINT "product_bom_lines_quantity" CHECK ("quantity" > 0)
);
CREATE UNIQUE INDEX "product_bom_lines_bom_id_material_id_key" ON "product_bom_lines"("bom_id", "material_id");
CREATE INDEX "product_bom_lines_organization_id_material_id_idx" ON "product_bom_lines"("organization_id", "material_id");
ALTER TABLE "product_bom_lines" ADD CONSTRAINT "product_bom_lines_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 "product_bom_lines" ADD CONSTRAINT "product_bom_lines_material_id_organization_id_fkey" FOREIGN KEY ("material_id", "organization_id") REFERENCES "materials"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE 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;
IF NEW.revision <> previous_revision + 1 THEN RAISE EXCEPTION 'Product BOM revision must be sequential'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER product_bom_revision_sequence BEFORE INSERT ON product_boms FOR EACH ROW EXECUTE FUNCTION check_product_bom_revision();
CREATE FUNCTION guard_product_bom_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'DELETE' OR NEW.id <> OLD.id OR NEW.organization_id <> OLD.organization_id OR NEW.variant_id <> OLD.variant_id
OR NEW.created_by_id <> OLD.created_by_id OR NEW.revision <> OLD.revision OR NEW.output_quantity <> OLD.output_quantity
OR NEW.created_at <> OLD.created_at
OR NOT ((OLD.status = 'DRAFT' AND NEW.status = 'ACTIVE' AND OLD.activated_at IS NULL AND NEW.activated_at IS NOT NULL)
OR (OLD.status = 'ACTIVE' AND NEW.status = 'SUPERSEDED' AND NEW.activated_at = OLD.activated_at))
THEN RAISE EXCEPTION 'Product BOM mutation is not allowed'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER product_boms_guard BEFORE UPDATE OR DELETE ON product_boms FOR EACH ROW EXECUTE FUNCTION guard_product_bom_mutation();
CREATE 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;
RETURN NEW;
END;
$$;
CREATE TRIGGER product_bom_lines_guard BEFORE INSERT OR UPDATE OR DELETE ON product_bom_lines FOR EACH ROW EXECUTE FUNCTION guard_product_bom_line();
UPDATE "roles" SET "permissions" = array_append(array_append("permissions", 'bom.read'), 'bom.manage')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('bom.read' = ANY("permissions"));

View File

@ -68,6 +68,7 @@ model Material {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
suppliers SupplierMaterial[]
purchaseOrderLines PurchaseOrderLine[]
bomLines ProductBomLine[]
@@unique([organizationId, code])
@@unique([id, organizationId])

View File

@ -36,6 +36,7 @@ model Organization {
supplierDocuments SupplierDocument[]
supplierDocumentVersions SupplierDocumentVersion[]
supplierDocumentDecisions SupplierDocumentDecision[]
productBoms ProductBom[]
@@map("organizations")
}
model User {
@ -63,6 +64,7 @@ model User {
supplierDocuments SupplierDocument[]
supplierDocumentVersions SupplierDocumentVersion[]
supplierDocumentDecisions SupplierDocumentDecision[]
productBoms ProductBom[]
stockEntries StockLedger[]
stockReservations StockReservation[]
carts Cart[]

View File

@ -306,4 +306,39 @@ export const COMMERCE_ERRORS = {
'Document is temporarily unavailable',
'Supplier document checksum verification failed',
],
BOM_NOT_FOUND: [
404,
'Bill of materials not found',
'Scoped BOM lookup failed',
],
BOM_VARIANT_INACTIVE: [
409,
'Variant is inactive',
'BOM variant eligibility failed',
],
BOM_MATERIAL_INACTIVE: [
409,
'A material is inactive',
'BOM material eligibility failed',
],
BOM_MATERIAL_MISSING: [
404,
'A material was not found',
'BOM material scope lookup failed',
],
BOM_REVISION_LIMIT: [
409,
'BOM revision limit reached',
'BOM resource quota exceeded',
],
BOM_NOT_DRAFT: [
409,
'Only a draft BOM can be activated',
'BOM lifecycle transition rejected',
],
BOM_REVISION_STALE: [
409,
'A newer BOM revision is already active',
'BOM activation order rejected',
],
} as const;

View File

@ -26,5 +26,7 @@ export const PERMISSIONS = [
'supplier_document.read',
'supplier_document.manage',
'supplier_document.validate',
'bom.read',
'bom.manage',
] as const;
export type Permission = (typeof PERMISSIONS)[number];

View File

@ -0,0 +1,26 @@
import { z } from 'zod';
import { pageSchema } from '../identity/identity.schemas';
const quantity = z.string().regex(/^(?!0\.000$)(?:0|[1-9]\d{0,8})\.\d{3}$/);
export const createBomSchema = z
.object({
outputQuantity: z.number().int().min(1).max(100000),
lines: z
.array(z.object({ materialId: z.uuid(), quantity }).strict())
.min(1)
.max(50)
.refine(
(lines) =>
new Set(lines.map((line) => line.materialId)).size === lines.length,
'Material may occur only once',
),
})
.strict();
export const bomListQuery = pageSchema
.extend({ status: z.enum(['DRAFT', 'ACTIVE', 'SUPERSEDED']).optional() })
.strict();
export type CreateBomInput = z.infer<typeof createBomSchema>;
export type BomListQuery = z.infer<typeof bomListQuery>;

View File

@ -0,0 +1,182 @@
import { Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { DatabaseService } from '../database/database.service';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { Principal } from '../identity/identity.types';
import type { BomListQuery, CreateBomInput } from './bom.schemas';
const bomView = { lines: { orderBy: { materialCode: 'asc' as const } } };
@Injectable()
export class BomStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async list(actor: Principal, variantId: string, query: BomListQuery) {
await this.requireVariant(actor, variantId);
return this.db.productBom.findMany({
where: {
organizationId: actor.organizationId,
variantId,
...(query.status ? { status: query.status } : {}),
},
orderBy: { revision: 'desc' },
take: query.limit,
skip: query.offset,
});
}
async find(actor: Principal, id: string) {
const bom = await this.db.productBom.findFirst({
where: { id, organizationId: actor.organizationId },
include: bomView,
});
if (!bom) throw new AppError('BOM_NOT_FOUND');
return bom;
}
async active(actor: Principal, variantId: string) {
await this.requireVariant(actor, variantId);
const bom = await this.db.productBom.findFirst({
where: {
organizationId: actor.organizationId,
variantId,
status: 'ACTIVE',
},
include: bomView,
});
if (!bom) throw new AppError('BOM_NOT_FOUND');
return bom;
}
create(actor: Principal, variantId: string, input: CreateBomInput) {
return this.access.mutate(actor, 'bom.manage', async (tx) => {
const variant = await tx.productVariant.findFirst({
where: { id: variantId, organizationId: actor.organizationId },
select: { active: true },
});
if (!variant) throw new AppError('VARIANT_NOT_FOUND');
if (!variant.active) throw new AppError('BOM_VARIANT_INACTIVE');
const materialIds = input.lines.map((line) => line.materialId);
const materials = await tx.material.findMany({
where: {
id: { in: materialIds },
organizationId: actor.organizationId,
},
select: { id: true, name: true, code: true, unit: 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');
const byId = new Map(
materials.map((material) => [material.id, material]),
);
const revision = await tx.productBom.count({
where: { organizationId: actor.organizationId, variantId },
});
if (revision >= 100) throw new AppError('BOM_REVISION_LIMIT');
const bom = await tx.productBom.create({
data: {
organizationId: actor.organizationId,
variantId,
createdById: actor.userId,
revision: revision + 1,
outputQuantity: input.outputQuantity,
},
});
await tx.productBomLine.createMany({
data: input.lines.map((line) => {
const material = byId.get(line.materialId)!;
return {
organizationId: actor.organizationId,
bomId: bom.id,
materialId: material.id,
materialName: material.name,
materialCode: material.code,
unit: material.unit,
quantity: line.quantity,
};
}),
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'bom.created',
bom.id,
);
return tx.productBom.findUniqueOrThrow({
where: { id: bom.id },
include: bomView,
});
});
}
activate(actor: Principal, id: string) {
return this.access.mutate(actor, 'bom.manage', async (tx) => {
const bom = await tx.productBom.findFirst({
where: { id, organizationId: actor.organizationId },
include: { lines: { select: { materialId: true } } },
});
if (!bom) throw new AppError('BOM_NOT_FOUND');
if (bom.status !== 'DRAFT') throw new AppError('BOM_NOT_DRAFT');
const newer = await tx.productBom.findFirst({
where: {
organizationId: actor.organizationId,
variantId: bom.variantId,
revision: { gt: bom.revision },
status: { not: 'DRAFT' },
},
select: { id: true },
});
if (newer) throw new AppError('BOM_REVISION_STALE');
const variant = await tx.productVariant.findFirst({
where: { id: bom.variantId, organizationId: actor.organizationId },
select: { active: true },
});
if (!variant?.active) throw new AppError('BOM_VARIANT_INACTIVE');
const activeMaterials = await tx.material.count({
where: {
organizationId: actor.organizationId,
active: true,
id: { in: bom.lines.map((line) => line.materialId) },
},
});
if (activeMaterials !== bom.lines.length)
throw new AppError('BOM_MATERIAL_INACTIVE');
await tx.productBom.updateMany({
where: {
organizationId: actor.organizationId,
variantId: bom.variantId,
status: 'ACTIVE',
},
data: { status: 'SUPERSEDED' },
});
const result = await tx.productBom.update({
where: { id },
data: { status: 'ACTIVE', activatedAt: new Date() },
include: bomView,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'bom.activated',
id,
);
return result;
});
}
private async requireVariant(actor: Principal, variantId: string) {
const variant = await this.db.productVariant.findFirst({
where: { id: variantId, organizationId: actor.organizationId },
select: { id: true },
});
if (!variant) throw new AppError('VARIANT_NOT_FOUND');
}
}

View File

@ -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/boms')
export class VariantBomsController {
constructor(private readonly boms: BomStore) {}
@Get()
@RequirePermission('bom.read')
list(
@CurrentPrincipal() actor: Principal,
@Param('variantId', ParseUUIDPipe) variantId: string,
@Query(new SchemaPipe(bomListQuery)) query: BomListQuery,
) {
return this.boms.list(actor, variantId, query);
}
@Get('active')
@RequirePermission('bom.read')
active(
@CurrentPrincipal() actor: Principal,
@Param('variantId', ParseUUIDPipe) variantId: string,
) {
return this.boms.active(actor, variantId);
}
@Post()
@RequirePermission('bom.manage')
create(
@CurrentPrincipal() actor: Principal,
@Param('variantId', ParseUUIDPipe) variantId: string,
@Body(new SchemaPipe(createBomSchema)) input: CreateBomInput,
) {
return this.boms.create(actor, variantId, input);
}
}
@Controller('boms')
export class BomsController {
constructor(private readonly boms: BomStore) {}
@Get(':id')
@RequirePermission('bom.read')
find(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.boms.find(actor, id);
}
@Post(':id/activate')
@RequirePermission('bom.manage')
activate(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.boms.activate(actor, id);
}
}

View File

@ -9,6 +9,8 @@ import { GoodsReceiptStore } from './goods-receipt.store';
import { SupplierInvoiceStore } from './supplier-invoice.store';
import { SupplierPaymentStore } from './supplier-payment.store';
import { SupplierDocumentStore } from './supplier-document.store';
import { BomStore } from './bom.store';
import { BomsController, VariantBomsController } from './boms.controller';
import {
SupplierDocumentsController,
SupplierDocumentController,
@ -36,6 +38,7 @@ import {
SupplierInvoiceStore,
SupplierPaymentStore,
SupplierDocumentStore,
BomStore,
],
controllers: [
ProcurementController,
@ -49,6 +52,8 @@ import {
SupplierDocumentsController,
SupplierDocumentController,
SupplierDocumentVersionsController,
VariantBomsController,
BomsController,
],
})
export class ProcurementModule {}

38
test/bom.schemas.spec.ts Normal file
View File

@ -0,0 +1,38 @@
import { createBomSchema } from '../src/procurement/bom.schemas';
import { randomUUID } from 'node:crypto';
describe('BOM input', () => {
const materialId = randomUUID();
it('accepts a bounded material recipe', () => {
expect(
createBomSchema.safeParse({
outputQuantity: 12,
lines: [{ materialId, quantity: '0.001' }],
}).success,
).toBe(true);
});
it('rejects duplicate materials, zero quantities and unknown fields', () => {
const input = {
outputQuantity: 1,
lines: [{ materialId, quantity: '1.000' }],
};
expect(
createBomSchema.safeParse({
...input,
lines: [...input.lines, ...input.lines],
}).success,
).toBe(false);
expect(
createBomSchema.safeParse({
...input,
lines: [{ materialId, quantity: '0.000' }],
}).success,
).toBe(false);
expect(createBomSchema.safeParse({ ...input, extra: true }).success).toBe(
false,
);
expect(
createBomSchema.safeParse({ ...input, outputQuantity: 100001 }).success,
).toBe(false);
});
});

179
test/boms.spec.ts Normal file
View File

@ -0,0 +1,179 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor, seedProduct } from './helpers/commerce';
describe('product BOM API', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const materialInput = (code: string, active = true) => ({
name: 'Soy Wax',
code,
kind: 'WAX',
unit: 'GRAM',
active,
});
const createMaterial = async (active = true) => {
const code = `W-${randomUUID().slice(0, 8)}`;
return (
await ctx
.api()
.post('/api/v1/materials')
.auth(ctx.token, auth)
.send(materialInput(code, active))
.expect(201)
).body as { id: string; code: string };
};
const createBom = (variantId: string, materialId: string) =>
ctx
.api()
.post(`/api/v1/variants/${variantId}/boms`)
.auth(ctx.token, auth)
.send({
outputQuantity: 10,
lines: [{ materialId, quantity: '125.000' }],
});
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('creates immutable snapshots and activates a new revision', async () => {
const { variant } = await seedProduct(ctx);
const material = await createMaterial();
const first = await createBom(variant.id, material.id).expect(201);
expect(first.body).toMatchObject({
revision: 1,
status: 'DRAFT',
outputQuantity: 10,
});
expect(first.body.lines[0]).toMatchObject({
materialCode: material.code,
unit: 'GRAM',
quantity: '125',
});
await ctx
.api()
.put(`/api/v1/materials/${material.id}`)
.auth(ctx.token, auth)
.send({ ...materialInput(material.code), name: 'Updated Wax' })
.expect(200);
const active = await ctx
.api()
.post(`/api/v1/boms/${first.body.id}/activate`)
.auth(ctx.token, auth)
.expect(201);
expect(active.body.status).toBe('ACTIVE');
const again = await ctx
.api()
.post(`/api/v1/boms/${first.body.id}/activate`)
.auth(ctx.token, auth)
.expect(409);
expect(again.body.code).toBe('BOM_NOT_DRAFT');
const second = await createBom(variant.id, material.id).expect(201);
expect(second.body.revision).toBe(2);
await ctx
.api()
.post(`/api/v1/boms/${second.body.id}/activate`)
.auth(ctx.token, auth)
.expect(201);
const former = await ctx
.api()
.get(`/api/v1/boms/${first.body.id}`)
.auth(ctx.token, auth)
.expect(200);
expect(former.body.status).toBe('SUPERSEDED');
expect(former.body.activatedAt).toBe(active.body.activatedAt);
expect(former.body.lines[0].materialName).toBe('Soy Wax');
const current = await ctx
.api()
.get(`/api/v1/variants/${variant.id}/boms/active`)
.auth(ctx.token, auth)
.expect(200);
expect(current.body.id).toBe(second.body.id);
const list = await ctx
.api()
.get(`/api/v1/variants/${variant.id}/boms?status=SUPERSEDED`)
.auth(ctx.token, auth)
.expect(200);
expect(list.body.map((row: { id: string }) => row.id)).toEqual([
first.body.id,
]);
expect(
await ctx.db.auditEvent.count({
where: {
organizationId: ctx.owner.organizationId,
action: 'bom.activated',
},
}),
).toBe(2);
});
it('rejects missing, cross-organization and inactive materials', async () => {
const { variant } = await seedProduct(ctx);
const missing = await createBom(variant.id, randomUUID()).expect(404);
expect(missing.body.code).toBe('BOM_MATERIAL_MISSING');
const material = await createMaterial(false);
const inactive = await createBom(variant.id, material.id).expect(409);
expect(inactive.body.code).toBe('BOM_MATERIAL_INACTIVE');
const outsider = await secondActor(ctx, false, ['bom.read', 'bom.manage']);
const denied = await ctx
.api()
.get(`/api/v1/variants/${variant.id}/boms`)
.auth(outsider.token, auth)
.expect(404);
expect(denied.body.code).toBe('VARIANT_NOT_FOUND');
});
it('enforces BOM permissions and rechecks material state at activation', async () => {
const { variant } = await seedProduct(ctx);
const material = await createMaterial();
const bom = await createBom(variant.id, material.id).expect(201);
const reader = await secondActor(ctx, true, ['bom.read']);
await ctx
.api()
.get(`/api/v1/boms/${bom.body.id}`)
.auth(reader.token, auth)
.expect(200);
await ctx
.api()
.post(`/api/v1/boms/${bom.body.id}/activate`)
.auth(reader.token, auth)
.expect(403);
await ctx
.api()
.put(`/api/v1/materials/${material.id}`)
.auth(ctx.token, auth)
.send(materialInput(material.code, false))
.expect(200);
const inactive = await ctx
.api()
.post(`/api/v1/boms/${bom.body.id}/activate`)
.auth(ctx.token, auth)
.expect(409);
expect(inactive.body.code).toBe('BOM_MATERIAL_INACTIVE');
});
it('does not activate a stale draft after a newer revision', async () => {
const { variant } = await seedProduct(ctx);
const material = await createMaterial();
const oldDraft = await createBom(variant.id, material.id).expect(201);
const newDraft = await createBom(variant.id, material.id).expect(201);
await ctx
.api()
.post(`/api/v1/boms/${newDraft.body.id}/activate`)
.auth(ctx.token, auth)
.expect(201);
const stale = await ctx
.api()
.post(`/api/v1/boms/${oldDraft.body.id}/activate`)
.auth(ctx.token, auth)
.expect(409);
expect(stale.body.code).toBe('BOM_REVISION_STALE');
});
});