From 3c8c6b25a3adaa080798e6e58720f35ed6ba9b76 Mon Sep 17 00:00:00 2001 From: mihir Date: Thu, 12 Nov 2026 19:08:11 +0530 Subject: [PATCH] feat: manage production and packaging BOM revisions --- docs/PHASES.md | 4 +- src/App.tsx | 9 ++ src/components/WorkspaceShell.tsx | 2 + src/lib/bom.ts | 37 ++++++ src/pages/BomPage.tsx | 190 ++++++++++++++++++++++++++++++ src/pages/CatalogAdminPage.tsx | 13 +- test/bom.test.ts | 24 ++++ test/workflows.ui.test.tsx | 78 ++++++++++++ 8 files changed, 351 insertions(+), 6 deletions(-) create mode 100644 src/lib/bom.ts create mode 100644 src/pages/BomPage.tsx create mode 100644 test/bom.test.ts diff --git a/docs/PHASES.md b/docs/PHASES.md index 0ffd730..9008e1b 100644 --- a/docs/PHASES.md +++ b/docs/PHASES.md @@ -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. - 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. -- 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. - 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. diff --git a/src/App.tsx b/src/App.tsx index e3ec678..09fc78d 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -30,6 +30,7 @@ const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage")); const InventoryPage = lazy(() => import("@/pages/InventoryPage")); const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage")); const ProcurementPage = lazy(() => import("@/pages/ProcurementPage")); +const BomPage = lazy(() => import("@/pages/BomPage")); const SupplierDocumentsPage = lazy(() => import("@/pages/SupplierDocumentsPage")); const PurchaseOrdersPage = lazy(() => import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })), @@ -86,6 +87,14 @@ function Router() { {(params) => } + {() => } + + {(params) => } + + {() => } + + {(params) => } + {() => } {(params) => } diff --git a/src/components/WorkspaceShell.tsx b/src/components/WorkspaceShell.tsx index b22c2bf..fca3129 100644 --- a/src/components/WorkspaceShell.tsx +++ b/src/components/WorkspaceShell.tsx @@ -63,6 +63,8 @@ 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: "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: "All orders", path: "/admin/orders", permission: "orders.read" }, { label: "Audit", path: "/admin/audit", permission: "audit.read" }, diff --git a/src/lib/bom.ts b/src/lib/bom.ts new file mode 100644 index 0000000..0a89477 --- /dev/null +++ b/src/lib/bom.ts @@ -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})?$/), + })), +}); diff --git a/src/pages/BomPage.tsx b/src/pages/BomPage.tsx new file mode 100644 index 0000000..c7a2aac --- /dev/null +++ b/src/pages/BomPage.tsx @@ -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; +type DraftLine = { key: number; material?: Material }; + +function FindVariant({ config }: { config: Config }) { + const { can } = usePlatform(); + const [, navigate] = useLocation(); + return + {can("catalog.read") &&

You can also open revisions from a variant in the product catalog.

} + ({ variantId: readText(data, "variantId").trim() })} + submit={async (value) => { + const { variantId } = z.object({ variantId: uuid }).parse(value); + navigate(`/admin/${config.api}/${variantId}`); + }}> + + +
; +} + +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 <> +

Variant ID {variantId}

+ Open another variant + + { setStatus(next); setOffset(0); }} + options={[{ value: "ALL", label: "All statuses" }, ...bomStatus.options.map((value) => ({ value, label: value }))]} /> + {(rows) => <> + row.id)} + rows={rows.map((row) => [ + row.revision, `${row.outputQuantity} pieces`, row.status, + , + ])} /> + + } + + {selected && } + {can(config.manage) && + {uncertain ? + The server may have saved the draft. Check revision history before reopening this variant to create another draft. + + : { + 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(); + }} />} + } + ; +} + +function RevisionDetail({ config, id, refreshList }: { + config: Config; + id: string; + refreshList: () => Promise; +}) { + const { can, request } = usePlatform(); + const path = `/${config.api}/${id}`; + const query = usePrivateQuery(path, bomDetail); + return {(revision) => +

{revision.status} · Yields {revision.outputQuantity} finished pieces

+ {revision.activatedAt &&

Activated {new Date(revision.activatedAt).toLocaleString()}

} +
line.id)} + rows={revision.lines.map((line) => [line.materialName, line.materialCode, line.unit, line.quantity])} /> + {can(config.manage) && revision.status === "DRAFT" && ( + { + try { + await request(`${path}/activate`, bomDetail, { method: "POST" }); + } finally { + await Promise.all([query.refetch(), refreshList()]); + } + }} /> + )} + }; +} + +function DraftForm({ packaging, submit }: { + packaging: boolean; + submit: (value: unknown) => Promise; +}) { + const { can } = usePlatform(); + const [lines, setLines] = useState([]); + const nextKey = useRef(0); + function addLine(material?: Material) { + const key = nextKey.current++; + setLines((current) => [...current, { key, material }]); + } + + return 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([]); }}> +

Enter material quantities for the full yield. Saved revisions keep their material names, codes and units.

+ + {can("procurement.read") && } + + {lines.map((line, index) => ( +
+ {line.material ? `${line.material.name} (${line.material.code})` : `Material line ${index + 1}`} + {!line.material && } + + +
+ ))} +
; +} + +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
+ {packaging ? "Active packaging and label materials" : "Active materials"} + {(rows) => { + const available = packaging ? rows.filter((row) => packagingMaterialKinds.some((kind) => kind === row.kind)) : rows; + return <> +
row.id)} + rows={available.map((row) => [ + row.name, row.code, row.unit, + , + ])} /> + + ; + }} + ; +} + +export default function BomPage({ variantId, packaging = false }: { variantId?: string; packaging?: boolean }) { + const config = packaging ? kinds.packaging : kinds.production; + const id = uuid.safeParse(variantId); + return + {!variantId ? : id.success ? ( + + ) : Invalid variant ID.} + ; +} diff --git a/src/pages/CatalogAdminPage.tsx b/src/pages/CatalogAdminPage.tsx index 03a8d27..14444fd 100644 --- a/src/pages/CatalogAdminPage.tsx +++ b/src/pages/CatalogAdminPage.tsx @@ -383,11 +383,14 @@ function ProductEditor({ id }: { id: string }) { `${v.currency} ${money(v.price)}`, v.active ? "Yes" : "No", v.id, - can("catalog.manage") && item.status !== "ARCHIVED" ? ( - - ) : ( - "Read only" - ), + <> + {can("catalog.manage") && item.status !== "ARCHIVED" && ( + + )} + {can("bom.read") &&
Production BOMs for {v.name}
} + {can("packaging.read") &&
Packaging BOMs for {v.name}
} + {!can("bom.read") && !can("packaging.read") && (!can("catalog.manage") || item.status === "ARCHIVED") && "Read only"} + , ])} /> {can("catalog.manage") && item.status !== "ARCHIVED" && ( diff --git a/test/bom.test.ts b/test/bom.test.ts new file mode 100644 index 0000000..fe59ac8 --- /dev/null +++ b/test/bom.test.ts @@ -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]); +}); diff --git a/test/workflows.ui.test.tsx b/test/workflows.ui.test.tsx index 5083a88..dbe9264 100644 --- a/test/workflows.ui.test.tsx +++ b/test/workflows.ui.test.tsx @@ -15,6 +15,7 @@ import ProcurementPage from "../src/pages/ProcurementPage"; import { ReceiptStockPosting } from "../src/pages/ReceiptStockPosting"; import { PurchaseOrderInvoices } from "../src/pages/PurchaseOrderInvoices"; import SupplierDocumentsPage from "../src/pages/SupplierDocumentsPage"; +import BomPage from "../src/pages/BomPage"; import theme from "../src/theme"; import { Switch, Route } from "wouter"; const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; @@ -177,6 +178,83 @@ function harness(children: ReactNode) { 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(); + 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(); + 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 () => { const version = { id, uploadedById: id, version: 1, filename: "certificate.pdf", mimeType: "application/pdf", -- 2.40.1