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])} /> {config.kind === "PRODUCTION" && revision.status === "ACTIVE" && can("production.read") && can("production.manage") && ( Plan a batch from revision {revision.revision} )} {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.} ; }