+ The preview covers merchandise only. Enter quantities for up to 100 distinct variants.
+ {
+ 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) => )}
+
+
+ {checked && <>
+ Last price check
+ Merchandise total {checked.currency} {checked.merchandiseTotal}
+ line.variantId)}
+ rows={checked.lines.map((line) => [
+ line.variantId, line.quantity, line.minQuantity,
+ `${checked.currency} ${line.unitPrice}`, `${checked.currency} ${line.lineTotal}`,
+ ])} />
+ >}
+ ;
+}
diff --git a/src/pages/PriceListsPage.tsx b/src/pages/PriceListsPage.tsx
new file mode 100644
index 0000000..d034078
--- /dev/null
+++ b/src/pages/PriceListsPage.tsx
@@ -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
+ {can("b2b.read") && Choose a business in the business directory.
}
+ ({ accountId: readText(form, "accountId").trim() })}
+ submit={async (input) => {
+ const { accountId } = z.object({ accountId: uuid }).parse(input);
+ navigate(`${route}/account/${accountId}`);
+ }}>
+
+
+ ;
+}
+
+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 <>
+ Business account {id}
+ Open another account
+ {can("b2b.read") && Business profile
}
+
+ { setStatus(value); setOffset(0); }}
+ options={[{ value: "ALL", label: "All statuses" }, ...priceListStatus.options.map((value) => ({ value, label: value }))]} />
+ {(rows) => <>
+ row.id)}
+ rows={rows.map((row) => [
+ {row.name}, row.currency, row.status,
+ ])} />
+
+ >}
+
+ {can("b2b.price.manage") &&
+ {uncertain ? The server may have saved {uncertain}. Review the latest lists before creating another draft. :
+ 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;
+ }
+ }}>
+
+
+ }
+ }
+ >;
+}
+
+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, 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 {(list) => {
+ const manage = can("b2b.price.manage");
+ const edit = manage && list.status === "DRAFT";
+ const item = list.items.find((entry) => entry.variantId === selected);
+ return <>
+ All price lists for this account
+
+ {list.currency} · {list.status}
+ entry.id)} rows={list.items.map((entry) => [
+ entry.variantId, `${list.currency} ${money(entry.unitPrice)}`, entry.minQuantity,
+ ...(edit ? [<>
+
+ update(async () => {
+ await request(`${path}/items/${entry.variantId}`, z.object({ removed: z.literal(true) }), { method: "DELETE" });
+ if (selected === entry.variantId) setSelected("");
+ }, list.accountId)} />
+ >] : []),
+ ])} />
+ {edit && <>
+ Activation requires a verified business, eligible variants, and an available active slot in {list.currency}.
+ update(() => request(`${path}/activate`, priceList, { method: "POST" }), list.accountId)} />
+ >}
+ {manage && list.status === "ACTIVE" && update(() => request(`${path}/archive`, priceList, { method: "POST" }), list.accountId)} />}
+
+ {edit &&
+ {can("catalog.read") && Find active variant IDs on published products in the catalog.
}
+ {item && Variant ID {item.variantId}
}
+ {item && }
+ ({
+ 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 && }
+
+
+
+ }
+ {list.status === "ACTIVE" && }
+ >;
+ }};
+}
+
+export default function PriceListsPage({ id, account = false }: { id?: string; account?: boolean }) {
+ const parsed = uuid.safeParse(id);
+ return
+ {!id ? : parsed.success ? account ?
+ :
+ :
+ Invalid {account ? "business account" : "price list"} ID.}
+ ;
+}
diff --git a/test/price-lists.test.ts b/test/price-lists.test.ts
new file mode 100644
index 0000000..61e7ede
--- /dev/null
+++ b/test/price-lists.test.ts
@@ -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);
+});
diff --git a/test/workflows.ui.test.tsx b/test/workflows.ui.test.tsx
index 81c1f21..837f527 100644
--- a/test/workflows.ui.test.tsx
+++ b/test/workflows.ui.test.tsx
@@ -22,6 +22,7 @@ import { BatchCostSnapshot } from "../src/pages/CostingPanels";
import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage";
import MaterialStockPage from "../src/pages/MaterialStockPage";
import BusinessAccountsPage from "../src/pages/BusinessAccountsPage";
+import PriceListsPage from "../src/pages/PriceListsPage";
import { batchDetail } from "../src/lib/production";
import theme from "../src/theme";
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]);
});
+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();
+ 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 () => {
const destination = "d66c798a-f764-4b88-8d13-ace328ff1011";
const stock = {