ManiCandles/src/pages/BatchMaterialUsage.tsx

61 lines
3.7 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 { useState } from "react";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import { ActionForm, Field, Pager, Panel, QueryView, Table, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { usePlatform } from "@/lib/platform";
import { batchDetail, batchUsage, usageEvent, usageInput } from "@/lib/production";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
export function BatchMaterialUsage({ batch }: { batch: z.infer<typeof batchDetail> }) {
const { can } = usePlatform();
const [offset, setOffset] = useState(0);
const path = `/production-batches/${batch.id}/material-usage`;
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, batchUsage);
const command = useIdempotentCommand(path, usageInput, usageEvent, batch.id);
const labels = new Map(batch.plannedMaterials.map((line) => [line.id, `${line.materialName} (${line.materialCode}) · ${line.unit}`]));
const pending = command.pending;
return <Panel title="Material usage">
<QueryView query={query}>{(data) => <>
<Table head={["Material", "Planned", "Consumed", "Wasted", "Variance"]}
rowKeys={data.materials.map((line) => line.bomLineId)} rows={data.materials.map((line) => [
`${line.materialName} (${line.materialCode}) · ${line.unit}`, line.plannedQuantity,
line.consumedQuantity, line.wastedQuantity, line.varianceQuantity,
])} />
<h3>Usage history</h3>
<Table head={["Time", "Material", "Event", "Quantity", "Reason"]}
rowKeys={data.events.map((event) => event.id)} rows={data.events.map((event) => [
new Date(event.createdAt).toLocaleString(), labels.get(event.bomLineId) ?? event.bomLineId,
event.kind, event.quantity, event.reason ?? "—",
])} />
<Pager offset={offset} count={offset + data.events.length < data.total ? 25 : 0} onPage={setOffset} />
{can("production.material.record") && (pending || (batch.status === "IN_PROGRESS" && data.total < 500)) && (
<ActionForm key={pending ? "retry" : "record"} label={pending ? "Retry material usage" : "Record material usage"}
read={(form) => pending ? {} : ({
bomLineId: readText(form, "bomLineId"),
kind: readText(form, "kind"),
quantity: readText(form, "quantity").trim(),
reason: readText(form, "reason").trim() || undefined,
})}
submit={async (input) => {
await command.run(input);
const result = await query.refetch();
if (result.data) setOffset(Math.floor(Math.max(0, result.data.total - 1) / 25) * 25);
}}>
{pending ? (
<Alert severity="warning">The server may have saved this entry. Retrying reuses {pending.quantity} for {labels.get(pending.bomLineId) ?? pending.bomLineId} as {pending.kind.toLowerCase()}.</Alert>
) : <>
<Field name="bomLineId" label="Material" value={batch.plannedMaterials[0]?.id}
options={[...labels].map(([value, label]) => ({ value, label }))} />
<Field name="kind" label="Usage type" value="CONSUMED"
options={[{ value: "CONSUMED", label: "Consumed" }, { value: "WASTED", label: "Wasted" }]} />
<Field name="quantity" label="Actual quantity" maxLength={13} helper="Use three decimal places in the material’s unit." />
<Field name="reason" label="Usage reason" required={false} maxLength={500} helper="Required for waste." />
</>}
</ActionForm>
)}
{batch.status === "IN_PROGRESS" && data.total === 500 && <Alert severity="info">This batch has reached the 500-event limit.</Alert>}
</>}</QueryView>
</Panel>;
}