OrderChangeDialogs.tsx 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /**
  2. * 订阅办理弹窗:新建/叠加走 `create`、升降配走 `change`、编辑只放开白名单字段走 `update`。
  3. *
  4. * ✅ D-03:行内「叠加」=本弹窗 `mode: "new"`(新建并存订阅+客户在用时生成服务开通工单),
  5. * ⛔ 再走 legacy `subscription/stack@v1` 就地改结束日。
  6. *
  7. * 价格、月标准、结束日、实际开通日、线路出口、订单号六项只读,由服务端按套餐配置与合同条目带出;
  8. * ⛔ 在此提交或改写它们(出现即 `11103`)。
  9. *
  10. * 三个入口共用同一份弹窗:客户档案「套餐订阅管理」行内、客户档案「04 全部订阅」行内、订阅详情页头,
  11. * 判据与载荷只写一次,⛔ 各页各写一份抽屉造成口径漂移。
  12. * ⚠️ 菜单「全部订阅」(路由 `/orders`)按需求 5.2 只读,⛔ 挂本弹窗的写入口。
  13. * 升降配只改「套餐」这一项:原订阅的合同/条目/档位在左侧只读锁定,右侧只列**可替换的新套餐**
  14. * (来源=各替换合同条目的绑定档位),选一次即带出合同/条目/档位三键(业主 2026-11-16 定案)。
  15. */
  16. import { useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";
  17. import { ArrowRight, X } from "lucide-react";
  18. import { Button } from "./ui/button";
  19. import { FieldHint } from "./ui/field-hint";
  20. import { OPTIONS } from "../lib/api/labels";
  21. import {
  22. CONTRACT_OPTIONS_EMPTY, ORDER_AMOUNT_TITLE, ORDER_CREATE_READONLY_NOTE, ORDER_END_DATE_READONLY,
  23. WORD_FETCH_FAILED, WORD_MODE_PENDING, WORD_NOT_OPENED, WORD_PICK_CONTRACT_FIRST,
  24. WORD_PICK_CONTRACT_ITEM_FIRST, WORD_PICK_PLAN_FIRST, WORD_UNCONFIGURED,
  25. } from "../lib/api/lockedCopy";
  26. import { moneyCell, yuanToCents } from "../lib/package-catalog";
  27. import { rowsOf, orderChange, orderContractOptions, orderCreate, orderPlanOptions, orderUpdate, contractGet } from "../lib/api/bos";
  28. import type { OrderContractItemOption, OrderContractOption, OrderPlanOption } from "../lib/api/types";
  29. import { useLoad } from "../lib/useLoad";
  30. import type { OrderView } from "../lib/order-demo";
  31. export type OrderEditorMode = "new" | "edit" | "view" | "updown";
  32. export type OrderEditorContext = { mode: OrderEditorMode; record?: OrderView };
  33. /** 升降配的变更目标:替换合同+服务构成条目+新档位,三者由后端强校验必须自洽。 */
  34. type UpdownTarget = {
  35. key: string;
  36. contractId: string;
  37. /** 合同**外部单号**:台账、订阅详情都按这个口径显示,⛔ 这里改用内部号造成两处对不上。 */
  38. contractLabel: string;
  39. /** 真合同号:外部单号可重复(实测两份合同同叫 WB-P3-20261115-01),两号并显才分得清(D-33)。 */
  40. contractInternal: string | null;
  41. sameContract: boolean;
  42. itemId: string;
  43. planId: string;
  44. planName: string;
  45. annualCents: number | null;
  46. settleCents: number | null;
  47. quota: number | null;
  48. exits: string[] | null;
  49. sameAsOriginal: boolean;
  50. };
  51. /**
  52. * 结束日预览(D-72)=`/subscription/create@v1` 里 `derive_period` 的同口径前端镜像:
  53. * 生效日折 N 个月(当月不足 N 月时夹到月末)得「下一周期生效日」⇒ 再减一天;
  54. * 结果晚于合同止期 ⇒ 截到合同止期。⚠️ 只是**预览**,落库值一律以服务端为准。
  55. */
  56. function previewEnd(start: string, term: string, contractEnd: string | null): string | null {
  57. if (!/^\d{4}-\d{2}-\d{2}$/.test(start)) return null;
  58. const months = term === "quarterly" ? 3 : term === "monthly" ? 1 : 12;
  59. const [y, m, d] = start.split("-").map(Number);
  60. const anchor = new Date(Date.UTC(y, m - 1 + months, 1));
  61. const last = new Date(Date.UTC(anchor.getUTCFullYear(), anchor.getUTCMonth() + 1, 0)).getUTCDate();
  62. anchor.setUTCDate(Math.min(d, last));
  63. anchor.setUTCDate(anchor.getUTCDate() - 1);
  64. const iso = anchor.toISOString().slice(0, 10);
  65. return contractEnd && contractEnd < iso ? contractEnd : iso;
  66. }
  67. /** 只读输入框只能用字符串:三态在这里落到锁定文案,⛔ 用「—」或 0 冒充。 */
  68. const textOf = (value: string | null | undefined, missing: string = WORD_UNCONFIGURED) =>
  69. (value === undefined ? WORD_FETCH_FAILED : value === null || value === "" ? missing : value);
  70. /**
  71. * 合同两号并显:`contract_no` 是外部单号,**可以重复**(实测两份合同同叫 WB-P3-20261115-01),
  72. * 内部号才唯一 ⇒ 只显示一个就会把「原合同」和另一份合同认成同一份(D-33)。
  73. */
  74. const contractText = (external: string | null | undefined, internal: string | null | undefined) => {
  75. const ext = external ?? "";
  76. if (!internal || internal === ext) return ext || textOf(external);
  77. return ext ? `${ext} / ${internal}` : internal;
  78. };
  79. /** 本地「今天」:`toISOString()` 是 UTC,跨时区会把默认生效日推到前一天/后一天。 */
  80. function todayText(): string {
  81. const now = new Date();
  82. return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
  83. }
  84. function Dialog({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
  85. const ref = useRef<HTMLDialogElement>(null);
  86. useEffect(() => {
  87. const dialog = ref.current;
  88. if (!dialog) return;
  89. const previous = document.activeElement as HTMLElement | null;
  90. dialog.showModal();
  91. return () => { dialog.close(); previous?.focus(); };
  92. }, []);
  93. return <dialog ref={ref} className="customer-sub-dialog" aria-labelledby="customer-sub-dialog-title" onCancel={onClose} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
  94. <header><div><span>订阅办理</span><h2 id="customer-sub-dialog-title">{title}</h2></div><button type="button" aria-label="关闭" onClick={onClose}><X size={19} /></button></header>
  95. {children}
  96. </dialog>;
  97. }
  98. export function OrderEditor({ customerId, customerName, context, onClose, onSaved }: {
  99. customerId: string; customerName: string; context: OrderEditorContext; onClose: () => void; onSaved: (message: string) => void;
  100. }) {
  101. const existing = context.record;
  102. /**
  103. * 升降配带入原订阅的合同/条目/档位/时长(业主 2026-11-16 定案):
  104. * 原订阅的合同/条目/套餐是**被替换的对象**,⛔ 可编辑——它们只作为只读「原订阅」呈现;
  105. * 用户唯一要做的是在「新套餐」里挑一个变更目标(业主 2026-11-16 二次定案:
  106. * 「带入的原套餐还可以改」=说不清在改哪一边,套餐切换也就看不出来)。
  107. * 合同/条目仍由所选新套餐反推(后端按 `contract_item_id` 反查条目并强校验档位匹配)。
  108. */
  109. const updown = context.mode === "updown";
  110. const fresh = context.mode === "new";
  111. const originalContractId = existing?.contractId ?? "";
  112. const originalItemId = existing?.contractItemId ?? "";
  113. const [contractId, setContractId] = useState(fresh || updown ? "" : originalContractId);
  114. const [itemId, setItemId] = useState(fresh || updown ? "" : originalItemId);
  115. const [planId, setPlanId] = useState(fresh || updown ? "" : existing?.planId ?? "");
  116. /** 升降配的「变更目标」=(替换合同, 服务构成条目, 新档位) 三元组;选它一次就带齐三个载荷键。 */
  117. const [targetKey, setTargetKey] = useState("");
  118. const [term, setTerm] = useState(updown ? existing?.row.term ?? "yearly" : "yearly");
  119. /**
  120. * 升降配的生效日默认**当天**(契约 §5.2「开始日默当天」):原订阅的生效日多半已过去,
  121. * 照抄会把替换单做成过去时,截原时「新开始−1 天」早于原开始日 ⇒ 原订阅被压成零天期间。
  122. */
  123. const defaultStart = updown ? todayText() : existing?.start ?? "";
  124. const [startDate, setStartDate] = useState(defaultStart);
  125. const [trialMonths, setTrialMonths] = useState<"0" | "1" | "2">(existing?.trialMonths === 1 || existing?.trialMonths === 2 ? String(existing.trialMonths) as "1" | "2" : "0");
  126. const [trialDiscount, setTrialDiscount] = useState(existing?.trialDiscount ? String(existing.trialDiscount / 100) : "");
  127. const [error, setError] = useState("");
  128. const [pending, setPending] = useState(false);
  129. const contracts = useLoad(() => orderContractOptions({ customer_id: customerId }), [customerId]);
  130. const plans = useLoad(() => orderPlanOptions({ customer_id: customerId }), [customerId]);
  131. /**
  132. * 原合同明细另取:候选口按「合同未开通」+「条目未被订阅引用」双筛,而升降配的源头合同恰恰
  133. * 两条都不满足 ⇒ 原合同及其全部条目都不在 `contract_options` 里。`contract/get@v1` 才给得出
  134. * 全量条目(含止期),据此拼出「原合同」候选:下拉回显、条目可选、档位按条目收窄都靠它。
  135. */
  136. const originalContract = useLoad(
  137. () => (updown && originalContractId ? contractGet({ contract_id: originalContractId }) : Promise.resolve(null)),
  138. [updown, originalContractId],
  139. );
  140. const candidates = rowsOf(contracts.data);
  141. /**
  142. * 「原合同」的带入条目:候选口把**已被订阅引用的条目**也剔了(§5.2「尚未有订阅的条目」),
  143. * 而升降配的源头条目恰恰全部被引用 ⇒ 只看候选,原合同会显示成「没有服务构成条目」。
  144. * 这里按 `contract/get@v1` 的明细补齐全部条目;明细未到/查不到原条目时用订阅行兜底,
  145. * ⛔ 让下拉空着冒充「未选」。
  146. */
  147. const originalItems: OrderContractItemOption[] = (() => {
  148. if (!updown || !existing || !originalContractId) return [];
  149. const detail = originalContract.data;
  150. const items: OrderContractItemOption[] = rowsOf(detail?.service_items).flatMap((entry) => entry.item_id ? [{
  151. item_id: entry.item_id,
  152. plan_id: entry.plan_id ?? null,
  153. plan_name: entry.plan_name ?? null,
  154. item_family: entry.item_family ?? null,
  155. quantity: entry.quantity ?? null,
  156. annual_price_cents: entry.sub_account_quota ?? null,
  157. line_exits: entry.line_exits ?? null,
  158. available: true,
  159. }] : []);
  160. if (originalItemId && !items.some((entry) => entry.item_id === originalItemId)) {
  161. items.unshift({
  162. item_id: originalItemId,
  163. plan_id: existing.planId || null,
  164. plan_name: existing.planName ?? null,
  165. item_family: existing.row.plan_family ?? null,
  166. quantity: existing.row.quantity ?? 1,
  167. annual_price_cents: null,
  168. line_exits: existing.exits ?? null,
  169. available: true,
  170. });
  171. }
  172. return items;
  173. })();
  174. /** 原合同的候选形状与标签:标签点名「原合同」,免得不带标识地混在可签新合同里。 */
  175. const originalOption: OrderContractOption | null = (() => {
  176. if (!updown || !existing || !originalContractId) return null;
  177. const detail = originalContract.data;
  178. const internalNo = detail?.contract_no ?? existing.contractNo ?? originalContractId;
  179. const externalNo = detail?.external_no ?? null;
  180. const baseLabel = detail ? `${internalNo}${externalNo ? `(外部单号 ${externalNo})` : ""}` : existing.contractNo ?? originalContractId;
  181. return {
  182. contract_id: originalContractId,
  183. contract_no: externalNo ?? existing.contractNo ?? originalContractId,
  184. internal_no: internalNo,
  185. external_no: externalNo,
  186. option_label: `${baseLabel} · 原合同`,
  187. start_date: detail?.start_date ?? null,
  188. end_date: detail?.end_date ?? null,
  189. items: originalItems,
  190. };
  191. })();
  192. /**
  193. * 合同下拉=服务端候选 ∪ 原合同(同一份合同⛔ 出现两遍):
  194. * 原合同被「已开通」剔出候选 ⇒ 补在最前;仍在候选里 ⇒ 只换标签并补齐条目。
  195. */
  196. const contractList: OrderContractOption[] = (() => {
  197. if (!originalOption) return candidates;
  198. const hit = candidates.find((item: OrderContractOption) => item.contract_id === originalOption.contract_id);
  199. if (!hit) return [originalOption, ...candidates];
  200. const merged = [...originalOption.items, ...rowsOf(hit.items).filter((entry) => !originalOption.items.some((mine) => mine.item_id === entry.item_id))];
  201. return candidates.map((item: OrderContractOption) => item.contract_id === originalOption.contract_id
  202. ? { ...item, option_label: originalOption.option_label, end_date: item.end_date ?? originalOption.end_date, items: merged }
  203. : item);
  204. })();
  205. const contractItems = rowsOf(contractList.find((item: OrderContractOption) => item.contract_id === contractId)?.items);
  206. /**
  207. * 候选空态(D-68):后端把「已开通」与**已到期**合同一并剔出候选,候选为空时回 200+`empty_state`
  208. * +契约空态句 ⇒ 下拉渲染该句(TC-CU-50 步骤1),⛔ 留一句「请选择该客户的可选合同」冒充还有得选。
  209. */
  210. const contractEmpty = contracts.loading || contractList.length ? null : contracts.data?.empty_text || CONTRACT_OPTIONS_EMPTY;
  211. /**
  212. * 写口锁定面(D-69):编辑/详情态后端白名单只有 `trial_months`/`discount_monthly_cents`,
  213. * 其余键(`term`/`start_date`/`plan_id`/`contract_id`…)逐键 `11103`/`60222` 拒收 ⇒
  214. * 页面在**输入侧**就锁死,⛔ 给出可改错觉(改套餐走升降配,改价另签新合同后新建订阅)。
  215. */
  216. const editing = context.mode === "edit";
  217. const locked = editing || context.mode === "view";
  218. const selectedContract = contractList.find((item: OrderContractOption) => item.contract_id === contractId);
  219. const selectedItem = contractItems.find((entry) => entry.item_id === itemId);
  220. /**
  221. * 套餐候选随合同条目收窄(O-15;新建态与升降配态同规则)。
  222. *
  223. * 后端把「条目档位 ≠ 所选套餐」当业务错拒(实测 `60221`:`条目 CI-0001-1 关联档位 P-002,
  224. * 与所选档位 P-008 不匹配`)⇒ 在**输入侧**收窄:条目钉死档位只列该档;未选条目只列该合同
  225. * 未订阅条目涉及的档位;还没选合同 ⇒ 不列候选。条目未钉档位(`plan_id` 与 `plan_id_derived`
  226. * 都空)时不下约束,避免走投无路。
  227. * 升降配态后端按**新合同**反查条目(P5-D1 修正后:载荷可另选新合同),而同屏可选套餐若仍列全目录,
  228. * 用户就会选到合同里根本没有的档位,提交必吃 `KLT-M228`(P5-D2)⇒ 与新建态同规则收窄。
  229. */
  230. const contractPlanIds = new Set(contractItems.map((entry) => entry.plan_id ?? "").filter(Boolean));
  231. const itemPlanId =
  232. context.mode === "new" || context.mode === "updown"
  233. ? selectedItem?.plan_id ?? null
  234. : null;
  235. const planChoices = rowsOf(plans.data).filter((item: OrderPlanOption) => {
  236. if (context.mode !== "new" && context.mode !== "updown") return true;
  237. if (itemPlanId) return item.plan_id === itemPlanId;
  238. if (!contractId || !contractPlanIds.size) return true;
  239. return contractPlanIds.has(item.plan_id);
  240. });
  241. /**
  242. * 升降配的「变更目标」清单(业主要求:原套餐锁死、只挑新套餐)。
  243. *
  244. * 可替换的组合只有一种来源——**合同的服务构成条目**:后端 `change` 按条目反查档位并强校验
  245. * 「条目关联档位 = 所选档位」,所以能换到哪个套餐完全由条目决定,不能直接列全目录。
  246. * 这里把 `contractList`(原合同已并入,条目按 `contract/get` 全量补齐)里每个条目的档位摊平,
  247. * 选一次即同时定下 `contract_id`/`contract_item_id`/`plan_id`——用户只需认套餐名,
  248. * ⛔ 逼他先理解「合同 → 条目 → 档位」三层再自己配对。
  249. * 与原订阅同合同/同条目/同档位的组合标成「当前订阅」并禁用:那不是升降配,是原样重开。
  250. */
  251. const updownTargets = (() => {
  252. if (!updown || !existing) return [] as UpdownTarget[];
  253. const catalog = new Map(rowsOf(plans.data).map((item: OrderPlanOption) => [item.plan_id, item]));
  254. const seen = new Set<string>();
  255. const out: UpdownTarget[] = [];
  256. for (const contract of contractList) {
  257. for (const entry of rowsOf(contract.items)) {
  258. const pid = entry.plan_id ?? "";
  259. if (!pid) continue;
  260. const key = `${contract.contract_id}::${entry.item_id}::${pid}`;
  261. if (seen.has(key)) continue;
  262. seen.add(key);
  263. const price = catalog.get(pid);
  264. /* 目录里明确不可订阅的档位(停用/越权)后端必拒,先在下拉里置灰。 */
  265. if (price && price.available === false) continue;
  266. out.push({
  267. key,
  268. contractId: contract.contract_id,
  269. contractLabel: contract.contract_no ?? contract.internal_no ?? contract.contract_id,
  270. contractInternal: contract.internal_no ?? null,
  271. sameContract: contract.contract_id === originalContractId,
  272. itemId: entry.item_id,
  273. planId: pid,
  274. planName: price?.plan_name ?? entry.plan_name ?? pid,
  275. annualCents: price?.annual_price_cents ?? entry.annual_price_cents ?? null,
  276. settleCents: price?.monthly_settle_cents ?? null,
  277. quota: price?.sub_account_quota ?? null,
  278. exits: entry.line_exits ?? price?.line_exits ?? null,
  279. sameAsOriginal:
  280. contract.contract_id === originalContractId && entry.item_id === originalItemId && pid === existing.planId,
  281. });
  282. }
  283. }
  284. return out;
  285. })();
  286. const pickedTarget = updownTargets.find((item) => item.key === targetKey) ?? null;
  287. /** 是否存在「换得动」的目标:只剩当前订阅那一项时,等于这条订阅没有可替换的档位。 */
  288. const updownHasNew = updownTargets.some((item) => !item.sameAsOriginal);
  289. /** 选中新套餐后把三键(合同/条目/档位)一起落到提交状态上,表单其余只读格才跟着变。 */
  290. function pickTarget(next: string) {
  291. setTargetKey(next);
  292. const found = updownTargets.find((item) => item.key === next);
  293. setContractId(found?.contractId ?? "");
  294. setItemId(found?.itemId ?? "");
  295. setPlanId(found?.planId ?? "");
  296. setError("");
  297. }
  298. /** 升降幅度:只拿年订阅价格比,⛔ 拿月结算比(口径不同,比出来没意义)。 */
  299. const updownDelta = (() => {
  300. if (!pickedTarget) return null;
  301. const before = existing?.row.annual_price_cents ?? null;
  302. const after = pickedTarget.annualCents;
  303. if (before === null || after === null) return { tone: "flat" as const, text: "金额缺少一侧下发,不做涨跌判定" };
  304. const diff = after - before;
  305. if (diff === 0) return { tone: "flat" as const, text: "年订阅价格不变" };
  306. return {
  307. tone: diff > 0 ? "up" as const : "down" as const,
  308. text: `${diff > 0 ? "升配" : "降配"} ${diff > 0 ? "+" : "−"}${moneyCell(Math.abs(diff)).text}/年`,
  309. };
  310. })();
  311. /**
  312. * 当前值不在候选内(编辑态合同已开通/条目已订阅,升降配态原条目不在新合同里)
  313. * ⇒ 补一条回显选项,⛔ 让下拉空着冒充「未选」(O-16)。升降配的原合同已并入 `contractList`,
  314. * 正常情况下三项都选得中,这层兜底只为脏引用/明细未到时不留空白。
  315. */
  316. const contractInOptions = contractList.some((item: OrderContractOption) => item.contract_id === contractId);
  317. const itemInOptions = contractItems.some((entry) => entry.item_id === itemId);
  318. const planInOptions = planChoices.some((item: OrderPlanOption) => item.plan_id === planId);
  319. /** 可写性只取服务端结论:新建/升降配始终可提交,编辑要求后端下发 `editable`。 */
  320. const writable = context.mode === "new" || context.mode === "updown" || (context.mode === "edit" && existing?.editable === true);
  321. const priceOf = planId ? rowsOf(plans.data).find((item: OrderPlanOption) => item.plan_id === planId) : undefined;
  322. /**
  323. * 档位份数随合同条目带入订阅(2026-11-17):一份条目只生一份订阅,份数是订阅自身的「几份」。
  324. * 不可叠加档(用途分类 ≠ 叠加增值)恒 1 —— 界面上也不显示该只读格。
  325. * ⚠️ `contract_options` 历史脏包可能把 quantity 下成字符串;提交前强制收成正整数,
  326. * 避免 create 口 `expected i64`(D-02)。后端出参已改为数值,此处仍做兜底。
  327. */
  328. const itemQuantity = (() => {
  329. if (context.mode !== "new") return 1;
  330. const raw = selectedItem?.quantity;
  331. const n = typeof raw === "number" ? raw : Number(raw);
  332. return Number.isFinite(n) && n > 0 ? Math.trunc(n) : 1;
  333. })();
  334. const stackableItem = (selectedItem?.item_family ?? priceOf?.plan_family ?? null) === "addon";
  335. /** 引导句=三态之外的第四形态:还没选到能带出值的对象,⛔ 判成「取数失败」(D-26/D-29)。 */
  336. const pickHint = context.mode === "updown" ? WORD_PICK_PLAN_FIRST : contractId ? WORD_PICK_CONTRACT_ITEM_FIRST : WORD_PICK_CONTRACT_FIRST;
  337. /** 线路出口优先取**合同条目**(`plan_options` 对固定档回 `line_exits:null`,条目上才是真值)。 */
  338. const exitsText = (() => {
  339. const ofRow = (exits: string[] | null | undefined) =>
  340. (exits === undefined ? WORD_FETCH_FAILED : exits === null || !exits.length ? WORD_UNCONFIGURED : exits.join("、"));
  341. if (locked) return ofRow(existing?.exits);
  342. const fromItem = selectedItem?.line_exits;
  343. const fromPrice = priceOf?.line_exits;
  344. if (!planId && !selectedItem) return pickHint;
  345. if (fromItem && fromItem.length) return ofRow(fromItem);
  346. if (fromPrice && fromPrice.length) return ofRow(fromPrice);
  347. /**
  348. * 升降配沿用原合同且固定档在 `plan_options` 回 `line_exits:null` ⇒ 两处都取不到时,
  349. * 用原订阅行上服务端当初写入的出口(它才是这条合同条目真正冻过的值)。
  350. */
  351. if (updown && contractId === originalContractId && existing?.exits?.length) return ofRow(existing.exits);
  352. return ofRow(fromPrice);
  353. })();
  354. /** 订阅方式只读格=服务端 `sub_mode` 的三态结论;`null`(派生档未预置用途分类)⇒ 诚实占位(D-31)。 */
  355. const modeText = (() => {
  356. /** I6 已停用(D-15):订阅方式不再由交付形态派生,新订阅该列恒为空。 */
  357. const pending = "订阅方式不再派生(I6 已停用,新订阅不写该值)";
  358. if (!locked) return planId ? pending : pickHint;
  359. if (existing?.modeLabel) return existing.modeLabel;
  360. return existing?.row.sub_mode === undefined ? WORD_FETCH_FAILED : WORD_MODE_PENDING;
  361. })();
  362. /** D-72:结束日只读格此前恒显提示语,填了生效日也不预览(服务端实会派生)。 */
  363. const endText = (() => {
  364. if (context.mode === "edit" || context.mode === "view") return existing?.end ?? WORD_UNCONFIGURED;
  365. const chosen = contractList.find((item: OrderContractOption) => item.contract_id === contractId);
  366. const preview = previewEnd(startDate, term, chosen?.end_date ?? null);
  367. return preview ?? ORDER_END_DATE_READONLY;
  368. })();
  369. /** 分账号额度:随**所选档位**带出(升降配的对比走「变更后」卡片,⛔ 在这里拼原值)。 */
  370. const quotaText = (() => {
  371. if (locked) { const v = existing?.quotaSlots; return v === undefined ? WORD_FETCH_FAILED : v === null ? WORD_UNCONFIGURED : String(v); }
  372. if (!planId) return pickHint;
  373. const v = priceOf?.sub_account_quota ?? pickedTarget?.quota;
  374. if (v === undefined || v === null) return WORD_UNCONFIGURED;
  375. return String(v);
  376. })();
  377. const annualText = (() => {
  378. if (locked) return textOf(existing?.annual.text);
  379. if (!planId) return pickHint;
  380. return priceOf?.annual_price_cents === undefined || priceOf.annual_price_cents === null ? WORD_UNCONFIGURED : moneyCell(priceOf.annual_price_cents).text;
  381. })();
  382. const settleText = (() => {
  383. if (locked) return `${textOf(existing?.settle.text)} / 月`;
  384. if (!planId) return pickHint;
  385. return priceOf?.monthly_settle_cents === undefined || priceOf.monthly_settle_cents === null ? WORD_UNCONFIGURED : `${moneyCell(priceOf.monthly_settle_cents).text} / 月`;
  386. })();
  387. /** 订单号随合同外部单号冻结:选定合同后把将要冻结的单号显出来,⛔ 只留一句空话(D-40 族)。 */
  388. const externalNo = selectedContract?.contract_no ?? (contractId && !contractInOptions ? existing?.contractNo ?? "" : "");
  389. const orderText = locked ? textOf(existing?.orderNo, "无运营商订单号") : `由服务端按合同外部单号冻结${externalNo ? `:${externalNo}` : ""}`;
  390. /**
  391. * 「一项没改」判定:合同/条目/档位/时长/生效日全等于原订阅 ⇒ 提交只会把原订阅截断、
  392. * 再生成一份同档位的重复订阅,这不是升降配。升降配的候选里已把「原订阅」那一项禁用,
  393. * 这里只兜脏数据(例如原条目既没条目明细也推不出档位)。
  394. */
  395. const unchanged = updown && existing !== undefined
  396. && contractId === originalContractId
  397. && itemId === originalItemId
  398. && planId === existing.planId
  399. && term === (existing.row.term ?? "yearly")
  400. && startDate === defaultStart;
  401. async function submit(event: FormEvent<HTMLFormElement>) {
  402. event.preventDefault();
  403. if (updown && !pickedTarget) { setError("请先选择要变更到的新套餐(原套餐已锁定,不在可选范围内)。"); return; }
  404. if (!editing && !contractId) { setError("请选择合同编号:订阅必须引用该客户已登记且未开通的合同"); return; }
  405. if (!editing && (!itemId || !planId || !startDate)) { setError("请选择合同服务构成条目、套餐并填写生效日。"); return; }
  406. if (context.mode === "updown" && !existing) return setError("缺少被替换的原订阅。");
  407. if (unchanged) return setError("所选组合就是原订阅本身:请换一个档位,或另选替换合同/条目(只改时长/生效日也算重开原档)。");
  408. setPending(true);
  409. setError("");
  410. try {
  411. if (context.mode === "edit" && existing) {
  412. const discount = trialMonths === "0" || !trialDiscount.trim() ? undefined : yuanToCents(trialDiscount);
  413. if (trialMonths !== "0" && trialDiscount.trim() && discount === null) { setError("试用优惠金额须为非负金额,最多两位小数。"); setPending(false); return; }
  414. await orderUpdate({
  415. subscription_id: existing.no,
  416. row_version: Number(existing.rowVersion),
  417. trial_months: Number(trialMonths),
  418. ...(discount === undefined ? {} : { discount_monthly_cents: discount }),
  419. });
  420. onSaved("订阅已更新(仅试用与优惠白名单字段可写)。");
  421. } else if (context.mode === "updown" && existing) {
  422. await orderChange({
  423. replaces_subscription_id: existing.no,
  424. customer_id: customerId,
  425. plan_id: planId,
  426. contract_id: contractId,
  427. contract_item_id: itemId,
  428. term,
  429. start_date: startDate,
  430. ...(trialMonths === "0" ? {} : { trial_months: Number(trialMonths) }),
  431. });
  432. onSaved("已创建替换订阅(升降配),原订阅保留为历史记录。");
  433. } else {
  434. const created = await orderCreate({
  435. customer_id: customerId,
  436. plan_id: planId,
  437. contract_id: contractId,
  438. contract_item_id: itemId,
  439. term,
  440. start_date: startDate,
  441. quantity: itemQuantity,
  442. ...(trialMonths === "0" ? {} : { trial_months: Number(trialMonths) }),
  443. });
  444. onSaved(`订阅已创建(${created.subscription_id}),等待网络开通回填。`);
  445. }
  446. } catch (cause) {
  447. setError((cause as Error).message);
  448. } finally {
  449. setPending(false);
  450. }
  451. }
  452. const title = context.mode === "new" ? "新增订阅" : context.mode === "updown" ? `升降配 · ${existing?.planName ?? WORD_FETCH_FAILED}` : context.mode === "edit" ? `编辑订阅 · ${existing?.no}` : `订阅详情 · ${existing?.no}`;
  453. return <Dialog title={title} onClose={onClose}>
  454. <form className="customer-sub-form" onSubmit={submit}>
  455. <p className="customer-sub-context">{customerName} · {customerId}{updown && <span>替换 {existing?.no}:原合同、条目、套餐已锁定(左侧),只需在右侧挑一个「新套餐」;提交后原订阅的有效期截到新订阅生效前一天。</span>}</p>
  456. {contracts.error && <div className="customer-sub-alert" role="alert">可选合同取数失败:{contracts.error.message}</div>}
  457. {originalContract.error && <div className="customer-sub-alert" role="alert">原合同明细取数失败:{originalContract.error.message}(服务构成条目暂按原订阅当前条目回显)</div>}
  458. {plans.error && <div className="customer-sub-alert" role="alert">可选套餐取数失败:{plans.error.message}</div>}
  459. {!writable && <div className="customer-sub-alert">{context.mode === "view" ? "详情为只读。需要变更时请新建订阅或办理升降配。" : existing?.editable === undefined ? "写口可见性未随记录下发,按只读呈现。" : "服务端判定本条只读(已到期或已开通计费)。需要变更时请新建订阅。"}</div>}
  460. {/*
  461. 升降配的分栏(业主 2026-11-16):左「原订阅」只读、右「变更后」只有一个新套餐下拉。
  462. 原套餐此前也画成可选下拉,看着像「在改原订阅」,套餐切换反而看不出来 ⇒ 改成左侧锁定卡。
  463. 合同与条目不再单独暴露:它们由所选新套餐反推(后端按条目反查档位并强校验匹配)。
  464. */}
  465. {updown ? <div className="order-change">
  466. <section className="order-change-card is-locked" aria-label="原订阅(只读)">
  467. <header><h3>原订阅</h3><span>已锁定 · 不可修改</span></header>
  468. <dl className="order-change-grid">
  469. <div><dt>订单号</dt><dd>{textOf(existing?.no, WORD_UNCONFIGURED)}</dd></div>
  470. <div><dt>套餐</dt><dd>{textOf(existing?.planName)}</dd></div>
  471. <div><dt>合同编号</dt><dd>{contractText(existing?.contractNo, originalContract.data?.contract_no)}</dd></div>
  472. <div><dt>服务构成条目</dt><dd>{textOf(existing?.contractItemId)}</dd></div>
  473. <div><dt>订阅时长</dt><dd>{textOf(existing?.termLabel)}</dd></div>
  474. <div><dt>期间</dt><dd>{textOf(existing?.start)} 至 {textOf(existing?.end)}</dd></div>
  475. <div><dt>订阅价格</dt><dd>{textOf(existing?.annual.text)}</dd></div>
  476. <div><dt>月结算标准</dt><dd>{textOf(existing?.settle.text)} / 月</dd></div>
  477. <div><dt>分账号额度</dt><dd>{existing?.quotaSlots === undefined ? WORD_FETCH_FAILED : existing.quotaSlots === null ? WORD_UNCONFIGURED : `${existing.quotaSlots} 个`}</dd></div>
  478. </dl>
  479. </section>
  480. <div className="order-change-pivot" aria-hidden="true"><ArrowRight size={18} /><span>变更为</span></div>
  481. <section className="order-change-card is-target" aria-label="变更后">
  482. <header><h3>变更后</h3><span>{pickedTarget ? "请核对带出的值" : "挑一个要变更到的套餐"}</span></header>
  483. <label className="order-change-pick"><span>新套餐 <b>*</b></span>
  484. <select value={targetKey} onChange={(event) => pickTarget(event.target.value)} disabled={!updownTargets.length} aria-label="选择要变更到的新套餐">
  485. <option value="">{contracts.loading || plans.loading ? "正在读取可替换套餐…" : updownTargets.length ? "请选择新套餐" : "没有可替换的新套餐"}</option>
  486. {updownTargets.map((item) => <option key={item.key} value={item.key} disabled={item.sameAsOriginal}>{item.planName}{item.annualCents === null ? "" : ` · ${moneyCell(item.annualCents).text}/年`} · 合同 {contractText(item.contractLabel, item.contractInternal)}{item.sameContract ? "(原合同)" : ""}{item.sameAsOriginal ? "(当前订阅,不可选)" : ""}</option>)}
  487. </select>
  488. </label>
  489. {pickedTarget ? <dl className="order-change-grid">
  490. <div><dt>变更后套餐</dt><dd>{pickedTarget.planName}</dd></div>
  491. <div><dt>替换合同</dt><dd>{contractText(pickedTarget.contractLabel, pickedTarget.contractInternal)}{pickedTarget.sameContract ? "(原合同)" : ""}</dd></div>
  492. <div><dt>服务构成条目</dt><dd>{pickedTarget.itemId}</dd></div>
  493. <div><dt>订阅价格</dt><dd>{pickedTarget.annualCents === null ? WORD_UNCONFIGURED : moneyCell(pickedTarget.annualCents).text}</dd></div>
  494. <div><dt>月结算标准</dt><dd>{pickedTarget.settleCents === null ? WORD_UNCONFIGURED : `${moneyCell(pickedTarget.settleCents).text} / 月`}</dd></div>
  495. <div><dt>分账号额度</dt><dd>{pickedTarget.quota === null ? WORD_UNCONFIGURED : `${pickedTarget.quota} 个`}</dd></div>
  496. <div><dt>线路出口</dt><dd>{pickedTarget.exits?.length ? pickedTarget.exits.join("、") : WORD_UNCONFIGURED}</dd></div>
  497. </dl> : <p className="order-change-note">原套餐与合同条目已锁定;选一个新套餐后,替换合同、条目、订阅价格、月结算与额度会随它带出。</p>}
  498. {updownDelta && <div className="order-change-delta"><span className={`order-change-badge is-${updownDelta.tone}`}>{updownDelta.text}</span><span className="order-change-note">按年订阅价格对比</span></div>}
  499. {!updownHasNew && !contracts.loading && !plans.loading && <p className="order-change-note is-warn">当前没有可替换的新套餐:原合同 {textOf(existing?.contractNo, originalContractId)} 下没有第二条已绑定档位的服务构成条目,该客户名下也没有其他可选合同。换档需先在第 1 步签一份带新条目的合同,再回到「升降配」。</p>}
  500. </section>
  501. </div> : <div className="customer-sub-fields">
  502. <label><span>合同编号 <b>*</b></span><select disabled={locked} value={contractId} onChange={(event) => { const next = event.target.value; setContractId(next); setItemId(""); if (!locked) setPlanId(""); setError(""); }}><option value="">{contracts.loading ? "正在读取可选合同…" : contractEmpty ?? "请选择该客户的可选合同"}</option>{contractId && !contractInOptions && <option value={contractId}>{textOf(existing?.contractNo, contractId)}</option>}{contractList.map((item: OrderContractOption) => <option key={item.contract_id} value={item.contract_id}>{item.option_label ?? `${item.contract_no}${item.internal_no && item.internal_no !== item.contract_no ? ` / ${item.internal_no}` : ""}`}</option>)}</select></label>
  503. <label><span>合同服务构成条目 <b>*</b></span><select disabled={locked || !contractId} value={itemId} onChange={(event) => { const next = event.target.value; setItemId(next); const bound = contractItems.find((entry) => entry.item_id === next)?.plan_id ?? ""; setPlanId(bound); setError(""); }}><option value="">{contractId ? "请选择服务构成条目" : WORD_UNCONFIGURED}</option>{itemId && !itemInOptions && <option value={itemId}>{textOf(existing?.planName, itemId)}</option>}{contractItems.map((item) => <option key={item.item_id} value={item.item_id}>{item.plan_name ?? item.item_family ?? item.item_id}{item.quantity ? ` × ${item.quantity}` : ""}</option>)}</select></label>
  504. <label><span>套餐 <b>*</b></span><select disabled={locked} value={planId} onChange={(event) => { setPlanId(event.target.value); setError(""); }}><option value="">{plans.loading ? "正在读取可选套餐…" : context.mode === "new" && !contractId ? "请先选择合同(候选按该合同未订阅条目收窄)" : "请选择套餐"}</option>{planId && !planInOptions && <option value={planId}>{textOf(existing?.planName, planId)}</option>}{planChoices.map((item: OrderPlanOption) => <option key={item.plan_id} value={item.plan_id} disabled={item.available === false}>{item.plan_name}{item.available === false ? ` · ${item.unavailable_reason ?? "不可订阅"}` : ""}</option>)}</select></label>
  505. </div>}
  506. <div className="customer-sub-fields">
  507. {!updown && <label>线路出口(随合同条目)<input readOnly value={exitsText} /></label>}
  508. {!updown && <label>订阅方式<FieldHint label="订阅方式说明">订阅方式不再随交付形态派生(I6 已停用)。</FieldHint><input readOnly value={modeText} /></label>}
  509. {context.mode === "edit" ? <label><span>订阅时长</span><input readOnly value={existing?.termLabel || WORD_UNCONFIGURED} /></label>
  510. : <label><span>订阅时长 <b>*</b></span><select disabled={locked} value={term} onChange={(event) => setTerm(event.target.value)}>{OPTIONS.term.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</select></label>}
  511. <label><span>生效日 <b>*</b></span><input disabled={locked} type="date" value={startDate} onChange={(event) => setStartDate(event.target.value)} /></label>
  512. <label><span>结束日(服务端派生)</span><FieldHint label="结束日说明">预览=生效日折订阅时长(月末夹紧)再减一天,晚于合同止期则截到合同止期;落库值以服务端为准。</FieldHint><input readOnly value={updown && !pickedTarget ? "选定新套餐后按替换合同止期派生" : endText} /></label>
  513. <label>订单号(随合同外部单号)<input readOnly value={orderText} /></label>
  514. {!updown && <label>订阅价格<FieldHint label="订阅价格说明">{ORDER_AMOUNT_TITLE}</FieldHint><input readOnly value={annualText} /></label>}
  515. {!updown && <label>月结算标准<FieldHint label="月结算标准说明">{ORDER_AMOUNT_TITLE}</FieldHint><input readOnly value={settleText} /></label>}
  516. {!updown && <label>分账号额度<FieldHint label="分账号额度说明">随所选档位的额度带出。</FieldHint><input readOnly value={quotaText} /></label>}
  517. {!updown && stackableItem && <label>档位数量(随合同条目)<FieldHint label="档位数量说明">可叠加档按份计价(例如单独境外 IP 按个);保存时带入订阅 subscription.quantity。</FieldHint><input readOnly value={itemQuantity} /></label>}
  518. <label>试用优惠期<select disabled={!writable} value={trialMonths} onChange={(event) => setTrialMonths(event.target.value as "0" | "1" | "2")}><option value="0">不试用</option><option value="1">1 个月</option><option value="2">2 个月</option></select></label>
  519. {trialMonths !== "0" && <label>试用优惠金额(元/月)<input readOnly={!writable} inputMode="decimal" placeholder="选填,留空不套用正式月费" value={trialDiscount} onChange={(event) => setTrialDiscount(event.target.value)} /></label>}
  520. <label>实际开通日<input readOnly value={locked ? (existing?.openedOn === undefined ? WORD_FETCH_FAILED : existing.openedOn || WORD_NOT_OPENED) : WORD_NOT_OPENED} /></label>
  521. </div>
  522. <p className="customer-sub-hint">{editing ? "编辑态只有「试用优惠期」与「试用优惠金额」两项可改,其余由服务端冻结:换套餐请走「升降配」替换,改价须另签新合同后新建订阅。" : updown ? "升降配只变更「套餐」这一项:原订阅的合同、条目、档位不可改,替换用的合同与条目随新套餐带出。原订阅在新订阅生效前一天结束,历史保留。" : `${ORDER_CREATE_READONLY_NOTE}(${ORDER_AMOUNT_TITLE})。合同期间、订单号与线路出口随合同条目带出,网络开通由运维流程回填。`}</p>
  523. {error && <p className="ops-form-error" role="alert">{error}</p>}
  524. <footer><Button type="button" variant="outline" onClick={onClose}>{writable ? "取消" : "关闭"}</Button>{writable && <Button type="submit" disabled={pending || (!editing && (!contractId || !itemId || !planId || !startDate))}>{context.mode === "edit" ? "保存订阅" : context.mode === "updown" ? "创建替换订阅" : "创建订阅"}</Button>}</footer>
  525. </form>
  526. </Dialog>;
  527. }
  528. /* D-03:原 StackEditor(就地改 end_date → stack@v1)已下线;叠加改走 OrderEditor mode=new → create@v1。 */