ContractDetailPages.tsx 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
  2. import { ArrowLeft, Plus, Trash2, Upload, X } from "lucide-react";
  3. import { FetchError } from "../components/fetchError";
  4. import { useNavigate, useParams } from "react-router";
  5. import { Button } from "../components/ui/button";
  6. import { Input } from "../components/ui/input";
  7. import { TreeSelect } from "../components/ui/tree-select";
  8. import { CustomerTeamSelect } from "../components/CustomerTeamSelect";
  9. import { contractRawByParam } from "../lib/contract-demo";
  10. import { contractAttachmentDiscard, contractCreate, contractCustomerLookup, contractUpdate, rowsOf } from "../lib/api/bos";
  11. import { ApiError } from "../lib/api/http";
  12. import { OPTIONS, label, PAY_CYCLE, SUBJECT_TYPE, USE_CATEGORY } from "../lib/api/labels";
  13. import { WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
  14. import { Tri } from "../components/triState";
  15. import { useCatalogPlans, useIpBandwidthTiers, useLineExits } from "../lib/package-catalog";
  16. import { IP_BANDWIDTH_TIERS, IP_COUNT_MAX, IP_TIER_UNCOMMITTED, LINE_EXIT_MAX } from "../domain/contract-items";
  17. import type { ContractMissing, ContractRequiredKey, IpRowDraft } from "../domain/contract-items";
  18. import { REQUIRED_KEY_BY_DRAFT, buildContractWrite, draftFromRow, emptyDraft, emptyItem, emptyIpRow, firstItemExit, type ContractDraft as Draft, type ItemDraft } from "../domain/contract-draft";
  19. import { regionTreeNodes } from "../lib/region-tree";
  20. import { useOrganizationData } from "../lib/organization-demo";
  21. import type { ContractCreateResult } from "../lib/api/types";
  22. import { uploadContractAttachment, uploadCustomerLicense, type UploadedObject } from "../lib/api/oss-upload";
  23. import { contractAttachmentLabel } from "../lib/contract-attachments";
  24. import { useLoad } from "../lib/useLoad";
  25. import { useDemoIdentity } from "../lib/demo-session";
  26. import "../styles/operations.css";
  27. /**
  28. * 客户候选:`contract/customer_lookup` 三种命中方式,未命中转自由录入(⛔ 红叉、⛔ 11102)。
  29. *
  30. * **输入防抖**:连击期间只重置计时器,`CUSTOMER_LOOKUP_DEBOUNCE_MS` 内不再发第二次请求;
  31. * 检索词去空白后才作为依赖 ⇒ 尾部空格/前后空白变动不触发重取。
  32. */
  33. const CUSTOMER_LOOKUP_DEBOUNCE_MS = 300;
  34. function useCustomerCandidates(term: string) {
  35. const [debounced, setDebounced] = useState(term);
  36. useEffect(() => {
  37. const timer = window.setTimeout(() => setDebounced(term), CUSTOMER_LOOKUP_DEBOUNCE_MS);
  38. return () => window.clearTimeout(timer);
  39. }, [term]);
  40. /** 服务端只认 `query_type` + `value` 两键(`identity` 走 HMAC 密钥通路、dev 未接线会回 `KLT-S406`)⇒ 主体号走 `credit_code`,其余走名称模糊。 */
  41. const query = debounced.trim();
  42. const load = useLoad(() => {
  43. if (query.length < 2) return Promise.resolve(null);
  44. const queryType = /^KL-\d{4}-\d{6}$/.test(query) ? "credit_code" : "keyword";
  45. return contractCustomerLookup({ query_type: queryType, value: query });
  46. }, [query]);
  47. /** 回带结果对应的检索词:调用方据此判断「候选还是上一次的」(⛔ 据此清空候选,见页面内注释)。 */
  48. return { ...load, term: query };
  49. }
  50. export function ContractEditorPage() {
  51. const { no } = useParams();
  52. const navigate = useNavigate();
  53. const identity = useDemoIdentity();
  54. const editing = Boolean(no);
  55. const catalog = useCatalogPlans();
  56. const plans = useMemo(() => rowsOf(catalog.data?.items), [catalog.data]);
  57. /** 线路出口目录(套餐配置统一维护):合同条目与 IP 条目只从这里选(2026-11-15 裁定)。 */
  58. const exitCatalog = useLineExits();
  59. /** 带宽档位目录(2026-11-16 起可配置):IP 条目的档位只从这里选。 */
  60. const tierCatalog = useIpBandwidthTiers();
  61. const tierOptions = useMemo(() => {
  62. const items = tierCatalog.data?.items ?? [];
  63. if (items.length) {
  64. return items.map((item) => ({
  65. value: item.bandwidth_tier_mbps === null ? IP_TIER_UNCOMMITTED : String(item.bandwidth_tier_mbps),
  66. label: item.tier_name,
  67. }));
  68. }
  69. return [
  70. ...IP_BANDWIDTH_TIERS.map((tier) => ({ value: String(tier), label: `${tier} 兆` })),
  71. { value: IP_TIER_UNCOMMITTED, label: "不承诺带宽" },
  72. ];
  73. }, [tierCatalog.data]);
  74. const tierValues = useMemo(() => tierOptions.map((option) => option.value), [tierOptions]);
  75. const record = useLoad(() => contractRawByParam(no), [no]);
  76. const [draft, setDraft] = useState<Draft>(emptyDraft);
  77. const [customerId, setCustomerId] = useState<string | null>(null);
  78. const [customerTerm, setCustomerTerm] = useState("");
  79. const [error, setError] = useState("");
  80. /** 必填项的单字段红显(需求 §5.3 第 522 行「不保存并红显该字段」),提示语照抄后端 `60004` 原话,⛔ 只弹一句总提示找不到错在哪。 */
  81. const [fieldError, setFieldError] = useState<ContractMissing | null>(null);
  82. const [submitting, setSubmitting] = useState(false);
  83. /**
  84. * 合同附件(单份,2026-11-16 定案):选中即直传平台对象存储,成功后只把**对象键**挂进
  85. * `draft.attachmentUrl`(字面量须与后端 `CONTRACT_ATTACHMENT_KEY_PREFIX` 同前缀)。
  86. * ⛔ 字节流/上传凭证经本服务;查看地址由详情读口现签,⛔ 前端缓存签名。
  87. */
  88. const attachmentInput = useRef<HTMLInputElement | null>(null);
  89. const [attachmentBusy, setAttachmentBusy] = useState(false);
  90. const [attachmentError, setAttachmentError] = useState("");
  91. /** 本次刚上传的原始文件名(键里不含文件名 ⇒ 刷新后按后缀显示「合同附件.<ext>」)。 */
  92. const [attachmentName, setAttachmentName] = useState("");
  93. /**
  94. * 本页**刚上传、还没被任何合同引用**的对象键(孤儿回收清单)。
  95. *
  96. * 平台只有「即时删除」一条通道(`object/delete@v1`,见 unified-oss §6.6.10:不做后台遍历删对象),
  97. * 所以「换了/移除了/取消了」的那一刻必须由本页把没人要的那一份退回去([`discardPendingAttachments`])。
  98. * 服务端还会再查一次引用面(仍被合同引用就拒删)⇒ 这里可以放宽心调,⛔ 当成前端独占真相。
  99. */
  100. const pendingAttachmentKeys = useRef<string[]>([]);
  101. useEffect(() => {
  102. if (record.data) setDraft(draftFromRow(record.data));
  103. }, [record.data]);
  104. /**
  105. * 把清单里的对象键交给服务端回收(best-effort):失败⛔ 拦用户、⛔ 回滚草稿——
  106. * 用户的动作(换文件/移除/取消)已经完成,回收只是桶侧的清尾。
  107. */
  108. const discardPendingAttachments = (keys?: string[]) => {
  109. const targets = keys ?? pendingAttachmentKeys.current;
  110. if (!targets.length) return;
  111. pendingAttachmentKeys.current = pendingAttachmentKeys.current.filter(
  112. (key) => !targets.includes(key),
  113. );
  114. for (const objectKey of targets) {
  115. void contractAttachmentDiscard({ object_key: objectKey }).catch(() => {});
  116. }
  117. };
  118. /** 离开本页(返回/取消)时把没落库的上传一起退掉:`useRef` 读的是最新清单,⛔ 闭包快照。 */
  119. useEffect(() => () => discardPendingAttachments(), []);
  120. /**
  121. * 新建态的「运营商经办人」姓名默认取当前登录身份(与姓名同一来源、可改,⛔ 写死号码);
  122. * `auth/context@v1` 实测只回 7 个键、不含手机号 ⇒ 取不到就留空由必填校验拦下,⛔ 造号。
  123. * ⚠️ 这一组是**交接单上的运营商侧联系人**,不是「录入账号」(`created_by`,服务端另写、恒只读);
  124. * 建后它随档案轴(未开通且 72h 内或未到期)仍可改,与「交接单日期」同一命运。
  125. */
  126. useEffect(() => {
  127. if (editing || !identity) return;
  128. setDraft((current) => ({ ...current, agent: current.agent || identity.name, agentPhone: current.agentPhone || identity.phone || "" }));
  129. }, [editing, identity]);
  130. /**
  131. * 客户检索=**输入防抖**(300ms 内的连击只打一次 `contract/customer_lookup@v1`)
  132. * + **沿用上一次结果**:防抖窗口里⛔ 把候选清空——否则每敲一个字下拉就消失再出现,列表整体抖一下。
  133. */
  134. const lookup = useCustomerCandidates(customerTerm);
  135. const trimmedTerm = customerTerm.trim();
  136. /** 输入已变、检索还没跟上(防抖计时中或请求在飞):候选沿用旧结果,只在列表底部标「正在检索…」。 */
  137. const lookupStale = lookup.term !== trimmedTerm;
  138. const searching = trimmedTerm.length >= 2 && (lookupStale || lookup.loading);
  139. const candidates = lookup.data?.customers ?? [];
  140. const freeText = !lookup.data?.matched && trimmedTerm.length >= 2;
  141. const customerLabel = record.data?.customer_name || (record.data?.customer_id ? record.data.customer_id : WORD_UNCONFIGURED);
  142. /**
  143. * 客户检索=**输入框内下拉**(业主 2026-11-16 定案):命中项直接挂在输入框下方的候选列表,
  144. * ⛔ 另起一个「命中的客户档案」下拉。选中后输入框锁定该客户并显示 × 清除,再输入即重新检索。
  145. */
  146. const customerInput = useRef<HTMLInputElement | null>(null);
  147. const [customerOpen, setCustomerOpen] = useState(false);
  148. const [customerActive, setCustomerActive] = useState(0);
  149. const showCustomerOptions = customerOpen && !customerId && trimmedTerm.length >= 2 && (candidates.length > 0 || searching);
  150. const activeCustomer = showCustomerOptions && candidates.length ? (customerActive < candidates.length ? customerActive : 0) : -1;
  151. const pickCustomer = (hit: (typeof candidates)[number]) => {
  152. setCustomerId(hit.customer_id);
  153. setCustomerTerm(hit.customer_name);
  154. setCustomerOpen(false);
  155. setCustomerActive(0);
  156. setError("");
  157. };
  158. const clearCustomer = () => {
  159. setCustomerId(null);
  160. setCustomerTerm("");
  161. setCustomerOpen(false);
  162. setCustomerActive(0);
  163. setError("");
  164. customerInput.current?.focus();
  165. };
  166. const onCustomerKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
  167. if (customerId) {
  168. if (event.key === "Escape") { event.preventDefault(); clearCustomer(); }
  169. return;
  170. }
  171. if (event.key === "ArrowDown" || event.key === "ArrowUp") {
  172. if (!candidates.length) return;
  173. event.preventDefault();
  174. if (!customerOpen) { setCustomerOpen(true); return; }
  175. const delta = event.key === "ArrowDown" ? 1 : -1;
  176. setCustomerActive((current) => (current + delta + candidates.length) % candidates.length);
  177. return;
  178. }
  179. if (event.key === "Enter") {
  180. if (!showCustomerOptions || activeCustomer < 0) return;
  181. event.preventDefault();
  182. pickCustomer(candidates[activeCustomer]);
  183. return;
  184. }
  185. if (event.key === "Escape" && customerOpen) { event.preventDefault(); setCustomerOpen(false); }
  186. };
  187. /**
  188. * 客户内联建档段(需求 §5.3 CU-13;业主 2026-11-16 定案):
  189. * **命中已有客户 ⇒ 本段整段不出现**(命中项直接选在上方输入框内的候选下拉,选中后输入框锁定并带 × 清除);
  190. * 未命中 ⇒ 在客户名称下方展开建档必填项,含运营商与运维团队两个下拉。
  191. * ⚠️ 本段只收集 CU-13 第 1 步字段,逐项与 `/customer/create@v1` 同源;
  192. * 企业营业执照影像**可留空**(本通道例外),建档后到客户档案「登记材料」格补传。
  193. */
  194. const org = useOrganizationData(["regions", "operators", "maintenanceTeams"]);
  195. const regionTree = useMemo(() => regionTreeNodes(org.regions, org.regions.map((item) => item.id)), [org.regions]);
  196. const [inline, setInline] = useState({ subject: "enterprise", idNo: "", contact: "", phone: "", address: "", regionId: "", operatorId: "", teamId: "", login: "", mobile: "" });
  197. const [licenseObj, setLicenseObj] = useState<UploadedObject | null>(null);
  198. const [licenseBusy, setLicenseBusy] = useState(false);
  199. const [licenseError, setLicenseError] = useState("");
  200. /** 内联建档成功后的回执(客户号/主账号/激活码口径);合同已生成,下一步是去合同详情。 */
  201. const [created, setCreated] = useState<{ contractId: string; customer: NonNullable<ContractCreateResult["inline_customer"]> } | null>(null);
  202. const setInlineField = <K extends keyof typeof inline>(key: K, value: (typeof inline)[K]) => {
  203. setInline((current) => ({ ...current, [key]: value }));
  204. setError("");
  205. };
  206. /** 所挂区域沿父链找到最近的「省」节点(与后端 `province_of` 同口径:⛔ 按名字前缀猜)。 */
  207. const provinceId = useMemo(() => {
  208. if (!inline.regionId) return "";
  209. const byId = new Map(org.regions.map((item) => [item.id, item]));
  210. let node = byId.get(inline.regionId);
  211. // `Region.level` 是层级序号(0=省、1=市、2=区县;null=未定级,⛔ 按父子深度猜)。
  212. while (node && node.level !== 0 && node.parent) node = byId.get(node.parent);
  213. return node && node.level === 0 ? node.id : "";
  214. }, [org.regions, inline.regionId]);
  215. /** 运营商候选=所挂区域省份下可见的档案(省份一致性是后端硬校验 KLT-C008);为空则退回全量,由后端判定。 */
  216. const operatorOptions = useMemo(() => {
  217. const sameProvince = provinceId ? org.operators.filter((item) => item.region === provinceId) : [];
  218. return (sameProvince.length ? sameProvince : org.operators).map((item) => ({ id: item.id, name: item.name }));
  219. }, [org.operators, provinceId]);
  220. useEffect(() => {
  221. setInline((current) => (current.operatorId || !operatorOptions.length ? current : { ...current, operatorId: operatorOptions[0].id }));
  222. }, [operatorOptions]);
  223. useEffect(() => {
  224. setInline((current) => (current.teamId || !org.maintenanceTeams.length ? current : { ...current, teamId: org.maintenanceTeams[0].id }));
  225. }, [org.maintenanceTeams]);
  226. /** 区域换了 ⇒ 原运营商可能跨省,重新预选第一个(⛔ 留着让后端回 C008)。 */
  227. useEffect(() => {
  228. setInline((current) => {
  229. if (!provinceId || operatorOptions.some((item) => item.id === current.operatorId)) return current;
  230. return { ...current, operatorId: operatorOptions[0]?.id ?? "" };
  231. });
  232. // eslint-disable-next-line react-hooks/exhaustive-deps
  233. }, [provinceId]);
  234. const inlineSubjectOptions = (["enterprise", "individual", "sole_proprietor"] as const).map((code) => ({ code, name: SUBJECT_TYPE[code] ?? code }));
  235. const set = <K extends keyof Draft>(key: K, value: Draft[K]) => {
  236. setDraft((current) => ({ ...current, [key]: value }));
  237. setError("");
  238. setFieldError((current) => (current && REQUIRED_KEY_BY_DRAFT[key] === current.key ? null : current));
  239. };
  240. /** 命中必填项的字段红显+原话(需求 §5.3 第 522 行「不保存并红显该字段」)。 */
  241. const invalidOf = (key: ContractRequiredKey) => (fieldError?.key === key ? "true" : undefined);
  242. const requiredErrorOf = (key: ContractRequiredKey) => (fieldError?.key === key ? <span className="ops-field-error">{fieldError.message}</span> : null);
  243. const patchItem = (index: number, patch: Partial<ItemDraft>) => {
  244. setDraft((current) => ({ ...current, items: current.items.map((item, i) => (i === index ? { ...item, ...patch } : item)) }));
  245. setError("");
  246. };
  247. const removeItem = (index: number) => setDraft((current) => ({ ...current, items: current.items.filter((_, i) => i !== index) }));
  248. /** 换档位只换档位带出的口径(数量/带宽/价格),⛔ 清空已选出口——出口是独立于档位的目录配置。 */
  249. const pickPlan = (index: number, planId: string) => patchItem(index, { planId, planName: plans.find((plan) => plan.plan_id === planId)?.plan_name ?? "" });
  250. /** 线路出口只允许从套餐配置选择(2026-11-15 裁定):出口清单在「套餐配置 → 线路出口」维护。 */
  251. const toggleExit = (index: number, exit: string) => {
  252. const item = draft.items[index];
  253. const active = item.exits.includes(exit);
  254. if (!active && item.exits.length >= LINE_EXIT_MAX) {
  255. setError(`条目 ${index + 1} 的线路出口最多 ${LINE_EXIT_MAX} 个。`);
  256. return;
  257. }
  258. patchItem(index, { exits: active ? item.exits.filter((value) => value !== exit) : [...item.exits, exit] });
  259. };
  260. /** 合同级 IP 条目(04 册 §4.4):未勾选「有固定 IP 需求」⇒ 本表零行,勾选才给一条空行。 */
  261. const setNeedIp = (on: boolean) => {
  262. setDraft((current) => ({ ...current, needIp: on, ipRows: on ? (current.ipRows.length ? current.ipRows : [emptyIpRow(firstItemExit(current.items))]) : [] }));
  263. setError("");
  264. };
  265. const patchIpRow = (index: number, patch: Partial<IpRowDraft>) => {
  266. setDraft((current) => ({ ...current, ipRows: current.ipRows.map((row, i) => (i === index ? { ...row, ...patch } : row)) }));
  267. setError("");
  268. };
  269. const addIpRow = () => {
  270. setDraft((current) => ({ ...current, ipRows: [...current.ipRows, emptyIpRow(firstItemExit(current.items))] }));
  271. setError("");
  272. };
  273. const removeIpRow = (index: number) => {
  274. setDraft((current) => ({ ...current, ipRows: current.ipRows.filter((_, i) => i !== index) }));
  275. setError("");
  276. };
  277. /** 出口候选=套餐配置清单;历史数据里已出现的值也保留,避免旧合同编辑时选项凭空消失。 */
  278. const exitOptions = useMemo(() => {
  279. const names = (exitCatalog.data?.items ?? []).map((item) => item.exit_name);
  280. const legacy = [...draft.items.flatMap((item) => item.exits), ...draft.ipRows.map((row) => row.line_exit.trim()).filter(Boolean)];
  281. return [...new Set([...names, ...legacy])];
  282. }, [exitCatalog.data, draft.items, draft.ipRows]);
  283. /** 固定 IP 条目的出口候选=**上方服务构成条目已选出口**(2026-11-16 裁定,⛔ 全量目录)。 */
  284. const itemExitOptions = useMemo(
  285. () => [...new Set(draft.items.flatMap((item) => item.exits))],
  286. [draft.items],
  287. );
  288. async function save() {
  289. if (!identity) { setError("请先登录后再提交合同;写入权限由服务端判定。"); return; }
  290. if (submitting) return;
  291. if (!editing && !customerId && !freeText) { setError("请输入客户名称或信用码检索签约主体。"); return; }
  292. /** 未命中客户 ⇒ 内联建档段的必填集(CU-13 第 1 步;识别号同时是重试幂等键,⛔ 省)。 */
  293. if (!editing && !customerId) {
  294. const idNo = inline.idNo.trim().replace(/[\s-]/g, "").toUpperCase();
  295. const missing: string[] = [];
  296. if (!idNo) missing.push("客户识别号");
  297. if (!inline.regionId) missing.push("挂载区域");
  298. if (!inline.operatorId) missing.push("运营商");
  299. if (!inline.teamId) missing.push("运维团队");
  300. if (missing.length) { setError(`新建客户缺少:${missing.join("、")}(需求 §5.3 CU-13 第 1 步必填)`); return; }
  301. if (!/^[A-Z0-9]{18}$|^\d{15}$/.test(idNo)) {
  302. setError("客户识别号格式不符:应为 18 位统一社会信用代码/组织代码,或 15 位旧营业执照号。");
  303. return;
  304. }
  305. }
  306. const built = buildContractWrite(draft, tierValues);
  307. if (!built.ok) { setFieldError(built.fieldError ?? null); setError(built.error); return; }
  308. const w = built.write;
  309. /**
  310. * 写入口径必填 5 项(2026-11-14 探针实测 `contract/create@v1` 逐字段短路的 `60004`):
  311. * 付款周期(需求 §5.3 第 523 行)→ 合同金额(第 522 行「须大于 0…不保存并红显该字段」)→
  312. * 经办人姓名 → 经办人联系电话 → 交接单日期;提示语照抄后端原话并红显命中的那个字段,
  313. * `agent_org` 选填(不送也 `10000`)⇒ ⛔ 参与校验。校验同源 `domain/contract-draft`。
  314. */
  315. /** IP 条目随合同整表替换(04 册 §4.3);未勾选=送空数组=清空。⛔ 另送 `has_fixed_ip`:后端按 `ip_entries` 非空推导该触发位,`false` 却不带空表反而回 11103。 */
  316. const shared = {
  317. ...(w.externalNo ? { external_no: w.externalNo } : {}),
  318. contract_amount_cents: w.contractAmountCents,
  319. pay_cycle: w.payCycle,
  320. start_date: w.startDate,
  321. end_date: w.endDate,
  322. agent_name: w.agentName,
  323. agent_mobile: w.agentMobile,
  324. agent_handover_on: w.agentHandoverOn,
  325. /** `agent_org`=选填:恒送 trim 值(空串=后端 `text_param` 置 `NULL`),⛔ 因缺它而拦人。 */
  326. agent_org: w.agentOrg,
  327. /** 附件单值:空串=清空(后端 `text_param` 置 `NULL`)⇒ ⛔ 省略键,否则「移除附件」永远存不下去。 */
  328. attachment_url: w.attachmentUrl.trim(),
  329. service_items: w.serviceItems,
  330. ...(w.ipCarried ? { ip_entries: w.ipEntries } : {}),
  331. };
  332. setSubmitting(true);
  333. setError("");
  334. try {
  335. if (editing) {
  336. const row = record.data;
  337. if (!row?.contract_id) { setError("合同主键未取到,无法保存。"); return; }
  338. const version = Number(row.row_version);
  339. if (!row.contract_id || !Number.isFinite(version)) { setError("未取到合同主键或并发版本(row_version),无法保存。"); return; }
  340. await contractUpdate({
  341. contract_id: row.contract_id,
  342. row_version: version,
  343. ...shared,
  344. });
  345. // 落库成功 ⇒ 清单里的对象键已被合同引用(服务端也会拒删),⛔ 别再当孤儿回收。
  346. pendingAttachmentKeys.current = [];
  347. navigate(`/contracts/${encodeURIComponent(row.contract_id)}`);
  348. } else {
  349. const res = await contractCreate({
  350. ...shared,
  351. ...(draft.contractNo.trim() ? { contract_no: draft.contractNo.trim() } : {}),
  352. ...(customerId
  353. ? { customer_id: customerId }
  354. : {
  355. customer_inline: {
  356. customer_name: customerTerm.trim(),
  357. subject_type: inline.subject,
  358. id_code: inline.idNo.trim().replace(/[\s-]/g, "").toUpperCase(),
  359. ...(inline.contact.trim() ? { contact_name: inline.contact.trim() } : {}),
  360. ...(inline.phone.trim() ? { contact_mobile: inline.phone.trim() } : {}),
  361. ...(inline.address.trim() ? { address: inline.address.trim() } : {}),
  362. parent_node_id: inline.regionId,
  363. operator_id: inline.operatorId,
  364. ops_team_ids: [inline.teamId],
  365. // 影像本通道可留空;非企业⛔ 送(与 `/customer/create@v1` 同一条判据)。
  366. ...(inline.subject === "enterprise" && licenseObj ? { license: { object_key: licenseObj.object_key, file_name: licenseObj.file_name } } : {}),
  367. ...(inline.login.trim() ? { primary_username: inline.login.trim() } : {}),
  368. ...(inline.mobile.trim() ? { primary_mobile: inline.mobile.trim() } : {}),
  369. },
  370. }),
  371. });
  372. // 合同已生成 ⇒ 附件对象已被引用(服务端也会拒删)⇒ 清空孤儿清单。
  373. pendingAttachmentKeys.current = [];
  374. // 内联建档成功 ⇒ 停在回执页展示客户号与主账号(激活码明文由「导出激活码」取,⛔ 在此伪造)。
  375. if (res?.inline_customer) {
  376. setCreated({ contractId: res.contract_id, customer: res.inline_customer });
  377. return;
  378. }
  379. navigate(`/contracts/${encodeURIComponent(res?.contract_id ?? "")}`);
  380. }
  381. } catch (e) {
  382. setError(e instanceof ApiError ? e.message : "保存失败,请稍后重试。");
  383. setSubmitting(false);
  384. }
  385. }
  386. /**
  387. * 营业执照影像:选中即直传平台对象存储(与客户建档同一通路、同一前缀),成功后才把对象键挂进载荷。
  388. * 本通道**可留空**(业主 2026-11-16 定案);留空时回执会带 `license_pending`,
  389. * 由客户档案「登记材料」格补传。
  390. */
  391. async function pickLicense(file: File | null) {
  392. if (!file) return;
  393. setLicenseError("");
  394. setLicenseBusy(true);
  395. try {
  396. setLicenseObj(await uploadCustomerLicense(file));
  397. } catch (e) {
  398. setLicenseObj(null);
  399. setLicenseError((e as Error)?.message || "影像上传失败。");
  400. } finally {
  401. setLicenseBusy(false);
  402. }
  403. }
  404. /**
  405. * 合同附件:选中即直传平台桶(同一两段式通路,前缀换成合同附件),成功才写进草稿;
  406. * `attachment_url` 在提交时才随合同落库 ⇒ 上传成功但未保存=库里仍是旧附件。
  407. *
  408. * 孤儿回收(2026-11-16):上一份若也是**本页刚上传、还没落库**的,换掉的那一刻它就没人引用了
  409. * ⇒ 立刻退回服务端(库里那份仍在引用,由写口的 `attachment_object_delete` 回收,⛔ 在这里删)。
  410. */
  411. async function pickAttachment(file: File | null) {
  412. if (!file) return;
  413. setAttachmentError("");
  414. setAttachmentBusy(true);
  415. try {
  416. const previous = draft.attachmentUrl.trim();
  417. const uploaded = await uploadContractAttachment(file);
  418. if (previous && previous !== record.data?.attachment_url) {
  419. discardPendingAttachments([previous]);
  420. }
  421. pendingAttachmentKeys.current = [
  422. ...pendingAttachmentKeys.current.filter((key) => key !== previous),
  423. uploaded.object_key,
  424. ];
  425. set("attachmentUrl", uploaded.object_key);
  426. setAttachmentName(uploaded.file_name);
  427. } catch (e) {
  428. // 失败⛔ 清掉上一份:用户点的是「更换」,换失败时旧附件仍在库里,草稿也保持旧值。
  429. setAttachmentError((e as Error)?.message || "合同附件上传失败。");
  430. } finally {
  431. setAttachmentBusy(false);
  432. }
  433. }
  434. /** 现签查看地址只在「库里那一条=草稿这一条」时有效(刚换过/未保存的还没签)。 */
  435. const attachmentView = useMemo(() => {
  436. const current = draft.attachmentUrl.trim();
  437. if (!current) return "";
  438. const row = record.data;
  439. if (row && row.attachment_url === current) return row.attachment_view_url ?? "";
  440. return /^https?:\/\//i.test(current) ? current : "";
  441. }, [draft.attachmentUrl, record.data]);
  442. const attachmentLabelText = attachmentName || contractAttachmentLabel(draft.attachmentUrl);
  443. if (created) {
  444. const c = created.customer;
  445. return <section className="ops-page ops-record-page">
  446. <div className="ops-record-card customer-created-result">
  447. <h1>合同已生成,客户已随合同建档</h1>
  448. <p>客户资料按 <code>POST /customer/create@v1</code> 的同一套规则推入客户档案,再签本合同(两个事务,⛔ 合并)。</p>
  449. <dl>
  450. <dt>合同号</dt><dd>{created.contractId}</dd>
  451. <dt>客户号</dt><dd>{c.customer_id}</dd>
  452. <dt>客户名称</dt><dd>{c.customer_name ?? WORD_UNCONFIGURED}</dd>
  453. <dt>客户主账号</dt><dd>{c.primary_username ?? <Tri tone="missing" text="后端未下发" title="建档回执未带主账号登录名" />}</dd>
  454. <dt>服务开通状态</dt><dd>未开通(业务开通走工单)</dd>
  455. <dt>账号激活状态</dt><dd>未激活(待激活)</dd>
  456. <dt>激活码</dt><dd>{c.code_issued ? "已发放(明文不在本页展示)" : "本次未发码,见建档回执"}</dd>
  457. <dt>营业执照影像</dt><dd>{c.subject_type && c.subject_type !== "enterprise"
  458. ? "不适用(非企业主体无需营业执照)"
  459. : c.license_pending ? "本次留空 ⇒ 请到客户档案「登记材料」格补传" : "已登记"}</dd>
  460. </dl>
  461. <p className="ops-form-note">激活码请用客户列表的「导出激活码」经平台凭证通道取;⛔ 本页不留存明文。</p>
  462. <div className="ops-form-actions">
  463. <Button onClick={() => navigate(`/contracts/${encodeURIComponent(created.contractId)}`)}>查看合同详情</Button>
  464. <Button variant="outline" onClick={() => navigate(`/customers/${encodeURIComponent(c.customer_id)}`)}>查看客户档案</Button>
  465. </div>
  466. </div>
  467. </section>;
  468. }
  469. return <section className="ops-page ops-record-page contract-editor">
  470. <header className="ops-page-head">
  471. <div>
  472. <p className="ops-eyebrow"><span /> 合同管理 · {editing ? "编辑" : "新增"}</p>
  473. <h1>{editing ? "编辑合同" : "新增合同"}</h1>
  474. <p>{editing ? `合同 ${no}` : "录入合同与固定套餐式、自定义规格式两类服务构成。"}</p>
  475. </div>
  476. <div className="ops-head-actions">
  477. <Button variant="outline" size="sm" onClick={() => navigate("/contracts")}><ArrowLeft size={15} />返回合同台账</Button>
  478. </div>
  479. </header>
  480. {record.loading && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="contract-form-summary">正在从合同接口读取…</p></section></div>}
  481. {record.error && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="ops-form-error" role="alert">{record.error.message}</p><div className="ops-form-actions"><Button variant="outline" size="sm" onClick={() => navigate("/contracts")}>返回合同台账</Button></div></section></div>}
  482. {!record.loading && !record.error && editing && !record.data && <div className="ops-record-layout"><section className="ops-record-card ops-record-card-full"><h2>合同资料</h2><p className="contract-form-summary">未找到合同 {no},可能已被删除。请从合同台账重新进入,或返回台账检索。</p><div className="ops-form-actions"><Button variant="outline" size="sm" onClick={() => navigate("/contracts")}>返回合同台账</Button></div></section></div>}
  483. {(!editing || record.data) && <div className="ops-record-layout">
  484. <div className="ops-record-stack">
  485. <section className="ops-record-card">
  486. <h2>一、客户资料 <span>必填</span></h2>
  487. {editing ? (
  488. <div className="ops-form-grid ops-form-grid--business">
  489. <label htmlFor="contract-customer"><span className="ops-field-title">所属客户</span><Input id="contract-customer" value={customerLabel} readOnly disabled /></label>
  490. </div>
  491. ) : (
  492. <div className="ops-form-grid ops-form-grid--business">
  493. {/* 客户检索=输入框内下拉(业主 2026-11-16 定案):命中项直接挂在输入框下方,⛔ 另起「命中的客户档案」下拉框。 */}
  494. <div className="contract-customer-combobox ops-form-span-2" onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setCustomerOpen(false); }}>
  495. <label htmlFor="contract-customer" className="ops-field-title">客户名称或信用码 <b title="必填">*</b></label>
  496. <div className="contract-customer-combobox-control">
  497. <Input
  498. ref={customerInput}
  499. id="contract-customer"
  500. role="combobox"
  501. autoComplete="off"
  502. aria-expanded={showCustomerOptions}
  503. aria-controls="contract-customer-options"
  504. aria-autocomplete="list"
  505. aria-activedescendant={showCustomerOptions && activeCustomer >= 0 ? `contract-customer-option-${activeCustomer}` : undefined}
  506. placeholder="客户名称至少 2 个字,或输入统一社会信用代码"
  507. value={customerTerm}
  508. readOnly={Boolean(customerId)}
  509. onFocus={() => { if (!customerId) setCustomerOpen(true); }}
  510. onKeyDown={onCustomerKeyDown}
  511. onChange={(event) => { setCustomerTerm(event.target.value); setCustomerId(null); setCustomerOpen(true); setCustomerActive(0); setError(""); }}
  512. />
  513. {customerId && <button type="button" className="contract-customer-combobox-clear" aria-label="清除已选客户" title="清除已选客户" onClick={clearCustomer}><X size={14} /></button>}
  514. {showCustomerOptions && (
  515. <ul id="contract-customer-options" role="listbox" aria-label="命中的客户档案" className="contract-customer-combobox-options">
  516. {candidates.map((item, index) => <li
  517. key={item.customer_id}
  518. id={`contract-customer-option-${index}`}
  519. role="option"
  520. aria-selected={index === activeCustomer}
  521. className={index === activeCustomer ? "is-active" : undefined}
  522. onMouseDown={(event) => event.preventDefault()}
  523. onMouseEnter={() => setCustomerActive(index)}
  524. onClick={() => pickCustomer(item)}
  525. >
  526. <strong>{item.customer_name}</strong>
  527. {item.identity_no_masked && <span>{item.identity_no_masked}</span>}
  528. {item.province_name && <small>{item.province_name}</small>}
  529. </li>)}
  530. {/* 检索在飞时只加一行状态,⛔ 收起整个候选列表(收起再展开就是「抖动」)。 */}
  531. {searching && <li className="contract-customer-combobox-status" role="presentation">正在检索…</li>}
  532. </ul>
  533. )}
  534. </div>
  535. </div>
  536. </div>
  537. )}
  538. {lookup.error && !editing && <FetchError message={lookup.error.message} onRetry={lookup.reload} />}
  539. {/* 提示行常驻(⛔ 随请求起落显隐):检索状态只在候选列表内以一行「正在检索…」呈现,避免整块内容上下跳。 */}
  540. {!editing && !customerId && !lookup.error && <p className="contract-form-summary">{freeText ? CONTRACT_FREE_TEXT_HINT : CONTRACT_CUSTOMER_LOOKUP_HINT}</p>}
  541. {/**
  542. * 未命中 ⇒ 展开客户建档必填段(CU-13 第 1 步;业主 2026-11-16 定案):
  543. * 客户名称沿用上方检索框(保存时按它建档);命中已有客户时本段整段不出现。
  544. */}
  545. {!editing && !customerId && freeText && (
  546. <div className="ops-form-grid ops-form-grid--business">
  547. <label htmlFor="inline-subject"><span className="ops-field-title">主体类型 <b title="必填">*</b></span>
  548. <select id="inline-subject" value={inline.subject} onChange={(event) => setInlineField("subject", event.target.value)}>
  549. {inlineSubjectOptions.map((item) => <option key={item.code} value={item.code}>{item.name}</option>)}
  550. </select>
  551. </label>
  552. <label htmlFor="inline-id"><span className="ops-field-title">客户识别号 <b title="必填">*</b></span>
  553. <Input id="inline-id" placeholder="18 位统一社会信用代码 / 15 位旧执照号" value={inline.idNo} onChange={(event) => setInlineField("idNo", event.target.value)} />
  554. <small>同时是查重与重试幂等键:合同保存失败后重新保存会按它命中已建客户。</small>
  555. </label>
  556. <label htmlFor="inline-contact"><span className="ops-field-title">经办联系人</span><Input id="inline-contact" placeholder="客户方经办人" value={inline.contact} onChange={(event) => setInlineField("contact", event.target.value)} /></label>
  557. <label htmlFor="inline-phone"><span className="ops-field-title">联系电话</span><Input id="inline-phone" placeholder="支持固定电话或手机号" value={inline.phone} onChange={(event) => setInlineField("phone", event.target.value)} /></label>
  558. <label htmlFor="inline-address" className="ops-form-span-2"><span className="ops-field-title">地址</span><Input id="inline-address" placeholder="客户地址(含楼栋与房间号)" value={inline.address} onChange={(event) => setInlineField("address", event.target.value)} /></label>
  559. <label htmlFor="inline-region" className="ops-form-span-2"><span className="ops-field-title">挂载区域 <b title="必填">*</b></span>
  560. <TreeSelect treeData={regionTree} value={inline.regionId} onChange={(value) => setInlineField("regionId", value)} ariaLabel="挂载区域" placeholder="请选择区域节点" name="inline-region" />
  561. </label>
  562. <label htmlFor="inline-operator"><span className="ops-field-title">运营商 <b title="必填">*</b></span>
  563. <select id="inline-operator" value={inline.operatorId} onChange={(event) => setInlineField("operatorId", event.target.value)}>
  564. <option value="">请选择运营商</option>
  565. {operatorOptions.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
  566. </select>
  567. <small>{provinceId ? "候选=所挂区域省份下可见的运营商档案(按需预选第一个,可改)。" : "先选挂载区域:运营商档案须与该区域同省,否则建档会被省份一致性校验拦下。"}</small>
  568. </label>
  569. <div className="customer-team-field"><span className="ops-field-title">运维团队 <b title="必填">*</b></span>
  570. <CustomerTeamSelect options={org.maintenanceTeams.map((item) => ({ id: item.id, name: item.name, hint: (item.ticketTypes ?? []).join("、") }))} value={inline.teamId} onChange={(id) => setInlineField("teamId", id)} />
  571. <small>单支定案:一个客户同一时刻恰好挂 1 支运维团队;默认预选范围内的第一支,可改。</small>
  572. </div>
  573. <label htmlFor="inline-login"><span className="ops-field-title">主账号登录名 <small>选填</small></span><Input id="inline-login" placeholder="留空按客户号派生" value={inline.login} onChange={(event) => setInlineField("login", event.target.value)} /></label>
  574. <label htmlFor="inline-mobile"><span className="ops-field-title">主账号绑定手机号 <small>选填</small></span><Input id="inline-mobile" inputMode="numeric" maxLength={11} placeholder="11 位手机号" value={inline.mobile} onChange={(event) => setInlineField("mobile", event.target.value)} /></label>
  575. {inline.subject === "enterprise" ? (
  576. <div className="ops-form-span-2 customer-document-picker">
  577. <div><strong>营业执照影像(本通道可留空)</strong>
  578. <label className="customer-upload-button" title="选择后立即直传平台对象存储(字节流不经过本系统)">
  579. <Upload size={15} />{licenseBusy ? "正在上传…" : licenseObj ? "重新选择" : "选择文件"}
  580. <input aria-label="上传营业执照影像" type="file" disabled={licenseBusy || submitting} onChange={(event) => { const file = event.target.files?.[0] ?? null; event.target.value = ""; void pickLicense(file); }} />
  581. </label>
  582. </div>
  583. <p>{licenseObj ? `已上传:${licenseObj.file_name}` : "留空=建档后到客户档案「登记材料」格补传;企业建档要求影像,本通道是唯一例外。"}</p>
  584. {licenseError && <small className="customer-field-error">{licenseError}</small>}
  585. </div>
  586. ) : null}
  587. </div>
  588. )}
  589. {editing && <p className="contract-form-summary">修改合同的客户归属需要后端提供迁移接口,此处不提供换客户。</p>}
  590. </section>
  591. <section className="ops-record-card">
  592. <h2>二、合同基本要素 <span>必填</span></h2>
  593. <div className="ops-form-grid ops-form-grid--business">
  594. <label htmlFor="contract-no"><span className="ops-field-title">合同编号 <small>{editing ? "服务端生成" : "可选"}</small></span><Input id="contract-no" placeholder={editing ? "" : "不填由服务端生成"} value={draft.contractNo} disabled={editing} onChange={(event) => set("contractNo", event.target.value)} /></label>
  595. <label htmlFor="external-no"><span className="ops-field-title">外部单号</span><Input id="external-no" placeholder="外部单号" value={draft.externalNo} onChange={(event) => set("externalNo", event.target.value)} /></label>
  596. <label htmlFor="contract-amount"><span className="ops-field-title">合同金额(元) <b title="必填">*</b></span><Input id="contract-amount" inputMode="decimal" placeholder="0.00" aria-invalid={invalidOf("amount")} value={draft.amount} onChange={(event) => set("amount", event.target.value)} />{requiredErrorOf("amount")}</label>
  597. <label htmlFor="pay-cycle"><span className="ops-field-title">付款周期 <b title="必填">*</b></span><select id="pay-cycle" aria-invalid={invalidOf("payCycle")} value={draft.payCycle} onChange={(event) => set("payCycle", event.target.value)}><option value="">未配置</option>{OPTIONS.pay_cycle.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</select>{requiredErrorOf("payCycle")}</label>
  598. <label htmlFor="start-date"><span className="ops-field-title">合同生效日</span><Input id="start-date" type="date" value={draft.start} onChange={(event) => set("start", event.target.value)} /></label>
  599. <label htmlFor="end-date"><span className="ops-field-title">合同结束日</span><Input id="end-date" type="date" value={draft.end} onChange={(event) => set("end", event.target.value)} /></label>
  600. {/* 运营商经办人=交接单口径的三段,独占一行(机构/姓名/联系方式),⛔ 与上面六个商务格混排。 */}
  601. <div className="ops-form-span-full contract-agent-block">
  602. <span className="ops-field-title">运营商经办人</span>
  603. <div className="ops-form-grid contract-agent-grid">
  604. <label htmlFor="agent-org"><span className="ops-field-title">机构 <small>选填</small></span><Input id="agent-org" placeholder="经办人所属机构" value={draft.agentOrg} onChange={(event) => set("agentOrg", event.target.value)} /><span className="ops-field-note">选填,不填也可提交;清空后保存即清除已记录的机构。</span></label>
  605. <label htmlFor="agent-name"><span className="ops-field-title">姓名 <b title="必填">*</b></span><Input id="agent-name" aria-invalid={invalidOf("agent")} value={draft.agent} onChange={(event) => set("agent", event.target.value)} />{requiredErrorOf("agent")}</label>
  606. <label htmlFor="agent-phone"><span className="ops-field-title">联系方式 <b title="必填">*</b></span><Input id="agent-phone" inputMode="numeric" aria-invalid={invalidOf("agentPhone")} value={draft.agentPhone} onChange={(event) => set("agentPhone", event.target.value)} />{requiredErrorOf("agentPhone")}<span className="ops-field-note">必填。当前登录身份未提供手机号时留空,请手工录入经办人实际联系电话。</span></label>
  607. </div>
  608. </div>
  609. {/*
  610. * 录入经办人=界面录入账号,服务端从鉴权上下文写入(⛔ 入参、建后恒只读):
  611. * 机构取账号绑定团队(运营/运维团队名,`hq` 回落「总运营」)、姓名取账号显示名、联系方式取绑定手机号(出参已掩码)。
  612. * 新建态只在提交后才拿得到机构,故此处不给可编辑控件,⛔ 让前端「代填」一个值造成与后端不一致。
  613. * 独占一行(`ops-form-span-full`),⛔ 与运营商经办人挤在同一行。
  614. */}
  615. <div className="ops-form-span-full contract-agent-readonly">
  616. <span className="ops-field-title">录入经办人 <small>=当前录入账号,提交时自动带入</small></span>
  617. <div className="contract-inline-group">
  618. <span className="contract-inline-seg"><small>机构</small><span className="contract-inline-readonly">{editing ? record.data?.created_by_org || "未记录" : "取账号绑定团队"}</span></span>
  619. <span className="contract-inline-seg"><small>姓名</small><span className="contract-inline-readonly">{editing ? record.data?.created_by_name || record.data?.created_by || "未记录" : identity?.name || "未登录"}</span></span>
  620. <span className="contract-inline-seg"><small>联系方式</small><span className="contract-inline-readonly">{editing ? record.data?.created_by_mobile || "未绑定" : identity?.phone || "账号未绑手机号"}</span></span>
  621. </div>
  622. <span className="ops-field-note">这三段由录入时账号自动带入,建后恒只读(KLT-L221),不得手工改。</span>
  623. </div>
  624. <label htmlFor="handover-on"><span className="ops-field-title">交接单日期 <b title="必填">*</b></span><Input id="handover-on" type="date" aria-invalid={invalidOf("handoverOn")} value={draft.handoverOn} onChange={(event) => set("handoverOn", event.target.value)} />{requiredErrorOf("handoverOn")}</label>
  625. </div>
  626. {record.data?.source_label !== undefined && <p className="contract-form-summary">来源:{record.data.source_label === null ? WORD_UNCONFIGURED : record.data.source_label}{record.data.pay_cycle ? `;付款周期 ${record.data.pay_cycle} → ${label(PAY_CYCLE, record.data.pay_cycle)}` : ""}</p>}
  627. </section>
  628. <section className="ops-record-card">
  629. <h2>三、服务构成 <span>固定套餐式/自定义规格式</span></h2>
  630. {!plans.length && <p className="contract-form-summary">{catalog.error ? <>套餐配置取数失败:{catalog.error.message}</> : catalog.loading ? "正在载入套餐配置…" : "套餐配置暂无可选档位。"}</p>}
  631. <div className="ops-contract-items">
  632. {draft.items.map((item, index) => (
  633. <article key={`${item.itemId ?? "new"}-${index}`} className="ops-contract-item">
  634. <header className="ops-contract-item-head">
  635. <span className="ops-contract-index">条目 {index + 1}</span>
  636. <Button variant="ghost" size="sm" disabled={draft.items.length === 1} onClick={() => removeItem(index)}><Trash2 size={15} />删除</Button>
  637. </header>
  638. <div className="ops-form-grid ops-form-grid--business">
  639. <label><span className="ops-field-title">条目形态</span><select value={item.kind} onChange={(event) => patchItem(index, { kind: event.target.value as ItemDraft["kind"] })}><option value="plan_based">固定套餐式</option><option value="custom_spec">自定义规格式</option></select></label>
  640. {item.kind === "plan_based" ? <>
  641. <label><span className="ops-field-title">套餐档位</span><select value={item.planId} onChange={(event) => pickPlan(index, event.target.value)}><option value="">{catalog.loading ? "载入中…" : WORD_UNCONFIGURED}</option>{plans.map((plan) => <option key={plan.plan_id} value={plan.plan_id}>{plan.plan_name}</option>)}</select></label>
  642. <label><span className="ops-field-title">档位数量</span><Input type="number" min={1} value={item.quantity} onChange={(event) => patchItem(index, { quantity: Number(event.target.value) })} /></label>
  643. </> : <>
  644. <label><span className="ops-field-title">账号数</span><Input type="number" min={1} value={item.accountCount} onChange={(event) => patchItem(index, { accountCount: Number(event.target.value) })} /></label>
  645. <label><span className="ops-field-title">下行带宽(Mbps)</span><Input type="number" min={0} max={1000} value={item.bwDown} onChange={(event) => patchItem(index, { bwDown: Number(event.target.value) })} /></label>
  646. <label><span className="ops-field-title">上行带宽(Mbps)</span><Input type="number" min={0} max={1000} value={item.bwUp} onChange={(event) => patchItem(index, { bwUp: Number(event.target.value) })} /></label>
  647. <label><span className="ops-field-title">条目年价(元)</span><Input inputMode="decimal" placeholder="0.00" value={item.annualPrice} onChange={(event) => patchItem(index, { annualPrice: event.target.value })} /></label>
  648. {/* D-32:自定义规格补齐「用途分类」——订单方式与出账分类都按它派生,套餐式由所引目录档带出、此处不录。 */}
  649. <label><span className="ops-field-title">用途分类</span><select value={item.useCategory} onChange={(event) => patchItem(index, { useCategory: event.target.value })}><option value="">请选择用途分类</option>{Object.entries(USE_CATEGORY).map(([value, text]) => <option key={value} value={value}>{text}</option>)}</select></label>
  650. </>}
  651. <fieldset className="ops-form-span-full ops-contract-exit-fieldset">
  652. <legend>线路出口(从套餐配置选择,1–{LINE_EXIT_MAX} 个)</legend>
  653. {exitCatalog.error && <FetchError message={exitCatalog.error.message} onRetry={exitCatalog.reload} />}
  654. {!exitCatalog.error && !exitOptions.length && !exitCatalog.loading && <p className="contract-form-summary">套餐配置尚未配置线路出口;请先到「套餐配置 → 线路出口」维护。</p>}
  655. {!!exitOptions.length && <div className="ops-contract-exits">{exitOptions.map((exit) => {
  656. const active = item.exits.includes(exit);
  657. return <button type="button" key={exit} className={active ? "ops-contract-exit is-active" : "ops-contract-exit"} aria-pressed={active} onClick={() => toggleExit(index, exit)}>{exit}{active ? <X size={13} /> : <Plus size={13} />}</button>;
  658. })}</div>}
  659. <span className="ops-field-note">已选 {item.exits.length}/{LINE_EXIT_MAX}。线路出口在「套餐配置 → 线路出口」统一维护,此处只做选择。</span>
  660. </fieldset>
  661. </div>
  662. </article>
  663. ))}
  664. </div>
  665. <div className="ops-contract-item-actions">
  666. <p className="contract-form-summary"><span><strong>{draft.items.length}</strong> 个构成条目</span><span>套餐式 {draft.items.filter((item) => item.kind === "plan_based").length} · 自定义式 {draft.items.filter((item) => item.kind === "custom_spec").length}</span></p>
  667. <Button variant="outline" size="sm" onClick={() => setDraft((current) => ({ ...current, items: [...current.items, emptyItem()] }))}><Plus size={15} />添加条目</Button>
  668. </div>
  669. </section>
  670. <div className="ops-record-pair">
  671. <section className="ops-record-card">
  672. <h2>四、固定 IP 条目 <span>每条=线路出口+带宽档位+IP 数量</span></h2>
  673. <label className="ops-form-check"><input type="checkbox" checked={draft.needIp} onChange={(event) => setNeedIp(event.target.checked)} /><span>有固定 IP 需求(默认无固定 IP;勾上才核定 IP)</span></label>
  674. {!draft.ipCarried && <p className="contract-form-summary">读口没回 `ip_entries` 这个键=读不到已备案条目,本次提交不带 IP(拿空表覆盖会清掉库里已有的条目)。</p>}
  675. {draft.needIp ? <>
  676. <div className="ops-contract-ip-rows">{draft.ipRows.map((row, index) => (
  677. <div key={row.key} className="ops-contract-ip-row">
  678. <label><span className="ops-field-title">线路出口</span><select aria-label={`IP 条目 ${index + 1} 线路出口`} value={row.line_exit} onChange={(event) => patchIpRow(index, { line_exit: event.target.value })}><option value="">请选择服务构成出口</option>{[...new Set([...itemExitOptions, row.line_exit.trim()].filter(Boolean))].map((exit) => <option key={exit} value={exit}>{itemExitOptions.includes(exit) ? exit : `${exit}(不在服务构成已选出口中)`}</option>)}</select></label>
  679. <label><span className="ops-field-title">带宽档位</span><select aria-label={`IP 条目 ${index + 1} 带宽档位`} value={row.bandwidth_tier_mbps} onChange={(event) => patchIpRow(index, { bandwidth_tier_mbps: event.target.value })}><option value="">{WORD_UNCONFIGURED}</option>{[...tierOptions, ...(row.bandwidth_tier_mbps && !tierValues.includes(row.bandwidth_tier_mbps) ? [{ value: row.bandwidth_tier_mbps, label: `${row.bandwidth_tier_mbps}(目录外,需重新配置)` }] : [])].map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}</select></label>
  680. <label><span className="ops-field-title">IP 数量</span><Input type="number" min={1} max={IP_COUNT_MAX} aria-label={`IP 条目 ${index + 1} IP 数量`} value={row.ip_count} onChange={(event) => patchIpRow(index, { ip_count: event.target.value })} /></label>
  681. <Button variant="ghost" size="sm" onClick={() => removeIpRow(index)}><Trash2 size={15} />删除</Button>
  682. </div>
  683. ))}</div>
  684. {!itemExitOptions.length && <p className="contract-form-summary">上方服务构成条目尚未选择线路出口 ⇒ IP 条目没有可选项;请先在条目上勾选线路出口。</p>}
  685. <div className="ops-contract-item-actions"><Button variant="outline" size="sm" onClick={addIpRow}><Plus size={15} />添加 IP 条目</Button></div>
  686. <p className="contract-form-summary">每条=线路出口+带宽档位+IP 数量,三元组缺一项后端回 `KLT-L217`;带宽档位从「套餐配置 → 线路出口」的档位清单里选(可含「不承诺带宽」=该条 IP 不带带宽承诺,对应 `bandwidth_committed=false`)。出口<strong>只能从上方服务构成条目已选出口中选</strong>,初始默认带出第一个已选出口。</p>
  687. </> : <p className="contract-form-summary">未勾选=本表零行(提交时随合同送 `ip_entries: []`=清空旧条目)。</p>}
  688. </section>
  689. <section className="ops-record-card">
  690. <h2>五、合同附件 <span>可选 · 单份</span></h2>
  691. <div className="ops-contract-upload-list">
  692. {draft.attachmentUrl.trim()
  693. ? <div><span>{attachmentLabelText} · 已上传</span></div>
  694. : <div><Tri tone="missing" text={WORD_UNCONFIGURED} title="尚未选择附件文件" /></div>}
  695. </div>
  696. <input
  697. ref={attachmentInput}
  698. type="file"
  699. accept=".pdf,.ofd,.png,.jpg,.jpeg,.doc,.docx,.xls,.xlsx"
  700. hidden
  701. aria-label="选择合同附件文件"
  702. onChange={(event) => { void pickAttachment(event.target.files?.[0] ?? null); event.target.value = ""; }}
  703. />
  704. <div className="ops-contract-item-actions">
  705. <Button variant="outline" size="sm" disabled={attachmentBusy || submitting} onClick={() => attachmentInput.current?.click()}>
  706. <Upload size={15} />{attachmentBusy ? "正在上传…" : draft.attachmentUrl.trim() ? "更换附件" : "选择并上传附件"}
  707. </Button>
  708. {attachmentView && <Button variant="ghost" size="sm" onClick={() => window.open(attachmentView, "_blank", "noopener,noreferrer")}>查看附件</Button>}
  709. {draft.attachmentUrl.trim() && <Button variant="ghost" size="sm" disabled={attachmentBusy || submitting} onClick={() => {
  710. // 移除的若是「本页刚上传、还没落库」的那一份 ⇒ 它当场失去引用,立即退回;
  711. // 库里那份仍被合同引用(保存后才由写口回收),这里⛔ 提前删。
  712. const current = draft.attachmentUrl.trim();
  713. if (current && current !== record.data?.attachment_url) discardPendingAttachments([current]);
  714. set("attachmentUrl", ""); setAttachmentName(""); setAttachmentError("");
  715. }}><X size={15} />移除</Button>}
  716. </div>
  717. {attachmentError && <p className="ops-form-error" role="alert">{attachmentError}</p>}
  718. <p className="contract-form-summary">文件选中即直传平台对象存储(字节流与上传凭证都不经本服务),成功后随合同保存对象键;单份,重传即替换,保存前不影响库里已有附件。查看地址由详情读口按需现签。</p>
  719. </section>
  720. </div>
  721. </div>
  722. <aside className="ops-record-side">
  723. <section className="ops-record-card">
  724. <h2>提交校验</h2>
  725. <div className="ops-contract-summary">
  726. <div><span>客户</span><strong>{editing ? customerLabel : (customerId ? candidates.find((item) => item.customer_id === customerId)?.customer_name ?? "" : freeText ? `${customerTerm.trim()}(自由录入)` : "待检索")}</strong></div>
  727. <div><span>合同编号</span><strong>{draft.contractNo || "服务端生成"}</strong></div>
  728. <div><span>合同金额</span><strong>{/^\d+(?:\.\d{1,2})?$/.test(draft.amount.trim()) ? `¥${Number(draft.amount).toLocaleString("zh-CN")}` : "待填写"}</strong></div>
  729. <div><span>付款周期</span><strong>{draft.payCycle ? label(PAY_CYCLE, draft.payCycle) : WORD_UNCONFIGURED}</strong></div>
  730. <div><span>合同期间</span><strong>{draft.start && draft.end ? `${draft.start} 至 ${draft.end}` : "待填写"}</strong></div>
  731. <div><span>构成条目</span><strong>{draft.items.length} 个</strong></div>
  732. <div><span>固定 IP 条目</span><strong>{draft.needIp ? `${draft.ipRows.length} 条/${draft.ipRows.reduce((sum, row) => sum + (Number(row.ip_count) || 0), 0)} 个 IP` : "无固定 IP 需求"}</strong></div>
  733. <div><span>附件</span><strong>{draft.attachmentUrl.trim() ? (attachmentBusy ? "上传中…" : attachmentLabelText) : "无附件"}</strong></div>
  734. </div>
  735. {error && <p className="ops-form-error" role="alert">{error}</p>}
  736. <div className="ops-form-actions"><Button size="sm" variant="outline" onClick={() => navigate(-1)}>取消</Button><Button size="sm" disabled={submitting || attachmentBusy || (editing && record.loading)} onClick={save}>{submitting ? "正在提交…" : editing ? "保存修改" : "提交合同"}</Button></div>
  737. </section>
  738. </aside>
  739. </div>}
  740. </section>;
  741. }
  742. const CONTRACT_FREE_TEXT_HINT = "未命中客户档案:继续填下方建档必填项,保存时先建客户档案(含客户主账号)再签本合同;命中后本段自动收起。";
  743. /** 检索进行中/尚无候选时的常驻提示(⛔ 用「正在检索」替换本行,那句话改成候选列表里的一行)。 */
  744. const CONTRACT_CUSTOMER_LOOKUP_HINT = "输入客户名称(至少 2 个字)或统一社会信用代码检索:命中项直接列在输入框下方,选中后可用 × 清除重选;未命中则继续填下方建档必填项。";