| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812 |
- import { useEffect, useMemo, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
- import { AlertTriangle, ArrowLeft, ArrowRight, Building2, CalendarClock, Check, FileSignature, FileText, Lock, PencilLine, Plus, RefreshCcw, Trash2, X } from "lucide-react";
- import { FetchError } from "../components/fetchError";
- import { Link, useLocation, useNavigate, useParams } from "react-router";
- import { Button } from "../components/ui/button";
- import { Input } from "../components/ui/input";
- import { FieldHint } from "../components/ui/field-hint";
- import { OpsNotice, OpsStatus, OpsTag, OpsTableEmpty } from "../components/OperationsKit";
- import { ListPager } from "../components/ListPager";
- import { ReferenceDrawer, type RefTarget } from "../components/ReferenceDrawer";
- import { RecordTabs } from "../components/RecordTabs";
- import { Tri } from "../components/triState";
- import { contractFromDetail, contractRawByParam, contractSourceTone, contractStatusOf, contractStatusTone, useContracts } from "../lib/contract-demo";
- import { contractUpdate, contractChangeLog, rowsOf } from "../lib/api/bos";
- import { ticketList, statusLabel, typeLabel } from "../lib/api/ticket";
- import { fmtDate } from "../lib/ticket";
- import { isImeComposing } from "../lib/ime";
- import { ApiError } from "../lib/api/http";
- import { ITEM_FAMILY, label, SUBJECT_TYPE, ORDER_MODE, ORDER_STATUS } from "../lib/api/labels";
- import { WORD_NOT_PROVIDED, WORD_FETCH_FAILED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
- import { useCatalogPlans, useLineExits } from "../lib/package-catalog";
- import { useLoad } from "../lib/useLoad";
- import { LIST_PAGE_SIZE } from "../lib/list-paging";
- import { useBusinessView } from "../lib/use-business-view";
- import { detailBack, detailLinkState } from "../lib/detail-navigation";
- import { LINE_EXIT_MAX } from "../domain/contract-items";
- import type { ContractMissing } from "../domain/contract-items";
- import { CONTRACT_AMOUNT_DERIVED, CONTRACT_END_DERIVED, CONTRACT_TYPE_LABEL, REQUIRED_KEY_BY_DRAFT, buildContractWrite, changedWriteFields, contractEndFromMonths, deriveContractAmount, draftFromRow, emptyItem, frozenChanges, itemSubtreeKeys, itemTree, parseDiscountRate, type ContractDraft, type ItemDraft } from "../domain/contract-draft";
- import { changeLogFields, changeLogSummary, formatLogTime } from "../lib/contract-audit";
- import { attachmentKindOf, contractAttachmentLabel } from "../lib/contract-attachments";
- import { expiringLabel, isExpiringSoon } from "../lib/expiring-soon";
- import { lockIfCandidate, operationsTeamDisplay, regionAncestorChain, teamsCoveringRegion } from "../lib/region-ownership";
- import type { ContractChangeLogItem, ContractReplacementResult } from "../lib/api/types";
- import "../styles/operations.css";
- const money = (value: number | string) => `¥${Number(value).toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
- /** 三态文本格:字段缺失=取数失败,null=未配置,⛔ 用 0/「—」冒充有值。 */
- const cell = (value: string | number | null | undefined, format: (v: string | number) => string = String) =>
- value === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : value === null || value === "" ? <Tri tone="missing" text={WORD_UNCONFIGURED} /> : format(value);
- /** 关联订阅状态:后端下发 `subscription.status` 原值(`active`/`pending`/`expired`)。 */
- const orderEffective = (status?: string | null) =>
- status === "active" || status === "EFFECTIVE" || status === "生效中";
- type ContractTab = "overview" | "services" | "subscriptions" | "tickets" | "billing" | "history";
- type InlineFieldProps = {
- id: string;
- label: string;
- value: string;
- editing: boolean;
- writable: boolean;
- onStart: () => void;
- onChange: (value: string) => void;
- onDone: () => void;
- onCancel: () => void;
- type?: "text" | "date" | "number";
- inputMode?: "decimal" | "numeric" | "text";
- min?: number;
- max?: number;
- step?: number | string;
- placeholder?: string;
- display?: ReactNode;
- emptyText?: string;
- invalid?: boolean;
- error?: ReactNode;
- selectOptions?: readonly { value: string; label: string }[];
- /** 只读原因:给了就在值后面挂一把锁并带悬停说明,避免"看不到铅笔"被当成页面坏了。 */
- lockedReason?: string;
- };
- /**
- * 详情里的单个可编辑项:非编辑态只渲染值,鼠标移入才显出铅笔;点铅笔切到输入态。
- * 改动先进页面草稿,由底部「保存修改」一次性整段提交(契约 §3.2 全量替换)。
- */
- function InlineField({ id, label, value, editing, writable, onStart, onChange, onDone, onCancel, type = "text", inputMode, min, max, step, placeholder, display, emptyText = WORD_UNCONFIGURED, invalid, error, selectOptions, lockedReason }: InlineFieldProps) {
- const shown = display ?? (value ? value : emptyText);
- if (!writable) return <span className={lockedReason ? "contract-inline-field is-locked" : "contract-inline-readonly"}>{shown}{lockedReason && <span className="contract-inline-lock" role="img" aria-label={lockedReason} title={lockedReason}><Lock size={12} /></span>}</span>;
- if (!editing) return <span className="contract-inline-field">
- <span className="contract-inline-value">{shown}</span>
- <button type="button" className="contract-inline-edit" aria-label={`编辑${label}`} title={`编辑${label}`} onClick={onStart}><PencilLine size={14} /></button>
- </span>;
- const onKeyDown = (event: ReactKeyboardEvent) => {
- // 输入法上屏用的 Enter/Esc ⛔ 当成「保存/取消」,否则拼音选字就被提交了。
- if (isImeComposing(event)) return;
- if (event.key === "Enter") { event.preventDefault(); onDone(); }
- if (event.key === "Escape") { event.preventDefault(); onCancel(); }
- };
- return <span className="contract-inline-editor">
- {selectOptions ? (
- <select id={id} aria-label={label} autoFocus value={value} onChange={(event) => onChange(event.target.value)} onKeyDown={onKeyDown}>
- {selectOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
- </select>
- ) : (
- <Input id={id} aria-label={label} autoFocus type={type} inputMode={inputMode} min={min} max={max} step={step} placeholder={placeholder} aria-invalid={invalid || undefined} value={value} onChange={(event) => onChange(event.target.value)} onKeyDown={onKeyDown} />
- )}
- <button type="button" className="contract-inline-ok" aria-label="完成编辑" title="完成" onClick={onDone}><Check size={14} /></button>
- <button type="button" className="contract-inline-cancel" aria-label="取消编辑" title="取消" onClick={onCancel}><X size={14} /></button>
- {error}
- </span>;
- }
- export function ContractRecordPage() {
- const { no } = useParams();
- const param = decodeURIComponent(no ?? "");
- const navigate = useNavigate();
- /** 运营团队按挂载区域实时反查(客户档案不存快照)⇒ 详情需 regions/operationsTeams。 */
- const view = useBusinessView(["regions", "operationsTeams"]);
- const location = useLocation();
- const back = detailBack(location.state, "/contracts", `返回${view.contractListTitle}`);
- const outgoingState = detailLinkState(location.pathname, location.state);
- /** 新建合同随路由带来的逐条替换回执(升降配):只提示一次,刷新即消失。 */
- const replacements = (location.state as { replacements?: ContractReplacementResult[] } | null)?.replacements ?? [];
- const writable = !view.readOnly;
- const catalog = useCatalogPlans();
- // D-CT-11:只读角色(运营商)对 line_exit/ticket 常 11001;编辑才需要出口目录,只读跳过请求,
- // ⛔ 把「无权限+重试」卡片挂在可读详情页上。
- const exitCatalog = useLineExits({ enabled: writable });
- const plans = useMemo(() => rowsOf(catalog.data?.items), [catalog.data]);
- /** 查表对象必须稳定:每次 render 新建 ⇒ useLoad 反复重发同一请求(页面永停在 loading)。 */
- const quotaById = useMemo(
- () => Object.fromEntries(rowsOf(catalog.data?.items).map((plan) => [plan.plan_id, plan.sub_account_quota])),
- [catalog.data],
- );
- const record = useLoad(() => contractRawByParam(param), [param]);
- const contract = useMemo(() => (record.data ? contractFromDetail(record.data, quotaById) : null), [record.data, quotaById]);
- /** 详情即编辑态:同一份草稿按字段/条目拆开渲染,保存走整段替换。 */
- const baseline = useMemo(() => (record.data ? draftFromRow(record.data) : null), [record.data]);
- /**
- * 编辑口径=后端下发(04 册 §4.2,两轴独立)。
- *
- * ⚠️ 旧后端不下发该键时回落到「按开通态判」——⛔ 在判不出来时凭猜臆断冻结,
- * 页面已在头部把「取数失败/未配置」标出来了。
- */
- const scope = record.data?.edit_scope ?? null;
- /** 修改记录卡片:只取本合同流水(后端先过合同可见性,⛔ 复用审计页的团队过滤口径)。 */
- const changeLogId = record.data?.contract_id ?? "";
- const changeLog = useLoad(
- () => (changeLogId ? contractChangeLog({ contract_id: changeLogId, page_size: 10 }) : Promise.resolve(null)),
- [changeLogId],
- );
- /**
- * 关联工单(P3-D7):改读 `/ticket/list@v1` 的 `contract_id` 过滤键,后端先把该合同下的
- * 订阅解成集合再取工单。旧口径是「合同详情接口未下发型变更/关联工单清单」的诚实空态,
- * 于是恒显示 0 张;现在按合同现查服务端台账。只读角色不拉本口(D-CT-11)。
- * ⚠️ 工单 list 页码 1 基;每页条数由前端请求决定(默认 20)。
- */
- const [ticketPage, setTicketPage] = useState(0);
- const relatedTickets = useLoad(
- () => (writable && changeLogId
- ? ticketList({ contract_id: changeLogId, page: ticketPage + 1, page_size: LIST_PAGE_SIZE })
- : Promise.resolve(null)),
- [changeLogId, writable, ticketPage],
- );
- const ticketTotal = Number(relatedTickets.data?.total ?? relatedTickets.data?.rows?.length ?? 0);
- const [olderLogs, setOlderLogs] = useState<ContractChangeLogItem[]>([]);
- const [logCursor, setLogCursor] = useState<string | null>(null);
- const [logMoreBusy, setLogMoreBusy] = useState(false);
- const [logMoreError, setLogMoreError] = useState("");
- useEffect(() => {
- setOlderLogs([]);
- setLogCursor(changeLog.data?.next_cursor ?? null);
- setLogMoreError("");
- }, [changeLog.data]);
- const loadOlderLogs = async () => {
- if (!logCursor || logMoreBusy || !changeLogId) return;
- setLogMoreBusy(true);
- setLogMoreError("");
- try {
- const next = await contractChangeLog({ contract_id: changeLogId, page_size: 10, cursor: logCursor });
- setOlderLogs((rows) => [...rows, ...(next.items ?? [])]);
- setLogCursor(next.next_cursor ?? null);
- } catch (e) {
- setLogMoreError(e instanceof ApiError ? e.message : "更早的记录取数失败,请稍后重试。");
- } finally {
- setLogMoreBusy(false);
- }
- };
- const [draft, setDraft] = useState<ContractDraft | null>(null);
- const [editingField, setEditingField] = useState<keyof ContractDraft | null>(null);
- const [editingItem, setEditingItem] = useState<number | null>(null);
- const [tab, setTab] = useState<ContractTab>("overview");
- useEffect(() => setTab("overview"), [param]);
- const [error, setError] = useState("");
- const [fieldError, setFieldError] = useState<ContractMissing | null>(null);
- const [saving, setSaving] = useState(false);
- const [notice, setNotice] = useState("");
- /** P1(D-7):级联删条目后的提示(子行随父走,必须告诉用户一起删了几条)。 */
- const [itemNotice, setItemNotice] = useState("");
- const [refStack, setRefStack] = useState<RefTarget[]>([]);
- const openRef = (target: RefTarget) => setRefStack((stack) => [...stack, target]);
- useEffect(() => {
- if (baseline) setDraft(baseline);
- }, [baseline]);
- const dirty = useMemo(() => Boolean(draft && baseline && JSON.stringify(draft) !== JSON.stringify(baseline)), [draft, baseline]);
- const catalogForPlans = plans;
- /** 客户段只走合同详情联查(`contract.customerProfile`)+主键;⛔ 再回落到演示 store。 */
- const profile = contract?.customerProfile;
- const customerId = profile?.customer_id ?? contract?.customerId ?? null;
- /**
- * 运营团队=按挂载区域实时反查(与客户档案/新增合同同口径;⛔ 档案快照)。
- * `region_node_id` 缺席(旧后端)⇒ 标明「未下发」,⛔ 拿 path 文本冒充节点去反查。
- */
- const operationsTeamView = useMemo(() => {
- const regionId = profile?.region_node_id ?? "";
- if (!profile) return null;
- if (!regionId) {
- return {
- text: profile.region_path ? "所属区域节点未下发" : "未挂载所属区域",
- note: "运营团队按所挂区域实时反查;详情联查未下发 region_node_id 时无法反查",
- };
- }
- const candidates = teamsCoveringRegion(
- view.organization.operationsTeams,
- regionAncestorChain(view.organization.regions, regionId),
- );
- const lockedId = lockIfCandidate(view.identity?.operationsTeamId, candidates);
- return operationsTeamDisplay(candidates, lockedId);
- }, [profile, view.organization.operationsTeams, view.organization.regions, view.identity?.operationsTeamId]);
- /** 「第 N 份合同」=同客户名下按生效日排序的序号,后端无该口径接口,只在合同列表结果上本地派生。 */
- const contracts = useContracts({ customerId: contract?.customerId || undefined });
- const ordinal = useMemo(() => {
- if (!contract || contracts.loading) return null;
- const siblings = rowsOf(contracts.data?.items)
- .sort((a, b) => (a.start_date ?? "").localeCompare(b.start_date ?? "") || (a.contract_no ?? "").localeCompare(b.contract_no ?? ""));
- const index = siblings.findIndex((row) => (row.contract_id || row.contract_no) === (contract.contractId || contract.no));
- return index >= 0 ? index + 1 : null;
- }, [contract?.contractId, contract?.no, contracts.data, contracts.loading]);
- /** 出口候选=套餐配置清单;历史数据里已出现的值也保留,避免旧合同编辑时选项凭空消失。 */
- const exitOptions = useMemo(() => {
- if (!draft) return [];
- const names = (exitCatalog.data?.items ?? []).map((item) => item.exit_name);
- const legacy = [...draft.items.flatMap((item) => item.exits)];
- return [...new Set([...names, ...legacy])];
- }, [exitCatalog.data, draft]);
- const patch = <K extends keyof ContractDraft>(key: K, value: ContractDraft[K]) => {
- setDraft((current) => {
- if (!current) return current;
- const next = { ...current, [key]: value };
- /** 合同结束日恒由生效日+服务期(月)推算(2026-11-19 定案,⛔ 手填):改任一项即重算。 */
- if (key === "start" || key === "serviceMonths") {
- next.end = contractEndFromMonths(next.start, next.serviceMonths);
- }
- return next;
- });
- setError("");
- setFieldError((current) => (current && REQUIRED_KEY_BY_DRAFT[key] === current.key ? null : current));
- };
- const startField = (key: keyof ContractDraft) => { setEditingItem(null); setEditingField(key); };
- const cancelField = (key: keyof ContractDraft) => {
- if (baseline) setDraft((current) => {
- if (!current) return current;
- /**
- * 撤销生效日/服务期要连带把结束日退回基线:只退输入项会把上一轮推算值留下,
- * 页面上就成了「生效日还是旧的、结束日却是新算的」。
- */
- const next = { ...current, [key]: baseline[key] };
- if (key === "start" || key === "serviceMonths") next.end = baseline.end;
- return next;
- });
- setEditingField(null);
- };
- const invalidOf = (key: "amount" | "serviceMonths" | "agent" | "agentPhone" | "signDate") => (fieldError?.key === key ? true : undefined);
- const requiredErrorOf = (key: "amount" | "serviceMonths" | "agent" | "agentPhone" | "signDate") => (fieldError?.key === key ? <span className="ops-field-error">{fieldError.message}</span> : null);
- const patchItem = (index: number, values: Partial<ItemDraft>) => {
- setDraft((current) => (current ? { ...current, items: current.items.map((item, i) => (i === index ? { ...item, ...values } : item)) } : current));
- setError("");
- };
- const pickPlan = (index: number, planId: string) => {
- const plan = catalogForPlans.find((row) => row.plan_id === planId);
- // 跨境链路份数恒 1;叠加服务份数即个数(可 > 1)。
- patchItem(index, { planId, planName: plan?.plan_name ?? "", planFamily: plan?.plan_family ?? "", ...(plan && plan.plan_family === "link" ? { quantity: 1 } : {}) });
- };
- /** 叠加服务(例如「单独境外 IP」按个)才允许填份数;链路档份数恒 1。 */
- const stackablePlan = (planId: string) => catalogForPlans.find((row) => row.plan_id === planId)?.plan_family === "addon";
- /** 线路出口**单选**(2026-11-17):下拉选中即设为该出口,选空即清空。
- * 2026-11-19:叠加服务不单独选出口 ⇒ 父行一换出口,子行同步成同一出口。 */
- const toggleExit = (index: number, exit: string) => {
- if (!draft) return;
- const key = draft.items[index]?.key;
- const nextExits = exit ? [exit] : [];
- setDraft((current) => {
- if (!current) return current;
- return {
- ...current,
- items: current.items.map((row, i) => {
- if (i === index) return { ...row, exits: nextExits };
- if (key && row.parentKey === key) return { ...row, exits: [...nextExits] };
- return row;
- }),
- };
- });
- setError("");
- };
- const addItem = () => {
- if (!draft) return;
- const next = draft.items.length;
- setDraft({ ...draft, items: [...draft.items, emptyItem()] });
- setEditingItem(next);
- setEditingField(null);
- setItemNotice("");
- };
- /**
- * D-7:叠加服务只能从「跨境链路」节点下新增(父子两级,⛔ 叠加服务再挂叠加服务)。
- * `parentKey` 指向链路节点的本地 key,落库时换成 `serves_item_id`/`serves_item_index`。
- */
- const addChildItem = (parentKey: string) => {
- if (!draft) return;
- const next = draft.items.length;
- const parent = draft.items.find((item) => item.key === parentKey);
- /** 2026-11-19:叠加服务不单独选出口,建行时直接依从父链路出口。 */
- setDraft({ ...draft, items: [...draft.items, { ...emptyItem(parentKey, "new"), exits: parent ? [...parent.exits] : [] }] });
- setEditingItem(next);
- setEditingField(null);
- setItemNotice("");
- };
- /** D-9:增量分组的「再加一条叠加服务」——同一条既有订阅下再补一个叠加服务,引用不变。 */
- const addIncrementChild = (parent: ItemDraft) => {
- if (!draft) return;
- const next = draft.items.length;
- setDraft({ ...draft, items: [...draft.items, { ...emptyItem(null, "increment"), refSubscriptionId: parent.refSubscriptionId, refSubscriptionLabel: parent.refSubscriptionLabel, exits: [...parent.exits] }] });
- setEditingItem(next);
- setEditingField(null);
- setItemNotice("");
- };
- const removeItem = (index: number) => {
- if (!draft) return;
- const target = draft.items[index];
- if (!target) return;
- /** D-7:删父连带删子,并报出连带条数;⛔ 留孤儿行(后端也拒收无父的叠加服务)。 */
- const doomed = new Set(itemSubtreeKeys(draft.items, target.key));
- const children = doomed.size - 1;
- setDraft((current) => (current ? { ...current, items: current.items.filter((row) => !doomed.has(row.key)) } : current));
- setEditingItem(null);
- setError("");
- setItemNotice(children > 0 ? `已移除条目 ${index + 1} 及其 ${children} 个叠加服务(子行随父走,不留孤儿)。` : "");
- };
- const cancelItem = (index: number) => {
- if (baseline) setDraft((current) => {
- if (!current) return current;
- const items = [...current.items];
- if (index < baseline.items.length) items[index] = baseline.items[index];
- else items.splice(index, 1);
- return { ...current, items };
- });
- setEditingItem(null);
- };
- const discard = () => {
- if (baseline) setDraft(baseline);
- setEditingField(null);
- setEditingItem(null);
- setFieldError(null);
- setError("");
- };
- async function save() {
- if (!draft || !record.data || saving) return;
- /** 兜底:草稿装载后被开通/被冻结(他端开户工单回填)时,按**两轴**判越界。 */
- if (baseline) {
- const frozen = frozenChanges(draft, baseline, scope);
- if (frozen.length) { setError(`${frozen.join("、")}属当前不可修改的口径(编辑口径见下方说明);请点「放弃修改」后重试。`); return; }
- }
- const built = buildContractWrite(draft);
- if (!built.ok) {
- setFieldError(built.fieldError ?? null);
- setError(built.error);
- if (built.fieldError) setTab("overview");
- return;
- }
- /** 只提交**变了的**字段:后端「键缺席=保持现值」,整份回传会被冻结合同判成越界。 */
- const patch = baseline ? changedWriteFields(draft, baseline) : {};
- const contractId = record.data.contract_id;
- const version = Number(record.data.row_version);
- if (!contractId || !Number.isFinite(version)) { setError("未取到合同主键或并发版本(row_version),无法保存。"); return; }
- if (!Object.keys(patch).length) { setError("没有需要保存的改动。"); return; }
- setSaving(true);
- setError("");
- setFieldError(null);
- try {
- await contractUpdate({
- contract_id: contractId,
- row_version: version,
- external_no: patch.externalNo,
- contract_type: patch.contractType,
- sign_date: patch.signDate,
- contract_amount_cents: patch.contractAmountCents,
- discount_rate_pct: patch.discountRatePct,
- service_months: patch.serviceMonths,
- start_date: patch.startDate,
- end_date: patch.endDate,
- agent_name: patch.agentName,
- agent_mobile: patch.agentMobile,
- agent_handover_on: patch.agentHandoverOn,
- agent_org: patch.agentOrg,
- attachment_url: patch.attachmentUrl,
- service_items: patch.serviceItems,
- });
- setEditingField(null);
- setEditingItem(null);
- setNotice("合同修改已保存(本次改动已记入右侧「修改记录」)。");
- record.reload();
- changeLog.reload();
- } catch (e) {
- setError(e instanceof ApiError ? e.message : "保存失败,请稍后重试。");
- } finally {
- setSaving(false);
- }
- }
- /**
- * 编辑口径=后端 `edit_scope`(04 册 §4.2):两轴各自独立。
- * 必须在下方 early return **之前**算完,且金额派生 `useEffect` 也必须挂在这里——
- * 否则 loading → 有数据时 hooks 数量变多,React 会直接白屏。
- */
- const opened = contract?.opened === true;
- const billingEditable = scope ? scope.billing.editable : !opened;
- const archiveEditable = scope ? scope.archive.editable : !opened;
- const billingWritable = writable && billingEditable;
- const archiveWritable = writable && archiveEditable;
- /** 锁形图标只在「能改但被合同状态挡住」时给:整页只读的身份不必看到这把锁。 */
- const billingLocked = writable && !billingEditable;
- const archiveLocked = writable && !archiveEditable;
- /**
- * 计费轴可写时:合同金额随服务构成重算(改造稿 D-15)。
- * 已锁定时保留库内金额,⛔ 用目录现值覆盖冻结值。
- */
- useEffect(() => {
- if (!draft?.items || !billingWritable) return;
- const discount = parseDiscountRate(draft.discountRate) ?? 100;
- const derived = deriveContractAmount(draft.items, plans, exitCatalog.data?.items ?? [], discount);
- if (!derived.ok && derived.reason === "incomplete") return;
- const nextAmount = derived.ok ? derived.text : "";
- setDraft((current) => (current && current.amount !== nextAmount ? { ...current, amount: nextAmount } : current));
- }, [draft?.items, draft?.discountRate, billingWritable, plans, exitCatalog.data]);
- if (record.loading && !record.data) 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>;
- if (record.error && !record.data) 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"><AlertTriangle size={26} /><h1>合同资料取数失败</h1><FetchError message={record.error.message} onRetry={record.reload} /></div></section>;
- if (!contract) 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>;
- if (!draft) 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>;
- const orders = contract.relatedOrders;
- /**
- * 「关联关系」列(2026-11-17):本合同名下订阅的关联真源只有 `contract_id`,行内再按两枚落点
- * 指针细化——`contract_item_id`=由哪条服务条目签约,`replaces_subscription_id`=升降配替换了谁。
- * 两枚都缺席=存量行只按合同归属,⛔ 拿「首次签约」之类的推测定性(首签/续签后端不作区分)。
- */
- const itemNoOf = new Map(contract.items.flatMap((item, index) => (item.itemId ? [[item.itemId, index + 1] as const] : [])));
- /**
- * P1(D-7)呈现树:两行扁平表里用「父行 → 缩进子行」表达附加关系,⛔ 嵌套折叠——
- * 订阅/工单/台账仍是扁平清单(D-7「不扩散」)。增量条目自成一类只读引用节点。
- */
- const tree = itemTree(draft.items);
- const indexOfKey = new Map(draft.items.map((item, index) => [item.key, index] as const));
- const itemRows: { item: ItemDraft; index: number; depth: number; parentIndex: number | null }[] = [];
- for (const node of tree) {
- itemRows.push({ item: node.item, index: node.index, depth: 0, parentIndex: null });
- for (const child of node.children) {
- itemRows.push({ item: child.item, index: child.index, depth: 1, parentIndex: indexOfKey.get(node.item.key) ?? null });
- }
- }
- /** 增量合同(D-9):合同下全部条目都挂在既有订阅上 ⇒ 头图打标签,⛔ 当成普通新签合同读。 */
- const incrementContract = draft.items.length > 0 && draft.items.every((item) => item.itemMode === "increment");
- const relationOf = (sub: { contractItemId?: string | null; replacesSubscriptionId?: string | null }) => {
- const itemNo = sub.contractItemId ? itemNoOf.get(sub.contractItemId) : undefined;
- const replaced = sub.replacesSubscriptionId;
- return <>
- <span>{sub.contractItemId ? (itemNo ? `第 ${itemNo} 条服务条目签约` : `服务条目 ${sub.contractItemId} 签约`) : "仅按合同归属(未挂服务条目)"}</span>
- {replaced && <small>升降配替换 · 替代 <button type="button" className="contract-ref-link" onClick={() => openRef({ kind: "order", id: replaced, name: (orders ?? []).find((row) => row.orderId === replaced)?.planName ?? null })}>{replaced}</button></small>}
- </>;
- };
- const state = draft.start && draft.end ? contractStatusOf(draft.start, draft.end) : null;
- const LOCK_REASON: Record<string, string> = {
- opened: "本合同已开通:开通后计费口径与档案字段均不再随页面修改",
- expired: "本合同已过结束日:计费与档案字段冻结",
- synced_source: "本合同为运营商同步来源:以同步数据为准,本地不可改",
- grace_expired: "已过录后 72 小时更正期且合同已生效:计费口径冻结",
- effective: "合同已生效:计费口径冻结",
- locked: "本合同当前状态不允许修改该字段",
- };
- const billingLockReason = billingLocked ? LOCK_REASON[scope?.billing.reason ?? "opened"] ?? LOCK_REASON.opened : undefined;
- const archiveLockReason = archiveLocked ? LOCK_REASON[scope?.archive.reason ?? "opened"] ?? LOCK_REASON.opened : undefined;
- /** 金额恒派生;计费轴已锁时优先展示冻结原因,否则用派生说明。 */
- const amountLockReason = billingLockReason ?? CONTRACT_AMOUNT_DERIVED;
- /** 已开通/已到期/来源同步 ⇒ 顶部一行说明;「未生效」不提示(本来就能改)。 */
- const lockNote = billingLocked || archiveLocked
- ? [
- billingLocked && `计费口径(合同金额、服务期、合同期间、服务构成)已锁定:${scope?.billing.reason === "synced_source" ? "以运营商同步数据为准" : "需调整请走变更工单"}`,
- archiveLocked && "档案字段(外部单号、签署日期、运营商经办人)已锁定",
- ].filter(Boolean).join(";")
- : null;
- /**
- * 合同附件(单值,2026-11-16):`attachment_url` 要么是外部链接(可直接打开),要么是
- * 平台桶对象键(`attachment_kind=object`)——后者的下载地址由**详情读口现签**并随
- * `attachment_view_url` 下发;列表口不签(⛔ 按行 N 次调平台)⇒ 此处只认详情那一份。
- */
- const attachment = contract.file;
- const attachmentKind = record.data?.attachment_kind ?? attachmentKindOf(attachment);
- const attachmentNames = attachment ? [contractAttachmentLabel(attachment)] : [];
- const attachmentUrl = (() => {
- if (!attachment) return undefined;
- if (attachmentKind === "link") return attachment;
- if (attachmentKind !== "object") return undefined;
- // 现签地址只对「读口那一条」有效:编辑过地址但没刷新时,⛔ 拿旧签名冒充新附件。
- return record.data?.attachment_url === attachment ? record.data.attachment_view_url ?? undefined : undefined;
- })();
- const attachmentViewNote = attachmentKind === "object"
- ? "下载签名未取到(对象存储不可达/对象已回收)⇒ 刷新详情重取;不得用对象键充当链接"
- : "附件地址形态无法识别(形态校验上线前的存量脏值)⇒ 请重新上传";
- const ordinalText = ordinal ?? (contracts.loading ? "…" : contracts.error ? <Tri tone="fail" text={WORD_FETCH_FAILED} title={contracts.error.message} /> : WORD_UNCONFIGURED);
- /** 档案联查不可用时的统一空态(与旧「客户主体」行同一判据)。 */
- const profileMissing = profile === null
- ? <Tri tone="missing" text="档案不可读" title="该 customer_id 在客户册查不到(已注销或脏引用)⇒ 不冒充「未登记」" />
- : contract.customerId
- ? <Tri tone="fail" text={WORD_FETCH_FAILED} title="详情接口未下发 customerProfile" />
- : <Tri tone="missing" text="未关联档案" title="本合同未携带客户主键" />;
- const contactPair = (name?: string | null, phone?: string | null) => {
- const n = name?.trim() || "";
- const p = phone?.trim() || "";
- if (!n && !p) return "未登记";
- return `${n || "未填"} · ${p || "未填"}`;
- };
- /** 营业执照:企业才适用;摘要键缺席=旧后端;其余按 none/viewable/expired 三态。 */
- const licenseCell = (() => {
- if (!profile) return profileMissing;
- if (profile.subject_type && profile.subject_type !== "enterprise") return "不适用(个人与个体工商户不采集证件影像)";
- if (profile.license === undefined) return <Tri tone="fail" text={WORD_FETCH_FAILED} title="详情联查未下发 license(旧后端)" />;
- const lic = profile.license;
- if (!lic || lic.status === "none") return "未登记";
- if (lic.status === "expired") return <>已超期{lic.file_name ? `:${lic.file_name}` : ""}<span className="contract-readonly-note">(留存期满,不下发下载)</span></>;
- if (lic.status === "viewable") {
- return lic.view_url
- ? <span className="contract-record-file"><FileText size={18} /><strong>{lic.file_name || "营业执照影像"}</strong><a href={lic.view_url} target="_blank" rel="noreferrer">查看影像</a></span>
- : <>{lic.file_name || "营业执照影像"}<span className="contract-readonly-note">(下载签名未取到)</span></>;
- }
- return lic.file_name || WORD_UNCONFIGURED;
- })();
- /** 账号数按草稿现算:套餐式=档位额度 × 数量,自定义式=录入账号数(04 册 §4.9)。目录额度未取到=未配置,⛔ 计 0。 */
- const accountsKnown = draft.items.every((item) => quotaById[item.planId] !== null && quotaById[item.planId] !== undefined);
- const accountTotal = draft.items.reduce((sum, item) => {
- const quota = quotaById[item.planId];
- return sum + (quota === null || quota === undefined ? 0 : quota * item.quantity);
- }, 0);
- /** 境外 IP 数量(D-15 改口径):叠加服务档的份数即个数(链路档份数恒 1,不计入)。 */
- const overseasIpTotal = draft.items.reduce((sum, item) => {
- const family = item.planFamily || catalogForPlans.find((row) => row.plan_id === item.planId)?.plan_family;
- return sum + (family === "addon" ? item.quantity : 0);
- }, 0);
- const exits = [...new Set(draft.items.flatMap((item) => item.exits))];
- const tabs: { id: ContractTab; label: string; count?: ReactNode }[] = [
- { id: "overview", label: "合同概况" },
- { id: "services", label: "服务构成", count: draft.items.length },
- { id: "subscriptions", label: "关联订阅", count: orders?.length },
- ];
- if (writable) {
- tabs.push(
- { id: "tickets", label: "关联工单", count: relatedTickets.error ? "—" : ticketTotal },
- { id: "billing", label: "出账信息" },
- );
- }
- tabs.push({ id: "history", label: "修改记录" });
- const activeTab = tabs.some((item) => item.id === tab) ? tab : "overview";
- return <section className="ops-page contract-record record-detail">
- <Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} />{back.label}</Link>
- <header className="contract-record-hero"><div className="customer-hero-symbol"><FileSignature size={28} /></div><div className="customer-hero-copy"><span className="customer-eyebrow">合同详情</span><h1>{contract.no}</h1><p className="contract-record-subtitle"><Building2 size={15} />{customerId || profile ? <button type="button" className="contract-ref-link" onClick={() => openRef({ kind: "customer", id: customerId ?? profile?.customer_id ?? "", name: profile?.customer_name ?? contract.customer })}>{contract.customer || WORD_UNCONFIGURED}</button> : contract.customer || WORD_UNCONFIGURED}{customerId ? `(${customerId})` : ""} <i>·</i> 外部单号 {draft.externalNo || "未登记"} <i>·</i> 第 {ordinalText} 份合同</p><div className="ops-record-pills">{contract.source === undefined || contract.source === null ? <Tri tone="missing" text={contract.source === undefined ? WORD_NOT_PROVIDED : WORD_UNCONFIGURED} title="合同来源标识:列表与详情接口均不下发该口径" /> : <OpsTag tone={contractSourceTone[contract.source as keyof typeof contractSourceTone] ?? "neutral"}>{contract.source}</OpsTag>}{state ? <OpsStatus tone={contractStatusTone[state]}>{state}</OpsStatus> : <Tri tone={contract.periodState === "fail" ? "fail" : "missing"} text={contract.periodState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} title="缺少生效日或结束日,状态不可判" />}{isExpiringSoon(record.data?.end_date) ? <OpsStatus tone="warning">快到期 · {expiringLabel(record.data?.end_date)}</OpsStatus> : null}{contract.opened === undefined || contract.opened === null ? <Tri tone={contract.opened === undefined ? "fail" : "missing"} text={contract.opened === undefined ? WORD_FETCH_FAILED : WORD_UNCONFIGURED} title="是否已开通取关联工单回填" /> : <OpsStatus tone={contract.opened ? "success" : "warning"}>{contract.opened ? "已开通" : "未开通"}</OpsStatus>}</div>{writable && <p className="contract-record-edit-hint"><PencilLine size={13} />悬停可编辑项显示铅笔,点击即切换编辑状态</p>}</div><div className="ops-record-actions">{writable && record.data?.contract_id && isExpiringSoon(record.data?.end_date) ? <Button size="sm" title="按本合同带入金额、服务期、服务条目与新的生效日(旧止期次日),生成新合同;不替换原订阅" onClick={() => navigate(`/contracts/new?renew=${encodeURIComponent(record.data?.contract_id ?? "")}`)}><CalendarClock size={15} />续签合同</Button> : null}<Button variant="outline" size="sm" onClick={record.reload}><RefreshCcw size={15} />刷新</Button></div></header>
- {lockNote && <p className="contract-lock-note" role="note"><Lock size={14} />{lockNote}。录入经办人(录入账号)由录入时账号自动带入机构/姓名/联系方式,建后一律只读。</p>}
- {replacements.length > 0 && <div className="contract-replace-receipt" role="status">
- <strong><Check size={14} />本次已按本合同生成 {replacements.length} 条订阅</strong>
- <ul>
- {replacements.map((row) => <li key={row.subscription_id}>
- {row.mode === "renewed"
- ? `续签新开 → 新订阅 ${row.subscription_id}(原订阅不动)`
- : `替换:原订阅 ${row.replaces_subscription_id} → 新订阅 ${row.subscription_id}`}
- {row.ticket_type ? `;工单 ${row.ticket_type}${row.ticket_no ? `(${row.ticket_no})` : ""}` : row.note ? `;未生成工单(${row.note.replace(/。$/, "")})` : ";本次未生成工单"}
- {row.actual_opened_at ? `;视为已交付(实际开通日 ${row.actual_opened_at})` : ""}
- </li>)}
- </ul>
- </div>}
- <div className="contract-record-summary">
- <div><span>合同总额</span><strong><InlineField id="contract-amount-summary" label="合同金额" value={draft.amount} editing={false} writable={false} lockedReason={amountLockReason} onStart={() => {}} onChange={() => {}} onDone={() => {}} onCancel={() => {}} inputMode="decimal" placeholder="0.00" display={draft.amount ? money(Number(draft.amount)) : undefined} emptyText={WORD_UNCONFIGURED} invalid={invalidOf("amount")} error={requiredErrorOf("amount")} /></strong><small>{draft.serviceMonths ? `服务期 ${draft.serviceMonths} 个月` : <Tri tone="missing" text={WORD_UNCONFIGURED} />} · 折扣率 {draft.discountRate ? `${draft.discountRate}%` : "100%"}</small></div>
- <div><span>账号数</span><strong>{accountsKnown ? accountTotal : <Tri tone="missing" text={WORD_UNCONFIGURED} title="套餐档位额度未取到(目录接口未下发)" />}</strong><small>按服务条目派生</small></div>
- <div><span>境外 IP</span><strong>{overseasIpTotal}</strong><small>按「叠加服务」档位 × 份数派生 · {exits.join("、") || "无出口"}</small></div>
- <div><span>关联订阅</span><strong>{orders ? orders.length : <Tri tone="fail" text={WORD_FETCH_FAILED} />}</strong><small>{orders ? `生效中 ${orders.filter((item) => orderEffective(item.status)).length} 份` : "详情接口未返回关联订阅"}</small></div>
- <div><span>应收合计</span><strong><Tri tone="missing" text={WORD_UNCONFIGURED} title="应收结算属第 6 册,后端未提供接口" /></strong><small>出账与对账接口未提供</small></div>
- <div><span>已出账金额</span><strong><Tri tone="missing" text={WORD_UNCONFIGURED} title="出账金额属第 6 册,后端未提供接口" /></strong><small>出账与对账接口未提供</small></div>
- </div>
- <div className="record-tabs-frame">
- <RecordTabs prefix="contract" label="合同详情视图" tabs={tabs} active={activeTab} onChange={setTab} />
- <div className="contract-record-main record-tab-panel" id="contract-panel-overview" role="tabpanel" aria-labelledby="contract-tab-overview" hidden={activeTab !== "overview"}>
- <section className="contract-record-section">
- <div className="contract-record-section-title"><h2>客户资料</h2>{customerId ? <button type="button" className="ops-card-link contract-ref-link" onClick={() => openRef({ kind: "customer", id: customerId, name: profile?.customer_name ?? contract.customer })}>查看客户档案<ArrowRight size={15} /></button> : <Link className="ops-card-link" to={`/customers?query=${encodeURIComponent(contract.customer)}`} state={outgoingState}>查找客户档案<ArrowRight size={15} /></Link>}</div>
- {/**
- * 字段顺序/标签与新增合同「01 客户资料」对齐(业主 2026-11-20):
- * 客户名称 → 识别号 → 类型 → 区域 → 运营商 → 地址 → 三联系人 → 合伙人 → 运营/运维团队 → 备注 → 执照。
- */}
- <dl className="contract-record-facts">
- <div><dt>客户名称</dt><dd>{profile ? <button type="button" className="contract-ref-link" onClick={() => openRef({ kind: "customer", id: profile.customer_id, name: profile.customer_name })}>{profile.customer_name}<small>{profile.customer_id}</small></button> : profileMissing}</dd></div>
- <div><dt>客户识别号</dt><dd>{profile ? (profile.identity_no_masked || "未登记") : profileMissing}</dd></div>
- <div><dt>客户类型</dt><dd>{profile ? (profile.subject_type ? label(SUBJECT_TYPE, profile.subject_type) : WORD_UNCONFIGURED) : profileMissing}</dd></div>
- <div><dt>所属区域</dt><dd>{profile ? (profile.region_path || WORD_UNCONFIGURED) : profileMissing}</dd></div>
- <div><dt>运营商</dt><dd>{profile ? (profile.operator_name || "未登记") : profileMissing}</dd></div>
- <div><dt>客户地址</dt><dd>{profile ? (profile.address || "未登记") : profileMissing}</dd></div>
- <div><dt>商务联系人</dt><dd>{profile ? contactPair(profile.contact_name, profile.contact_mobile) : profileMissing}</dd></div>
- <div><dt>技术联系人</dt><dd>{profile ? (profile.tech_contact_name === undefined && profile.tech_contact_mobile === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} title="详情联查未下发技术联系人(旧后端)" /> : contactPair(profile.tech_contact_name, profile.tech_contact_mobile)) : profileMissing}</dd></div>
- <div><dt>财务联系人</dt><dd>{profile ? (profile.finance_contact_name === undefined && profile.finance_contact_mobile === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} title="详情联查未下发财务联系人(旧后端)" /> : contactPair(profile.finance_contact_name, profile.finance_contact_mobile)) : profileMissing}</dd></div>
- <div><dt>合伙人</dt><dd>{profile ? (profile.partner_name || "未匹配合伙人") : profileMissing}</dd></div>
- <div><dt>运营团队</dt><dd>{profile ? (operationsTeamView ? <span title={operationsTeamView.note}>{operationsTeamView.text}{operationsTeamView.note ? <small className="contract-readonly-note">({operationsTeamView.note})</small> : null}</span> : WORD_UNCONFIGURED) : profileMissing}</dd></div>
- <div><dt>运维团队</dt><dd>{profile ? (profile.ops_team_names === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} title="详情联查未下发 ops_team_names(旧后端)" /> : profile.ops_team_names?.length ? profile.ops_team_names.join("、") : "未匹配运维团队") : profileMissing}</dd></div>
- <div className="contract-facts-row-full"><dt>客户备注</dt><dd>{profile ? (profile.remark === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} title="详情联查未下发 remark(旧后端)" /> : profile.remark || "未登记") : profileMissing}</dd></div>
- <div className="contract-facts-row-full"><dt>营业执照影像</dt><dd>{profile ? licenseCell : profileMissing}</dd></div>
- </dl>
- </section>
- <section className="contract-record-section">
- {/**
- * 标题保持「商务信息」(详情定名);字段顺序对齐新增合同「02 合同基本信息」。
- * 合同金额挂标题行右侧(与新增页同口径,只读派生)。
- */}
- <div className="contract-record-section-title">
- <h2>商务信息</h2>
- <div className="contract-section-amount" id="contract-amount" aria-live="polite" aria-invalid={invalidOf("amount")}>
- <span className="contract-section-amount-label">合同金额<FieldHint label="合同金额说明">按服务构成自动汇总:Σ(档位年价 × 份数 × 计费系数)× 折扣率/100;挂在标题行只读展示。特价须先建客户自定义档再引用。</FieldHint></span>
- <strong><InlineField id="contract-amount-value" label="合同金额" value={draft.amount} editing={false} writable={false} lockedReason={amountLockReason} onStart={() => {}} onChange={() => {}} onDone={() => {}} onCancel={() => {}} inputMode="decimal" placeholder="0.00" display={draft.amount ? money(Number(draft.amount)) : undefined} emptyText={WORD_UNCONFIGURED} invalid={invalidOf("amount")} error={requiredErrorOf("amount")} /></strong>
- </div>
- </div>
- <dl className="contract-record-facts">
- <div><dt>合同类型</dt><dd>{CONTRACT_TYPE_LABEL[draft.contractType] ?? draft.contractType ?? WORD_UNCONFIGURED}<span className="contract-readonly-note">(新建时确定,建后不改)</span></dd></div>
- <div><dt>合同编号</dt><dd>{contract.no}<span className="contract-readonly-note">(建后不可改)</span></dd></div>
- <div><dt>外部单号</dt><dd><InlineField id="contract-external-no" label="外部单号" value={draft.externalNo} editing={editingField === "externalNo"} writable={archiveWritable} lockedReason={archiveLockReason} onStart={() => startField("externalNo")} onChange={(value) => patch("externalNo", value)} onDone={() => setEditingField(null)} onCancel={() => cancelField("externalNo")} emptyText="未登记" /></dd></div>
- {/* 运营商经办人=姓名+电话(与新增合同对齐;机构仍随草稿回传,UI 不再展示/编辑)。 */}
- <div className="contract-facts-row-full"><dt>运营商经办人</dt><dd className="contract-inline-group"><span className="contract-inline-seg"><small>姓名</small><InlineField id="contract-agent" label="运营商经办人姓名" value={draft.agent} editing={editingField === "agent"} writable={archiveWritable} lockedReason={archiveLockReason} onStart={() => startField("agent")} onChange={(value) => patch("agent", value)} onDone={() => setEditingField(null)} onCancel={() => cancelField("agent")} emptyText="未登记" invalid={invalidOf("agent")} error={requiredErrorOf("agent")} /></span><span className="contract-inline-seg"><small>联系电话</small><InlineField id="contract-agent-phone" label="运营商经办人联系电话" value={draft.agentPhone} editing={editingField === "agentPhone"} writable={archiveWritable} lockedReason={archiveLockReason} onStart={() => startField("agentPhone")} onChange={(value) => patch("agentPhone", value)} onDone={() => setEditingField(null)} onCancel={() => cancelField("agentPhone")} emptyText="未登记" inputMode="numeric" invalid={invalidOf("agentPhone")} error={requiredErrorOf("agentPhone")} /></span></dd></div>
- {/* 交接日期即签署日期(2026-11-19 定案):详情只保留一格,交接日期列由写口同值落库。 */}
- <div><dt>签署日期</dt><dd><InlineField id="contract-sign-date" label="签署日期" type="date" value={draft.signDate} editing={editingField === "signDate"} writable={archiveWritable} lockedReason={archiveLockReason} onStart={() => startField("signDate")} onChange={(value) => patch("signDate", value)} onDone={() => setEditingField(null)} onCancel={() => cancelField("signDate")} emptyText="未登记" invalid={invalidOf("signDate")} error={requiredErrorOf("signDate")} /></dd></div>
- <div><dt>折扣率</dt><dd><InlineField id="contract-discount-rate" label="折扣率(%)" type="number" min={1} max={100} step={0.01} value={draft.discountRate} editing={editingField === "discountRate"} writable={billingWritable} lockedReason={billingLockReason} onStart={() => startField("discountRate")} onChange={(value) => patch("discountRate", value)} onDone={() => setEditingField(null)} onCancel={() => cancelField("discountRate")} display={draft.discountRate ? `${draft.discountRate}%` : undefined} emptyText="100%" inputMode="decimal" invalid={parseDiscountRate(draft.discountRate) === null} /></dd></div>
- <div><dt>服务期(月)</dt><dd><InlineField id="contract-service-months" label="服务期(月)" type="number" value={draft.serviceMonths} editing={editingField === "serviceMonths"} writable={billingWritable} lockedReason={billingLockReason} onStart={() => startField("serviceMonths")} onChange={(value) => patch("serviceMonths", value)} onDone={() => setEditingField(null)} onCancel={() => cancelField("serviceMonths")} display={draft.serviceMonths ? `${draft.serviceMonths} 个月` : undefined} emptyText={WORD_UNCONFIGURED} invalid={invalidOf("serviceMonths")} error={requiredErrorOf("serviceMonths")} /></dd></div>
- <div><dt>生效日期</dt><dd><InlineField id="contract-start" label="生效日期" type="date" value={draft.start} editing={editingField === "start"} writable={billingWritable} lockedReason={billingLockReason} onStart={() => startField("start")} onChange={(value) => patch("start", value)} onDone={() => setEditingField(null)} onCancel={() => cancelField("start")} emptyText={WORD_UNCONFIGURED} /></dd></div>
- <div><dt>到期日期</dt><dd><InlineField id="contract-end" label="到期日期" type="date" value={draft.end} editing={false} writable={false} lockedReason={billingLockReason ?? CONTRACT_END_DERIVED} onStart={() => {}} onChange={() => {}} onDone={() => {}} onCancel={() => {}} emptyText={WORD_UNCONFIGURED} /></dd></div>
- {/* 详情专属:排在共享字段之后、附件之前(不影响与新增页共享字段对齐)。 */}
- <div><dt>合同来源</dt><dd>{contract.source === undefined ? WORD_NOT_PROVIDED : contract.source ?? WORD_UNCONFIGURED}</dd></div>
- <div><dt>合同状态</dt><dd>{state ?? (contract.periodState === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED)}</dd></div>
- <div><dt>网络开通</dt><dd>{contract.opened === undefined || contract.opened === null ? (contract.opened === undefined ? WORD_FETCH_FAILED : WORD_UNCONFIGURED) : contract.opened ? `已开通 · ${contract.openedOn || "待回填日期"}` : `未开通 · 实际开通日 ${contract.openedOn ? contract.openedOn : "未回填"}`}<span className="contract-readonly-note">(由开户工单回填,不得手工改)</span></dd></div>
- <div className="contract-facts-row-full"><dt>录入经办人</dt><dd className="contract-inline-group">{record.data?.created_by ? <><span className="contract-inline-seg"><small>机构</small><span className="contract-inline-readonly">{record.data.created_by_org || "未记录"}</span></span><span className="contract-inline-seg"><small>姓名</small><span className="contract-inline-readonly">{record.data.created_by_name || record.data.created_by}</span></span><span className="contract-inline-seg"><small>联系方式</small><span className="contract-inline-readonly">{record.data.created_by_mobile || "未绑定"}</span></span></> : <Tri tone="missing" text="未记录" title="存量合同没有录入账号列(created_by)⇒ 不回填造值" />}</dd></div>
- <div className="contract-facts-row-full"><dt>合同附件</dt><dd>{attachment === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} title="详情接口未下发 attachment_url 键" /> : attachmentNames.length ? <span className="contract-record-file"><FileText size={18} /><strong title={attachment ?? ""}>{attachmentNames[0]}</strong>{attachmentUrl ? <a href={attachmentUrl} target="_blank" rel="noreferrer">{attachmentKind === "object" ? "下载附件" : "打开链接"}</a> : <small>{attachmentViewNote}</small>}</span> : "未登记"}<span className="contract-readonly-note">(附件单份;查看/下载地址由详情读口按需现签)</span></dd></div>
- </dl>
- </section>
- </div>
- <section className="contract-record-section record-tab-panel" id="contract-panel-services" role="tabpanel" aria-labelledby="contract-tab-services" hidden={activeTab !== "services"}>
- <div className="contract-record-section-title"><h2>服务构成</h2><span className="contract-title-note">{draft.items.length} 个条目{incrementContract ? " · 增量合同" : ""}</span></div>
- {exitCatalog.error && <FetchError message={exitCatalog.error.message} onRetry={exitCatalog.reload} />}
- {!exitCatalog.loading && !exitCatalog.error && !exitOptions.length && <p className="contract-record-note">套餐配置尚未配置线路出口;请先到「套餐配置 → 线路出口」维护,叠加服务依从所挂跨境链路的出口。</p>}
- <div className="ops-table-wrap record-table-scroll" role="region" aria-label="服务构成列表" tabIndex={0}>
- <table className="ops-table contract-items-table" style={{ minWidth: 900 }}>
- <thead><tr><th>套餐档位</th><th>交付形态</th><th>份数</th><th>账号数</th><th>线路出口</th>{billingWritable && <th className="contract-item-actions-col">操作</th>}</tr></thead>
- <tbody>
- {itemRows.map(({ item, index, depth, parentIndex }) => {
- const row = contract.items[index];
- const child = depth > 0;
- const planQuota = quotaById[item.planId];
- const accounts = planQuota === null || planQuota === undefined ? null : planQuota * item.quantity;
- const family = item.planFamily || row?.family || "";
- /** 2026-11-19:叠加服务不单独选出口 —— 子行依从父条目、增量条目依从被引用的既有链路订阅。 */
- const inheritsExit = item.itemMode === "increment" || (item.planFamily !== "link" && item.parentKey !== null);
- const inheritedExits = item.itemMode === "increment"
- ? item.exits
- : parentIndex !== null ? (draft.items[parentIndex]?.exits ?? item.exits) : item.exits;
- const parentLabel = parentIndex !== null ? `条目 ${parentIndex + 1}` : "条目";
- if (editingItem === index) return <tr key={`${item.itemId ?? "new"}-${index}`} className="contract-item-edit-row">
- <td colSpan={billingWritable ? 6 : 5}>
- <div className="contract-item-editor">
- <header>
- <strong>{child ? `叠加服务 · 叠加于${parentLabel}` : `条目 ${index + 1}`}</strong>
- <span>{child ? "档位 × 份数 × 父行出口" : "档位 × 份数 × 出口"}{item.itemMode === "increment" ? "(增量:挂在本客户既有订阅上)" : ""}</span>
- </header>
- <div className="ops-form-grid ops-form-grid--business">
- <label><span className="ops-field-title">套餐档位 <small>{child || item.itemMode === "increment" ? "叠加服务" : "跨境链路"}</small></span><select value={item.planId} onChange={(event) => pickPlan(index, event.target.value)}><option value="">{catalog.loading ? "载入中…" : WORD_UNCONFIGURED}</option>{catalogForPlans.filter((plan) => (child || item.itemMode === "increment" ? plan.plan_family === "addon" : plan.plan_family === "link")).map((plan) => <option key={plan.plan_id} value={plan.plan_id}>{plan.plan_name}{plan.plan_family ? `(${label(ITEM_FAMILY, plan.plan_family)})` : ""}</option>)}</select></label>
- {/* ⛔ 编辑态不再给「交付形态」格:形态只由所引档位带入(D-15),
- 档位下拉的选项文字已带「(跨境链路)/(叠加服务)」标签,列表另有独立列;
- 编辑态再放一格只读回显=第三条重复的信息源(2026-11-19 裁定)。 */}
- {stackablePlan(item.planId) && <label><span className="ops-field-title">份数<FieldHint label="份数说明">叠加服务按份计价,例如「单独境外 IP」按个叠加。</FieldHint></span><Input type="number" min={1} value={item.quantity} onChange={(event) => patchItem(index, { quantity: Number(event.target.value) })} /></label>}
- {inheritsExit ? (
- <div className="ops-contract-exit-cell">
- <span className="ops-field-title">线路出口 <small>{item.itemMode === "increment" ? "依从引用链路" : "依从父条目"}</small></span>
- <span className="ops-contract-exit-inherited" title="叠加服务不单独选线路出口:恒依从所挂跨境链路的出口">{inheritedExits.join("、") || (item.itemMode === "increment" ? "引用链路未登记出口" : "父条目尚未选择")}</span>
- </div>
- ) : item.exits.length > LINE_EXIT_MAX ? (
- /* 2026-11-17 出口改单选后的历史多出口条目:只读呈现,⛔ 可改。 */
- <div className="ops-contract-exit-cell">
- <span className="ops-field-title">线路出口 <small>历史多出口(只读)</small></span>
- <span className="ops-contract-exits">{item.exits.map((exit) => <span key={exit} className="ops-contract-exit is-active is-readonly">{exit}</span>)}</span>
- </div>
- ) : (
- <label className="ops-contract-exit-cell">
- <span className="ops-field-title">线路出口 <b title="必填">*</b><FieldHint label="线路出口说明">线路出口在「套餐配置 → 线路出口」统一维护,此处只做单选;叠加服务不单独选,恒依从所挂跨境链路的出口。</FieldHint></span>
- <select value={item.exits[0] ?? ""} onChange={(event) => toggleExit(index, event.target.value)}>
- <option value="">{exitCatalog.loading ? "载入中…" : exitOptions.length ? "请选择线路出口" : "套餐配置尚未配置线路出口"}</option>
- {exitOptions.map((exit) => <option key={exit} value={exit}>{exit}</option>)}
- </select>
- </label>
- )}
- </div>
- <div className="contract-item-editor-actions">
- <Button variant="ghost" size="sm" disabled={draft.items.length === 1} title={draft.items.length === 1 ? "至少保留一条服务条目" : child ? "删除本条叠加服务(父行保留)" : "删除本条并连带删除其下叠加服务"} onClick={() => removeItem(index)}><Trash2 size={15} />删除{itemSubtreeKeys(draft.items, item.key).length > 1 ? "(含叠加服务)" : "条目"}</Button>
- <Button variant="ghost" size="sm" onClick={() => cancelItem(index)}><X size={15} />撤销本条改动</Button>
- <Button variant="outline" size="sm" onClick={() => setEditingItem(null)}><Check size={15} />完成</Button>
- </div>
- </div>
- </td>
- </tr>;
- return <tr key={`${item.itemId ?? "new"}-${index}`} className={child ? "contract-item-row is-child" : "contract-item-row"}>
- <td>
- {child && <span className="contract-item-child-mark">叠加服务 · 叠加于{parentLabel}</span>}
- {item.itemMode === "increment" && <OpsTag tone="brand">增量</OpsTag>}{" "}
- <strong className="contract-item-plan">{item.planId ? <button type="button" className="contract-ref-link" onClick={() => openRef({ kind: "plan", id: item.planId, name: item.planName })}>{item.planName || item.planId}</button> : <Tri tone="missing" text={WORD_UNCONFIGURED} title="条目未选择套餐档位" />}</strong>
- <small>{item.itemId || "新建条目"}</small>
- {/* D-9:增量条目的父是**既有订阅**(不在本合同内),页面必须交代清楚去哪儿看这条订阅。 */}
- {item.itemMode === "increment" && <small className="contract-item-increment-ref"><Lock size={11} /> 挂既有订阅 <button type="button" className="contract-ref-link" onClick={() => item.refSubscriptionId && openRef({ kind: "order", id: item.refSubscriptionId, name: item.refSubscriptionLabel ?? null })}>{item.refSubscriptionId || "引用订阅未登记"}</button>(本合同为增量合同,⛔ 新建链路)</small>}
- </td>
- <td>{family ? label(ITEM_FAMILY, family) : <Tri tone="missing" text={WORD_UNCONFIGURED} />}</td>
- <td>{item.quantity}</td>
- <td>{accounts === null ? <Tri tone="missing" text={WORD_UNCONFIGURED} title="目录档位额度未下发" /> : accounts}</td>
- <td>{item.exits.join("、") || "—"}</td>
- {billingWritable && <td className="contract-item-actions-col">
- <button type="button" className="contract-row-edit" aria-label={`编辑条目 ${index + 1}`} title={`编辑条目 ${index + 1}`} onClick={() => { setEditingField(null); setEditingItem(index); }}><PencilLine size={15} />编辑</button>
- {/* D-7:叠加服务只从链路节点下新增,页面上⛔ 平级「新增叠加服务」入口。 */}
- {!child && (item.planFamily === "link" || item.itemMode === "increment") && <button type="button" className="contract-row-edit" aria-label={`在条目 ${index + 1} 下添加叠加服务`} title="在该链路下添加叠加服务(出口只能从父行已选出口里取)" onClick={() => { if (item.itemMode === "increment") addIncrementChild(item); else addChildItem(item.key); }}><Plus size={14} />叠加服务</button>}
- </td>}
- </tr>;
- })}
- {!draft.items.length && <OpsTableEmpty colSpan={billingWritable ? 6 : 5}>本合同暂无服务条目。</OpsTableEmpty>}
- </tbody>
- </table>
- </div>
- <div className="contract-items-footer">
- <p className="contract-record-note">{billingLocked ? <>本合同已开通:服务构成(档位/份数)随计费口径冻结,需新增或调整走变更工单。<br /></> : null}条目按整段替换提交;移除已被订阅引用的条目会回 `KLT-L213` 并点名是哪条、被哪几份订阅引用。<br />叠加服务以从属方式挂在跨境链路条目下(D-7:两级树,叠加服务不能再挂叠加服务;出口只能从父行已选出口里取);删父行连同其叠加服务一起删,不留孤儿。</p>
- {billingWritable && <Button variant="outline" size="sm" onClick={addItem}><Plus size={15} />添加条目</Button>}
- </div>
- {itemNotice && <p className="contract-form-summary" role="status">{itemNotice}</p>}
- <p className="contract-record-note">固定 IP 条目已下线:境外 IP 的核定基准改由上方服务构成里的<strong>「叠加服务」档位 × 份数</strong>表达(例如「单独境外 IP」选 2 份=2 个 IP),不再单独登记线路出口 / 带宽档位 / IP 数量三元组。存量 IP 条目保留在库里仅供追溯,页面与接口都不再展示、也不再随合同改写。</p>
- </section>
- <section className="contract-record-section record-tab-panel" id="contract-panel-subscriptions" role="tabpanel" aria-labelledby="contract-tab-subscriptions" hidden={activeTab !== "subscriptions"}>
- <div className="contract-record-section-title"><h2>关联订阅</h2></div>
- <div className="ops-table-wrap record-table-scroll" role="region" aria-label="关联订阅列表" tabIndex={0}><table className="ops-table" style={{ minWidth: 1140 }}><thead><tr><th>套餐 / 订阅</th><th>数量</th><th>关联关系</th><th>方式</th><th>状态</th><th>期间</th><th>订阅价格</th><th>月标准</th><th>实际开通日</th><th>订单号</th></tr></thead><tbody>{(orders ?? []).map((sub) => <tr key={sub.orderId}><td><button type="button" className="contract-ref-link" onClick={() => openRef({ kind: "order", id: sub.orderId, name: sub.planName })}>{sub.planName || sub.orderId}</button><small>{sub.orderId}</small>{sub.parentSubscriptionId && <small className="order-parent-mark">叠加于 {sub.parentSubscriptionId}</small>}</td><td>{sub.quantity ?? <Tri tone="missing" text={WORD_UNCONFIGURED} title="订阅行未下发 quantity(2026-11-17 之前的存量行)" />}</td><td>{relationOf(sub)}</td><td>{sub.orderMode ? label(ORDER_MODE, sub.orderMode) : <Tri tone="missing" text={WORD_UNCONFIGURED} title="订阅方式不再派生(I6 已停用):历史值为空或接口未下发该列时,均显示「未配置」" />}</td><td><OpsStatus tone={orderEffective(sub.status) ? "success" : "neutral"}>{label(ORDER_STATUS, sub.status ?? "") || sub.status || WORD_UNCONFIGURED}</OpsStatus></td><td>{sub.startDate && sub.endDate ? `${sub.startDate} 至 ${sub.endDate}` : WORD_UNCONFIGURED}</td><td>{cell(sub.annualPriceCents, (value) => money(Number(value) / 100))}</td><td>{cell(sub.monthlySettleCents, (value) => money(Number(value) / 100))}</td><td>{sub.actualOpenedAt ? sub.actualOpenedAt.slice(0, 10) : <Tri tone="missing" text={WORD_UNCONFIGURED} title="开户竣工未回填实际开通日" />}</td><td>{cell(sub.orderNo)}</td></tr>)}</tbody></table></div>{orders === undefined ? <p className="contract-record-note"><Tri tone="fail" text={WORD_FETCH_FAILED} title="合同详情接口未返回 orders 键" /></p> : !orders.length && <p className="contract-record-note">暂无关联订阅。</p>}<p className="contract-record-note">口径:按 <code>subscription.contract_id</code> 归集本合同名下订阅;「关联关系」列交代每条订阅挂在本合同下的落点——由第 N 条服务条目签约,或由升降配替换原订阅(原订阅仍在表内,已被截期)。两枚落点都没有=存量行只按合同归属,不臆断首签/续签。</p>
- </section>
- {writable && <><section className="contract-record-section record-tab-panel" id="contract-panel-billing" role="tabpanel" aria-labelledby="contract-tab-billing" hidden={activeTab !== "billing"}><div className="contract-record-section-title"><h2>出账信息</h2></div><p className="contract-record-note"><Tri tone="missing" text={WORD_UNCONFIGURED} title="出账与对账属第 6 册:后端未提供期次应收、成本快照与对账清单接口" /></p><p className="contract-record-note">出账期次、应收与已出账金额属第 6 册(出账/对账)口径,klt-bos 本期未提供相应接口;页面不以 0 元、0 期冒充已出账。</p></section>
- <section className="contract-record-section record-tab-panel" id="contract-panel-tickets" role="tabpanel" aria-labelledby="contract-tab-tickets" hidden={activeTab !== "tickets"}><div className="contract-record-section-title"><h2>关联工单</h2></div>
- {relatedTickets.loading ? <p className="contract-record-note">正在按合同读取工单台账…</p>
- : relatedTickets.error ? <p className="contract-record-note"><Tri tone="fail" text={WORD_FETCH_FAILED} title={relatedTickets.error.message} /> 工单台账取数失败,不得把「查不了」渲染成「0 张」。</p>
- : relatedTickets.data?.rows?.length ? <div className="ops-table-wrap record-table-scroll" role="region" aria-label="关联工单列表" tabIndex={0}><table className="ops-table" style={{ minWidth: 720 }}><thead><tr><th>我方工单号</th><th>类型</th><th>状态</th><th>创建日</th><th>完成日</th></tr></thead><tbody>{relatedTickets.data.rows.map((ticket) => <tr key={ticket.ticket_id}><td><Link className="contract-ref-link" to={`/work-orders/${encodeURIComponent(ticket.ticket_id)}`} state={outgoingState}>{ticket.ticket_no ?? ticket.ticket_id}<ArrowRight size={14} /></Link></td><td>{typeLabel(ticket.ticket_type)}</td><td><OpsStatus tone={ticket.status === "completed" || ticket.status === "settled" ? "success" : ticket.status === "processing" || ticket.status === "pending" ? "warning" : "neutral"}>{statusLabel(ticket.status, ticket.ticket_type)}</OpsStatus></td><td>{fmtDate(ticket.created_at)}</td><td>{fmtDate(ticket.completed_at)}</td></tr>)}</tbody></table></div>
- : <p className="contract-record-note">本合同暂无关联工单(按合同下订阅集合现查 <code>/ticket/list@v1</code>,服务端可见范围内为空)。</p>}
- <ListPager total={ticketTotal} page={ticketPage} pageSize={LIST_PAGE_SIZE} onPageChange={setTicketPage} unit="张" />
- <p className="contract-record-note">口径:工单按其挂载的订阅(订阅)回挂到合同;合同内多条服务条目各自形成订阅,工单只归其实际挂载的那一条。列表服务端分页(默认每页 {LIST_PAGE_SIZE},页码 1 基)。</p></section></>}
- <section className="contract-record-section contract-log-card record-tab-panel" id="contract-panel-history" role="tabpanel" aria-labelledby="contract-tab-history" hidden={activeTab !== "history"}>
- <div className="contract-record-section-title"><h2>修改记录</h2></div>
- <span className="contract-log-meta">{changeLog.loading && !changeLog.data ? "读取中" : `${(changeLog.data?.items?.length ?? 0) + olderLogs.length} 条${logCursor ? "+" : ""}`}</span>
- {changeLog.error && <small className="contract-log-error"><Tri tone="fail" text={WORD_FETCH_FAILED} title={changeLog.error.message} /></small>}
- {!changeLog.error && changeLog.data && !changeLog.data.items?.length && <small className="contract-log-empty">暂无修改记录(本合同自录入后未发生改动)。</small>}
- {!changeLog.error && changeLog.data && (
- <ol className="contract-log-list">
- {[...(changeLog.data.items ?? []), ...olderLogs].map((item, index) => {
- const fields = changeLogFields(item);
- const summary = changeLogSummary(item);
- return (
- <li key={`${item.cursor ?? "no-cursor"}-${index}`} className="contract-log-row">
- <div className="contract-log-head">
- <time>{item.occurred_at ? formatLogTime(item.occurred_at) : "时间未记录"}</time>
- <b>{item.actor.name || item.actor.user_id || "操作人未记录"}</b>
- <OpsTag tone={item.action === "contract.delete" ? "danger" : item.action === "contract.create" ? "success" : "neutral"}>{item.action_label}</OpsTag>
- </div>
- {summary.length > 0 && <ul className="contract-log-changes">{summary.map((line) => <li key={line}>{line}</li>)}</ul>}
- {fields.length > 0 && (
- <details className="contract-log-detail">
- <summary>字段明细({fields.length})</summary>
- <dl>{fields.map((field) => <div key={field.key}><dt>{field.label}</dt><dd><span>{field.old}</span><ArrowRight size={12} /><span>{field.new}</span></dd></div>)}</dl>
- </details>
- )}
- </li>
- );
- })}
- </ol>
- )}
- {logMoreError && <small className="contract-log-error"><Tri tone="fail" text={logMoreError} /></small>}
- {logCursor && !changeLog.error && (
- <Button variant="outline" size="sm" disabled={logMoreBusy} onClick={loadOlderLogs}>{logMoreBusy ? "正在读取…" : "载入更早的记录"}</Button>
- )}
- <small className="contract-log-note">每次保存均记录修改人、时间及字段变化。</small>
- </section>
- </div>
- {writable && dirty && <div className="contract-savebar" role="region" aria-label="合同修改">
- <div><strong>有未保存的修改</strong><span>保存按整段替换提交服务构成(契约 §3.2)。</span></div>
- {error && <p className="ops-form-error" role="alert">{error}</p>}
- <div className="contract-savebar-actions">
- <Button variant="outline" size="sm" disabled={saving} onClick={discard}>放弃修改</Button>
- <Button size="sm" disabled={saving} onClick={save}>{saving ? "正在保存…" : "保存修改"}</Button>
- </div>
- </div>}
- {!dirty && error && <p className="ops-form-error" role="alert">{error}</p>}
- {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
- {refStack.length > 0 && <ReferenceDrawer stack={refStack} onPush={openRef} onBack={() => setRefStack((stack) => stack.slice(0, -1))} onClose={() => setRefStack([])} />}
- </section>;
- }
|