371 lines
11 KiB
TypeScript
371 lines
11 KiB
TypeScript
import { useEffect, useState } from "react";
|
||
import { useQueryClient } from "@tanstack/react-query";
|
||
import { z } from "zod";
|
||
import Alert from "@mui/material/Alert";
|
||
import {
|
||
warehouse,
|
||
warehouseInput,
|
||
stock,
|
||
stockInput,
|
||
stockDetail,
|
||
adjustmentInput,
|
||
ledger,
|
||
reservation,
|
||
reservationInput,
|
||
uuid,
|
||
} from "@/lib/commerce";
|
||
import { usePlatform } from "@/lib/platform";
|
||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||
import {
|
||
ActionForm,
|
||
Field,
|
||
Pager,
|
||
Panel,
|
||
QueryView,
|
||
Table,
|
||
usePrivateQuery,
|
||
readText,
|
||
readNumber,
|
||
WorkspaceLink,
|
||
} from "@/components/WorkspaceTools";
|
||
import { ConfirmAction } from "@/components/ConfirmAction";
|
||
function StockList() {
|
||
const { request, can } = usePlatform();
|
||
const [offset, setOffset] = useState(0),
|
||
[warehouseOffset, setWarehouseOffset] = useState(0);
|
||
const query = usePrivateQuery(
|
||
`/inventory/stock-items?limit=25&offset=${offset}`,
|
||
z.array(stock),
|
||
),
|
||
warehouses = usePrivateQuery(
|
||
`/inventory/warehouses?limit=25&offset=${warehouseOffset}`,
|
||
z.array(warehouse),
|
||
);
|
||
return (
|
||
<>
|
||
<Panel title="Finished-goods stock">
|
||
<QueryView query={query}>
|
||
{(items) => (
|
||
<>
|
||
<Table
|
||
head={["Stock item", "Variant", "Warehouse", "On hand"]}
|
||
rowKeys={items.map((item) => item.id)}
|
||
rows={items.map((s) => [
|
||
<WorkspaceLink href={`/admin/inventory/${s.id}`}>
|
||
{s.id}
|
||
</WorkspaceLink>,
|
||
s.variantId,
|
||
s.warehouseId,
|
||
s.onHand,
|
||
])}
|
||
/>
|
||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||
</>
|
||
)}
|
||
</QueryView>
|
||
{can("inventory.manage") && (
|
||
<ActionForm
|
||
label="Create stock item"
|
||
read={(data) => ({
|
||
variantId: readText(data, "variantId"),
|
||
warehouseId: readText(data, "warehouseId"),
|
||
})}
|
||
submit={async (value) => {
|
||
await request("/inventory/stock-items", stock, {
|
||
method: "POST",
|
||
body: stockInput.parse(value),
|
||
});
|
||
await query.refetch();
|
||
}}
|
||
>
|
||
<Field
|
||
name="variantId"
|
||
label="Variant UUID"
|
||
helper="Copy the variant ID from catalog administration."
|
||
/>
|
||
<Field
|
||
name="warehouseId"
|
||
label="Warehouse UUID"
|
||
helper="Copy the warehouse ID from the warehouse list below."
|
||
/>
|
||
</ActionForm>
|
||
)}
|
||
</Panel>
|
||
<Panel title="Warehouses">
|
||
<QueryView query={warehouses}>
|
||
{(items) => (
|
||
<>
|
||
<Table
|
||
head={["Warehouse", "ID"]}
|
||
rowKeys={items.map((item) => item.id)}
|
||
rows={items.map((w) => [w.name, w.id])}
|
||
/>
|
||
<Pager
|
||
offset={warehouseOffset}
|
||
count={items.length}
|
||
onPage={setWarehouseOffset}
|
||
/>
|
||
</>
|
||
)}
|
||
</QueryView>
|
||
{can("inventory.manage") && (
|
||
<ActionForm
|
||
label="Create warehouse"
|
||
read={(data) => ({ name: readText(data, "name") })}
|
||
submit={async (value) => {
|
||
await request("/inventory/warehouses", warehouse, {
|
||
method: "POST",
|
||
body: warehouseInput.parse(value),
|
||
});
|
||
await warehouses.refetch();
|
||
}}
|
||
>
|
||
<Field name="name" label="Warehouse name" maxLength={100} />
|
||
</ActionForm>
|
||
)}
|
||
</Panel>
|
||
</>
|
||
);
|
||
}
|
||
function ReservationCard({ id }: { id: string }) {
|
||
const { request, can, scope } = usePlatform(),
|
||
query = usePrivateQuery(`/inventory/reservations/${id}`, reservation);
|
||
const client = useQueryClient(),
|
||
{ data, refetch } = query;
|
||
useEffect(() => {
|
||
if (data?.status !== "ACTIVE") return;
|
||
const timer = setTimeout(
|
||
() => {
|
||
void client.invalidateQueries({
|
||
predicate: (query) =>
|
||
query.queryKey[0] === "private" &&
|
||
query.queryKey[1] === scope &&
|
||
String(query.queryKey[2]).startsWith("/inventory/"),
|
||
});
|
||
},
|
||
Math.max(1000, Date.parse(data.expiresAt) - Date.now() + 250),
|
||
);
|
||
return () => clearTimeout(timer);
|
||
}, [data, client, scope]);
|
||
async function refreshStock() {
|
||
await refetch();
|
||
await client.invalidateQueries({
|
||
predicate: (query) =>
|
||
query.queryKey[0] === "private" &&
|
||
query.queryKey[1] === scope &&
|
||
String(query.queryKey[2]).startsWith("/inventory/"),
|
||
});
|
||
}
|
||
return (
|
||
<QueryView query={query}>
|
||
{(record) => (
|
||
<>
|
||
<p className="workspace-id">
|
||
Reservation {record.id}: {record.status}, {record.quantity} units.
|
||
Expires {new Date(record.expiresAt).toLocaleString()}.
|
||
</p>
|
||
{record.orderId && (
|
||
<Alert severity="info">
|
||
This hold is managed by its order and cannot be committed or
|
||
released here.
|
||
</Alert>
|
||
)}
|
||
{record.status === "ACTIVE" && !record.orderId && (
|
||
<>
|
||
<ConfirmAction
|
||
label="Release reservation"
|
||
message="Release this standalone hold? Order-managed holds cannot be changed here."
|
||
onConfirm={async () => {
|
||
await request(
|
||
`/inventory/reservations/${id}/release`,
|
||
reservation,
|
||
{ method: "POST" },
|
||
);
|
||
await refreshStock();
|
||
}}
|
||
/>
|
||
{can("inventory.commit") && (
|
||
<ConfirmAction
|
||
label="Commit reservation"
|
||
message="Commit this reservation? This deducts finished-goods stock and writes an immutable ledger entry."
|
||
onConfirm={async () => {
|
||
await request(
|
||
`/inventory/reservations/${id}/commit`,
|
||
reservation,
|
||
{ method: "POST" },
|
||
);
|
||
await refreshStock();
|
||
}}
|
||
/>
|
||
)}
|
||
</>
|
||
)}
|
||
</>
|
||
)}
|
||
</QueryView>
|
||
);
|
||
}
|
||
function StockEditor({ id }: { id: string }) {
|
||
const { can } = usePlatform();
|
||
const [offset, setOffset] = useState(0),
|
||
[reservationId, setReservationId] = useState("");
|
||
const query = usePrivateQuery(`/inventory/stock-items/${id}`, stockDetail),
|
||
history = usePrivateQuery(
|
||
`/inventory/stock-items/${id}/ledger?limit=25&offset=${offset}`,
|
||
z.array(ledger),
|
||
);
|
||
const adjust = useIdempotentCommand(
|
||
"/inventory/adjustments",
|
||
adjustmentInput,
|
||
ledger,
|
||
id,
|
||
),
|
||
reserve = useIdempotentCommand(
|
||
"/inventory/reservations",
|
||
reservationInput,
|
||
reservation,
|
||
id,
|
||
);
|
||
return (
|
||
<>
|
||
<Panel title="Stock balance">
|
||
<QueryView query={query}>
|
||
{(s) => (
|
||
<>
|
||
<p className="workspace-id">
|
||
Stock item: {s.id}
|
||
<br />
|
||
Variant: {s.variantId}
|
||
<br />
|
||
Warehouse: {s.warehouseId}
|
||
</p>
|
||
<dl className="order-totals">
|
||
<dt>On hand</dt>
|
||
<dd>{s.onHand}</dd>
|
||
<dt>Reserved</dt>
|
||
<dd>{s.reserved}</dd>
|
||
<dt>Available</dt>
|
||
<dd>{s.available}</dd>
|
||
</dl>
|
||
</>
|
||
)}
|
||
</QueryView>
|
||
</Panel>
|
||
{can("inventory.adjust") && (
|
||
<Panel title="Reasoned stock adjustment">
|
||
{adjust.uncertain && (
|
||
<Alert severity="warning">
|
||
The result is unknown. Retry the original adjustment; the same key
|
||
and input will be reused. Check the ledger before starting another
|
||
adjustment.
|
||
</Alert>
|
||
)}
|
||
<ActionForm
|
||
label={
|
||
adjust.uncertain ? "Retry original adjustment" : "Post adjustment"
|
||
}
|
||
lockFields={adjust.uncertain}
|
||
read={(data) => ({
|
||
stockItemId: id,
|
||
delta: readNumber(data, "delta"),
|
||
reason: readText(data, "reason"),
|
||
})}
|
||
submit={async (value) => {
|
||
await adjust.run(value);
|
||
await query.refetch();
|
||
await history.refetch();
|
||
}}
|
||
>
|
||
<Field
|
||
name="delta"
|
||
label="Quantity change (+ or −)"
|
||
type="number"
|
||
/>
|
||
<Field name="reason" label="Adjustment reason" maxLength={200} />
|
||
</ActionForm>
|
||
</Panel>
|
||
)}
|
||
{can("inventory.reserve") && (
|
||
<Panel title="Standalone stock reservation">
|
||
{reserve.uncertain && (
|
||
<Alert severity="warning">
|
||
Retry the original reservation to recover the same result.
|
||
</Alert>
|
||
)}
|
||
<ActionForm
|
||
label={
|
||
reserve.uncertain ? "Retry original reservation" : "Reserve stock"
|
||
}
|
||
lockFields={reserve.uncertain}
|
||
read={(data) => ({
|
||
stockItemId: id,
|
||
quantity: readNumber(data, "quantity"),
|
||
ttlMinutes: readNumber(data, "ttlMinutes"),
|
||
})}
|
||
submit={async (value) => {
|
||
const result = await reserve.run(value);
|
||
setReservationId(result.id);
|
||
await query.refetch();
|
||
}}
|
||
>
|
||
<Field name="quantity" label="Units to reserve" type="number" />
|
||
<Field
|
||
name="ttlMinutes"
|
||
label="Hold duration in minutes"
|
||
type="number"
|
||
value={15}
|
||
/>
|
||
</ActionForm>
|
||
<ActionForm
|
||
label="Look up own reservation"
|
||
read={(data) => readText(data, "id")}
|
||
submit={async (value) => {
|
||
setReservationId(z.string().uuid().parse(value));
|
||
}}
|
||
>
|
||
<Field name="id" label="Reservation UUID" />
|
||
</ActionForm>
|
||
{reservationId && (
|
||
<ReservationCard key={reservationId} id={reservationId} />
|
||
)}
|
||
</Panel>
|
||
)}
|
||
<Panel title="Immutable stock ledger">
|
||
<QueryView query={history}>
|
||
{(items) => (
|
||
<>
|
||
<Table
|
||
head={["Time", "Change", "Reason"]}
|
||
rowKeys={items.map((item) => item.id)}
|
||
rows={items.map((e) => [
|
||
new Date(e.createdAt).toLocaleString(),
|
||
e.delta,
|
||
e.reason,
|
||
])}
|
||
/>
|
||
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
||
</>
|
||
)}
|
||
</QueryView>
|
||
</Panel>
|
||
</>
|
||
);
|
||
}
|
||
export default function InventoryPage({ id }: { id?: string }) {
|
||
return (
|
||
<WorkspaceShell
|
||
title="Finished-goods Inventory"
|
||
permission="inventory.read"
|
||
>
|
||
{id && !uuid.safeParse(id).success ? (
|
||
<Alert severity="error">Invalid stock identifier.</Alert>
|
||
) : id ? (
|
||
<StockEditor key={uuid.parse(id)} id={uuid.parse(id)} />
|
||
) : (
|
||
<StockList />
|
||
)}
|
||
</WorkspaceShell>
|
||
);
|
||
}
|