feat(costing): snapshot completed batch material costs #19

Merged
mihir merged 1 commits from feat/batch-cost-snapshots into main 2026-09-29 17:11:24 +05:30
21 changed files with 919 additions and 26 deletions

View File

@ -49,3 +49,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).
Batch cost snapshots: see [Phase 2M API guide](docs/batch-cost-api.md).

14
docs/batch-cost-api.md Normal file
View File

@ -0,0 +1,14 @@
# Batch cost snapshots (Phase 2M)
Create one immutable standard-cost snapshot after a production batch is completed. The snapshot prices recorded material consumption and wastage, plus recorded packaging use and wastage, using the latest material cost rates in one selected currency at creation time. It stores the exact rate IDs, material quantities, line costs and totals, so later rate revisions cannot change it.
| Method | Path | Permission |
| ------ | --------------------------------------------------- | ------------- |
| GET | `/api/v1/production-batches/:batchId/cost-snapshot` | `cost.read` |
| POST | `/api/v1/production-batches/:batchId/cost-snapshot` | `cost.manage` |
POST body: `{ "currency": "INR", "idempotencyKey": "<uuid>" }`. Supported currencies are INR, USD, EUR and GBP. A batch has at most one snapshot. An exact retry with the same key returns the saved snapshot; a changed request returns `BATCH_COST_REPLAY_CONFLICT`.
Every production BOM line must have at least one material usage event before batch completion. A batch with good output also needs its packaging execution record. A fully rejected batch with zero good pieces can be costed without packaging. Missing usage, packaging or cost rates return distinct errors. Completed legacy batches without usage events cannot be costed retroactively because material usage is append-only and closes with the batch.
Each line adds used and wasted quantities, multiplies by its selected standard rate, and rounds half-up to two decimal places. Production and packaging totals sum their rounded lines; the overall total sums those subtotals. Quantities stay in each material's native unit. These snapshots are operational standard-cost reports, not stock valuation or accounting COGS; they exclude labor, overhead, tax and freight. Physical stock posting remains a separate milestone pending a stock-location policy.

View File

@ -26,6 +26,7 @@ Suppliers, material/urli classification and compatibility, procurement, purchase
- 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.
- 2M (implemented): immutable completed-batch standard-cost snapshots from actual material and packaging use, frozen rate revisions, and exact totals. Physical stock posting remains dependent on the stock-location policy.
## Phase 3: B2B and white label

48
prisma/batch-cost.prisma Normal file
View File

@ -0,0 +1,48 @@
enum BatchCostLineKind {
PRODUCTION
PACKAGING
}
model BatchCostSnapshot {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
batchId String @unique @map("batch_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
currency String @db.Char(3)
goodQuantity Int @map("good_quantity")
productionTotal Decimal @map("production_total") @db.Decimal(12,2)
packagingTotal Decimal @map("packaging_total") @db.Decimal(12,2)
total Decimal @db.Decimal(12,2)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
sealedAt DateTime? @map("sealed_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
batch ProductionBatch @relation(fields: [batchId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines BatchCostLine[]
@@unique([organizationId, idempotencyKey])
@@unique([batchId, organizationId])
@@unique([id, organizationId])
@@map("batch_cost_snapshots")
}
model BatchCostLine {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
snapshotId String @map("snapshot_id") @db.Uuid
kind BatchCostLineKind
bomId String @map("bom_id") @db.Uuid
bomLineId String @map("bom_line_id") @db.Uuid
materialId String @map("material_id") @db.Uuid
rateId String @map("rate_id") @db.Uuid
usedQuantity Decimal @map("used_quantity") @db.Decimal(12,3)
wastedQuantity Decimal @map("wasted_quantity") @db.Decimal(12,3)
unitCost Decimal @map("unit_cost") @db.Decimal(12,4)
lineCost Decimal @map("line_cost") @db.Decimal(12,2)
snapshot BatchCostSnapshot @relation(fields: [snapshotId, organizationId], references: [id, organizationId], onDelete: Restrict)
bomLine ProductBomLine @relation(fields: [bomLineId, bomId, materialId, organizationId], references: [id, bomId, materialId, organizationId], onDelete: Restrict, map: "batch_cost_lines_bom_scope_fkey")
rate MaterialCostRate @relation(fields: [rateId, materialId, organizationId], references: [id, materialId, organizationId], onDelete: Restrict, map: "batch_cost_lines_rate_scope_fkey")
@@unique([snapshotId, bomLineId])
@@map("batch_cost_lines")
}

View File

@ -45,6 +45,8 @@ model ProductBomLine {
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
materialUsage ProductionMaterialUsage[]
packagingRunLines PackagingRunLine[]
batchCostLines BatchCostLine[]
@@unique([id, bomId, materialId, organizationId], map: "product_bom_lines_cost_scope_key")
@@unique([bomId, materialId])
@@unique([id, bomId, organizationId])
@@index([organizationId, materialId])

View File

@ -10,7 +10,9 @@ model MaterialCostRate {
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)
batchCostLines BatchCostLine[]
@@unique([materialId, currency, revision])
@@unique([id, materialId, organizationId])
@@index([organizationId, materialId, currency, revision], map: "material_cost_rates_scope_revision_idx")
@@map("material_cost_rates")
}

View File

@ -25,5 +25,6 @@
"20260928190933_material_usage": "950a2f1861e88c052b1e4d40aff178524c3a7c198e9fb27a3c47cb77fb984e1e",
"20260928193354_packaging_boms": "1f78a1f42b905ea7d371fadba6180a9f756fc4c360a04b92d58b37ec1dd2bad3",
"20260929013000_packaging_execution": "63c0fb096c769478ba9422fb606fd421188abd70eeef1375dd07bef2cbc731c1",
"20260929132000_material_cost_rates": "b7a9068407b6caf5f2c226969929c8e435ca37cc4e7fd7632da1140f79f77b0c"
"20260929132000_material_cost_rates": "b7a9068407b6caf5f2c226969929c8e435ca37cc4e7fd7632da1140f79f77b0c",
"20260929170000_batch_cost_snapshots": "ef59558614f6bfe7fe07a095a4bafef2d3ffdb0ea514dfb1761a02d8d4da0bab"
}

View File

@ -0,0 +1,88 @@
CREATE TYPE "BatchCostLineKind" AS ENUM ('PRODUCTION', 'PACKAGING');
CREATE UNIQUE INDEX "product_bom_lines_cost_scope_key" ON "product_bom_lines"("id", "bom_id", "material_id", "organization_id");
CREATE UNIQUE INDEX "material_cost_rates_id_material_id_organization_id_key" ON "material_cost_rates"("id", "material_id", "organization_id");
CREATE TABLE "batch_cost_snapshots" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"batch_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"currency" CHAR(3) NOT NULL,
"good_quantity" INTEGER NOT NULL,
"production_total" DECIMAL(12,2) NOT NULL,
"packaging_total" DECIMAL(12,2) NOT NULL,
"total" DECIMAL(12,2) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"sealed_at" TIMESTAMPTZ(3),
CONSTRAINT "batch_cost_snapshots_pkey" PRIMARY KEY ("id"),
CONSTRAINT "batch_cost_snapshots_values" CHECK (
"request_hash" ~ '^[a-f0-9]{64}$' AND "currency" IN ('INR', 'USD', 'EUR', 'GBP')
AND "good_quantity" >= 0 AND "production_total" >= 0 AND "packaging_total" >= 0
AND "total" = "production_total" + "packaging_total"
)
);
CREATE UNIQUE INDEX "batch_cost_snapshots_batch_id_key" ON "batch_cost_snapshots"("batch_id");
CREATE UNIQUE INDEX "batch_cost_snapshots_batch_id_organization_id_key" ON "batch_cost_snapshots"("batch_id", "organization_id");
CREATE UNIQUE INDEX "batch_cost_snapshots_organization_id_idempotency_key_key" ON "batch_cost_snapshots"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "batch_cost_snapshots_id_organization_id_key" ON "batch_cost_snapshots"("id", "organization_id");
ALTER TABLE "batch_cost_snapshots" ADD CONSTRAINT "batch_cost_snapshots_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "batch_cost_snapshots" ADD CONSTRAINT "batch_cost_snapshots_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 "batch_cost_snapshots" ADD CONSTRAINT "batch_cost_snapshots_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 "batch_cost_lines" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"snapshot_id" UUID NOT NULL,
"kind" "BatchCostLineKind" NOT NULL,
"bom_id" UUID NOT NULL,
"bom_line_id" UUID NOT NULL,
"material_id" UUID NOT NULL,
"rate_id" UUID NOT NULL,
"used_quantity" DECIMAL(12,3) NOT NULL,
"wasted_quantity" DECIMAL(12,3) NOT NULL,
"unit_cost" DECIMAL(12,4) NOT NULL,
"line_cost" DECIMAL(12,2) NOT NULL,
CONSTRAINT "batch_cost_lines_pkey" PRIMARY KEY ("id"),
CONSTRAINT "batch_cost_lines_values" CHECK (
"used_quantity" >= 0 AND "wasted_quantity" >= 0 AND "unit_cost" > 0 AND "line_cost" >= 0
AND ROUND(("used_quantity" + "wasted_quantity") * "unit_cost", 2) = "line_cost"
)
);
CREATE UNIQUE INDEX "batch_cost_lines_snapshot_id_bom_line_id_key" ON "batch_cost_lines"("snapshot_id", "bom_line_id");
ALTER TABLE "batch_cost_lines" ADD CONSTRAINT "batch_cost_lines_snapshot_id_organization_id_fkey" FOREIGN KEY ("snapshot_id", "organization_id") REFERENCES "batch_cost_snapshots"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "batch_cost_lines" ADD CONSTRAINT "batch_cost_lines_bom_scope_fkey" FOREIGN KEY ("bom_line_id", "bom_id", "material_id", "organization_id") REFERENCES "product_bom_lines"("id", "bom_id", "material_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "batch_cost_lines" ADD CONSTRAINT "batch_cost_lines_rate_scope_fkey" FOREIGN KEY ("rate_id", "material_id", "organization_id") REFERENCES "material_cost_rates"("id", "material_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_batch_cost_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'UPDATE' THEN
IF OLD.sealed_at IS NULL AND NEW.sealed_at IS NOT NULL
AND (to_jsonb(NEW) - 'sealed_at') = (to_jsonb(OLD) - 'sealed_at')
THEN RETURN NEW; END IF;
RAISE EXCEPTION 'Batch cost snapshots are immutable';
END IF;
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Batch cost snapshots are immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM production_batches b JOIN production_batch_completions c
ON c.batch_id = b.id AND c.organization_id = b.organization_id
WHERE b.id = NEW.batch_id AND b.organization_id = NEW.organization_id
AND b.status = 'COMPLETED' AND c.good_quantity = NEW.good_quantity
) THEN RAISE EXCEPTION 'Batch cost snapshot requires matching completion'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER batch_cost_snapshots_guard BEFORE INSERT OR UPDATE OR DELETE ON batch_cost_snapshots FOR EACH ROW EXECUTE FUNCTION guard_batch_cost_snapshot();
CREATE FUNCTION guard_batch_cost_line() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Batch cost lines are immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM batch_cost_snapshots WHERE id = NEW.snapshot_id
AND organization_id = NEW.organization_id AND sealed_at IS NULL
) THEN RAISE EXCEPTION 'Batch cost snapshot is sealed'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER batch_cost_lines_guard BEFORE INSERT OR UPDATE OR DELETE ON batch_cost_lines FOR EACH ROW EXECUTE FUNCTION guard_batch_cost_line();

View File

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

View File

@ -43,6 +43,7 @@ model Organization {
productionMaterialUsage ProductionMaterialUsage[]
packagingRuns PackagingRun[]
materialCostRates MaterialCostRate[]
batchCostSnapshots BatchCostSnapshot[]
@@map("organizations")
}
model User {
@ -77,6 +78,7 @@ model User {
productionMaterialUsage ProductionMaterialUsage[]
packagingRuns PackagingRun[]
materialCostRates MaterialCostRate[]
batchCostSnapshots BatchCostSnapshot[]
stockEntries StockLedger[]
stockReservations StockReservation[]
carts Cart[]

View File

@ -491,4 +491,39 @@ export const COMMERCE_ERRORS = {
'Activate the material before setting its cost',
'Inactive material cost rate rejected',
],
BATCH_COST_NOT_FOUND: [
404,
'Batch cost snapshot not found',
'Batch cost scoped lookup failed',
],
BATCH_COST_STATE: [
409,
'Complete the batch before costing it',
'Batch cost state rejected',
],
BATCH_COST_USAGE_INCOMPLETE: [
409,
'Record usage for every production BOM line before costing',
'Batch cost production usage incomplete',
],
BATCH_COST_PACKAGING_MISSING: [
409,
'Record packaging before costing this batch',
'Batch cost packaging record missing',
],
BATCH_COST_QUANTITY_LIMIT: [
409,
'Actual material quantity exceeds the supported limit',
'Batch cost quantity aggregation overflow',
],
BATCH_COST_ALREADY_RECORDED: [
409,
'This batch already has a cost snapshot',
'Batch cost duplicate rejected',
],
BATCH_COST_REPLAY_CONFLICT: [
409,
'Idempotency key was used for different batch costing',
'Batch cost idempotency payload mismatch',
],
} as const;

View File

@ -0,0 +1,87 @@
import { AppError } from '../common/errors/app-error';
import {
formatMaterialQuantity,
parseMaterialQuantity,
} from '../production/batch-quantity';
import { estimateLineCost, sumCosts } from './cost-math';
type Decimal = { toString(): string; toFixed(digits: number): string };
type BomLine = { id: string; bomId: string; materialId: string };
type Usage = {
bomLineId: string;
kind: 'CONSUMED' | 'WASTED';
quantity: Decimal;
};
type PackagingLine = {
bomLineId: string;
usedQuantity: Decimal;
wastedQuantity: Decimal;
bomLine: BomLine;
};
type Rate = { id: string; unitCost: Decimal };
const MAX_QUANTITY = 999999999999n;
function quantity(value: bigint) {
if (value > MAX_QUANTITY) throw new AppError('BATCH_COST_QUANTITY_LIMIT');
return formatMaterialQuantity(value);
}
export function calculateBatchCost(
productionLines: BomLine[],
usage: Usage[],
packagingLines: PackagingLine[],
rates: Map<string, Rate>,
) {
const totals = new Map<string, { used: bigint; wasted: bigint }>();
for (const event of usage) {
const current = totals.get(event.bomLineId) ?? { used: 0n, wasted: 0n };
current[event.kind === 'CONSUMED' ? 'used' : 'wasted'] +=
parseMaterialQuantity(event.quantity.toString());
totals.set(event.bomLineId, current);
}
if (productionLines.some((line) => !totals.has(line.id)))
throw new AppError('BATCH_COST_USAGE_INCOMPLETE');
const line = (
kind: 'PRODUCTION' | 'PACKAGING',
bomLine: BomLine,
used: bigint,
wasted: bigint,
) => {
const rate = rates.get(bomLine.materialId);
if (!rate) throw new AppError('COST_RATE_MISSING');
const usedQuantity = quantity(used);
const wastedQuantity = quantity(wasted);
const unitCost = rate.unitCost.toFixed(4);
return {
kind,
bomId: bomLine.bomId,
bomLineId: bomLine.id,
materialId: bomLine.materialId,
rateId: rate.id,
usedQuantity,
wastedQuantity,
unitCost,
lineCost: estimateLineCost(quantity(used + wasted), unitCost),
};
};
const production = productionLines.map((bomLine) => {
const { used, wasted } = totals.get(bomLine.id)!;
return line('PRODUCTION', bomLine, used, wasted);
});
const packaging = packagingLines.map((item) =>
line(
'PACKAGING',
item.bomLine,
parseMaterialQuantity(item.usedQuantity.toString()),
parseMaterialQuantity(item.wastedQuantity.toString()),
),
);
const productionTotal = sumCosts(production.map((row) => row.lineCost));
const packagingTotal = sumCosts(packaging.map((row) => row.lineCost));
return {
lines: [...production, ...packaging],
productionTotal,
packagingTotal,
total: sumCosts([productionTotal, packagingTotal]),
};
}

View File

@ -0,0 +1,40 @@
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 { batchCostSchema, type BatchCostInput } from './batch-cost.schemas';
import { BatchCostStore } from './batch-cost.store';
@Controller('production-batches/:batchId/cost-snapshot')
export class BatchCostController {
constructor(private readonly costs: BatchCostStore) {}
@Get()
@RequirePermission('cost.read')
find(
@CurrentPrincipal() actor: Principal,
@Param('batchId', ParseUUIDPipe) batchId: string,
) {
return this.costs.find(actor, batchId);
}
@Post()
@RequirePermission('cost.manage')
create(
@CurrentPrincipal() actor: Principal,
@Param('batchId', ParseUUIDPipe) batchId: string,
@Body(new SchemaPipe(batchCostSchema)) input: BatchCostInput,
) {
return this.costs.create(actor, batchId, input);
}
}

View File

@ -0,0 +1,10 @@
import { z } from 'zod';
import { CURRENCIES } from '../common/currency';
export const batchCostSchema = z
.object({
currency: z.enum(CURRENCIES),
idempotencyKey: z.uuid(),
})
.strict();
export type BatchCostInput = z.infer<typeof batchCostSchema>;

View File

@ -0,0 +1,165 @@
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 { calculateBatchCost } from './batch-cost-calculation';
import type { BatchCostInput } from './batch-cost.schemas';
import { latestCostRates } from './latest-cost-rates';
const snapshotView = {
lines: {
include: { bomLine: true, rate: true },
orderBy: [{ kind: 'asc' as const }, { bomLineId: 'asc' as const }],
},
};
type Snapshot = Prisma.BatchCostSnapshotGetPayload<{
include: typeof snapshotView;
}>;
function present(snapshot: Snapshot) {
return {
id: snapshot.id,
batchId: snapshot.batchId,
currency: snapshot.currency,
goodQuantity: snapshot.goodQuantity,
createdById: snapshot.createdById,
createdAt: snapshot.createdAt,
productionTotal: snapshot.productionTotal.toFixed(2),
packagingTotal: snapshot.packagingTotal.toFixed(2),
total: snapshot.total.toFixed(2),
lines: snapshot.lines.map((line) => ({
kind: line.kind,
bomLineId: line.bomLineId,
materialId: line.materialId,
materialCode: line.bomLine.materialCode,
materialName: line.bomLine.materialName,
unit: line.bomLine.unit,
rateId: line.rateId,
rateRevision: line.rate.revision,
usedQuantity: line.usedQuantity.toFixed(3),
wastedQuantity: line.wastedQuantity.toFixed(3),
unitCost: line.unitCost.toFixed(4),
lineCost: line.lineCost.toFixed(2),
})),
};
}
@Injectable()
export class BatchCostStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async find(actor: Principal, batchId: string) {
const snapshot = await this.db.batchCostSnapshot.findFirst({
where: { batchId, organizationId: actor.organizationId },
include: snapshotView,
});
if (!snapshot) throw new AppError('BATCH_COST_NOT_FOUND');
return present(snapshot);
}
create(actor: Principal, batchId: string, input: BatchCostInput) {
return this.access.mutate(actor, 'cost.manage', async (tx) => {
const hash = createHash('sha256')
.update(JSON.stringify({ batchId, currency: input.currency }))
.digest('hex');
const prior = await tx.batchCostSnapshot.findFirst({
where: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
include: snapshotView,
});
if (prior) {
if (prior.requestHash !== hash)
throw new AppError('BATCH_COST_REPLAY_CONFLICT');
return present(prior);
}
const batch = await tx.productionBatch.findFirst({
where: { id: batchId, organizationId: actor.organizationId },
include: {
bom: { include: { lines: true } },
completion: true,
materialUsage: true,
packagingRun: { include: { lines: { include: { bomLine: true } } } },
},
});
if (!batch) throw new AppError('BATCH_NOT_FOUND');
if (batch.status !== 'COMPLETED' || !batch.completion)
throw new AppError('BATCH_COST_STATE');
if (
await tx.batchCostSnapshot.findUnique({
where: { batchId },
select: { id: true },
})
)
throw new AppError('BATCH_COST_ALREADY_RECORDED');
if (batch.completion.goodQuantity > 0 && !batch.packagingRun)
throw new AppError('BATCH_COST_PACKAGING_MISSING');
const recorded = new Set(
batch.materialUsage.map((event) => event.bomLineId),
);
if (batch.bom.lines.some((line) => !recorded.has(line.id)))
throw new AppError('BATCH_COST_USAGE_INCOMPLETE');
const packagingLines = batch.packagingRun?.lines ?? [];
const rates = await latestCostRates(
tx,
actor.organizationId,
input.currency,
[...batch.bom.lines, ...packagingLines.map((line) => line.bomLine)].map(
(line) => line.materialId,
),
);
const calculated = calculateBatchCost(
batch.bom.lines,
batch.materialUsage,
packagingLines,
rates,
);
const snapshot = await tx.batchCostSnapshot.create({
data: {
organizationId: actor.organizationId,
batchId,
createdById: actor.userId,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
currency: input.currency,
goodQuantity: batch.completion.goodQuantity,
productionTotal: calculated.productionTotal,
packagingTotal: calculated.packagingTotal,
total: calculated.total,
},
});
await tx.batchCostLine.createMany({
data: calculated.lines.map((line) => ({
...line,
organizationId: actor.organizationId,
snapshotId: snapshot.id,
})),
});
await tx.batchCostSnapshot.update({
where: { id: snapshot.id },
data: { sealedAt: new Date() },
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'batch.cost_snapshotted',
snapshot.id,
);
return present(
await tx.batchCostSnapshot.findUniqueOrThrow({
where: { id: snapshot.id },
include: snapshotView,
}),
);
});
}
}

View File

@ -2,6 +2,8 @@ import { Module } from '@nestjs/common';
import { DatabaseModule } from '../database/database.module';
import { IdentityModule } from '../identity/identity.module';
import { CostingStore } from './costing.store';
import { BatchCostController } from './batch-cost.controller';
import { BatchCostStore } from './batch-cost.store';
import {
MaterialCostRatesController,
PackagingCostController,
@ -10,11 +12,12 @@ import {
@Module({
imports: [DatabaseModule, IdentityModule],
providers: [CostingStore],
providers: [CostingStore, BatchCostStore],
controllers: [
MaterialCostRatesController,
ProductionCostController,
PackagingCostController,
BatchCostController,
],
})
export class CostingModule {}

View File

@ -6,6 +6,7 @@ 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 { latestCostRates } from './latest-cost-rates';
import type { CostHistoryQuery, CostRateInput } from './costing.schemas';
@Injectable()
@ -90,30 +91,11 @@ export class CostingStore {
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 byMaterial = await latestCostRates(
tx,
actor.organizationId,
currency,
bom.lines.map((line) => line.materialId),
);
const lines = bom.lines.map((line) => {
const rate = byMaterial.get(line.materialId);

View File

@ -0,0 +1,29 @@
import { AppError } from '../common/errors/app-error';
import type { Prisma } from '../generated/prisma/client';
export async function latestCostRates(
tx: Prisma.TransactionClient,
organizationId: string,
currency: string,
materialIds: string[],
) {
const ids = [...new Set(materialIds)];
const latest = await tx.materialCostRate.groupBy({
by: ['materialId'],
where: { 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,
currency,
OR: latest.map((row) => ({
materialId: row.materialId,
revision: row._max.revision!,
})),
},
});
if (rates.length !== ids.length) throw new AppError('COST_RATE_MISSING');
return new Map(rates.map((rate) => [rate.materialId, rate]));
}

View File

@ -0,0 +1,70 @@
import { AppError } from '../src/common/errors/app-error';
import { calculateBatchCost } from '../src/costing/batch-cost-calculation';
const decimal = (value: string) => ({
toString: () => value,
toFixed: (digits: number) => Number(value).toFixed(digits),
});
describe('batch cost arithmetic', () => {
it('sums production and packaging quantities, then prices each line exactly', () => {
const production = {
id: 'wax-line',
bomId: 'production-bom',
materialId: 'wax',
};
const packaging = {
id: 'box-line',
bomId: 'packaging-bom',
materialId: 'box',
};
const report = calculateBatchCost(
[production],
[
{
bomLineId: production.id,
kind: 'CONSUMED',
quantity: decimal('200.000'),
},
{
bomLineId: production.id,
kind: 'WASTED',
quantity: decimal('10.000'),
},
],
[
{
bomLineId: packaging.id,
bomLine: packaging,
usedQuantity: decimal('19.000'),
wastedQuantity: decimal('1.000'),
},
],
new Map([
['wax', { id: 'wax-rate', unitCost: decimal('0.1000') }],
['box', { id: 'box-rate', unitCost: decimal('2.0000') }],
]),
);
expect(report).toMatchObject({
productionTotal: '21.00',
packagingTotal: '40.00',
total: '61.00',
});
expect(report.lines[0]).toMatchObject({
usedQuantity: '200.000',
wastedQuantity: '10.000',
lineCost: '21.00',
});
});
it('requires usage for every production line', () => {
expect(() =>
calculateBatchCost(
[{ id: 'wax-line', bomId: 'bom', materialId: 'wax' }],
[],
[],
new Map(),
),
).toThrow(AppError);
});
});

185
test/batch-cost.spec.ts Normal file
View File

@ -0,0 +1,185 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
import {
completeCostBatch,
packageCostBatch,
prepareCostBatch,
recordCostUsage,
setCostRate,
startCostBatch,
} from './helpers/batch-cost';
describe('batch cost snapshots API', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const post = (batchId: string, body: object) =>
ctx
.api()
.post(`/api/v1/production-batches/${batchId}/cost-snapshot`)
.auth(ctx.token, auth)
.send(body);
const get = (batchId: string) =>
ctx
.api()
.get(`/api/v1/production-batches/${batchId}/cost-snapshot`)
.auth(ctx.token, auth);
const ready = async () => {
const batch = await prepareCostBatch(ctx);
await startCostBatch(ctx, batch.batchId);
await recordCostUsage(
ctx,
batch.batchId,
batch.productionLineId,
'CONSUMED',
'200.000',
);
await recordCostUsage(
ctx,
batch.batchId,
batch.productionLineId,
'WASTED',
'10.000',
);
await completeCostBatch(ctx, batch.batchId);
await packageCostBatch(
ctx,
batch.batchId,
batch.packagingBomId,
batch.packagingLineId,
);
await setCostRate(ctx, batch.productionMaterialId, '0.1000');
await setCostRate(ctx, batch.packagingMaterialId, '2.0000');
return batch;
};
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('freezes actual production and packaging cost at selected rate revisions', async () => {
const batch = await ready();
const body = { currency: 'INR', idempotencyKey: randomUUID() };
const created = await post(batch.batchId, body).expect(201);
expect(created.body).toMatchObject({
productionTotal: '21.00',
packagingTotal: '40.00',
total: '61.00',
});
expect(created.body.lines).toHaveLength(2);
await setCostRate(ctx, batch.productionMaterialId, '0.2000');
const saved = await get(batch.batchId).expect(200);
expect(saved.body.total).toBe('61.00');
expect(
saved.body.lines.find(
(line: { kind: string }) => line.kind === 'PRODUCTION',
),
).toMatchObject({
rateRevision: 1,
usedQuantity: '200.000',
wastedQuantity: '10.000',
});
const retry = await post(batch.batchId, body).expect(201);
expect(retry.body.id).toBe(created.body.id);
});
it('requires completed usage, packaging and cost rates', async () => {
const batch = await prepareCostBatch(ctx);
const body = { currency: 'INR', idempotencyKey: randomUUID() };
const draft = await post(batch.batchId, body).expect(409);
expect(draft.body.code).toBe('BATCH_COST_STATE');
await startCostBatch(ctx, batch.batchId);
await completeCostBatch(ctx, batch.batchId);
const missingPackage = await post(batch.batchId, body).expect(409);
expect(missingPackage.body.code).toBe('BATCH_COST_PACKAGING_MISSING');
await packageCostBatch(
ctx,
batch.batchId,
batch.packagingBomId,
batch.packagingLineId,
);
const missingUsage = await post(batch.batchId, body).expect(409);
expect(missingUsage.body.code).toBe('BATCH_COST_USAGE_INCOMPLETE');
});
it('rejects missing rates, changed retries, duplicate snapshots and other organizations', async () => {
const batch = await ready();
const body = { currency: 'USD', idempotencyKey: randomUUID() };
const missing = await post(batch.batchId, body).expect(409);
expect(missing.body.code).toBe('COST_RATE_MISSING');
const reader = await secondActor(ctx, true, ['cost.read']);
await ctx
.api()
.post(`/api/v1/production-batches/${batch.batchId}/cost-snapshot`)
.auth(reader.token, auth)
.send({ currency: 'INR', idempotencyKey: randomUUID() })
.expect(403);
const created = await post(batch.batchId, {
...body,
currency: 'INR',
}).expect(201);
const changed = await post(batch.batchId, body).expect(409);
expect(changed.body.code).toBe('BATCH_COST_REPLAY_CONFLICT');
const duplicate = await post(batch.batchId, {
currency: 'INR',
idempotencyKey: randomUUID(),
}).expect(409);
expect(duplicate.body.code).toBe('BATCH_COST_ALREADY_RECORDED');
const outsider = await secondActor(ctx, false, [
'cost.read',
'cost.manage',
]);
await ctx
.api()
.get(`/api/v1/production-batches/${batch.batchId}/cost-snapshot`)
.auth(outsider.token, auth)
.expect(404);
expect((await get(batch.batchId).expect(200)).body.id).toBe(
created.body.id,
);
});
it('costs a fully rejected batch without a packaging run', async () => {
const batch = await prepareCostBatch(ctx);
await startCostBatch(ctx, batch.batchId);
await recordCostUsage(
ctx,
batch.batchId,
batch.productionLineId,
'WASTED',
'50.000',
);
await completeCostBatch(ctx, batch.batchId, 0);
await setCostRate(ctx, batch.productionMaterialId, '0.1000');
const snapshot = await post(batch.batchId, {
currency: 'INR',
idempotencyKey: randomUUID(),
}).expect(201);
expect(snapshot.body).toMatchObject({
goodQuantity: 0,
productionTotal: '5.00',
packagingTotal: '0.00',
total: '5.00',
});
});
it('keeps snapshots and lines immutable in PostgreSQL', async () => {
const batch = await ready();
const snapshot = await post(batch.batchId, {
currency: 'INR',
idempotencyKey: randomUUID(),
}).expect(201);
await expect(
ctx.db.batchCostSnapshot.update({
where: { id: snapshot.body.id },
data: { total: '1.00' },
}),
).rejects.toThrow();
});
});

127
test/helpers/batch-cost.ts Normal file
View File

@ -0,0 +1,127 @@
import { randomUUID } from 'node:crypto';
import type { IdentityApp } from './identity-app';
import { createBatch, seedActiveBom } from './production';
const auth = { type: 'bearer' as const };
export async function prepareCostBatch(ctx: IdentityApp) {
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 ctx
.api()
.post(`/api/v1/packaging-boms/${packaging.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,
productionLineId: production.bomLineId,
productionMaterialId: production.materialId,
packagingBomId: packaging.body.id as string,
packagingLineId: packaging.body.lines[0].id as string,
packagingMaterialId: box.body.id as string,
};
}
export async function startCostBatch(ctx: IdentityApp, batchId: string) {
await ctx
.api()
.post(`/api/v1/production-batches/${batchId}/start`)
.auth(ctx.token, auth)
.expect(201);
}
export async function recordCostUsage(
ctx: IdentityApp,
batchId: string,
bomLineId: string,
kind: 'CONSUMED' | 'WASTED',
quantity: string,
) {
return ctx
.api()
.post(`/api/v1/production-batches/${batchId}/material-usage`)
.auth(ctx.token, auth)
.send({
bomLineId,
kind,
quantity,
...(kind === 'WASTED' ? { reason: 'Spill' } : {}),
idempotencyKey: randomUUID(),
})
.expect(201);
}
export async function completeCostBatch(
ctx: IdentityApp,
batchId: string,
goodQuantity = 20,
) {
await ctx
.api()
.post(`/api/v1/production-batches/${batchId}/complete`)
.auth(ctx.token, auth)
.send({
goodQuantity,
rejectedQuantity: 20 - goodQuantity,
...(goodQuantity < 20 ? { rejectionReason: 'Rejected' } : {}),
})
.expect(201);
}
export async function packageCostBatch(
ctx: IdentityApp,
batchId: string,
bomId: string,
bomLineId: string,
) {
await ctx
.api()
.post(`/api/v1/production-batches/${batchId}/packaging`)
.auth(ctx.token, auth)
.send({
bomId,
idempotencyKey: randomUUID(),
lines: [
{
bomLineId,
usedQuantity: '19.000',
wastedQuantity: '1.000',
wasteReason: 'Torn',
},
],
})
.expect(201);
}
export async function setCostRate(
ctx: IdentityApp,
materialId: string,
unitCost: string,
) {
return ctx
.api()
.post(`/api/v1/materials/${materialId}/cost-rates`)
.auth(ctx.token, auth)
.send({ currency: 'INR', unitCost })
.expect(201);
}