ManiCandles/src/pages/MaterialCostRatesPage.tsx

103 lines
4.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 { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useLocation } from "wouter";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { isUnknownOutcome } from "@/lib/api";
import { uuid } from "@/lib/commerce";
import { costCurrencies, costRate, costRateInput } from "@/lib/costing";
import { usePlatform } from "@/lib/platform";
const route = "/admin/material-cost-rates";
function OpenMaterial() {
const { can } = usePlatform();
const [, navigate] = useLocation();
return <Panel title="Open material rates">
{can("procurement.read") && <p>Choose a material from the <WorkspaceLink href="/admin/procurement/materials">material directory</WorkspaceLink>.</p>}
<ActionForm label="Open cost rates" read={(data) => ({ materialId: readText(data, "materialId").trim() })}
submit={async (input) => {
const { materialId } = z.object({ materialId: uuid }).parse(input);
navigate(`${route}/${materialId}`);
}}>
<Field name="materialId" label="Material ID" maxLength={36} />
</ActionForm>
</Panel>;
}
function Rates({ id }: { id: string }) {
const { can, request, scope } = usePlatform();
const client = useQueryClient();
const [currency, setCurrency] = useState("INR");
const [offset, setOffset] = useState(0);
const [uncertain, setUncertain] = useState("");
const [saving, setSaving] = useState(false);
const path = `/materials/${id}/cost-rates`;
const page = `${path}?currency=${currency}&limit=25&offset=${offset}`;
const query = usePrivateQuery(page, z.array(costRate));
async function refresh() {
setOffset(0);
await client.invalidateQueries({
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
typeof queryKey[2] === "string" &&
(queryKey[2].startsWith(`${path}?currency=${currency}&`) || queryKey[2].endsWith(`/cost-estimate?currency=${currency}`)),
});
}
return <>
<WorkspaceLink href={route}>Open another material</WorkspaceLink>
<p className="workspace-id">Material ID {id}</p>
<Panel title="Rate history">
<fieldset disabled={saving} className="cart-lines">
<Field name="currency" label="Rate currency" value={currency} options={costCurrencies}
onChange={(value) => { setCurrency(value); setOffset(0); }} />
</fieldset>
<QueryView query={query}>{(rows) => <>
<Table head={["Revision", "Rate per native unit", "Recorded"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [row.revision, `${row.currency} ${row.unitCost}`, new Date(row.createdAt).toLocaleString()])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
</Panel>
{can("cost.manage") && <Panel title={`New ${currency} rate revision`}>
{uncertain ? <Alert severity="warning">
The server may have saved the {uncertain} rate. Check its latest revision before recording another rate.
<Button onClick={() => {
setCurrency(uncertain);
setOffset(0);
void client.invalidateQueries({ queryKey: ["private", scope, `${path}?currency=${uncertain}&limit=25&offset=0`] });
}}>Check rate history</Button>
</Alert> : <ActionForm key={currency} label="Record standard cost rate"
read={(form) => costRateInput.parse({ currency, unitCost: readText(form, "unitCost").trim() })}
submit={async (body) => {
setSaving(true);
try {
await request(path, costRate, { method: "POST", body });
await refresh();
} catch (error) {
if (isUnknownOutcome(error)) {
setUncertain(currency);
await refresh();
}
throw error;
} finally {
setSaving(false);
}
}}>
<p>Each rate is an immutable revision. Enter the cost per material’s native unit.</p>
<Field name="unitCost" label={`Unit cost in ${currency}`} maxLength={13} helper="Use four decimal places." />
</ActionForm>}
</Panel>}
</>;
}
export default function MaterialCostRatesPage({ materialId }: { materialId?: string }) {
const id = uuid.safeParse(materialId);
return <WorkspaceShell title="Material Cost Rates" permission="cost.read">
{!materialId ? <OpenMaterial /> : id.success ? <Rates key={id.data} id={id.data} /> : <Alert severity="warning">Invalid material ID.</Alert>}
</WorkspaceShell>;
}