CustomerOrdersPage.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import { useBusinessView } from "../lib/use-business-view";
  2. import { PageIntro } from "../components/PageIntro";
  3. import { useState, type ReactNode } from "react";
  4. import { ArrowLeft, ArrowRight, CalendarPlus, PencilLine, Plus, RefreshCw, Trash2 } from "lucide-react";
  5. import { Link, useLocation, useNavigate, useParams } from "react-router";
  6. import { Button } from "../components/ui/button";
  7. import { OpsMore, OpsNotice, OpsStatus, type OpsMoreItem } from "../components/OperationsKit";
  8. import { Tri } from "../components/triState";
  9. import { orderView, useOrders, type OrderView } from "../lib/order-demo";
  10. import { WORD_FETCH_FAILED, WORD_NOT_OPENED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
  11. import { rowsOf, orderDelete, orderGetList, customerGet } from "../lib/api/bos";
  12. import { ACCT_STATUS, label } from "../lib/api/labels";
  13. import { useLoad } from "../lib/useLoad";
  14. import { OrderEditor, type OrderEditorContext } from "../components/OrderChangeDialogs";
  15. import { detailBack, detailLinkState } from "../lib/detail-navigation";
  16. import { useHorizontalOverflow } from "../lib/use-horizontal-overflow";
  17. import { ListPager } from "../components/ListPager";
  18. import { LIST_PAGE_SIZE, useLocalPage } from "../lib/list-paging";
  19. import "../styles/operations.css";
  20. const statusTone = (status: string) => status === "生效中" ? "success" : status === "提前停机" ? "danger" : status === "已到期" ? "neutral" : "warning";
  21. /** 三态文本格:键缺失=取数失败,null=未配置,⛔ 用 0/「—」冒充有值。 */
  22. function cell(value: string | null | undefined, missing: string = WORD_UNCONFIGURED) {
  23. if (value === undefined) return <Tri tone="fail" text={WORD_FETCH_FAILED} />;
  24. if (value === null || value === "") return <Tri tone="missing" text={missing} />;
  25. return value;
  26. }
  27. const moneyView = (c: { tone: "val" | "missing" | "fail"; text: string }) =>
  28. (c.tone === "val" ? c.text : <Tri tone={c.tone} text={c.text} title="金额取数失败=接口未下发该键;未配置=后端明确回 null" />);
  29. const exitsView = (exits: string[] | null | undefined) =>
  30. (exits === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : exits === null || !exits.length ? <Tri tone="missing" text={WORD_UNCONFIGURED} /> : exits.join("、"));
  31. export function CustomerOrdersPage() {
  32. const view = useBusinessView([]);
  33. const location = useLocation();
  34. const navigate = useNavigate();
  35. const { no } = useParams();
  36. const param = decodeURIComponent(no ?? "");
  37. const back = detailBack(location.state, param ? `/customers/${encodeURIComponent(param)}` : "/customers", "返回客户档案");
  38. const outgoingState = detailLinkState(location.pathname, location.state);
  39. const tableOverflow = useHorizontalOverflow();
  40. /**
  41. * 客户档案改读真实接口(`/customer/get@v1`)。
  42. *
  43. * ⚠️ 2026-11-18 修(巡检 F-1):此前从 `useBusinessView` 的演示客户 store 反查 ⇒ 页头
  44. * 「客户账户」恒「未配置」、且不渲染「查看客户档案」链接,尽管订阅行都正常。
  45. * 该口是客户侧自读口,行集由后端按主体收窄;运营侧(admin/运主/运子)同样可读。
  46. */
  47. const account = useLoad(() => (param ? customerGet({ customer_id: param }) : Promise.resolve(null)), [param]);
  48. const profile = account.data?.customer ?? null;
  49. const customerName = profile?.customer_name ?? null;
  50. /** 按客户 `get_list` 服务端分页,⛔ page_size=200 再本地切。 */
  51. const customerIdForList = profile?.customer_id || param;
  52. const [listPage, setListPage] = useState(0);
  53. const orders = useOrders(customerIdForList || undefined, { page: listPage, pageSize: LIST_PAGE_SIZE });
  54. const activeProbe = useLoad(
  55. () => (customerIdForList
  56. ? orderGetList({ customer_id: customerIdForList, status: "active", page: 0, page_size: 1 })
  57. : Promise.resolve(null)),
  58. [customerIdForList],
  59. );
  60. const rows = orders.data === undefined || orders.data === null ? [] : rowsOf(orders.data.items).map(orderView);
  61. const listTotal = Number(orders.data?.total ?? rows.length);
  62. const customerId = rows[0]?.customerId || profile?.customer_id || param;
  63. const [context, setContext] = useState<OrderEditorContext | null>(null);
  64. const [confirm, setConfirm] = useState<OrderView | null>(null);
  65. const [deleteBlocked, setDeleteBlocked] = useState("");
  66. const [pendingDelete, setPendingDelete] = useState(false);
  67. const [notice, setNotice] = useState("");
  68. const paging = useLocalPage(listTotal, LIST_PAGE_SIZE, listPage);
  69. const pageRows = rows;
  70. if (orders.loading) return <section className="ops-page"><Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} />{back.label}</Link><div className="ops-empty"><h1>正在从订阅接口读取该客户的订阅…</h1></div></section>;
  71. if (orders.error) return <section className="ops-page"><Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} />{back.label}</Link><div className="ops-empty"><h1>订阅取数失败</h1><p role="alert">{orders.error.message}</p><Button variant="ghost" size="sm" onClick={() => orders.reload()}>重试</Button></div></section>;
  72. const active = Number(activeProbe.data?.total ?? 0);
  73. /** 「分账号额度」汇总=本页订阅行 `quota_slots` 之和(全量汇总需另口;本页如实标本页)。 */
  74. const quotaRows = rows.filter((item) => typeof item.quotaSlots === "number");
  75. const quotaSummary = quotaRows.length
  76. ? quotaRows.reduce((sum, item) => sum + (item.quotaSlots ?? 0), 0)
  77. : <Tri tone="missing" text={WORD_UNCONFIGURED} title="本页订阅行的 quota_slots 均为 null" />;
  78. async function removeOrder() {
  79. if (!confirm) return;
  80. setPendingDelete(true);
  81. setDeleteBlocked("");
  82. try {
  83. const result = await orderDelete({ subscription_id: confirm.no });
  84. if (result && result.deleted === false) setDeleteBlocked("服务端未删除本条订阅(应答未给出原因);是否仍被引用由服务端判定,页面不自行放行。");
  85. else { setConfirm(null); setNotice("订阅已删除。"); orders.reload(); }
  86. } catch (cause) {
  87. setDeleteBlocked((cause as Error).message);
  88. } finally {
  89. setPendingDelete(false);
  90. }
  91. }
  92. return <section className="ops-page customer-sub-page page-fill">
  93. <Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} />{back.label}</Link>
  94. <header className="ops-heading"><div><h1>套餐订阅管理</h1><PageIntro>{view.readOnly ? "核对这家客户订了哪些套餐,以及服务何时到期。" : "客户需要开通新服务、调整套餐或叠加订阅时,在这里办理。"}</PageIntro><p>{customerName ?? cell(rows[0]?.customer)} · {customerId}</p></div>{!view.readOnly && <Button onClick={() => setContext({ mode: "new" })}><Plus size={16} />新增订阅</Button>}</header>
  95. <div className="customer-sub-overview"><div><span>客户账户</span>{profile
  96. ? <OpsStatus tone={profile.acct_status === "in_use" || profile.acct_status === "normal" ? "success" : profile.acct_status === "stopped" || profile.acct_status === "disabled" ? "danger" : "warning"}>{label(ACCT_STATUS, profile.acct_status)}</OpsStatus>
  97. : account.error
  98. ? <Tri tone="fail" text={WORD_FETCH_FAILED} title={`/customer/get@v1 取数失败:${account.error.message}`} />
  99. : account.loading
  100. ? <span className="ops-muted">读取中…</span>
  101. : <Tri tone="missing" text={WORD_UNCONFIGURED} title="客户档案未关联到该客户主键(后端回 null)" />}</div><div><span>全部订阅</span><strong>{listTotal}</strong></div><div><span>生效中</span><strong>{active}</strong></div><div><span>分账号额度</span><strong title="本页订阅 quota_slots 之和">{quotaSummary}</strong></div>{profile && <Link className="ops-card-link" to={`/customers/${profile.customer_id}`} state={outgoingState}>查看客户档案 <ArrowRight size={15} /></Link>}</div>
  102. <div className="ops-list-shell list-shell-fill">
  103. <div ref={tableOverflow.ref} className={`measured-table-scroll ops-table-wrap${tableOverflow.overflow ? " has-horizontal-overflow" : ""}`}><table className="ops-table customer-sub-table"><colgroup>{Array.from({ length: 9 }, (_, index) => <col key={index} />)}</colgroup><thead><tr><th>套餐 / 合同 / 订单号</th><th>线路出口</th><th>方式</th><th>状态</th><th>合同期间</th><th>订阅价格</th><th>月结算标准</th><th>实际开通日</th><th>操作</th></tr></thead><tbody>{pageRows.map((item) => {
  104. const canUpdown = item.statusLabel === "生效中";
  105. const orderActions: { key: string; label: string; icon: ReactNode; danger?: boolean; info?: boolean; show: boolean; onSelect: () => void }[] = [
  106. { key: "view", label: "详情", icon: null, info: false, show: true, onSelect: () => navigate(`/orders/${encodeURIComponent(item.no)}`, { state: outgoingState }) },
  107. { key: "updown", label: "升降配", icon: <RefreshCw size={15} />, show: canUpdown, onSelect: () => setContext({ mode: "updown", record: item }) },
  108. // D-03:叠加=新建并存订阅(原订阅不动),走 create@v1;⛔ 再开「就地改结束日」的 StackEditor。
  109. { key: "stack", label: "叠加", icon: <CalendarPlus size={15} />, show: canUpdown, onSelect: () => setContext({ mode: "new" }) },
  110. { key: "edit", label: "编辑", icon: <PencilLine size={15} />, show: item.editable === true, onSelect: () => setContext({ mode: "edit", record: item }) },
  111. { key: "delete", label: "删除", icon: <Trash2 size={15} />, danger: true, show: true, onSelect: () => { setDeleteBlocked(""); setConfirm(item); } },
  112. ];
  113. const shown = orderActions.filter((action) => action.show && (!view.readOnly || action.key === "view"));
  114. /**
  115. * 行内只留「详情」;升降配/叠加改收进「更多」菜单——台账一行九列,
  116. * 三颗按钮直出会把操作列挤到换行,且升降配要动合同与档位,误点成本高。
  117. */
  118. const visible = shown.filter((action) => action.key === "view");
  119. const moreItems: OpsMoreItem[] = shown.filter((action) => action.key !== "view").map(({ key, label, icon, onSelect, danger }) => ({ key, label, icon, onSelect, ...(danger ? { title: "删除订阅(服务端按引用关系判定)" } : {}) }));
  120. return <tr key={item.no}><td title={`${item.planName ?? WORD_UNCONFIGURED} · ${item.contractNo ?? WORD_UNCONFIGURED} · ${item.orderNo ?? "无订单号"}`}><strong>{cell(item.planName)}</strong><small>{cell(item.contractNo)} · {cell(item.orderNo, "无订单号")}</small></td><td title={item.exits?.join("、") ?? ""}>{exitsView(item.exits)}</td><td>{cell(item.modeLabel)}</td><td>{item.statusLabel ? <OpsStatus tone={statusTone(item.statusLabel)}>{item.statusLabel}</OpsStatus> : <Tri tone="fail" text={WORD_FETCH_FAILED} title="订阅状态编码未下发" />}{item.replacedBy && <small>已被 {item.replacedBy.subscription_id} 替换</small>}</td><td title={`${item.start ?? WORD_UNCONFIGURED} 至 ${item.end ?? WORD_UNCONFIGURED}`}><strong className="customer-sub-date">{cell(item.start)}</strong><small>至 {cell(item.end)}</small></td><td><strong>{moneyView(item.annual)}</strong></td><td>{moneyView(item.settle)}</td><td title={item.openedOn ?? WORD_NOT_OPENED}><span className="customer-sub-date">{item.openedOn === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : item.openedOn || <Tri tone="missing" text={WORD_NOT_OPENED} />}</span></td><td><div className="ops-inline-actions">{visible.map((action) => <button key={action.key} type="button" className={[action.danger && "is-danger", action.info && "is-info"].filter(Boolean).join(" ") || undefined} onClick={(event) => { event.stopPropagation(); action.onSelect(); }}>{action.key === "view" ? action.label : <>{action.icon}{action.label}</>}</button>)}<OpsMore items={moreItems} placeholder /></div></td></tr>;
  121. })}</tbody></table></div>
  122. <ListPager total={listTotal} page={paging.safePage} pageSize={paging.pageSize} onPageChange={setListPage} unit="条" className="list-pager" />
  123. {!rows.length && !orders.loading && <div className="ops-empty"><h3>还没有订阅</h3><p>先为客户登记一份合同,再新增套餐订阅。</p></div>}
  124. </div>
  125. {context && <OrderEditor key={`${context.mode}-${context.record?.no ?? "new"}`} customerId={customerId} customerName={customerName ?? rows[0]?.customer ?? customerId} context={context} onClose={() => setContext(null)} onSaved={(message) => { setContext(null); setNotice(message); setListPage(0); orders.reload(); }} />}
  126. {confirm && <div className="ops-confirm-backdrop"><div className="ops-confirm" role="alertdialog" aria-modal="true" aria-labelledby="customer-sub-confirm-title"><h2 id="customer-sub-confirm-title">删除订阅?</h2><p>{confirm.planName ?? WORD_UNCONFIGURED} · {confirm.no}。是否可删除由服务端按引用关系判定,页面不自行放行。</p>{deleteBlocked && <p className="ops-form-error" role="alert">{deleteBlocked}</p>}<div><Button variant="outline" onClick={() => { setConfirm(null); setDeleteBlocked(""); }}>取消</Button><Button variant="destructive" disabled={pendingDelete} onClick={removeOrder}>{pendingDelete ? "提交中…" : "确认删除"}</Button></div></div></div>}
  127. {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
  128. </section>;
  129. }