138 lines
7.2 KiB
TypeScript
138 lines
7.2 KiB
TypeScript
import { useState } from "react";
|
||
import { useQueryClient } from "@tanstack/react-query";
|
||
import { z } from "zod";
|
||
import Alert from "@mui/material/Alert";
|
||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||
import { WarehousePostingForm } from "@/components/WarehousePostingForm";
|
||
import { materialAdjustment, materialAdjustmentInput, materialStockItem, materialTransfer, materialTransferInput } from "@/lib/material-stock";
|
||
import { usePlatform } from "@/lib/platform";
|
||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||
|
||
const transferPath = "/inventory/material-transfers";
|
||
const adjustmentPath = "/inventory/material-adjustments";
|
||
const stockRoute = "/admin/material-stock";
|
||
type Stock = z.infer<typeof materialStockItem>;
|
||
type Adjustment = z.infer<typeof materialAdjustment>;
|
||
|
||
function useRefreshMovements(path: string) {
|
||
const { scope } = usePlatform();
|
||
const client = useQueryClient();
|
||
return () => client.invalidateQueries({
|
||
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||
typeof queryKey[2] === "string" &&
|
||
(queryKey[2].startsWith("/inventory/material-stock-items") || queryKey[2].startsWith(path)),
|
||
});
|
||
}
|
||
|
||
export function MaterialStockMovements({ stock }: { stock: Stock }) {
|
||
const { can } = usePlatform();
|
||
return <>
|
||
<Transfers stock={stock} write={can("inventory.manage")} />
|
||
<AdjustmentHistory materialId={stock.material.id} warehouseId={stock.warehouse.id} unit={stock.material.unit} />
|
||
{can("inventory.adjust") && <MaterialAdjustmentForm stock={stock} />}
|
||
</>;
|
||
}
|
||
|
||
function Transfers({ stock, write }: { stock: Stock; write: boolean }) {
|
||
const [offset, setOffset] = useState(0);
|
||
const [saved, setSaved] = useState<z.infer<typeof materialTransfer>>();
|
||
const query = usePrivateQuery(
|
||
`${transferPath}?materialId=${stock.material.id}&limit=25&offset=${offset}`,
|
||
z.array(materialTransfer),
|
||
);
|
||
const command = useIdempotentCommand(transferPath, materialTransferInput, materialTransfer, stock.id);
|
||
const refresh = useRefreshMovements(transferPath);
|
||
const pending = command.pending;
|
||
async function submit(value: unknown) {
|
||
const transfer = await command.run(value);
|
||
setSaved(transfer);
|
||
setOffset(0);
|
||
await refresh();
|
||
}
|
||
return <Panel title="Warehouse transfers for this material">
|
||
{saved && <Alert severity="success">Transferred {saved.quantity} {stock.material.unit}. <WorkspaceLink href={`${stockRoute}/${saved.toStockItemId}`}>Open destination ledger</WorkspaceLink></Alert>}
|
||
{write && (pending ? (
|
||
<ActionForm label="Retry material transfer" read={() => ({})} submit={submit}>
|
||
<Alert severity="warning">Retrying uses the original quantity {pending.quantity} {stock.material.unit} and destination warehouse {pending.toWarehouseId}.</Alert>
|
||
</ActionForm>
|
||
) : <WarehousePostingForm label="Transfer material" warehouseLabel="Destination warehouse" excludeWarehouseId={stock.warehouse.id}
|
||
instruction={`Move stock from ${stock.warehouse.name}. Both warehouse ledgers update together.`}
|
||
reset read={(data) => ({
|
||
materialId: stock.material.id,
|
||
fromWarehouseId: stock.warehouse.id,
|
||
toWarehouseId: readText(data, "warehouseId"),
|
||
quantity: readText(data, "quantity").trim(),
|
||
})} submit={submit}>
|
||
<Field name="quantity" label={`Quantity to transfer (${stock.material.unit})`} maxLength={13} helper="Enter a positive quantity with three decimal places." />
|
||
</WarehousePostingForm>)}
|
||
<QueryView query={query}>{(rows) => <>
|
||
<Table head={["Time", "Quantity", "Source", "Destination"]} rowKeys={rows.map((row) => row.id)}
|
||
rows={rows.map((row) => [
|
||
new Date(row.createdAt).toLocaleString(), `${row.quantity} ${stock.material.unit}`,
|
||
<WorkspaceLink href={`${stockRoute}/${row.fromStockItemId}`}>{row.fromWarehouseId === stock.warehouse.id ? stock.warehouse.name : "Source ledger"}</WorkspaceLink>,
|
||
<WorkspaceLink href={`${stockRoute}/${row.toStockItemId}`}>{row.toWarehouseId === stock.warehouse.id ? stock.warehouse.name : "Destination ledger"}</WorkspaceLink>,
|
||
])} />
|
||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||
</>}</QueryView>
|
||
</Panel>;
|
||
}
|
||
|
||
function AdjustmentHistory({ materialId, warehouseId, unit }: { materialId: string; warehouseId: string; unit: string }) {
|
||
const [offset, setOffset] = useState(0);
|
||
const query = usePrivateQuery(
|
||
`${adjustmentPath}?materialId=${materialId}&warehouseId=${warehouseId}&limit=25&offset=${offset}`,
|
||
z.array(materialAdjustment),
|
||
);
|
||
return <Panel title="Warehouse adjustments for this material">
|
||
<QueryView query={query}>{(rows) => <>
|
||
<Table head={["Time", "Quantity change", "Reason"]} rowKeys={rows.map((row) => row.id)}
|
||
rows={rows.map((row) => [new Date(row.createdAt).toLocaleString(), `${signed(row.delta)} ${unit}`, row.reason])} />
|
||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||
</>}</QueryView>
|
||
</Panel>;
|
||
}
|
||
|
||
export function MaterialAdjustmentForm({ stock, materialId }: { stock?: Stock; materialId?: string }) {
|
||
const [saved, setSaved] = useState<Adjustment>();
|
||
const command = useIdempotentCommand(adjustmentPath, materialAdjustmentInput, materialAdjustment, stock?.id ?? materialId ?? "new");
|
||
const refresh = useRefreshMovements(adjustmentPath);
|
||
const pending = command.pending;
|
||
const instruction = "Record a counted discrepancy or stock correction. Use a minus sign for decreases.";
|
||
const fields = <>
|
||
{!stock && !materialId && <Field name="materialId" label="Material ID" maxLength={36} />}
|
||
<Field name="delta" label={stock ? `Quantity change (${stock.material.unit})` : "Quantity change"}
|
||
maxLength={14} helper="Use three decimal places in the material’s native unit." />
|
||
<Field name="reason" label="Adjustment reason" maxLength={200} />
|
||
</>;
|
||
function read(data: FormData) {
|
||
return {
|
||
materialId: stock?.material.id ?? materialId ?? readText(data, "materialId").trim(),
|
||
warehouseId: stock?.warehouse.id ?? readText(data, "warehouseId"),
|
||
delta: readText(data, "delta").trim(),
|
||
reason: readText(data, "reason"),
|
||
};
|
||
}
|
||
async function submit(input: unknown) {
|
||
setSaved(await command.run(input));
|
||
await refresh();
|
||
}
|
||
return <Panel title="Adjust material stock">
|
||
{materialId && <p className="workspace-id">Material ID {materialId}</p>}
|
||
{saved && <Alert severity="success">Recorded {signed(saved.delta)}. <WorkspaceLink href={`${stockRoute}/${saved.stockItemId}`}>Open adjusted stock ledger</WorkspaceLink></Alert>}
|
||
{pending ? (
|
||
<ActionForm label="Retry stock adjustment" read={() => ({})} submit={submit}>
|
||
<Alert severity="warning">Retrying uses the original change {signed(pending.delta)} and reason. Warehouse {pending.warehouseId}.</Alert>
|
||
</ActionForm>
|
||
) : stock ? (
|
||
<ActionForm label="Record stock adjustment" read={read} submit={submit}>
|
||
<p>{instruction}</p>
|
||
{fields}
|
||
</ActionForm>
|
||
) : <WarehousePostingForm label="Record stock adjustment" instruction={instruction} read={read} submit={submit} reset>{fields}</WarehousePostingForm>}
|
||
</Panel>;
|
||
}
|
||
|
||
function signed(delta: string) {
|
||
return delta.startsWith("-") ? delta : `+${delta}`;
|
||
}
|