OrderChangeDialogs.tsx 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. /**
  2. * 订阅办理弹窗:新建走 `create`、升降配走 `change`、编辑只放开白名单字段走 `update`、叠加走 `stack`。
  3. *
  4. * 价格、月标准、结束日、实际开通日、线路出口、订单号六项只读,由服务端按套餐配置与合同条目带出;
  5. * ⛔ 在此提交或改写它们(出现即 `11103`)。
  6. *
  7. * 三个入口共用同一份弹窗:客户档案「套餐订阅管理」行内、客户档案「04 全部订阅」行内、订阅详情页头,
  8. * 判据与载荷只写一次,⛔ 各页各写一份抽屉造成口径漂移。
  9. * ⚠️ 菜单「全部订阅」(路由 `/orders`)按需求 5.2 只读,⛔ 挂本弹窗的写入口。
  10. * 升降配只改「套餐」这一项:原订阅的合同/条目/档位在左侧只读锁定,右侧只列**可替换的新套餐**
  11. * (来源=各替换合同条目的绑定档位),选一次即带出合同/条目/档位三键(业主 2026-11-16 定案)。
  12. */
  13. import { useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";
  14. import { ArrowRight, X } from "lucide-react";
  15. import { Button } from "./ui/button";
  16. import { OPTIONS, ORDER_MODE, label } from "../lib/api/labels";
  17. import {
  18. CONTRACT_OPTIONS_EMPTY, ORDER_AMOUNT_TITLE, ORDER_CREATE_READONLY_NOTE, ORDER_END_DATE_READONLY,
  19. ORDER_MODE_BY_CATEGORY, WORD_FETCH_FAILED, WORD_MODE_PENDING, WORD_NOT_OPENED, WORD_PICK_CONTRACT_FIRST,
  20. WORD_PICK_CONTRACT_ITEM_FIRST, WORD_PICK_PLAN_FIRST, WORD_UNCONFIGURED,
  21. } from "../lib/api/lockedCopy";
  22. import { moneyCell, yuanToCents } from "../lib/package-catalog";
  23. import { rowsOf, orderChange, orderContractOptions, orderCreate, orderPlanOptions, orderStack, orderUpdate, contractGet } from "../lib/api/bos";
  24. import type { OrderContractItemOption, OrderContractOption, OrderPlanOption } from "../lib/api/types";
  25. import { useLoad } from "../lib/useLoad";
  26. import type { OrderView } from "../lib/order-demo";
  27. export type OrderEditorMode = "new" | "edit" | "view" | "updown";
  28. export type OrderEditorContext = { mode: OrderEditorMode; record?: OrderView };
  29. /** 升降配的变更目标:替换合同+服务构成条目+新档位,三者由后端强校验必须自洽。 */
  30. type UpdownTarget = {
  31. key: string;
  32. contractId: string;
  33. /** 合同**外部单号**:台账、订阅详情都按这个口径显示,⛔ 这里改用内部号造成两处对不上。 */
  34. contractLabel: string;
  35. /** 真合同号:外部单号可重复(实测两份合同同叫 WB-P3-20261115-01),两号并显才分得清(D-33)。 */
  36. contractInternal: string | null;
  37. sameContract: boolean;
  38. itemId: string;
  39. planId: string;
  40. planName: string;
  41. annualCents: number | null;
  42. settleCents: number | null;
  43. quota: number | null;
  44. exits: string[] | null;
  45. sameAsOriginal: boolean;
  46. };
  47. /**
  48. * 结束日预览(D-72)=`/subscription/create@v1` 里 `derive_period` 的同口径前端镜像:
  49. * 生效日折 N 个月(当月不足 N 月时夹到月末)得「下一周期生效日」⇒ 再减一天;
  50. * 结果晚于合同止期 ⇒ 截到合同止期。⚠️ 只是**预览**,落库值一律以服务端为准。
  51. */
  52. function previewEnd(start: string, term: string, contractEnd: string | null): string | null {
  53. if (!/^\d{4}-\d{2}-\d{2}$/.test(start)) return null;
  54. const months = term === "quarterly" ? 3 : term === "monthly" ? 1 : 12;
  55. const [y, m, d] = start.split("-").map(Number);
  56. const anchor = new Date(Date.UTC(y, m - 1 + months, 1));
  57. const last = new Date(Date.UTC(anchor.getUTCFullYear(), anchor.getUTCMonth() + 1, 0)).getUTCDate();
  58. anchor.setUTCDate(Math.min(d, last));
  59. anchor.setUTCDate(anchor.getUTCDate() - 1);
  60. const iso = anchor.toISOString().slice(0, 10);
  61. return contractEnd && contractEnd < iso ? contractEnd : iso;
  62. }
  63. /** 只读输入框只能用字符串:三态在这里落到锁定文案,⛔ 用「—」或 0 冒充。 */
  64. const textOf = (value: string | null | undefined, missing: string = WORD_UNCONFIGURED) =>
  65. (value === undefined ? WORD_FETCH_FAILED : value === null || value === "" ? missing : value);
  66. /**
  67. * 合同两号并显:`contract_no` 是外部单号,**可以重复**(实测两份合同同叫 WB-P3-20261115-01),
  68. * 内部号才唯一 ⇒ 只显示一个就会把「原合同」和另一份合同认成同一份(D-33)。
  69. */
  70. const contractText = (external: string | null | undefined, internal: string | null | undefined) => {
  71. const ext = external ?? "";
  72. if (!internal || internal === ext) return ext || textOf(external);
  73. return ext ? `${ext} / ${internal}` : internal;
  74. };
  75. /** 本地「今天」:`toISOString()` 是 UTC,跨时区会把默认生效日推到前一天/后一天。 */
  76. function todayText(): string {
  77. const now = new Date();
  78. return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
  79. }
  80. function Dialog({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
  81. const ref = useRef<HTMLDialogElement>(null);
  82. useEffect(() => {
  83. const dialog = ref.current;
  84. if (!dialog) return;
  85. const previous = document.activeElement as HTMLElement | null;
  86. dialog.showModal();
  87. return () => { dialog.close(); previous?.focus(); };
  88. }, []);
  89. return <dialog ref={ref} className="customer-sub-dialog" aria-labelledby="customer-sub-dialog-title" onCancel={onClose} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
  90. <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>
  91. {children}
  92. </dialog>;
  93. }
  94. export function OrderEditor({ customerId, customerName, context, onClose, onSaved }: {
  95. customerId: string; customerName: string; context: OrderEditorContext; onClose: () => void; onSaved: (message: string) => void;
  96. }) {
  97. const existing = context.record;
  98. /**
  99. * 升降配带入原订阅的合同/条目/档位/时长(业主 2026-11-16 定案):
  100. * 原订阅的合同/条目/套餐是**被替换的对象**,⛔ 可编辑——它们只作为只读「原订阅」呈现;
  101. * 用户唯一要做的是在「新套餐」里挑一个变更目标(业主 2026-11-16 二次定案:
  102. * 「带入的原套餐还可以改」=说不清在改哪一边,套餐切换也就看不出来)。
  103. * 合同/条目仍由所选新套餐反推(后端按 `contract_item_id` 反查条目并强校验档位匹配)。
  104. */
  105. const updown = context.mode === "updown";
  106. const fresh = context.mode === "new";
  107. const originalContractId = existing?.contractId ?? "";
  108. const originalItemId = existing?.contractItemId ?? "";
  109. const [contractId, setContractId] = useState(fresh || updown ? "" : originalContractId);
  110. const [itemId, setItemId] = useState(fresh || updown ? "" : originalItemId);
  111. const [planId, setPlanId] = useState(fresh || updown ? "" : existing?.planId ?? "");
  112. /** 升降配的「变更目标」=(替换合同, 服务构成条目, 新档位) 三元组;选它一次就带齐三个载荷键。 */
  113. const [targetKey, setTargetKey] = useState("");
  114. const [term, setTerm] = useState(updown ? existing?.row.term ?? "yearly" : "yearly");
  115. /**
  116. * 升降配的生效日默认**当天**(契约 §5.2「开始日默当天」):原订阅的生效日多半已过去,
  117. * 照抄会把替换单做成过去时,截原时「新开始−1 天」早于原开始日 ⇒ 原订阅被压成零天期间。
  118. */
  119. const defaultStart = updown ? todayText() : existing?.start ?? "";
  120. const [startDate, setStartDate] = useState(defaultStart);
  121. const [trialMonths, setTrialMonths] = useState<"0" | "1" | "2">(existing?.trialMonths === 1 || existing?.trialMonths === 2 ? String(existing.trialMonths) as "1" | "2" : "0");
  122. const [trialDiscount, setTrialDiscount] = useState(existing?.trialDiscount ? String(existing.trialDiscount / 100) : "");
  123. const [error, setError] = useState("");
  124. const [pending, setPending] = useState(false);
  125. const contracts = useLoad(() => orderContractOptions({ customer_id: customerId }), [customerId]);
  126. const plans = useLoad(() => orderPlanOptions({ customer_id: customerId }), [customerId]);
  127. /**
  128. * 原合同明细另取:候选口按「合同未开通」+「条目未被订阅引用」双筛,而升降配的源头合同恰恰
  129. * 两条都不满足 ⇒ 原合同及其全部条目都不在 `contract_options` 里。`contract/get@v1` 才给得出
  130. * 全量条目(含止期),据此拼出「原合同」候选:下拉回显、条目可选、档位按条目收窄都靠它。
  131. */
  132. const originalContract = useLoad(
  133. () => (updown && originalContractId ? contractGet({ contract_id: originalContractId }) : Promise.resolve(null)),
  134. [updown, originalContractId],
  135. );
  136. const candidates = rowsOf(contracts.data);
  137. /**
  138. * 「原合同」的带入条目:候选口把**已被订阅引用的条目**也剔了(§5.2「尚未有订阅的条目」),
  139. * 而升降配的源头条目恰恰全部被引用 ⇒ 只看候选,原合同会显示成「没有服务构成条目」。
  140. * 这里按 `contract/get@v1` 的明细补齐全部条目;明细未到/查不到原条目时用订阅行兜底,
  141. * ⛔ 让下拉空着冒充「未选」。
  142. */
  143. const originalItems: OrderContractItemOption[] = (() => {
  144. if (!updown || !existing || !originalContractId) return [];
  145. const detail = originalContract.data;
  146. const items: OrderContractItemOption[] = rowsOf(detail?.service_items).flatMap((entry) => entry.item_id ? [{
  147. item_id: entry.item_id,
  148. item_kind: entry.item_kind ?? "plan_based",
  149. plan_id: entry.plan_id ?? null,
  150. plan_id_derived: entry.derived_plan_id ?? null,
  151. plan_name: entry.plan_name ?? entry.derived_plan_name ?? null,
  152. quantity: entry.quantity ?? null,
  153. annual_price_cents: entry.annual_price_cents ?? null,
  154. line_exits: entry.line_exits ?? null,
  155. use_category: entry.use_category ?? null,
  156. available: true,
  157. }] : []);
  158. if (originalItemId && !items.some((entry) => entry.item_id === originalItemId)) {
  159. items.unshift({
  160. item_id: originalItemId,
  161. item_kind: existing.row.plan_kind === "custom" ? "custom_spec" : "plan_based",
  162. plan_id: existing.planId || null,
  163. plan_id_derived: null,
  164. plan_name: existing.planName ?? null,
  165. quantity: null,
  166. annual_price_cents: null,
  167. line_exits: existing.exits ?? null,
  168. use_category: existing.row.use_category ?? 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 ?? entry.plan_id_derived ?? "").filter(Boolean));
  231. const itemPlanId =
  232. context.mode === "new" || context.mode === "updown"
  233. ? selectedItem?.plan_id ?? selectedItem?.plan_id_derived ?? 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 ?? entry.plan_id_derived ?? "";
  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. */
  326. const itemQuantity = context.mode === "new" ? (selectedItem?.quantity ?? 1) : 1;
  327. const stackableItem = (selectedItem?.use_category ?? priceOf?.use_category ?? null) === "value_add";
  328. /** 引导句=三态之外的第四形态:还没选到能带出值的对象,⛔ 判成「取数失败」(D-26/D-29)。 */
  329. const pickHint = context.mode === "updown" ? WORD_PICK_PLAN_FIRST : contractId ? WORD_PICK_CONTRACT_ITEM_FIRST : WORD_PICK_CONTRACT_FIRST;
  330. /** 线路出口优先取**合同条目**(`plan_options` 对固定档回 `line_exits:null`,条目上才是真值)。 */
  331. const exitsText = (() => {
  332. const ofRow = (exits: string[] | null | undefined) =>
  333. (exits === undefined ? WORD_FETCH_FAILED : exits === null || !exits.length ? WORD_UNCONFIGURED : exits.join("、"));
  334. if (locked) return ofRow(existing?.exits);
  335. const fromItem = selectedItem?.line_exits;
  336. const fromPrice = priceOf?.line_exits;
  337. if (!planId && !selectedItem) return pickHint;
  338. if (fromItem && fromItem.length) return ofRow(fromItem);
  339. if (fromPrice && fromPrice.length) return ofRow(fromPrice);
  340. /**
  341. * 升降配沿用原合同且固定档在 `plan_options` 回 `line_exits:null` ⇒ 两处都取不到时,
  342. * 用原订阅行上服务端当初写入的出口(它才是这条合同条目真正冻过的值)。
  343. */
  344. if (updown && contractId === originalContractId && existing?.exits?.length) return ofRow(existing.exits);
  345. return ofRow(fromPrice);
  346. })();
  347. /** 订阅方式只读格=服务端 `sub_mode` 的三态结论;`null`(派生档未预置用途分类)⇒ 诚实占位(D-31)。 */
  348. const modeText = (() => {
  349. // D-32:已选套餐却判不出订阅方式,根因是**该档位没预置用途分类**,不是「还没选条目」
  350. // ⇒ 文案点名真实缺口,⛔ 用「待选条目后判定」把人支到走不通的路上。
  351. const pending = priceOf && priceOf.use_category === null
  352. ? "用途分类未配置(请先在合同条目或目录档位补齐)"
  353. : WORD_MODE_PENDING;
  354. if (!locked) return planId ? label(ORDER_MODE, priceOf?.sub_mode) || pending : pickHint;
  355. if (existing?.modeLabel) return existing.modeLabel;
  356. return existing?.row.sub_mode === undefined ? WORD_FETCH_FAILED : pending;
  357. })();
  358. /** D-72:结束日只读格此前恒显提示语,填了生效日也不预览(服务端实会派生)。 */
  359. const endText = (() => {
  360. if (context.mode === "edit" || context.mode === "view") return existing?.end ?? WORD_UNCONFIGURED;
  361. const chosen = contractList.find((item: OrderContractOption) => item.contract_id === contractId);
  362. const preview = previewEnd(startDate, term, chosen?.end_date ?? null);
  363. return preview ?? ORDER_END_DATE_READONLY;
  364. })();
  365. /** 分账号额度:随**所选档位**带出(升降配的对比走「变更后」卡片,⛔ 在这里拼原值)。 */
  366. const quotaText = (() => {
  367. if (locked) { const v = existing?.quotaSlots; return v === undefined ? WORD_FETCH_FAILED : v === null ? WORD_UNCONFIGURED : String(v); }
  368. if (!planId) return pickHint;
  369. const v = priceOf?.sub_account_quota ?? pickedTarget?.quota;
  370. if (v === undefined || v === null) return WORD_UNCONFIGURED;
  371. return String(v);
  372. })();
  373. const annualText = (() => {
  374. if (locked) return textOf(existing?.annual.text);
  375. if (!planId) return pickHint;
  376. return priceOf?.annual_price_cents === undefined || priceOf.annual_price_cents === null ? WORD_UNCONFIGURED : moneyCell(priceOf.annual_price_cents).text;
  377. })();
  378. const settleText = (() => {
  379. if (locked) return `${textOf(existing?.settle.text)} / 月`;
  380. if (!planId) return pickHint;
  381. return priceOf?.monthly_settle_cents === undefined || priceOf.monthly_settle_cents === null ? WORD_UNCONFIGURED : `${moneyCell(priceOf.monthly_settle_cents).text} / 月`;
  382. })();
  383. /** 订单号随合同外部单号冻结:选定合同后把将要冻结的单号显出来,⛔ 只留一句空话(D-40 族)。 */
  384. const externalNo = selectedContract?.contract_no ?? (contractId && !contractInOptions ? existing?.contractNo ?? "" : "");
  385. const orderText = locked ? textOf(existing?.orderNo, "无运营商订单号") : `由服务端按合同外部单号冻结${externalNo ? `:${externalNo}` : ""}`;
  386. /**
  387. * 「一项没改」判定:合同/条目/档位/时长/生效日全等于原订阅 ⇒ 提交只会把原订阅截断、
  388. * 再生成一份同档位的重复订阅,这不是升降配。升降配的候选里已把「原订阅」那一项禁用,
  389. * 这里只兜脏数据(例如原条目既没条目明细也推不出档位)。
  390. */
  391. const unchanged = updown && existing !== undefined
  392. && contractId === originalContractId
  393. && itemId === originalItemId
  394. && planId === existing.planId
  395. && term === (existing.row.term ?? "yearly")
  396. && startDate === defaultStart;
  397. async function submit(event: FormEvent<HTMLFormElement>) {
  398. event.preventDefault();
  399. if (updown && !pickedTarget) { setError("请先选择要变更到的新套餐(原套餐已锁定,不在可选范围内)。"); return; }
  400. if (!editing && !contractId) { setError("请选择合同编号:订阅必须引用该客户已登记且未开通的合同"); return; }
  401. if (!editing && (!itemId || !planId || !startDate)) { setError("请选择合同服务构成条目、套餐并填写生效日。"); return; }
  402. if (context.mode === "updown" && !existing) return setError("缺少被替换的原订阅。");
  403. if (unchanged) return setError("所选组合就是原订阅本身:请换一个档位,或另选替换合同/条目(只改时长/生效日也算重开原档)。");
  404. setPending(true);
  405. setError("");
  406. try {
  407. if (context.mode === "edit" && existing) {
  408. const discount = trialMonths === "0" || !trialDiscount.trim() ? undefined : yuanToCents(trialDiscount);
  409. if (trialMonths !== "0" && trialDiscount.trim() && discount === null) { setError("试用优惠金额须为非负金额,最多两位小数。"); setPending(false); return; }
  410. await orderUpdate({
  411. subscription_id: existing.no,
  412. row_version: Number(existing.rowVersion),
  413. trial_months: Number(trialMonths),
  414. ...(discount === undefined ? {} : { discount_monthly_cents: discount }),
  415. });
  416. onSaved("订阅已更新(仅试用与优惠白名单字段可写)。");
  417. } else if (context.mode === "updown" && existing) {
  418. await orderChange({
  419. replaces_subscription_id: existing.no,
  420. customer_id: customerId,
  421. plan_id: planId,
  422. contract_id: contractId,
  423. contract_item_id: itemId,
  424. term,
  425. start_date: startDate,
  426. ...(trialMonths === "0" ? {} : { trial_months: Number(trialMonths) }),
  427. });
  428. onSaved("已创建替换订阅(升降配),原订阅保留为历史记录。");
  429. } else {
  430. const created = await orderCreate({
  431. customer_id: customerId,
  432. plan_id: planId,
  433. contract_id: contractId,
  434. contract_item_id: itemId,
  435. term,
  436. start_date: startDate,
  437. quantity: itemQuantity,
  438. ...(trialMonths === "0" ? {} : { trial_months: Number(trialMonths) }),
  439. });
  440. onSaved(`订阅已创建(${created.subscription_id}),等待网络开通回填。`);
  441. }
  442. } catch (cause) {
  443. setError((cause as Error).message);
  444. } finally {
  445. setPending(false);
  446. }
  447. }
  448. const title = context.mode === "new" ? "新增订阅" : context.mode === "updown" ? `升降配 · ${existing?.planName ?? WORD_FETCH_FAILED}` : context.mode === "edit" ? `编辑订阅 · ${existing?.no}` : `订阅详情 · ${existing?.no}`;
  449. return <Dialog title={title} onClose={onClose}>
  450. <form className="customer-sub-form" onSubmit={submit}>
  451. <p className="customer-sub-context">{customerName} · {customerId}{updown && <span>替换 {existing?.no}:原合同、条目、套餐已锁定(左侧),只需在右侧挑一个「新套餐」;提交后原订阅的有效期截到新订阅生效前一天。</span>}</p>
  452. {contracts.error && <div className="customer-sub-alert" role="alert">可选合同取数失败:{contracts.error.message}</div>}
  453. {originalContract.error && <div className="customer-sub-alert" role="alert">原合同明细取数失败:{originalContract.error.message}(服务构成条目暂按原订阅当前条目回显)</div>}
  454. {plans.error && <div className="customer-sub-alert" role="alert">可选套餐取数失败:{plans.error.message}</div>}
  455. {!writable && <div className="customer-sub-alert">{context.mode === "view" ? "详情为只读。需要变更时请新建订阅或办理升降配。" : existing?.editable === undefined ? "写口可见性未随记录下发,按只读呈现。" : "服务端判定本条只读(已到期或已开通计费)。需要变更时请新建订阅。"}</div>}
  456. {/*
  457. 升降配的分栏(业主 2026-11-16):左「原订阅」只读、右「变更后」只有一个新套餐下拉。
  458. 原套餐此前也画成可选下拉,看着像「在改原订阅」,套餐切换反而看不出来 ⇒ 改成左侧锁定卡。
  459. 合同与条目不再单独暴露:它们由所选新套餐反推(后端按条目反查档位并强校验匹配)。
  460. */}
  461. {updown ? <div className="order-change">
  462. <section className="order-change-card is-locked" aria-label="原订阅(只读)">
  463. <header><h3>原订阅</h3><span>已锁定 · 不可修改</span></header>
  464. <dl className="order-change-grid">
  465. <div><dt>订单号</dt><dd>{textOf(existing?.no, WORD_UNCONFIGURED)}</dd></div>
  466. <div><dt>套餐</dt><dd>{textOf(existing?.planName)}</dd></div>
  467. <div><dt>合同编号</dt><dd>{contractText(existing?.contractNo, originalContract.data?.contract_no)}</dd></div>
  468. <div><dt>服务构成条目</dt><dd>{textOf(existing?.contractItemId)}</dd></div>
  469. <div><dt>订阅时长</dt><dd>{textOf(existing?.termLabel)}</dd></div>
  470. <div><dt>期间</dt><dd>{textOf(existing?.start)} 至 {textOf(existing?.end)}</dd></div>
  471. <div><dt>订阅价格</dt><dd>{textOf(existing?.annual.text)}</dd></div>
  472. <div><dt>月结算标准</dt><dd>{textOf(existing?.settle.text)} / 月</dd></div>
  473. <div><dt>分账号额度</dt><dd>{existing?.quotaSlots === undefined ? WORD_FETCH_FAILED : existing.quotaSlots === null ? WORD_UNCONFIGURED : `${existing.quotaSlots} 个`}</dd></div>
  474. </dl>
  475. </section>
  476. <div className="order-change-pivot" aria-hidden="true"><ArrowRight size={18} /><span>变更为</span></div>
  477. <section className="order-change-card is-target" aria-label="变更后">
  478. <header><h3>变更后</h3><span>{pickedTarget ? "请核对带出的值" : "挑一个要变更到的套餐"}</span></header>
  479. <label className="order-change-pick"><span>新套餐 <b>*</b></span>
  480. <select value={targetKey} onChange={(event) => pickTarget(event.target.value)} disabled={!updownTargets.length} aria-label="选择要变更到的新套餐">
  481. <option value="">{contracts.loading || plans.loading ? "正在读取可替换套餐…" : updownTargets.length ? "请选择新套餐" : "没有可替换的新套餐"}</option>
  482. {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>)}
  483. </select>
  484. </label>
  485. {pickedTarget ? <dl className="order-change-grid">
  486. <div><dt>变更后套餐</dt><dd>{pickedTarget.planName}</dd></div>
  487. <div><dt>替换合同</dt><dd>{contractText(pickedTarget.contractLabel, pickedTarget.contractInternal)}{pickedTarget.sameContract ? "(原合同)" : ""}</dd></div>
  488. <div><dt>服务构成条目</dt><dd>{pickedTarget.itemId}</dd></div>
  489. <div><dt>订阅价格</dt><dd>{pickedTarget.annualCents === null ? WORD_UNCONFIGURED : moneyCell(pickedTarget.annualCents).text}</dd></div>
  490. <div><dt>月结算标准</dt><dd>{pickedTarget.settleCents === null ? WORD_UNCONFIGURED : `${moneyCell(pickedTarget.settleCents).text} / 月`}</dd></div>
  491. <div><dt>分账号额度</dt><dd>{pickedTarget.quota === null ? WORD_UNCONFIGURED : `${pickedTarget.quota} 个`}</dd></div>
  492. <div><dt>线路出口</dt><dd>{pickedTarget.exits?.length ? pickedTarget.exits.join("、") : WORD_UNCONFIGURED}</dd></div>
  493. </dl> : <p className="order-change-note">原套餐与合同条目已锁定;选一个新套餐后,替换合同、条目、订阅价格、月结算与额度会随它带出。</p>}
  494. {updownDelta && <div className="order-change-delta"><span className={`order-change-badge is-${updownDelta.tone}`}>{updownDelta.text}</span><span className="order-change-note">按年订阅价格对比</span></div>}
  495. {!updownHasNew && !contracts.loading && !plans.loading && <p className="order-change-note is-warn">当前没有可替换的新套餐:原合同 {textOf(existing?.contractNo, originalContractId)} 下没有第二条已绑定档位的服务构成条目,该客户名下也没有其他可选合同。换档需先在第 1 步签一份带新条目的合同,再回到「升降配」。</p>}
  496. </section>
  497. </div> : <div className="customer-sub-fields">
  498. <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>
  499. <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 ?? contractItems.find((entry) => entry.item_id === next)?.plan_id_derived ?? ""; 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_kind}{item.quantity ? ` × ${item.quantity}` : ""}</option>)}</select></label>
  500. <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>
  501. </div>}
  502. <div className="customer-sub-fields">
  503. {!updown && <label>线路出口(随合同条目)<input readOnly value={exitsText} /></label>}
  504. {!updown && <label>订阅方式<input readOnly value={modeText} title={ORDER_MODE_BY_CATEGORY} /></label>}
  505. {context.mode === "edit" ? <label><span>订阅时长</span><input readOnly value={existing?.termLabel || WORD_UNCONFIGURED} /></label>
  506. : <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>}
  507. <label><span>生效日 <b>*</b></span><input disabled={locked} type="date" value={startDate} onChange={(event) => setStartDate(event.target.value)} /></label>
  508. <label><span>结束日(服务端派生)</span><input readOnly value={updown && !pickedTarget ? "选定新套餐后按替换合同止期派生" : endText} title="预览=生效日折订阅时长(月末夹紧)再减一天,晚于合同止期则截到合同止期;落库值以服务端为准" /></label>
  509. <label>订单号(随合同外部单号)<input readOnly value={orderText} /></label>
  510. {!updown && <label>订阅价格<input readOnly value={annualText} title={ORDER_AMOUNT_TITLE} /></label>}
  511. {!updown && <label>月结算标准<input readOnly value={settleText} title={ORDER_AMOUNT_TITLE} /></label>}
  512. {!updown && <label>分账号额度<input readOnly value={quotaText} title="随所选档位的额度带出" /></label>}
  513. {!updown && stackableItem && <label>档位数量(随合同条目)<input readOnly value={itemQuantity} title="可叠加档按份计价(例如单独境外 IP 按个);保存时带入订阅 subscription.quantity" /></label>}
  514. <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>
  515. {trialMonths !== "0" && <label>试用优惠金额(元/月)<input readOnly={!writable} inputMode="decimal" placeholder="选填,留空不套用正式月费" value={trialDiscount} onChange={(event) => setTrialDiscount(event.target.value)} /></label>}
  516. <label>实际开通日<input readOnly value={locked ? (existing?.openedOn === undefined ? WORD_FETCH_FAILED : existing.openedOn || WORD_NOT_OPENED) : WORD_NOT_OPENED} /></label>
  517. </div>
  518. <p className="customer-sub-hint">{editing ? "编辑态只有「试用优惠期」与「试用优惠金额」两项可改,其余由服务端冻结:换套餐请走「升降配」替换,改价须另签新合同后新建订阅。" : updown ? "升降配只变更「套餐」这一项:原订阅的合同、条目、档位不可改,替换用的合同与条目随新套餐带出。原订阅在新订阅生效前一天结束,历史保留。" : `${ORDER_CREATE_READONLY_NOTE}(${ORDER_AMOUNT_TITLE})。合同期间、订单号与线路出口随合同条目带出,网络开通由运维流程回填。`}</p>
  519. {error && <p className="ops-form-error" role="alert">{error}</p>}
  520. <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>
  521. </form>
  522. </Dialog>;
  523. }
  524. /**
  525. * 订阅叠加弹窗(手册 P5 步骤③):在旧订阅上**只改服务结束日期**,走 `/subscription/stack@v1`。
  526. *
  527. * 套餐、价格、月结算标准与本条订阅的其余字段一律只读呈现,⛔ 在此提交(`stack` 只收 end_date);
  528. * 提交前先给出二次确认,确认后才调接口。
  529. */
  530. export function StackEditor({ record, customerName, onClose, onSaved }: {
  531. record: OrderView; customerName: string; onClose: () => void; onSaved: (message: string) => void;
  532. }) {
  533. const [endDate, setEndDate] = useState("");
  534. const [error, setError] = useState("");
  535. const [pending, setPending] = useState(false);
  536. const [confirming, setConfirming] = useState(false);
  537. async function submit(event: FormEvent<HTMLFormElement>) {
  538. event.preventDefault();
  539. if (!endDate) { setError("请选择叠加后的服务结束日期。"); return; }
  540. if (!confirming) { setConfirming(true); return; }
  541. setPending(true);
  542. setError("");
  543. try {
  544. await orderStack({ subscription_id: record.no, end_date: endDate });
  545. onSaved(`叠加已生效:${record.no} 的服务结束日期改为 ${endDate}。`);
  546. } catch (cause) {
  547. setError((cause as Error).message);
  548. setPending(false);
  549. setConfirming(false);
  550. }
  551. }
  552. return <Dialog title={`叠加 · ${record.planName ?? WORD_FETCH_FAILED}`} onClose={onClose}>
  553. <form className="customer-sub-form" onSubmit={submit}>
  554. <p className="customer-sub-context">{customerName} · {record.no} 沿用本条订阅,只改服务结束日期。</p>
  555. <div className="customer-sub-fields">
  556. <label>套餐<input readOnly value={textOf(record.planName)} /></label>
  557. <label>合同期间<input readOnly value={`${textOf(record.start)} 至 ${textOf(record.end)}`} /></label>
  558. <label>当前结束日<input readOnly value={textOf(record.end)} /></label>
  559. <label><span>叠加后结束日 <b>*</b></span><input type="date" disabled={confirming && pending} value={endDate} onChange={(event) => { setEndDate(event.target.value); setConfirming(false); setError(""); }} /></label>
  560. </div>
  561. <p className="customer-sub-hint">叠加在本条订阅上直接续期:套餐、订阅价格与月结算标准不变,期间由服务端按新结束日生效。</p>
  562. {confirming && !error && <div className="customer-sub-alert" role="alertdialog">确认把服务结束日期由「{textOf(record.end)}」改为「{endDate}」?确认后立即生效。</div>}
  563. {error && <p className="ops-form-error" role="alert">{error}</p>}
  564. <footer><Button type="button" variant="outline" onClick={onClose}>{confirming ? "取消" : "关闭"}</Button><Button type="submit" disabled={pending || !endDate}>{confirming ? (pending ? "提交中…" : "确认叠加") : "下一步"}</Button></footer>
  565. </form>
  566. </Dialog>;
  567. }