feat(costing): add versioned material rates and BOM estimates #18

Merged
mihir merged 1 commits from feat/material-costing into main 2026-09-29 16:49:38 +05:30
18 changed files with 534 additions and 1 deletions

View File

@ -48,3 +48,4 @@ For a development owner, see [local admin setup](docs/local-admin.md).
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).
Cost estimates: see [Phase 2L API guide](docs/costing-api.md).

16
docs/costing-api.md Normal file
View File

@ -0,0 +1,16 @@
# Material costing estimates (Phase 2L)
Record an internal standard cost per material and currency. Each new rate is an immutable revision; rates are entered in the material's native unit. These are planning inputs, independent of supplier quotes, invoices, tax, freight and physical inventory valuation.
| Method | Path | Permission |
| ------ | ---------------------------------------------------------------------- | ------------- |
| GET | `/api/v1/materials/:materialId/cost-rates?currency=INR&limit=&offset=` | `cost.read` |
| POST | `/api/v1/materials/:materialId/cost-rates` | `cost.manage` |
| GET | `/api/v1/boms/:id/cost-estimate?currency=INR` | `cost.read` |
| GET | `/api/v1/packaging-boms/:id/cost-estimate?currency=INR` | `cost.read` |
Example rate body: `{ "currency": "INR", "unitCost": "0.1250" }`. Supported currencies are INR, USD, EUR and GBP. Unit cost is positive with exactly four decimal places. Revisions are numbered independently for each material and currency; a material can have at most 1,000 revisions per currency.
An estimate multiplies each BOM-line quantity by the latest rate in the requested currency, rounds each line half-up to two decimal places, then sums the rounded lines. The response includes each rate ID and revision, the line amounts, total for the BOM's output quantity, and the time of calculation. Missing rates return `COST_RATE_MISSING`; no exchange conversion or cross-currency addition occurs. Production and packaging BOM estimates use separate paths and cannot be confused.
Estimates are calculated from current rates when requested. Updating a rate changes future estimates, including estimates of older BOM revisions. Save the returned rate IDs and amounts externally if a planning decision needs a point-in-time reference. Actual batch costing, labor and overhead, tax, shipping, and stock valuation require separate policies and milestones.

View File

@ -25,6 +25,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase
- 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.
- 2L (implemented): append-only standard material cost rates by currency and live production/packaging BOM cost estimates with exact decimal arithmetic. Batch actual costing and physical stock posting remain later milestones.
## Phase 3: B2B and white label

View File

@ -0,0 +1,16 @@
model MaterialCostRate {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
materialId String @map("material_id") @db.Uuid
recordedById String @map("recorded_by_id") @db.Uuid
currency String @db.Char(3)
revision Int
unitCost Decimal @map("unit_cost") @db.Decimal(12,4)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
recordedBy User @relation(fields: [recordedById, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([materialId, currency, revision])
@@index([organizationId, materialId, currency, revision], map: "material_cost_rates_scope_revision_idx")
@@map("material_cost_rates")
}

View File

@ -24,5 +24,6 @@
"20260928183508_production_batches": "53b3fbabe17d3270ae3c5d74393a07abb28858ca2af8d3a1aa19c92686c84a0a",
"20260928190933_material_usage": "950a2f1861e88c052b1e4d40aff178524c3a7c198e9fb27a3c47cb77fb984e1e",
"20260928193354_packaging_boms": "1f78a1f42b905ea7d371fadba6180a9f756fc4c360a04b92d58b37ec1dd2bad3",
"20260929013000_packaging_execution": "63c0fb096c769478ba9422fb606fd421188abd70eeef1375dd07bef2cbc731c1"
"20260929013000_packaging_execution": "63c0fb096c769478ba9422fb606fd421188abd70eeef1375dd07bef2cbc731c1",
"20260929132000_material_cost_rates": "b7a9068407b6caf5f2c226969929c8e435ca37cc4e7fd7632da1140f79f77b0c"
}

View File

@ -0,0 +1,33 @@
CREATE TABLE "material_cost_rates" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"material_id" UUID NOT NULL,
"recorded_by_id" UUID NOT NULL,
"currency" CHAR(3) NOT NULL,
"revision" INTEGER NOT NULL,
"unit_cost" DECIMAL(12,4) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "material_cost_rates_pkey" PRIMARY KEY ("id"),
CONSTRAINT "material_cost_rates_values" CHECK ("revision" BETWEEN 1 AND 1000 AND "unit_cost" > 0 AND "currency" IN ('INR', 'USD', 'EUR', 'GBP'))
);
CREATE UNIQUE INDEX "material_cost_rates_material_id_currency_revision_key" ON "material_cost_rates"("material_id", "currency", "revision");
CREATE INDEX "material_cost_rates_scope_revision_idx" ON "material_cost_rates"("organization_id", "material_id", "currency", "revision");
ALTER TABLE "material_cost_rates" ADD CONSTRAINT "material_cost_rates_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_cost_rates" ADD CONSTRAINT "material_cost_rates_material_id_organization_id_fkey" FOREIGN KEY ("material_id", "organization_id") REFERENCES "materials"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_cost_rates" ADD CONSTRAINT "material_cost_rates_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 FUNCTION guard_material_cost_rate() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE previous_revision INTEGER;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material cost rates are immutable'; END IF;
PERFORM id FROM materials WHERE id = NEW.material_id AND organization_id = NEW.organization_id FOR UPDATE;
SELECT COALESCE(MAX(revision), 0) INTO previous_revision FROM material_cost_rates
WHERE material_id = NEW.material_id AND currency = NEW.currency;
IF NEW.revision <> previous_revision + 1 THEN RAISE EXCEPTION 'Material cost revision must be sequential'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER material_cost_rates_guard BEFORE INSERT OR UPDATE OR DELETE ON material_cost_rates FOR EACH ROW EXECUTE FUNCTION guard_material_cost_rate();
UPDATE "roles" SET "permissions" = array_append(array_append("permissions", 'cost.read'), 'cost.manage')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('cost.read' = ANY("permissions"));

View File

@ -69,6 +69,7 @@ model Material {
suppliers SupplierMaterial[]
purchaseOrderLines PurchaseOrderLine[]
bomLines ProductBomLine[]
costRates MaterialCostRate[]
@@unique([organizationId, code])
@@unique([id, organizationId])

View File

@ -42,6 +42,7 @@ model Organization {
productionBatchCancellations ProductionBatchCancellation[]
productionMaterialUsage ProductionMaterialUsage[]
packagingRuns PackagingRun[]
materialCostRates MaterialCostRate[]
@@map("organizations")
}
model User {
@ -75,6 +76,7 @@ model User {
productionBatchCancellations ProductionBatchCancellation[]
productionMaterialUsage ProductionMaterialUsage[]
packagingRuns PackagingRun[]
materialCostRates MaterialCostRate[]
stockEntries StockLedger[]
stockReservations StockReservation[]
carts Cart[]

View File

@ -5,6 +5,7 @@ import { AddressesModule } from './addresses/addresses.module';
import { InventoryModule } from './inventory/inventory.module';
import { ProcurementModule } from './procurement/procurement.module';
import { ProductionModule } from './production/production.module';
import { CostingModule } from './costing/costing.module';
import { Module } from '@nestjs/common';
import { EnvironmentModule } from './config/environment.module';
import { IdentityModule } from './identity/identity.module';
@ -20,6 +21,7 @@ import { HealthModule } from './health/health.module';
InventoryModule,
ProcurementModule,
ProductionModule,
CostingModule,
CheckoutModule,
OperationsModule,
],

View File

@ -471,4 +471,24 @@ export const COMMERCE_ERRORS = {
'Idempotency key was used for different packaging',
'Packaging idempotency payload mismatch',
],
COST_RATE_MISSING: [
409,
'Set a material cost rate for every BOM line in this currency',
'BOM cost estimate missing material rate',
],
COST_RATE_LIMIT: [
409,
'Material cost rate revision limit reached',
'Material cost rate revision quota exceeded',
],
COST_AMOUNT_LIMIT: [
409,
'Cost estimate exceeds the supported amount',
'BOM cost arithmetic overflow',
],
COST_MATERIAL_INACTIVE: [
409,
'Activate the material before setting its cost',
'Inactive material cost rate rejected',
],
} as const;

19
src/costing/cost-math.ts Normal file
View File

@ -0,0 +1,19 @@
import { AppError } from '../common/errors/app-error';
import { scaled } from '../procurement/purchase-order-money';
const MAX_CENTS = 999999999999n;
export function formatCost(cents: bigint) {
if (cents > MAX_CENTS) throw new AppError('COST_AMOUNT_LIMIT');
return `${cents / 100n}.${(cents % 100n).toString().padStart(2, '0')}`;
}
export function estimateLineCost(quantity: string, unitCost: string) {
const cents = (scaled(quantity, 3) * scaled(unitCost, 4) + 50000n) / 100000n;
return formatCost(cents);
}
export function sumCosts(amounts: string[]) {
return formatCost(
amounts.reduce((total, amount) => total + scaled(amount, 2), 0n),
);
}

View File

@ -0,0 +1,75 @@
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 {
costHistoryQuerySchema,
costQuerySchema,
costRateSchema,
type CostHistoryQuery,
type CostQuery,
type CostRateInput,
} from './costing.schemas';
import { CostingStore } from './costing.store';
@Controller('materials/:materialId/cost-rates')
export class MaterialCostRatesController {
constructor(private readonly costing: CostingStore) {}
@Get()
@RequirePermission('cost.read')
list(
@CurrentPrincipal() actor: Principal,
@Param('materialId', ParseUUIDPipe) materialId: string,
@Query(new SchemaPipe(costHistoryQuerySchema)) query: CostHistoryQuery,
) {
return this.costing.listRates(actor, materialId, query);
}
@Post()
@RequirePermission('cost.manage')
create(
@CurrentPrincipal() actor: Principal,
@Param('materialId', ParseUUIDPipe) materialId: string,
@Body(new SchemaPipe(costRateSchema)) input: CostRateInput,
) {
return this.costing.createRate(actor, materialId, input);
}
}
@Controller('boms')
export class ProductionCostController {
constructor(private readonly costing: CostingStore) {}
@Get(':id/cost-estimate')
@RequirePermission('cost.read')
estimate(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Query(new SchemaPipe(costQuerySchema)) query: CostQuery,
) {
return this.costing.estimate(actor, id, 'PRODUCTION', query.currency);
}
}
@Controller('packaging-boms')
export class PackagingCostController {
constructor(private readonly costing: CostingStore) {}
@Get(':id/cost-estimate')
@RequirePermission('cost.read')
estimate(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Query(new SchemaPipe(costQuerySchema)) query: CostQuery,
) {
return this.costing.estimate(actor, id, 'PACKAGING', query.currency);
}
}

View File

@ -0,0 +1,20 @@
import { Module } from '@nestjs/common';
import { DatabaseModule } from '../database/database.module';
import { IdentityModule } from '../identity/identity.module';
import { CostingStore } from './costing.store';
import {
MaterialCostRatesController,
PackagingCostController,
ProductionCostController,
} from './costing.controller';
@Module({
imports: [DatabaseModule, IdentityModule],
providers: [CostingStore],
controllers: [
MaterialCostRatesController,
ProductionCostController,
PackagingCostController,
],
})
export class CostingModule {}

View File

@ -0,0 +1,16 @@
import { z } from 'zod';
import { CURRENCIES } from '../common/currency';
import { pageSchema } from '../identity/identity.schemas';
const currency = z.enum(CURRENCIES);
export const costRateSchema = z
.object({
currency,
unitCost: z.string().regex(/^(?!0\.0000$)(?:0|[1-9]\d{0,7})\.\d{4}$/),
})
.strict();
export const costQuerySchema = z.object({ currency }).strict();
export const costHistoryQuerySchema = pageSchema.extend({ currency }).strict();
export type CostRateInput = z.infer<typeof costRateSchema>;
export type CostQuery = z.infer<typeof costQuerySchema>;
export type CostHistoryQuery = z.infer<typeof costHistoryQuerySchema>;

View File

@ -0,0 +1,150 @@
import { Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { DatabaseService } from '../database/database.service';
import { Prisma } from '../generated/prisma/client';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { Principal } from '../identity/identity.types';
import { estimateLineCost, sumCosts } from './cost-math';
import type { CostHistoryQuery, CostRateInput } from './costing.schemas';
@Injectable()
export class CostingStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async listRates(
actor: Principal,
materialId: string,
query: CostHistoryQuery,
) {
const material = await this.db.material.findFirst({
where: { id: materialId, organizationId: actor.organizationId },
select: { id: true },
});
if (!material) throw new AppError('MATERIAL_NOT_FOUND');
return this.db.materialCostRate.findMany({
where: {
organizationId: actor.organizationId,
materialId,
currency: query.currency,
},
orderBy: { revision: 'desc' },
take: query.limit,
skip: query.offset,
});
}
createRate(actor: Principal, materialId: string, input: CostRateInput) {
return this.access.mutate(actor, 'cost.manage', async (tx) => {
const material = await tx.material.findFirst({
where: { id: materialId, organizationId: actor.organizationId },
select: { active: true },
});
if (!material) throw new AppError('MATERIAL_NOT_FOUND');
if (!material.active) throw new AppError('COST_MATERIAL_INACTIVE');
const latest = await tx.materialCostRate.findFirst({
where: {
materialId,
organizationId: actor.organizationId,
currency: input.currency,
},
orderBy: { revision: 'desc' },
select: { revision: true },
});
const revision = (latest?.revision ?? 0) + 1;
if (revision > 1000) throw new AppError('COST_RATE_LIMIT');
const rate = await tx.materialCostRate.create({
data: {
organizationId: actor.organizationId,
materialId,
recordedById: actor.userId,
currency: input.currency,
revision,
unitCost: input.unitCost,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'material.cost_rate_recorded',
rate.id,
);
return rate;
});
}
estimate(
actor: Principal,
bomId: string,
kind: 'PRODUCTION' | 'PACKAGING',
currency: string,
) {
return this.db.$transaction(
async (tx) => {
const bom = await tx.productBom.findFirst({
where: { id: bomId, organizationId: actor.organizationId, kind },
include: { lines: { orderBy: { materialCode: 'asc' } } },
});
if (!bom) throw new AppError('BOM_NOT_FOUND');
const ids = bom.lines.map((line) => line.materialId);
const latest = await tx.materialCostRate.groupBy({
by: ['materialId'],
where: {
organizationId: actor.organizationId,
currency,
materialId: { in: ids },
},
_max: { revision: true },
});
if (latest.length !== ids.length)
throw new AppError('COST_RATE_MISSING');
const rates = await tx.materialCostRate.findMany({
where: {
organizationId: actor.organizationId,
currency,
OR: latest.map((row) => ({
materialId: row.materialId,
revision: row._max.revision!,
})),
},
});
const byMaterial = new Map(
rates.map((rate) => [rate.materialId, rate]),
);
const lines = bom.lines.map((line) => {
const rate = byMaterial.get(line.materialId);
if (!rate) throw new AppError('COST_RATE_MISSING');
const quantity = line.quantity.toFixed(3);
const unitCost = rate.unitCost.toFixed(4);
const estimatedCost = estimateLineCost(quantity, unitCost);
return {
bomLineId: line.id,
materialId: line.materialId,
materialCode: line.materialCode,
materialName: line.materialName,
unit: line.unit,
quantity,
rateId: rate.id,
rateRevision: rate.revision,
unitCost,
estimatedCost,
};
});
return {
bomId: bom.id,
kind,
currency,
outputQuantity: bom.outputQuantity,
estimatedAt: new Date(),
lines,
estimatedTotal: sumCosts(lines.map((line) => line.estimatedCost)),
};
},
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
);
}
}

View File

@ -31,6 +31,8 @@ export const PERMISSIONS = [
'packaging.read',
'packaging.manage',
'packaging.record',
'cost.read',
'cost.manage',
'production.read',
'production.manage',
'production.material.record',

16
test/cost-math.spec.ts Normal file
View File

@ -0,0 +1,16 @@
import { AppError } from '../src/common/errors/app-error';
import { estimateLineCost, sumCosts } from '../src/costing/cost-math';
describe('cost estimate arithmetic', () => {
it('uses exact decimal arithmetic with half-up rounding per line', () => {
expect(estimateLineCost('0.125', '2.3000')).toBe('0.29');
expect(estimateLineCost('1.000', '0.0050')).toBe('0.01');
expect(sumCosts(['0.29', '0.01'])).toBe('0.30');
});
it('rejects amounts beyond the supported money range', () => {
expect(() => estimateLineCost('999999999.000', '99999999.0000')).toThrow(
AppError,
);
});
});

142
test/costing.spec.ts Normal file
View File

@ -0,0 +1,142 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
import { seedActiveBom } from './helpers/production';
describe('material costing API', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const rate = (materialId: string, currency: string, unitCost: string) =>
ctx
.api()
.post(`/api/v1/materials/${materialId}/cost-rates`)
.auth(ctx.token, auth)
.send({ currency, unitCost });
const estimate = (bomId: string, currency = 'INR', kind = 'boms') =>
ctx
.api()
.get(`/api/v1/${kind}/${bomId}/cost-estimate?currency=${currency}`)
.auth(ctx.token, auth);
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('revises rates per currency and estimates production BOMs exactly', async () => {
const bom = await seedActiveBom(ctx);
const missing = await estimate(bom.bomId).expect(409);
expect(missing.body.code).toBe('COST_RATE_MISSING');
const first = await rate(bom.materialId, 'INR', '0.1000').expect(201);
expect(first.body.revision).toBe(1);
const initial = await estimate(bom.bomId).expect(200);
expect(initial.body).toMatchObject({
kind: 'PRODUCTION',
currency: 'INR',
estimatedTotal: '12.50',
});
expect(initial.body.lines[0].rateId).toBe(first.body.id);
const next = await rate(bom.materialId, 'INR', '0.2000').expect(201);
expect(next.body.revision).toBe(2);
const revised = await estimate(bom.bomId).expect(200);
expect(revised.body.estimatedTotal).toBe('25.00');
expect(revised.body.lines[0].rateRevision).toBe(2);
await rate(bom.materialId, 'USD', '0.0100').expect(201);
const usd = await estimate(bom.bomId, 'USD').expect(200);
expect(usd.body.estimatedTotal).toBe('1.25');
const history = await ctx
.api()
.get(
`/api/v1/materials/${bom.materialId}/cost-rates?currency=INR&limit=1`,
)
.auth(ctx.token, auth)
.expect(200);
expect(history.body).toHaveLength(1);
expect(history.body[0].revision).toBe(2);
});
it('keeps packaging and production estimates separate', async () => {
const production = await seedActiveBom(ctx);
const box = await ctx
.api()
.post('/api/v1/materials')
.auth(ctx.token, auth)
.send({
code: `P-${randomUUID().slice(0, 8)}`,
name: 'Box',
kind: 'PACKAGING',
unit: 'PIECE',
})
.expect(201);
const packaging = await ctx
.api()
.post(`/api/v1/variants/${production.variantId}/packaging-boms`)
.auth(ctx.token, auth)
.send({
outputQuantity: 10,
lines: [{ materialId: box.body.id, quantity: '10.000' }],
})
.expect(201);
await rate(box.body.id, 'INR', '2.5000').expect(201);
const result = await estimate(
packaging.body.id,
'INR',
'packaging-boms',
).expect(200);
expect(result.body).toMatchObject({
kind: 'PACKAGING',
estimatedTotal: '25.00',
});
const wrongKind = await estimate(packaging.body.id).expect(404);
expect(wrongKind.body.code).toBe('BOM_NOT_FOUND');
});
it('enforces validation, permissions and organization scope', async () => {
const bom = await seedActiveBom(ctx);
await rate(bom.materialId, 'INR', '0.0000').expect(400);
await rate(bom.materialId, 'XYZ', '1.0000').expect(400);
const reader = await secondActor(ctx, true, ['cost.read']);
await ctx
.api()
.post(`/api/v1/materials/${bom.materialId}/cost-rates`)
.auth(reader.token, auth)
.send({ currency: 'INR', unitCost: '1.0000' })
.expect(403);
await rate(bom.materialId, 'INR', '1.0000').expect(201);
await ctx
.api()
.get(`/api/v1/boms/${bom.bomId}/cost-estimate?currency=INR`)
.auth(reader.token, auth)
.expect(200);
const outsider = await secondActor(ctx, false, [
'cost.read',
'cost.manage',
]);
await ctx
.api()
.get(`/api/v1/boms/${bom.bomId}/cost-estimate?currency=INR`)
.auth(outsider.token, auth)
.expect(404);
await ctx
.api()
.get(`/api/v1/materials/${bom.materialId}/cost-rates?currency=INR`)
.auth(outsider.token, auth)
.expect(404);
});
it('keeps rate revisions immutable in PostgreSQL', async () => {
const bom = await seedActiveBom(ctx);
const created = await rate(bom.materialId, 'INR', '1.0000').expect(201);
await expect(
ctx.db.materialCostRate.update({
where: { id: created.body.id },
data: { unitCost: '2.0000' },
}),
).rejects.toThrow();
});
});