ContractManagementPage.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import { FilterSelect } from "../components/ui/filter-select";
  2. import { PageIntro } from "../components/PageIntro";
  3. import { useEffect, useMemo, useState } from "react";
  4. import { Plus, Search, Trash2, X, CalendarClock } from "lucide-react";
  5. import { useLocation, useNavigate, useSearchParams } from "react-router";
  6. import { Button } from "../components/ui/button";
  7. import { SearchInput } from "../components/ui/search-input";
  8. import {
  9. contractFromRow,
  10. contractStatusOf, contractStatusTone, useContractLedger, type ContractRowView,
  11. } from "../lib/contract-demo";
  12. import { OpsResponsiveActions, OpsNotice, OpsStatus, OpsTableEmpty, OpsTableColumns } from "../components/OperationsKit";
  13. import { contractDelete, rowsOf } from "../lib/api/bos";
  14. import { ApiError } from "../lib/api/http";
  15. import { WORD_NOT_PROVIDED, WORD_FETCH_FAILED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
  16. import { Tri } from "../components/triState";
  17. import { useHorizontalOverflow } from "../lib/use-horizontal-overflow";
  18. import { useBusinessView } from "../lib/use-business-view";
  19. import { useLineExits } from "../lib/package-catalog";
  20. import { EXPIRING_SOON_DAYS, expiringLabel, isExpiringSoon } from "../lib/expiring-soon";
  21. import { ListPager } from "../components/ListPager";
  22. import { LIST_PAGE_SIZE, useLocalPage } from "../lib/list-paging";
  23. import "../styles/operations.css";
  24. const SOURCE_OPTIONS = ["运营商同步", "界面录入", "批量导入"] as const;
  25. /** 文本格三态:后端未下发该键=取数失败,下发 null=未配置,⛔ 显示「—」当空值兜底。 */
  26. const textCell = (value: string | null | undefined) =>
  27. value === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : value === null || value === "" ? <Tri tone="missing" text={WORD_UNCONFIGURED} /> : value;
  28. const d = (value: string) => value.replaceAll("-", ".");
  29. export function ContractManagementPage() {
  30. const tableOverflow = useHorizontalOverflow();
  31. // 操作列为固定像素宽,其余六列按阅读需求分配剩余宽度;容器宽度变化时同步重算。
  32. const expandedActions = tableOverflow.width >= 1850;
  33. const actionWidth = expandedActions ? 224 : 148;
  34. const flexibleWidth = Math.max(1080, tableOverflow.width) - actionWidth;
  35. const columnWidths = [.231, .179, .179, .154, .115, .142].map((weight) => flexibleWidth * weight).concat(actionWidth);
  36. const navigate = useNavigate();
  37. const location = useLocation();
  38. const view = useBusinessView([]);
  39. const [params, setParams] = useSearchParams();
  40. function filter(key: string, value: string) { setParams((current) => { const next = new URLSearchParams(current); if (value) next.set(key, value); else next.delete(key); return next; }, { replace: true }); }
  41. const [failure, setFailure] = useState("");
  42. const status = params.get("status") || "全部";
  43. const setStatus = (value: string) => filter("status", value === "全部" ? "" : value);
  44. const exit = params.get("exit") || "";
  45. const setExit = (value: string) => filter("exit", value);
  46. const source = params.get("source") || "全部来源";
  47. const setSource = (value: string) => filter("source", value === "全部来源" ? "" : value);
  48. const search = params.get("q") || "";
  49. const setSearch = (value: string) => filter("q", value);
  50. /** 快到期快捷筛选(2026-11-17 四轮):勾上=只看「合同止期在 30 天内」的合同。 */
  51. const expiring = params.get("expiring") === "1";
  52. const setExpiring = (on: boolean) => filter("expiring", on ? "1" : "");
  53. // D-CT-13:页码与筛选同等写 URL(0 基;缺省/第 0 页不写,刷新/从详情返回可复位)。
  54. const pageFromUrl = Math.max(0, Number.parseInt(params.get("page") || "0", 10) || 0);
  55. /** 关键字防抖后下推服务端(本地再筛关键字会与服务端分页打架)。 */
  56. const [searchQuery, setSearchQuery] = useState(search.trim());
  57. useEffect(() => {
  58. const timer = window.setTimeout(() => setSearchQuery(search.trim()), 300);
  59. return () => window.clearTimeout(timer);
  60. }, [search]);
  61. const contracts = useContractLedger({
  62. keyword: searchQuery || undefined,
  63. status: status === "全部" ? undefined : status,
  64. source: source === "全部来源" ? undefined : source,
  65. lineExit: exit || undefined,
  66. expiringWithinDays: expiring ? EXPIRING_SOON_DAYS : undefined,
  67. page: pageFromUrl,
  68. pageSize: LIST_PAGE_SIZE,
  69. });
  70. /**
  71. * 线路出口下拉:进页不预拉(`line_exit/get_list` 含引用面全表扫,墙钟常 > 数百 ms)。
  72. * URL 已带 exit=需要选项回显;否则等用户点开筛选项再拉。
  73. */
  74. const [exitsNeeded, setExitsNeeded] = useState(() => Boolean(exit));
  75. const exitsLoad = useLineExits({ enabled: exitsNeeded });
  76. /** 额度取自列表条目 JOIN 的 `sub_account_quota`,⛔ 再打 catalog/get_list。 */
  77. const records = useMemo(() => rowsOf(contracts.data?.items).map((row) => contractFromRow(row)), [contracts.data]);
  78. const [deleteId, setDeleteId] = useState<string | null>(null);
  79. const [notice, setNotice] = useState("");
  80. const [deleting, setDeleting] = useState(false);
  81. const deleteTarget = records.find((item) => item.contractId === deleteId) ?? null;
  82. /** 状态只由生效日/结束日推导;期间未配置时状态不可判,⛔ 猜一个。 */
  83. const statusOf = (item: ContractRowView) => item.periodState === "val" ? contractStatusOf(item.start, item.end) : null;
  84. async function removeContract() {
  85. if (view.readOnly || !deleteTarget?.contractId) return;
  86. setDeleting(true);
  87. try {
  88. const result = await contractDelete({ contract_id: deleteTarget.contractId });
  89. setDeleteId(null);
  90. setFailure("");
  91. setNotice(result?.deleted ? `合同 ${deleteTarget.no} 已删除。` : `未能删除:合同仍被订阅或工单引用。`);
  92. contracts.reload();
  93. } catch (e) {
  94. setDeleteId(null);
  95. setNotice("");
  96. setFailure(e instanceof ApiError ? e.message : "删除失败,请稍后重试。");
  97. contracts.reload();
  98. } finally {
  99. setDeleting(false);
  100. }
  101. }
  102. const exits = useMemo(
  103. () => (exitsLoad.data?.items ?? []).map((item) => item.exit_name).filter(Boolean).sort(),
  104. [exitsLoad.data],
  105. );
  106. const listTotal = Number(contracts.data?.total ?? records.length);
  107. /** 快到期角标:只在已勾选快到期时用本页 total(⛔ 再打一次 page_size=1 探针)。 */
  108. const expiringCount = expiring ? listTotal : 0;
  109. const paging = useLocalPage(listTotal, LIST_PAGE_SIZE, pageFromUrl);
  110. const setPage = (next: number) => {
  111. const safe = Math.max(0, next);
  112. filter("page", safe > 0 ? String(safe) : "");
  113. };
  114. const resetPage = () => filter("page", "");
  115. const pageRows = records;
  116. const hasFilter = status !== "全部" || expiring || exit !== "" || source !== "全部来源" || search !== "" || pageFromUrl > 0;
  117. function reset() { setParams({}); }
  118. return <section className="ops-page ops-page--contracts page-fill page-fill-window">
  119. <header className="ops-heading"><div><p className="ops-eyebrow"><span /> CONTRACTS / 客户与订阅</p><h1>{view.contractListTitle}</h1><PageIntro>{view.readOnly ? "按客户查找合同,核对服务何时开始、何时到期。" : "登记客户签约信息,跟进从服务开通到合同到期的进度。"}</PageIntro></div>{!view.readOnly && <Button onClick={() => navigate("/contracts/new")}><Plus size={16} />新增合同</Button>}</header>
  120. <div className="ops-list-shell list-shell-fill">
  121. <div className="ops-toolbar">
  122. <label className="ops-search"><Search size={17} /><SearchInput aria-label="搜索合同" placeholder="搜索编号、客户、外部单号、经办人或套餐名" value={search} onCommit={(value) => { setSearch(value); resetPage(); }} />{search && <button type="button" aria-label="清空搜索" onClick={() => { setSearch(""); resetPage(); }}><X size={15} /></button>}</label>
  123. <FilterSelect icon="status" aria-label="合同状态筛选" value={status} onChange={(event) => { setStatus(event.target.value as typeof status); resetPage(); }}><option value="全部">全部状态</option><option>待生效</option><option>生效中</option><option>已到期</option></FilterSelect>
  124. {/* 快到期快捷筛选(2026-11-17 四轮):一键只看 30 天内到期的合同,计数随取数实时变。 */}
  125. <Button variant={expiring ? "default" : "outline"} size="sm" aria-pressed={expiring} title={`只看合同止期在 ${EXPIRING_SOON_DAYS} 天内的合同(已到期的不算)`} onClick={() => { setExpiring(!expiring); resetPage(); }}><CalendarClock size={15} />快到期 {EXPIRING_SOON_DAYS} 天内{expiringCount ? `(${expiringCount})` : ""}</Button>
  126. <FilterSelect
  127. icon="exit"
  128. aria-label="线路出口筛选"
  129. value={exit}
  130. onPointerDown={() => setExitsNeeded(true)}
  131. onFocus={() => setExitsNeeded(true)}
  132. onChange={(event) => { setExit(event.target.value); resetPage(); }}
  133. >
  134. <option value="">{exitsNeeded && exitsLoad.loading && !exitsLoad.data ? "载入出口…" : "全部出口"}</option>
  135. {exit && !exits.includes(exit) ? <option value={exit}>{exit}</option> : null}
  136. {exits.map((item) => <option key={item}>{item}</option>)}
  137. </FilterSelect>
  138. <FilterSelect icon="source" aria-label="来源筛选" value={source} onChange={(event) => { setSource(event.target.value); resetPage(); }}><option>全部来源</option>{SOURCE_OPTIONS.map((item) => <option key={item}>{item}</option>)}</FilterSelect>
  139. {hasFilter && <Button variant="ghost" size="sm" onClick={reset}>重置筛选</Button>}
  140. </div>
  141. <div ref={tableOverflow.ref} tabIndex={0} role="region" aria-label="合同台账,可横向滚动查看字段" className={`measured-table-scroll ops-table-wrap contract-table-scroll${tableOverflow.overflow ? " has-horizontal-overflow" : ""}${tableOverflow.canScrollLeft ? " can-scroll-left" : ""}${tableOverflow.canScrollRight ? " can-scroll-right" : ""}`}><table className="ops-table ops-clickable-table contract-ledger"><OpsTableColumns widths={columnWidths} /><thead><tr><th>合同 / 客户</th><th>外部单号</th><th>状态 / 期间</th><th>是否已开通</th><th>总额 / 服务期</th><th>经办人</th><th>操作</th></tr></thead><tbody>{pageRows.map((item) => {
  142. const state = statusOf(item);
  143. const link = encodeURIComponent(item.contractId || item.no);
  144. /**
  145. * 快到期(2026-11-17 四轮):合同止期在 30 天内 ⇒ 行内直接给「续签」入口,
  146. * 不必先记住客户名再到新增合同页里翻下拉。判据与筛选同源(`isExpiringSoon`)。
  147. */
  148. const expiringRow = isExpiringSoon(item.end);
  149. const renewContractId = item.contractId ?? "";
  150. return <tr key={item.contractId || item.no} tabIndex={0} aria-label={`查看合同 ${item.no}`} onClick={() => navigate(`/contracts/${link}`, { state: { from: location.pathname + location.search } })} onKeyDown={(event) => { if (event.key === "Enter" && event.target === event.currentTarget) navigate(`/contracts/${link}`, { state: { from: location.pathname + location.search } }); }}>
  151. <td><strong className="table-cell-title" title={item.no}>{item.no || WORD_UNCONFIGURED}</strong><small title={`${item.customer} · ${item.source ?? ""}`}>{item.customer || WORD_UNCONFIGURED} · {item.contractType || "新建"} · {item.source === undefined ? <Tri tone="missing" text={WORD_NOT_PROVIDED} title="后端合同读口未返回 source 列(服务版本落后于 20261115000002 迁移)——如实标未下发,不填 manual 冒充" /> : textCell(item.source)}</small></td>
  152. <td title={item.extNo || undefined}>{item.extNo ? <span className="ops-mono">{item.extNo}</span> : "—"}</td>
  153. <td>{state ? <OpsStatus tone={contractStatusTone[state]}>{state}</OpsStatus> : <Tri tone={item.periodState === "fail" ? "fail" : "missing"} text={item.periodState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} title="缺少生效日或结束日,状态不可判" />}{expiringRow && <OpsStatus tone="warning">快到期 · {expiringLabel(item.end)}</OpsStatus>}<small>{item.periodState === "val" ? `${d(item.start)} 至 ${d(item.end)}` : <Tri tone={item.periodState === "fail" ? "fail" : "missing"} text={item.periodState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}</small></td>
  154. <td>{item.opened === undefined || item.opened === null ? <Tri tone={item.opened === undefined ? "fail" : "missing"} text={item.opened === undefined ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} title="是否已开通取关联工单回填,取数失败只坏本列" /> : <OpsStatus tone={item.opened ? "success" : "warning"}>{item.opened ? "已开通" : "未开通"}</OpsStatus>}<small>实际开通日 {item.openedOn ? d(item.openedOn) : "未回填"}</small></td>
  155. <td>{item.amountState === "val" ? <span className="ops-money">¥{item.amount.toLocaleString("zh-CN")}</span> : <Tri tone={item.amountState === "fail" ? "fail" : "missing"} text={item.amountState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}<small>{item.serviceMonthsState === "val" ? `服务期 ${item.serviceMonths} 个月` : <Tri tone={item.serviceMonthsState === "fail" ? "fail" : "missing"} text={item.serviceMonthsState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} />}</small></td>
  156. <td><strong>{item.agent || WORD_UNCONFIGURED}</strong><small>{item.agentPhone || WORD_UNCONFIGURED}</small></td>
  157. <td><div className="ops-inline-actions"><button type="button" onClick={(event) => { event.stopPropagation(); navigate(`/contracts/${link}`, { state: { from: location.pathname + location.search } }); }}>详情</button>{!view.readOnly && <OpsResponsiveActions expanded={expandedActions} items={[
  158. ...(expiringRow && renewContractId ? [{ label: "续签合同", shortLabel: "续签", icon: <CalendarClock size={15} />, title: "按旧合同带入金额、服务期、服务条目与新的生效日(旧止期次日),生成新合同;不替换原订阅", onSelect: () => navigate(`/contracts/new?renew=${encodeURIComponent(renewContractId)}`) }] : []),
  159. { label: "删除合同", shortLabel: "删除", danger: true, icon: <Trash2 size={15} />, title: "引用拦截由服务端判定,删除后不可恢复", onSelect: () => setDeleteId(item.contractId ?? item.no) },
  160. ]} />}</div></td>
  161. </tr>;
  162. })}{!pageRows.length && <OpsTableEmpty colSpan={7}>{contracts.error ? <>合同台账取数失败:{contracts.error.message}</> : contracts.loading ? "正在从合同接口读取台账…" : expiring ? `没有 ${EXPIRING_SOON_DAYS} 天内到期的合同。` : "没有符合筛选条件的合同。"}</OpsTableEmpty>}</tbody></table></div>
  163. <ListPager total={listTotal} page={paging.safePage} pageSize={paging.pageSize} onPageChange={setPage} unit="条" />
  164. </div>
  165. {deleteTarget && <div className="ops-confirm-backdrop" role="presentation"><div className="ops-confirm" role="alertdialog" aria-modal="true" aria-labelledby="contract-delete-title"><h2 id="contract-delete-title">删除合同 {deleteTarget.no}?</h2><p>删除请求提交服务端判定:被订阅或工单引用的合同不会被删除。此操作无法撤销。</p><div><Button variant="outline" onClick={() => setDeleteId(null)}>取消</Button><Button variant="destructive" disabled={deleting} onClick={removeContract}>{deleting ? "正在删除…" : "确认删除"}</Button></div></div></div>}
  166. {failure && <p className="ops-form-error" role="alert">{failure}</p>}
  167. {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
  168. </section>;
  169. }