| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149 |
- import { FilterSelect } from "../components/ui/filter-select";
- import { useMemo, useState } from "react";
- import { Plus, Search, Trash2, X, CalendarClock } from "lucide-react";
- import { useLocation, useNavigate, useSearchParams } from "react-router";
- import { Button } from "../components/ui/button";
- import { SearchInput } from "../components/ui/search-input";
- import {
- contractExitsOf, contractFromRow,
- contractStatusOf, contractStatusTone, useContracts, type ContractRowView,
- } from "../lib/contract-demo";
- import { OpsResponsiveActions, OpsNotice, OpsStatus, OpsTableEmpty, OpsTableColumns } from "../components/OperationsKit";
- import { contractDelete, rowsOf } from "../lib/api/bos";
- import { ApiError } from "../lib/api/http";
- import { WORD_NOT_PROVIDED, WORD_FETCH_FAILED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
- import { Tri } from "../components/triState";
- import { useCatalogPlans } from "../lib/package-catalog";
- import { useHorizontalOverflow } from "../lib/use-horizontal-overflow";
- import { useBusinessView } from "../lib/use-business-view";
- import { EXPIRING_SOON_DAYS, expiringLabel, isExpiringSoon } from "../lib/expiring-soon";
- import { ListPager } from "../components/ListPager";
- import { LIST_PAGE_SIZE, slicePage, useLocalPage } from "../lib/list-paging";
- import "../styles/operations.css";
- /** 文本格三态:后端未下发该键=取数失败,下发 null=未配置,⛔ 显示「—」当空值兜底。 */
- const textCell = (value: string | null | undefined) =>
- value === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : value === null || value === "" ? <Tri tone="missing" text={WORD_UNCONFIGURED} /> : value;
- const d = (value: string) => value.replaceAll("-", ".");
- export function ContractManagementPage() {
- const tableOverflow = useHorizontalOverflow();
- // 操作列为固定像素宽,其余六列按阅读需求分配剩余宽度;容器宽度变化时同步重算。
- const expandedActions = tableOverflow.width >= 1850;
- const actionWidth = expandedActions ? 224 : 148;
- const flexibleWidth = Math.max(1080, tableOverflow.width) - actionWidth;
- const columnWidths = [.231, .179, .179, .154, .115, .142].map((weight) => flexibleWidth * weight).concat(actionWidth);
- const navigate = useNavigate();
- const location = useLocation();
- const view = useBusinessView([]);
- const [params, setParams] = useSearchParams();
- 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 }); }
- const contracts = useContracts();
- const catalog = useCatalogPlans();
- /** 套餐式条目的分账号额度=目录额度 × 数量,目录未取到=未配置,⛔ 计 0。 */
- const quotaById = useMemo(() => Object.fromEntries(rowsOf(catalog.data?.items).map((plan) => [plan.plan_id, plan.sub_account_quota])), [catalog.data]);
- const records = useMemo(() => rowsOf(contracts.data?.items).map((row) => contractFromRow(row, quotaById)), [contracts.data, quotaById]);
- const [failure, setFailure] = useState("");
- const status = params.get("status") || "全部";
- const setStatus = (value: string) => filter("status", value === "全部" ? "" : value);
- const exit = params.get("exit") || "";
- const setExit = (value: string) => filter("exit", value);
- const source = params.get("source") || "全部来源";
- const setSource = (value: string) => filter("source", value === "全部来源" ? "" : value);
- const search = params.get("q") || "";
- const setSearch = (value: string) => filter("q", value);
- /** 快到期快捷筛选(2026-11-17 四轮):勾上=只看「合同止期在 30 天内」的合同。 */
- const expiring = params.get("expiring") === "1";
- const setExpiring = (on: boolean) => filter("expiring", on ? "1" : "");
- const [deleteId, setDeleteId] = useState<string | null>(null);
- const [notice, setNotice] = useState("");
- const [deleting, setDeleting] = useState(false);
- const deleteTarget = records.find((item) => item.contractId === deleteId) ?? null;
- /** 状态只由生效日/结束日推导;期间未配置时状态不可判,⛔ 猜一个。 */
- const statusOf = (item: ContractRowView) => item.periodState === "val" ? contractStatusOf(item.start, item.end) : null;
- async function removeContract() {
- if (view.readOnly || !deleteTarget?.contractId) return;
- setDeleting(true);
- try {
- const result = await contractDelete({ contract_id: deleteTarget.contractId });
- setDeleteId(null);
- setFailure("");
- setNotice(result?.deleted ? `合同 ${deleteTarget.no} 已删除。` : `未能删除:合同仍被订阅或工单引用。`);
- contracts.reload();
- } catch (e) {
- setDeleteId(null);
- setNotice("");
- setFailure(e instanceof ApiError ? e.message : "删除失败,请稍后重试。");
- contracts.reload();
- } finally {
- setDeleting(false);
- }
- }
- /** 操作人/客户范围由服务端裁剪:后端未提供范围接口,页面⛔ 用本地客户档案二次裁剪。 */
- const scopedRecords = records;
- const exits = [...new Set(scopedRecords.flatMap((item) => contractExitsOf(item.items)))].sort();
- const sources = [...new Set(scopedRecords.map((item) => item.source).filter((item): item is string => Boolean(item)))];
- const filtered = useMemo(() => scopedRecords.filter((item) =>
- (status === "全部" || statusOf(item) === status) &&
- (!expiring || isExpiringSoon(item.end)) &&
- (exit === "" || contractExitsOf(item.items).includes(exit)) &&
- (source === "全部来源" || item.source === source) &&
- `${item.no} ${item.customer} ${item.extNo} ${item.agent} ${item.items.map((child) => child.type === "套餐" ? child.pkg : "").join(" ")}`.toLowerCase().includes(search.trim().toLowerCase()),
- ), [scopedRecords, status, expiring, exit, source, search]);
- /** 快到期计数:按「状态/出口/来源/搜索」已筛出的集合再算,⛔ 拿全量算(否则与列表数量对不上)。 */
- const expiringCount = useMemo(() => scopedRecords.filter((item) => isExpiringSoon(item.end)).length, [scopedRecords]);
- // D-CT-13:页码与筛选同等写 URL(0 基;缺省/第 0 页不写,刷新/从详情返回可复位)。
- const pageFromUrl = Math.max(0, Number.parseInt(params.get("page") || "0", 10) || 0);
- const paging = useLocalPage(filtered.length, LIST_PAGE_SIZE, pageFromUrl);
- const setPage = (next: number) => {
- const safe = Math.max(0, next);
- filter("page", safe > 0 ? String(safe) : "");
- };
- const resetPage = () => filter("page", "");
- const pageRows = slicePage(filtered, paging.safePage);
- const hasFilter = status !== "全部" || expiring || exit !== "" || source !== "全部来源" || search !== "" || pageFromUrl > 0;
- function reset() { setParams({}); }
- return <section className="ops-page ops-page--contracts page-fill page-fill-window">
- <header className="ops-heading"><div><p className="ops-eyebrow"><span /> CONTRACTS / 客户与订阅</p><h1>{view.contractListTitle}</h1></div>{!view.readOnly && <Button onClick={() => navigate("/contracts/new")}><Plus size={16} />新增合同</Button>}</header>
- <div className="ops-list-shell list-shell-fill">
- <div className="ops-toolbar">
- <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>
- <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>
- {/* 快到期快捷筛选(2026-11-17 四轮):一键只看 30 天内到期的合同,计数随取数实时变。 */}
- <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>
- <FilterSelect icon="exit" aria-label="线路出口筛选" value={exit} onChange={(event) => { setExit(event.target.value); resetPage(); }}><option value="">全部出口</option>{exits.map((item) => <option key={item}>{item}</option>)}</FilterSelect>
- <FilterSelect icon="source" aria-label="来源筛选" value={source} onChange={(event) => { setSource(event.target.value); resetPage(); }}><option>全部来源</option>{[...new Set(["运营商同步", "界面录入", "批量导入", ...sources])].map((item) => <option key={item}>{item}</option>)}</FilterSelect>
- {hasFilter && <Button variant="ghost" size="sm" onClick={reset}>重置筛选</Button>}
- </div>
- <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) => {
- const state = statusOf(item);
- const link = encodeURIComponent(item.contractId || item.no);
- /**
- * 快到期(2026-11-17 四轮):合同止期在 30 天内 ⇒ 行内直接给「续签」入口,
- * 不必先记住客户名再到新增合同页里翻下拉。判据与筛选同源(`isExpiringSoon`)。
- */
- const expiringRow = isExpiringSoon(item.end);
- const renewContractId = item.contractId ?? "";
- 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 } }); }}>
- <td><strong 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>
- <td title={item.extNo || undefined}>{item.extNo ? <span className="ops-mono">{item.extNo}</span> : "—"}</td>
- <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>
- <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>
- <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>
- <td><strong>{item.agent || WORD_UNCONFIGURED}</strong><small>{item.agentPhone || WORD_UNCONFIGURED}</small></td>
- <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={[
- ...(expiringRow && renewContractId ? [{ label: "续签合同", shortLabel: "续签", icon: <CalendarClock size={15} />, title: "按旧合同带入金额、服务期、服务条目与新的生效日(旧止期次日),生成新合同;不替换原订阅", onSelect: () => navigate(`/contracts/new?renew=${encodeURIComponent(renewContractId)}`) }] : []),
- { label: "删除合同", shortLabel: "删除", danger: true, icon: <Trash2 size={15} />, title: "引用拦截由服务端判定,删除后不可恢复", onSelect: () => setDeleteId(item.contractId ?? item.no) },
- ]} />}</div></td>
- </tr>;
- })}{!filtered.length && <OpsTableEmpty colSpan={7}>{contracts.error ? <>合同台账取数失败:{contracts.error.message}</> : contracts.loading ? "正在从合同接口读取台账…" : expiring ? `没有 ${EXPIRING_SOON_DAYS} 天内到期的合同。` : "没有符合筛选条件的合同。"}</OpsTableEmpty>}</tbody></table></div>
- <ListPager total={filtered.length} page={paging.safePage} pageSize={paging.pageSize} onPageChange={setPage} unit="条" />
- </div>
- {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>}
- {failure && <p className="ops-form-error" role="alert">{failure}</p>}
- {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
- </section>;
- }
|