feat: manage production and packaging BOM revisions
continuous-integration/drone/push Build is passing Details

This commit is contained in:
mihir 2026-11-12 19:08:11 +05:30
parent 98e241f61b
commit 3c8c6b25a3
8 changed files with 351 additions and 6 deletions

View File

@ -35,6 +35,8 @@ Customer and administration screens are implemented, with recovery, pricing, sto
- Inspected receipts support idempotent posting to a warehouse. Staff can review material balances and movement ledgers. - Inspected receipts support idempotent posting to a warehouse. Staff can review material balances and movement ledgers.
- Issued orders support supplier invoices, payment records, reversals and voids. The backend enforces accepted quantities, outstanding balances and correction rules. - Issued orders support supplier invoices, payment records, reversals and voids. The backend enforces accepted quantities, outstanding balances and correction rules.
- Private supplier PDFs support version uploads, independent review decisions, and authenticated downloads. - Private supplier PDFs support version uploads, independent review decisions, and authenticated downloads.
- BOMs, production and packaging, costing, warehouse transfers and adjustments remain open. - Production and packaging BOMs support separate revision histories, draft creation, material snapshots and confirmed activation.
- Production batches, material usage, packaging runs, costing, 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. - 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. - 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.

View File

@ -30,6 +30,7 @@ const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
const InventoryPage = lazy(() => import("@/pages/InventoryPage")); const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage")); const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage")); const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
const BomPage = lazy(() => import("@/pages/BomPage"));
const SupplierDocumentsPage = lazy(() => import("@/pages/SupplierDocumentsPage")); const SupplierDocumentsPage = lazy(() => import("@/pages/SupplierDocumentsPage"));
const PurchaseOrdersPage = lazy(() => const PurchaseOrdersPage = lazy(() =>
import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })), import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })),
@ -86,6 +87,14 @@ function Router() {
<Route path="/admin/supplier-documents/:id"> <Route path="/admin/supplier-documents/:id">
{(params) => <SupplierDocumentsPage supplierId={params.id} />} {(params) => <SupplierDocumentsPage supplierId={params.id} />}
</Route> </Route>
<Route path="/admin/boms">{() => <BomPage />}</Route>
<Route path="/admin/boms/:id">
{(params) => <BomPage variantId={params.id} />}
</Route>
<Route path="/admin/packaging-boms">{() => <BomPage packaging />}</Route>
<Route path="/admin/packaging-boms/:id">
{(params) => <BomPage packaging variantId={params.id} />}
</Route>
<Route path="/admin/purchase-orders">{() => <PurchaseOrdersPage />}</Route> <Route path="/admin/purchase-orders">{() => <PurchaseOrdersPage />}</Route>
<Route path="/admin/purchase-orders/:id"> <Route path="/admin/purchase-orders/:id">
{(params) => <PurchaseOrdersPage orderId={params.id} />} {(params) => <PurchaseOrdersPage orderId={params.id} />}

View File

@ -63,6 +63,8 @@ export function WorkspaceNavigation() {
{ label: "Materials", path: "/admin/procurement/materials", permission: "procurement.read" }, { label: "Materials", path: "/admin/procurement/materials", permission: "procurement.read" },
{ label: "Purchase orders", path: "/admin/purchase-orders", 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 stock", path: "/admin/material-stock", permission: "inventory.read" },
{ label: "Production BOMs", path: "/admin/boms", permission: "bom.read" },
{ label: "Packaging BOMs", path: "/admin/packaging-boms", permission: "packaging.read" },
{ label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" }, { label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" },
{ label: "All orders", path: "/admin/orders", permission: "orders.read" }, { label: "All orders", path: "/admin/orders", permission: "orders.read" },
{ label: "Audit", path: "/admin/audit", permission: "audit.read" }, { label: "Audit", path: "/admin/audit", permission: "audit.read" },

37
src/lib/bom.ts Normal file
View File

@ -0,0 +1,37 @@
import { z } from "zod";
import { uuid } from "./commerce.ts";
import { materialInput } from "./procurement.ts";
export const bomKind = z.enum(["PRODUCTION", "PACKAGING"]);
export const bomStatus = z.enum(["DRAFT", "ACTIVE", "SUPERSEDED"]);
export const packagingMaterialKinds = ["PACKAGING", "LABEL"] as const;
export const bomInput = z.object({
outputQuantity: z.number().int().min(1).max(100000),
lines: z.array(z.object({
materialId: uuid,
quantity: z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places")
.refine((value) => value !== "0.000", "Quantity must be positive"),
}).strict()).min(1, "Add at least one material").max(50)
.refine((lines) => new Set(lines.map((line) => line.materialId)).size === lines.length, "Each material may occur once"),
}).strict();
export const bomSummary = z.object({
id: uuid,
variantId: uuid,
kind: bomKind,
status: bomStatus,
revision: z.number().int().min(1).max(100),
outputQuantity: bomInput.shape.outputQuantity,
activatedAt: z.string().datetime().nullable(),
});
export const bomDetail = bomSummary.extend({
lines: z.array(z.object({
id: uuid,
materialName: z.string(),
materialCode: z.string(),
unit: materialInput.shape.unit,
quantity: z.string().regex(/^\d{1,9}(\.\d{1,3})?$/),
})),
});

190
src/pages/BomPage.tsx Normal file
View File

@ -0,0 +1,190 @@
import { useRef, useState } from "react";
import { useLocation } from "wouter";
import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button";
import { ConfirmAction } from "@/components/ConfirmAction";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { isUnknownOutcome } from "@/lib/api";
import { bomDetail, bomInput, bomStatus, bomSummary, packagingMaterialKinds } from "@/lib/bom";
import { uuid } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { material } from "@/lib/procurement";
const kinds = {
production: { title: "Production BOMs", api: "boms", read: "bom.read", manage: "bom.manage", kind: "PRODUCTION" },
packaging: { title: "Packaging BOMs", api: "packaging-boms", read: "packaging.read", manage: "packaging.manage", kind: "PACKAGING" },
} as const;
type Config = (typeof kinds)[keyof typeof kinds];
type Material = z.infer<typeof material>;
type DraftLine = { key: number; material?: Material };
function FindVariant({ config }: { config: Config }) {
const { can } = usePlatform();
const [, navigate] = useLocation();
return <Panel title="Open variant revisions">
{can("catalog.read") && <p>You can also open revisions from a variant in the <WorkspaceLink href="/admin/catalog">product catalog</WorkspaceLink>.</p>}
<ActionForm label="Open revisions"
read={(data) => ({ variantId: readText(data, "variantId").trim() })}
submit={async (value) => {
const { variantId } = z.object({ variantId: uuid }).parse(value);
navigate(`/admin/${config.api}/${variantId}`);
}}>
<Field name="variantId" label="Variant ID" maxLength={36} helper="Enter the UUID of the product variant." />
</ActionForm>
</Panel>;
}
function Revisions({ config, variantId }: { config: Config; variantId: string }) {
const { can, request, scope } = usePlatform();
const client = useQueryClient();
const [offset, setOffset] = useState(0);
const [status, setStatus] = useState("ALL");
const [selected, select] = useState("");
const [uncertain, setUncertain] = useState(false);
const path = `/variants/${variantId}/${config.api}`;
const params = new URLSearchParams({ limit: "25", offset: String(offset), ...(status === "ALL" ? {} : { status }) });
const query = usePrivateQuery(`${path}?${params}`, z.array(bomSummary));
function showLatest() {
setStatus("ALL");
setOffset(0);
return client.invalidateQueries({ queryKey: ["private", scope, `${path}?limit=25&offset=0`] });
}
return <>
<p className="workspace-id">Variant ID {variantId}</p>
<WorkspaceLink href={`/admin/${config.api}`}>Open another variant</WorkspaceLink>
<Panel title="Revision history">
<Field name="status" label="Revision status" value={status} onChange={(next) => { setStatus(next); setOffset(0); }}
options={[{ value: "ALL", label: "All statuses" }, ...bomStatus.options.map((value) => ({ value, label: value }))]} />
<QueryView query={query}>{(rows) => <>
<Table head={["Revision", "Yield", "Status", "Actions"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [
row.revision, `${row.outputQuantity} pieces`, row.status,
<Button onClick={() => select(row.id)} aria-pressed={row.id === selected}>View revision {row.revision}</Button>,
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
</Panel>
{selected && <RevisionDetail key={selected} config={config} id={selected} refreshList={query.refetch} />}
{can(config.manage) && <Panel title="New draft revision">
{uncertain ? <Alert severity="warning">
The server may have saved the draft. Check revision history before reopening this variant to create another draft.
<Button onClick={() => showLatest()}>Show latest revisions</Button>
</Alert> : <DraftForm packaging={config.kind === "PACKAGING"} submit={async (body) => {
try {
const revision = await request(path, bomDetail, { method: "POST", body });
select(revision.id);
} catch (error) {
if (isUnknownOutcome(error)) {
setUncertain(true);
await showLatest();
}
throw error;
}
await showLatest();
}} />}
</Panel>}
</>;
}
function RevisionDetail({ config, id, refreshList }: {
config: Config;
id: string;
refreshList: () => Promise<unknown>;
}) {
const { can, request } = usePlatform();
const path = `/${config.api}/${id}`;
const query = usePrivateQuery(path, bomDetail);
return <QueryView query={query}>{(revision) => <Panel title={`Revision ${revision.revision}`}>
<p>{revision.status} · Yields {revision.outputQuantity} finished pieces</p>
{revision.activatedAt && <p>Activated {new Date(revision.activatedAt).toLocaleString()}</p>}
<Table head={["Material", "Code", "Unit", "Quantity for this yield"]}
rowKeys={revision.lines.map((line) => line.id)}
rows={revision.lines.map((line) => [line.materialName, line.materialCode, line.unit, line.quantity])} />
{can(config.manage) && revision.status === "DRAFT" && (
<ConfirmAction label={`Activate revision ${revision.revision}`}
message="Activation supersedes the current active revision of this type for this variant."
onConfirm={async () => {
try {
await request(`${path}/activate`, bomDetail, { method: "POST" });
} finally {
await Promise.all([query.refetch(), refreshList()]);
}
}} />
)}
</Panel>}</QueryView>;
}
function DraftForm({ packaging, submit }: {
packaging: boolean;
submit: (value: unknown) => Promise<void>;
}) {
const { can } = usePlatform();
const [lines, setLines] = useState<DraftLine[]>([]);
const nextKey = useRef(0);
function addLine(material?: Material) {
const key = nextKey.current++;
setLines((current) => [...current, { key, material }]);
}
return <ActionForm label="Create draft revision" read={(data) => bomInput.parse({
outputQuantity: Number(readText(data, "outputQuantity")),
lines: lines.map((line) => ({
materialId: line.material?.id ?? readText(data, `material-${line.key}`).trim(),
quantity: readText(data, `quantity-${line.key}`).trim(),
})),
})} submit={async (body) => { await submit(body); setLines([]); }}>
<p>Enter material quantities for the full yield. Saved revisions keep their material names, codes and units.</p>
<Field name="outputQuantity" label="Finished pieces per yield" type="number" />
{can("procurement.read") && <MaterialPicker packaging={packaging} lines={lines} addLine={addLine} />}
<Button type="button" onClick={() => addLine()} disabled={lines.length >= 50}>Add material by ID</Button>
{lines.map((line, index) => (
<fieldset className="record-picker" key={line.key}>
<legend>{line.material ? `${line.material.name} (${line.material.code})` : `Material line ${index + 1}`}</legend>
{!line.material && <Field name={`material-${line.key}`} label={`Material ID for line ${index + 1}`} maxLength={36} />}
<Field name={`quantity-${line.key}`} maxLength={13} label={line.material ? `Quantity for ${line.material.name}` : `Quantity for line ${index + 1}`}
helper={line.material ? `Use three decimal places in ${line.material.unit}.` : "Use three decimal places in the material’s native unit."} />
<Button type="button" onClick={() => setLines((current) => current.filter((entry) => entry.key !== line.key))}>Remove line {index + 1}</Button>
</fieldset>
))}
</ActionForm>;
}
function MaterialPicker({ packaging, lines, addLine }: {
packaging: boolean;
lines: DraftLine[];
addLine: (material: Material) => void;
}) {
const [offset, setOffset] = useState(0);
const query = usePrivateQuery(`/materials?limit=25&offset=${offset}&active=true`, z.array(material));
return <fieldset className="record-picker">
<legend>{packaging ? "Active packaging and label materials" : "Active materials"}</legend>
<QueryView query={query}>{(rows) => {
const available = packaging ? rows.filter((row) => packagingMaterialKinds.some((kind) => kind === row.kind)) : rows;
return <>
<Table head={["Material", "Code", "Unit", "Actions"]} rowKeys={available.map((row) => row.id)}
rows={available.map((row) => [
row.name, row.code, row.unit,
<Button type="button" onClick={() => addLine(row)}
disabled={lines.length >= 50 || lines.some((line) => line.material?.id === row.id)}>
Add {row.name}
</Button>,
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>;
}}</QueryView>
</fieldset>;
}
export default function BomPage({ variantId, packaging = false }: { variantId?: string; packaging?: boolean }) {
const config = packaging ? kinds.packaging : kinds.production;
const id = uuid.safeParse(variantId);
return <WorkspaceShell title={config.title} permission={config.read}>
{!variantId ? <FindVariant key={config.api} config={config} /> : id.success ? (
<Revisions key={`${config.api}:${id.data}`} config={config} variantId={id.data} />
) : <Alert severity="warning">Invalid variant ID.</Alert>}
</WorkspaceShell>;
}

View File

@ -383,11 +383,14 @@ function ProductEditor({ id }: { id: string }) {
`${v.currency} ${money(v.price)}`, `${v.currency} ${money(v.price)}`,
v.active ? "Yes" : "No", v.active ? "Yes" : "No",
v.id, v.id,
can("catalog.manage") && item.status !== "ARCHIVED" ? ( <>
<Button onClick={() => setEditingVariant(v)}>Edit</Button> {can("catalog.manage") && item.status !== "ARCHIVED" && (
) : ( <Button onClick={() => setEditingVariant(v)} aria-label={`Edit ${v.name}`}>Edit</Button>
"Read only" )}
), {can("bom.read") && <div><WorkspaceLink href={`/admin/boms/${v.id}`}>Production BOMs for {v.name}</WorkspaceLink></div>}
{can("packaging.read") && <div><WorkspaceLink href={`/admin/packaging-boms/${v.id}`}>Packaging BOMs for {v.name}</WorkspaceLink></div>}
{!can("bom.read") && !can("packaging.read") && (!can("catalog.manage") || item.status === "ARCHIVED") && "Read only"}
</>,
])} ])}
/> />
{can("catalog.manage") && item.status !== "ARCHIVED" && ( {can("catalog.manage") && item.status !== "ARCHIVED" && (

24
test/bom.test.ts Normal file
View File

@ -0,0 +1,24 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { bomDetail, bomInput, bomSummary } from "../src/lib/bom.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
test("draft BOMs preserve exact quantities and reject duplicate materials and invalid yields", () => {
const line = { materialId: id, quantity: "0.125" };
const input = { outputQuantity: 10, lines: [line] };
assert.deepEqual(bomInput.parse(input), input);
assert.equal(bomInput.safeParse({ ...input, outputQuantity: 100001 }).success, false);
assert.equal(bomInput.safeParse({ ...input, lines: [] }).success, false);
assert.equal(bomInput.safeParse({ ...input, lines: [{ ...line, quantity: "0.000" }] }).success, false);
assert.equal(bomInput.safeParse({ ...input, lines: [{ ...line, quantity: "0.12" }] }).success, false);
assert.equal(bomInput.safeParse({ ...input, lines: [line, { ...line, materialId: id.toUpperCase() }] }).success, false);
});
test("revision lists accept metadata without lines and details accept serialized decimal snapshots", () => {
const metadata = { id, variantId: id, kind: "PACKAGING", status: "DRAFT", revision: 1, outputQuantity: 10, activatedAt: null };
assert.deepEqual(bomSummary.parse(metadata), metadata);
assert.equal(bomDetail.safeParse(metadata).success, false);
const line = { id, materialName: "Label", materialCode: "LABEL", unit: "PIECE", quantity: "10" };
assert.deepEqual(bomDetail.parse({ ...metadata, lines: [line] }).lines, [line]);
});

View File

@ -15,6 +15,7 @@ import ProcurementPage from "../src/pages/ProcurementPage";
import { ReceiptStockPosting } from "../src/pages/ReceiptStockPosting"; import { ReceiptStockPosting } from "../src/pages/ReceiptStockPosting";
import { PurchaseOrderInvoices } from "../src/pages/PurchaseOrderInvoices"; import { PurchaseOrderInvoices } from "../src/pages/PurchaseOrderInvoices";
import SupplierDocumentsPage from "../src/pages/SupplierDocumentsPage"; import SupplierDocumentsPage from "../src/pages/SupplierDocumentsPage";
import BomPage from "../src/pages/BomPage";
import theme from "../src/theme"; import theme from "../src/theme";
import { Switch, Route } from "wouter"; import { Switch, Route } from "wouter";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
@ -177,6 +178,83 @@ function harness(children: ReactNode) {
return { client, ...result }; return { client, ...result };
} }
test("packaging staff draft and activate an independent BOM with eligible materials", async () => {
const draftId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const draft = {
id: draftId, variantId: id, kind: "PACKAGING", status: "DRAFT", revision: 2,
outputQuantity: 10, activatedAt: null,
lines: [{ id, materialName: "Label", materialCode: "LABEL", unit: "PIECE", quantity: "10" }],
};
const first = { ...draft, id, revision: 1, status: "ACTIVE", activatedAt: "2026-11-12T00:00:00.000Z" };
let created = false;
let activated = false;
let draftBody: unknown;
const 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: ["packaging.read", "packaging.manage", "procurement.read"] });
if (url.includes("/materials?")) return json([
{ id, name: "Label", code: "LABEL", kind: "LABEL", unit: "PIECE", active: true },
{ id: draftId, name: "Wax", code: "WAX", kind: "WAX", unit: "GRAM", active: true },
]);
const current = activated ? { ...draft, status: "ACTIVE", activatedAt: first.activatedAt } : draft;
if (url.includes(`/variants/${id}/packaging-boms?`))
return json(created ? [current, { ...first, status: activated ? "SUPERSEDED" : "ACTIVE" }] : [first]);
if (url.endsWith(`/variants/${id}/packaging-boms`) && options?.method === "POST") {
draftBody = JSON.parse(String(options.body));
created = true;
return json(draft);
}
if (url.endsWith(`/packaging-boms/${draftId}`)) return json(current);
if (url.endsWith(`/packaging-boms/${draftId}/activate`) && options?.method === "POST") {
activated = true;
return json({ ...draft, status: "ACTIVE", activatedAt: first.activatedAt });
}
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
harness(<BomPage variantId={id} packaging />);
expect(fetch).not.toHaveBeenCalled();
const user = userEvent.setup();
await user.click(screen.getByText("Test login"));
await user.click(await screen.findByRole("button", { name: "Add Label" }));
expect(screen.queryByRole("button", { name: "Add Wax" })).toBeNull();
await user.type(screen.getByRole("spinbutton", { name: /Finished pieces/ }), "10");
await user.type(screen.getByRole("textbox", { name: /Quantity for Label/ }), "10.000");
await user.click(screen.getByRole("button", { name: "Create draft revision" }));
await user.click(await screen.findByRole("button", { name: "Activate revision 2" }));
await user.click(screen.getByRole("button", { name: "Confirm" }));
await screen.findByText("ACTIVE · Yields 10 finished pieces");
await screen.findByRole("cell", { name: "SUPERSEDED" });
expect(draftBody).toEqual({ outputQuantity: 10, lines: [{ materialId: id, quantity: "10.000" }] });
expect(screen.queryByRole("link", { name: "Production BOMs" })).toBeNull();
expect(fetch.mock.calls.some(([url]) => url.includes(`/variants/${id}/boms`))).toBe(false);
});
test("production BOM observers can review a draft without seeing write controls", async () => {
const revision = {
id, variantId: id, kind: "PRODUCTION", status: "DRAFT", revision: 1,
outputQuantity: 1, activatedAt: null,
};
const fetch = vi.fn(async (url: string) => {
if (url.endsWith("/auth/login")) return json(session);
if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["bom.read"] });
if (url.includes(`/variants/${id}/boms?`)) return json([revision]);
if (url.endsWith(`/boms/${id}`)) return json({
...revision, lines: [{ id, materialName: "Wax", materialCode: "WAX", unit: "GRAM", quantity: "125.5" }],
});
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
harness(<BomPage variantId={id} />);
const user = userEvent.setup();
await user.click(screen.getByText("Test login"));
await user.click(await screen.findByRole("button", { name: "View revision 1" }));
await screen.findByRole("cell", { name: "125.5" });
expect(screen.queryByRole("button", { name: "Create draft revision" })).toBeNull();
expect(screen.queryByRole("button", { name: "Activate revision 1" })).toBeNull();
expect(fetch.mock.calls.some(([url]) => url.includes("/materials"))).toBe(false);
});
test("supplier document reviewer sees only permitted actions for their own upload", async () => { test("supplier document reviewer sees only permitted actions for their own upload", async () => {
const version = { const version = {
id, uploadedById: id, version: 1, filename: "certificate.pdf", mimeType: "application/pdf", id, uploadedById: id, version: 1, filename: "certificate.pdf", mimeType: "application/pdf",