ManiCandles/src/pages/BomPage.tsx

194 lines
9.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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