CustomerOrdersPage.tsx 13 KB

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