Ví dụ chạy tại chỗ
Mỗi ví dụ là một file app/page.tsx chạy thật trong trình duyệt, dữ liệu giả để sẵn trong file. Tab Code cho xem và sao chép file, tab Prompt cho agent là câu đã giao cho agent để có màn hình đó. Bấm Mở để sửa để sửa thử trong Playground.
App hoàn chỉnh (có database, đăng nhập, quy trình thật) nằm ở trang App mẫu, chạy và sửa được ngay trong trình duyệt. Khung từng màn hình (danh sách, form, dashboard…) ở Mẫu giao diện.
Dashboard điều hành
Chủ chuỗi bán lẻ xem doanh thu, đơn và việc cần xử lý theo kỳ.
// Dashboard của chủ cửa hàng nội thất 3 kênh: chọn kỳ (hôm nay / 7 ngày / tháng / 12 tháng) đổi mọi con số, 4 KPI có so sánh kỳ trước, biểu đồ doanh thu – lợi nhuận, tỷ trọng kênh, sản phẩm bán chạy, việc cần xử lý và tồn kho cảnh báo.
// Trong app thật: api.reports.summary({ period }) trả KPI + chuỗi theo ngày/tháng; api.tasks.counts(), api.inventory.lowStock() thay cho dữ liệu mẫu.
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; // phần doanh thu một ngày thường đạt được trước 14:30
const CHANNELS = [{ label: "Showroom", aov: 9.2e6, margin: 0.41 }, { label: "Website", aov: 4.6e6, margin: 0.35 }, { label: "Dự án B2B", aov: 0, margin: 0.27 }];
const nf = new Intl.NumberFormat("vi-VN");
const vnd = (n: number) => `${nf.format(Math.round(n))} ₫`;
const num = (n: number, d: number) => new Intl.NumberFormat("vi-VN", { maximumFractionDigits: d }).format(n);
const short = (n: number) => (Math.abs(n) >= 1e9 ? `${num(n / 1e9, 2)} tỷ` : `${num(n / 1e6, Math.abs(n) >= 1e8 ? 0 : 1)} tr`);
const pct = (x: number) => `${new Intl.NumberFormat("vi-VN", { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(x * 100)}%`;
const sum = (a: number[]) => a.reduce((s, v) => s + v, 0);
// Dữ liệu mẫu: 731 ngày bán hàng sinh từ một seed cố định (mulberry32) — cùng kết quả mỗi lần 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 / 1e5) * 1e5;
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(48e6 * k * weekend * (0.75 + 0.5 * r())), round(22e6 * k * (0.7 + 0.6 * r())), r() < 0.22 ? round((60 + 220 * r()) * 1e6 * 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)), "hôm qua cùng giờ"]
: p === "7d" ? [between(t.subtract(6, "day"), t), between(t.subtract(13, "day"), t.subtract(7, "day")), "7 ngày trước đó"]
: p === "month" ? [between(t.startOf("month"), t), between(t.subtract(1, "month").startOf("month"), t.subtract(1, "month")), `cùng kỳ tháng ${t.subtract(1, "month").month() + 1}`]
: [between(t.subtract(11, "month").startOf("month"), t), between(t.subtract(23, "month").startOf("month"), t.subtract(12, "month")), "12 tháng trước đó"];
// Cột biểu đồ: theo giờ (hôm nay), theo ngày (7 ngày, tháng này), theo tháng (12 tháng).
const groups = new Map<string, Day[]>();
if (p === "today") HOURS.forEach((h, i) => groups.set(`${h}h`, [scale(cur[0], HOUR_W[i])]));
else cur.forEach((d) => { const key = d.date.format(p === "12m" ? "MM/YY" : "DD/MM"); groups.set(key, [...(groups.get(key) ?? []), d]); });
const buckets = [...groups].map(([label, days]) => ({ label, ...total(days) }));
// Đơn đang xử lý: đơn của kỳ chưa giao xong, chia theo tuổi đơn.
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: "Sofa da Milano 3 chỗ", price: 32.9e6, share: [0.16, 0.08, 0.02] },
{ name: "Bàn ăn gỗ sồi Oslo 6 ghế", price: 18.5e6, share: [0.12, 0.07, 0.03] },
{ name: "Giường óc chó Kyoto 1m8", price: 24.9e6, share: [0.11, 0.06, 0.02] },
{ name: "Ghế công thái học ErgoPro", price: 4.29e6, share: [0.03, 0.12, 0.1] },
{ name: "Bàn nâng hạ Flex 1m4", price: 8.9e6, share: [0.03, 0.09, 0.14] },
{ name: "Ghế văn phòng Mesh", price: 2.19e6, share: [0.01, 0.04, 0.22] },
{ name: "Tủ áo Nordic 4 cánh", price: 15.9e6, 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: "Sofa da Milano 3 chỗ · xám", warehouse: "Showroom Q7", onHand: 0, min: 3, incoming: 4, eta: "25/11", perDay: 0.4 },
{ sku: "GVP-MESH-BK", name: "Ghế văn phòng Mesh · đen", warehouse: "Kho Bình Dương", onHand: 18, min: 60, incoming: 120, eta: "20/11", perDay: 7.5 },
{ sku: "BNH-FLX14-WH", name: "Bàn nâng hạ Flex 1m4 · trắng", warehouse: "Kho Bình Dương", onHand: 6, min: 15, incoming: 0, perDay: 1.6 },
{ sku: "GCT-ERGO-BK", name: "Ghế công thái học ErgoPro", warehouse: "Kho Bình Dương", onHand: 9, min: 20, incoming: 40, eta: "18/11", perDay: 2.1 },
{ sku: "KTV-WAL20", name: "Kệ tivi Walnut 2m", warehouse: "Showroom Q7", onHand: 4, min: 5, incoming: 0, perDay: 0.3 },
];
const DEBTS = [186_000_000, 142_500_000, 84_000_000]; // 3 khách B2B quá hạn thanh toán
const STATUS_LABELS = ["Chờ xác nhận", "Đang chuẩn bị hàng", "Đang giao & lắp đặt"];
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" ? "giờ" : period === "12m" ? "tháng" : "ngày";
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">so với {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: "Đơn chờ xác nhận quá 2 giờ", note: "Lâu nhất 5 giờ 10 phút · 3 đơn website", count: 4, color: token.colorWarning },
{ icon: <CarOutlined />, title: "Đơn giao trễ hẹn", note: "2 đơn showroom · 1 dự án B2B", count: 3, color: token.colorError },
{ icon: <InboxOutlined />, title: "Hàng dưới mức tồn tối thiểu", note: `${STOCK.filter((s) => s.onHand === 0).length} mã đã hết hàng`, count: STOCK.length, color: token.colorWarning },
{ icon: <DollarOutlined />, title: "Công nợ B2B quá hạn", note: `${vnd(sum(DEBTS))} · quá hạn lâu nhất 34 ngày`, count: DEBTS.length, color: token.colorError },
];
const stockCols: TableProps<Stock>["columns"] = [
{ title: "Sản phẩm", 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: "Tình trạng", key: "st", width: 140, render: (_, r) => <Badge status={r.onHand === 0 ? "error" : "warning"} text={r.onHand === 0 ? "Hết hàng" : "Dưới tối thiểu"} /> },
{ title: "Tồn / tối thiểu", key: "qty", align: "right", width: 130, render: (_, r) => <span><b>{r.onHand}</b> / {r.min}</span> },
{ title: "Đủ bán", key: "days", align: "right", width: 100, render: (_, r) => (r.onHand === 0 ? "—" : `${Math.floor(r.onHand / r.perDay)} ngày`) },
{ title: "Hàng đang về", key: "in", width: 150, render: (_, r) => (r.incoming ? `${r.incoming} cái · ngày ${r.eta}` : <Typography.Text type="danger">Chưa đặt hàng</Typography.Text>) },
{ title: "", key: "act", width: 130, align: "right", render: (_, r) => <Button size="small">{r.incoming ? "Xem đơn nhập" : "Tạo đơn nhập"}</Button> },
];
return (
<PageContainer
title="Chào buổi chiều, anh Tuấn"
subTitle={`Nội thất Mộc An · số liệu tính đến ${NOW.format("HH:mm")}, thứ Sáu ${NOW.format("DD/MM/YYYY")}`}
extra={[
<Segmented<Period> key="p" value={period} onChange={setPeriod}
options={[{ label: "Hôm nay", value: "today" }, { label: "7 ngày", value: "7d" }, { label: "Tháng này", value: "month" }, { label: "12 tháng", value: "12m" }]} />,
<Button key="x" icon={<DownloadOutlined />}>Xuất báo cáo</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: "Doanh thu", 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">Lợi nhuận gộp {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: "Đơn mới", value: orders, formatter: () => nf.format(orders), description: delta(orders / prevOrders - 1, pct(Math.abs(orders / prevOrders - 1))) }}
footer={<Typography.Text type="secondary">Giá trị trung bình {short(rev / Math.max(1, orders))} ₫/đơn</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: "Biên lợi nhuận gộp", value: margin, formatter: () => pct(margin), description: delta(margin - prevMargin, `${num(Math.abs(margin - prevMargin) * 100, 1)} điểm %`) }}
footer={<Typography.Text type="secondary">B2B thấp nhất: {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: "Đơn đang xử lý", value: open, formatter: () => nf.format(open), description: <Typography.Text type="secondary">trong {nf.format(orders)} đơn của kỳ</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="Doanh thu và lợi nhuận gộp" subTitle={`theo ${unit}`} headerBordered style={{ height: "100%" }}>
<Column height={300} data={d.buckets.flatMap((b) => [{ label: b.label, kind: "Doanh thu", value: sum(b.rev) }, { label: b.label, kind: "Lợi nhuận gộp", 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="Việc cần xử lý" subTitle="cập nhật lúc 14:30" 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="Doanh thu theo kênh" subTitle={`tổng ${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])} đơn</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="Sản phẩm bán chạy" subTitle="theo doanh thu" extra={<a>Xem báo cáo sản phẩm</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)} sp</Typography.Text>
</Flex>
</Flex>
</Flex>
))}
</Flex>
</ProCard>
</Col>
</Row>
<ProCard title="Tồn kho cảnh báo" subTitle={`${STOCK.length} mã dưới mức tồn tối thiểu`} extra={<a>Mở kho hàng</a>} headerBordered bodyStyle={{ paddingTop: 0 }}>
<Table<Stock> rowKey="sku" size="small" columns={stockCols} dataSource={STOCK} pagination={false} scroll={{ x: 760 }} />
</ProCard>
</Flex>
</PageContainer>
);
}
Làm màn hình dashboard điều hành hằng ngày cho chủ chuỗi nội thất bán qua 3 kênh (showroom, website, dự án B2B). Đầu trang có lời chào kèm thời điểm số liệu và bộ chọn kỳ Hôm nay / 7 ngày / Tháng này / 12 tháng; đổi kỳ thì mọi con số đổi theo và so với kỳ trước tương ứng (hôm qua cùng giờ, cùng kỳ tháng trước…). Hàng trên cùng là 4 thẻ KPI có sparkline: doanh thu, đơn mới, biên lợi nhuận gộp (chênh lệch tính bằng điểm %), và đơn đang xử lý với thanh xếp chồng theo trạng thái. Tiếp theo là biểu đồ cột doanh thu và lợi nhuận gộp theo giờ/ngày/tháng, cạnh đó là khung "Việc cần xử lý": mỗi dòng bấm được, có số đếm, gồm đơn chờ xác nhận quá 2 giờ, đơn giao trễ hẹn, hàng dưới mức tồn tối thiểu và công nợ B2B quá hạn. Thêm biểu đồ donut tỷ trọng doanh thu theo kênh (tổng các kênh phải khớp tổng doanh thu), danh sách "Sản phẩm bán chạy" có thanh tiến độ, và bảng tồn kho cảnh báo kèm nút tạo đơn nhập. Tiền định dạng vi-VN, dùng "tr"/"tỷ" trên biểu đồ. Mọi số liệu lấy từ API của app qua useApiClient() (báo cáo tổng hợp theo kỳ, số việc cần xử lý, danh sách hàng sắp hết), không viết cứng dữ liệu.
Bảng theo dõi đơn hàng
Kanban kéo thả, chỉ cho chuyển sang bước kế tiếp; huỷ đơn phải ghi lý do.
// Bảng theo dõi đơn hàng: kéo thẻ qua từng bước (không nhảy cóc), huỷ đơn phải chọn lý do, chỉ số đầu trang, tìm kiếm, lọc kênh và Drawer chi tiết đơn.
// Trong app thật: api.orders.list({ q, channel }) đổ dữ liệu; kéo thẻ / nút trong Drawer gọi api.orders.updateStatus(id, { status, reason }) rồi tải lại.
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: "Mới", badge: "default", dot: "gray" },
confirmed: { title: "Đã xác nhận", badge: "processing", dot: "blue" },
shipping: { title: "Đang giao", badge: "warning", dot: "orange" },
done: { title: "Hoàn tất", badge: "success", dot: "green" },
cancelled: { title: "Đã huỷ", badge: "error", dot: "red" },
};
const CHANNEL_COLOR: Record<Channel, string> = { Showroom: "gold", Website: "blue", B2B: "purple" };
const REASONS = ["Khách đổi ý", "Hết hàng, không kịp nhập", "Không liên lạc được khách", "Khác"];
const vnd = (n: number) => n.toLocaleString("vi-VN") + " đ";
const million = (n: number) => (n / 1e6).toLocaleString("vi-VN", { maximumFractionDigits: 1 }) + " tr";
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: `MA2611-${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" ? "Khách đổi ý" : undefined })),
};
}
const SEED: Order[] = [
mk(43, "Nguyễn Văn Hùng", "0903 412 776", "12 Nguyễn Trãi, Q.1, TP.HCM", "Showroom", "Hà Linh", 0, 5, "new", [{ name: "Sofa góc chữ L vải bố", qty: 1, price: 18_900_000 }, { name: "Gối tựa sofa 45×45", qty: 4, price: 290_000 }]),
mk(44, "Cty TNHH Nội thất Hoà Bình", "028 3822 5510", "KCN Tân Bình, TP.HCM", "B2B", "Quang Thắng", 0, 14, "new", [{ name: "Ghế làm việc công thái học", qty: 20, price: 3_450_000 }]),
mk(45, "Trần Thị Mai", "0938 220 145", "88 Lê Văn Sỹ, Q.3, TP.HCM", "Website", "Minh Anh", 0, 7, "new", [{ name: "Bàn trang điểm gỗ sồi", qty: 1, price: 4_200_000 }]),
mk(42, "Trịnh Văn Long", "0912 663 018", "5 Hoàng Diệu, Q.4, TP.HCM", "Showroom", "Tuấn Dũng", 1, 4, "new", [{ name: "Kệ sách 5 tầng", qty: 2, price: 1_850_000 }]),
mk(41, "Lê Hoàng Phúc", "0977 504 331", "Vinhomes Grand Park, TP. Thủ Đức", "Website", "Minh Anh", 1, 3, "confirmed", [{ name: "Giường gỗ óc chó 1m8", qty: 1, price: 24_500_000 }, { name: "Nệm cao su 1m8", qty: 1, price: 9_800_000 }]),
mk(40, "Khách sạn Biển Xanh", "0258 352 1188", "Trần Phú, Nha Trang", "B2B", "Quang Thắng", 2, 6, "confirmed", [{ name: "Tủ đầu giường", qty: 30, price: 1_150_000 }, { name: "Đèn ngủ gốm", qty: 30, price: 450_000 }]),
mk(38, "Phạm Ngọc Ánh", "0908 117 992", "21 Phan Xích Long, Phú Nhuận", "Showroom", "Hà Linh", 4, -1, "confirmed", [{ name: "Tủ giày 2 cánh", qty: 1, price: 3_900_000 }]),
mk(37, "Võ Thanh Tâm", "0965 880 213", "102 Quang Trung, Gò Vấp", "Website", "Tuấn Dũng", 3, 1, "shipping", [{ name: "Kệ tivi gỗ tràm 1m8", qty: 1, price: 5_600_000 }]),
mk(36, "Đặng Thu Trang", "0933 456 120", "Sunrise City, Q.7, TP.HCM", "Showroom", "Tuấn Dũng", 5, -2, "shipping", [{ name: "Bàn ăn gỗ sồi 6 ghế", qty: 1, price: 15_900_000 }]),
mk(35, "Café Gỗ Mộc", "0283 910 4477", "45 Võ Văn Tần, Q.3, TP.HCM", "B2B", "Quang Thắng", 6, 0, "shipping", [{ name: "Bàn cà phê tròn", qty: 12, price: 1_650_000 }, { name: "Ghế mây", qty: 24, price: 890_000 }]),
mk(33, "Bùi Quốc Bảo", "0919 302 554", "17 Cộng Hoà, Tân Bình", "Website", "Minh Anh", 7, -2, "done", [{ name: "Tủ quần áo 3 cánh", qty: 1, price: 7_300_000 }]),
mk(31, "Hoàng Minh Châu", "0987 221 649", "3 Nguyễn Huệ, Q.1, TP.HCM", "Showroom", "Hà Linh", 9, -4, "done", [{ name: "Đèn cây đứng", qty: 2, price: 1_250_000 }, { name: "Thảm lông 1m6×2m3", qty: 1, price: 2_100_000 }]),
mk(39, "Ngô Thị Hạnh", "0902 778 340", "9 Bà Huyện Thanh Quan, Q.3", "Website", "Minh Anh", 2, 5, "cancelled", [{ name: "Sofa văng 2m", qty: 1, price: 9_900_000 }]),
];
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("DD/MM");
if (days < 0) return `Trễ ${-days} ngày`;
return days === 0 ? "Giao hôm nay" : o.due.format("DD/MM");
}
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="Bấm để xem đơn đã huỷ" 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}>Thu gọn</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 ? "Thả đơn vào đây" : "Không có đơn"}</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: "Bạn", 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 ? `Đơn ${o.code} chỉ chuyển được sang “${META[next].title}” — không bỏ qua hay lùi bước.` : `Đơn ${o.code} đã ${META[o.status].title.toLowerCase()}, không đổi trạng thái được.`);
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 === "Khác" ? note.trim() : [reason, note.trim()].filter(Boolean).join(" — "));
message.success(`Đã huỷ đơn ${cancelling.code}`);
setCancelId(null);
};
const next = opened && nextOf(opened.status);
return (
<PageContainer title="Đơn hàng" subTitle={`${inProgress.length} đơn đang xử lý · kéo thẻ sang cột kế tiếp để chuyển bước`}>
<Flex justify="space-between" align="center" gap={12} wrap style={{ marginBottom: 16 }}>
<Flex gap={8} wrap>
<Chip label="Đơn hôm nay" value={kpi.today} />
<Chip label="Giá trị đang xử lý" value={vnd(kpi.wip)} />
<Chip label="Giao trễ" value={kpi.late} danger={kpi.late > 0} active={lateOnly} onClick={() => setLateOnly((v) => !v)} />
</Flex>
<Flex gap={8} wrap>
<Input allowClear prefix={<SearchOutlined />} placeholder="Mã đơn, tên khách" value={q} onChange={(e) => setQ(e.target.value)} style={{ width: 220 }} />
<Segmented<"all" | Channel> value={channel} onChange={setChannel} options={[{ label: "Tất cả", 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")}>Huỷ đơn</Button>
{next && <Button type="primary" icon={<ArrowRightOutlined />} iconPlacement="end" onClick={() => request(opened, next)}>Chuyển sang {META[next].title}</Button>}
</Flex>
)}>
{opened && (
<Flex vertical gap={24}>
<Descriptions size="small" column={1} items={[
{ key: "c", label: "Khách hàng", children: opened.customer },
{ key: "p", label: "Điện thoại", children: opened.phone },
{ key: "a", label: "Địa chỉ giao", children: opened.address },
{ key: "ch", label: "Kênh", children: <Tag color={CHANNEL_COLOR[opened.channel]}>{opened.channel}</Tag> },
{ key: "o", label: "Phụ trách", children: <Flex gap={8} align="center"><Staff name={opened.owner} size={20} />{opened.owner}</Flex> },
{ key: "d", label: "Hạn giao", children: <Typography.Text type={isLate(opened) ? "danger" : undefined}>{opened.due.format("DD/MM/YYYY")}{isLate(opened) ? ` · ${dueText(opened).toLowerCase()}` : ""}</Typography.Text> },
]} />
<div>
<Typography.Title level={5}>Sản phẩm</Typography.Title>
<Table<Line> size="small" rowKey="name" pagination={false} dataSource={opened.lines} columns={[
{ title: "Sản phẩm", dataIndex: "name" },
{ title: "SL", dataIndex: "qty", align: "right", width: 56 },
{ title: "Đơn giá", dataIndex: "price", align: "right", render: vnd },
{ title: "Thành tiền", 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>Tổng cộng</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}>Lịch sử</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("HH:mm DD/MM")}{h.note ? <><br />Lý do: {h.note}</> : null}</Typography.Text>,
}))} />
</div>
</Flex>
)}
</Drawer>
<Modal open={!!cancelling} title={`Huỷ đơn ${cancelling?.code ?? ""}`} okText="Huỷ đơn" cancelText="Giữ đơn" destroyOnHidden onOk={confirmCancel} onCancel={() => setCancelId(null)}
okButtonProps={{ danger: true, disabled: !reason || (reason === "Khác" && !note.trim()) }}>
<Typography.Paragraph type="secondary">Lý do được lưu vào lịch sử đơn. Đơn đã huỷ không chuyển lại được.</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 === "Khác" ? "Ghi rõ lý do (bắt buộc)" : "Ghi chú thêm (không bắt buộc)"} style={{ marginTop: 12 }} />
</Modal>
</PageContainer>
);
}
Làm màn hình bảng theo dõi đơn hàng dạng kanban cho cửa hàng nội thất, với các cột Mới → Đã xác nhận → Đang giao → Hoàn tất, còn cột Đã huỷ thu gọn ở cuối, bấm vào mới mở ra. Mỗi thẻ hiện mã đơn, tên khách, tag kênh (Showroom / Website / B2B), tổng tiền VND, hạn giao (đơn trễ thì tô đỏ và ghi "Trễ n ngày") và avatar người phụ trách. Kéo thẻ bằng @dnd-kit, chỉ cho chuyển sang bước kế tiếp: không bỏ qua bước, không lùi lại, đơn đã hoàn tất thì không kéo được. Kéo vào Đã huỷ thì mở Modal bắt chọn lý do, lý do "Khác" thì phải ghi chú, rồi lưu vào lịch sử đơn. Đầu trang có các chỉ số đơn hôm nay, giá trị đang xử lý và số đơn giao trễ (bấm vào để lọc đơn trễ), cùng ô tìm theo mã đơn hoặc tên khách và bộ lọc kênh. Bấm vào thẻ thì mở Drawer gồm thông tin khách, bảng sản phẩm có dòng tổng cộng, timeline trạng thái, và nút "Huỷ đơn" / "Chuyển sang bước kế". Dữ liệu lấy từ API của app qua useApiClient(): api.orders.list({ q, channel }) để tải đơn, api.orders.updateStatus(id, { status, reason }) khi đổi trạng thái rồi tải lại. Backend cũng phải chặn việc nhảy bước. Trên màn hình hẹp, bảng cuộn ngang.Lịch hẹn phòng khám
Mỗi bác sĩ một cột, không cho đặt hai lịch chồng giờ.
// Lịch hẹn lễ tân phòng khám nha: mỗi bác sĩ một cột, ô 30 phút 08:00–18:00, bấm ô trống để đặt (chặn trùng giờ), bấm lịch để check-in / khám / hoàn tất.
// Trong app thật: api.appointments.list({ branch, date }) nạp lưới, api.appointments.create(...) đặt lịch (server cũng chặn trùng), api.appointments.update(id, { status }) đổi trạng thái.
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 = ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"];
const STATUS: Record<Status, { text: string; badge: "default" | "processing" | "warning" | "success" | "error" }> = {
booked: { text: "Đã đặt", badge: "processing" },
arrived: { text: "Đã đến", badge: "warning" },
in_progress: { text: "Đang khám", badge: "success" },
done: { text: "Xong", badge: "default" },
no_show: { text: "Không đến", badge: "error" },
};
const BRANCHES = [
{ value: "q3", label: "Chi nhánh Quận 3 — 214 Võ Văn Tần" },
{ value: "td", label: "Chi nhánh Thủ Đức — 18 Võ Văn Ngân" },
];
const DOCTORS: Record<string, Array<{ id: string; name: string; role: string }>> = {
q3: [
{ id: "hung", name: "BS. Nguyễn Văn Hùng", role: "Chỉnh nha" },
{ id: "mai", name: "BS. Trần Thị Mai", role: "Nha tổng quát" },
{ id: "huy", name: "BS. Lê Quang Huy", role: "Phẫu thuật" },
{ id: "anh", name: "BS. Phạm Ngọc Ánh", role: "Nha thẩm mỹ" },
],
td: [
{ id: "khoa", name: "BS. Võ Đăng Khoa", role: "Nha tổng quát" },
{ id: "thu", name: "BS. Đỗ Minh Thư", role: "Chỉnh nha" },
{ id: "tuan", name: "BS. Hoàng Anh Tuấn", role: "Phẫu thuật" },
],
};
const SERVICES: Record<string, number> = { "Khám tổng quát": 30, "Cạo vôi răng": 30, "Trám răng": 60, "Niềng răng — tái khám": 30, "Nhổ răng khôn": 60, "Tẩy trắng răng": 90, "Điều trị tuỷ": 90 };
const PATIENTS = [
["0903 412 785", "Nguyễn Thị Hồng Nhung"], ["0918 226 041", "Trần Minh Khang"], ["0987 554 120", "Lê Thu Trang"],
["0932 118 907", "Phạm Gia Bảo"], ["0909 671 352", "Huỳnh Ngọc Vy"], ["0976 300 418", "Đặng Quốc Việt"],
["0938 845 226", "Bùi Thanh Tâm"], ["0912 079 634", "Võ Hoài An"], ["0965 482 913", "Ngô Phương Linh"], ["0908 137 560", "Lý Hoàng Nam"],
] 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, "Niềng răng — tái khám", "done"], ["q3", -1, "mai", "09:00", 60, 4, "Trám răng", "done"], ["q3", -1, "anh", "14:00", 90, 6, "Tẩy trắng răng", "no_show"],
["q3", 0, "hung", "08:00", 30, 0, "Niềng răng — tái khám", "done"], ["q3", 0, "hung", "09:30", 30, 3, "Niềng răng — tái khám", "arrived"], ["q3", 0, "hung", "14:00", 30, 8, "Khám tổng quát", "booked"],
["q3", 0, "mai", "08:30", 30, 2, "Cạo vôi răng", "done"], ["q3", 0, "mai", "10:00", 60, 5, "Trám răng", "in_progress"], ["q3", 0, "mai", "15:30", 30, 9, "Cạo vôi răng", "booked"],
["q3", 0, "huy", "09:00", 60, 7, "Nhổ răng khôn", "in_progress"], ["q3", 0, "huy", "13:30", 90, 1, "Điều trị tuỷ", "booked"],
["q3", 0, "anh", "08:00", 30, 6, "Khám tổng quát", "no_show"], ["q3", 0, "anh", "10:30", 90, 4, "Tẩy trắng răng", "booked"], ["q3", 0, "anh", "16:00", 60, 0, "Trám răng", "booked"],
["q3", 1, "hung", "09:00", 30, 2, "Niềng răng — tái khám", "booked"], ["q3", 1, "huy", "10:00", 60, 3, "Nhổ răng khôn", "booked"],
["td", 0, "khoa", "08:30", 30, 5, "Cạo vôi răng", "arrived"], ["td", 0, "khoa", "11:00", 60, 9, "Trám răng", "booked"], ["td", 0, "thu", "09:00", 30, 7, "Niềng răng — tái khám", "done"],
["td", 0, "tuan", "14:30", 60, 8, "Nhổ răng khôn", "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("Khung giờ này đã qua — chọn giờ khác.");
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="Lịch hẹn"
subTitle={`${WEEKDAY[date.day()]}, ${date.format("DD/MM/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)}>Hôm qua</Button>
<Button type={isOffset(0) ? "primary" : "default"} onClick={() => shift(0)}>Hôm nay</Button>
<Button type={isOffset(1) ? "primary" : "default"} onClick={() => shift(1)}>Ngày mai</Button>
<DatePicker value={date} onChange={(d) => d && setDate(d.startOf("day"))} format="DD/MM/YYYY" allowClear={false} style={{ width: 130 }} />
</Space.Compact>,
<Button key="n" type="primary" icon={<PlusOutlined />} disabled={date.isBefore(dayjs(), "day")} onClick={() => setBooking({})}>Đặt lịch</Button>,
]}
>
<Flex vertical gap={16}>
<StatisticCard.Group direction="row">
<StatisticCard statistic={{ title: "Lịch hẹn", value: dayAppts.length, description: `${count("booked")} đang chờ khách đến` }} />
<StatisticCard.Divider />
<StatisticCard statistic={{ title: "Đã đến", value: count("arrived", "in_progress", "done"), description: `${count("in_progress")} đang khám · ${count("done")} xong` }} />
<StatisticCard.Divider />
<StatisticCard statistic={{ title: "Không đến", value: count("no_show"), styles: { content: count("no_show") ? { color: token.colorError } : undefined } }} />
<StatisticCard.Divider />
<StatisticCard statistic={{ title: "Slot trống còn lại", value: freeLeft, suffix: `/ ${doctors.length * ROWS.length}`, description: "ô 30 phút chưa có lịch" }} />
</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" }}>Bấm ô trống để đặt lịch · bấm lịch hẹn để 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} lịch</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={`Đặt lịch ${d.name} lúc ${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 ? `+ ${hhmm(m)} đặt lịch` : 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={`Đặt lịch · ${date.format("DD/MM/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: "Đặt lịch", resetText: "Huỷ" } }}
onValuesChange={(changed) => changed.service && form.setFieldValue("dur", SERVICES[changed.service])}
onFinish={async (v) => {
if (v.start + v.dur > CLOSE) { message.error(`Lịch kết thúc lúc ${hhmm(v.start + v.dur)}, sau giờ đóng cửa 18:00 — chọn giờ sớm hơn.`); return false; }
const clash = findClash(appts, { branch, date: dateKey, ...v });
if (clash) { message.error(`${docName(v.doctor)} đã có lịch ${hhmm(clash.start)}–${hhmm(clash.start + clash.dur)} với ${patientName(clash.phone)}. Chọn giờ khác hoặc bác sĩ khác.`); return false; }
setAppts((xs) => [...xs, { id: Math.max(...xs.map((a) => a.id)) + 1, branch, date: dateKey, status: "booked", ...v }]);
message.success(`Đã đặt ${patientName(v.phone)} lúc ${hhmm(v.start)} với ${docName(v.doctor)}`);
return true;
}}
>
<ProFormSelect name="phone" label="Bệnh nhân" placeholder="Gõ số điện thoại hoặc tên" showSearch rules={[{ required: true, message: "Chọn bệnh nhân" }]}
options={PATIENTS.map(([phone, name]) => ({ value: phone, label: `${phone} · ${name}` }))} />
<ProFormSelect name="service" label="Dịch vụ" rules={[{ required: true, message: "Chọn dịch vụ" }]}
options={Object.entries(SERVICES).map(([s, m]) => ({ value: s, label: `${s} (${m} phút)` }))} />
<ProFormSelect name="doctor" label="Bác sĩ" rules={[{ required: true, message: "Chọn bác sĩ" }]} options={doctors.map((d) => ({ value: d.id, label: `${d.name} — ${d.role}` }))} />
<Flex gap={16}>
<ProFormSelect name="start" label="Giờ bắt đầu" width="xs" rules={[{ required: true, message: "Chọn giờ" }]} options={ROWS.filter((m) => !isPast(m)).map((m) => ({ value: m, label: hhmm(m) }))} />
<ProFormRadio.Group name="dur" label="Thời lượng" radioType="button" options={[30, 60, 90, 120].map((m) => ({ value: m, label: `${m} phút` }))} />
</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={`Trùng lịch: ${docName(doctor)} đang có ${patientName(clash.phone)} lúc ${hhmm(clash.start)}–${hhmm(clash.start + clash.dur)}`} />;
return <Alert type="success" showIcon style={{ marginBottom: 16 }} title={`Còn trống ${hhmm(start)}–${hhmm(start + dur)}`} />;
}}
</ProFormDependency>
<ProFormTextArea name="note" label="Ghi chú" placeholder="VD: răng 36 ê buốt, sợ đau, cần gọi nhắc trước 1 ngày" 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")}>Đánh dấu không đến</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")}>Bắt đầu khám</Button>}
{current.status === "in_progress" && <Button type="primary" onClick={() => setStatus(current.id, "done")}>Hoàn tất</Button>}
{(current.status === "done" || current.status === "no_show") && <Typography.Text type="secondary">Lịch hẹn đã đóng</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: "Đã đặt" }, { title: current.status === "no_show" ? "Không đến" : "Đã đến" }, { title: "Đang khám" }, { title: "Xong" }]} />
<Descriptions column={1} size="small" items={[
{ label: "Số điện thoại", children: current.phone },
{ label: "Dịch vụ", children: current.service },
{ label: "Bác sĩ", children: docName(current.doctor) },
{ label: "Giờ", children: `${hhmm(current.start)}–${hhmm(current.start + current.dur)} · ${dayjs(current.date).format("DD/MM/YYYY")}` },
{ label: "Ghi chú", children: current.note || "—" },
]} />
</Flex>
) : null}
</Drawer>
</PageContainer>
);
}
Làm màn hình lịch hẹn cho lễ tân phòng khám nha khoa (nhiều chi nhánh) ở `app/appointments/page.tsx`: xem theo ngày, mỗi bác sĩ của chi nhánh đang chọn là một cột, mỗi hàng là một ô 30 phút từ 08:00 đến 18:00, lịch hẹn hiện thành khối (tên bệnh nhân, dịch vụ như cạo vôi, trám răng, niềng răng; mỗi trạng thái một màu: Đã đặt, Đã đến, Đang khám, Xong, Không đến). Trên đầu có chọn chi nhánh, nút Hôm qua / Hôm nay / Ngày mai kèm DatePicker, và hàng số liệu trong ngày (số lịch hẹn, đã đến, không đến, số ô trống còn lại). Bấm ô trống mở DrawerForm đặt lịch (tìm bệnh nhân theo số điện thoại, chọn dịch vụ thì tự điền thời lượng, chọn bác sĩ và giờ). Không cho đặt hai lịch chồng giờ của cùng một bác sĩ: báo lỗi ghi rõ ai đang có lịch lúc mấy giờ. Không cho đặt vào giờ đã qua hoặc kết thúc sau 18:00. API cũng phải chặn trùng giờ, không chỉ giao diện. Bấm một lịch hẹn mở Drawer chỉ hiện nút hợp với trạng thái hiện tại: Check-in, Bắt đầu khám, Hoàn tất, Đánh dấu không đến. Lưới dựng bằng div và token antd, không dùng thư viện lịch. Dữ liệu lấy từ API của app qua `useApiClient()` (`appointments.list` theo chi nhánh và ngày, `appointments.create`, `appointments.update` để đổi trạng thái), không viết cứng dữ liệu trong trang.
Bán hàng tại quầy
Lưới món, hoá đơn đang mở, ba cách thanh toán.
// Bán hàng tại quầy quán cà phê: lưới món theo danh mục + tìm kiếm, hoá đơn có size/ghi chú/số lượng, tại bàn hoặc mang về, mã giảm giá, VAT 8%, ba cách thanh toán, nhiều đơn tạm giữ, in hoá đơn.
// Trong app thật: món lấy từ api.products.list(), mã giảm giá kiểm bằng api.discounts.check(code), "Thanh toán" gọi api.orders.create(...) và server tính lại tiền.
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 = ["Cà phê", "Trà", "Bánh", "Topping"];
const PRODUCTS: Product[] = [
{ id: "cf1", name: "Cà phê sữa đá", cat: "Cà phê", price: 29000, priceL: 35000 },
{ id: "cf2", name: "Cà phê đen đá", cat: "Cà phê", price: 25000, priceL: 31000 },
{ id: "cf3", name: "Bạc xỉu", cat: "Cà phê", price: 32000, priceL: 38000 },
{ id: "cf4", name: "Cà phê muối", cat: "Cà phê", price: 35000, priceL: 41000 },
{ id: "cf5", name: "Cà phê cốt dừa", cat: "Cà phê", price: 39000, priceL: 45000, out: true },
{ id: "cf6", name: "Espresso", cat: "Cà phê", price: 30000 },
{ id: "tr1", name: "Trà đào cam sả", cat: "Trà", price: 39000, priceL: 45000 },
{ id: "tr2", name: "Trà vải hoa hồng", cat: "Trà", price: 39000, priceL: 45000 },
{ id: "tr3", name: "Trà sen vàng", cat: "Trà", price: 42000, priceL: 48000, out: true },
{ id: "tr4", name: "Trà sữa ô long", cat: "Trà", price: 35000, priceL: 41000 },
{ id: "bk1", name: "Bánh mì que pa-tê", cat: "Bánh", price: 15000 },
{ id: "bk2", name: "Croissant bơ", cat: "Bánh", price: 32000 },
{ id: "bk3", name: "Tiramisu", cat: "Bánh", price: 45000 },
{ id: "bk4", name: "Bông lan trứng muối", cat: "Bánh", price: 28000, out: true },
{ id: "tp1", name: "Trân châu trắng", cat: "Topping", price: 8000 },
{ id: "tp2", name: "Thạch đào", cat: "Topping", price: 8000 },
{ id: "tp3", name: "Kem cheese", cat: "Topping", price: 12000 },
{ id: "tp4", name: "Thêm shot espresso", cat: "Topping", price: 10000 },
];
const byId = Object.fromEntries(PRODUCTS.map((p) => [p.id, p]));
const TABLES = Array.from({ length: 12 }, (_, i) => `Bàn ${i + 1}`);
const NOTES = ["ít đá", "không đá", "ít ngọt", "không đường", "nhiều sữa", "đá riêng"].map((value) => ({ value }));
const CODES: Record<string, { label: string; min: number; calc: (sub: number) => number }> = {
QUEN10: { label: "Khách quen giảm 10%", min: 0, calc: (s) => Math.round(s * 0.1) },
GIAM20K: { label: "Giảm 20.000 đ cho đơn từ 100.000 đ", min: 100000, calc: () => 20000 },
};
const METHOD_LABEL: Record<Method, string> = { cash: "Tiền mặt", transfer: "Chuyển khoản", card: "Thẻ" };
const fmt = new Intl.NumberFormat("vi-VN");
const vnd = (n: number) => `${fmt.format(n)} đ`;
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 : `Mang về #${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) * 0.08);
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: "Bàn 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: "Bàn 4", no: 11, lines: [{ key: "1", pid: "cf1", size: "L", qty: 2, note: "ít đá" }, { key: "2", pid: "bk2", size: "M", qty: 1, note: "" }], code: "", method: "cash", given: null },
{ id: "b12", mode: "takeaway", table: "Bàn 1", no: 12, lines: [{ key: "3", pid: "tr1", size: "M", qty: 1, note: "ít ngọt" }], 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(`Đã tạm giữ ${billName(bill)} — mở lại ở thanh đơn phía trên`);
};
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("Mã giảm giá không đúng hoặc đã hết hạn");
if (t.sub < c.min) return message.warning(`Mã ${code} cần đơn từ ${vnd(c.min)}`);
patch((b) => ({ ...b, code }));
setCodeInput("");
message.success(`Đã áp dụng: ${c.label}`);
};
const cashShort = bill.method === "cash" && (bill.given ?? 0) < t.total;
const pay = () => {
const invoice = `HD${invoiceNo}`;
setReceipt({ invoice, at: dayjs().format("DD/MM/YYYY HH:mm"), bill, t });
setInvoiceNo((n) => n + 1);
closeBill(bill.id);
};
const transferNote = `${billName(bill).replace(/\s|#/g, "").toUpperCase()} HD${invoiceNo}`;
return (
<PageContainer title="Bán hàng tại quầy" subTitle="Cà phê Phố Cũ · Ca sáng · Thu ngân: Ngọc Anh">
<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="Tìm món" value={q} onChange={(e) => setQ(e.target.value)} style={{ width: 200 }} />
</Flex>
{q && <Typography.Text type="secondary">{shown.length} món khớp “{q}” trong mọi danh mục</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">Hết hàng</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="Không có món nào khớp" /></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: `Huỷ ${billName(b)}?`, content: `${b.lines.length} món sẽ bị xoá khỏi đơn.`, okText: "Huỷ đơn", okButtonProps: { danger: true }, cancelText: "Giữ lại", 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: "Tại bàn" }, { value: "takeaway", label: "Mang về" }]} />
{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" }}>Tạm giữ</Button>
</Flex>
<Divider style={{ margin: "12px 0" }} />
{!bill.lines.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="Chạm vào món bên trái để thêm vào đơn" />}
<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="Bớt một" 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="Thêm một" 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 !== "Topping" && p.cat !== "Bánh" && (
<AutoComplete size="small" options={NOTES} value={l.note} onChange={(v) => setLine(l.key, (x) => ({ ...x, note: v }))} placeholder="Ghi chú: ít đá, ít ngọt…" 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="Mã giảm giá (VD: QUEN10)" enterButton="Áp dụng" 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">Tạm tính ({t.count} món)</Typography.Text><Typography.Text>{vnd(t.sub)}</Typography.Text></Flex>
{t.disc > 0 && <Flex justify="space-between"><Typography.Text type="secondary">Giảm giá</Typography.Text><Typography.Text type="success">−{vnd(t.disc)}</Typography.Text></Flex>}
{bill.code && t.disc === 0 && <Typography.Text type="warning" style={{ fontSize: 12 }}>Đơn chưa đủ điều kiện dùng mã {bill.code}</Typography.Text>}
<Flex justify="space-between"><Typography.Text type="secondary">VAT 8%</Typography.Text><Typography.Text>{vnd(t.vat)}</Typography.Text></Flex>
<Flex justify="space-between" align="baseline"><Typography.Text strong>Tổng cộng</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>Khách đưa</Space.Addon><InputNumber<number> suffix="đ" min={0} step={1000} 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, 100000, 200000, 500000].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 ? "Vừa đủ" : vnd(v)}</Button>
))}
</Flex>
<Flex justify="space-between">
<Typography.Text type="secondary">Tiền thừa trả khách</Typography.Text>
{cashShort ? <Typography.Text type="danger">{bill.given ? `Thiếu ${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={`STK 0123456789 VCB|${t.total}|${transferNote}`} size={128} bordered />
<Flex vertical gap={2}>
<Typography.Text type="secondary">Số tiền</Typography.Text>
<Typography.Text strong style={{ fontSize: 18 }}>{vnd(t.total)}</Typography.Text>
<Typography.Text type="secondary">Nội dung chuyển khoản</Typography.Text>
<Typography.Text code copyable>{transferNote}</Typography.Text>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>Vietcombank · 0123456789 · CONG TY PHO CU</Typography.Text>
</Flex>
</Flex>
)}
{bill.method === "card" && (
<Flex gap={8} align="center">
<CreditCardOutlined style={{ fontSize: 20 }} />
<Typography.Text type="secondary">Nhập {vnd(t.total)} trên máy cà thẻ. Khi máy báo thành công, bấm Thanh toán.</Typography.Text>
</Flex>
)}
</div>
<Button type="primary" size="large" block style={{ marginTop: 16 }} disabled={!bill.lines.length || cashShort} onClick={pay}>
Thanh toán {bill.lines.length ? vnd(t.total) : ""}
</Button>
</ProCard>
</Col>
</Row>
<Modal
open={!!receipt}
title={`Hoá đơn ${receipt?.invoice ?? ""}`}
onCancel={() => setReceipt(null)}
width={380}
footer={[
<Button key="print" onClick={() => message.success("Đã gửi hoá đơn tới máy in quầy")}>In hoá đơn</Button>,
<Button key="ok" type="primary" onClick={() => setReceipt(null)}>Đơn mới</Button>,
]}
>
{receipt && (
<Flex vertical gap={6}>
<Typography.Text type="secondary">Cà phê Phố Cũ · 12 Hàng Bạc, Hà Nội</Typography.Text>
<Typography.Text type="secondary">{receipt.at} · {billName(receipt.bill)} · Thu ngân: Ngọc Anh</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>Tạm tính</span><span>{vnd(receipt.t.sub)}</span></Flex>
{receipt.t.disc > 0 && <Flex justify="space-between"><span>Giảm giá ({receipt.bill.code})</span><span>−{vnd(receipt.t.disc)}</span></Flex>}
<Flex justify="space-between"><span>VAT 8%</span><span>{vnd(receipt.t.vat)}</span></Flex>
<Flex justify="space-between"><Typography.Text strong>Tổng cộng</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>Tiền thừa</span><span>{vnd((receipt.bill.given ?? 0) - receipt.t.total)}</span></Flex>}
<Typography.Text type="secondary" style={{ textAlign: "center", marginTop: 8 }}>Cảm ơn bạn — hẹn gặp lại!</Typography.Text>
</Flex>
)}
</Modal>
</PageContainer>
);
}
Làm màn hình bán hàng tại quầy cho quán cà phê. Bên trái là lưới món chia theo tab danh mục (Cà phê, Trà, Bánh, Topping), có ô tìm món trong mọi danh mục; mỗi món hiện tên, giá, giá size L nếu có; món hết hàng mờ đi, gắn nhãn "Hết hàng" và không bấm được. Bên phải là hoá đơn đang mở: mỗi dòng có nút −/+ (về 0 thì xoá dòng), chọn size M/L làm đổi giá, ghi chú gợi ý sẵn "ít đá", "ít ngọt"…; chọn "Tại bàn" (kèm số bàn) hoặc "Mang về"; ô mã giảm giá báo lỗi khi mã sai hoặc đơn chưa đủ mức tối thiểu; hiện tạm tính, giảm giá, VAT 8% và tổng cộng, định dạng tiền vi-VN. Cho giữ nhiều đơn cùng lúc dưới dạng tab, nút "Tạm giữ" để cất đơn hiện tại và mở đơn mới, huỷ đơn có món thì phải xác nhận. Thanh toán có ba cách: Tiền mặt (nhập tiền khách đưa, có nút nhanh "Vừa đủ"/100k/200k/500k, tính tiền thừa, không cho thanh toán khi thiếu), Chuyển khoản (mã QR kèm số tiền, nội dung chuyển khoản có mã đơn và số tài khoản), Thẻ (nhắc cà thẻ trên máy POS). Bấm "Thanh toán" thì đóng đơn và mở hoá đơn trong Modal, có nút "In hoá đơn" và "Đơn mới". Dữ liệu lấy từ API của app qua useApiClient(): danh sách món và tồn kho từ api.products.list(), kiểm mã giảm giá bằng api.discounts.check(), tạo đơn bằng api.orders.create() — server tự tính lại tiền, không tin số tiền từ trình duyệt.
Công nợ phải thu
Tuổi nợ theo nhóm, ghi nhận thanh toán phân bổ vào hoá đơn đến hạn trước.
// Công nợ phải thu: thẻ KPI + thanh tuổi nợ bấm để lọc, ProTable khách hàng có thanh dư nợ so với hạn mức, Drawer hoá đơn mở với ghi nhận thanh toán (phân bổ hoá đơn cũ trước) và gửi nhắc nợ.
// Trong app thật: api.receivables.summary() cho KPI và tuổi nợ, api.customers.list({ bucket, q, staff }), api.invoices.list({ customerId, open: true }), api.payments.create(...) trả về kết quả phân bổ, 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("vi-VN");
const vnd = (n: number) => `${fmt.format(Math.round(n))} ₫`;
const day = (d: string) => dayjs(d).format("DD/MM/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: "Chưa đến hạn", tone: "green6" },
{ key: "d30", label: "1–30 ngày", tone: "gold6" },
{ key: "d60", label: "31–60 ngày", tone: "orange6" },
{ key: "d90", label: "61–90 ngày", tone: "volcano6" },
{ key: "d90p", label: "Trên 90 ngày", 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: "KH001", name: "Công ty TNHH Thương mại Minh Phát", limit: 800e6, staff: "Nguyễn Văn Hùng", contact: "Chị Phạm Thu Trang (kế toán)", email: "ketoan@minhphat.vn" },
{ id: "KH002", name: "Công ty CP Phân phối Hoàng Long", limit: 500e6, staff: "Trần Thị Mai", contact: "Anh Võ Đức Thịnh", email: "congno@hoanglongdist.vn" },
{ id: "KH003", name: "Siêu thị mini Thuận Thành", limit: 200e6, staff: "Lê Quốc Bảo", contact: "Chị Nguyễn Kim Oanh", email: "thuanthanh.mart@gmail.com" },
{ id: "KH004", name: "Công ty TNHH Dược phẩm Tâm Đức", limit: 600e6, staff: "Trần Thị Mai", contact: "Anh Đỗ Minh Quân (KTT)", email: "ktt@duoctamduc.com.vn" },
{ id: "KH005", name: "HTX Thương mại Bình Minh", limit: 150e6, staff: "Lê Quốc Bảo", contact: "Chú Trương Văn Lộc", email: "htxbinhminh@gmail.com" },
{ id: "KH006", name: "Công ty CP Nhà hàng Sen Vàng", limit: 300e6, staff: "Nguyễn Văn Hùng", contact: "Chị Lý Ngọc Hân", email: "accounting@senvang.vn" },
{ id: "KH007", name: "Công ty TNHH Tạp hoá Phúc An", limit: 100e6, staff: "Lê Quốc Bảo", contact: "Anh Hồ Văn Phúc", email: "phucan.store@gmail.com" },
{ id: "KH008", name: "Công ty CP Chuỗi cà phê Mộc Trà", limit: 400e6, staff: "Nguyễn Văn Hùng", contact: "Chị Đặng Thảo Vy", email: "finance@moctra.vn" },
{ id: "KH009", name: "Công ty TNHH Bếp Việt Catering", limit: 250e6, staff: "Trần Thị Mai", contact: "Anh Bùi Thanh Tùng", email: "ketoan@bepviet.vn" },
{ id: "KH010", name: "Đại lý Hải Yến", limit: 80e6, staff: "Lê Quốc Bảo", contact: "Chị Hải Yến", email: "daily.haiyen@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("KH001", "0001845", "2026-08-05", "2026-09-04", 128.5e6), inv("KH001", "0002011", "2026-09-20", "2026-10-20", 215.4e6, 50e6),
inv("KH001", "0002210", "2026-10-28", "2026-11-27", 186.75e6), inv("KH001", "0002305", "2026-11-08", "2026-12-08", 142.3e6),
inv("KH002", "0001702", "2026-06-18", "2026-07-18", 96.2e6, 30e6), inv("KH002", "0001930", "2026-08-30", "2026-09-29", 154e6),
inv("KH002", "0002150", "2026-10-15", "2026-11-14", 212.8e6),
inv("KH003", "0002188", "2026-10-22", "2026-11-06", 48.6e6), inv("KH003", "0002260", "2026-11-03", "2026-11-18", 37.9e6),
inv("KH004", "0001655", "2026-06-02", "2026-07-17", 184e6), inv("KH004", "0001790", "2026-07-10", "2026-08-24", 226.5e6, 100e6),
inv("KH004", "0002090", "2026-10-05", "2026-11-19", 205.3e6), inv("KH004", "0002255", "2026-11-02", "2026-12-17", 74e6),
inv("KH005", "0002230", "2026-10-30", "2026-11-29", 64.2e6),
inv("KH006", "0001988", "2026-09-08", "2026-10-08", 88.4e6), inv("KH006", "0002101", "2026-10-08", "2026-11-07", 92.15e6),
inv("KH006", "0002280", "2026-11-06", "2026-12-06", 101.7e6),
inv("KH007", "0002199", "2026-10-24", "2026-11-08", 23.8e6, 10e6), inv("KH007", "0002290", "2026-11-07", "2026-11-17", 18.45e6),
inv("KH008", "0002040", "2026-09-25", "2026-10-25", 132.6e6), inv("KH008", "0002242", "2026-11-01", "2026-12-01", 147.9e6),
inv("KH009", "0001610", "2026-05-20", "2026-06-19", 57.3e6, 20e6),
inv("KH010", "0002120", "2026-10-10", "2026-10-17", 31.2e6), inv("KH010", "0002300", "2026-11-08", "2026-11-15", 26.9e6),
];
const PAYMENTS: Payment[] = [
{ customerId: "KH001", date: "2026-11-05", amount: 50e6, method: "Chuyển khoản" },
{ customerId: "KH004", date: "2026-11-03", amount: 100e6, method: "Chuyển khoản" },
{ customerId: "KH007", date: "2026-11-10", amount: 10e6, method: "Tiền mặt" },
{ customerId: "KH008", date: "2026-11-02", amount: 284.6e6, method: "Chuyển khoản" },
];
const METHODS = ["Chuyển khoản", "Tiền mặt", "Bù trừ công nợ"];
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>>({ KH009: "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">Trong hạn</Typography.Text>
: <Tag color={d > 90 ? "red" : d > 60 ? "volcano" : d > 30 ? "orange" : "gold"}>{d} ngày</Tag>;
const columns: ProColumns<Row>[] = [
{ title: "Mã KH", dataIndex: "id", width: 80 },
{ title: "Khách hàng", 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 /> Đã nhắc nợ {day(reminded[r.id])}</Typography.Text>}
</Space>) },
{ title: "Hạn mức", dataIndex: "limit", align: "right", width: 130, render: (_, r) => vnd(r.limit) },
{ title: "Dư nợ", 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: "Quá hạn", 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: "Quá hạn lâu nhất", dataIndex: "maxLate", width: 130, sorter: (a, b) => a.maxLate - b.maxLate, render: (_, r) => lateTag(r.maxLate) },
{ title: "Phụ trách", dataIndex: "staff", width: 140 },
{ title: "", valueType: "option", width: 70, render: (_, r) => [<a key="v" onClick={() => setOpenId(r.id)}>Chi tiết</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(`Đã ghi nhận ${vnd(v.amount)} · tất toán ${closed} hoá đơn${credit ? ` · ghi có ${vnd(credit)}` : ""}`);
return true;
};
return (
<PageContainer title="Công nợ phải thu" subTitle={`Số liệu đến ngày ${TODAY.format("DD/MM/YYYY")}`}
extra={<Select allowClear placeholder="Nhân viên phụ trách" 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: "Tổng phải thu", value: vnd(total), description: <StatisticCard.Statistic title="Khách còn nợ" value={rows.filter((r) => r.balance).length} /> }} />
<StatisticCard.Divider type={md ? "vertical" : "horizontal"} />
<StatisticCard statistic={{ title: "Quá hạn", value: vnd(overdue), styles: { content: { color: token.colorError } }, description: <StatisticCard.Statistic title="Tỷ lệ" value={`${((overdue / total) * 100).toFixed(1).replace(".", ",")}%`} /> }} />
<StatisticCard.Divider type={md ? "vertical" : "horizontal"} />
<StatisticCard statistic={{ title: "Đến hạn trong 7 ngày", value: vnd(soon.reduce((s, i) => s + owed(i), 0)), description: <StatisticCard.Statistic title="Hoá đơn" value={soon.length} /> }} />
<StatisticCard.Divider type={md ? "vertical" : "horizontal"} />
<StatisticCard statistic={{ title: "Đã thu tháng này", value: vnd(monthPaid.reduce((s, p) => s + p.amount, 0)), description: <StatisticCard.Statistic title="Lần thu" value={monthPaid.length} /> }} />
</StatisticCard.Group>
<ProCard title="Tuổi nợ" subTitle="bấm một nhóm để lọc danh sách" headerBordered
extra={bucket && <a onClick={() => setBucket(null)}>Bỏ lọc</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).replace(".", ",") : 0}%</Typography.Text>
</div>
</Col>
))}
</Row>
</ProCard>
<ProTable<Row>
rowKey="id" cardBordered columns={columns} dataSource={shown} search={false}
headerTitle={bucket ? `Khách có nợ ${BUCKETS.find((b) => b.key === bucket)!.label.toLowerCase()}` : "Khách hàng còn nợ"}
options={{ density: true, setting: false, reload: false }}
toolbar={{ search: { placeholder: "Tìm mã KH hoặc tên công ty", allowClear: true, onSearch: setQ, style: { width: 260 } } }}
pagination={{ pageSize: 10, showTotal: (t) => `${t} khách hàng` }}
summary={(data) => (
<Table.Summary.Row>
<Table.Summary.Cell index={0} colSpan={2}><b>Tổng {data.length} khách</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)}>Gửi nhắc nợ</Button>
<ModalForm<{ amount: number; date: string; method: string; ref?: string }> title="Ghi nhận thanh toán" width={620} formRef={formRef}
trigger={<Button type="primary" icon={<DollarOutlined />}>Ghi nhận thanh toán</Button>}
initialValues={{ date: TODAY, method: "Chuyển khoản" }} modalProps={{ destroyOnHidden: true, okText: "Lưu phiếu thu" }}
onFinish={record}>
<ProFormMoney name="amount" label="Số tiền thu" locale="vi-VN" fieldProps={{ precision: 0 }} rules={[{ required: true, message: "Nhập số tiền" }]}
extra={<a onClick={() => formRef.current?.setFieldsValue({ amount: cust.balance })}>Thu toàn bộ dư nợ ({vnd(cust.balance)})</a>} />
<Flex gap={16}>
<ProFormDatePicker name="date" label="Ngày thu" width="sm" fieldProps={{ format: "DD/MM/YYYY" }} transform={(v: string) => ({ date: dayjs(v).format("YYYY-MM-DD") })} />
<ProFormSelect name="method" label="Hình thức" width="sm" options={METHODS} />
<ProFormText name="ref" label="Số chứng từ" width="sm" placeholder="VD: UNC 1125" />
</Flex>
<ProFormDependency name={["amount"]}>
{({ amount }) => {
if (!amount) return <Typography.Text type="secondary">Nhập số tiền để xem phân bổ — tiền thu trừ vào hoá đơn đến hạn sớm nhất trước.</Typography.Text>;
const { lines, credit } = allocate(custOpen, amount);
return (<Flex vertical gap={8}>
<Typography.Text strong>Phân bổ dự kiến</Typography.Text>
<Table size="small" rowKey="no" pagination={false} dataSource={lines} columns={[
{ title: "Hoá đơn", dataIndex: "no" }, { title: "Hạn", dataIndex: "due", render: day },
{ title: "Còn nợ", align: "right", render: (_, l) => vnd(owed(l)) },
{ title: "Trừ vào", dataIndex: "applied", align: "right", render: (v: number) => <b>{vnd(v)}</b> },
{ title: "Sau khi thu", dataIndex: "after", align: "right", render: (v: number) => v ? vnd(v) : <Tag color="success">Tất toán</Tag> },
]} />
{credit > 0 && <Alert type="warning" showIcon title={`Thu dư ${vnd(credit)} so với dư nợ — phần dư ghi có cho khách, trừ vào hoá đơn sau.`} />}
</Flex>);
}}
</ProFormDependency>
</ModalForm>
</Space>}>
{cust && <Flex vertical gap={16}>
<Descriptions size="small" column={2} items={[
{ label: "Dư nợ", children: <b>{vnd(cust.balance)}</b> }, { label: "Hạn mức", children: `${vnd(cust.limit)} (đã dùng ${Math.round((cust.balance / cust.limit) * 100)}%)` },
{ label: "Quá hạn", children: <Typography.Text type="danger">{vnd(cust.overdue)}</Typography.Text> }, { label: "Phụ trách", children: cust.staff },
{ label: "Liên hệ", children: cust.contact }, { label: "Email", children: cust.email },
]} />
<Table<Invoice> size="small" rowKey="no" pagination={false} dataSource={custOpen}
columns={[
{ title: "Số hoá đơn", dataIndex: "no" }, { title: "Ngày", dataIndex: "date", render: day },
{ title: "Hạn thanh toán", dataIndex: "due", render: (d: string) => <Space size={4}>{day(d)}{lateTag(lateDays(d))}</Space> },
{ title: "Giá trị", dataIndex: "amount", align: "right", render: vnd },
{ title: "Còn nợ", align: "right", render: (_, i) => <b>{vnd(owed(i))}</b> },
]}
summary={(data) => <Table.Summary.Row><Table.Summary.Cell index={0} colSpan={4}>Tổng {data.length} hoá đơn còn mở</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="Xem trước email nhắc nợ" okText="Gửi email" cancelText="Huỷ" width={620} onCancel={() => setRemindId(null)}
onOk={() => { setReminded((m) => ({ ...m, [remindId!]: TODAY.format("YYYY-MM-DD") })); message.success(`Đã gửi nhắc nợ tới ${remind?.email}`); setRemindId(null); }}>
{remind && <Flex vertical gap={8}>
<Typography.Text><Typography.Text type="secondary">Đến:</Typography.Text> {remind.email}</Typography.Text>
<Typography.Text><Typography.Text type="secondary">Tiêu đề:</Typography.Text> [Phân phối An Phú] Đề nghị thanh toán công nợ quá hạn — {remind.id}</Typography.Text>
<ProCard bordered style={{ background: token.colorFillQuaternary }}>
<Typography.Paragraph>Kính gửi {remind.contact} — {remind.name},</Typography.Paragraph>
<Typography.Paragraph>Đến ngày {TODAY.format("DD/MM/YYYY")}, quý công ty còn {remindLate.length} hoá đơn quá hạn với tổng số tiền <b>{vnd(remind.overdue)}</b>:</Typography.Paragraph>
<ul>{remindLate.map((i) => <li key={i.no}>Hoá đơn {i.no}, hạn {day(i.due)} (quá {lateDays(i.due)} ngày): {vnd(owed(i))}</li>)}</ul>
<Typography.Paragraph>Đề nghị quý công ty thanh toán vào tài khoản 0071 0012 34567 (Vietcombank — CN Tân Bình), nội dung “{remind.id} thanh toán công nợ”. Nếu đã thanh toán, xin bỏ qua email này.</Typography.Paragraph>
<Typography.Paragraph style={{ marginBottom: 0 }}>Trân trọng,<br />{remind.staff} — Phòng Kế toán, Công ty TNHH Phân phối An Phú</Typography.Paragraph>
</ProCard>
</Flex>}
</Modal>
</PageContainer>
);
}
Làm màn hình công nợ phải thu cho công ty phân phối: trên cùng là 4 thẻ số liệu (tổng phải thu, quá hạn, đến hạn trong 7 ngày, đã thu tháng này) và thanh tuổi nợ chia 5 nhóm (chưa đến hạn, 1–30, 31–60, 61–90, trên 90 ngày) — bấm một nhóm thì lọc danh sách khách. Bên dưới là ProTable khách hàng còn nợ (mã KH, tên công ty, hạn mức, dư nợ kèm thanh tiến độ so với hạn mức, chuyển đỏ khi vượt 90%, số tiền quá hạn, số ngày quá hạn lâu nhất, nhân viên phụ trách), có ô tìm kiếm, lọc theo nhân viên và dòng tổng. Bấm vào khách thì mở Drawer liệt kê hoá đơn còn nợ (số hoá đơn, ngày, hạn, còn nợ), có nút "Ghi nhận thanh toán" (số tiền, ngày, hình thức, số chứng từ). Tiền thu phân bổ vào hoá đơn có hạn sớm nhất trước, và form hiện bảng phân bổ dự kiến trước khi lưu, kể cả phần thu dư ghi có. Thêm nút "Gửi nhắc nợ" mở bản xem trước email liệt kê các hoá đơn quá hạn. Lấy dữ liệu từ API của app qua useApiClient(): server tính tuổi nợ, phân bổ thanh toán và tổng tiền. Sau khi ghi nhận thanh toán thì tải lại để thẻ số liệu, thanh tuổi nợ và bảng cập nhật theo.
Thiết kế quy trình
Kéo thả các bước và nhánh duyệt bằng React Flow.
// Thiết kế quy trình duyệt: @xyflow/react kéo thả node, nối cạnh, thêm bước, lưu JSON (CSS đã có trong vendor — không 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: "Nhân viên" },
{ value: "manager", label: "Trưởng phòng" },
{ value: "accountant", label: "Kế toán" },
{ value: "director", label: "Giám đốc" },
];
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: "Gửi đề xuất", role: "staff" } },
{ id: "2", type: "step", position: { x: 120, y: 120 }, data: { label: "Trưởng phòng duyệt", role: "manager" } },
{ id: "3", type: "step", position: { x: 0, y: 240 }, data: { label: "Kế toán kiểm tra", role: "accountant" } },
{ id: "4", type: "step", position: { x: 260, y: 240 }, data: { label: "Giám đốc duyệt (> 50 triệu)", 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: "> 50 triệu" },
];
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="Quy trình duyệt đề xuất chi"
extra={[
<Button key="save" type="primary" icon={<SaveOutlined />} onClick={() => message.success(`Đã lưu ${nodes.length} bước, ${edges.length} liên kết (gửi JSON lên API)`)}>
Lưu quy trình
</Button>,
]}
>
<ProCard
title="Sơ đồ"
extra={
<Space.Compact>
<Input placeholder="Tên bước" 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}>
Thêm bước
</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>
);
}
Làm màn hình "Thiết kế quy trình (React Flow)" cho app của tôi theo mẫu manh.run UI playbook (framework_docs("pro")): Thiết kế quy trình duyệt: @xyflow/react kéo thả node, nối cạnh, thêm bước, lưu JSON (CSS đã có trong vendor — không import .css). Dữ liệu lấy từ API của app qua useApiClient(); nhãn và trường theo spec của tôi.Trợ lý AI
Khung chat có gợi ý và trả lời dạng Markdown.
// Trợ lý AI trong app: antd X (Welcome, Prompts, Bubble.List, Sender) + XMarkdown; câu trả lời giả lập stream (app thật: khối lego "ai-assistant").
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 = `Có **3 đơn quá hạn giao**:
| Mã đơn | Khách | Trễ |
|---|---|---|
| DH-2026-0141 | Cty An Khang | 2 ngày |
| DH-2026-0150 | Café Mộc | 1 ngày |
| DH-2026-0152 | Thép Việt | 1 ngày |
Gợi ý: gọi khách **An Khang** trước — đơn lớn nhất (120 triệu).`;
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="Trợ lý">
<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="Trợ lý bán hàng" description="Hỏi về đơn hàng, tồn kho, khách hàng — trợ lý tra dữ liệu thật bằng công cụ của app." />
<Prompts
items={["Đơn nào quá hạn giao?", "Sản phẩm nào sắp hết hàng?", "Doanh số tuần này?"].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="Hỏi trợ lý…" />
</Flex>
</ProCard>
</PageContainer>
);
}
Làm màn hình "Trợ lý AI (antd X)" cho app của tôi theo mẫu manh.run UI playbook (framework_docs("pro")): Trợ lý AI trong app: antd X (Welcome, Prompts, Bubble.List, Sender) + XMarkdown; câu trả lời giả lập stream (app thật: khối lego "ai-assistant"). Dữ liệu lấy từ API của app qua useApiClient(); nhãn và trường theo spec của tôi.Bước tiếp theo
- Chọn component theo việc — biết nên dùng bảng, kanban, lịch hay màn hình bán hàng cho từng việc.
- App đầu tiên — giao cho agent một app thật có database và đăng nhập.