diff --git a/docs/PHASES.md b/docs/PHASES.md
index b7dc056..6f05e2e 100644
--- a/docs/PHASES.md
+++ b/docs/PHASES.md
@@ -38,7 +38,9 @@ Customer and administration screens are implemented, with recovery, pricing, sto
- Production and packaging BOMs support separate revision histories, draft creation, material snapshots and confirmed activation.
- Production batches support draft planning, start, completion, cancellation, and exact planned material quantities. Staff can log consumption and waste and reconcile the results against the plan.
- Completed batches support packaging runs, production and packaging material debits, and receipt of good finished pieces into warehouse stock.
-- Costing, warehouse transfers and adjustments remain open.
+- Costing supports immutable material rate revisions, current-rate BOM estimates, and completed-batch cost snapshots with exact totals and saved rate revisions.
+- Warehouse transfers and adjustments remain open.
- Live acceptance requires an organization and procurement test users. Exercise read-only and manage roles, inactive suppliers and materials, mixed currencies, below-minimum quantities, price snapshots and purchase order state conflicts.
- Supplier document UAT requires an uploader, an independent reviewer, and a read-only account. Through the deployed ingress, upload a valid PDF near the 2 MiB limit, verify that the uploader cannot decide on it, and check that a reader can download it only after approval.
- BOM UAT should activate a second revision and confirm the previous revision becomes superseded. Repeat for the other BOM type and verify its active revision is independent. Check that inactive materials and stale drafts are rejected.
+- Costing UAT should revise a material rate and verify that future BOM estimates use the new revision while an existing batch snapshot retains its original amounts and rates. Test missing rates, missing usage, and fully rejected output.
diff --git a/src/App.tsx b/src/App.tsx
index f445eb4..e38cee0 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -29,6 +29,7 @@ const AuditPage = lazy(() =>
const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
+const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
const BomPage = lazy(() => import("@/pages/BomPage"));
const ProductionBatchesPage = lazy(() => import("@/pages/ProductionBatchesPage"));
@@ -75,6 +76,10 @@ function Router() {
{(params) => }
+ {() => }
+
+ {(params) => }
+
{(params) => }
diff --git a/src/components/WorkspaceShell.tsx b/src/components/WorkspaceShell.tsx
index b5b1c08..e7fc74d 100644
--- a/src/components/WorkspaceShell.tsx
+++ b/src/components/WorkspaceShell.tsx
@@ -63,6 +63,7 @@ export function WorkspaceNavigation() {
{ label: "Materials", path: "/admin/procurement/materials", permission: "procurement.read" },
{ label: "Purchase orders", path: "/admin/purchase-orders", permission: "procurement.read" },
{ label: "Material stock", path: "/admin/material-stock", permission: "inventory.read" },
+ { label: "Material cost rates", path: "/admin/material-cost-rates", permission: "cost.read" },
{ label: "Production BOMs", path: "/admin/boms", permission: "bom.read" },
{ label: "Production batches", path: "/admin/production-batches", permission: "production.read" },
{ label: "Packaging BOMs", path: "/admin/packaging-boms", permission: "packaging.read" },
diff --git a/src/lib/costing.ts b/src/lib/costing.ts
new file mode 100644
index 0000000..259e004
--- /dev/null
+++ b/src/lib/costing.ts
@@ -0,0 +1,65 @@
+import { z } from "zod";
+import { bomKind } from "./bom.ts";
+import { currency, uuid } from "./commerce.ts";
+import { materialInput } from "./procurement.ts";
+
+const cents = z.string().regex(/^\d{1,10}\.\d{2}$/);
+const quantity = z.string().regex(/^\d{1,9}\.\d{3}$/);
+const rateRevision = z.number().int().min(1).max(1000);
+const timestamp = z.string().datetime();
+
+export const costRateInput = z.object({
+ currency,
+ unitCost: z.string().regex(/^(0|[1-9]\d{0,7})\.\d{4}$/, "Use four decimal places")
+ .refine((value) => value !== "0.0000", "Unit cost must be positive"),
+}).strict();
+
+export const costRate = z.object({
+ id: uuid,
+ materialId: uuid,
+ currency,
+ revision: rateRevision,
+ unitCost: z.string().regex(/^\d{1,8}(\.\d{1,4})?$/),
+ createdAt: timestamp,
+});
+
+const costLine = z.object({
+ bomLineId: uuid,
+ materialId: uuid,
+ materialCode: z.string(),
+ materialName: z.string(),
+ unit: materialInput.shape.unit,
+ rateId: uuid,
+ rateRevision,
+ unitCost: costRateInput.shape.unitCost,
+});
+
+export const bomEstimate = z.object({
+ bomId: uuid,
+ kind: bomKind,
+ currency,
+ outputQuantity: z.number().int().positive(),
+ estimatedAt: timestamp,
+ estimatedTotal: cents,
+ lines: z.array(costLine.extend({ quantity, estimatedCost: cents })),
+});
+
+export const snapshotInput = z.object({ currency, idempotencyKey: uuid }).strict();
+export const batchSnapshot = z.object({
+ id: uuid,
+ batchId: uuid,
+ currency,
+ goodQuantity: z.number().int().min(0).max(100000),
+ createdAt: timestamp,
+ productionTotal: cents,
+ packagingTotal: cents,
+ total: cents,
+ lines: z.array(costLine.extend({
+ kind: bomKind,
+ usedQuantity: quantity,
+ wastedQuantity: quantity,
+ lineCost: cents,
+ })),
+});
+
+export const costCurrencies = currency.options.map((value) => ({ value, label: value }));
diff --git a/src/pages/BomPage.tsx b/src/pages/BomPage.tsx
index c98852f..e5bd9b8 100644
--- a/src/pages/BomPage.tsx
+++ b/src/pages/BomPage.tsx
@@ -12,6 +12,7 @@ import { bomDetail, bomInput, bomStatus, bomSummary, packagingMaterialKinds } fr
import { uuid } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { material } from "@/lib/procurement";
+import { BomCostEstimate } from "./CostingPanels";
const kinds = {
production: { title: "Production BOMs", api: "boms", read: "bom.read", manage: "bom.manage", kind: "PRODUCTION" },
@@ -103,7 +104,10 @@ function RevisionDetail({ config, id, refreshList }: {
{revision.activatedAt &&
Activated {new Date(revision.activatedAt).toLocaleString()}
}
line.id)}
- rows={revision.lines.map((line) => [line.materialName, line.materialCode, line.unit, line.quantity])} />
+ rows={revision.lines.map((line) => [
+ can("cost.read") ? {line.materialName} : line.materialName,
+ line.materialCode, line.unit, line.quantity,
+ ])} />
{config.kind === "PRODUCTION" && revision.status === "ACTIVE" && can("production.read") && can("production.manage") && (
Plan a batch from revision {revision.revision}
)}
@@ -118,6 +122,7 @@ function RevisionDetail({ config, id, refreshList }: {
}
}} />
)}
+ {can("cost.read") && }
};
}
diff --git a/src/pages/CostingPanels.tsx b/src/pages/CostingPanels.tsx
new file mode 100644
index 0000000..8b80cdc
--- /dev/null
+++ b/src/pages/CostingPanels.tsx
@@ -0,0 +1,75 @@
+import { useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import Alert from "@mui/material/Alert";
+import { ActionForm, Field, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
+import { useOptionalPrivateQuery } from "@/components/useOptionalPrivateQuery";
+import { ApiError } from "@/lib/api";
+import { batchSnapshot, bomEstimate, costCurrencies, snapshotInput } from "@/lib/costing";
+import { usePlatform } from "@/lib/platform";
+import { useIdempotentCommand } from "@/lib/use-idempotent-command";
+
+export function BomCostEstimate({ path }: { path: string }) {
+ const [currency, setCurrency] = useState("INR");
+ const query = usePrivateQuery(`${path}/cost-estimate?currency=${currency}`, bomEstimate);
+ return
+
+ {(data) => <>
+ {data.currency} {data.estimatedTotal} for {data.outputQuantity} pieces · Calculated {new Date(data.estimatedAt).toLocaleString()}
+ line.bomLineId)}
+ rows={data.lines.map((line) => [
+ {line.materialName} ({line.materialCode}) ,
+ `${line.quantity} ${line.unit}`, `${data.currency} ${line.unitCost}`, line.rateRevision,
+ `${data.currency} ${line.estimatedCost}`,
+ ])} />
+ >}
+ ;
+}
+
+export function BatchCostSnapshot({ batchId, goodQuantity }: { batchId: string; goodQuantity: number }) {
+ const { can, scope } = usePlatform();
+ const client = useQueryClient();
+ const path = `/production-batches/${batchId}/cost-snapshot`;
+ const query = useOptionalPrivateQuery(path, batchSnapshot, "BATCH_COST_NOT_FOUND");
+ const command = useIdempotentCommand(path, snapshotInput, batchSnapshot, batchId);
+ const pending = command.pending;
+
+ return
+ Standard material costs include production and packaging use and waste. Labor, overhead, tax and freight are excluded.
+ {(snapshot) => {
+ if (snapshot) return <>
+ Saved {new Date(snapshot.createdAt).toLocaleString()} · {snapshot.goodQuantity} good pieces
+
+ Production {snapshot.currency} {snapshot.productionTotal}
+ Packaging {snapshot.currency} {snapshot.packagingTotal}
+ Total {snapshot.currency} {snapshot.total}
+
+ `${line.kind}:${line.bomLineId}`)}
+ rows={snapshot.lines.map((line) => [
+ line.kind === "PRODUCTION" ? "Production" : "Packaging",
+ {line.materialName} ({line.materialCode}) ,
+ `${line.usedQuantity} ${line.unit}`, `${line.wastedQuantity} ${line.unit}`,
+ `${snapshot.currency} ${line.unitCost}`, line.rateRevision, `${snapshot.currency} ${line.lineCost}`,
+ ])} />
+ >;
+ if (!can("cost.manage")) return No cost snapshot recorded. ;
+ return pending ? {} : ({ currency: readText(form, "currency") })}
+ submit={async (body) => {
+ try {
+ const saved = await command.run(body);
+ client.setQueryData(["private", scope, path], saved);
+ } catch (error) {
+ if (error instanceof ApiError && error.code === "BATCH_COST_ALREADY_RECORDED") await query.refetch();
+ throw error;
+ }
+ }}>
+ {pending ? The server may have saved the snapshot. Retrying uses the original currency {pending.currency}. : <>
+ Record usage for every production material{goodQuantity > 0 ? " and complete the packaging run" : ""}. Creating a snapshot fixes its currency and rates.
+
+ >}
+ ;
+ }}
+ ;
+}
diff --git a/src/pages/MaterialCostRatesPage.tsx b/src/pages/MaterialCostRatesPage.tsx
new file mode 100644
index 0000000..3751ee2
--- /dev/null
+++ b/src/pages/MaterialCostRatesPage.tsx
@@ -0,0 +1,102 @@
+import { useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { useLocation } from "wouter";
+import { z } from "zod";
+import Alert from "@mui/material/Alert";
+import Button from "@mui/material/Button";
+import { WorkspaceShell } from "@/components/WorkspaceShell";
+import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
+import { isUnknownOutcome } from "@/lib/api";
+import { uuid } from "@/lib/commerce";
+import { costCurrencies, costRate, costRateInput } from "@/lib/costing";
+import { usePlatform } from "@/lib/platform";
+
+const route = "/admin/material-cost-rates";
+
+function OpenMaterial() {
+ const { can } = usePlatform();
+ const [, navigate] = useLocation();
+ return
+ {can("procurement.read") && Choose a material from the material directory .
}
+ ({ materialId: readText(data, "materialId").trim() })}
+ submit={async (input) => {
+ const { materialId } = z.object({ materialId: uuid }).parse(input);
+ navigate(`${route}/${materialId}`);
+ }}>
+
+
+ ;
+}
+
+function Rates({ id }: { id: string }) {
+ const { can, request, scope } = usePlatform();
+ const client = useQueryClient();
+ const [currency, setCurrency] = useState("INR");
+ const [offset, setOffset] = useState(0);
+ const [uncertain, setUncertain] = useState("");
+ const [saving, setSaving] = useState(false);
+ const path = `/materials/${id}/cost-rates`;
+ const page = `${path}?currency=${currency}&limit=25&offset=${offset}`;
+ const query = usePrivateQuery(page, z.array(costRate));
+
+ async function refresh() {
+ setOffset(0);
+ await client.invalidateQueries({
+ predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
+ typeof queryKey[2] === "string" &&
+ (queryKey[2].startsWith(`${path}?currency=${currency}&`) || queryKey[2].endsWith(`/cost-estimate?currency=${currency}`)),
+ });
+ }
+
+ return <>
+ Open another material
+ Material ID {id}
+
+
+ { setCurrency(value); setOffset(0); }} />
+
+ {(rows) => <>
+ row.id)}
+ rows={rows.map((row) => [row.revision, `${row.currency} ${row.unitCost}`, new Date(row.createdAt).toLocaleString()])} />
+
+ >}
+
+ {can("cost.manage") &&
+ {uncertain ?
+ The server may have saved the {uncertain} rate. Check its latest revision before recording another rate.
+ {
+ setCurrency(uncertain);
+ setOffset(0);
+ void client.invalidateQueries({ queryKey: ["private", scope, `${path}?currency=${uncertain}&limit=25&offset=0`] });
+ }}>Check rate history
+ : costRateInput.parse({ currency, unitCost: readText(form, "unitCost").trim() })}
+ submit={async (body) => {
+ setSaving(true);
+ try {
+ await request(path, costRate, { method: "POST", body });
+ await refresh();
+ } catch (error) {
+ if (isUnknownOutcome(error)) {
+ setUncertain(currency);
+ await refresh();
+ }
+ throw error;
+ } finally {
+ setSaving(false);
+ }
+ }}>
+ Each rate is an immutable revision. Enter the cost per material’s native unit.
+
+ }
+ }
+ >;
+}
+
+export default function MaterialCostRatesPage({ materialId }: { materialId?: string }) {
+ const id = uuid.safeParse(materialId);
+ return
+ {!materialId ? : id.success ? : Invalid material ID. }
+ ;
+}
diff --git a/src/pages/ProcurementPage.tsx b/src/pages/ProcurementPage.tsx
index 1ed8ca5..d729cbe 100644
--- a/src/pages/ProcurementPage.tsx
+++ b/src/pages/ProcurementPage.tsx
@@ -38,6 +38,7 @@ function Directory({ materials }: { materials: boolean }) {
row.active ? "Active" : "Inactive",
<>
{can("procurement.manage") && select(row.id)} aria-label={`Edit ${row.name}`}>Edit }
+ {"kind" in row && can("cost.read") && Cost rates for {row.name} }
{"contactName" in row && Supply terms and orders for {row.name} }
{"contactName" in row && can("supplier_document.read") && (
<> · Documents for {row.name} >
diff --git a/src/pages/ProductionBatchesPage.tsx b/src/pages/ProductionBatchesPage.tsx
index 626d71e..10d2f33 100644
--- a/src/pages/ProductionBatchesPage.tsx
+++ b/src/pages/ProductionBatchesPage.tsx
@@ -11,6 +11,7 @@ import { usePlatform } from "@/lib/platform";
import { batchDetail, batchInput, batchStatus, cancelBatchInput, parseCompletion, productionBatch } from "@/lib/production";
import { BatchMaterialUsage } from "./BatchMaterialUsage";
import { CompletedBatchOperations } from "./CompletedBatchOperations";
+import { BatchCostSnapshot } from "./CostingPanels";
const route = "/admin/production-batches";
const api = "/production-batches";
@@ -103,6 +104,9 @@ function BatchDetails({ id }: { id: string }) {
{batch.status === "COMPLETED" && }
+ {batch.status === "COMPLETED" && batch.completion && can("cost.read") && (
+
+ )}
{can("production.manage") && batch.status === "IN_PROGRESS" && (
Record all material usage before completing production. Completion closes the batch to new usage entries.
diff --git a/test/costing.test.ts b/test/costing.test.ts
new file mode 100644
index 0000000..7261297
--- /dev/null
+++ b/test/costing.test.ts
@@ -0,0 +1,34 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { batchSnapshot, bomEstimate, costRate, costRateInput } from "../src/lib/costing.ts";
+
+const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
+const date = "2026-11-14T00:00:00.000Z";
+const material = {
+ bomLineId: id, materialId: id, materialCode: "WAX", materialName: "Wax",
+ unit: "GRAM", rateId: id, rateRevision: 2, unitCost: "99999999.9999",
+};
+
+test("standard rates preserve four input decimals and accept serialized revision history", () => {
+ const input = { currency: "INR", unitCost: "0.1250" };
+ assert.deepEqual(costRateInput.parse(input), input);
+ assert.equal(costRateInput.safeParse({ ...input, unitCost: "0.0000" }).success, false);
+ assert.equal(costRateInput.safeParse({ ...input, unitCost: "0.125" }).success, false);
+ assert.equal(costRateInput.safeParse({ ...input, currency: "JPY" }).success, false);
+ assert.equal(costRate.parse({ ...input, id, materialId: id, revision: 2, createdAt: date, unitCost: "0.125" }).unitCost, "0.125");
+});
+
+test("estimates and snapshots preserve exact backend totals and rate references", () => {
+ const estimate = {
+ bomId: id, kind: "PACKAGING", currency: "USD", outputQuantity: 10, estimatedAt: date,
+ estimatedTotal: "9999999999.99", lines: [{ ...material, quantity: "100.000", estimatedCost: "9999999999.99" }],
+ };
+ assert.deepEqual(bomEstimate.parse(estimate), estimate);
+ const snapshot = {
+ id, batchId: id, currency: "USD", goodQuantity: 0, createdAt: date, productionTotal: "9999999999.99",
+ packagingTotal: "0.00", total: "9999999999.99",
+ lines: [{ ...material, kind: "PRODUCTION", usedQuantity: "100.000", wastedQuantity: "0.000", lineCost: "9999999999.99" }],
+ };
+ assert.deepEqual(batchSnapshot.parse(snapshot), snapshot);
+ assert.equal(batchSnapshot.safeParse({ ...snapshot, total: 9999999999.99 }).success, false);
+});
diff --git a/test/workflows.ui.test.tsx b/test/workflows.ui.test.tsx
index 36fac96..677f7a3 100644
--- a/test/workflows.ui.test.tsx
+++ b/test/workflows.ui.test.tsx
@@ -18,6 +18,8 @@ import SupplierDocumentsPage from "../src/pages/SupplierDocumentsPage";
import BomPage from "../src/pages/BomPage";
import ProductionBatchesPage from "../src/pages/ProductionBatchesPage";
import { CompletedBatchOperations } from "../src/pages/CompletedBatchOperations";
+import { BatchCostSnapshot } from "../src/pages/CostingPanels";
+import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage";
import { batchDetail } from "../src/lib/production";
import theme from "../src/theme";
import { Switch, Route } from "wouter";
@@ -181,6 +183,72 @@ function harness(children: ReactNode) {
return { client, ...result };
}
+test("recording a material rate refreshes the selected currency history", async () => {
+ let body: unknown;
+ let finish: (() => void) | undefined;
+ const rate = { id, materialId: id, currency: "USD", revision: 1, unitCost: "0.125", createdAt: "2026-11-14T00:00:00.000Z" };
+ vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
+ if (url.endsWith("/auth/login")) return json(session);
+ if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["cost.read", "cost.manage"] });
+ if (url.endsWith(`/materials/${id}/cost-rates`) && options?.method === "POST") {
+ body = JSON.parse(String(options.body));
+ return new Promise((resolve) => { finish = () => resolve(json(rate)); });
+ }
+ if (url.includes(`/materials/${id}/cost-rates?`)) return json(body && url.includes("currency=USD") ? [rate] : []);
+ throw new Error(`Unexpected request ${url}`);
+ }));
+ harness( );
+ const user = userEvent.setup();
+ await user.click(screen.getByText("Test login"));
+ const currency = await screen.findByRole("combobox", { name: /Rate currency/ });
+ await user.selectOptions(currency, "USD");
+ await user.type(screen.getByRole("textbox", { name: /Unit cost in USD/ }), "0.1250");
+ await user.click(screen.getByRole("button", { name: "Record standard cost rate" }));
+ await waitFor(() => expect(finish).toBeDefined());
+ expect(currency.matches(":disabled")).toBe(true);
+ await act(async () => { finish?.(); });
+ await screen.findByRole("cell", { name: "USD 0.125" });
+ expect(body).toEqual({ currency: "USD", unitCost: "0.1250" });
+ await user.selectOptions(currency, "INR");
+ await waitFor(() => expect(screen.queryByRole("cell", { name: "USD 0.125" })).toBeNull());
+});
+
+test("a batch cost snapshot retries in the original currency and displays the saved totals", async () => {
+ const attempts: unknown[] = [];
+ const snapshot = {
+ id, batchId: id, currency: "USD", goodQuantity: 10, createdAt: "2026-11-14T00:00:00.000Z",
+ productionTotal: "12.34", packagingTotal: "0.66", total: "13.00",
+ lines: [{
+ kind: "PRODUCTION", bomLineId: id, materialId: id, materialCode: "WAX", materialName: "Wax", unit: "GRAM",
+ rateId: id, rateRevision: 2, unitCost: "0.1234", usedQuantity: "100.000", wastedQuantity: "0.000", lineCost: "12.34",
+ }],
+ };
+ vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
+ if (url.endsWith("/auth/login")) return json(session);
+ if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["cost.read", "cost.manage"] });
+ if (!url.endsWith(`/production-batches/${id}/cost-snapshot`)) throw new Error(`Unexpected request ${url}`);
+ if (options?.method !== "POST") return attempts.length ? json(snapshot) : json({ code: "BATCH_COST_NOT_FOUND" }, 404);
+ attempts.push(JSON.parse(String(options.body)));
+ if (attempts.length === 1) throw new Error("Response lost");
+ return json(snapshot);
+ }));
+ function AuthorizedSnapshot() {
+ return usePlatform().can("cost.read") ? : null;
+ }
+ harness( );
+ const user = userEvent.setup();
+ await user.click(screen.getByText("Test login"));
+ await user.selectOptions(await screen.findByRole("combobox", { name: /Snapshot currency/ }), "USD");
+ await user.click(screen.getByRole("button", { name: "Create cost snapshot" }));
+ await user.click(await screen.findByRole("button", { name: "Retry cost snapshot" }));
+ await screen.findByText("USD 13.00");
+ expect(attempts).toHaveLength(2);
+ expect(attempts[0]).toEqual({ currency: "USD", idempotencyKey: expect.any(String) });
+ expect(attempts[1]).toEqual(attempts[0]);
+ expect(screen.getByRole("cell", { name: "USD 0.1234" })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Create cost snapshot" })).toBeNull();
+});
+
test("completed production posts both material debits before receiving good pieces and retries with the same key", async () => {
const date = "2026-11-14T00:00:00.000Z";
const labelId = "d66c798a-f764-4b88-8d13-ace328ff1011";