ContractManagementPage.tsx 16 KB

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