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 ? : value === null || value === "" ? : 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 {shown}{lockedReason && }; if (!editing) return {shown} ; 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 {selectOptions ? ( ) : ( onChange(event.target.value)} onKeyDown={onKeyDown} /> )} {error} ; } 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([]); const [logCursor, setLogCursor] = useState(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(null); const [editingField, setEditingField] = useState(null); const [editingItem, setEditingItem] = useState(null); const [tab, setTab] = useState("overview"); useEffect(() => setTab("overview"), [param]); const [error, setError] = useState(""); const [fieldError, setFieldError] = useState(null); const [saving, setSaving] = useState(false); const [notice, setNotice] = useState(""); /** P1(D-7):级联删条目后的提示(子行随父走,必须告诉用户一起删了几条)。 */ const [itemNotice, setItemNotice] = useState(""); const [refStack, setRefStack] = useState([]); 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 = (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 ? {fieldError.message} : null); const patchItem = (index: number, values: Partial) => { 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
{back.label}

正在从合同接口读取合同资料…

; if (record.error && !record.data) return
{back.label}

合同资料取数失败

; if (!contract) return
{back.label}

合同不存在或不在当前负责范围

; if (!draft) return
{back.label}

正在装载合同草稿…

; 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 <> {sub.contractItemId ? (itemNo ? `第 ${itemNo} 条服务条目签约` : `服务条目 ${sub.contractItemId} 签约`) : "仅按合同归属(未挂服务条目)"} {replaced && 升降配替换 · 替代 } ; }; const state = draft.start && draft.end ? contractStatusOf(draft.start, draft.end) : null; const LOCK_REASON: Record = { 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 ? : WORD_UNCONFIGURED); /** 档案联查不可用时的统一空态(与旧「客户主体」行同一判据)。 */ const profileMissing = profile === null ? : contract.customerId ? : ; 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 ; const lic = profile.license; if (!lic || lic.status === "none") return "未登记"; if (lic.status === "expired") return <>已超期{lic.file_name ? `:${lic.file_name}` : ""}(留存期满,不下发下载); if (lic.status === "viewable") { return lic.view_url ? {lic.file_name || "营业执照影像"}查看影像 : <>{lic.file_name || "营业执照影像"}(下载签名未取到); } 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
{back.label}
合同详情

{contract.no}

{customerId || profile ? : contract.customer || WORD_UNCONFIGURED}{customerId ? `(${customerId})` : ""} · 外部单号 {draft.externalNo || "未登记"} · 第 {ordinalText} 份合同

{contract.source === undefined || contract.source === null ? : {contract.source}}{state ? {state} : }{isExpiringSoon(record.data?.end_date) ? 快到期 · {expiringLabel(record.data?.end_date)} : null}{contract.opened === undefined || contract.opened === null ? : {contract.opened ? "已开通" : "未开通"}}
{writable &&

悬停可编辑项显示铅笔,点击即切换编辑状态

}
{writable && record.data?.contract_id && isExpiringSoon(record.data?.end_date) ? : null}
{lockNote &&

{lockNote}。录入经办人(录入账号)由录入时账号自动带入机构/姓名/联系方式,建后一律只读。

} {replacements.length > 0 &&
本次已按本合同生成 {replacements.length} 条订阅
    {replacements.map((row) =>
  • {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})` : ""}
  • )}
}
合同总额 {}} 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")} />{draft.serviceMonths ? `服务期 ${draft.serviceMonths} 个月` : } · 折扣率 {draft.discountRate ? `${draft.discountRate}%` : "100%"}
账号数{accountsKnown ? accountTotal : }按服务条目派生
境外 IP{overseasIpTotal}按「叠加服务」档位 × 份数派生 · {exits.join("、") || "无出口"}
关联订阅{orders ? orders.length : }{orders ? `生效中 ${orders.filter((item) => orderEffective(item.status)).length} 份` : "详情接口未返回关联订阅"}
应收合计出账与对账接口未提供
已出账金额出账与对账接口未提供
{writable && <> }
{writable && dirty &&
有未保存的修改保存按整段替换提交服务构成(契约 §3.2)。
{error &&

{error}

}
} {!dirty && error &&

{error}

} {notice && setNotice("")} />} {refStack.length > 0 && setRefStack((stack) => stack.slice(0, -1))} onClose={() => setRefStack([])} />}
; }