CustomerWorkspacePage.tsx 64 KB

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