Live examples
Each example is one app/page.tsx running in your browser, with mock data inside the file. The Code tab shows the file and lets you copy it; the Agent prompt tab is what the agent was asked to build. Click Open in editor to try changes in the Playground.
Complete apps (database, sign-in, real workflows) are on the Showcase page, and run and edit right in your browser. Single-screen frames (lists, forms, dashboards…) are in UI templates.
Executive dashboard
A retail chain owner checks revenue, orders and open tasks for a period.
// Owner dashboard for a 3-channel furniture store: the period picker (today / 7 days / month / 12 months) drives every number; 4 KPIs vs the previous period, revenue vs gross profit chart, channel mix, best sellers, action items and low-stock alerts.
// In a real app: api.reports.summary({ period }) returns the KPIs + daily/monthly series; api.tasks.counts() and api.inventory.lowStock() replace the sample data.
import { useMemo, useState } from "react";
import { PageContainer, ProCard, StatisticCard } from "@ant-design/pro-components";
import { Badge, Button, Col, Flex, Progress, Row, Segmented, Table, Tooltip, Typography, theme, type TableProps } from "antd";
import { ArrowDownOutlined, ArrowUpOutlined, ClockCircleOutlined, DollarOutlined, DownloadOutlined, InboxOutlined, RightOutlined, CarOutlined } from "@ant-design/icons";
import { Column, Pie, Tiny } from "@ant-design/charts";
import dayjs, { type Dayjs } from "dayjs";
type Period = "today" | "7d" | "month" | "12m";
type Day = { date: Dayjs; rev: number[]; gp: number[]; orders: number[] };
const NOW = dayjs("2026-11-13T14:30:00");
const TODAY_SHARE = 0.58; // share of a typical day's revenue taken by 2:30 PM
const CHANNELS = [{ label: "Showroom", aov: 1460, margin: 0.41 }, { label: "Website", aov: 730, margin: 0.35 }, { label: "B2B projects", aov: 0, margin: 0.27 }];
const nf = new Intl.NumberFormat("en-US");
const vnd = (n: number) => `$${nf.format(Math.round(n))}`;
const num = (n: number, d: number) => new Intl.NumberFormat("en-US", { maximumFractionDigits: d }).format(n);
const short = (n: number) => (Math.abs(n) >= 1e6 ? `$${num(n / 1e6, 2)}M` : `$${num(n / 1e3, Math.abs(n) >= 1e5 ? 0 : 1)}k`);
const pct = (x: number) => `${new Intl.NumberFormat("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(x * 100)}%`;
const sum = (a: number[]) => a.reduce((s, v) => s + v, 0);
// Sample data: 731 days of sales generated from a fixed seed (mulberry32) — same result on every render.
function rng(seed: number) {
return () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
const DAYS: Day[] = (() => {
const r = rng(2026);
const round = (v: number) => Math.round(v / 10) * 10;
return Array.from({ length: 731 }, (_, i) => {
const date = NOW.startOf("day").subtract(730 - i, "day");
const k = (0.8 + (0.2 * i) / 730) * (i === 730 ? TODAY_SHARE : 1);
const weekend = date.day() === 0 || date.day() === 6 ? 1.55 : 1;
const rev = [round(7600 * k * weekend * (0.75 + 0.5 * r())), round(3500 * k * (0.7 + 0.6 * r())), r() < 0.22 ? round((9.5 + 35 * r()) * 1e3 * k) : 0];
const gp = rev.map((v, c) => round(v * (CHANNELS[c].margin + (r() - 0.5) * 0.04)));
const orders = [Math.max(1, Math.round(rev[0] / CHANNELS[0].aov)), Math.max(1, Math.round(rev[1] / CHANNELS[1].aov)), rev[2] ? 1 : 0];
return { date, rev, gp, orders };
});
})();
const between = (a: Dayjs, b: Dayjs) => DAYS.filter((d) => !d.date.isBefore(a, "day") && !d.date.isAfter(b, "day"));
const scale = (d: Day, k: number): Day => ({ ...d, rev: d.rev.map((v) => v * k), gp: d.gp.map((v) => v * k), orders: d.orders.map((v) => Math.round(v * k)) });
const total = (days: Day[]) => ({
rev: [0, 1, 2].map((c) => sum(days.map((d) => d.rev[c]))),
gp: [0, 1, 2].map((c) => sum(days.map((d) => d.gp[c]))),
orders: [0, 1, 2].map((c) => sum(days.map((d) => d.orders[c]))),
});
const HOURS = [8, 9, 10, 11, 12, 13, 14];
const HOUR_W = [0.06, 0.12, 0.16, 0.18, 0.14, 0.17, 0.17];
function buildPeriod(p: Period) {
const t = NOW.startOf("day");
const [cur, prev, prevLabel] =
p === "today" ? [between(t, t), between(t.subtract(1, "day"), t.subtract(1, "day")).map((d) => scale(d, TODAY_SHARE)), "same time yesterday"]
: p === "7d" ? [between(t.subtract(6, "day"), t), between(t.subtract(13, "day"), t.subtract(7, "day")), "the previous 7 days"]
: p === "month" ? [between(t.startOf("month"), t), between(t.subtract(1, "month").startOf("month"), t.subtract(1, "month")), `the same days of ${t.subtract(1, "month").format("MMMM")}`]
: [between(t.subtract(11, "month").startOf("month"), t), between(t.subtract(23, "month").startOf("month"), t.subtract(12, "month")), "the previous 12 months"];
// Chart columns: by hour (today), by day (7 days, this month), by month (12 months).
const groups = new Map<string, Day[]>();
if (p === "today") HOURS.forEach((h, i) => groups.set(h > 12 ? `${h - 12} PM` : h === 12 ? "12 PM" : `${h} AM`, [scale(cur[0], HOUR_W[i])]));
else cur.forEach((d) => { const key = d.date.format(p === "12m" ? "MMM YY" : "MMM D"); groups.set(key, [...(groups.get(key) ?? []), d]); });
const buckets = [...groups].map(([label, days]) => ({ label, ...total(days) }));
// Open orders: orders from the period not yet delivered, split by order age.
const status = [0, 0, 0];
cur.forEach((d) => {
const age = t.diff(d.date, "day");
d.orders.forEach((n, c) => {
const open = Math.round(n * (age === 0 ? 0.9 : age <= 6 ? 0.55 : age <= 20 ? 0.18 : c === 2 && age <= 60 ? 0.4 : 0));
status[age === 0 ? 0 : age <= 6 ? 1 : 2] += open;
});
});
return { cur: total(cur), prev: total(prev), prevLabel, buckets, status };
}
const PRODUCTS = [
{ name: "Milano 3-seat leather sofa", price: 3490, share: [0.16, 0.08, 0.02] },
{ name: "Oslo oak dining set, 6 chairs", price: 2190, share: [0.12, 0.07, 0.03] },
{ name: "Kyoto walnut bed, king", price: 2690, share: [0.11, 0.06, 0.02] },
{ name: "ErgoPro ergonomic chair", price: 649, share: [0.03, 0.12, 0.1] },
{ name: "Flex 55\" standing desk", price: 899, share: [0.03, 0.09, 0.14] },
{ name: "Mesh office chair", price: 329, share: [0.01, 0.04, 0.22] },
{ name: "Nordic 4-door wardrobe", price: 1590, share: [0.08, 0.05, 0.04] },
];
type Stock = { sku: string; name: string; warehouse: string; onHand: number; min: number; incoming: number; eta?: string; perDay: number };
const STOCK: Stock[] = [
{ sku: "SF-MIL3-GR", name: "Milano 3-seat leather sofa · grey", warehouse: "Austin showroom", onHand: 0, min: 3, incoming: 4, eta: "Nov 25", perDay: 0.4 },
{ sku: "GVP-MESH-BK", name: "Mesh office chair · black", warehouse: "Round Rock warehouse", onHand: 18, min: 60, incoming: 120, eta: "Nov 20", perDay: 7.5 },
{ sku: "BNH-FLX14-WH", name: "Flex 55\" standing desk · white", warehouse: "Round Rock warehouse", onHand: 6, min: 15, incoming: 0, perDay: 1.6 },
{ sku: "GCT-ERGO-BK", name: "ErgoPro ergonomic chair", warehouse: "Round Rock warehouse", onHand: 9, min: 20, incoming: 40, eta: "Nov 18", perDay: 2.1 },
{ sku: "KTV-WAL20", name: "Walnut TV console, 79\"", warehouse: "Austin showroom", onHand: 4, min: 5, incoming: 0, perDay: 0.3 },
];
const DEBTS = [29_500, 22_600, 13_300]; // 3 B2B customers past their payment due date
const STATUS_LABELS = ["Awaiting confirmation", "Being prepared", "Out for delivery & install"];
export default function Page() {
const { token } = theme.useToken();
const [period, setPeriod] = useState<Period>("month");
const d = useMemo(() => buildPeriod(period), [period]);
const rev = sum(d.cur.rev), prevRev = sum(d.prev.rev), gp = sum(d.cur.gp), prevGp = sum(d.prev.gp);
const orders = sum(d.cur.orders), prevOrders = sum(d.prev.orders);
const margin = gp / rev, prevMargin = prevGp / prevRev;
const open = sum(d.status);
const chColors = [token.colorPrimary, token.cyan, token.gold];
const stColors = [token.colorWarning, token.colorPrimary, token.colorSuccess];
const unit = period === "today" ? "hour" : period === "12m" ? "month" : "day";
const delta = (x: number, text: string) => (
<Typography.Text style={{ color: x >= 0 ? token.colorSuccess : token.colorError }}>
{x >= 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />} {text} <Typography.Text type="secondary">vs {d.prevLabel}</Typography.Text>
</Typography.Text>
);
const spark = (data: number[]) => (
<Tiny.Area height={44} data={data.map((value, index) => ({ index, value }))} xField="index" yField="value" shapeField="smooth"
style={{ fill: token.colorPrimary, fillOpacity: 0.18 }} />
);
const top = PRODUCTS.map((p) => {
const value = sum(p.share.map((s, c) => s * d.cur.rev[c]));
return { ...p, value, units: Math.max(1, Math.round(value / p.price)) };
}).sort((a, b) => b.value - a.value).slice(0, 6);
const tasks = [
{ icon: <ClockCircleOutlined />, title: "Orders unconfirmed for over 2 hours", note: "Oldest 5 h 10 min · 3 website orders", count: 4, color: token.colorWarning },
{ icon: <CarOutlined />, title: "Late deliveries", note: "2 showroom orders · 1 B2B project", count: 3, color: token.colorError },
{ icon: <InboxOutlined />, title: "Items below minimum stock", note: `${STOCK.filter((s) => s.onHand === 0).length} SKU out of stock`, count: STOCK.length, color: token.colorWarning },
{ icon: <DollarOutlined />, title: "Overdue B2B invoices", note: `${vnd(sum(DEBTS))} · oldest 34 days overdue`, count: DEBTS.length, color: token.colorError },
];
const stockCols: TableProps<Stock>["columns"] = [
{ title: "Product", dataIndex: "name", render: (_, r) => <Flex vertical><Typography.Link>{r.name}</Typography.Link><Typography.Text type="secondary" style={{ fontSize: 12 }}>{r.sku} · {r.warehouse}</Typography.Text></Flex> },
{ title: "Status", key: "st", width: 140, render: (_, r) => <Badge status={r.onHand === 0 ? "error" : "warning"} text={r.onHand === 0 ? "Out of stock" : "Below minimum"} /> },
{ title: "On hand / min", key: "qty", align: "right", width: 130, render: (_, r) => <span><b>{r.onHand}</b> / {r.min}</span> },
{ title: "Cover", key: "days", align: "right", width: 100, render: (_, r) => (r.onHand === 0 ? "—" : `${Math.floor(r.onHand / r.perDay)} days`) },
{ title: "Incoming", key: "in", width: 150, render: (_, r) => (r.incoming ? `${r.incoming} units · ${r.eta}` : <Typography.Text type="danger">Not ordered</Typography.Text>) },
{ title: "", key: "act", width: 130, align: "right", render: (_, r) => <Button size="small">{r.incoming ? "View PO" : "Create PO"}</Button> },
];
return (
<PageContainer
title="Good afternoon, Tom"
subTitle={`Oak & Anchor Home · figures as of ${NOW.format("h:mm A")}, Friday ${NOW.format("MMM D, YYYY")}`}
extra={[
<Segmented<Period> key="p" value={period} onChange={setPeriod}
options={[{ label: "Today", value: "today" }, { label: "7 days", value: "7d" }, { label: "This month", value: "month" }, { label: "12 months", value: "12m" }]} />,
<Button key="x" icon={<DownloadOutlined />}>Export report</Button>,
]}
>
<Flex vertical gap={16}>
<Row gutter={[16, 16]}>
<Col xs={24} sm={12} xl={6}>
<StatisticCard style={{ height: "100%" }} chart={spark(d.buckets.map((b) => sum(b.rev)))}
statistic={{ title: "Revenue", value: rev, formatter: () => <Tooltip title={vnd(rev)}>{short(rev)}</Tooltip>, description: delta(rev / prevRev - 1, pct(Math.abs(rev / prevRev - 1))) }}
footer={<Typography.Text type="secondary">Gross profit {short(gp)}</Typography.Text>} />
</Col>
<Col xs={24} sm={12} xl={6}>
<StatisticCard style={{ height: "100%" }} chart={spark(d.buckets.map((b) => sum(b.orders)))}
statistic={{ title: "New orders", value: orders, formatter: () => nf.format(orders), description: delta(orders / prevOrders - 1, pct(Math.abs(orders / prevOrders - 1))) }}
footer={<Typography.Text type="secondary">Average order {short(rev / Math.max(1, orders))}</Typography.Text>} />
</Col>
<Col xs={24} sm={12} xl={6}>
<StatisticCard style={{ height: "100%" }} chart={spark(d.buckets.map((b) => sum(b.gp) / Math.max(1, sum(b.rev))))}
statistic={{ title: "Gross margin", value: margin, formatter: () => pct(margin), description: delta(margin - prevMargin, `${num(Math.abs(margin - prevMargin) * 100, 1)} pts`) }}
footer={<Typography.Text type="secondary">Lowest, B2B: {pct(d.cur.gp[2] / Math.max(1, d.cur.rev[2]))}</Typography.Text>} />
</Col>
<Col xs={24} sm={12} xl={6}>
<StatisticCard style={{ height: "100%" }}
statistic={{ title: "Open orders", value: open, formatter: () => nf.format(open), description: <Typography.Text type="secondary">of {nf.format(orders)} orders this period</Typography.Text> }}
chart={
<Flex vertical gap={8} style={{ paddingTop: 8 }}>
<Flex style={{ height: 10, borderRadius: 5, overflow: "hidden", background: token.colorFillSecondary }}>
{d.status.map((n, i) => <Tooltip key={i} title={`${STATUS_LABELS[i]}: ${n}`}><div style={{ width: `${(n / Math.max(1, open)) * 100}%`, background: stColors[i] }} /></Tooltip>)}
</Flex>
{d.status.map((n, i) => (
<Flex key={i} justify="space-between" style={{ fontSize: 12 }}>
<Badge color={stColors[i]} text={STATUS_LABELS[i]} /><b>{n}</b>
</Flex>
))}
</Flex>
} />
</Col>
</Row>
<Row gutter={[16, 16]}>
<Col xs={24} lg={15}>
<ProCard title="Revenue and gross profit" subTitle={`by ${unit}`} headerBordered style={{ height: "100%" }}>
<Column height={300} data={d.buckets.flatMap((b) => [{ label: b.label, kind: "Revenue", value: sum(b.rev) }, { label: b.label, kind: "Gross profit", value: sum(b.gp) }])}
xField="label" yField="value" colorField="kind" group
scale={{ color: { range: [token.colorPrimary, token.colorSuccess] } }}
axis={{ y: { labelFormatter: (v: number) => short(v) } }}
legend={{ color: { position: "top", layout: { justifyContent: "flex-end" } } }}
tooltip={{ items: [{ channel: "y", valueFormatter: (v: number) => vnd(v) }] }} />
</ProCard>
</Col>
<Col xs={24} lg={9}>
<ProCard title="Needs attention" subTitle="updated 2:30 PM" headerBordered style={{ height: "100%" }} bodyStyle={{ padding: 8 }}>
<Flex vertical>
{tasks.map((t) => (
<a key={t.title} href="#" onClick={(e) => e.preventDefault()}
style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 12px", borderRadius: token.borderRadius, color: token.colorText, borderBottom: `1px solid ${token.colorSplit}` }}>
<span style={{ color: t.color, fontSize: 18 }}>{t.icon}</span>
<Flex vertical style={{ flex: 1, minWidth: 0 }}>
<Typography.Text strong>{t.title}</Typography.Text>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>{t.note}</Typography.Text>
</Flex>
<Typography.Text strong style={{ fontSize: 20, color: t.color }}>{t.count}</Typography.Text>
<RightOutlined style={{ color: token.colorTextTertiary }} />
</a>
))}
</Flex>
</ProCard>
</Col>
</Row>
<Row gutter={[16, 16]}>
<Col xs={24} lg={10}>
<ProCard title="Revenue by channel" subTitle={`total ${vnd(rev)}`} headerBordered style={{ height: "100%" }}>
<Pie height={220} data={CHANNELS.map((c, i) => ({ type: c.label, value: d.cur.rev[i] }))} angleField="value" colorField="type"
innerRadius={0.66} label={false} legend={false} scale={{ color: { range: chColors } }}
tooltip={{ items: [{ field: "value", valueFormatter: (v: number) => vnd(v) }] }}
annotations={[{ type: "text", style: { text: short(rev), x: "50%", y: "50%", textAlign: "center", fontSize: 18, fontWeight: 600 } }]} />
<Flex vertical gap={8}>
{CHANNELS.map((c, i) => (
<Flex key={c.label} justify="space-between" gap={8}>
<Badge color={chColors[i]} text={c.label} />
<Typography.Text type="secondary">{nf.format(d.cur.orders[i])} orders</Typography.Text>
<span><b>{short(d.cur.rev[i])}</b> <Typography.Text type="secondary">· {pct(d.cur.rev[i] / rev)}</Typography.Text></span>
</Flex>
))}
</Flex>
</ProCard>
</Col>
<Col xs={24} lg={14}>
<ProCard title="Best sellers" subTitle="by revenue" extra={<a>View product report</a>} headerBordered style={{ height: "100%" }}>
<Flex vertical gap={12}>
{top.map((p, i) => (
<Flex key={p.name} align="center" gap={12}>
<Typography.Text strong style={{ width: 20, color: i < 3 ? token.colorPrimary : token.colorTextTertiary }}>{i + 1}</Typography.Text>
<Flex vertical style={{ flex: 1, minWidth: 0 }}>
<Flex justify="space-between" gap={8}>
<Typography.Text ellipsis>{p.name}</Typography.Text>
<Typography.Text strong>{short(p.value)}</Typography.Text>
</Flex>
<Flex align="center" gap={8}>
<Progress percent={(p.value / top[0].value) * 100} showInfo={false} size="small" style={{ flex: 1, margin: 0 }} />
<Typography.Text type="secondary" style={{ fontSize: 12, width: 64, textAlign: "right" }}>{nf.format(p.units)} units</Typography.Text>
</Flex>
</Flex>
</Flex>
))}
</Flex>
</ProCard>
</Col>
</Row>
<ProCard title="Low stock" subTitle={`${STOCK.length} SKUs below minimum stock`} extra={<a>Open inventory</a>} headerBordered bodyStyle={{ paddingTop: 0 }}>
<Table<Stock> rowKey="sku" size="small" columns={stockCols} dataSource={STOCK} pagination={false} scroll={{ x: 760 }} />
</ProCard>
</Flex>
</PageContainer>
);
}
Build a daily executive dashboard for the owner of a furniture chain that sells on 3 channels (showroom, website, B2B projects). At the top: a greeting with the data timestamp and a period picker Today / 7 days / This month / 12 months; changing the period changes every number and compares it with the matching previous period (yesterday at the same hour, the same days last month…). First row: 4 KPI cards with sparklines — revenue, new orders, gross margin (change shown in percentage points), and orders in progress with a bar stacked by status. Next: a column chart of revenue and gross profit by hour/day/month, and beside it a "To do" panel where every row is clickable and shows a count — orders waiting for confirmation over 2 hours, late deliveries, items below minimum stock and overdue B2B receivables. Add a donut of revenue by channel (the channels must add up to total revenue), a "Best sellers" list with progress bars, and a low-stock table with a button to create a purchase order. Format money for the app's locale. Every number comes from the app's API through useApiClient() (period report, to-do counts, low-stock list) — no hard-coded data.
Order tracking board
Drag-and-drop kanban that only allows the next step; cancelling needs a reason.
// Order tracking board: drag cards one step at a time (no skipping), cancelling requires a reason, header metrics, search, channel filter and an order detail Drawer.
// In a real app: api.orders.list({ q, channel }) loads the data; dragging a card / the Drawer buttons call api.orders.updateStatus(id, { status, reason }) and reload.
import { useMemo, useState, type ReactNode } from "react";
import { PageContainer } from "@ant-design/pro-components";
import { App, Avatar, Badge, Button, Card, Descriptions, Drawer, Flex, Grid, Input, Modal, Radio, Segmented, Table, Tag, Timeline, Tooltip, Typography, theme } from "antd";
import { ArrowRightOutlined, CalendarOutlined, SearchOutlined, StopOutlined } from "@ant-design/icons";
import { DndContext, DragOverlay, PointerSensor, useDraggable, useDroppable, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
import dayjs, { type Dayjs } from "dayjs";
/** Mock people get a face (manh.run avatars 01–24), the same one for the same name. */
const face = (name: string) => {
let h = 0;
for (const ch of name) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
return `https://manh.run/avatars/${String((h % 24) + 1).padStart(2, "0")}.svg`;
};
type Status = "new" | "confirmed" | "shipping" | "done" | "cancelled";
type Channel = "Showroom" | "Website" | "B2B";
type Line = { name: string; qty: number; price: number };
type Step = { status: Status; by: string; at: Dayjs; note?: string };
type Order = { id: string; code: string; customer: string; phone: string; address: string; channel: Channel; owner: string; createdAt: Dayjs; due: Dayjs; lines: Line[]; status: Status; history: Step[] };
const FLOW: Status[] = ["new", "confirmed", "shipping", "done"];
const META: Record<Status, { title: string; badge: "default" | "processing" | "warning" | "success" | "error"; dot: string }> = {
new: { title: "New", badge: "default", dot: "gray" },
confirmed: { title: "Confirmed", badge: "processing", dot: "blue" },
shipping: { title: "Shipping", badge: "warning", dot: "orange" },
done: { title: "Delivered", badge: "success", dot: "green" },
cancelled: { title: "Cancelled", badge: "error", dot: "red" },
};
const CHANNEL_COLOR: Record<Channel, string> = { Showroom: "gold", Website: "blue", B2B: "purple" };
const REASONS = ["Customer changed their mind", "Out of stock, can't restock in time", "Couldn't reach the customer", "Other"];
const vnd = (n: number) => n.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
const million = (n: number) => "$" + (n / 1e3).toLocaleString("en-US", { maximumFractionDigits: 1 }) + "k";
const total = (o: Order) => o.lines.reduce((s, l) => s + l.qty * l.price, 0);
const today = () => dayjs().startOf("day");
const isLate = (o: Order) => (o.status === "confirmed" || o.status === "shipping") && o.due.isBefore(today());
const nextOf = (s: Status) => (FLOW.includes(s) ? FLOW[FLOW.indexOf(s) + 1] : undefined);
const canMove = (from: Status, to: Status) => (to === "cancelled" ? from !== "done" && from !== "cancelled" : nextOf(from) === to);
function mk(n: number, customer: string, phone: string, address: string, channel: Channel, owner: string, createdDays: number, dueDays: number, status: Status, lines: Line[]): Order {
const steps: Status[] = status === "cancelled" ? ["new", "cancelled"] : FLOW.slice(0, FLOW.indexOf(status) + 1);
const createdAt = today().subtract(createdDays, "day").add(8, "hour");
const gap = createdDays === 0 ? 25 : Math.floor((createdDays * 1440) / steps.length);
return {
id: String(n), code: `SO2611-${String(n).padStart(4, "0")}`, customer, phone, address, channel, owner, createdAt, due: today().add(dueDays, "day"), lines, status,
history: steps.map((s, i) => ({ status: s, by: i === 0 ? (channel === "Website" ? "Website" : owner) : owner, at: createdAt.add(i * gap, "minute"), note: s === "cancelled" ? "Customer changed their mind" : undefined })),
};
}
const SEED: Order[] = [
mk(43, "Robert Harris", "(512) 555-0176", "1204 Oak Street, Austin, TX", "Showroom", "Holly Adams", 0, 5, "new", [{ name: "Canvas L-shaped sectional", qty: 1, price: 1_890 }, { name: "Throw pillow 18×18", qty: 4, price: 29 }]),
mk(44, "Brightline Interiors LLC", "(512) 555-0110", "Riverside Business Park, Austin, TX", "B2B", "Greg Turner", 0, 14, "new", [{ name: "Ergonomic task chair", qty: 20, price: 345 }]),
mk(45, "Emily Parker", "(737) 555-0145", "88 Maple Avenue, Round Rock, TX", "Website", "Mia Anderson", 0, 7, "new", [{ name: "Oak vanity table", qty: 1, price: 420 }]),
mk(42, "Kevin Lewis", "(512) 555-0118", "5 Elm Court, Austin, TX", "Showroom", "Tony Diaz", 1, 4, "new", [{ name: "5-tier bookshelf", qty: 2, price: 185 }]),
mk(41, "Andrew Scott", "(737) 555-0131", "Mueller Park Apartments, Austin, TX", "Website", "Mia Anderson", 1, 3, "confirmed", [{ name: "Walnut bed, king", qty: 1, price: 2_450 }, { name: "Latex mattress, king", qty: 1, price: 980 }]),
mk(40, "Bluewater Hotel", "(361) 555-0188", "Ocean Drive, Corpus Christi, TX", "B2B", "Greg Turner", 2, 6, "confirmed", [{ name: "Nightstand", qty: 30, price: 115 }, { name: "Ceramic bedside lamp", qty: 30, price: 45 }]),
mk(38, "Olivia Bennett", "(512) 555-0192", "21 Cedar Lane, Austin, TX", "Showroom", "Holly Adams", 4, -1, "confirmed", [{ name: "2-door shoe cabinet", qty: 1, price: 390 }]),
mk(37, "Jason Miller", "(512) 555-0113", "102 Pine Street, Pflugerville, TX", "Website", "Tony Diaz", 3, 1, "shipping", [{ name: "Acacia TV console, 71\"", qty: 1, price: 560 }]),
mk(36, "Sarah Collins", "(737) 555-0120", "Sunrise Towers, Austin, TX", "Showroom", "Tony Diaz", 5, -2, "shipping", [{ name: "Oak dining set, 6 chairs", qty: 1, price: 1_590 }]),
mk(35, "Timber & Bean Coffee", "(512) 555-0177", "45 Congress Avenue, Austin, TX", "B2B", "Greg Turner", 6, 0, "shipping", [{ name: "Round cafe table", qty: 12, price: 165 }, { name: "Rattan chair", qty: 24, price: 89 }]),
mk(33, "Brian Walker", "(737) 555-0154", "17 Lakeview Drive, Cedar Park, TX", "Website", "Mia Anderson", 7, -2, "done", [{ name: "3-door wardrobe", qty: 1, price: 730 }]),
mk(31, "Rachel Young", "(512) 555-0149", "3 Main Street, Austin, TX", "Showroom", "Holly Adams", 9, -4, "done", [{ name: "Floor lamp", qty: 2, price: 125 }, { name: "Shag rug 5×8", qty: 1, price: 210 }]),
mk(39, "Nicole Hall", "(737) 555-0140", "9 Willow Way, Georgetown, TX", "Website", "Mia Anderson", 2, 5, "cancelled", [{ name: "79\" sofa", qty: 1, price: 990 }]),
];
function Staff({ name, size = 24 }: { name: string; size?: number }) {
return <Tooltip title={name}><Avatar size={size} src={face(name)} alt={name} style={{ flex: "none" }} /></Tooltip>;
}
function dueText(o: Order) {
const days = o.due.diff(today(), "day");
if (o.status === "done" || o.status === "cancelled") return o.due.format("MMM D");
if (days < 0) return `${-days} ${-days === 1 ? "day" : "days"} late`;
return days === 0 ? "Due today" : o.due.format("MMM D");
}
function OrderCard({ o, ghost, onOpen }: { o: Order; ghost?: boolean; onOpen?: () => void }) {
const { token } = theme.useToken();
const late = isLate(o);
return (
<Card size="small" hoverable onClick={onOpen} styles={{ body: { padding: "10px 12px" } }} style={{ opacity: ghost ? 0.35 : 1, cursor: "grab", borderColor: late ? token.colorErrorBorder : undefined }}>
<Flex justify="space-between" align="center" gap={8}>
<Typography.Text strong style={{ fontFamily: token.fontFamilyCode, fontSize: 13 }}>{o.code}</Typography.Text>
<Tag color={CHANNEL_COLOR[o.channel]} style={{ marginInlineEnd: 0 }}>{o.channel}</Tag>
</Flex>
<Flex justify="space-between" align="center" gap={8} style={{ marginTop: 6 }}>
<Typography.Text ellipsis>{o.customer}</Typography.Text>
<Staff name={o.owner} />
</Flex>
<Flex justify="space-between" align="center" style={{ marginTop: 6 }}>
<Typography.Text strong>{vnd(total(o))}</Typography.Text>
<Typography.Text type={late ? "danger" : "secondary"} style={{ fontSize: 12 }}><CalendarOutlined /> {dueText(o)}</Typography.Text>
</Flex>
</Card>
);
}
function DraggableCard({ o, onOpen }: { o: Order; onOpen: () => void }) {
const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id: o.id, disabled: o.status === "done" || o.status === "cancelled" });
return <div ref={setNodeRef} {...listeners} {...attributes}><OrderCard o={o} ghost={isDragging} onOpen={onOpen} /></div>;
}
function Column({ status, orders, target, collapsed, onToggle, onOpen }: { status: Status; orders: Order[]; target?: boolean; collapsed?: boolean; onToggle?: () => void; onOpen: (id: string) => void }) {
const { token } = theme.useToken();
const { setNodeRef, isOver } = useDroppable({ id: status });
const m = META[status];
const bg = isOver ? (target ? token.colorPrimaryBg : token.colorErrorBg) : token.colorFillQuaternary;
const box = { background: bg, borderRadius: token.borderRadiusLG, padding: token.paddingSM, minHeight: 420, outline: target ? `1px dashed ${token.colorPrimaryBorder}` : undefined, transition: "background .15s" };
if (collapsed)
return (
<div ref={setNodeRef} onClick={onToggle} title="Click to show cancelled orders" style={{ ...box, flex: "none", width: 56, cursor: "pointer", writingMode: "vertical-rl", display: "flex", alignItems: "center", gap: 8 }}>
<Badge status={m.badge} /><Typography.Text type="secondary">{m.title} · {orders.length}</Typography.Text>
</div>
);
return (
<div ref={setNodeRef} style={{ ...box, flex: "1 1 0", minWidth: 210 }}>
<Flex justify="space-between" align="center" style={{ marginBottom: 10 }}>
<Flex gap={6} align="center"><Badge status={m.badge} /><Typography.Text strong>{m.title}</Typography.Text><Typography.Text type="secondary">{orders.length}</Typography.Text></Flex>
{onToggle ? <Button type="link" size="small" onClick={onToggle}>Collapse</Button> : <Typography.Text type="secondary" style={{ fontSize: 12 }}>{million(orders.reduce((s, o) => s + total(o), 0))}</Typography.Text>}
</Flex>
<Flex vertical gap={8}>
{orders.map((o) => <DraggableCard key={o.id} o={o} onOpen={() => onOpen(o.id)} />)}
{orders.length === 0 && <Typography.Text type="secondary" style={{ textAlign: "center", padding: 24, fontSize: 12 }}>{target ? "Drop an order here" : "No orders"}</Typography.Text>}
</Flex>
</div>
);
}
function Chip({ label, value, danger, active, onClick }: { label: string; value: ReactNode; danger?: boolean; active?: boolean; onClick?: () => void }) {
const { token } = theme.useToken();
return (
<div role={onClick ? "button" : undefined} tabIndex={onClick ? 0 : undefined} onClick={onClick} onKeyDown={(e) => e.key === "Enter" && onClick?.()} aria-pressed={onClick ? !!active : undefined}
style={{ display: "flex", alignItems: "baseline", gap: 8, padding: "6px 14px", borderRadius: 999, cursor: onClick ? "pointer" : "default", border: `1px solid ${active ? token.colorError : token.colorBorderSecondary}`, background: active ? token.colorErrorBg : token.colorBgContainer }}>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>{label}</Typography.Text>
<Typography.Text strong type={danger ? "danger" : undefined} style={{ fontSize: 16 }}>{value}</Typography.Text>
</div>
);
}
export default function Page() {
const { message } = App.useApp();
const screens = Grid.useBreakpoint();
const [orders, setOrders] = useState<Order[]>(SEED);
const [q, setQ] = useState("");
const [channel, setChannel] = useState<"all" | Channel>("all");
const [lateOnly, setLateOnly] = useState(false);
const [showCancelled, setShowCancelled] = useState(false);
const [dragId, setDragId] = useState<string | null>(null);
const [openId, setOpenId] = useState<string | null>(null);
const [cancelId, setCancelId] = useState<string | null>(null);
const [reason, setReason] = useState<string>();
const [note, setNote] = useState("");
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
const kw = q.trim().toLowerCase();
const visible = useMemo(() => orders.filter((o) => (channel === "all" || o.channel === channel) && (!lateOnly || isLate(o)) && (!kw || o.code.toLowerCase().includes(kw) || o.customer.toLowerCase().includes(kw))), [orders, channel, lateOnly, kw]);
const active = orders.find((o) => o.id === dragId);
const opened = orders.find((o) => o.id === openId);
const cancelling = orders.find((o) => o.id === cancelId);
const inProgress = orders.filter((o) => o.status !== "done" && o.status !== "cancelled");
const kpi = {
today: orders.filter((o) => o.createdAt.isSame(dayjs(), "day")).length,
wip: inProgress.reduce((s, o) => s + total(o), 0),
late: orders.filter(isLate).length,
};
const move = (id: string, to: Status, reasonNote?: string) =>
setOrders((os) => os.map((o) => (o.id === id ? { ...o, status: to, history: [...o.history, { status: to, by: "You", at: dayjs(), note: reasonNote }] } : o)));
const request = (o: Order, to: Status) => {
if (o.status === to) return;
if (!canMove(o.status, to)) {
const next = nextOf(o.status);
message.warning(next ? `Order ${o.code} can only move to “${META[next].title}” — steps can't be skipped or reversed.` : `Order ${o.code} is already ${META[o.status].title.toLowerCase()} and can't change status.`);
return;
}
if (to === "cancelled") { setCancelId(o.id); setReason(undefined); setNote(""); return; }
move(o.id, to);
message.success(`${o.code}: ${META[to].title}`);
};
const onDragEnd = (e: DragEndEvent) => {
setDragId(null);
const o = orders.find((x) => x.id === e.active.id);
if (o && e.over) request(o, e.over.id as Status);
};
const confirmCancel = () => {
if (!cancelling || !reason) return;
move(cancelling.id, "cancelled", reason === "Other" ? note.trim() : [reason, note.trim()].filter(Boolean).join(" — "));
message.success(`Order ${cancelling.code} cancelled`);
setCancelId(null);
};
const next = opened && nextOf(opened.status);
return (
<PageContainer title="Orders" subTitle={`${inProgress.length} orders in progress · drag a card to the next column to advance it`}>
<Flex justify="space-between" align="center" gap={12} wrap style={{ marginBottom: 16 }}>
<Flex gap={8} wrap>
<Chip label="Orders today" value={kpi.today} />
<Chip label="Value in progress" value={vnd(kpi.wip)} />
<Chip label="Late" value={kpi.late} danger={kpi.late > 0} active={lateOnly} onClick={() => setLateOnly((v) => !v)} />
</Flex>
<Flex gap={8} wrap>
<Input allowClear prefix={<SearchOutlined />} placeholder="Order number, customer" value={q} onChange={(e) => setQ(e.target.value)} style={{ width: 220 }} />
<Segmented<"all" | Channel> value={channel} onChange={setChannel} options={[{ label: "All", value: "all" }, "Showroom", "Website", "B2B"]} />
</Flex>
</Flex>
<DndContext sensors={sensors} onDragStart={(e) => setDragId(String(e.active.id))} onDragCancel={() => setDragId(null)} onDragEnd={onDragEnd}>
<div style={{ overflowX: "auto", paddingBottom: 8 }}>
<Flex gap={12} align="flex-start" style={{ minWidth: "min-content" }}>
{FLOW.map((s) => <Column key={s} status={s} orders={visible.filter((o) => o.status === s)} target={!!active && canMove(active.status, s)} onOpen={setOpenId} />)}
<Column status="cancelled" orders={visible.filter((o) => o.status === "cancelled")} target={!!active && canMove(active.status, "cancelled")} collapsed={!showCancelled} onToggle={() => setShowCancelled((v) => !v)} onOpen={setOpenId} />
</Flex>
</div>
<DragOverlay>{active ? <div style={{ transform: "rotate(2deg)" }}><OrderCard o={active} /></div> : null}</DragOverlay>
</DndContext>
<Drawer open={!!opened} onClose={() => setOpenId(null)} size={screens.sm ? 560 : "100%"} destroyOnHidden
title={opened && <Flex gap={8} align="center">{opened.code}<Badge status={META[opened.status].badge} text={META[opened.status].title} /></Flex>}
footer={opened && canMove(opened.status, "cancelled") && (
<Flex justify="space-between">
<Button danger icon={<StopOutlined />} onClick={() => request(opened, "cancelled")}>Cancel order</Button>
{next && <Button type="primary" icon={<ArrowRightOutlined />} iconPlacement="end" onClick={() => request(opened, next)}>Move to {META[next].title}</Button>}
</Flex>
)}>
{opened && (
<Flex vertical gap={24}>
<Descriptions size="small" column={1} items={[
{ key: "c", label: "Customer", children: opened.customer },
{ key: "p", label: "Phone", children: opened.phone },
{ key: "a", label: "Delivery address", children: opened.address },
{ key: "ch", label: "Channel", children: <Tag color={CHANNEL_COLOR[opened.channel]}>{opened.channel}</Tag> },
{ key: "o", label: "Owner", children: <Flex gap={8} align="center"><Staff name={opened.owner} size={20} />{opened.owner}</Flex> },
{ key: "d", label: "Due date", children: <Typography.Text type={isLate(opened) ? "danger" : undefined}>{opened.due.format("MMM D, YYYY")}{isLate(opened) ? ` · ${dueText(opened).toLowerCase()}` : ""}</Typography.Text> },
]} />
<div>
<Typography.Title level={5}>Items</Typography.Title>
<Table<Line> size="small" rowKey="name" pagination={false} dataSource={opened.lines} columns={[
{ title: "Product", dataIndex: "name" },
{ title: "Qty", dataIndex: "qty", align: "right", width: 56 },
{ title: "Unit price", dataIndex: "price", align: "right", render: vnd },
{ title: "Amount", key: "sum", align: "right", render: (_, l) => vnd(l.qty * l.price) },
]} summary={() => (
<Table.Summary.Row>
<Table.Summary.Cell index={0} colSpan={3}><Typography.Text strong>Total</Typography.Text></Table.Summary.Cell>
<Table.Summary.Cell index={1} align="right"><Typography.Text strong>{vnd(total(opened))}</Typography.Text></Table.Summary.Cell>
</Table.Summary.Row>
)} />
</div>
<div>
<Typography.Title level={5}>History</Typography.Title>
<Timeline items={opened.history.map((h, i) => ({
key: i, color: META[h.status].dot, title: META[h.status].title,
content: <Typography.Text type="secondary" style={{ fontSize: 12 }}>{h.by} · {h.at.format("MMM D, h:mm A")}{h.note ? <><br />Reason: {h.note}</> : null}</Typography.Text>,
}))} />
</div>
</Flex>
)}
</Drawer>
<Modal open={!!cancelling} title={`Cancel order ${cancelling?.code ?? ""}`} okText="Cancel order" cancelText="Keep order" destroyOnHidden onOk={confirmCancel} onCancel={() => setCancelId(null)}
okButtonProps={{ danger: true, disabled: !reason || (reason === "Other" && !note.trim()) }}>
<Typography.Paragraph type="secondary">The reason is saved to the order history. A cancelled order can't be reopened.</Typography.Paragraph>
<Radio.Group orientation="vertical" value={reason} onChange={(e) => setReason(e.target.value)} options={REASONS} />
<Input.TextArea rows={2} value={note} onChange={(e) => setNote(e.target.value)} placeholder={reason === "Other" ? "Describe the reason (required)" : "Additional note (optional)"} style={{ marginTop: 12 }} />
</Modal>
</PageContainer>
);
}
Build an order tracking board as a kanban for a furniture store, with the columns New → Confirmed → Shipping → Done, plus a collapsed Cancelled column at the end that opens on click. Each card shows the order code, customer name, a channel tag (Showroom / Website / B2B), the order total, the delivery date (late orders in red with "n days late") and the assignee's avatar. Drag cards with @dnd-kit and only allow moving to the next step: no skipping, no going back, and done orders cannot be dragged. Dropping on Cancelled opens a Modal that requires a reason — "Other" requires a note — and saves it to the order history. The header shows today's orders, the value in progress and the number of late deliveries (click to filter late orders), plus a search by order code or customer name and a channel filter. Clicking a card opens a Drawer with the customer, a product table with a total row, a status timeline, and "Cancel order" / "Move to next step" buttons. Data comes from the app's API through useApiClient(): api.orders.list({ q, channel }) to load, api.orders.updateStatus(id, { status, reason }) on a status change, then reload. The backend must refuse skipped steps too. On narrow screens the board scrolls horizontally.Clinic appointments
One column per doctor; two bookings can’t overlap.
// Dental clinic front-desk schedule: one column per dentist, 30-minute slots 08:00–18:00, click an empty slot to book (double bookings blocked), click an appointment to check in / start / complete.
// In a real app: api.appointments.list({ branch, date }) loads the grid, api.appointments.create(...) books (the server blocks clashes too), api.appointments.update(id, { status }) changes status.
import { useMemo, useState } from "react";
import { DrawerForm, PageContainer, ProFormDependency, ProFormRadio, ProFormSelect, ProFormTextArea, StatisticCard } from "@ant-design/pro-components";
import { Alert, App, Avatar, Badge, Button, DatePicker, Descriptions, Drawer, Flex, Form, Select, Space, Steps, Typography, theme } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import dayjs, { type Dayjs } from "dayjs";
/** Mock people get a face (manh.run avatars 01–24), the same one for the same name. */
const face = (name: string) => {
let h = 0;
for (const ch of name) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
return `https://manh.run/avatars/${String((h % 24) + 1).padStart(2, "0")}.svg`;
};
type Status = "booked" | "arrived" | "in_progress" | "done" | "no_show";
type Appt = { id: number; branch: string; date: string; doctor: string; start: number; dur: number; phone: string; service: string; status: Status; note?: string };
const OPEN = 8 * 60, CLOSE = 18 * 60, STEP = 30, ROW_H = 44;
const ROWS = Array.from({ length: (CLOSE - OPEN) / STEP }, (_, i) => OPEN + i * STEP);
const hhmm = (m: number) => `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`;
const WEEKDAY = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const STATUS: Record<Status, { text: string; badge: "default" | "processing" | "warning" | "success" | "error" }> = {
booked: { text: "Booked", badge: "processing" },
arrived: { text: "Checked in", badge: "warning" },
in_progress: { text: "In chair", badge: "success" },
done: { text: "Done", badge: "default" },
no_show: { text: "No-show", badge: "error" },
};
const BRANCHES = [
{ value: "q3", label: "Midtown — 214 Lexington Ave" },
{ value: "td", label: "Brooklyn — 18 Court St" },
];
const DOCTORS: Record<string, Array<{ id: string; name: string; role: string }>> = {
q3: [
{ id: "hung", name: "Dr. Robert Hayes", role: "Orthodontics" },
{ id: "mai", name: "Dr. Maria Lopez", role: "General dentistry" },
{ id: "huy", name: "Dr. Andrew Kim", role: "Oral surgery" },
{ id: "anh", name: "Dr. Sophie Turner", role: "Cosmetic dentistry" },
],
td: [
{ id: "khoa", name: "Dr. Nathan Price", role: "General dentistry" },
{ id: "thu", name: "Dr. Chloe Walker", role: "Orthodontics" },
{ id: "tuan", name: "Dr. Marcus Bell", role: "Oral surgery" },
],
};
const SERVICES: Record<string, number> = { "Checkup": 30, "Cleaning": 30, "Filling": 60, "Braces — follow-up": 30, "Wisdom tooth extraction": 60, "Whitening": 90, "Root canal": 90 };
const PATIENTS = [
["(212) 555-0147", "Jessica Morgan"], ["(212) 555-0183", "Tyler Brooks"], ["(646) 555-0129", "Ashley Coleman"],
["(646) 555-0172", "Brandon Hughes"], ["(718) 555-0136", "Natalie Foster"], ["(718) 555-0194", "Jordan Patel"],
["(917) 555-0158", "Samantha Gray"], ["(917) 555-0111", "Christopher Diaz"], ["(347) 555-0165", "Rachel Kim"], ["(347) 555-0108", "Justin Ward"],
] as const;
const patientName = (phone: string) => PATIENTS.find((p) => p[0] === phone)?.[1] ?? phone;
const day = (offset: number) => dayjs().add(offset, "day").format("YYYY-MM-DD");
const SEED: Appt[] = ([
["q3", -1, "hung", "08:30", 30, 1, "Braces — follow-up", "done"], ["q3", -1, "mai", "09:00", 60, 4, "Filling", "done"], ["q3", -1, "anh", "14:00", 90, 6, "Whitening", "no_show"],
["q3", 0, "hung", "08:00", 30, 0, "Braces — follow-up", "done"], ["q3", 0, "hung", "09:30", 30, 3, "Braces — follow-up", "arrived"], ["q3", 0, "hung", "14:00", 30, 8, "Checkup", "booked"],
["q3", 0, "mai", "08:30", 30, 2, "Cleaning", "done"], ["q3", 0, "mai", "10:00", 60, 5, "Filling", "in_progress"], ["q3", 0, "mai", "15:30", 30, 9, "Cleaning", "booked"],
["q3", 0, "huy", "09:00", 60, 7, "Wisdom tooth extraction", "in_progress"], ["q3", 0, "huy", "13:30", 90, 1, "Root canal", "booked"],
["q3", 0, "anh", "08:00", 30, 6, "Checkup", "no_show"], ["q3", 0, "anh", "10:30", 90, 4, "Whitening", "booked"], ["q3", 0, "anh", "16:00", 60, 0, "Filling", "booked"],
["q3", 1, "hung", "09:00", 30, 2, "Braces — follow-up", "booked"], ["q3", 1, "huy", "10:00", 60, 3, "Wisdom tooth extraction", "booked"],
["td", 0, "khoa", "08:30", 30, 5, "Cleaning", "arrived"], ["td", 0, "khoa", "11:00", 60, 9, "Filling", "booked"], ["td", 0, "thu", "09:00", 30, 7, "Braces — follow-up", "done"],
["td", 0, "tuan", "14:30", 60, 8, "Wisdom tooth extraction", "booked"],
] as const).map(([branch, off, doctor, t, dur, p, service, status], i) => ({
id: i + 1, branch, date: day(off), doctor, start: Number(t.slice(0, 2)) * 60 + Number(t.slice(3)), dur, phone: PATIENTS[p][0], service, status,
}));
const blocks = (a: Appt) => a.status !== "no_show"; // a no-show frees the chair
function findClash(list: Appt[], v: { branch: string; date: string; doctor: string; start: number; dur: number }) {
return list.find((a) => blocks(a) && a.branch === v.branch && a.date === v.date && a.doctor === v.doctor && v.start < a.start + a.dur && a.start < v.start + v.dur);
}
export default function Page() {
const { token } = theme.useToken();
const { message } = App.useApp();
const [form] = Form.useForm();
const [appts, setAppts] = useState<Appt[]>(SEED);
const [branch, setBranch] = useState("q3");
const [date, setDate] = useState<Dayjs>(dayjs().startOf("day"));
const [booking, setBooking] = useState<{ doctor?: string; start?: number } | null>(null);
const [openId, setOpenId] = useState<number | null>(null);
const [hover, setHover] = useState<string | null>(null);
const dateKey = date.format("YYYY-MM-DD");
const doctors = DOCTORS[branch];
const docName = (id: string) => doctors.find((d) => d.id === id)?.name ?? id;
const dayAppts = useMemo(() => appts.filter((a) => a.branch === branch && a.date === dateKey), [appts, branch, dateKey]);
const nowMin = dayjs().hour() * 60 + dayjs().minute();
const isToday = date.isSame(dayjs(), "day");
const isPast = (start: number) => date.isBefore(dayjs(), "day") || (isToday && start + STEP <= nowMin);
const busy = (doctor: string, m: number) => dayAppts.some((a) => blocks(a) && a.doctor === doctor && m >= a.start && m < a.start + a.dur);
const freeLeft = doctors.reduce((n, d) => n + ROWS.filter((m) => !isPast(m) && !busy(d.id, m)).length, 0);
const count = (...s: Status[]) => dayAppts.filter((a) => s.includes(a.status)).length;
const current = appts.find((a) => a.id === openId);
const setStatus = (id: number, status: Status) => {
setAppts((xs) => xs.map((a) => (a.id === id ? { ...a, status } : a)));
message.success(`${patientName(appts.find((a) => a.id === id)!.phone)}: ${STATUS[status].text.toLowerCase()}`);
setOpenId(null);
};
const openSlot = (doctor: string, start: number) => {
if (isPast(start)) return message.info("That time has already passed — pick another slot.");
setBooking({ doctor, start });
};
const shift = (n: number) => setDate(dayjs().startOf("day").add(n, "day"));
const isOffset = (n: number) => date.isSame(dayjs().add(n, "day"), "day");
return (
<PageContainer
title="Appointments"
subTitle={`${WEEKDAY[date.day()]}, ${date.format("MMM D, YYYY")}`}
extra={[
<Select key="b" value={branch} onChange={setBranch} options={BRANCHES} style={{ width: 280 }} />,
<Space.Compact key="d">
<Button type={isOffset(-1) ? "primary" : "default"} onClick={() => shift(-1)}>Yesterday</Button>
<Button type={isOffset(0) ? "primary" : "default"} onClick={() => shift(0)}>Today</Button>
<Button type={isOffset(1) ? "primary" : "default"} onClick={() => shift(1)}>Tomorrow</Button>
<DatePicker value={date} onChange={(d) => d && setDate(d.startOf("day"))} format="MMM D, YYYY" allowClear={false} style={{ width: 130 }} />
</Space.Compact>,
<Button key="n" type="primary" icon={<PlusOutlined />} disabled={date.isBefore(dayjs(), "day")} onClick={() => setBooking({})}>Book appointment</Button>,
]}
>
<Flex vertical gap={16}>
<StatisticCard.Group direction="row">
<StatisticCard statistic={{ title: "Appointments", value: dayAppts.length, description: `${count("booked")} not arrived yet` }} />
<StatisticCard.Divider />
<StatisticCard statistic={{ title: "Checked in", value: count("arrived", "in_progress", "done"), description: `${count("in_progress")} in chair · ${count("done")} done` }} />
<StatisticCard.Divider />
<StatisticCard statistic={{ title: "No-shows", value: count("no_show"), styles: { content: count("no_show") ? { color: token.colorError } : undefined } }} />
<StatisticCard.Divider />
<StatisticCard statistic={{ title: "Open slots left", value: freeLeft, suffix: `/ ${doctors.length * ROWS.length}`, description: "unbooked 30-minute slots" }} />
</StatisticCard.Group>
<Flex gap={16} wrap align="center">
{(Object.keys(STATUS) as Status[]).map((s) => <Badge key={s} status={STATUS[s].badge} text={STATUS[s].text} />)}
<Typography.Text type="secondary" style={{ marginLeft: "auto" }}>Click an empty slot to book · click an appointment to check in</Typography.Text>
</Flex>
<div style={{ overflow: "auto", maxHeight: 640, background: token.colorBgContainer, border: `1px solid ${token.colorBorderSecondary}`, borderRadius: token.borderRadiusLG }}>
<div style={{ display: "grid", gridTemplateColumns: `64px repeat(${doctors.length}, minmax(190px, 1fr))`, minWidth: 64 + doctors.length * 190 }}>
<div style={{ position: "sticky", top: 0, left: 0, zIndex: 3, background: token.colorBgContainer, borderBottom: `1px solid ${token.colorBorderSecondary}` }} />
{doctors.map((d) => (
<Flex key={d.id} gap={8} align="center" style={{ position: "sticky", top: 0, zIndex: 2, background: token.colorBgContainer, padding: "10px 12px", borderBottom: `1px solid ${token.colorBorderSecondary}`, borderLeft: `1px solid ${token.colorBorderSecondary}` }}>
<Avatar src={face(d.name)} alt={d.name} />
<div style={{ lineHeight: 1.3 }}>
<Typography.Text strong>{d.name}</Typography.Text>
<div><Typography.Text type="secondary" style={{ fontSize: 12 }}>{d.role} · {dayAppts.filter((a) => a.doctor === d.id && blocks(a)).length} appts</Typography.Text></div>
</div>
</Flex>
))}
<div style={{ position: "sticky", left: 0, zIndex: 1, background: token.colorBgContainer }}>
{ROWS.map((m) => (
<div key={m} style={{ height: ROW_H, padding: "2px 8px", fontSize: 12, color: token.colorTextTertiary, textAlign: "right", borderTop: m % 60 ? undefined : `1px solid ${token.colorBorderSecondary}` }}>{m % 60 ? "" : hhmm(m)}</div>
))}
</div>
{doctors.map((d) => (
<div key={d.id} style={{ position: "relative", borderLeft: `1px solid ${token.colorBorderSecondary}` }}>
{ROWS.map((m) => {
const k = `${d.id}-${m}`, past = isPast(m), free = !busy(d.id, m);
return (
<div key={k} role="button" aria-label={`Book ${d.name} at ${hhmm(m)}`} onClick={() => free && openSlot(d.id, m)} onMouseEnter={() => setHover(k)} onMouseLeave={() => setHover(null)}
style={{ height: ROW_H, borderTop: `1px ${m % 60 ? "dashed" : "solid"} ${token.colorBorderSecondary}`, background: past ? token.colorFillQuaternary : hover === k && free ? token.colorPrimaryBg : undefined, cursor: free && !past ? "pointer" : "default", padding: "0 8px", fontSize: 12, lineHeight: `${ROW_H}px`, color: token.colorPrimary }}>
{hover === k && free && !past ? `+ Book ${hhmm(m)}` : null}
</div>
);
})}
{dayAppts.filter((a) => a.doctor === d.id).map((a) => {
const c = { booked: token.colorInfo, arrived: token.colorWarning, in_progress: token.colorSuccess, done: token.colorTextQuaternary, no_show: token.colorError }[a.status];
const bg = { booked: token.colorInfoBg, arrived: token.colorWarningBg, in_progress: token.colorSuccessBg, done: token.colorFillTertiary, no_show: token.colorErrorBg }[a.status];
return (
<div key={a.id} role="button" onClick={() => setOpenId(a.id)}
style={{ position: "absolute", left: 4, right: a.status === "no_show" ? "45%" : 4, top: ((a.start - OPEN) / STEP) * ROW_H + 2, height: (a.dur / STEP) * ROW_H - 4, background: bg, borderLeft: `3px solid ${c}`, borderRadius: token.borderRadiusSM, padding: "2px 8px", overflow: "hidden", cursor: "pointer", opacity: a.status === "done" ? 0.75 : 1, boxShadow: token.boxShadowTertiary }}>
<Flex justify="space-between" gap={4} style={{ fontSize: 12 }}>
<Typography.Text strong ellipsis style={{ fontSize: 12, textDecoration: a.status === "no_show" ? "line-through" : undefined }}>{patientName(a.phone)}</Typography.Text>
<Typography.Text type="secondary" style={{ fontSize: 11, flexShrink: 0 }}>{hhmm(a.start)}</Typography.Text>
</Flex>
{a.dur > STEP || a.status !== "no_show" ? <Typography.Text type="secondary" ellipsis style={{ fontSize: 12, display: "block" }}>{a.service} · {STATUS[a.status].text}</Typography.Text> : null}
</div>
);
})}
{isToday && nowMin > OPEN && nowMin < CLOSE ? <div style={{ position: "absolute", left: 0, right: 0, top: ((nowMin - OPEN) / STEP) * ROW_H, borderTop: `2px solid ${token.colorError}`, pointerEvents: "none" }} /> : null}
</div>
))}
</div>
</div>
</Flex>
<DrawerForm<{ phone: string; service: string; doctor: string; start: number; dur: number; note?: string }>
key={booking ? `${booking.doctor}-${booking.start}` : "closed"}
title={`Book appointment · ${date.format("MMM D, YYYY")}`}
open={!!booking}
onOpenChange={(o) => !o && setBooking(null)}
form={form}
width={480}
drawerProps={{ destroyOnHidden: true }}
initialValues={{ doctor: booking?.doctor, start: booking?.start, dur: 30 }}
submitter={{ searchConfig: { submitText: "Book", resetText: "Cancel" } }}
onValuesChange={(changed) => changed.service && form.setFieldValue("dur", SERVICES[changed.service])}
onFinish={async (v) => {
if (v.start + v.dur > CLOSE) { message.error(`This appointment would end at ${hhmm(v.start + v.dur)}, after closing time (18:00) — pick an earlier slot.`); return false; }
const clash = findClash(appts, { branch, date: dateKey, ...v });
if (clash) { message.error(`${docName(v.doctor)} is already booked ${hhmm(clash.start)}–${hhmm(clash.start + clash.dur)} with ${patientName(clash.phone)}. Pick another time or dentist.`); return false; }
setAppts((xs) => [...xs, { id: Math.max(...xs.map((a) => a.id)) + 1, branch, date: dateKey, status: "booked", ...v }]);
message.success(`Booked ${patientName(v.phone)} at ${hhmm(v.start)} with ${docName(v.doctor)}`);
return true;
}}
>
<ProFormSelect name="phone" label="Patient" placeholder="Type a phone number or name" showSearch rules={[{ required: true, message: "Select a patient" }]}
options={PATIENTS.map(([phone, name]) => ({ value: phone, label: `${phone} · ${name}` }))} />
<ProFormSelect name="service" label="Service" rules={[{ required: true, message: "Select a service" }]}
options={Object.entries(SERVICES).map(([s, m]) => ({ value: s, label: `${s} (${m} min)` }))} />
<ProFormSelect name="doctor" label="Dentist" rules={[{ required: true, message: "Select a dentist" }]} options={doctors.map((d) => ({ value: d.id, label: `${d.name} — ${d.role}` }))} />
<Flex gap={16}>
<ProFormSelect name="start" label="Start time" width="xs" rules={[{ required: true, message: "Select a time" }]} options={ROWS.filter((m) => !isPast(m)).map((m) => ({ value: m, label: hhmm(m) }))} />
<ProFormRadio.Group name="dur" label="Duration" radioType="button" options={[30, 60, 90, 120].map((m) => ({ value: m, label: `${m} min` }))} />
</Flex>
<ProFormDependency name={["doctor", "start", "dur"]}>
{({ doctor, start, dur }) => {
if (!doctor || start == null || !dur) return null;
const clash = findClash(appts, { branch, date: dateKey, doctor, start, dur });
if (clash) return <Alert type="error" showIcon style={{ marginBottom: 16 }} title={`Clash: ${docName(doctor)} is seeing ${patientName(clash.phone)} ${hhmm(clash.start)}–${hhmm(clash.start + clash.dur)}`} />;
return <Alert type="success" showIcon style={{ marginBottom: 16 }} title={`Available ${hhmm(start)}–${hhmm(start + dur)}`} />;
}}
</ProFormDependency>
<ProFormTextArea name="note" label="Notes" placeholder="e.g. sensitive lower left molar, anxious patient, call a day ahead to remind" fieldProps={{ rows: 3, maxLength: 500 }} />
</DrawerForm>
<Drawer size={420} open={!!current} onClose={() => setOpenId(null)} title={current ? patientName(current.phone) : ""} extra={current ? <Badge status={STATUS[current.status].badge} text={STATUS[current.status].text} /> : null}
footer={current && (
<Flex gap={8} justify="flex-end">
{current.status === "booked" && <Button danger onClick={() => setStatus(current.id, "no_show")}>Mark as no-show</Button>}
{current.status === "booked" && <Button type="primary" onClick={() => setStatus(current.id, "arrived")}>Check-in</Button>}
{current.status === "arrived" && <Button type="primary" onClick={() => setStatus(current.id, "in_progress")}>Start visit</Button>}
{current.status === "in_progress" && <Button type="primary" onClick={() => setStatus(current.id, "done")}>Complete</Button>}
{(current.status === "done" || current.status === "no_show") && <Typography.Text type="secondary">Appointment closed</Typography.Text>}
</Flex>
)}>
{current ? (
<Flex vertical gap={24}>
<Steps size="small" orientation="vertical" current={current.status === "no_show" ? 1 : ["booked", "arrived", "in_progress", "done"].indexOf(current.status) + (current.status === "done" ? 1 : 0)} status={current.status === "no_show" ? "error" : undefined}
items={[{ title: "Booked" }, { title: current.status === "no_show" ? "No-show" : "Checked in" }, { title: "In chair" }, { title: "Done" }]} />
<Descriptions column={1} size="small" items={[
{ label: "Phone", children: current.phone },
{ label: "Service", children: current.service },
{ label: "Dentist", children: docName(current.doctor) },
{ label: "Time", children: `${hhmm(current.start)}–${hhmm(current.start + current.dur)} · ${dayjs(current.date).format("MMM D, YYYY")}` },
{ label: "Notes", children: current.note || "—" },
]} />
</Flex>
) : null}
</Drawer>
</PageContainer>
);
}
Build an appointment calendar for the front desk of a dental clinic with several branches at `app/appointments/page.tsx`: a day view where each dentist of the selected branch is a column and each row is a 30-minute slot from 08:00 to 18:00; appointments show as blocks (patient name, service such as scaling, filling, braces; one colour per status: Booked, Arrived, In treatment, Done, No-show). At the top: a branch picker, Yesterday / Today / Tomorrow buttons with a DatePicker, and the day's numbers (appointments, arrived, no-shows, free slots left). Clicking an empty slot opens a DrawerForm to book (find the patient by phone number, choosing a service fills in its duration, pick dentist and time). Never allow two overlapping appointments for the same dentist — the error says who is booked at what time. No booking in the past or ending after 18:00. The API must refuse overlaps too, not only the UI. Clicking an appointment opens a Drawer that only shows the buttons valid for its status: Check in, Start treatment, Finish, Mark no-show. Build the grid with divs and antd tokens, no calendar library. Data comes from the app's API through `useApiClient()` (`appointments.list` by branch and day, `appointments.create`, `appointments.update` to change status) — no hard-coded data in the page.
Point of sale
Item grid, open bill, three ways to pay.
// Coffee shop point of sale: item grid by category + search, ticket with size/notes/quantity, dine-in or takeaway, discount codes, 8% tax, three payment methods, multiple held tickets, receipt printing.
// In a real app: items come from api.products.list(), codes are checked with api.discounts.check(code), "Charge" calls api.orders.create(...) and the server recalculates the totals.
import { useMemo, useState } from "react";
import { PageContainer, ProCard } from "@ant-design/pro-components";
import { App, AutoComplete, Button, Col, Divider, Empty, Flex, Input, InputNumber, Modal, QRCode, Row, Segmented, Select, Space, Tabs, Tag, Typography } from "antd";
import { CreditCardOutlined, DeleteOutlined, MinusOutlined, PauseCircleOutlined, PlusOutlined, SearchOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
type Size = "M" | "L";
type Method = "cash" | "transfer" | "card";
type Product = { id: string; name: string; cat: string; price: number; priceL?: number; out?: boolean };
type Line = { key: string; pid: string; size: Size; qty: number; note: string };
type Bill = { id: string; mode: "table" | "takeaway"; table: string; no: number; lines: Line[]; code: string; method: Method; given: number | null };
const CATS = ["Coffee", "Tea", "Bakery", "Add-ons"];
const PRODUCTS: Product[] = [
{ id: "cf1", name: "Iced latte", cat: "Coffee", price: 4.75, priceL: 5.5 },
{ id: "cf2", name: "Cold brew", cat: "Coffee", price: 4.25, priceL: 5 },
{ id: "cf3", name: "Flat white", cat: "Coffee", price: 4.5, priceL: 5.25 },
{ id: "cf4", name: "Sea salt cold foam", cat: "Coffee", price: 5.5, priceL: 6.25 },
{ id: "cf5", name: "Coconut mocha", cat: "Coffee", price: 5.75, priceL: 6.5, out: true },
{ id: "cf6", name: "Espresso", cat: "Coffee", price: 3.25 },
{ id: "tr1", name: "Peach lemongrass iced tea", cat: "Tea", price: 4.5, priceL: 5.25 },
{ id: "tr2", name: "Lychee rose tea", cat: "Tea", price: 4.75, priceL: 5.5 },
{ id: "tr3", name: "Jasmine green tea", cat: "Tea", price: 4.25, priceL: 5, out: true },
{ id: "tr4", name: "Oolong milk tea", cat: "Tea", price: 5.25, priceL: 6 },
{ id: "bk1", name: "Ham & cheese roll", cat: "Bakery", price: 4.5 },
{ id: "bk2", name: "Butter croissant", cat: "Bakery", price: 3.75 },
{ id: "bk3", name: "Tiramisu", cat: "Bakery", price: 6.5 },
{ id: "bk4", name: "Blueberry muffin", cat: "Bakery", price: 3.5, out: true },
{ id: "tp1", name: "Boba pearls", cat: "Add-ons", price: 0.75 },
{ id: "tp2", name: "Peach jelly", cat: "Add-ons", price: 0.75 },
{ id: "tp3", name: "Cheese foam", cat: "Add-ons", price: 1.25 },
{ id: "tp4", name: "Extra espresso shot", cat: "Add-ons", price: 1 },
];
const byId = Object.fromEntries(PRODUCTS.map((p) => [p.id, p]));
const TABLES = Array.from({ length: 12 }, (_, i) => `Table ${i + 1}`);
const NOTES = ["light ice", "no ice", "less sweet", "no sugar", "extra milk", "ice on the side"].map((value) => ({ value }));
const CODES: Record<string, { label: string; min: number; calc: (sub: number) => number }> = {
REGULAR10: { label: "10% off for regulars", min: 0, calc: (s) => Math.round(s * 10) / 100 },
SAVE3: { label: "$3 off orders of $15 or more", min: 15, calc: () => 3 },
};
const METHOD_LABEL: Record<Method, string> = { cash: "Cash", transfer: "Bank transfer", card: "Card" };
const fmt = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });
const vnd = (n: number) => n.toLocaleString("en-US", { style: "currency", currency: "USD" });
const unitPrice = (l: Line) => (l.size === "L" ? byId[l.pid].priceL ?? byId[l.pid].price : byId[l.pid].price);
const billName = (b: Bill) => (b.mode === "table" ? b.table : `Takeaway #${b.no}`);
function totals(b: Bill) {
const sub = b.lines.reduce((s, l) => s + unitPrice(l) * l.qty, 0);
const c = CODES[b.code];
const disc = c && sub >= c.min ? Math.min(c.calc(sub), sub) : 0;
const vat = Math.round((sub - disc) * 8) / 100;
return { sub, disc, vat, total: sub - disc + vat, count: b.lines.reduce((s, l) => s + l.qty, 0) };
}
let seq = 13;
const newBill = (): Bill => ({ id: `b${seq}`, mode: "takeaway", table: "Table 1", no: seq++, lines: [], code: "", method: "cash", given: null });
type Receipt = { invoice: string; at: string; bill: Bill; t: ReturnType<typeof totals> };
export default function Page() {
const { message, modal } = App.useApp();
const [bills, setBills] = useState<Bill[]>(() => [
{ id: "b11", mode: "table", table: "Table 4", no: 11, lines: [{ key: "1", pid: "cf1", size: "L", qty: 2, note: "light ice" }, { key: "2", pid: "bk2", size: "M", qty: 1, note: "" }], code: "", method: "cash", given: null },
{ id: "b12", mode: "takeaway", table: "Table 1", no: 12, lines: [{ key: "3", pid: "tr1", size: "M", qty: 1, note: "less sweet" }], code: "", method: "transfer", given: null },
]);
const [activeId, setActiveId] = useState("b11");
const [cat, setCat] = useState(CATS[0]);
const [q, setQ] = useState("");
const [codeInput, setCodeInput] = useState("");
const [receipt, setReceipt] = useState<Receipt | null>(null);
const [invoiceNo, setInvoiceNo] = useState(1042);
const bill = bills.find((b) => b.id === activeId) ?? bills[0];
const t = useMemo(() => totals(bill), [bill]);
const shown = useMemo(() => {
const s = q.trim().toLowerCase();
return PRODUCTS.filter((p) => (s ? p.name.toLowerCase().includes(s) : p.cat === cat));
}, [q, cat]);
const patch = (fn: (b: Bill) => Bill) => setBills((all) => all.map((b) => (b.id === bill.id ? fn(b) : b)));
const setLine = (key: string, fn: (l: Line) => Line | null) =>
patch((b) => ({ ...b, lines: b.lines.map((l) => (l.key === key ? fn(l) : l)).filter((l): l is Line => l !== null) }));
const add = (p: Product) => {
if (p.out) return;
patch((b) => {
const same = b.lines.find((l) => l.pid === p.id && l.size === "M" && !l.note);
if (same) return { ...b, lines: b.lines.map((l) => (l === same ? { ...l, qty: l.qty + 1 } : l)) };
return { ...b, lines: [...b.lines, { key: `${Date.now()}`, pid: p.id, size: "M", qty: 1, note: "" }] };
});
};
const hold = () => {
const nb = newBill();
setBills((all) => [...all, nb]);
setActiveId(nb.id);
setCodeInput("");
if (bill.lines.length) message.info(`${billName(bill)} is on hold — reopen it from the tabs above`);
};
const closeBill = (id: string) => {
const rest = bills.filter((b) => b.id !== id);
const next = rest.length ? rest : [newBill()];
setBills(next);
if (id === activeId) setActiveId(next[0].id);
};
const applyCode = (raw: string) => {
const code = raw.trim().toUpperCase();
if (!code) return patch((b) => ({ ...b, code: "" }));
const c = CODES[code];
if (!c) return message.error("That code is invalid or has expired");
if (t.sub < c.min) return message.warning(`Code ${code} needs an order of ${vnd(c.min)} or more`);
patch((b) => ({ ...b, code }));
setCodeInput("");
message.success(`Applied: ${c.label}`);
};
const cashShort = bill.method === "cash" && (bill.given ?? 0) < t.total;
const pay = () => {
const invoice = `INV${invoiceNo}`;
setReceipt({ invoice, at: dayjs().format("MMM D, YYYY h:mm A"), bill, t });
setInvoiceNo((n) => n + 1);
closeBill(bill.id);
};
const transferNote = `${billName(bill).replace(/\s|#/g, "").toUpperCase()} INV${invoiceNo}`;
return (
<PageContainer title="Point of sale" subTitle="Old Town Coffee · Morning shift · Cashier: Natalie">
<Row gutter={[16, 16]}>
<Col xs={24} lg={14}>
<ProCard>
<Flex gap={12} wrap align="center" style={{ marginBottom: 8 }}>
<Tabs activeKey={q ? "" : cat} onChange={(k) => { setCat(k); setQ(""); }} items={CATS.map((c) => ({ key: c, label: c }))} style={{ flex: 1, minWidth: 260, marginBottom: -16 }} />
<Input allowClear prefix={<SearchOutlined />} placeholder="Search items" value={q} onChange={(e) => setQ(e.target.value)} style={{ width: 200 }} />
</Flex>
{q && <Typography.Text type="secondary">{shown.length} items match “{q}” across all categories</Typography.Text>}
<Row gutter={[12, 12]} style={{ marginTop: 12 }}>
{shown.map((p) => (
<Col key={p.id} xs={12} sm={8} xxl={6}>
<ProCard bordered hoverable={!p.out} onClick={() => add(p)} style={{ height: "100%", cursor: p.out ? "not-allowed" : "pointer", opacity: p.out ? 0.5 : 1 }} bodyStyle={{ padding: 12 }}>
<Flex vertical gap={4}>
<Typography.Text strong ellipsis>{p.name}</Typography.Text>
<Flex justify="space-between" align="center">
<Typography.Text>{vnd(p.price)}</Typography.Text>
{p.out ? <Tag color="default">Sold out</Tag> : p.priceL ? <Typography.Text type="secondary" style={{ fontSize: 12 }}>L {vnd(p.priceL)}</Typography.Text> : null}
</Flex>
</Flex>
</ProCard>
</Col>
))}
{!shown.length && <Col span={24}><Empty description="No matching items" /></Col>}
</Row>
</ProCard>
</Col>
<Col xs={24} lg={10}>
<ProCard bodyStyle={{ paddingTop: 0 }}>
<Tabs
type="editable-card"
activeKey={bill.id}
onChange={(k) => { setActiveId(k); setCodeInput(""); }}
onEdit={(key, action) => {
if (action === "add") return hold();
const b = bills.find((x) => x.id === key);
if (!b?.lines.length) return closeBill(String(key));
modal.confirm({ title: `Void ${billName(b)}?`, content: `${b.lines.length} items will be removed from the ticket.`, okText: "Void ticket", okButtonProps: { danger: true }, cancelText: "Keep it", onOk: () => closeBill(b.id) });
}}
items={bills.map((b) => ({ key: b.id, label: `${billName(b)}${b.lines.length ? ` · ${totals(b).count}` : ""}` }))}
/>
<Flex gap={8} wrap align="center">
<Segmented value={bill.mode} onChange={(v) => patch((b) => ({ ...b, mode: v as Bill["mode"] }))} options={[{ value: "table", label: "Dine in" }, { value: "takeaway", label: "Takeaway" }]} />
{bill.mode === "table" && <Select value={bill.table} onChange={(v) => patch((b) => ({ ...b, table: v }))} options={TABLES.map((x) => ({ value: x, label: x }))} style={{ width: 110 }} />}
<Button icon={<PauseCircleOutlined />} onClick={hold} disabled={!bill.lines.length} style={{ marginLeft: "auto" }}>Hold</Button>
</Flex>
<Divider style={{ margin: "12px 0" }} />
{!bill.lines.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="Tap an item on the left to add it to the ticket" />}
<Flex vertical gap={12} style={{ maxHeight: 340, overflowY: "auto" }}>
{bill.lines.map((l) => {
const p = byId[l.pid];
return (
<Flex key={l.key} vertical gap={6}>
<Flex justify="space-between" align="center" gap={8}>
<Typography.Text strong ellipsis>{p.name}</Typography.Text>
<Typography.Text strong>{vnd(unitPrice(l) * l.qty)}</Typography.Text>
</Flex>
<Flex gap={8} align="center" wrap>
<Flex align="center" gap={4}>
<Button size="small" aria-label="Remove one" icon={l.qty === 1 ? <DeleteOutlined /> : <MinusOutlined />} onClick={() => setLine(l.key, (x) => (x.qty > 1 ? { ...x, qty: x.qty - 1 } : null))} />
<Typography.Text style={{ minWidth: 24, textAlign: "center" }}>{l.qty}</Typography.Text>
<Button size="small" aria-label="Add one" icon={<PlusOutlined />} onClick={() => setLine(l.key, (x) => ({ ...x, qty: x.qty + 1 }))} />
</Flex>
{p.priceL && <Segmented size="small" value={l.size} onChange={(v) => setLine(l.key, (x) => ({ ...x, size: v as Size }))} options={["M", "L"]} />}
<Typography.Text type="secondary" style={{ fontSize: 12 }}>{vnd(unitPrice(l))}</Typography.Text>
{p.cat !== "Add-ons" && p.cat !== "Bakery" && (
<AutoComplete size="small" options={NOTES} value={l.note} onChange={(v) => setLine(l.key, (x) => ({ ...x, note: v }))} placeholder="Note: light ice, less sweet…" allowClear style={{ flex: 1, minWidth: 140 }} />
)}
</Flex>
</Flex>
);
})}
</Flex>
<Divider style={{ margin: "12px 0" }} />
{bill.code ? (
<Tag color="green" closable onClose={() => patch((b) => ({ ...b, code: "" }))}>{bill.code} · {CODES[bill.code].label}</Tag>
) : (
<Input.Search placeholder="Discount code (e.g. REGULAR10)" enterButton="Apply" value={codeInput} onChange={(e) => setCodeInput(e.target.value)} onSearch={applyCode} disabled={!bill.lines.length} />
)}
<Flex vertical gap={4} style={{ marginTop: 12 }}>
<Flex justify="space-between"><Typography.Text type="secondary">Subtotal ({t.count} items)</Typography.Text><Typography.Text>{vnd(t.sub)}</Typography.Text></Flex>
{t.disc > 0 && <Flex justify="space-between"><Typography.Text type="secondary">Discount</Typography.Text><Typography.Text type="success">−{vnd(t.disc)}</Typography.Text></Flex>}
{bill.code && t.disc === 0 && <Typography.Text type="warning" style={{ fontSize: 12 }}>This order doesn't qualify for {bill.code} yet</Typography.Text>}
<Flex justify="space-between"><Typography.Text type="secondary">Tax 8%</Typography.Text><Typography.Text>{vnd(t.vat)}</Typography.Text></Flex>
<Flex justify="space-between" align="baseline"><Typography.Text strong>Total</Typography.Text><Typography.Title level={3} style={{ margin: 0 }}>{vnd(t.total)}</Typography.Title></Flex>
</Flex>
<Divider style={{ margin: "12px 0" }} />
<Segmented block value={bill.method} onChange={(v) => patch((b) => ({ ...b, method: v as Method }))} options={(Object.keys(METHOD_LABEL) as Method[]).map((m) => ({ value: m, label: METHOD_LABEL[m] }))} />
<div style={{ marginTop: 12 }}>
{bill.method === "cash" && (
<Flex vertical gap={8}>
<Space.Compact block><Space.Addon>Cash received</Space.Addon><InputNumber<number> prefix="$" min={0} step={1} value={bill.given} onChange={(v) => patch((b) => ({ ...b, given: v }))} formatter={(v) => (v ? fmt.format(Number(v)) : "")} parser={(v) => Number((v ?? "").replace(/[^\d.]/g, ""))} style={{ width: "100%" }} /></Space.Compact>
<Flex gap={6} wrap>
{[t.total, 20, 50, 100].filter((v, i, a) => v > 0 && v >= t.total && a.indexOf(v) === i).map((v, i) => (
<Button key={v} size="small" onClick={() => patch((b) => ({ ...b, given: v }))}>{i === 0 && v === t.total ? "Exact" : vnd(v)}</Button>
))}
</Flex>
<Flex justify="space-between">
<Typography.Text type="secondary">Change due</Typography.Text>
{cashShort ? <Typography.Text type="danger">{bill.given ? `Short by ${vnd(t.total - bill.given)}` : "—"}</Typography.Text> : <Typography.Text strong>{vnd((bill.given ?? 0) - t.total)}</Typography.Text>}
</Flex>
</Flex>
)}
{bill.method === "transfer" && (
<Flex gap={16} align="center">
<QRCode value={`ACCT 0123456789|${t.total}|${transferNote}`} size={128} bordered />
<Flex vertical gap={2}>
<Typography.Text type="secondary">Amount</Typography.Text>
<Typography.Text strong style={{ fontSize: 18 }}>{vnd(t.total)}</Typography.Text>
<Typography.Text type="secondary">Payment reference</Typography.Text>
<Typography.Text code copyable>{transferNote}</Typography.Text>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>Bank transfer · Account 0123456789 · OLD TOWN COFFEE LLC</Typography.Text>
</Flex>
</Flex>
)}
{bill.method === "card" && (
<Flex gap={8} align="center">
<CreditCardOutlined style={{ fontSize: 20 }} />
<Typography.Text type="secondary">Enter {vnd(t.total)} on the card terminal. Once it shows approved, press Charge.</Typography.Text>
</Flex>
)}
</div>
<Button type="primary" size="large" block style={{ marginTop: 16 }} disabled={!bill.lines.length || cashShort} onClick={pay}>
Charge {bill.lines.length ? vnd(t.total) : ""}
</Button>
</ProCard>
</Col>
</Row>
<Modal
open={!!receipt}
title={`Receipt ${receipt?.invoice ?? ""}`}
onCancel={() => setReceipt(null)}
width={380}
footer={[
<Button key="print" onClick={() => message.success("Receipt sent to the counter printer")}>Print receipt</Button>,
<Button key="ok" type="primary" onClick={() => setReceipt(null)}>New ticket</Button>,
]}
>
{receipt && (
<Flex vertical gap={6}>
<Typography.Text type="secondary">Old Town Coffee · 12 Market Street, Portland, OR</Typography.Text>
<Typography.Text type="secondary">{receipt.at} · {billName(receipt.bill)} · Cashier: Natalie</Typography.Text>
<Divider dashed style={{ margin: "6px 0" }} />
{receipt.bill.lines.map((l) => (
<Flex key={l.key} justify="space-between" gap={8}>
<span>{l.qty} × {byId[l.pid].name}{byId[l.pid].priceL ? ` (${l.size})` : ""}{l.note ? ` — ${l.note}` : ""}</span>
<span>{vnd(unitPrice(l) * l.qty)}</span>
</Flex>
))}
<Divider dashed style={{ margin: "6px 0" }} />
<Flex justify="space-between"><span>Subtotal</span><span>{vnd(receipt.t.sub)}</span></Flex>
{receipt.t.disc > 0 && <Flex justify="space-between"><span>Discount ({receipt.bill.code})</span><span>−{vnd(receipt.t.disc)}</span></Flex>}
<Flex justify="space-between"><span>Tax 8%</span><span>{vnd(receipt.t.vat)}</span></Flex>
<Flex justify="space-between"><Typography.Text strong>Total</Typography.Text><Typography.Text strong>{vnd(receipt.t.total)}</Typography.Text></Flex>
<Flex justify="space-between"><span>{METHOD_LABEL[receipt.bill.method]}</span><span>{vnd(receipt.bill.method === "cash" ? receipt.bill.given ?? 0 : receipt.t.total)}</span></Flex>
{receipt.bill.method === "cash" && <Flex justify="space-between"><span>Change</span><span>{vnd((receipt.bill.given ?? 0) - receipt.t.total)}</span></Flex>}
<Typography.Text type="secondary" style={{ textAlign: "center", marginTop: 8 }}>Thanks for stopping by — see you soon!</Typography.Text>
</Flex>
)}
</Modal>
</PageContainer>
);
}
Build a point-of-sale screen for a café. Left: an item grid split into category tabs (Coffee, Tea, Cakes, Toppings) with a search across all categories; each item shows its name, price and size-L price if any; sold-out items are dimmed, labelled "Sold out" and cannot be clicked. Right: the open order — each line has −/+ buttons (reaching 0 removes the line), choosing size M/L changes the price, quick notes such as "less ice", "less sugar"…; choose "Dine in" (with a table number) or "Take away"; a discount code field shows an error when the code is wrong or the order is below its minimum; show subtotal, discount, 8% VAT and total, money formatted for the app's locale. Allow several orders at once as tabs, a "Hold" button to park the current order and start a new one, and cancelling an order with items asks for confirmation. Three payment methods: Cash (enter the amount given, quick buttons "Exact" / 100k / 200k / 500k, compute change, refuse when short), Bank transfer (a QR code with the amount, the transfer note holds the order code and account number), Card (prompt to use the card terminal). "Pay" closes the order and opens the receipt in a Modal with "Print receipt" and "New order" buttons. Data comes from the app's API through useApiClient(): items and stock from api.products.list(), discount check with api.discounts.check(), order creation with api.orders.create() — the server recomputes the amounts and never trusts the browser's totals.
Receivables
Ageing buckets; payments go to the earliest due invoice first.
// Accounts receivable: KPI cards + a clickable aging bar that filters, a customer ProTable with balance vs credit limit bars, an open-invoices Drawer with payment recording (oldest invoices first) and payment reminders.
// In a real app: api.receivables.summary() for KPIs and aging, api.customers.list({ bucket, q, staff }), api.invoices.list({ customerId, open: true }), api.payments.create(...) returns the allocation, api.reminders.send(...).
import { useMemo, useRef, useState } from "react";
import { ModalForm, PageContainer, ProCard, ProFormDatePicker, ProFormDependency, ProFormMoney, ProFormSelect, ProFormText, ProTable, StatisticCard, type ProColumns, type ProFormInstance } from "@ant-design/pro-components";
import { Alert, App, Button, Col, Descriptions, Drawer, Flex, Grid, Modal, Progress, Row, Select, Space, Table, Tag, Typography, theme } from "antd";
import { DollarOutlined, MailOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
const TODAY = dayjs("2026-11-13");
const fmt = new Intl.NumberFormat("en-US");
const vnd = (n: number) => `$${fmt.format(Math.round(n))}`;
const day = (d: string) => dayjs(d).format("MMM D, YYYY");
const lateDays = (due: string) => TODAY.diff(dayjs(due), "day");
type Bucket = "current" | "d30" | "d60" | "d90" | "d90p";
const BUCKETS: { key: Bucket; label: string; tone: "green6" | "gold6" | "orange6" | "volcano6" | "red7" }[] = [
{ key: "current", label: "Not yet due", tone: "green6" },
{ key: "d30", label: "1–30 days", tone: "gold6" },
{ key: "d60", label: "31–60 days", tone: "orange6" },
{ key: "d90", label: "61–90 days", tone: "volcano6" },
{ key: "d90p", label: "Over 90 days", tone: "red7" },
];
const bucketOf = (due: string): Bucket => {
const d = lateDays(due);
return d <= 0 ? "current" : d <= 30 ? "d30" : d <= 60 ? "d60" : d <= 90 ? "d90" : "d90p";
};
type Customer = { id: string; name: string; limit: number; staff: string; contact: string; email: string };
type Invoice = { no: string; customerId: string; date: string; due: string; amount: number; paid: number };
type Payment = { customerId: string; date: string; amount: number; method: string };
type Row = Customer & { balance: number; overdue: number; maxLate: number; buckets: Set<Bucket> };
const CUSTOMERS: Customer[] = [
{ id: "C001", name: "Brightway Trading Co.", limit: 40_000, staff: "Ryan Cooper", contact: "Ms. Karen Wright (accounting)", email: "ap@brightwaytrading.com" },
{ id: "C002", name: "Golden Gate Distribution Inc.", limit: 25_000, staff: "Megan Price", contact: "Mr. Steven Ortiz", email: "payables@goldengatedist.com" },
{ id: "C003", name: "Corner Market Grocery", limit: 10_000, staff: "Ben Foster", contact: "Ms. Linda Nguyen", email: "cornermarket.grocery@gmail.com" },
{ id: "C004", name: "Harbor Pharmaceuticals LLC", limit: 30_000, staff: "Megan Price", contact: "Mr. Paul Jensen (controller)", email: "controller@harborpharma.com" },
{ id: "C005", name: "Sunrise Farmers Co-op", limit: 7_500, staff: "Ben Foster", contact: "Mr. Walter Hughes", email: "sunrisecoop@gmail.com" },
{ id: "C006", name: "Golden Lotus Restaurant Group", limit: 15_000, staff: "Ryan Cooper", contact: "Ms. Grace Lee", email: "accounting@goldenlotusgroup.com" },
{ id: "C007", name: "Main Street General Store", limit: 5_000, staff: "Ben Foster", contact: "Mr. Frank Russo", email: "mainstreet.store@gmail.com" },
{ id: "C008", name: "Driftwood Coffee Co.", limit: 20_000, staff: "Ryan Cooper", contact: "Ms. Amanda Clark", email: "finance@driftwoodcoffee.com" },
{ id: "C009", name: "Hearth & Table Catering", limit: 12_500, staff: "Megan Price", contact: "Mr. Eric Johnson", email: "billing@hearthandtable.com" },
{ id: "C010", name: "Haley's Wholesale", limit: 4_000, staff: "Ben Foster", contact: "Ms. Haley Adams", email: "haleys.wholesale@gmail.com" },
];
const inv = (customerId: string, no: string, date: string, due: string, amount: number, paid = 0): Invoice => ({ customerId, no, date, due, amount, paid });
const INVOICES: Invoice[] = [
inv("C001", "0001845", "2026-08-05", "2026-09-04", 6_425), inv("C001", "0002011", "2026-09-20", "2026-10-20", 10_770, 2_500),
inv("C001", "0002210", "2026-10-28", "2026-11-27", 9_338), inv("C001", "0002305", "2026-11-08", "2026-12-08", 7_115),
inv("C002", "0001702", "2026-06-18", "2026-07-18", 4_810, 1_500), inv("C002", "0001930", "2026-08-30", "2026-09-29", 7_700),
inv("C002", "0002150", "2026-10-15", "2026-11-14", 10_640),
inv("C003", "0002188", "2026-10-22", "2026-11-06", 2_430), inv("C003", "0002260", "2026-11-03", "2026-11-18", 1_895),
inv("C004", "0001655", "2026-06-02", "2026-07-17", 9_200), inv("C004", "0001790", "2026-07-10", "2026-08-24", 11_325, 5_000),
inv("C004", "0002090", "2026-10-05", "2026-11-19", 10_265), inv("C004", "0002255", "2026-11-02", "2026-12-17", 3_700),
inv("C005", "0002230", "2026-10-30", "2026-11-29", 3_210),
inv("C006", "0001988", "2026-09-08", "2026-10-08", 4_420), inv("C006", "0002101", "2026-10-08", "2026-11-07", 4_608),
inv("C006", "0002280", "2026-11-06", "2026-12-06", 5_085),
inv("C007", "0002199", "2026-10-24", "2026-11-08", 1_190, 500), inv("C007", "0002290", "2026-11-07", "2026-11-17", 922),
inv("C008", "0002040", "2026-09-25", "2026-10-25", 6_630), inv("C008", "0002242", "2026-11-01", "2026-12-01", 7_395),
inv("C009", "0001610", "2026-05-20", "2026-06-19", 2_865, 1_000),
inv("C010", "0002120", "2026-10-10", "2026-10-17", 1_560), inv("C010", "0002300", "2026-11-08", "2026-11-15", 1_345),
];
const PAYMENTS: Payment[] = [
{ customerId: "C001", date: "2026-11-05", amount: 2_500, method: "Bank transfer" },
{ customerId: "C004", date: "2026-11-03", amount: 5_000, method: "Bank transfer" },
{ customerId: "C007", date: "2026-11-10", amount: 500, method: "Cash" },
{ customerId: "C008", date: "2026-11-02", amount: 14_230, method: "Bank transfer" },
];
const METHODS = ["Bank transfer", "Cash", "Offset against payables"];
const owed = (i: Invoice) => i.amount - i.paid;
/** Oldest due date first; returns what each open invoice receives and what is left over (credit). */
function allocate(open: Invoice[], amount: number) {
let left = amount;
const lines = [...open].sort((a, b) => a.due.localeCompare(b.due)).map((i) => {
const applied = Math.min(owed(i), Math.max(left, 0));
left -= applied;
return { ...i, applied, after: owed(i) - applied };
});
return { lines: lines.filter((l) => l.applied > 0), credit: Math.max(left, 0) };
}
export default function Page() {
const { message } = App.useApp();
const { token } = theme.useToken();
const md = Grid.useBreakpoint().md;
const formRef = useRef<ProFormInstance>(undefined);
const [invoices, setInvoices] = useState(INVOICES);
const [payments, setPayments] = useState(PAYMENTS);
const [bucket, setBucket] = useState<Bucket | null>(null);
const [q, setQ] = useState("");
const [staff, setStaff] = useState<string>();
const [openId, setOpenId] = useState<string | null>(null);
const [remindId, setRemindId] = useState<string | null>(null);
const [reminded, setReminded] = useState<Record<string, string>>({ C009: "2026-11-02" });
const open = useMemo(() => invoices.filter((i) => owed(i) > 0), [invoices]);
const rows: Row[] = useMemo(() => CUSTOMERS.map((c) => {
const mine = open.filter((i) => i.customerId === c.id);
const late = mine.filter((i) => lateDays(i.due) > 0);
return { ...c, balance: mine.reduce((s, i) => s + owed(i), 0), overdue: late.reduce((s, i) => s + owed(i), 0),
maxLate: Math.max(0, ...late.map((i) => lateDays(i.due))), buckets: new Set(mine.map((i) => bucketOf(i.due))) };
}), [open]);
const aging = useMemo(() => BUCKETS.map((b) => ({ ...b, amount: open.filter((i) => bucketOf(i.due) === b.key).reduce((s, i) => s + owed(i), 0) })), [open]);
const total = aging.reduce((s, b) => s + b.amount, 0);
const overdue = total - aging[0].amount;
const soon = open.filter((i) => { const d = lateDays(i.due); return d <= 0 && d >= -7; });
const monthPaid = payments.filter((p) => dayjs(p.date).isSame(TODAY, "month"));
const shown = rows.filter((r) => r.balance > 0 && (!bucket || r.buckets.has(bucket)) && (!staff || r.staff === staff)
&& (!q || `${r.id} ${r.name}`.toLowerCase().includes(q.toLowerCase())));
const cust = rows.find((r) => r.id === openId);
const custOpen = open.filter((i) => i.customerId === openId).sort((a, b) => a.due.localeCompare(b.due));
const remind = rows.find((r) => r.id === remindId);
const remindLate = open.filter((i) => i.customerId === remindId && lateDays(i.due) > 0);
const lateTag = (d: number) => d <= 0 ? <Typography.Text type="secondary">On time</Typography.Text>
: <Tag color={d > 90 ? "red" : d > 60 ? "volcano" : d > 30 ? "orange" : "gold"}>{d} days</Tag>;
const columns: ProColumns<Row>[] = [
{ title: "ID", dataIndex: "id", width: 80 },
{ title: "Customer", dataIndex: "name", ellipsis: true, render: (_, r) => (
<Space orientation="vertical" size={0}>
<Typography.Link strong onClick={() => setOpenId(r.id)}>{r.name}</Typography.Link>
{reminded[r.id] && <Typography.Text type="secondary" style={{ fontSize: 12 }}><MailOutlined /> Reminder sent {day(reminded[r.id])}</Typography.Text>}
</Space>) },
{ title: "Credit limit", dataIndex: "limit", align: "right", width: 130, render: (_, r) => vnd(r.limit) },
{ title: "Balance", dataIndex: "balance", width: 190, sorter: (a, b) => a.balance - b.balance, render: (_, r) => {
const pct = Math.round((r.balance / r.limit) * 100);
return (<div><Flex justify="space-between"><b>{vnd(r.balance)}</b><Typography.Text type={pct > 90 ? "danger" : "secondary"}>{pct}%</Typography.Text></Flex>
<Progress percent={Math.min(pct, 100)} showInfo={false} size="small" status={pct > 90 ? "exception" : "normal"} /></div>);
} },
{ title: "Overdue", dataIndex: "overdue", align: "right", width: 140, defaultSortOrder: "descend", sorter: (a, b) => a.overdue - b.overdue,
render: (_, r) => r.overdue ? <Typography.Text type="danger">{vnd(r.overdue)}</Typography.Text> : "—" },
{ title: "Oldest overdue", dataIndex: "maxLate", width: 130, sorter: (a, b) => a.maxLate - b.maxLate, render: (_, r) => lateTag(r.maxLate) },
{ title: "Account rep", dataIndex: "staff", width: 140 },
{ title: "", valueType: "option", width: 70, render: (_, r) => [<a key="v" onClick={() => setOpenId(r.id)}>Details</a>] },
];
const record = async (v: { amount: number; date: string; method: string; ref?: string }) => {
const { lines, credit } = allocate(custOpen, v.amount);
const by = new Map(lines.map((l) => [l.no, l.applied]));
setInvoices((all) => all.map((i) => (by.has(i.no) ? { ...i, paid: i.paid + (by.get(i.no) ?? 0) } : i)));
setPayments((p) => [...p, { customerId: openId!, date: v.date, amount: v.amount, method: v.method }]);
const closed = lines.filter((l) => l.after === 0).length;
message.success(`Recorded ${vnd(v.amount)} · ${closed} invoices paid in full${credit ? ` · ${vnd(credit)} credited` : ""}`);
return true;
};
return (
<PageContainer title="Accounts receivable" subTitle={`As of ${TODAY.format("MMM D, YYYY")}`}
extra={<Select allowClear placeholder="Account rep" style={{ width: 200 }} value={staff} onChange={setStaff}
options={[...new Set(CUSTOMERS.map((c) => c.staff))].map((s) => ({ value: s, label: s }))} />}>
<Flex vertical gap={16}>
<StatisticCard.Group direction={md ? "row" : "column"}>
<StatisticCard statistic={{ title: "Total receivable", value: vnd(total), description: <StatisticCard.Statistic title="Customers with a balance" value={rows.filter((r) => r.balance).length} /> }} />
<StatisticCard.Divider type={md ? "vertical" : "horizontal"} />
<StatisticCard statistic={{ title: "Overdue", value: vnd(overdue), styles: { content: { color: token.colorError } }, description: <StatisticCard.Statistic title="Share" value={`${((overdue / total) * 100).toFixed(1)}%`} /> }} />
<StatisticCard.Divider type={md ? "vertical" : "horizontal"} />
<StatisticCard statistic={{ title: "Due in the next 7 days", value: vnd(soon.reduce((s, i) => s + owed(i), 0)), description: <StatisticCard.Statistic title="Invoices" value={soon.length} /> }} />
<StatisticCard.Divider type={md ? "vertical" : "horizontal"} />
<StatisticCard statistic={{ title: "Collected this month", value: vnd(monthPaid.reduce((s, p) => s + p.amount, 0)), description: <StatisticCard.Statistic title="Payments" value={monthPaid.length} /> }} />
</StatisticCard.Group>
<ProCard title="Aging" subTitle="click a bucket to filter the list" headerBordered
extra={bucket && <a onClick={() => setBucket(null)}>Clear filter</a>}>
<Flex style={{ height: 14, borderRadius: token.borderRadiusSM, overflow: "hidden", marginBottom: 16 }}>
{aging.map((b) => b.amount > 0 && (
<div key={b.key} title={b.label} onClick={() => setBucket(b.key)}
style={{ width: `${(b.amount / total) * 100}%`, background: token[b.tone], cursor: "pointer", opacity: !bucket || bucket === b.key ? 1 : 0.3 }} />
))}
</Flex>
<Row gutter={[12, 12]}>
{aging.map((b) => (
<Col key={b.key} xs={12} md={8} lg={{ flex: "20%" }}>
<div role="button" tabIndex={0} onClick={() => setBucket(bucket === b.key ? null : b.key)}
onKeyDown={(e) => e.key === "Enter" && setBucket(bucket === b.key ? null : b.key)}
style={{ padding: "8px 12px", cursor: "pointer", borderRadius: token.borderRadius,
border: `1px solid ${bucket === b.key ? token.colorPrimary : token.colorBorderSecondary}`,
background: bucket === b.key ? token.colorPrimaryBg : undefined }}>
<Space size={6}><span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 4, background: token[b.tone] }} />
<Typography.Text type="secondary">{b.label}</Typography.Text></Space>
<div><b>{vnd(b.amount)}</b></div>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>{total ? ((b.amount / total) * 100).toFixed(1) : 0}%</Typography.Text>
</div>
</Col>
))}
</Row>
</ProCard>
<ProTable<Row>
rowKey="id" cardBordered columns={columns} dataSource={shown} search={false}
headerTitle={bucket ? `Customers with balances ${BUCKETS.find((b) => b.key === bucket)!.label.toLowerCase()}` : "Customers with a balance"}
options={{ density: true, setting: false, reload: false }}
toolbar={{ search: { placeholder: "Search ID or company name", allowClear: true, onSearch: setQ, style: { width: 260 } } }}
pagination={{ pageSize: 10, showTotal: (t) => `${t} customers` }}
summary={(data) => (
<Table.Summary.Row>
<Table.Summary.Cell index={0} colSpan={2}><b>Total · {data.length} customers</b></Table.Summary.Cell>
<Table.Summary.Cell index={2} align="right">{vnd(data.reduce((s, r) => s + r.limit, 0))}</Table.Summary.Cell>
<Table.Summary.Cell index={3}><b>{vnd(data.reduce((s, r) => s + r.balance, 0))}</b></Table.Summary.Cell>
<Table.Summary.Cell index={4} align="right"><Typography.Text type="danger" strong>{vnd(data.reduce((s, r) => s + r.overdue, 0))}</Typography.Text></Table.Summary.Cell>
<Table.Summary.Cell index={5} colSpan={3} />
</Table.Summary.Row>
)}
/>
</Flex>
<Drawer open={!!cust} onClose={() => setOpenId(null)} size={760} title={cust && `${cust.id} · ${cust.name}`} destroyOnHidden
extra={cust && <Space>
<Button icon={<MailOutlined />} disabled={!cust.overdue} onClick={() => setRemindId(cust.id)}>Send reminder</Button>
<ModalForm<{ amount: number; date: string; method: string; ref?: string }> title="Record payment" width={620} formRef={formRef}
trigger={<Button type="primary" icon={<DollarOutlined />}>Record payment</Button>}
initialValues={{ date: TODAY, method: "Bank transfer" }} modalProps={{ destroyOnHidden: true, okText: "Save receipt" }}
onFinish={record}>
<ProFormMoney name="amount" label="Amount received" locale="en-US" fieldProps={{ precision: 2 }} rules={[{ required: true, message: "Enter an amount" }]}
extra={<a onClick={() => formRef.current?.setFieldsValue({ amount: cust.balance })}>Collect the full balance ({vnd(cust.balance)})</a>} />
<Flex gap={16}>
<ProFormDatePicker name="date" label="Payment date" width="sm" fieldProps={{ format: "MMM D, YYYY" }} transform={(v: string) => ({ date: dayjs(v).format("YYYY-MM-DD") })} />
<ProFormSelect name="method" label="Method" width="sm" options={METHODS} />
<ProFormText name="ref" label="Reference" width="sm" placeholder="e.g. ACH 1125" />
</Flex>
<ProFormDependency name={["amount"]}>
{({ amount }) => {
if (!amount) return <Typography.Text type="secondary">Enter an amount to preview the allocation — payments go to the invoice with the earliest due date first.</Typography.Text>;
const { lines, credit } = allocate(custOpen, amount);
return (<Flex vertical gap={8}>
<Typography.Text strong>Allocation preview</Typography.Text>
<Table size="small" rowKey="no" pagination={false} dataSource={lines} columns={[
{ title: "Invoice", dataIndex: "no" }, { title: "Due", dataIndex: "due", render: day },
{ title: "Open", align: "right", render: (_, l) => vnd(owed(l)) },
{ title: "Applied", dataIndex: "applied", align: "right", render: (v: number) => <b>{vnd(v)}</b> },
{ title: "Remaining", dataIndex: "after", align: "right", render: (v: number) => v ? vnd(v) : <Tag color="success">Paid in full</Tag> },
]} />
{credit > 0 && <Alert type="warning" showIcon title={`That's ${vnd(credit)} more than the balance — the excess is credited to the customer and applied to future invoices.`} />}
</Flex>);
}}
</ProFormDependency>
</ModalForm>
</Space>}>
{cust && <Flex vertical gap={16}>
<Descriptions size="small" column={2} items={[
{ label: "Balance", children: <b>{vnd(cust.balance)}</b> }, { label: "Credit limit", children: `${vnd(cust.limit)} (${Math.round((cust.balance / cust.limit) * 100)}% used)` },
{ label: "Overdue", children: <Typography.Text type="danger">{vnd(cust.overdue)}</Typography.Text> }, { label: "Account rep", children: cust.staff },
{ label: "Contact", children: cust.contact }, { label: "Email", children: cust.email },
]} />
<Table<Invoice> size="small" rowKey="no" pagination={false} dataSource={custOpen}
columns={[
{ title: "Invoice no.", dataIndex: "no" }, { title: "Date", dataIndex: "date", render: day },
{ title: "Due date", dataIndex: "due", render: (d: string) => <Space size={4}>{day(d)}{lateTag(lateDays(d))}</Space> },
{ title: "Amount", dataIndex: "amount", align: "right", render: vnd },
{ title: "Open", align: "right", render: (_, i) => <b>{vnd(owed(i))}</b> },
]}
summary={(data) => <Table.Summary.Row><Table.Summary.Cell index={0} colSpan={4}>Total · {data.length} open invoices</Table.Summary.Cell>
<Table.Summary.Cell index={4} align="right"><b>{vnd(data.reduce((s, i) => s + owed(i), 0))}</b></Table.Summary.Cell></Table.Summary.Row>} />
</Flex>}
</Drawer>
<Modal open={!!remind} title="Reminder email preview" okText="Send email" cancelText="Cancel" width={620} onCancel={() => setRemindId(null)}
onOk={() => { setReminded((m) => ({ ...m, [remindId!]: TODAY.format("YYYY-MM-DD") })); message.success(`Reminder sent to ${remind?.email}`); setRemindId(null); }}>
{remind && <Flex vertical gap={8}>
<Typography.Text><Typography.Text type="secondary">To:</Typography.Text> {remind.email}</Typography.Text>
<Typography.Text><Typography.Text type="secondary">Subject:</Typography.Text> [Summit Distribution] Overdue balance — payment request — {remind.id}</Typography.Text>
<ProCard bordered style={{ background: token.colorFillQuaternary }}>
<Typography.Paragraph>Dear {remind.contact} — {remind.name},</Typography.Paragraph>
<Typography.Paragraph>As of {TODAY.format("MMM D, YYYY")}, your account has {remindLate.length} overdue invoices totaling <b>{vnd(remind.overdue)}</b>:</Typography.Paragraph>
<ul>{remindLate.map((i) => <li key={i.no}>Invoice {i.no}, due {day(i.due)} ({lateDays(i.due)} days overdue): {vnd(owed(i))}</li>)}</ul>
<Typography.Paragraph>Please pay by bank transfer to account 4410 0012 3456, with the reference “{remind.id} payment”. If you have already paid, please disregard this email.</Typography.Paragraph>
<Typography.Paragraph style={{ marginBottom: 0 }}>Kind regards,<br />{remind.staff} — Accounts Receivable, Summit Distribution Co.</Typography.Paragraph>
</ProCard>
</Flex>}
</Modal>
</PageContainer>
);
}
Build an accounts-receivable screen for a distribution company: at the top, 4 metric cards (total receivable, overdue, due in 7 days, collected this month) and an ageing bar in 5 buckets (not due, 1–30, 31–60, 61–90, over 90 days) — clicking a bucket filters the customer list. Below, a ProTable of customers with a balance (customer code, company name, credit limit, balance with a progress bar against the limit that turns red over 90%, overdue amount, longest days overdue, account manager), with a search, an account-manager filter and a total row. Clicking a customer opens a Drawer listing their open invoices (number, date, due date, outstanding) with a "Record payment" button (amount, date, method, reference). Payments are allocated to the earliest-due invoices first, and the form shows the planned allocation before saving, including any overpayment as a credit. Add a "Send reminder" button that previews an email listing the overdue invoices. Load data from the app's API through useApiClient(): the server computes ageing, payment allocation and totals. After recording a payment, reload so the cards, the ageing bar and the table update.
Workflow designer
Drag steps and approval branches with React Flow.
// Approval workflow designer: @xyflow/react drag-and-drop nodes, connect edges, add steps, save as JSON (CSS ships in the vendor bundle — don't import .css).
import { useCallback, useState } from "react";
import { PageContainer, ProCard } from "@ant-design/pro-components";
import { App, Button, Flex, Input, Select, Space, Tag, theme } from "antd";
import { PlusOutlined, SaveOutlined } from "@ant-design/icons";
import { ReactFlow, Background, Controls, MiniMap, addEdge, useNodesState, useEdgesState, Handle, Position, type Connection, type Node, type Edge } from "@xyflow/react";
type StepData = { label: string; role: string };
const ROLES = [
{ value: "staff", label: "Employee" },
{ value: "manager", label: "Manager" },
{ value: "accountant", label: "Accountant" },
{ value: "director", label: "Director" },
];
function StepNode({ data }: { data: StepData }) {
const { token } = theme.useToken();
return (
<div style={{ padding: "8px 12px", minWidth: 160, borderRadius: token.borderRadiusLG, background: token.colorBgContainer, border: `1px solid ${token.colorBorder}`, boxShadow: token.boxShadowTertiary }}>
<Handle type="target" position={Position.Top} />
<div style={{ fontWeight: 600, color: token.colorText }}>{data.label}</div>
<Tag color="blue" style={{ marginTop: 4 }}>{ROLES.find((r) => r.value === data.role)?.label ?? data.role}</Tag>
<Handle type="source" position={Position.Bottom} />
</div>
);
}
const nodeTypes = { step: StepNode };
const initialNodes: Node<StepData>[] = [
{ id: "1", type: "step", position: { x: 120, y: 0 }, data: { label: "Submit request", role: "staff" } },
{ id: "2", type: "step", position: { x: 120, y: 120 }, data: { label: "Manager approval", role: "manager" } },
{ id: "3", type: "step", position: { x: 0, y: 240 }, data: { label: "Accounting review", role: "accountant" } },
{ id: "4", type: "step", position: { x: 260, y: 240 }, data: { label: "Director approval (> $2,000)", role: "director" } },
];
const initialEdges: Edge[] = [
{ id: "e1-2", source: "1", target: "2", animated: true },
{ id: "e2-3", source: "2", target: "3" },
{ id: "e2-4", source: "2", target: "4", label: "> $2,000" },
];
export default function Page() {
const { message } = App.useApp();
const [nodes, setNodes, onNodesChange] = useNodesState<Node<StepData>>(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>(initialEdges);
const [label, setLabel] = useState("");
const [role, setRole] = useState("manager");
const onConnect = useCallback((c: Connection) => setEdges((eds) => addEdge(c, eds)), [setEdges]);
const addStep = () => {
if (!label.trim()) return;
const id = String(Date.now());
setNodes((ns) => [...ns, { id, type: "step", position: { x: 120, y: 360 + ns.length * 10 }, data: { label: label.trim(), role } }]);
setLabel("");
};
return (
<PageContainer
title="Spend request approval flow"
extra={[
<Button key="save" type="primary" icon={<SaveOutlined />} onClick={() => message.success(`Saved ${nodes.length} steps and ${edges.length} links (JSON sent to the API)`)}>
Save workflow
</Button>,
]}
>
<ProCard
title="Diagram"
extra={
<Space.Compact>
<Input placeholder="Step name" value={label} onChange={(e) => setLabel(e.target.value)} onPressEnter={addStep} style={{ width: 200 }} />
<Select value={role} onChange={setRole} options={ROLES} style={{ width: 150 }} />
<Button icon={<PlusOutlined />} onClick={addStep}>
Add step
</Button>
</Space.Compact>
}
>
<Flex style={{ height: 520 }}>
<ReactFlow nodes={nodes} edges={edges} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={onConnect} nodeTypes={nodeTypes} fitView>
<Background />
<MiniMap pannable zoomable />
<Controls />
</ReactFlow>
</Flex>
</ProCard>
</PageContainer>
);
}
Build the "Workflow designer (React Flow)" screen for my app following the Manh UI playbook (framework_docs("pro")): Approval workflow designer: @xyflow/react drag-and-drop nodes, connect edges, add steps, save as JSON (CSS is in the vendor bundle — do not import .css). Data comes from the app's API through useApiClient(); labels and fields follow my spec.AI assistant
Chat panel with suggestions and Markdown answers.
// In-app AI assistant: antd X (Welcome, Prompts, Bubble.List, Sender) + XMarkdown; the answer is a simulated stream (real app: the "ai-assistant" lego block).
import { useState } from "react";
import { PageContainer, ProCard } from "@ant-design/pro-components";
import { Flex } from "antd";
import { RobotOutlined, UserOutlined } from "@ant-design/icons";
import { Bubble, Prompts, Sender, Welcome } from "@ant-design/x";
import XMarkdown from "@ant-design/x-markdown";
type Msg = { key: string; role: "user" | "ai"; content: string; loading?: boolean };
const ANSWER = `There are **3 orders past their delivery date**:
| Order | Customer | Late by |
|---|---|---|
| SO-2026-0141 | Acme Supply Co. | 2 days |
| SO-2026-0150 | Maple Street Cafe | 1 day |
| SO-2026-0152 | Northwind Steel | 1 day |
Suggestion: call **Acme Supply** first — it's the largest order ($4,800).`;
export default function Page() {
const [items, setItems] = useState<Msg[]>([]);
const [text, setText] = useState("");
const [busy, setBusy] = useState(false);
const send = (q: string) => {
if (!q.trim() || busy) return;
const key = "a" + Date.now();
setItems((p) => [...p, { key: "u" + Date.now(), role: "user", content: q }, { key, role: "ai", content: "", loading: true }]);
setText("");
setBusy(true);
// Simulated answer (the real block: agent steps over the WebSocket, see block "ai-assistant").
let i = 0;
const timer = setInterval(() => {
i += 6;
setItems((p) => p.map((m) => (m.key === key ? { ...m, loading: false, content: ANSWER.slice(0, i) } : m)));
if (i >= ANSWER.length) {
clearInterval(timer);
setBusy(false);
}
}, 30);
};
return (
<PageContainer title="Assistant">
<ProCard>
<Flex vertical gap={12} style={{ height: 520 }}>
<div style={{ flex: 1, minHeight: 0, overflow: "auto" }}>
{items.length === 0 ? (
<Flex vertical gap={16}>
<Welcome icon={<RobotOutlined style={{ fontSize: 32 }} />} title="Sales assistant" description="Ask about orders, stock or customers — the assistant looks up real data with the app's own tools." />
<Prompts
items={["Which orders are overdue?", "What's about to run out of stock?", "How are sales this week?"].map((d, i) => ({ key: String(i), description: d }))}
onItemClick={(info) => send(String(info.data.description))}
/>
</Flex>
) : (
<Bubble.List
items={items.map((m) => ({
key: m.key,
role: m.role,
placement: m.role === "user" ? "end" : "start",
avatar: m.role === "user" ? <UserOutlined /> : <RobotOutlined />,
loading: m.loading,
content: m.role === "ai" ? <XMarkdown content={m.content} /> : m.content,
}))}
/>
)}
</div>
<Sender value={text} onChange={setText} loading={busy} onSubmit={send} placeholder="Ask the assistant…" />
</Flex>
</ProCard>
</PageContainer>
);
}
Build the "AI assistant (antd X)" screen for my app following the Manh UI playbook (framework_docs("pro")): In-app AI assistant: antd X (Welcome, Prompts, Bubble.List, Sender) + XMarkdown; the answer is a simulated stream (real apps: the "ai-assistant" lego block). Data comes from the app's API through useApiClient(); labels and fields follow my spec.Next steps
- Pick a component by job — when to use a table, a kanban board, a calendar or a point-of-sale screen.
- Your first app — give the agent a real app with a database and sign-in.