feat: manage B2B price lists and minimum quantities
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
This commit is contained in:
parent
e30272588a
commit
1443d74cd3
|
|
@ -50,4 +50,6 @@ Customer and administration screens are implemented, with recovery, pricing, sto
|
||||||
|
|
||||||
- Staff can create, edit, submit and review B2B business accounts. Verification uses submitted profile snapshots, separate permissions for submission and review, and an immutable event history.
|
- Staff can create, edit, submit and review B2B business accounts. Verification uses submitted profile snapshots, separate permissions for submission and review, and an immutable event history.
|
||||||
- B2B UAT should use distinct submitting and reviewing accounts. Verify self-review is blocked, rejection allows correction and resubmission, and a verified profile is read-only.
|
- B2B UAT should use distinct submitting and reviewing accounts. Verify self-review is blocked, rejection allows correction and resubmission, and a verified profile is read-only.
|
||||||
- Price lists, minimum order quantities, quotes, credit policies, samples, artwork, partner orders and payments, custom requests and reporting remain open.
|
- B2B price lists support draft variant prices and minimum quantities, activation, archiving, and active-list merchandise previews.
|
||||||
|
- Price-list UAT should verify that unverified accounts and competing active lists cannot activate a draft, archived terms stay read-only, and price checks reject quantities below the variant minimum.
|
||||||
|
- Quotes, credit policies, samples, artwork, partner orders and payments, custom requests and reporting remain open.
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,7 @@ const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
|
||||||
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
|
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
|
||||||
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
|
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
|
||||||
const BusinessAccountsPage = lazy(() => import("@/pages/BusinessAccountsPage"));
|
const BusinessAccountsPage = lazy(() => import("@/pages/BusinessAccountsPage"));
|
||||||
|
const PriceListsPage = lazy(() => import("@/pages/PriceListsPage"));
|
||||||
const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
|
const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
|
||||||
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
|
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
|
||||||
const BomPage = lazy(() => import("@/pages/BomPage"));
|
const BomPage = lazy(() => import("@/pages/BomPage"));
|
||||||
|
|
@ -73,6 +74,13 @@ function Router() {
|
||||||
<Route path="/admin/business-accounts/:id">
|
<Route path="/admin/business-accounts/:id">
|
||||||
{(params) => <BusinessAccountsPage id={params.id} />}
|
{(params) => <BusinessAccountsPage id={params.id} />}
|
||||||
</Route>
|
</Route>
|
||||||
|
<Route path="/admin/b2b-price-lists">{() => <PriceListsPage />}</Route>
|
||||||
|
<Route path="/admin/b2b-price-lists/account/:id">
|
||||||
|
{(params) => <PriceListsPage account id={params.id} />}
|
||||||
|
</Route>
|
||||||
|
<Route path="/admin/b2b-price-lists/:id">
|
||||||
|
{(params) => <PriceListsPage id={params.id} />}
|
||||||
|
</Route>
|
||||||
<Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route>
|
<Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route>
|
||||||
<Route path="/admin/catalog/:id">
|
<Route path="/admin/catalog/:id">
|
||||||
{(params) => <CatalogAdminPage id={params.id} />}
|
{(params) => <CatalogAdminPage id={params.id} />}
|
||||||
|
|
|
||||||
|
|
@ -71,6 +71,7 @@ export function WorkspaceNavigation() {
|
||||||
{ 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" },
|
||||||
{ label: "Business accounts", path: "/admin/business-accounts", permission: "b2b.read" },
|
{ label: "Business accounts", path: "/admin/business-accounts", permission: "b2b.read" },
|
||||||
|
{ label: "B2B price lists", path: "/admin/b2b-price-lists", permission: "b2b.price.read" },
|
||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
<nav className="workspace-links" aria-label="Workspace navigation">
|
<nav className="workspace-links" aria-label="Workspace navigation">
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { z } from "zod";
|
||||||
|
import { currency, uuid } from "./commerce.ts";
|
||||||
|
|
||||||
|
const units = z.number().int().min(1).max(1_000_000);
|
||||||
|
const cents = z.string().regex(/^\d+\.\d{2}$/);
|
||||||
|
export const priceListStatus = z.enum(["DRAFT", "ACTIVE", "ARCHIVED"]);
|
||||||
|
export const priceListInput = z.object({
|
||||||
|
name: z.string().trim().min(1).max(100).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text"),
|
||||||
|
currency,
|
||||||
|
}).strict();
|
||||||
|
export const priceList = priceListInput.extend({ id: uuid, accountId: uuid, status: priceListStatus }).strip();
|
||||||
|
|
||||||
|
export const priceTermsInput = z.object({
|
||||||
|
unitPrice: z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/, "Use exactly two decimal places")
|
||||||
|
.refine((price) => price !== "0.00", "Enter a positive price"),
|
||||||
|
minQuantity: units,
|
||||||
|
}).strict();
|
||||||
|
export const priceListItem = priceTermsInput.extend({
|
||||||
|
id: uuid,
|
||||||
|
variantId: uuid,
|
||||||
|
unitPrice: z.string().regex(/^\d{1,10}(\.\d{1,2})?$/),
|
||||||
|
}).strip();
|
||||||
|
export const priceListDetail = priceList.extend({ items: z.array(priceListItem) });
|
||||||
|
|
||||||
|
const requestedLine = z.object({ variantId: uuid, quantity: units }).strict();
|
||||||
|
export const priceCheckInput = z.object({
|
||||||
|
lines: z.array(requestedLine).min(1, "Enter a quantity for at least one variant").max(100)
|
||||||
|
.refine((lines) => new Set(lines.map((line) => line.variantId)).size === lines.length, "Use each variant once."),
|
||||||
|
}).strict();
|
||||||
|
export const priceCheck = z.object({
|
||||||
|
priceListId: uuid,
|
||||||
|
currency,
|
||||||
|
merchandiseTotal: cents,
|
||||||
|
lines: z.array(requestedLine.extend({
|
||||||
|
minQuantity: units,
|
||||||
|
unitPrice: cents,
|
||||||
|
lineTotal: cents,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
|
@ -111,6 +111,7 @@ function CreateAccount({ refreshDirectory }: { refreshDirectory: () => Promise<v
|
||||||
}
|
}
|
||||||
|
|
||||||
function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () => Promise<void> }) {
|
function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () => Promise<void> }) {
|
||||||
|
const { can } = usePlatform();
|
||||||
const path = `${api}/${id}`;
|
const path = `${api}/${id}`;
|
||||||
const query = usePrivateQuery(path, businessAccount);
|
const query = usePrivateQuery(path, businessAccount);
|
||||||
const events = usePrivateQuery(`${path}/events`, z.array(businessEvent));
|
const events = usePrivateQuery(`${path}/events`, z.array(businessEvent));
|
||||||
|
|
@ -120,6 +121,7 @@ function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () =>
|
||||||
return <QueryView query={query}>{(account) => <>
|
return <QueryView query={query}>{(account) => <>
|
||||||
<Panel title={account.legalName}>
|
<Panel title={account.legalName}>
|
||||||
<p>Business {account.code} · {account.status} · Profile version {account.profileVersion}</p>
|
<p>Business {account.code} · {account.status} · Profile version {account.profileVersion}</p>
|
||||||
|
{can("b2b.price.read") && <WorkspaceLink href={`/admin/b2b-price-lists/account/${account.id}`}>Business price lists</WorkspaceLink>}
|
||||||
<ReadProfile profile={account} />
|
<ReadProfile profile={account} />
|
||||||
</Panel>
|
</Panel>
|
||||||
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />
|
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,52 @@
|
||||||
|
import { useRef, useState } from "react";
|
||||||
|
import { z } from "zod";
|
||||||
|
import Button from "@mui/material/Button";
|
||||||
|
import { ActionForm, Field, Panel, Table, readNumber, readText } from "@/components/WorkspaceTools";
|
||||||
|
import { priceCheck, priceCheckInput, priceListDetail } from "@/lib/price-lists";
|
||||||
|
import { money } from "@/lib/commerce";
|
||||||
|
import { usePlatform } from "@/lib/platform";
|
||||||
|
|
||||||
|
export function PriceListCheck({ list }: { list: z.infer<typeof priceListDetail> }) {
|
||||||
|
const { request } = usePlatform();
|
||||||
|
const next = useRef(1);
|
||||||
|
const [rows, setRows] = useState([0]);
|
||||||
|
const [checked, setChecked] = useState<z.infer<typeof priceCheck>>();
|
||||||
|
const options = [
|
||||||
|
{ value: "", label: "Choose a variant" },
|
||||||
|
...list.items.map((item) => ({
|
||||||
|
value: item.variantId, label: `${item.variantId} · ${list.currency} ${money(item.unitPrice)} · minimum ${item.minQuantity}`,
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
return <Panel title="Check order quantities">
|
||||||
|
<p>The preview covers merchandise only. Enter quantities for up to 100 distinct variants.</p>
|
||||||
|
<ActionForm label="Check partner prices" reset={false} read={(form) => {
|
||||||
|
setChecked(undefined);
|
||||||
|
return priceCheckInput.parse({ lines: rows.map((key) => ({
|
||||||
|
variantId: readText(form, `variant-${key}`), quantity: readNumber(form, `quantity-${key}`),
|
||||||
|
})) });
|
||||||
|
}} submit={async (body) => {
|
||||||
|
setChecked(await request(`/b2b/price-lists/${list.id}/price-check`, priceCheck, { method: "POST", body }));
|
||||||
|
}}>
|
||||||
|
{rows.map((key, index) => <fieldset className="record-picker" key={key}>
|
||||||
|
<legend>Line {index + 1}</legend>
|
||||||
|
<Field name={`variant-${key}`} label={`Variant for line ${index + 1}`} options={options} />
|
||||||
|
<Field name={`quantity-${key}`} label={`Quantity for line ${index + 1}`} type="number" />
|
||||||
|
<Button type="button" disabled={rows.length === 1} onClick={() => setRows(rows.filter((row) => row !== key))}>Remove line {index + 1}</Button>
|
||||||
|
</fieldset>)}
|
||||||
|
<Button type="button" disabled={rows.length >= Math.min(100, list.items.length)} onClick={() => {
|
||||||
|
const key = next.current++;
|
||||||
|
setRows([...rows, key]);
|
||||||
|
}}>Add line</Button>
|
||||||
|
</ActionForm>
|
||||||
|
{checked && <>
|
||||||
|
<h3>Last price check</h3>
|
||||||
|
<p>Merchandise total {checked.currency} {checked.merchandiseTotal}</p>
|
||||||
|
<Table head={["Variant", "Quantity", "Minimum", "Unit price", "Line total"]}
|
||||||
|
rowKeys={checked.lines.map((line) => line.variantId)}
|
||||||
|
rows={checked.lines.map((line) => [
|
||||||
|
line.variantId, line.quantity, line.minQuantity,
|
||||||
|
`${checked.currency} ${line.unitPrice}`, `${checked.currency} ${line.lineTotal}`,
|
||||||
|
])} />
|
||||||
|
</>}
|
||||||
|
</Panel>;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,184 @@
|
||||||
|
import { useRef, 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 { ConfirmAction } from "@/components/ConfirmAction";
|
||||||
|
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||||
|
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readNumber, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||||
|
import { isUnknownOutcome } from "@/lib/api";
|
||||||
|
import { currency, money, uuid } from "@/lib/commerce";
|
||||||
|
import { usePlatform } from "@/lib/platform";
|
||||||
|
import { priceList, priceListDetail, priceListInput, priceListItem, priceListStatus, priceTermsInput } from "@/lib/price-lists";
|
||||||
|
import { PriceListCheck } from "./PriceListCheck";
|
||||||
|
|
||||||
|
const route = "/admin/b2b-price-lists";
|
||||||
|
const currencies = currency.options.map((value) => ({ value, label: value }));
|
||||||
|
const accountLists = (id: string) => `/b2b/accounts/${id}/price-lists`;
|
||||||
|
|
||||||
|
function useRefreshPriceLists() {
|
||||||
|
const { scope } = usePlatform();
|
||||||
|
const client = useQueryClient();
|
||||||
|
return (accountId: string) => client.invalidateQueries({
|
||||||
|
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||||||
|
typeof queryKey[2] === "string" && queryKey[2].startsWith(`${accountLists(accountId)}?`),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function OpenAccount() {
|
||||||
|
const { can } = usePlatform();
|
||||||
|
const [, navigate] = useLocation();
|
||||||
|
return <Panel title="Open an account’s price lists">
|
||||||
|
{can("b2b.read") && <p>Choose a business in the <WorkspaceLink href="/admin/business-accounts">business directory</WorkspaceLink>.</p>}
|
||||||
|
<ActionForm label="Open price lists" read={(form) => ({ accountId: readText(form, "accountId").trim() })}
|
||||||
|
submit={async (input) => {
|
||||||
|
const { accountId } = z.object({ accountId: uuid }).parse(input);
|
||||||
|
navigate(`${route}/account/${accountId}`);
|
||||||
|
}}>
|
||||||
|
<Field name="accountId" label="Business account ID" maxLength={36} />
|
||||||
|
</ActionForm>
|
||||||
|
</Panel>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccountPriceLists({ id }: { id: string }) {
|
||||||
|
const { can, request } = usePlatform();
|
||||||
|
const [, navigate] = useLocation();
|
||||||
|
const refresh = useRefreshPriceLists();
|
||||||
|
const [status, setStatus] = useState("ALL");
|
||||||
|
const [offset, setOffset] = useState(0);
|
||||||
|
const [uncertain, setUncertain] = useState("");
|
||||||
|
const path = accountLists(id);
|
||||||
|
const query = usePrivateQuery(
|
||||||
|
`${path}?limit=25&offset=${offset}${status === "ALL" ? "" : `&status=${status}`}`,
|
||||||
|
z.array(priceList),
|
||||||
|
);
|
||||||
|
return <>
|
||||||
|
<p className="workspace-id">Business account {id}</p>
|
||||||
|
<WorkspaceLink href={route}>Open another account</WorkspaceLink>
|
||||||
|
{can("b2b.read") && <p><WorkspaceLink href={`/admin/business-accounts/${id}`}>Business profile</WorkspaceLink></p>}
|
||||||
|
<Panel title="Account price lists">
|
||||||
|
<Field name="status" label="List status" value={status} onChange={(value) => { setStatus(value); setOffset(0); }}
|
||||||
|
options={[{ value: "ALL", label: "All statuses" }, ...priceListStatus.options.map((value) => ({ value, label: value }))]} />
|
||||||
|
<QueryView query={query}>{(rows) => <>
|
||||||
|
<Table head={["Price list", "Currency", "Status"]} rowKeys={rows.map((row) => row.id)}
|
||||||
|
rows={rows.map((row) => [
|
||||||
|
<WorkspaceLink href={`${route}/${row.id}`}>{row.name}</WorkspaceLink>, row.currency, row.status,
|
||||||
|
])} />
|
||||||
|
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||||
|
</>}</QueryView>
|
||||||
|
</Panel>
|
||||||
|
{can("b2b.price.manage") && <Panel title="New price list">
|
||||||
|
{uncertain ? <Alert severity="warning">The server may have saved {uncertain}. Review the latest lists before creating another draft.</Alert> :
|
||||||
|
<ActionForm label="Create draft price list" reset={false}
|
||||||
|
read={(form) => priceListInput.parse(Object.fromEntries(form))}
|
||||||
|
submit={async (input) => {
|
||||||
|
const body = priceListInput.parse(input);
|
||||||
|
try {
|
||||||
|
const saved = await request(path, priceList, { method: "POST", body });
|
||||||
|
await refresh(id);
|
||||||
|
navigate(`${route}/${saved.id}`);
|
||||||
|
} catch (error) {
|
||||||
|
if (isUnknownOutcome(error)) {
|
||||||
|
setUncertain(body.name);
|
||||||
|
setStatus("ALL");
|
||||||
|
setOffset(0);
|
||||||
|
await refresh(id);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}}>
|
||||||
|
<Field name="name" label="List name" maxLength={100} />
|
||||||
|
<Field name="currency" label="List currency" options={currencies} value="INR" />
|
||||||
|
</ActionForm>}
|
||||||
|
</Panel>}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function PriceListDetails({ id }: { id: string }) {
|
||||||
|
const { can, request } = usePlatform();
|
||||||
|
const refreshDirectory = useRefreshPriceLists();
|
||||||
|
const path = `/b2b/price-lists/${id}`;
|
||||||
|
const query = usePrivateQuery(path, priceListDetail);
|
||||||
|
const [selected, setSelected] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const updating = useRef(false);
|
||||||
|
async function update(action: () => Promise<unknown>, accountId: string) {
|
||||||
|
if (updating.current) throw new Error("A price list update is already in progress.");
|
||||||
|
updating.current = true;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await action();
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
await Promise.all([query.refetch(), refreshDirectory(accountId)]);
|
||||||
|
} finally {
|
||||||
|
updating.current = false;
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return <QueryView query={query}>{(list) => {
|
||||||
|
const manage = can("b2b.price.manage");
|
||||||
|
const edit = manage && list.status === "DRAFT";
|
||||||
|
const item = list.items.find((entry) => entry.variantId === selected);
|
||||||
|
return <>
|
||||||
|
<WorkspaceLink href={`${route}/account/${list.accountId}`}>All price lists for this account</WorkspaceLink>
|
||||||
|
<Panel title={list.name}>
|
||||||
|
<p>{list.currency} · {list.status}</p>
|
||||||
|
<Table head={["Variant ID", "Unit price", "Minimum quantity", ...(edit ? ["Actions"] : [])]}
|
||||||
|
rowKeys={list.items.map((entry) => entry.id)} rows={list.items.map((entry) => [
|
||||||
|
entry.variantId, `${list.currency} ${money(entry.unitPrice)}`, entry.minQuantity,
|
||||||
|
...(edit ? [<>
|
||||||
|
<Button disabled={busy} onClick={() => setSelected(entry.variantId)} aria-label={`Edit terms for ${entry.variantId}`}>Edit</Button>
|
||||||
|
<ConfirmAction label={`Remove terms for ${entry.variantId}`} disabled={busy}
|
||||||
|
message="Remove this variant from the draft price list?"
|
||||||
|
onConfirm={() => update(async () => {
|
||||||
|
await request(`${path}/items/${entry.variantId}`, z.object({ removed: z.literal(true) }), { method: "DELETE" });
|
||||||
|
if (selected === entry.variantId) setSelected("");
|
||||||
|
}, list.accountId)} />
|
||||||
|
</>] : []),
|
||||||
|
])} />
|
||||||
|
{edit && <>
|
||||||
|
<p>Activation requires a verified business, eligible variants, and an available active slot in {list.currency}.</p>
|
||||||
|
<ConfirmAction label="Activate price list" disabled={busy || !list.items.length}
|
||||||
|
message="Activate this list and freeze its variant prices and minimum quantities?"
|
||||||
|
onConfirm={() => update(() => request(`${path}/activate`, priceList, { method: "POST" }), list.accountId)} />
|
||||||
|
</>}
|
||||||
|
{manage && list.status === "ACTIVE" && <ConfirmAction label="Archive price list" disabled={busy}
|
||||||
|
message="Archive this list to free its active slot for a replacement?"
|
||||||
|
onConfirm={() => update(() => request(`${path}/archive`, priceList, { method: "POST" }), list.accountId)} />}
|
||||||
|
</Panel>
|
||||||
|
{edit && <Panel title={item ? "Edit variant terms" : "Add or update variant terms"}>
|
||||||
|
{can("catalog.read") && <p>Find active variant IDs on published products in the <WorkspaceLink href="/admin/catalog">catalog</WorkspaceLink>.</p>}
|
||||||
|
{item && <p className="workspace-id">Variant ID {item.variantId}</p>}
|
||||||
|
{item && <Button disabled={busy} onClick={() => setSelected("")}>Cancel editing</Button>}
|
||||||
|
<ActionForm key={item?.id ?? "new"} label="Save variant terms" lockFields={busy} reset={!item}
|
||||||
|
read={(form) => ({
|
||||||
|
variantId: item?.variantId ?? uuid.parse(readText(form, "variantId").trim()),
|
||||||
|
terms: priceTermsInput.parse({ unitPrice: readText(form, "unitPrice").trim(), minQuantity: readNumber(form, "minQuantity") }),
|
||||||
|
})}
|
||||||
|
submit={async (input) => {
|
||||||
|
const { variantId, terms } = z.object({ variantId: uuid, terms: priceTermsInput }).parse(input);
|
||||||
|
await update(() => request(`${path}/items/${variantId}`, priceListItem, { method: "PUT", body: terms }), list.accountId);
|
||||||
|
}}>
|
||||||
|
{!item && <Field name="variantId" label="Variant ID" maxLength={36} />}
|
||||||
|
<Field name="unitPrice" label={`Unit price in ${list.currency}`} value={item && money(item.unitPrice)} maxLength={13} helper="Use two decimal places." />
|
||||||
|
<Field name="minQuantity" label="Minimum order quantity" type="number" value={item?.minQuantity} />
|
||||||
|
</ActionForm>
|
||||||
|
</Panel>}
|
||||||
|
{list.status === "ACTIVE" && <PriceListCheck list={list} />}
|
||||||
|
</>;
|
||||||
|
}}</QueryView>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PriceListsPage({ id, account = false }: { id?: string; account?: boolean }) {
|
||||||
|
const parsed = uuid.safeParse(id);
|
||||||
|
return <WorkspaceShell title="B2B Price Lists" permission="b2b.price.read">
|
||||||
|
{!id ? <OpenAccount /> : parsed.success ? account ?
|
||||||
|
<AccountPriceLists key={parsed.data} id={parsed.data} /> :
|
||||||
|
<PriceListDetails key={parsed.data} id={parsed.data} /> :
|
||||||
|
<Alert severity="warning">Invalid {account ? "business account" : "price list"} ID.</Alert>}
|
||||||
|
</WorkspaceShell>;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,28 @@
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { priceTermsInput, priceCheckInput, priceCheck, priceListItem } from "../src/lib/price-lists.ts";
|
||||||
|
|
||||||
|
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||||
|
|
||||||
|
test("partner terms require exact positive prices and bounded minimum quantities", () => {
|
||||||
|
const terms = { unitPrice: "9999999999.99", minQuantity: 1_000_000 };
|
||||||
|
assert.deepEqual(priceTermsInput.parse(terms), terms);
|
||||||
|
for (const unitPrice of ["0.00", "1.2", "1.234", "-1.00"]) {
|
||||||
|
assert.equal(priceTermsInput.safeParse({ ...terms, unitPrice }).success, false);
|
||||||
|
}
|
||||||
|
assert.equal(priceTermsInput.safeParse({ ...terms, minQuantity: 1_000_001 }).success, false);
|
||||||
|
assert.equal(priceListItem.parse({ id, variantId: id, minQuantity: 12, unitPrice: "1.2" }).unitPrice, "1.2");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("price checks require distinct variants and retain server totals beyond safe integers", () => {
|
||||||
|
const line = { variantId: id, quantity: 1_000_000 };
|
||||||
|
assert.deepEqual(priceCheckInput.parse({ lines: [line] }), { lines: [line] });
|
||||||
|
assert.equal(priceCheckInput.safeParse({ lines: [line, { ...line, variantId: id.toUpperCase() }] }).success, false);
|
||||||
|
assert.equal(priceCheckInput.safeParse({ lines: [] }).success, false);
|
||||||
|
const merchandiseTotal = "9999999999990000.00";
|
||||||
|
const result = priceCheck.parse({
|
||||||
|
priceListId: id, currency: "INR", merchandiseTotal,
|
||||||
|
lines: [{ ...line, unitPrice: "9999999999.99", minQuantity: 1, lineTotal: merchandiseTotal }],
|
||||||
|
});
|
||||||
|
assert.equal(result.merchandiseTotal, merchandiseTotal);
|
||||||
|
});
|
||||||
|
|
@ -22,6 +22,7 @@ import { BatchCostSnapshot } from "../src/pages/CostingPanels";
|
||||||
import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage";
|
import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage";
|
||||||
import MaterialStockPage from "../src/pages/MaterialStockPage";
|
import MaterialStockPage from "../src/pages/MaterialStockPage";
|
||||||
import BusinessAccountsPage from "../src/pages/BusinessAccountsPage";
|
import BusinessAccountsPage from "../src/pages/BusinessAccountsPage";
|
||||||
|
import PriceListsPage from "../src/pages/PriceListsPage";
|
||||||
import { batchDetail } from "../src/lib/production";
|
import { batchDetail } from "../src/lib/production";
|
||||||
import theme from "../src/theme";
|
import theme from "../src/theme";
|
||||||
import { Switch, Route } from "wouter";
|
import { Switch, Route } from "wouter";
|
||||||
|
|
@ -250,6 +251,64 @@ test("an independent business reviewer retries the same decision before approval
|
||||||
expect(attempts[1]).toEqual(attempts[0]);
|
expect(attempts[1]).toEqual(attempts[0]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a price list freezes draft terms on activation and checks order minimums before archiving", async () => {
|
||||||
|
const variantId = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
||||||
|
let status = "DRAFT";
|
||||||
|
let terms: { unitPrice: string; minQuantity: number } | undefined;
|
||||||
|
const priceList = () => ({ id, accountId: id, name: "Wholesale", currency: "INR", status });
|
||||||
|
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
|
||||||
|
if (url.endsWith("/auth/login")) return json(session);
|
||||||
|
if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["b2b.price.read", "b2b.price.manage"] });
|
||||||
|
if (url.endsWith(`/b2b/price-lists/${id}`)) return json({
|
||||||
|
...priceList(), items: terms ? [{ id, variantId, ...terms, unitPrice: "12.5" }] : [],
|
||||||
|
});
|
||||||
|
if (url.endsWith(`/items/${variantId}`) && options?.method === "PUT") {
|
||||||
|
terms = JSON.parse(String(options.body));
|
||||||
|
return json({ id, variantId, ...terms });
|
||||||
|
}
|
||||||
|
if (url.endsWith("/activate") && options?.method === "POST") {
|
||||||
|
status = "ACTIVE";
|
||||||
|
return json(priceList());
|
||||||
|
}
|
||||||
|
if (url.endsWith("/archive") && options?.method === "POST") {
|
||||||
|
status = "ARCHIVED";
|
||||||
|
return json(priceList());
|
||||||
|
}
|
||||||
|
if (url.endsWith("/price-check") && options?.method === "POST") {
|
||||||
|
const { lines } = JSON.parse(String(options.body));
|
||||||
|
if (lines[0].quantity < 12) return json({ code: "B2B_PRICE_MINIMUM_QUANTITY", message: "Quantity below the minimum" }, 409);
|
||||||
|
return json({ priceListId: id, currency: "INR", merchandiseTotal: "150.00",
|
||||||
|
lines: [{ variantId, quantity: 12, minQuantity: 12, unitPrice: "12.50", lineTotal: "150.00" }] });
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected request ${url}`);
|
||||||
|
}));
|
||||||
|
harness(<PriceListsPage id={id} />);
|
||||||
|
const user = userEvent.setup();
|
||||||
|
await user.click(screen.getByText("Test login"));
|
||||||
|
await user.type(await screen.findByRole("textbox", { name: /Variant ID/ }), variantId);
|
||||||
|
await user.type(screen.getByRole("textbox", { name: /Unit price in INR/ }), "12.50");
|
||||||
|
await user.type(screen.getByRole("spinbutton", { name: /Minimum order quantity/ }), "12");
|
||||||
|
await user.click(screen.getByRole("button", { name: "Save variant terms" }));
|
||||||
|
await screen.findByRole("cell", { name: "INR 12.50" });
|
||||||
|
expect(terms).toEqual({ unitPrice: "12.50", minQuantity: 12 });
|
||||||
|
await user.click(screen.getByRole("button", { name: "Activate price list" }));
|
||||||
|
await user.click(screen.getByRole("button", { name: "Confirm" }));
|
||||||
|
await user.selectOptions(await screen.findByRole("combobox", { name: /Variant for line 1/ }), variantId);
|
||||||
|
expect(screen.queryByRole("button", { name: "Save variant terms" })).toBeNull();
|
||||||
|
const quantity = screen.getByRole("spinbutton", { name: /Quantity for line 1/ });
|
||||||
|
await user.type(quantity, "11");
|
||||||
|
await user.click(screen.getByRole("button", { name: "Check partner prices" }));
|
||||||
|
await screen.findByText("Quantity below the minimum");
|
||||||
|
await user.clear(quantity);
|
||||||
|
await user.type(quantity, "12");
|
||||||
|
await user.click(screen.getByRole("button", { name: "Check partner prices" }));
|
||||||
|
await screen.findByText("Merchandise total INR 150.00");
|
||||||
|
await user.click(screen.getByRole("button", { name: "Archive price list" }));
|
||||||
|
await user.click(screen.getByRole("button", { name: "Confirm" }));
|
||||||
|
await screen.findByText("INR · ARCHIVED");
|
||||||
|
expect(screen.queryByRole("button", { name: "Check partner prices" })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
test("material transfers exclude the source warehouse and retry with the same key", async () => {
|
test("material transfers exclude the source warehouse and retry with the same key", async () => {
|
||||||
const destination = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
const destination = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
||||||
const stock = {
|
const stock = {
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue