Compare commits
No commits in common. "c893078ac6183d2ce6d5039e85f8150e6b991286" and "67ec37948a57ccfc3152775dcf0fef3ce0fab014" have entirely different histories.
c893078ac6
...
67ec37948a
|
|
@ -25,11 +25,4 @@ Use existing MUI theme and React Query. Query keys include organization. Search
|
||||||
|
|
||||||
## Phase 2 implementation status — 12 October 2026
|
## Phase 2 implementation status — 12 October 2026
|
||||||
|
|
||||||
Customer and administration screens are implemented, with recovery, pricing, stock lifecycle and quality gates. See UAT-PHASE2.md and RELEASE-CHECKLIST.md. Authenticated UAT, container/ingress verification and production sign-off remain pending.
|
Customer and administration screens are implemented, with recovery, pricing, stock lifecycle and quality gates. See UAT-PHASE2.md and RELEASE-CHECKLIST.md. Authenticated UAT, container/ingress verification and production sign-off remain pending; Phase 3 has not started.
|
||||||
|
|
||||||
## Phase 3 implementation status
|
|
||||||
|
|
||||||
- Supplier and material directories support listing, creation and editing. Supplier material terms include SKU, lead time, minimum order quantity and unit price.
|
|
||||||
- Staff can create a purchase order draft from supplier terms, review the backend price snapshots, then issue or cancel the draft.
|
|
||||||
- Receipts and QC, supplier invoices/payments/documents, BOMs, production and packaging, costing, and material warehouse stock remain open.
|
|
||||||
- Live acceptance requires an organization and procurement test users. Exercise read-only and manage roles, inactive suppliers and materials, mixed currencies, below-minimum quantities, price snapshots and purchase order state conflicts.
|
|
||||||
|
|
|
||||||
13
src/App.tsx
13
src/App.tsx
|
|
@ -28,10 +28,6 @@ const AuditPage = lazy(() =>
|
||||||
);
|
);
|
||||||
const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
|
const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
|
||||||
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
|
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
|
||||||
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
|
|
||||||
const PurchaseOrdersPage = lazy(() =>
|
|
||||||
import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })),
|
|
||||||
);
|
|
||||||
const OffersPage = lazy(() => import("@/pages/OffersPage"));
|
const OffersPage = lazy(() => import("@/pages/OffersPage"));
|
||||||
const RecoveryPage = lazy(() => import("@/pages/RecoveryPage"));
|
const RecoveryPage = lazy(() => import("@/pages/RecoveryPage"));
|
||||||
const NotFound = lazy(() => import("@/pages/not-found"));
|
const NotFound = lazy(() => import("@/pages/not-found"));
|
||||||
|
|
@ -71,15 +67,6 @@ function Router() {
|
||||||
{(params) => <InventoryPage id={params.id} />}
|
{(params) => <InventoryPage id={params.id} />}
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="/admin/coupons">{() => <OffersPage />}</Route>
|
<Route path="/admin/coupons">{() => <OffersPage />}</Route>
|
||||||
<Route path="/admin/procurement">{() => <ProcurementPage />}</Route>
|
|
||||||
<Route path="/admin/procurement/materials">{() => <ProcurementPage materials />}</Route>
|
|
||||||
<Route path="/admin/procurement/suppliers/:id">
|
|
||||||
{(params) => <ProcurementPage supplierId={params.id} />}
|
|
||||||
</Route>
|
|
||||||
<Route path="/admin/purchase-orders">{() => <PurchaseOrdersPage />}</Route>
|
|
||||||
<Route path="/admin/purchase-orders/:id">
|
|
||||||
{(params) => <PurchaseOrdersPage orderId={params.id} />}
|
|
||||||
</Route>
|
|
||||||
<Route path="/admin/pricing">{() => <OffersPage pricing />}</Route>
|
<Route path="/admin/pricing">{() => <OffersPage pricing />}</Route>
|
||||||
<Route path="/recovery">{() => <RecoveryPage />}</Route>
|
<Route path="/recovery">{() => <RecoveryPage />}</Route>
|
||||||
<Route path="/reset-password">{() => <RecoveryPage reset />}</Route>
|
<Route path="/reset-password">{() => <RecoveryPage reset />}</Route>
|
||||||
|
|
|
||||||
|
|
@ -58,9 +58,6 @@ export function WorkspaceNavigation() {
|
||||||
permission: "inventory.read",
|
permission: "inventory.read",
|
||||||
},
|
},
|
||||||
{ label: "Coupons", path: "/admin/coupons", permission: "coupons.manage" },
|
{ label: "Coupons", path: "/admin/coupons", permission: "coupons.manage" },
|
||||||
{ label: "Suppliers", path: "/admin/procurement", permission: "procurement.read" },
|
|
||||||
{ label: "Materials", path: "/admin/procurement/materials", permission: "procurement.read" },
|
|
||||||
{ label: "Purchase orders", path: "/admin/purchase-orders", permission: "procurement.read" },
|
|
||||||
{ label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" },
|
{ label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" },
|
||||||
{ label: "All orders", path: "/admin/orders", permission: "orders.read" },
|
{ label: "All orders", path: "/admin/orders", permission: "orders.read" },
|
||||||
{ label: "Audit", path: "/admin/audit", permission: "audit.read" },
|
{ label: "Audit", path: "/admin/audit", permission: "audit.read" },
|
||||||
|
|
|
||||||
|
|
@ -1,69 +0,0 @@
|
||||||
import { z } from "zod";
|
|
||||||
import { currency, uuid } from "./commerce.ts";
|
|
||||||
|
|
||||||
const plainText = (max: number, min = 1) =>
|
|
||||||
z.string().trim().min(min).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
|
|
||||||
const directoryInput = z.object({
|
|
||||||
name: plainText(160),
|
|
||||||
code: z.string().trim().toUpperCase().max(32).regex(/^[A-Z0-9][A-Z0-9_-]*$/, "Use letters, numbers, hyphens or underscores"),
|
|
||||||
active: z.boolean(),
|
|
||||||
});
|
|
||||||
export const supplierInput = directoryInput.extend({
|
|
||||||
contactName: plainText(160),
|
|
||||||
email: z.string().email().max(254).toLowerCase(),
|
|
||||||
phone: z.string().trim().regex(/^\+?[0-9 ()-]{7,24}$/, "Enter a valid phone number").max(24),
|
|
||||||
}).strict();
|
|
||||||
export const materialInput = directoryInput.extend({
|
|
||||||
kind: z.enum(["WAX", "FRAGRANCE", "WICK", "DYE", "VESSEL", "PACKAGING", "LABEL", "OTHER"]),
|
|
||||||
unit: z.enum(["GRAM", "KILOGRAM", "MILLILITRE", "LITRE", "PIECE", "METRE"]),
|
|
||||||
}).strict();
|
|
||||||
export const supplier = supplierInput.extend({ id: uuid }).strip();
|
|
||||||
export const material = materialInput.extend({ id: uuid }).strip();
|
|
||||||
|
|
||||||
const quantity = z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Enter exactly three decimal places").refine((value) => value !== "0.000", "Quantity must be positive");
|
|
||||||
export const supplyTermsInput = z.object({
|
|
||||||
supplierSku: plainText(64, 0),
|
|
||||||
leadTimeDays: z.number().int().min(0).max(365),
|
|
||||||
minOrderQuantity: quantity,
|
|
||||||
unitPrice: z.string().regex(/^(0|[1-9]\d{0,8})\.\d{2}$/, "Enter exactly two decimal places"),
|
|
||||||
currency,
|
|
||||||
active: z.boolean(),
|
|
||||||
}).strict();
|
|
||||||
|
|
||||||
// Prisma serializes Decimal values without trailing zeroes.
|
|
||||||
const decimalResponse = z.string().regex(/^\d+(\.\d+)?$/);
|
|
||||||
export const supplyTerms = supplyTermsInput.extend({
|
|
||||||
id: uuid,
|
|
||||||
materialId: uuid,
|
|
||||||
minOrderQuantity: decimalResponse,
|
|
||||||
unitPrice: decimalResponse,
|
|
||||||
}).strip();
|
|
||||||
export const supplierMaterial = supplyTerms.extend({ material });
|
|
||||||
|
|
||||||
export const purchaseOrderInput = z.object({
|
|
||||||
supplierId: uuid,
|
|
||||||
expectedDeliveryDate: z.string().date().optional(),
|
|
||||||
lines: z.array(z.object({ materialId: uuid, quantity }).strict()).min(1, "Enter a quantity for at least one material").max(100).refine(
|
|
||||||
(lines) => new Set(lines.map((line) => line.materialId)).size === lines.length,
|
|
||||||
"Select each material once",
|
|
||||||
),
|
|
||||||
}).strict();
|
|
||||||
|
|
||||||
export const purchaseOrder = z.object({
|
|
||||||
id: uuid,
|
|
||||||
reference: z.string(),
|
|
||||||
status: z.enum(["DRAFT", "ISSUED", "CANCELLED"]),
|
|
||||||
currency,
|
|
||||||
supplier: supplier.pick({ id: true, name: true }),
|
|
||||||
expectedDeliveryAt: z.string().datetime().nullable(),
|
|
||||||
merchandiseTotal: decimalResponse,
|
|
||||||
lines: z.array(z.object({
|
|
||||||
id: uuid,
|
|
||||||
materialName: z.string(),
|
|
||||||
materialCode: z.string(),
|
|
||||||
quantity: decimalResponse,
|
|
||||||
unit: materialInput.shape.unit,
|
|
||||||
unitPrice: decimalResponse,
|
|
||||||
lineTotal: decimalResponse,
|
|
||||||
})),
|
|
||||||
});
|
|
||||||
|
|
@ -1,228 +0,0 @@
|
||||||
import { useState } from "react";
|
|
||||||
import { z } from "zod";
|
|
||||||
import Button from "@mui/material/Button";
|
|
||||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
|
||||||
import { ActionForm, Check, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
|
||||||
import { usePlatform } from "@/lib/platform";
|
|
||||||
import { currency, uuid } from "@/lib/commerce";
|
|
||||||
import { material, materialInput, purchaseOrder, purchaseOrderInput, supplier, supplierInput, supplierMaterial, supplyTerms, supplyTermsInput } from "@/lib/procurement";
|
|
||||||
import { useLocation } from "wouter";
|
|
||||||
import Alert from "@mui/material/Alert";
|
|
||||||
import { ConfirmAction } from "@/components/ConfirmAction";
|
|
||||||
import { isUnknownOutcome } from "@/lib/api";
|
|
||||||
|
|
||||||
type Supplier = z.infer<typeof supplier>;
|
|
||||||
type Material = z.infer<typeof material>;
|
|
||||||
const options = (values: readonly string[]) => values.map((value) => ({ value, label: value }));
|
|
||||||
|
|
||||||
function Directory({ materials }: { materials: boolean }) {
|
|
||||||
const { can, request } = usePlatform();
|
|
||||||
const [offset, setOffset] = useState(0);
|
|
||||||
const [selected, select] = useState("");
|
|
||||||
const path = materials ? "/materials" : "/suppliers";
|
|
||||||
const schema = z.union([supplier, material]);
|
|
||||||
const listSchema: z.ZodType<(Supplier | Material)[]> = materials ? z.array(material) : z.array(supplier);
|
|
||||||
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, listSchema);
|
|
||||||
return (
|
|
||||||
<Panel title={materials ? "Material directory" : "Supplier directory"}>
|
|
||||||
<QueryView query={query}>
|
|
||||||
{(rows) => {
|
|
||||||
const record = rows.find((row) => row.id === selected);
|
|
||||||
return <>
|
|
||||||
<Table head={["Name", "Code", "Details", "Status", "Actions"]} rowKeys={rows.map((row) => row.id)}
|
|
||||||
rows={rows.map((row) => [
|
|
||||||
row.name, row.code,
|
|
||||||
"kind" in row ? <>{row.kind} · {row.unit}<br />ID: {row.id}</> : `${row.contactName} · ${row.email} · ${row.phone}`,
|
|
||||||
row.active ? "Active" : "Inactive",
|
|
||||||
<>
|
|
||||||
{can("procurement.manage") && <Button onClick={() => select(row.id)} aria-label={`Edit ${row.name}`}>Edit</Button>}
|
|
||||||
{"contactName" in row && <WorkspaceLink href={`/admin/procurement/suppliers/${row.id}`}>Supply terms and orders for {row.name}</WorkspaceLink>}
|
|
||||||
</>,
|
|
||||||
])} />
|
|
||||||
<Pager count={rows.length} offset={offset} onPage={(next) => { select(""); setOffset(next); }} />
|
|
||||||
{can("procurement.manage") && <>
|
|
||||||
{record && <Button onClick={() => select("")}>Cancel editing</Button>}
|
|
||||||
<DirectoryForm key={record?.id ?? "create"} materials={materials} record={record}
|
|
||||||
submit={async (value) => {
|
|
||||||
await request(record ? `${path}/${record.id}` : path, schema, {
|
|
||||||
method: record ? "PUT" : "POST",
|
|
||||||
body: (materials ? materialInput : supplierInput).parse(value),
|
|
||||||
});
|
|
||||||
await query.refetch();
|
|
||||||
}} />
|
|
||||||
</>}
|
|
||||||
</>;
|
|
||||||
}}
|
|
||||||
</QueryView>
|
|
||||||
</Panel>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DirectoryForm({ materials, record, submit }: {
|
|
||||||
materials: boolean;
|
|
||||||
record?: Supplier | Material;
|
|
||||||
submit: (value: unknown) => Promise<void>;
|
|
||||||
}) {
|
|
||||||
const detail = record && "kind" in record ? record : undefined;
|
|
||||||
const contact = record && "contactName" in record ? record : undefined;
|
|
||||||
return (
|
|
||||||
<ActionForm label={`${record ? "Save" : "Create"} ${materials ? "material" : "supplier"}`} submit={submit} reset={!record}
|
|
||||||
read={(data) => ({ ...Object.fromEntries(data), active: data.has("active") })}>
|
|
||||||
<Field name="name" label="Name" value={record?.name} maxLength={160} />
|
|
||||||
<Field name="code" label="Code" value={record?.code} maxLength={32} />
|
|
||||||
{materials ? <>
|
|
||||||
<Field name="kind" label="Material kind" value={detail?.kind ?? "WAX"} options={options(materialInput.shape.kind.options)} />
|
|
||||||
<Field name="unit" label="Unit of measure" value={detail?.unit ?? "GRAM"} options={options(materialInput.shape.unit.options)} />
|
|
||||||
</> : <>
|
|
||||||
<Field name="contactName" label="Contact name" value={contact?.contactName} maxLength={160} />
|
|
||||||
<Field name="email" label="Email" type="email" value={contact?.email} maxLength={254} />
|
|
||||||
<Field name="phone" label="Phone" type="tel" value={contact?.phone} maxLength={24} />
|
|
||||||
</>}
|
|
||||||
<Check name="active" label="Active" value={record?.active ?? true} />
|
|
||||||
</ActionForm>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SupplierTerms({ id }: { id: string }) {
|
|
||||||
const { can, request } = usePlatform();
|
|
||||||
const [, navigate] = useLocation();
|
|
||||||
const query = usePrivateQuery(`/suppliers/${id}/materials`, z.array(supplierMaterial));
|
|
||||||
const [selected, select] = useState("");
|
|
||||||
const [draftUncertain, setDraftUncertain] = useState(false);
|
|
||||||
return <Panel title="Supplier material terms">
|
|
||||||
<WorkspaceLink href="/admin/procurement">Supplier directory</WorkspaceLink>
|
|
||||||
<QueryView query={query}>{(rows) => {
|
|
||||||
const terms = rows.find((row) => row.materialId === selected);
|
|
||||||
return <>
|
|
||||||
<Table head={["Material", "Supplier SKU", "Minimum quantity", "Unit price", "Lead time", "Status", "Actions"]}
|
|
||||||
rowKeys={rows.map((row) => row.id)} rows={rows.map((row) => [
|
|
||||||
row.material.name, row.supplierSku || "—", `${row.minOrderQuantity} ${row.material.unit}`,
|
|
||||||
`${row.currency} ${row.unitPrice}`, `${row.leadTimeDays} days`, row.active ? "Active" : "Inactive",
|
|
||||||
can("procurement.manage") && <Button onClick={() => select(row.materialId)} aria-label={`Edit terms for ${row.material.name}`}>Edit</Button>,
|
|
||||||
])} />
|
|
||||||
{can("procurement.manage") && <>
|
|
||||||
{terms && <Button onClick={() => select("")}>Cancel editing</Button>}
|
|
||||||
<ActionForm key={terms?.id ?? "new"} label="Save supply terms" reset={!terms}
|
|
||||||
read={(data) => ({
|
|
||||||
materialId: terms?.materialId ?? uuid.parse(readText(data, "materialId").trim()),
|
|
||||||
body: supplyTermsInput.parse({
|
|
||||||
...Object.fromEntries([...data].filter(([name]) => name !== "materialId")),
|
|
||||||
leadTimeDays: Number(readText(data, "leadTimeDays")),
|
|
||||||
active: data.has("active"),
|
|
||||||
}),
|
|
||||||
})}
|
|
||||||
submit={async (value) => {
|
|
||||||
const input = z.object({ materialId: uuid, body: supplyTermsInput }).parse(value);
|
|
||||||
await request(`/suppliers/${id}/materials/${input.materialId}`, supplyTerms, { method: "PUT", body: input.body });
|
|
||||||
await query.refetch();
|
|
||||||
}}>
|
|
||||||
{terms ? <p>{terms.material.name}</p> : <Field name="materialId" label="Material ID" maxLength={36} helper="Find the ID in the material directory." />}
|
|
||||||
<Field name="supplierSku" label="Supplier SKU" required={false} maxLength={64} value={terms?.supplierSku} />
|
|
||||||
<Field name="leadTimeDays" label="Lead time (days)" type="number" value={terms?.leadTimeDays ?? 0} />
|
|
||||||
<Field name="minOrderQuantity" label="Minimum order quantity" helper="Use three decimal places." value={terms?.minOrderQuantity && padDecimal(terms.minOrderQuantity, 3)} />
|
|
||||||
<Field name="unitPrice" label="Unit price" helper="Use two decimal places." value={terms?.unitPrice && padDecimal(terms.unitPrice, 2)} />
|
|
||||||
<Field name="currency" label="Currency" options={options(currency.options)} value={terms?.currency ?? "INR"} />
|
|
||||||
<Check name="active" label="Active" value={terms?.active ?? true} />
|
|
||||||
</ActionForm>
|
|
||||||
</>}
|
|
||||||
{can("procurement.manage") && rows.some((row) => row.active && row.material.active) && (
|
|
||||||
<Panel title="Draft purchase order">
|
|
||||||
<Alert severity="info">Enter quantities for the materials to order. The backend applies current supplier terms and snapshots prices when the draft is saved.</Alert>
|
|
||||||
{draftUncertain ? <Alert severity="warning">
|
|
||||||
The server may have saved the draft. <WorkspaceLink href="/admin/purchase-orders">Check purchase orders</WorkspaceLink> before submitting again.
|
|
||||||
</Alert> : <ActionForm label="Create purchase order" reset={false}
|
|
||||||
read={(data) => purchaseOrderInput.parse({
|
|
||||||
supplierId: id,
|
|
||||||
expectedDeliveryDate: readText(data, "expectedDeliveryDate") || undefined,
|
|
||||||
lines: rows.filter((row) => row.active && row.material.active).flatMap((row) => {
|
|
||||||
const quantity = readText(data, row.materialId).trim();
|
|
||||||
return quantity ? [{ materialId: row.materialId, quantity }] : [];
|
|
||||||
}),
|
|
||||||
})}
|
|
||||||
submit={async (body) => {
|
|
||||||
try {
|
|
||||||
const order = await request("/purchase-orders", purchaseOrder, { method: "POST", body });
|
|
||||||
navigate(`/admin/purchase-orders/${order.id}`);
|
|
||||||
} catch (error) {
|
|
||||||
if (isUnknownOutcome(error)) setDraftUncertain(true);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}}>
|
|
||||||
<Field name="expectedDeliveryDate" label="Expected delivery date (YYYY-MM-DD)" required={false} maxLength={10} />
|
|
||||||
{rows.filter((row) => row.active && row.material.active).map((row) => (
|
|
||||||
<Field key={row.materialId} name={row.materialId} label={`Quantity of ${row.material.name} (${row.material.code})`}
|
|
||||||
required={false} helper={`Use three decimals in ${row.material.unit}. Minimum ${row.minOrderQuantity}, unit price ${row.currency} ${row.unitPrice}.`} />
|
|
||||||
))}
|
|
||||||
</ActionForm>}
|
|
||||||
</Panel>
|
|
||||||
)}
|
|
||||||
</>;
|
|
||||||
}}</QueryView>
|
|
||||||
</Panel>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function PurchaseOrders() {
|
|
||||||
const [offset, setOffset] = useState(0);
|
|
||||||
const query = usePrivateQuery(`/purchase-orders?limit=25&offset=${offset}`, z.array(purchaseOrder));
|
|
||||||
return <Panel title="Purchase orders">
|
|
||||||
<p>To create a draft, choose a supplier and open its supply terms.</p>
|
|
||||||
<WorkspaceLink href="/admin/procurement">Supplier directory</WorkspaceLink>
|
|
||||||
<QueryView query={query}>{(rows) => <>
|
|
||||||
<Table head={["Reference", "Supplier", "Status", "Merchandise total"]} rowKeys={rows.map((row) => row.id)}
|
|
||||||
rows={rows.map((row) => [
|
|
||||||
<WorkspaceLink href={`/admin/purchase-orders/${row.id}`}>{row.reference}</WorkspaceLink>,
|
|
||||||
row.supplier.name, row.status, `${row.currency} ${row.merchandiseTotal}`,
|
|
||||||
])} />
|
|
||||||
<Pager count={rows.length} offset={offset} onPage={setOffset} />
|
|
||||||
</>}</QueryView>
|
|
||||||
</Panel>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function PurchaseOrderDetails({ id }: { id: string }) {
|
|
||||||
const { can, request } = usePlatform();
|
|
||||||
const query = usePrivateQuery(`/purchase-orders/${id}`, purchaseOrder);
|
|
||||||
return <QueryView query={query}>{(order) => <Panel title={order.reference}>
|
|
||||||
<WorkspaceLink href="/admin/purchase-orders">All purchase orders</WorkspaceLink>
|
|
||||||
<p>{order.supplier.name} · {order.status}</p>
|
|
||||||
{order.expectedDeliveryAt && <p>Expected delivery {order.expectedDeliveryAt.slice(0, 10)}</p>}
|
|
||||||
<Table head={["Material", "Quantity", "Unit price", "Line total"]} rowKeys={order.lines.map((line) => line.id)}
|
|
||||||
rows={order.lines.map((line) => [
|
|
||||||
`${line.materialName} (${line.materialCode})`, `${line.quantity} ${line.unit}`,
|
|
||||||
`${order.currency} ${line.unitPrice}`, `${order.currency} ${line.lineTotal}`,
|
|
||||||
])} />
|
|
||||||
<p>Merchandise total {order.currency} {order.merchandiseTotal}</p>
|
|
||||||
{can("procurement.manage") && order.status === "DRAFT" && <>
|
|
||||||
<ConfirmAction label="Issue purchase order" message={`Issue ${order.reference} so it can receive deliveries?`}
|
|
||||||
onConfirm={async () => {
|
|
||||||
await request(`/purchase-orders/${id}/issue`, purchaseOrder, { method: "POST" });
|
|
||||||
await query.refetch();
|
|
||||||
}} />
|
|
||||||
<ConfirmAction label="Cancel purchase order" message={`Cancel draft ${order.reference}?`}
|
|
||||||
onConfirm={async () => {
|
|
||||||
await request(`/purchase-orders/${id}/cancel`, purchaseOrder, { method: "POST" });
|
|
||||||
await query.refetch();
|
|
||||||
}} />
|
|
||||||
</>}
|
|
||||||
</Panel>}</QueryView>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function PurchaseOrdersPage({ orderId }: { orderId?: string }) {
|
|
||||||
const id = uuid.safeParse(orderId);
|
|
||||||
return <WorkspaceShell title="Purchase Orders" permission="procurement.read">
|
|
||||||
{orderId ? id.success ? <PurchaseOrderDetails key={id.data} id={id.data} /> : <Alert severity="warning">Invalid purchase order ID.</Alert> : <PurchaseOrders />}
|
|
||||||
</WorkspaceShell>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function padDecimal(value: string, scale: number) {
|
|
||||||
const [whole, fraction = ""] = value.split(".");
|
|
||||||
return `${whole}.${fraction.padEnd(scale, "0")}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ProcurementPage({ materials = false, supplierId }: { materials?: boolean; supplierId?: string }) {
|
|
||||||
const id = uuid.safeParse(supplierId);
|
|
||||||
return (
|
|
||||||
<WorkspaceShell title={materials ? "Materials" : supplierId ? "Supply terms" : "Suppliers"} permission="procurement.read">
|
|
||||||
{supplierId ? id.success ? <SupplierTerms key={id.data} id={id.data} /> : <p>Invalid supplier ID.</p> : <Directory key={String(materials)} materials={materials} />}
|
|
||||||
</WorkspaceShell>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
import { test } from "node:test";
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import { materialInput, purchaseOrderInput, supplierInput, supplyTerms, supplyTermsInput } from "../src/lib/procurement.ts";
|
|
||||||
|
|
||||||
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
|
||||||
const terms = {
|
|
||||||
supplierSku: "",
|
|
||||||
leadTimeDays: 10,
|
|
||||||
minOrderQuantity: "0.125",
|
|
||||||
unitPrice: "900000000.01",
|
|
||||||
currency: "INR",
|
|
||||||
active: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
test("supplier directory normalizes business codes and email addresses", () => {
|
|
||||||
const value = supplierInput.parse({
|
|
||||||
name: " Candle supply ", code: " wax_1 ", contactName: "Supplier contact",
|
|
||||||
email: "CONTACT@example.com", phone: "+91 1234567890", active: true,
|
|
||||||
});
|
|
||||||
assert.equal(value.name, "Candle supply");
|
|
||||||
assert.equal(value.code, "WAX_1");
|
|
||||||
assert.equal(value.email, "contact@example.com");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("material directory enforces backend material kinds and units", () => {
|
|
||||||
const value = { name: "Wax", code: "WAX", kind: "WAX", unit: "GRAM", active: true };
|
|
||||||
assert.equal(materialInput.safeParse(value).success, true);
|
|
||||||
assert.equal(materialInput.safeParse({ ...value, unit: "BOX" }).success, false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("supply terms preserve precise string quantities and enforce request scale", () => {
|
|
||||||
assert.deepEqual(supplyTermsInput.parse(terms), terms);
|
|
||||||
assert.equal(supplyTermsInput.safeParse({ ...terms, minOrderQuantity: "0.000" }).success, false);
|
|
||||||
assert.equal(supplyTermsInput.safeParse({ ...terms, unitPrice: "2.1" }).success, false);
|
|
||||||
assert.equal(supplyTermsInput.safeParse({ ...terms, leadTimeDays: 366 }).success, false);
|
|
||||||
assert.equal(supplyTerms.parse({ ...terms, id, materialId: id, unitPrice: "2", minOrderQuantity: "1.5" }).unitPrice, "2");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("draft orders require distinct materials, exact quantities and a calendar date", () => {
|
|
||||||
const line = { materialId: id, quantity: "1.001" };
|
|
||||||
const input = { supplierId: id, expectedDeliveryDate: "2026-12-01", lines: [line] };
|
|
||||||
assert.deepEqual(purchaseOrderInput.parse(input), input);
|
|
||||||
assert.equal(purchaseOrderInput.safeParse({ ...input, lines: [line, { ...line, materialId: id.toUpperCase() }] }).success, false);
|
|
||||||
assert.equal(purchaseOrderInput.safeParse({ ...input, expectedDeliveryDate: "2026-02-31" }).success, false);
|
|
||||||
assert.equal(purchaseOrderInput.safeParse({ ...input, lines: [] }).success, false);
|
|
||||||
});
|
|
||||||
|
|
@ -11,7 +11,6 @@ import { PlatformProvider, usePlatform } from "../src/lib/platform";
|
||||||
import CartPage from "../src/pages/CartPage";
|
import CartPage from "../src/pages/CartPage";
|
||||||
import AccessPage, { RolesPage } from "../src/pages/AccessPage";
|
import AccessPage, { RolesPage } from "../src/pages/AccessPage";
|
||||||
import OrdersPage from "../src/pages/OrdersPage";
|
import OrdersPage from "../src/pages/OrdersPage";
|
||||||
import ProcurementPage from "../src/pages/ProcurementPage";
|
|
||||||
import theme from "../src/theme";
|
import theme from "../src/theme";
|
||||||
import { Switch, Route } from "wouter";
|
import { Switch, Route } from "wouter";
|
||||||
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||||
|
|
@ -70,24 +69,6 @@ const session = {
|
||||||
tokenType: "Bearer",
|
tokenType: "Bearer",
|
||||||
expiresAt: new Date(Date.now() + 3600000).toISOString(),
|
expiresAt: new Date(Date.now() + 3600000).toISOString(),
|
||||||
};
|
};
|
||||||
test("procurement observers can read suppliers and cannot see write controls", async () => {
|
|
||||||
const fetch = vi.fn(async (url: string) =>
|
|
||||||
url.endsWith("/auth/login")
|
|
||||||
? json(session)
|
|
||||||
: url.endsWith("/auth/me")
|
|
||||||
? json({ ...me, permissions: ["procurement.read"] })
|
|
||||||
: url.includes("/suppliers?")
|
|
||||||
? json([{ id, name: "Wax Supplier", code: "WAX", contactName: "Contact", email: "contact@example.com", phone: "+919999999999", active: true }])
|
|
||||||
: Promise.reject(new Error("Unexpected private request")),
|
|
||||||
);
|
|
||||||
vi.stubGlobal("fetch", fetch);
|
|
||||||
harness(<ProcurementPage />);
|
|
||||||
await userEvent.setup().click(screen.getByText("Test login"));
|
|
||||||
const terms = await screen.findByRole("link", { name: "Supply terms and orders for Wax Supplier" });
|
|
||||||
expect(terms.getAttribute("href")).toBe(`/admin/procurement/suppliers/${id}`);
|
|
||||||
expect(screen.queryByRole("button", { name: "Edit Wax Supplier" })).toBeNull();
|
|
||||||
expect(screen.queryByRole("button", { name: "Create supplier" })).toBeNull();
|
|
||||||
});
|
|
||||||
const address = {
|
const address = {
|
||||||
id,
|
id,
|
||||||
recipient: "Test Recipient",
|
recipient: "Test Recipient",
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue