ContractDetailPages.tsx 50 KB

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