CustomerWorkspacePage.tsx 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. /**
  2. * 客户档案(工作台)—— 真源=klt-bos 接口,⛔ localStorage 与演示行。
  3. *
  4. * 读:`POST /customer/get@v1`(主体资料与归属)+ `POST /account/get_list@v1`(客户主账号与激活码
  5. *  生命周期)+ `POST /sub_account/get_list@v1`(分账号)+ `POST /customer/history@v1`(变更记录);
  6. *  区域名经 `/region/tree@v1`(`lib/organization-demo`)解析。
  7. * 写:`POST /customer/attribution_update@v1`(运营商/合伙人)+ `POST /customer/move_region@v1`(挂载区域,
  8. *  可带 `ops_team_ids`)+ `POST /customer/update@v1`(仅改运维团队时)+ `POST /sub_account/update@v1`。
  9. *
  10. * 后端边界(页面如实呈现,⛔ 造数填补):
  11. * * 激活码明文⛔ 读路由(仅开通/重置当次回执一次性下发)⇒ 主账号面板只回显激活码生命周期,
  12. *   明文只在「重置激活码」当次回显一次(手册 P2:激活码过期或遗失由运营在本页重置);
  13. * * `/sub_account/*` ⛔ 新增与删除路由 ⇒ 分账号只可改名与网络侧账号名;
  14. * * ⛔ `/customer/acct_status/update@v1` 封装 ⇒ 停用/恢复入口置灰;
  15. * * 登记材料(营业执照影像):读口一次给全 `license{file_name, status, view_url, view_url_expires_at}`;
  16. *  补传/替换由浏览器直传平台 `unified-oss` 后调 `POST /customer/update@v1` 回报对象键(⛔ 经本系统传字节);
  17. * * ⛔ 合同文档上传路由 ⇒ 合同文档区只给应备项说明。
  18. */
  19. import { useEffect, useMemo, useRef, useState, type FormEvent, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
  20. import { ArrowLeft, Building2, CalendarPlus, Check, FileSignature, FileText, Gauge, LoaderCircle, MapPin, PencilLine, RefreshCcw, RefreshCw, ScrollText, Upload, UsersRound, Wrench, X } from "lucide-react";
  21. import { Link, useLocation, useParams } from "react-router";
  22. import { Button } from "../components/ui/button";
  23. import { Input } from "../components/ui/input";
  24. import { OpsMore, OpsNotice, OpsStatus, OpsTableColumns, OpsTableEmpty, OpsTag, type OpsMoreItem } from "../components/OperationsKit";
  25. import { OrderEditor } from "../components/OrderChangeDialogs";
  26. import { CustomerServiceStopAction } from "../components/CustomerServiceStopAction";
  27. import { DeliveryStatusTable } from "../components/DeliveryStatusTable";
  28. import { RecordTabs } from "../components/RecordTabs";
  29. import { orderView, type OrderView } from "../lib/order-demo";
  30. import { FetchError } from "../components/fetchError";
  31. import { Tri } from "../components/triState";
  32. import { TreeSelect } from "../components/ui/tree-select";
  33. import { CustomerTeamSelect } from "../components/CustomerTeamSelect";
  34. import { ACCT_STATUS, ACTIVATION_STATUS, PLAN_KIND, SUBJECT_TYPE, label } from "../lib/api/labels";
  35. import { typeLabel } from "../lib/api/ticket";
  36. import type { ApiError } from "../lib/api/http";
  37. import { accountGetList, accountResetCode, customerAttributionUpdate, customerGet, customerHistory, customerMoveRegion, customerUpdate, subAccountGetList, subAccountUpdate, orderGetList, contractGetList } from "../lib/api/bos";
  38. import { uploadCustomerLicense } from "../lib/api/oss-upload";
  39. import { contractAttachmentLabel } from "../lib/contract-attachments";
  40. import { invalidateCustomerList } from "../lib/customer-list-store";
  41. import type { SubAccountRow } from "../lib/api/types";
  42. import { isSeatPlaceholder, seatDisplayName } from "../lib/customer-subaccounts";
  43. import { useLoad } from "../lib/useLoad";
  44. import { regionComparablePath, regionMountPath, useOrganizationData } from "../lib/organization-demo";
  45. import { lockIfCandidate, operationsTeamDisplay, regionAncestorChain, teamsCoveringRegion } from "../lib/region-ownership";
  46. import { regionTreeNodes } from "../lib/region-tree";
  47. import { isImeComposing } from "../lib/ime";
  48. import { customerMaterials } from "../lib/customer-records";
  49. import { detailBack, detailLinkState } from "../lib/detail-navigation";
  50. import { useBusinessView } from "../lib/use-business-view";
  51. import "../styles/operations.css";
  52. import "../styles/customer-onboarding.css";
  53. const MISSING = "后端未下发";
  54. /**
  55. * 客户工作台的页签(讨论稿 §7.7:01–07 七个区块全部改为页签,并新增「交付现状」)。
  56. * `#workspace-service` 锚点落在「全部订阅」页签上(保留旧链接的落点)。
  57. */
  58. type WorkspaceTab = "profile" | "attribution" | "primary" | "subscriptions" | "subaccounts" | "materials" | "history" | "delivery";
  59. const WORKSPACE_TABS: { id: WorkspaceTab; label: string }[] = [
  60. { id: "profile", label: "主体资料" },
  61. { id: "attribution", label: "归属关系" },
  62. { id: "primary", label: "客户主账号" },
  63. { id: "subscriptions", label: "全部订阅" },
  64. { id: "subaccounts", label: "分账号" },
  65. { id: "materials", label: "登记材料与合同文档" },
  66. { id: "history", label: "历史记录" },
  67. { id: "delivery", label: "交付现状" },
  68. ];
  69. /** 客户建档/更正只收这三个主体码(后端 `60004` 会拦下主体类型字典里的其余历史码)。 */
  70. const CUSTOMER_SUBJECT_CODES = ["enterprise", "individual", "sole_proprietor"] as const;
  71. const NO_ACCOUNT_FOUND = "未查到该客户的主账号记录:可能尚未开通,或该账号不在当前登录账号的可见范围(/account/get_list@v1 按 subject_id 查询为空)";
  72. const CONTRACT_DOC_NOTE = "合同文档随合同登记上传(合同详情 → 附件),本页只读汇总";
  73. const NO_ACTIVATION_CODE_READ = "激活码仅在后端开通/重置写口回执中一次性下发,读完即失效 ⇒ 无读路由,不回显明文";
  74. const CODE_RESET_ONCE_NOTE = "新激活码明文只随本次应答回显一次,请立即分发或安全保存;关闭后无法再查。";
  75. const CODE_RESET_ACTIVATED_NOTE = "该账号已激活:不可重置激活码(手册 P2「要知道的」)⇒ 换人接手请走客户自助改密或运营换绑手机号";
  76. /** 订阅表仍按中文状态上色(订阅域由 `lib/order-store` 下发,⛔ 在本页改写状态文案)。 */
  77. const statusTone = (status: string) => status === "在用" || status === "生效中" ? "success" : status === "停用" || status === "提前停机" ? "danger" : "neutral";
  78. const money = (value: string) => `¥${Number(value).toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  79. /** 账号状态色调只看后端原值,中文一律取自 `labels.ACCT_STATUS`。 */
  80. const acctTone = (raw: string) => raw === "stopped" || raw === "disabled" ? "danger" : raw === "active" || raw === "normal" || raw === "in_use" ? "success" : "neutral";
  81. /** 激活态色调:已激活绿、待激活/发放中黄、未发放灰。 */
  82. const activationTone = (raw: string) => raw === "activated" ? "success" : raw === "issued" || raw === "issuing" ? "warning" : "neutral";
  83. /** 缺列单元格:⛔ 用「—」「未知」或 0 冒充后端没给的列。 */
  84. function TextCell({ value, note }: { value: string | number | null | undefined; note?: string }) {
  85. const text = value === null || value === undefined ? "" : String(value).trim();
  86. return text ? <>{text}</> : <Tri tone="missing" text={MISSING} title={note ?? MISSING} />;
  87. }
  88. /** 可空资料单元格:读口已回该字段但值为空 ⇒「未登记」,⛔ 与「后端未下发」混为一谈。 */
  89. function OptionalCell({ value, note = "该字段未登记" }: { value: string | number | null | undefined; note?: string }) {
  90. const text = value === null || value === undefined ? "" : String(value).trim();
  91. return text ? <>{text}</> : <span className="ops-muted" title={note}>未登记</span>;
  92. }
  93. /** 账号状态单元格:后端未回状态 ≠ 「未开通」,两者分列。 */
  94. function AcctCell({ raw }: { raw: string | null | undefined }) {
  95. const text = raw ? label(ACCT_STATUS, raw) : "";
  96. return text ? <OpsStatus tone={acctTone(raw ?? "")}>{text}</OpsStatus> : <Tri tone="missing" text={MISSING} title={MISSING + ":acct_status"} />;
  97. }
  98. function metricCount(value: number | undefined, loading: boolean, error: ApiError | null) {
  99. if (error) return <Tri tone="fail" text="取数失败" title={error.message} />;
  100. if (loading) return <span className="customer-record-metric-loading">读取中</span>;
  101. return <TextCell value={value} />;
  102. }
  103. function CustomerMaterialCard({ children }: { children: ReactNode }) {
  104. return <div className="customer-material-card">
  105. <span className="customer-file-thumb" aria-hidden="true"><FileText size={20} /></span>
  106. <div className="customer-material-description">{children}</div>
  107. </div>;
  108. }
  109. /**
  110. * 详情里的单个可编辑项(与合同详情同一交互):非编辑态只渲染值,鼠标移入才显出铅笔;点铅笔切到输入态。
  111. * 改完点对号(或按 Enter)即提交**该项**:客户写口按字段可选,⛔ 攒到底部统一保存。
  112. */
  113. type InlineFieldProps = {
  114. id: string;
  115. label: string;
  116. value: string;
  117. editing: boolean;
  118. writable: boolean;
  119. /** 该项正在提交:锁住对号/取消,避免重复提交。 */
  120. busy?: boolean;
  121. onStart: () => void;
  122. onChange: (value: string) => void;
  123. onDone: () => void;
  124. onCancel: () => void;
  125. type?: "text" | "date" | "number";
  126. inputMode?: "decimal" | "numeric" | "text";
  127. placeholder?: string;
  128. display?: ReactNode;
  129. emptyText?: string;
  130. invalid?: boolean;
  131. error?: ReactNode;
  132. selectOptions?: readonly { value: string; label: string }[];
  133. /** 自定义编辑控件(区域树、运维团队下拉):给定时替代默认输入/下拉。 */
  134. editor?: ReactNode;
  135. };
  136. function InlineField({ id, label, value, editing, writable, busy = false, onStart, onChange, onDone, onCancel, type = "text", inputMode, placeholder, display, emptyText = MISSING, invalid, error, selectOptions, editor }: InlineFieldProps) {
  137. const shown = display ?? (value ? value : emptyText);
  138. if (!writable) return <span className="customer-inline-readonly">{shown}</span>;
  139. if (!editing) return <span className="customer-inline-field">
  140. <span className="customer-inline-value">{shown}</span>
  141. <button type="button" className="customer-inline-edit" aria-label={`编辑${label}`} title={`编辑${label}`} onClick={onStart}><PencilLine size={14} /></button>
  142. </span>;
  143. const onKeyDown = (event: ReactKeyboardEvent) => {
  144. // 输入法上屏用的 Enter/Esc ⛔ 当成「保存/取消」,否则拼音选字就被提交了。
  145. if (isImeComposing(event)) return;
  146. if (event.key === "Enter") { event.preventDefault(); onDone(); }
  147. if (event.key === "Escape") { event.preventDefault(); onCancel(); }
  148. };
  149. return <span className="customer-inline-editor">
  150. {editor ?? (selectOptions ? (
  151. <select id={id} aria-label={label} autoFocus disabled={busy} value={value} onChange={(event) => onChange(event.target.value)} onKeyDown={onKeyDown}>
  152. {selectOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
  153. </select>
  154. ) : (
  155. <Input id={id} aria-label={label} autoFocus disabled={busy} type={type} inputMode={inputMode} placeholder={placeholder} aria-invalid={invalid || undefined} value={value} onChange={(event) => onChange(event.target.value)} onKeyDown={onKeyDown} />
  156. ))}
  157. <button type="button" className="customer-inline-ok" aria-label={busy ? "正在保存" : "保存该项"} title={busy ? "正在保存…" : "保存该项(Enter)"} disabled={busy} onClick={onDone}>{busy ? <LoaderCircle aria-hidden="true" className="animate-spin" size={14} /> : <Check size={14} />}</button>
  158. <button type="button" className="customer-inline-cancel" aria-label="取消编辑" title="取消(Escape)" disabled={busy} onClick={onCancel}><X size={14} /></button>
  159. {error}
  160. </span>;
  161. }
  162. /** 客户档案的草稿:身份号只存「本次新填」的明文(读口只下脱敏值)。 */
  163. type ProfileDraft = {
  164. name: string; subject: string; idNo: string; contact: string; phone: string; address: string;
  165. regionId: string; operatorId: string; partnerId: string; teamId: string;
  166. };
  167. export function CustomerWorkspacePage() {
  168. const { no } = useParams();
  169. const location = useLocation();
  170. const outgoingState = detailLinkState(location.pathname, location.state);
  171. const organization = useOrganizationData(["regions", "operators", "partners", "operationsTeams", "maintenanceTeams"]);
  172. /** 页签=本页唯一的浏览轴(讨论稿 §7.7);`#workspace-service` 仍落在「全部订阅」。 */
  173. const [tab, setTab] = useState<WorkspaceTab>(() => (location.hash === "#workspace-service" ? "subscriptions" : "profile"));
  174. useEffect(() => {
  175. if (location.hash === "#workspace-service") setTab("subscriptions");
  176. }, [location.hash]);
  177. const detail = useLoad(() => (no ? customerGet({ customer_id: no }) : Promise.resolve(null)), [no]);
  178. // 主账号读口:按绑定主体直取(`subject_id`=客户号),一次取回启停态与激活码生命周期。
  179. const primaryAccountLoad = useLoad(() => (no ? accountGetList({ subject_id: no, page: 0, page_size: 20 }) : Promise.resolve(null)), [no]);
  180. const accounts = useLoad(() => (no ? subAccountGetList({ customer_id: no, page: 0, page_size: 200 }) : Promise.resolve(null)), [no]);
  181. const changes = useLoad(() => (no ? customerHistory({ customer_id: no, page: 0, page_size: 50 }) : Promise.resolve(null)), [no]);
  182. const ordersLoad = useLoad(() => (no ? orderGetList({ customer_id: no, page: 0, page_size: 200 }) : Promise.resolve(null)), [no]);
  183. const contractsLoad = useLoad(() => (no ? contractGetList({ customer_id: no, page: 0, page_size: 200 }) : Promise.resolve(null)), [no]);
  184. const customer = detail.data?.customer ?? null;
  185. const primaryAccount = useMemo(() => {
  186. const rows = primaryAccountLoad.data?.items ?? [];
  187. // 客户主账号=role_code=enterprise 且绑定客户主体;兼容历史绑定口径时退回首行。
  188. return rows.find((row) => row.role_code === "enterprise" || row.subject_type === "customer") ?? rows[0] ?? null;
  189. }, [primaryAccountLoad.data]);
  190. /** 主账号读取失败/未查到时的统一说明(⛔ 把「无账号」当「后端未下发」)。 */
  191. const primaryAccountMissing = primaryAccountLoad.error
  192. ? MISSING + ":/account/get_list@v1 取数失败(" + primaryAccountLoad.error.message + ")"
  193. : primaryAccountLoad.loading
  194. ? "主账号信息读取中…"
  195. : NO_ACCOUNT_FOUND;
  196. const mount = detail.data?.region_mounts?.[0];
  197. const teamIds = detail.data?.team_ids ?? [];
  198. const accountRows = accounts.data?.items ?? [];
  199. const changeRows = changes.data?.items ?? [];
  200. const orders = ordersLoad.data?.items ?? [];
  201. const contracts = contractsLoad.data?.items ?? [];
  202. const contractFiles = contracts.flatMap((contract) =>
  203. (contract.attachment_url
  204. ? [{
  205. // 单值附件两形态(外部链接/平台桶对象键):对象键末段是随机串 ⇒ 按后缀显示,
  206. // ⛔ 把随机串当文件名糊给用户;下载地址只在合同详情读口现签。
  207. name: contractAttachmentLabel(contract.attachment_url),
  208. contractNo: contract.contract_id,
  209. kind: contract.attachment_kind ?? "other",
  210. }]
  211. : []));
  212. /**
  213. * 登记材料摘要(客户§3.5)——`status ∈ none/viewable/expired` **由后端一次给全**:
  214. * 页面⛔ 为影像另发请求、⛔ 拿对象键自拼地址(对象键不在响应体里)。
  215. * 只看主体类型决定面板形态:个人/个体工商户恒「不适用」(⛔ 渲染控件)。
  216. */
  217. const license = detail.data?.license ?? null;
  218. const licenseApplicable = customer?.subject_type === "enterprise";
  219. const customerListTitle = "客户管理";
  220. const back = detailBack(location.state, "/customers", `返回${customerListTitle}`);
  221. const view = useBusinessView([]);
  222. /** 详情即编辑:可写角色才挂铅笔;只读身份(团队长/运维等)看到的是同一页的只读态。 */
  223. const writable = !view.readOnly;
  224. /**
  225. * 草稿基线=`/customer/get@v1` 的实际值。
  226. * 识别号读口只下发脱敏值 ⇒ 草稿的 `idNo` 恒从空串起,只有用户主动填入完整新号才提交(⛔ 回填脱敏串)。
  227. */
  228. const serverBaseline = useMemo<ProfileDraft | null>(() => {
  229. if (!detail.data?.customer) return null;
  230. const c = detail.data.customer;
  231. const mounted = detail.data.region_mounts?.[0]?.parent_node_id ?? "";
  232. const teams = detail.data.team_ids ?? [];
  233. return {
  234. name: c.customer_name ?? "",
  235. subject: c.subject_type ?? "",
  236. idNo: "",
  237. contact: c.contact_name ?? "",
  238. phone: c.contact_mobile ?? "",
  239. address: c.address ?? "",
  240. regionId: mounted,
  241. operatorId: c.operator_id ?? "",
  242. partnerId: c.partner_id ?? "",
  243. teamId: teams.length === 1 ? teams[0] : "",
  244. };
  245. }, [detail.data]);
  246. const [draft, setDraft] = useState<ProfileDraft | null>(null);
  247. const [editingField, setEditingField] = useState<keyof ProfileDraft | null>(null);
  248. /**
  249. * 提交成功后的乐观基线:在 `/customer/get@v1` 重读落定前先用它,
  250. * 否则「提交已完成、基线还是旧值」会把刚保存的值再判成未提交,甚至被后台重读回退。
  251. */
  252. const [baselineOverride, setBaselineOverride] = useState<ProfileDraft | null>(null);
  253. /** 读口重读落定 ⇒ 丢弃乐观基线,回到服务端真源。 */
  254. useEffect(() => { setBaselineOverride(null); }, [serverBaseline]);
  255. const baseline = baselineOverride ?? serverBaseline;
  256. useEffect(() => {
  257. // 正在编辑时不覆盖草稿:后台重读落定可能发生在输入过程中;退出编辑后由提交/取消各自对齐。
  258. if (!editingField) setDraft(baseline);
  259. }, [baseline]);
  260. /** 显示用草稿:数据刚到、state 还没跟上时直接用基线,⛔ 先闪一帧空值。 */
  261. const form = draft ?? baseline;
  262. const [fieldError, setFieldError] = useState<{ key: keyof ProfileDraft; message: string } | null>(null);
  263. const [notice, setNotice] = useState("");
  264. /** 识别号更正依据(写口 `change_basis`,选填):只在改识别号时随该项提交,由后端留存。 */
  265. const [idBasis, setIdBasis] = useState("");
  266. const [busy, setBusy] = useState(false);
  267. /** 登记材料补传/替换:直传状态与错误(⛔ 与建档页共用 state——两页生命周期独立)。 */
  268. const [licenseBusy, setLicenseBusy] = useState(false);
  269. const [licenseError, setLicenseError] = useState("");
  270. const [editingSub, setEditingSub] = useState<SubAccountRow | null>(null);
  271. const [orderDraft, setSubDraft] = useState({ displayName: "", netAccount: "" });
  272. const [orderError, setSubError] = useState("");
  273. const orderDialogRef = useRef<HTMLDialogElement>(null);
  274. /** 升降配/叠加:本页「04 全部订阅」行内「更多」直接办理,⛔ 逼用户先跳菜单「全部订阅」页再点一次。 */
  275. const [changeTarget, setChangeTarget] = useState<OrderView | null>(null);
  276. /** D-03:叠加=打开新建订阅弹窗(create@v1),⛔ 就地改结束日。 */
  277. const [createOpen, setCreateOpen] = useState(false);
  278. /* ── 主账号激活码重置(手册 P2:激活码过期或遗失 ⇒ 运营在本页重置,新明文只回显一次) ── */
  279. const [resetBusy, setResetBusy] = useState(false);
  280. const [resetError, setResetError] = useState("");
  281. const [freshCode, setFreshCode] = useState<{ code: string; expireDate: string } | null>(null);
  282. const primaryActivated = primaryAccount?.activation_status === "activated";
  283. async function resetPrimaryCode() {
  284. const userId = primaryAccount?.user_id;
  285. if (!userId) {
  286. setResetError("后端未下发 user_id,无法调用 /account/reset_code@v1。");
  287. return;
  288. }
  289. setResetBusy(true);
  290. setResetError("");
  291. setFreshCode(null);
  292. try {
  293. const res = await accountResetCode({ user_id: userId });
  294. const code = String(res?.plaintext_once ?? "").trim();
  295. // 平台「作废+发新码」三跳未接通时后端如实回 `capability_pending`+`reason`(本地只复位状态)
  296. // ⇒ 如实将原因呈现给运营,⛔ 把「已重置」说成「已发新码」、⛔ 前端造码。
  297. if (code) setFreshCode({ code, expireDate: String((res as { expire_date?: string | null })?.expire_date ?? "").trim() });
  298. else setResetError(res?.reason
  299. ? `本地状态已复位(旧码失效、可重新走导出交付),但本次未发新码:${res.reason}`
  300. : "应答未回激活码明文(plaintext_once 为空)⇒ 本次没有可分发的新码。");
  301. primaryAccountLoad.reload();
  302. } catch (e) {
  303. setResetError((e as ApiError)?.message || "重置激活码失败");
  304. } finally {
  305. setResetBusy(false);
  306. }
  307. }
  308. useEffect(() => {
  309. const dialog = orderDialogRef.current;
  310. if (!dialog) return;
  311. if (editingSub && !dialog.open) dialog.showModal();
  312. if (!editingSub && dialog.open) dialog.close();
  313. }, [editingSub]);
  314. const regionTree = useMemo(() => regionTreeNodes(organization.regions, organization.regions.map((item) => item.id)), [organization]);
  315. const mountedRegionPath = regionMountPath(organization, mount);
  316. const teamNames = teamIds.map((id) => organization.maintenanceTeams.find((item) => item.id === id)?.name ?? id);
  317. /** 后端当期回显 2 支以上=历史脏数据(运维团队单支定案)⇒ 按实呈现并提示改派,⛔ 前端截断成一支假装正常。 */
  318. const staleTeamHint = teamIds.length > 1 ? `历史脏数据:后端当期回显 ${teamIds.length} 支运维团队,按单支定案需改派为 1 支` : "";
  319. const subjectText = customer?.subject_type ? label(SUBJECT_TYPE, customer.subject_type) : "";
  320. const customerName = customer?.customer_name ?? "";
  321. const subjectOptions = CUSTOMER_SUBJECT_CODES.map((code) => ({ value: code, label: SUBJECT_TYPE[code] ?? code }));
  322. /** 草稿态展示名:改过的归属按草稿现算,没改过沿用读口原值(⛔ 用旧名字冒充新选择)。 */
  323. const draftRegionDisplay = form && baseline && form.regionId !== baseline.regionId
  324. ? regionComparablePath(organization, form.regionId) || form.regionId
  325. : mountedRegionPath;
  326. const draftOperatorName = form
  327. ? organization.operators.find((item) => item.id === form.operatorId)?.name ?? (form.operatorId === baseline?.operatorId ? customer?.operator_name ?? "" : "")
  328. : "";
  329. const draftPartnerName = form
  330. ? organization.partners.find((item) => item.id === form.partnerId)?.name ?? (form.partnerId === baseline?.partnerId ? customer?.partner_name ?? "" : "")
  331. : "";
  332. const draftTeamName = form
  333. ? organization.maintenanceTeams.find((item) => item.id === form.teamId)?.name ?? (form.teamId === baseline?.teamId ? teamNames.join("、") : "")
  334. : "";
  335. /** 运营团队=按挂载区域实时反查(⛔ 档案快照);身份命中候选时优先展示本队。 */
  336. const operationsTeamView = useMemo(() => {
  337. const regionId = form?.regionId || mount?.parent_node_id || "";
  338. if (!regionId) return { text: "请先挂载所属区域", note: "运营团队按所挂区域实时反查,客户档案不存快照" as string | undefined };
  339. const candidates = teamsCoveringRegion(organization.operationsTeams, regionAncestorChain(organization.regions, regionId));
  340. const lockedId = lockIfCandidate(view.identity?.operationsTeamId, candidates);
  341. return operationsTeamDisplay(candidates, lockedId);
  342. }, [form?.regionId, mount?.parent_node_id, organization.operationsTeams, organization.regions, view.identity?.operationsTeamId]);
  343. /** 主体类型由企业改为其他:后端会同时撤销已留存的营业执照影像(非企业不采集证件影像)。 */
  344. const subjectRevokesLicense = Boolean(baseline && baseline.subject === "enterprise" && form && form.subject !== "enterprise");
  345. if (detail.error) {
  346. return <section className="ops-page">
  347. <Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} />{back.label}</Link>
  348. <div className="ops-empty"><h1>取数失败</h1><FetchError message={detail.error.message} onRetry={detail.reload} /></div>
  349. </section>;
  350. }
  351. const invalidOf = (key: keyof ProfileDraft) => (fieldError?.key === key ? true : undefined);
  352. const errorOf = (key: keyof ProfileDraft) => (fieldError?.key === key ? <span className="ops-field-error">{fieldError.message}</span> : null);
  353. const patch = <K extends keyof ProfileDraft>(key: K, value: ProfileDraft[K]) => {
  354. setDraft((current) => (current ? { ...current, [key]: value } : current));
  355. setFieldError((current) => (current?.key === key ? null : current));
  356. };
  357. /** 点铅笔进入该项编辑:切走时把上一项未提交的草稿退回基线,⛔ 留下看不见的脏值。 */
  358. const startField = (key: keyof ProfileDraft) => {
  359. if (busy) return;
  360. if (editingField && editingField !== key && baseline) {
  361. setDraft((current) => (current ? { ...current, [editingField]: baseline[editingField] } : current));
  362. }
  363. setEditingField(key);
  364. setFieldError(null);
  365. setIdBasis("");
  366. };
  367. const cancelField = (key: keyof ProfileDraft) => {
  368. if (busy) return;
  369. if (baseline) setDraft((current) => (current ? { ...current, [key]: baseline[key] } : current));
  370. setEditingField(null);
  371. setFieldError(null);
  372. setIdBasis("");
  373. };
  374. /** 该字段的草稿值是否与基线一致(文本按去首尾空白比较;识别号读口只有脱敏值 ⇒ 从空串起算)。 */
  375. const sameAsBaseline = (key: keyof ProfileDraft, current: ProfileDraft) => {
  376. if (!baseline) return true;
  377. if (key === "name" || key === "contact" || key === "phone" || key === "address") {
  378. return String(current[key]).trim() === String(baseline[key]).trim();
  379. }
  380. return current[key] === baseline[key];
  381. };
  382. /**
  383. * 提交**单个**可编辑项(点对号/Enter 触发):改一项就写一项,⛔ 攒到底部统一保存。
  384. *
  385. * - 只送该项对应的写口:档案字段走 `customer/update@v1`,归属走 `attribution/update`,
  386. * 挂载区域走 `move_region`,运维团队走 `customer/update` 的 `ops_team_ids`;
  387. * - 失败保留输入态与草稿,错误行内呈现,可改后重试或取消;
  388. * - 成功后退出编辑并重读详情与变更历史。
  389. */
  390. async function commitField(key: keyof ProfileDraft) {
  391. if (!no || !draft || !baseline || busy) return;
  392. const current = draft;
  393. if (key === "name" && !current.name.trim()) { setFieldError({ key, message: "请填写客户名称" }); return; }
  394. if (key === "subject" && !current.subject) { setFieldError({ key, message: "请选择主体类型" }); return; }
  395. if (key === "regionId" && !current.regionId) { setFieldError({ key, message: "请选择挂载区域" }); return; }
  396. if (key === "operatorId" && !current.operatorId) { setFieldError({ key, message: "请选择运营商" }); return; }
  397. // 运维团队单支定案:客户固定挂 1 支,⛔ 提交空数组清空归属。
  398. if (key === "teamId" && !current.teamId) { setFieldError({ key, message: "请选择 1 支运维团队(客户固定挂 1 支,不可清空)" }); return; }
  399. const idNo = key === "idNo" ? current.idNo.trim().replace(/[\s-]/g, "").toUpperCase() : "";
  400. // 识别号读口只下发脱敏值:留空=该项未改,直接退出编辑,⛔ 提交脱敏串。
  401. if (key === "idNo" && !idNo) { setEditingField(null); setFieldError(null); setIdBasis(""); return; }
  402. if (key === "idNo" && !/^[A-Z0-9]{18}$|^\d{15}$/.test(idNo)) { setFieldError({ key, message: "识别号格式不符:应为 18 位统一社会信用代码/组织代码,或 15 位旧营业执照号" }); return; }
  403. // 值没变:不写接口、不留痕,直接退出编辑。
  404. if (sameAsBaseline(key, current)) { setEditingField(null); setFieldError(null); setIdBasis(""); return; }
  405. setBusy(true);
  406. setFieldError(null);
  407. try {
  408. switch (key) {
  409. case "name":
  410. await customerUpdate({ customer_id: no, customer_name: current.name.trim() });
  411. break;
  412. case "subject":
  413. await customerUpdate({ customer_id: no, subject_type: current.subject });
  414. break;
  415. case "idNo":
  416. await customerUpdate({ customer_id: no, id_code: idNo, ...(idBasis.trim() ? { change_basis: idBasis.trim() } : {}) });
  417. break;
  418. case "contact":
  419. await customerUpdate({ customer_id: no, contact_name: current.contact.trim() });
  420. break;
  421. case "phone":
  422. await customerUpdate({ customer_id: no, contact_mobile: current.phone.trim() });
  423. break;
  424. case "address":
  425. await customerUpdate({ customer_id: no, address: current.address.trim() });
  426. break;
  427. case "operatorId":
  428. case "partnerId":
  429. // `partner_id` 传空串=清空合伙人(后端约定),⛔ 用 undefined 冒充「不改」。
  430. await customerAttributionUpdate({ customer_id: no, operator_id: current.operatorId, partner_id: current.partnerId });
  431. break;
  432. case "regionId":
  433. await customerMoveRegion({ customer_id: no, new_region_node_id: current.regionId });
  434. break;
  435. case "teamId":
  436. await customerUpdate({ customer_id: no, ops_team_ids: [current.teamId] });
  437. break;
  438. }
  439. invalidateCustomerList();
  440. // 乐观基线:重读落定前,本次提交的值已视为基线,⛔ 让「刚保存」又被判成未提交。
  441. const committed = { ...current, name: current.name.trim(), contact: current.contact.trim(), phone: current.phone.trim(), address: current.address.trim() };
  442. setDraft(committed);
  443. setBaselineOverride(committed);
  444. setEditingField(null);
  445. setIdBasis("");
  446. setNotice("该项修改已保存,变更记录已写入历史。");
  447. detail.reload();
  448. changes.reload();
  449. } catch (e) {
  450. setFieldError({ key, message: (e as ApiError)?.message || "保存失败,请稍后重试。" });
  451. } finally {
  452. setBusy(false);
  453. }
  454. }
  455. function openSub(row: SubAccountRow) {
  456. if (false) return;
  457. setSubDraft({ displayName: row.display_name ?? "", netAccount: row.net_account ?? "" });
  458. setSubError("");
  459. setEditingSub(row);
  460. }
  461. async function saveSub(event: FormEvent<HTMLFormElement>) {
  462. event.preventDefault();
  463. if (false || !editingSub || busy) return;
  464. if (!orderDraft.displayName.trim()) { setSubError("请填写账号姓名。"); return; }
  465. setBusy(true);
  466. setSubError("");
  467. try {
  468. await subAccountUpdate({
  469. sub_account_id: editingSub.sub_account_id,
  470. display_name: orderDraft.displayName.trim(),
  471. network_account_name: orderDraft.netAccount.trim() || undefined,
  472. });
  473. setEditingSub(null);
  474. // 列表口的 `sub_account_count` 随分账号变化 ⇒ 共享快照一并作废(缺口清单 C-8)。
  475. invalidateCustomerList();
  476. accounts.reload();
  477. } catch (e) {
  478. setSubError((e as ApiError)?.message || "分账号修改失败。");
  479. } finally {
  480. setBusy(false);
  481. }
  482. }
  483. /**
  484. * 营业执照影像补传/替换(设计写入口只在本分区):选中即直传平台对象存储,
  485. * 成功后调 `POST /customer/update@v1` 写回对象键,再重读详情(拿新签名)。
  486. */
  487. async function replaceLicense(file: File | null) {
  488. if (!file || !no) return;
  489. setLicenseError("");
  490. setLicenseBusy(true);
  491. try {
  492. const uploaded = await uploadCustomerLicense(file);
  493. await customerUpdate({ customer_id: no, license: uploaded });
  494. invalidateCustomerList();
  495. detail.reload();
  496. } catch (e) {
  497. setLicenseError((e as ApiError)?.message || "影像上传失败。");
  498. } finally {
  499. setLicenseBusy(false);
  500. }
  501. }
  502. const displayName = customerName || no || "";
  503. /** 页头停用入口:取第一条生效中订阅;多条时行内仍可分别发起。 */
  504. const heroStopSub = orders.find((sub) => {
  505. const labelText = sub.status_display?.label ?? orderView(sub).statusLabel;
  506. return labelText === "生效中";
  507. });
  508. return <section className="ops-page ops-record-page customer-workspace record-detail">
  509. <Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} />{back.label}</Link>
  510. <header className="customer-record-masthead">
  511. <div className="customer-hero-symbol" aria-hidden="true"><Building2 size={26} /></div>
  512. <div className="customer-hero-copy">
  513. <p className="customer-record-id">CUSTOMER <span aria-hidden="true">·</span> <span>{no}</span></p>
  514. <h1 className="customer-record-title">{displayName}</h1>
  515. <div className="customer-record-tags">
  516. {subjectText && <OpsTag tone="brand">{subjectText}</OpsTag>}
  517. <AcctCell raw={customer?.acct_status} />
  518. <span className="customer-record-meta"><MapPin size={14} aria-hidden="true" /><span><TextCell value={mountedRegionPath} note="未取到该客户的区域挂载信息" /></span></span>
  519. <span className="customer-record-meta"><Building2 size={14} aria-hidden="true" /><span>运营商 <TextCell value={customer?.operator_name} /></span></span>
  520. <span className="customer-record-meta">
  521. <Wrench size={14} aria-hidden="true" />
  522. <span>运维团队 <TextCell value={teamNames.join("、")} note="未取到该客户的运维团队信息" />
  523. {staleTeamHint && <> <Tri tone="fail" text="需改派单支" title={staleTeamHint} /></>}
  524. </span>
  525. </span>
  526. </div>
  527. </div>
  528. <div className="ops-hero-actions customer-record-actions">
  529. {/* D-11:手册「客户/订阅详情页」均可发起服务停用;停用挂具体订阅(工单§3.2.1)。 */}
  530. {writable && heroStopSub ? <CustomerServiceStopAction
  531. customerId={no || ""}
  532. customerName={displayName}
  533. orderId={heroStopSub.subscription_id}
  534. orderLabel={heroStopSub.status_display?.label ?? orderView(heroStopSub).statusLabel}
  535. /> : null}
  536. <Button variant="outline" onClick={detail.reload}><RefreshCcw size={15} />刷新</Button>
  537. </div>
  538. </header>
  539. <dl className="customer-record-metrics" aria-label="客户业务摘要">
  540. <div>
  541. <dt><UsersRound size={16} aria-hidden="true" />分账号</dt>
  542. <dd>
  543. <strong>{metricCount(accounts.data?.total, accounts.loading, accounts.error)}</strong>
  544. <small>
  545. 在用分账号{(accounts.data?.total ?? 0) > accountRows.length ? "(已加载)" : ""}{" "}
  546. <span className="customer-record-active-count">
  547. {metricCount(accounts.data ? accountRows.filter((row) => row.status === "in_use").length : undefined, accounts.loading, accounts.error)}
  548. </span>
  549. </small>
  550. </dd>
  551. </div>
  552. <div>
  553. <dt><Gauge size={16} aria-hidden="true" />订阅额度</dt>
  554. <dd>
  555. <strong><TextCell value={customer?.quota_cents != null ? `${customer.quota_cents} 个` : undefined} /></strong>
  556. <small>汇总在用订阅席位,生效或终止时自动更新。明细见订阅详情。</small>
  557. </dd>
  558. </div>
  559. <div>
  560. <dt><ScrollText size={16} aria-hidden="true" />全部订阅</dt>
  561. <dd><strong>{metricCount(ordersLoad.data?.total ?? ordersLoad.data?.items.length, ordersLoad.loading, ordersLoad.error)}</strong><small>含历史订阅</small></dd>
  562. </div>
  563. <div>
  564. <dt><FileSignature size={16} aria-hidden="true" />关联合同</dt>
  565. <dd><strong>{metricCount(contractsLoad.data?.total ?? contractsLoad.data?.items.length, contractsLoad.loading, contractsLoad.error)}</strong><small>当前客户名下</small></dd>
  566. </div>
  567. </dl>
  568. <div className="record-tabs-frame">
  569. <RecordTabs prefix="customer" label="客户工作台视图" active={tab} onChange={setTab}
  570. tabs={WORKSPACE_TABS.map((item) => item.id === "subscriptions"
  571. ? { ...item, count: orders.length, panelId: "workspace-service" }
  572. : item.id === "subaccounts" ? { ...item, count: accounts.error ? "—" : accountRows.length } : item)}
  573. />
  574. <section className="ops-record-card customer-workspace-panel" id="customer-panel-profile" role="tabpanel" aria-labelledby="customer-tab-profile" hidden={tab !== "profile"}>
  575. <dl className="ops-record-summary">
  576. <div><dt>客户编号</dt><dd>{no}</dd></div>
  577. <div><dt>客户名称</dt><dd><InlineField id="customer-name" label="客户名称" value={form?.name ?? ""} editing={editingField === "name"} writable={writable} busy={busy} onStart={() => startField("name")} onChange={(value) => patch("name", value)} onDone={() => void commitField("name")} onCancel={() => cancelField("name")} emptyText={MISSING} invalid={invalidOf("name")} error={errorOf("name")} /></dd></div>
  578. <div><dt>主体类型</dt><dd><InlineField id="customer-subject" label="主体类型" value={form?.subject ?? ""} editing={editingField === "subject"} writable={writable} busy={busy} onStart={() => startField("subject")} onChange={(value) => patch("subject", value)} onDone={() => void commitField("subject")} onCancel={() => cancelField("subject")} display={form?.subject ? label(SUBJECT_TYPE, form.subject) : undefined} emptyText={MISSING} selectOptions={subjectOptions} invalid={invalidOf("subject")} error={errorOf("subject")} /></dd></div>
  579. <div><dt>识别号 / 统一社会信用代码</dt><dd><InlineField id="customer-id-no" label="客户识别号" value={form?.idNo ?? ""} editing={editingField === "idNo"} writable={writable} busy={busy} onStart={() => startField("idNo")} onChange={(value) => patch("idNo", value)} onDone={() => void commitField("idNo")} onCancel={() => cancelField("idNo")} display={form?.idNo ? form.idNo : customer?.identity_no_masked ?? undefined} emptyText="未登记识别号" invalid={invalidOf("idNo")} error={errorOf("idNo")} editor={<>
  580. <Input id="customer-id-no" aria-label="客户识别号" autoFocus disabled={busy} placeholder="填入完整识别号(留空=不改动)" value={form?.idNo ?? ""} onChange={(event) => patch("idNo", event.target.value)} onKeyDown={(event) => { if (isImeComposing(event)) return; if (event.key === "Enter") { event.preventDefault(); void commitField("idNo"); } if (event.key === "Escape") { event.preventDefault(); cancelField("idNo"); } }} />
  581. <Input aria-label="识别号变更依据" disabled={busy} placeholder="变更依据(选填,随变更日志留存)" value={idBasis} onChange={(event) => setIdBasis(event.target.value)} onKeyDown={(event) => { if (isImeComposing(event)) return; if (event.key === "Enter") { event.preventDefault(); void commitField("idNo"); } if (event.key === "Escape") { event.preventDefault(); cancelField("idNo"); } }} />
  582. </>} /></dd></div>
  583. <div><dt>联系人</dt><dd><InlineField id="customer-contact" label="联系人" value={form?.contact ?? ""} editing={editingField === "contact"} writable={writable} busy={busy} onStart={() => startField("contact")} onChange={(value) => patch("contact", value)} onDone={() => void commitField("contact")} onCancel={() => cancelField("contact")} emptyText="未登记" placeholder="客户方联系人,个人客户填本人" /></dd></div>
  584. <div><dt>联系电话</dt><dd><InlineField id="customer-phone" label="联系电话" value={form?.phone ?? ""} editing={editingField === "phone"} writable={writable} busy={busy} onStart={() => startField("phone")} onChange={(value) => patch("phone", value)} onDone={() => void commitField("phone")} onCancel={() => cancelField("phone")} emptyText="未登记" inputMode="numeric" placeholder="支持固定电话或手机号" /></dd></div>
  585. <div><dt>地址</dt><dd><InlineField id="customer-address" label="地址" value={form?.address ?? ""} editing={editingField === "address"} writable={writable} busy={busy} onStart={() => startField("address")} onChange={(value) => patch("address", value)} onDone={() => void commitField("address")} onCancel={() => cancelField("address")} emptyText="未登记" placeholder="完整地址,包括楼栋与房间号" /></dd></div>
  586. <div><dt>建档时间</dt><dd><TextCell value={customer?.created_at} /></dd></div>
  587. </dl>
  588. <p className="customer-form-note">识别号只能更正、不能读取明文(后端只下发脱敏值):点铅笔后填入完整新号码并点对号才会提交,留空或未改动=不提交。{staleTeamHint && <>运维团队{staleTeamHint}。</>}</p>
  589. {subjectRevokesLicense && <p className="customer-form-note">提交后主体类型将改为「{label(SUBJECT_TYPE, form?.subject ?? "")}」,系统会同时撤销该客户已留存的营业执照影像(非企业不采集证件影像),之后如需恢复只能按企业主体重新上传。</p>}
  590. </section>
  591. <section className="ops-record-card customer-workspace-panel" id="customer-panel-attribution" role="tabpanel" aria-labelledby="customer-tab-attribution" hidden={tab !== "attribution"}>
  592. <dl className="ops-record-summary">
  593. <div><dt>所属区域</dt><dd><InlineField id="customer-region" label="所属区域" value={form?.regionId ?? ""} editing={editingField === "regionId"} writable={writable} busy={busy} onStart={() => startField("regionId")} onChange={(value) => patch("regionId", value)} onDone={() => void commitField("regionId")} onCancel={() => cancelField("regionId")} display={draftRegionDisplay || undefined} emptyText={MISSING} editor={<TreeSelect treeData={regionTree} value={form?.regionId ?? ""} onChange={(value) => patch("regionId", value)} ariaLabel="所属区域" placeholder="请选择区域节点" name="customer-region" />} invalid={invalidOf("regionId")} error={errorOf("regionId")} /></dd></div>
  594. <div><dt>运营商</dt><dd><InlineField id="customer-operator" label="运营商" value={form?.operatorId ?? ""} editing={editingField === "operatorId"} writable={writable} busy={busy} onStart={() => startField("operatorId")} onChange={(value) => patch("operatorId", value)} onDone={() => void commitField("operatorId")} onCancel={() => cancelField("operatorId")} display={draftOperatorName || undefined} emptyText={MISSING} selectOptions={[{ value: "", label: "请选择运营商" }, ...organization.operators.map((item) => ({ value: item.id, label: item.name }))]} invalid={invalidOf("operatorId")} error={errorOf("operatorId")} /></dd></div>
  595. {/* 合伙人选填(至多 1 个):`partner_id` 为空=业务上的「未绑定」,⛔ 与「后端未下发」混为一谈。 */}
  596. <div><dt>合伙人</dt><dd><InlineField id="customer-partner" label="合伙人" value={form?.partnerId ?? ""} editing={editingField === "partnerId"} writable={writable} busy={busy} onStart={() => startField("partnerId")} onChange={(value) => patch("partnerId", value)} onDone={() => void commitField("partnerId")} onCancel={() => cancelField("partnerId")} display={form ? (form.partnerId ? draftPartnerName || form.partnerId : "未绑定合伙人") : undefined} emptyText="未绑定合伙人" selectOptions={[{ value: "", label: "不绑定" }, ...organization.partners.map((item) => ({ value: item.id, label: item.name }))]} /></dd></div>
  597. <div><dt>运营团队</dt><dd><span className="customer-inline-readonly" title={operationsTeamView.note}>{operationsTeamView.text}{operationsTeamView.note ? <span className="ops-muted"> {operationsTeamView.note}</span> : null}</span></dd></div>
  598. <div><dt>运维团队</dt><dd><InlineField id="customer-team" label="运维团队" value={form?.teamId ?? ""} editing={editingField === "teamId"} writable={writable} busy={busy} onStart={() => startField("teamId")} onChange={(value) => patch("teamId", value)} onDone={() => void commitField("teamId")} onCancel={() => cancelField("teamId")} display={draftTeamName || undefined} emptyText={MISSING} editor={<CustomerTeamSelect options={organization.maintenanceTeams.map((item) => ({ id: item.id, name: item.name, hint: (item.ticketTypes ?? []).map(typeLabel).join("、") }))} value={form?.teamId ?? ""} onChange={(id) => patch("teamId", id)} />} invalid={invalidOf("teamId")} error={errorOf("teamId")} /></dd></div>
  599. </dl>
  600. <p className="customer-form-note">挂载区域、运营商、合伙人与运维团队(客户固定挂 1 支)的变更由后端留存记录;运营团队按所挂区域实时反查、不写入客户档案。区域与运营商省份不一致会被后端拦下。每项点对号即提交。{staleTeamHint && <>{staleTeamHint};改派前本次不提交运维团队。</>}</p>
  601. </section>
  602. <section className="ops-record-card customer-workspace-panel" id="customer-panel-primary" role="tabpanel" aria-labelledby="customer-tab-primary" hidden={tab !== "primary"}>
  603. <div className="customer-panel-grid">
  604. <div className="customer-panel"><dl>
  605. <div><dt>登录名</dt><dd>{primaryAccount ? <TextCell value={primaryAccount.username} /> : <Tri tone={primaryAccountLoad.error ? "fail" : "missing"} text={MISSING} title={primaryAccountMissing} />}</dd></div>
  606. <div><dt>绑定手机号</dt><dd>{primaryAccount ? <OptionalCell value={primaryAccount.mobile} note="该主账号未登记手机号" /> : <Tri tone={primaryAccountLoad.error ? "fail" : "missing"} text={MISSING} title={primaryAccountMissing} />}</dd></div>
  607. <div><dt>账号状态</dt><dd>{primaryAccount ? <AcctCell raw={primaryAccount.status} /> : <Tri tone={primaryAccountLoad.error ? "fail" : "missing"} text={MISSING} title={primaryAccountMissing} />}</dd></div>
  608. <div><dt>首次登录改密</dt><dd>{primaryAccount ? (primaryAccount.pwd_set_at ? <>已改密<br /><span className="ops-muted">{primaryAccount.pwd_set_at}</span></> : <span className="ops-muted">未改密</span>) : <Tri tone={primaryAccountLoad.error ? "fail" : "missing"} text={MISSING} title={primaryAccountMissing} />}</dd></div>
  609. </dl></div>
  610. <div className="customer-panel"><h3>当前激活信息</h3><dl>
  611. <div><dt>激活状态</dt><dd>{primaryAccount ? (primaryAccount.activation_status
  612. ? <OpsStatus tone={activationTone(primaryAccount.activation_status)}>{label(ACTIVATION_STATUS, primaryAccount.activation_status)}</OpsStatus>
  613. /* 三态(巡检 P1-D2):非主账号(入口/分账号)本就不产生激活码,⛔ 写成「后端未下发」。 */
  614. : primaryAccount.account_kind !== "primary"
  615. ? <span className="ops-muted" title={`account_kind=${primaryAccount.account_kind}:入口/分账号不产生激活码,bos_account_ext 不会为其建行`}>不适用(非主账号,不产生激活码)</span>
  616. : <Tri tone="missing" text={MISSING} title="bos_account_ext 未生成该账号的激活码扩展行" />) : <Tri tone={primaryAccountLoad.error ? "fail" : "missing"} text={MISSING} title={primaryAccountMissing} />}</dd></div>
  617. <div><dt>激活码发送日</dt><dd>{primaryAccount ? <OptionalCell value={primaryAccount.delivered_at} note="尚未交付激活码" /> : <Tri tone={primaryAccountLoad.error ? "fail" : "missing"} text={MISSING} title={primaryAccountMissing} />}</dd></div>
  618. <div><dt>激活截止日</dt><dd>{primaryAccount ? <OptionalCell value={primaryAccount.expire_date} note="无未消费激活码(已激活或已过期)" /> : <Tri tone={primaryAccountLoad.error ? "fail" : "missing"} text={MISSING} title={primaryAccountMissing} />}</dd></div>
  619. <div><dt>激活码</dt><dd>{freshCode ? <><code className="ops-code-plain">{freshCode.code}</code>{freshCode.expireDate ? <span className="ops-muted"> 有效期至 {freshCode.expireDate}</span> : null}</> : primaryActivated ? <span className="ops-muted" title={NO_ACTIVATION_CODE_READ}>已激活,不可查看</span> : <Tri tone="missing" text={MISSING} title={NO_ACTIVATION_CODE_READ} />}</dd></div>
  620. <div><dt>重置激活码</dt><dd><div className="ops-entity-actions">{primaryActivated
  621. ? <span className="ops-muted" title={CODE_RESET_ACTIVATED_NOTE}>已激活,不提供重置入口</span>
  622. : <Button type="button" variant="outline" disabled={resetBusy || !primaryAccount} onClick={resetPrimaryCode} title={!primaryAccount ? NO_ACCOUNT_FOUND : "作废旧码并发新码(仅未激活账号),新明文只回显一次"}>{resetBusy ? "正在重置…" : "重置激活码"}</Button>}</div></dd></div>
  623. </dl></div>
  624. </div>
  625. {resetError ? <p className="ops-form-error" role="alert">{resetError}</p> : null}
  626. {freshCode ? <p className="customer-form-note">{CODE_RESET_ONCE_NOTE}</p> : null}
  627. <p className="customer-form-note">账号状态取 <code>bos_user_binding.status</code>(启停),激活状态取 <code>bos_account_ext.status</code>(激活码生命周期),两者正交:账号可用性只决定能否登录。激活码明文仅开通/重置当次回执一次性下发,本页「重置激活码」后的新码同样只在上方回显一次。</p>
  628. </section>
  629. <section className="ops-record-card customer-workspace-panel" id="workspace-service" role="tabpanel" aria-labelledby="customer-tab-subscriptions" hidden={tab !== "subscriptions"}>
  630. <div className="ops-table-wrap record-table-scroll" role="region" aria-label="全部订阅列表" tabIndex={0}>{ordersLoad.error ? <div className="ops-empty"><FetchError message={ordersLoad.error.message} onRetry={ordersLoad.reload} /></div> :
  631. <table className="ops-table record-subscriptions-table"><OpsTableColumns widths={[170, 90, 90, 110, 130, 170, 80, 110, 90, 80]} /><OpsTableHead columns={["套餐", "类型", "变更类型", "关联订阅", "合同", "服务期限", "分账号", "月缴金额", "状态", "操作"]} />
  632. <tbody>{orders.length ? orders.map((sub: any) => {
  633. const row = orderView(sub);
  634. const rowStatus = sub.status_display?.label ?? row.statusLabel;
  635. /** 只有生效中的订阅可替换(升降配)或叠加新建并存订阅;只读身份不挂入口。 */
  636. const orderMore: OpsMoreItem[] = writable && rowStatus === "生效中" ? [
  637. { label: "升降配", icon: <RefreshCw size={15} />, onSelect: () => setChangeTarget(row) },
  638. // D-03:叠加=新建并存订阅,⛔ 就地改结束日。
  639. { label: "叠加", icon: <CalendarPlus size={15} />, onSelect: () => setCreateOpen(true) },
  640. ] : [];
  641. return <tr key={sub.subscription_id}>
  642. <td><Link className="contract-ref-link" to={`/orders/${encodeURIComponent(sub.subscription_id)}`} state={outgoingState}>{sub.plan_name ?? sub.plan_id}</Link><small>{sub.subscription_id}</small></td>
  643. <td>{sub.plan_kind ? label(PLAN_KIND, sub.plan_kind) : "-"}</td>
  644. <td title="由替换关系派生:有 replaces_subscription_id=升降配,否则新签">{sub.replaces_subscription_id ? "升降配" : "新签"}</td>
  645. <td title="由替换关系派生:有 replaces_subscription_id=升降配,否则新签">{sub.replaces_subscription_id ? <TextCell value={sub.replaces_subscription_id} /> : <span className="ops-muted">—(新签,无前序订阅)</span>}</td>
  646. <td>{sub.contract_no ?? sub.contract_id ?? "-"}</td>
  647. <td>{sub.start_date ?? "—"} 至 {sub.end_date ?? "—"}</td>
  648. <td>{sub.quota_slots ?? 0} 个</td>
  649. <td>{sub.monthly_settle_cents ? money(String(sub.monthly_settle_cents / 100)) : <Tri tone="missing" text={MISSING} title={MISSING + ":monthly_settle_cents 未下发"} />}</td>
  650. <td><OpsStatus tone={statusTone(sub.status_display?.label ?? sub.status)}>{sub.status_display?.label ?? sub.status ?? MISSING}</OpsStatus>{sub.editable === false && sub.reason ? `(${sub.reason.replace(/([^()]*)$/, "").replace(/[,。;]$/, "")})` : ""}</td>
  651. <td><div className="ops-inline-actions">
  652. {writable && rowStatus === "生效中" ? <CustomerServiceStopAction customerId={no || ""} customerName={displayName} orderId={sub.subscription_id} orderLabel={rowStatus} /> : null}
  653. <OpsMore items={orderMore} placeholder />
  654. </div></td>
  655. </tr>;
  656. }) : <OpsTableEmpty colSpan={10}>该客户暂无套餐订阅记录</OpsTableEmpty>}</tbody>
  657. </table>}</div>
  658. </section>
  659. <section className="ops-record-card customer-workspace-panel" id="customer-panel-subaccounts" role="tabpanel" aria-labelledby="customer-tab-subaccounts" hidden={tab !== "subaccounts"}>
  660. <div className="ops-table-wrap record-table-scroll" role="region" aria-label="分账号列表" tabIndex={0}><table className="ops-table record-accounts-table"><OpsTableColumns widths={[60, 130, 110, 170, 90, 110, 110, 80]} /><OpsTableHead columns={["序号", "账号名", "姓名", "网络侧账号名", "账号状态", "开通日", "停用日", "操作"]} />
  661. <tbody>{accounts.error ? <tr><td colSpan={8}><Tri tone="fail" text="取数失败" title={accounts.error.message} /></td></tr>
  662. : accountRows.length ? accountRows.map((row, index) => <tr key={row.sub_account_id}>
  663. <td>{index + 1}</td>
  664. {/* 三态(巡检 P1-D2):未开通/已停用的席位没有账号名属正常态,⛔ 标「后端未下发」。 */}
  665. <td>{row.username?.trim()
  666. ? <TextCell value={row.username} />
  667. : row.status === "not_opened"
  668. ? <span className="ops-muted" title="该席位尚未开通,账号名在开通后登记">未开通</span>
  669. : row.status === "stopped"
  670. ? <span className="ops-muted" title="该席位已停用,账号名随停用不再展示">已停用</span>
  671. : <OptionalCell value={row.username} note="后端未登记该席位的账号名(sub_account.username 已下发、值为空)" />}</td>
  672. <td><TextCell value={seatDisplayName(row)} note={isSeatPlaceholder(row) ? "系统按套餐额度自动补建的席位(需求§4.2):姓名留空,此处按登录名尾号「席位 n」占位显示,不作为真实姓名落库" : undefined} /></td>
  673. {/*
  674. P1-D2:空值分三档,⛔ 一律标「后端未下发」——
  675. `not_opened`=席位尚未开通(回填后才登记);已开通但 `net_account` 为空=
  676. 开户回填未登记(字段已下发、值为空);有值=原样显示。
  677. */}
  678. <td>{row.net_account?.trim()
  679. ? row.net_account
  680. : row.status === "not_opened"
  681. ? <span className="ops-muted" title="该席位尚未开通,网络侧账号名在开户回填后登记">未开通</span>
  682. : <OptionalCell value={row.net_account} note="开户回填未登记该席位的网络侧账号名(sub_account.net_account 已下发、值为空)" />}</td>
  683. <td><AcctCell raw={row.status} /></td>
  684. <td><TextCell value={row.created_at} /></td>
  685. <td>{row.stopped_at ? <TextCell value={row.stopped_at} /> : <span className="ops-muted">—(未停用)</span>}</td>
  686. <td><Button variant="ghost" onClick={() => openSub(row)}>编辑</Button></td>
  687. </tr>) : <OpsTableEmpty colSpan={8}>该客户暂无分账号</OpsTableEmpty>}
  688. </tbody>
  689. </table></div>
  690. <p className="customer-form-note">网络侧账号名由客户提供,仅用于与本系统账号对照,系统不为其做唯一性或格式校验。分账号的开通与停发:{MISSING} —— <code>/sub_account/*</code> 只有读列表与改姓名两个口,无新增与删除路由。</p>
  691. </section>
  692. <section className="ops-record-card customer-workspace-panel" id="customer-panel-materials" role="tabpanel" aria-labelledby="customer-tab-materials" hidden={tab !== "materials"}>
  693. <div className="customer-panel customer-material-panel">
  694. <h3>登记材料 · 营业执照影像</h3>
  695. <CustomerMaterialCard>
  696. {!licenseApplicable ? <>
  697. <strong>不适用</strong>
  698. <p>个人和个体工商户无需登记营业执照影像。</p>
  699. </> : license?.status === "viewable" ? <>
  700. <div className="customer-license-filename"><strong>{license.file_name ?? "营业执照影像"}</strong><OpsStatus tone="success">已登记</OpsStatus></div>
  701. <p>{license.view_url ? "查看链接短期有效,失效后请刷新页面。" : "查看链接暂不可用,请刷新页面。"}</p>
  702. {license.view_url && <div className="customer-material-links">
  703. <a href={license.view_url} target="_blank" rel="noopener noreferrer">查看影像</a>
  704. <a href={license.view_url} download={license.file_name ?? ""} target="_blank" rel="noopener noreferrer">下载</a>
  705. </div>}
  706. </> : license?.status === "expired" ? <>
  707. <strong>已超期</strong>
  708. <p>影像留存期已满,无法查看或下载。</p>
  709. </> : <>
  710. <strong>{license ? "未登记影像" : MISSING}</strong>
  711. <p>{license ? "营业执照影像为选填材料,可在此补传。" : "暂未获取影像登记状态。"}</p>
  712. </>}
  713. {licenseApplicable && license?.status !== "expired" && <div className="customer-license-upload">
  714. <label className="customer-upload-button customer-license-button">
  715. <Upload size={15} aria-hidden="true" />
  716. {licenseBusy ? "正在上传…" : license?.status === "viewable" ? "替换影像" : "上传影像"}
  717. <input
  718. aria-label="上传营业执照影像"
  719. aria-describedby="customer-license-upload-note"
  720. type="file"
  721. disabled={licenseBusy || busy}
  722. onChange={(event) => {
  723. const file = event.target.files?.[0] ?? null;
  724. event.target.value = "";
  725. void replaceLicense(file);
  726. }}
  727. />
  728. </label>
  729. <small id="customer-license-upload-note">格式和大小以平台限制为准。替换影像后,留存期限仍从建档日起算。</small>
  730. </div>}
  731. </CustomerMaterialCard>
  732. {licenseError && <p className="ops-form-error" role="alert">{licenseError}</p>}
  733. </div>
  734. <div className="customer-panel customer-material-panel">
  735. <h3>合同文档</h3>
  736. {contractsLoad.error ? <CustomerMaterialCard>
  737. <strong>合同文档读取失败</strong>
  738. <FetchError message={contractsLoad.error.message} onRetry={contractsLoad.reload} />
  739. </CustomerMaterialCard> : contractsLoad.loading ? <CustomerMaterialCard>
  740. <strong>正在读取合同文档…</strong>
  741. </CustomerMaterialCard> : contractFiles.length ? <div className="customer-material-list">
  742. {contractFiles.map((document) => <CustomerMaterialCard key={`${document.contractNo}-${document.name}`}>
  743. <strong>{document.name}</strong>
  744. <p>{document.contractNo}</p>
  745. <div className="customer-material-links">
  746. <Link to={`/contracts/${encodeURIComponent(document.contractNo)}?download=${encodeURIComponent(document.name)}`} state={outgoingState}>预览</Link>
  747. </div>
  748. </CustomerMaterialCard>)}
  749. </div> : <CustomerMaterialCard>
  750. <strong>暂无合同文档</strong>
  751. <p>文档随合同登记上传。</p>
  752. </CustomerMaterialCard>}
  753. </div>
  754. <p className="customer-form-note">应备材料(按主体类型):{subjectText ? customerMaterials(subjectText as "企业" | "个体工商户" | "个人") : <Tri tone="missing" text={MISSING} title={MISSING + ":subject_type"} />};合同文档:{CONTRACT_DOC_NOTE}。</p>
  755. </section>
  756. <section className="ops-record-card customer-workspace-panel" id="customer-panel-history" role="tabpanel" aria-labelledby="customer-tab-history" hidden={tab !== "history"}>
  757. <div className="ops-table-wrap record-table-scroll" role="region" aria-label="客户历史记录列表" tabIndex={0}><table className="ops-table record-history-table"><OpsTableColumns widths={[150, 140, 320, 150]} /><OpsTableHead columns={["时间", "变更项", "变化前 → 变化后", "操作人"]} />
  758. <tbody>{changes.error ? <tr><td colSpan={4}><Tri tone="fail" text="取数失败" title={changes.error.message} /></td></tr>
  759. : changeRows.length ? changeRows.map((row, index) => <tr key={`${row.changed_at ?? "h"}-${index}`}>
  760. <td><TextCell value={row.changed_at} /></td>
  761. <td><TextCell value={row.field_key} /></td>
  762. <td>{row.old_value || row.new_value ? <div className="ops-change-diff"><span>{row.old_value?.trim() || "(空)"}</span><span>{row.new_value?.trim() || "(已清空)"}</span></div> : <Tri tone="missing" text={MISSING} title={MISSING + ":/customer/history@v1 未回该项的新旧值"} />}</td>
  763. <td><TextCell value={row.operator} />{row.source ? <><br /><span className="ops-muted">{row.source}</span></> : null}</td>
  764. </tr>) : <OpsTableEmpty colSpan={4}>后端未返回该客户的变更记录</OpsTableEmpty>}
  765. </tbody>
  766. </table></div>
  767. </section>
  768. {/* 交付现状(讨论稿 §7.7):按需挂载——不进该页签就不发 `/delivery/list@v1`。 */}
  769. <section className="ops-record-card customer-workspace-panel" id="customer-panel-delivery" role="tabpanel" aria-labelledby="customer-tab-delivery" hidden={tab !== "delivery"}>
  770. {tab === "delivery" && no ? <DeliveryStatusTable customerId={no} /> : null}
  771. </section>
  772. </div>
  773. {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
  774. {editingSub && <dialog ref={orderDialogRef} onClose={() => setEditingSub(null)} className="ops-dialog" aria-labelledby="sub-account-edit-title">
  775. <form method="dialog" className="ops-entity-form" onSubmit={saveSub}>
  776. <h2 id="sub-account-edit-title">编辑分账号</h2>
  777. <label><span className="ops-field-title">所属客户</span><Input disabled value={displayName} /></label>
  778. <label><span className="ops-field-title">账号名</span><Input disabled value={editingSub.username ?? ""} placeholder={MISSING} /></label>
  779. <label><span className="ops-field-title">姓名<b>*</b></span><Input value={orderDraft.displayName} autoComplete="off" aria-invalid={Boolean(orderError)} onChange={(event) => setSubDraft((value) => ({ ...value, displayName: event.target.value }))} /></label>
  780. <label><span className="ops-field-title">网络侧账号名</span><Input value={orderDraft.netAccount} autoComplete="off" placeholder="客户网络系统中的账号名" onChange={(event) => setSubDraft((value) => ({ ...value, netAccount: event.target.value }))} /></label>
  781. <div><span className="ops-field-title">当前状态</span><div style={{ paddingTop: 6 }}><AcctCell raw={editingSub.status} /></div></div>
  782. {orderError && <p className="ops-form-error" role="alert">{orderError}</p>}
  783. <div className="ops-entity-actions"><Button type="submit" disabled={busy}>保存</Button><Button type="button" variant="outline" disabled={busy} onClick={() => setEditingSub(null)}>取消</Button></div>
  784. </form>
  785. </dialog>}
  786. {changeTarget && <OrderEditor key={`updown-${changeTarget.no}`} customerId={changeTarget.customerId || no || ""} customerName={displayName} context={{ mode: "updown", record: changeTarget }} onClose={() => setChangeTarget(null)} onSaved={(message) => { setChangeTarget(null); setNotice(message); ordersLoad.reload(); detail.reload(); }} />}
  787. {createOpen && <OrderEditor key="stack-new" customerId={no || ""} customerName={displayName} context={{ mode: "new" }} onClose={() => setCreateOpen(false)} onSaved={(message) => { setCreateOpen(false); setNotice(message); ordersLoad.reload(); detail.reload(); }} />}
  788. </section>;
  789. }
  790. /** 表头(列宽比例由 OpsTableColumns 组件下发,⛔ 在本页硬编码像素宽)。 */
  791. function OpsTableHead({ columns }: { columns: string[] }) {
  792. return <thead><tr>{columns.map((title, index) => <th key={`${title}-${index}`}>{title}</th>)}</tr></thead>;
  793. }