Ver Fonte

feat(web): 订阅办理弹窗组件(新增/编辑/升降配/叠加)

把原先内联在客户套餐订阅管理页与订阅详情页的办理逻辑抽成 OrderChangeDialogs,
供「套餐订阅管理」「订阅详情」页头「更多」与订阅台账三处复用:
- 升降配带入原订阅与原合同条目,新套餐候选按「用途分类 + 线路出口」收窄
- 叠加按当前订阅的合同条目候选,额度 0 不新增分账号
- 六项只读带出(线路出口、订阅方式、结束日、订阅价格、月结算标准、额度)

Co-authored-by: Cursor <cursoragent@cursor.com>
cg há 6 dias atrás
pai
commit
a0040557ba
1 ficheiros alterados com 571 adições e 0 exclusões
  1. 571 0
      web-scaffold/src/components/OrderChangeDialogs.tsx

+ 571 - 0
web-scaffold/src/components/OrderChangeDialogs.tsx

@@ -0,0 +1,571 @@
+/**
+ * 订阅办理弹窗:新建走 `create`、升降配走 `change`、编辑只放开白名单字段走 `update`、叠加走 `stack`。
+ *
+ * 价格、月标准、结束日、实际开通日、线路出口、订单号六项只读,由服务端按套餐配置与合同条目带出;
+ * ⛔ 在此提交或改写它们(出现即 `11103`)。
+ *
+ * 三个入口共用同一份弹窗:客户档案「套餐订阅管理」行内、客户档案「04 全部订阅」行内、订阅详情页头,
+ * 判据与载荷只写一次,⛔ 各页各写一份抽屉造成口径漂移。
+ * ⚠️ 菜单「订阅台账」(原「全部订阅」,路由 `/orders`)按需求 5.2 只读,⛔ 挂本弹窗的写入口。
+ * 升降配只改「套餐」这一项:原订阅的合同/条目/档位在左侧只读锁定,右侧只列**可承接的新套餐**
+ * (来源=各承接合同条目的绑定档位),选一次即带出合同/条目/档位三键(业主 2026-11-16 定案)。
+ */
+import { useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";
+import { ArrowRight, X } from "lucide-react";
+import { Button } from "./ui/button";
+import { OPTIONS, ORDER_MODE, label } from "../lib/api/labels";
+import {
+  CONTRACT_OPTIONS_EMPTY, ORDER_AMOUNT_TITLE, ORDER_CREATE_READONLY_NOTE, ORDER_END_DATE_READONLY,
+  ORDER_MODE_BY_CATEGORY, WORD_FETCH_FAILED, WORD_MODE_PENDING, WORD_NOT_OPENED, WORD_PICK_CONTRACT_FIRST,
+  WORD_PICK_CONTRACT_ITEM_FIRST, WORD_PICK_PLAN_FIRST, WORD_UNCONFIGURED,
+} from "../lib/api/lockedCopy";
+import { moneyCell, yuanToCents } from "../lib/package-catalog";
+import { rowsOf, orderChange, orderContractOptions, orderCreate, orderPlanOptions, orderStack, orderUpdate, contractGet } from "../lib/api/bos";
+import type { OrderContractItemOption, OrderContractOption, OrderPlanOption } from "../lib/api/types";
+import { useLoad } from "../lib/useLoad";
+import type { OrderView } from "../lib/order-demo";
+
+export type OrderEditorMode = "new" | "edit" | "view" | "updown";
+export type OrderEditorContext = { mode: OrderEditorMode; record?: OrderView };
+
+/** 升降配的变更目标:承接合同+服务构成条目+新档位,三者由后端强校验必须自洽。 */
+type UpdownTarget = {
+  key: string;
+  contractId: string;
+  /** 合同**外部单号**:台账、订阅详情都按这个口径显示,⛔ 这里改用内部号造成两处对不上。 */
+  contractLabel: string;
+  /** 真合同号:外部单号可重复(实测两份合同同叫 WB-P3-20261115-01),两号并显才分得清(D-33)。 */
+  contractInternal: string | null;
+  sameContract: boolean;
+  itemId: string;
+  planId: string;
+  planName: string;
+  annualCents: number | null;
+  settleCents: number | null;
+  quota: number | null;
+  exits: string[] | null;
+  sameAsOriginal: boolean;
+};
+
+/**
+ * 结束日预览(D-72)=`/subscription/create@v1` 里 `derive_period` 的同口径前端镜像:
+ * 生效日折 N 个月(当月不足 N 月时夹到月末)得「下一周期生效日」⇒ 再减一天;
+ * 结果晚于合同止期 ⇒ 截到合同止期。⚠️ 只是**预览**,落库值一律以服务端为准。
+ */
+function previewEnd(start: string, term: string, contractEnd: string | null): string | null {
+  if (!/^\d{4}-\d{2}-\d{2}$/.test(start)) return null;
+  const months = term === "quarterly" ? 3 : term === "monthly" ? 1 : 12;
+  const [y, m, d] = start.split("-").map(Number);
+  const anchor = new Date(Date.UTC(y, m - 1 + months, 1));
+  const last = new Date(Date.UTC(anchor.getUTCFullYear(), anchor.getUTCMonth() + 1, 0)).getUTCDate();
+  anchor.setUTCDate(Math.min(d, last));
+  anchor.setUTCDate(anchor.getUTCDate() - 1);
+  const iso = anchor.toISOString().slice(0, 10);
+  return contractEnd && contractEnd < iso ? contractEnd : iso;
+}
+
+/** 只读输入框只能用字符串:三态在这里落到锁定文案,⛔ 用「—」或 0 冒充。 */
+const textOf = (value: string | null | undefined, missing: string = WORD_UNCONFIGURED) =>
+  (value === undefined ? WORD_FETCH_FAILED : value === null || value === "" ? missing : value);
+
+/**
+ * 合同两号并显:`contract_no` 是外部单号,**可以重复**(实测两份合同同叫 WB-P3-20261115-01),
+ * 内部号才唯一 ⇒ 只显示一个就会把「原合同」和另一份合同认成同一份(D-33)。
+ */
+const contractText = (external: string | null | undefined, internal: string | null | undefined) => {
+  const ext = external ?? "";
+  if (!internal || internal === ext) return ext || textOf(external);
+  return ext ? `${ext} / ${internal}` : internal;
+};
+
+/** 本地「今天」:`toISOString()` 是 UTC,跨时区会把默认生效日推到前一天/后一天。 */
+function todayText(): string {
+  const now = new Date();
+  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
+}
+function Dialog({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
+  const ref = useRef<HTMLDialogElement>(null);
+  useEffect(() => {
+    const dialog = ref.current;
+    if (!dialog) return;
+    const previous = document.activeElement as HTMLElement | null;
+    dialog.showModal();
+    return () => { dialog.close(); previous?.focus(); };
+  }, []);
+  return <dialog ref={ref} className="customer-sub-dialog" aria-labelledby="customer-sub-dialog-title" onCancel={onClose} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
+    <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>
+    {children}
+  </dialog>;
+}
+
+export function OrderEditor({ customerId, customerName, context, onClose, onSaved }: {
+  customerId: string; customerName: string; context: OrderEditorContext; onClose: () => void; onSaved: (message: string) => void;
+}) {
+  const existing = context.record;
+  /**
+   * 升降配带入原订阅的合同/条目/档位/时长(业主 2026-11-16 定案):
+   * 原订阅的合同/条目/套餐是**被承接的对象**,⛔ 可编辑——它们只作为只读「原订阅」呈现;
+   * 用户唯一要做的是在「新套餐」里挑一个变更目标(业主 2026-11-16 二次定案:
+   * 「带入的原套餐还可以改」=说不清在改哪一边,套餐切换也就看不出来)。
+   * 合同/条目仍由所选新套餐反推(后端按 `contract_item_id` 反查条目并强校验档位匹配)。
+   */
+  const updown = context.mode === "updown";
+  const fresh = context.mode === "new";
+  const originalContractId = existing?.contractId ?? "";
+  const originalItemId = existing?.contractItemId ?? "";
+  const [contractId, setContractId] = useState(fresh || updown ? "" : originalContractId);
+  const [itemId, setItemId] = useState(fresh || updown ? "" : originalItemId);
+  const [planId, setPlanId] = useState(fresh || updown ? "" : existing?.planId ?? "");
+  /** 升降配的「变更目标」=(承接合同, 服务构成条目, 新档位) 三元组;选它一次就带齐三个载荷键。 */
+  const [targetKey, setTargetKey] = useState("");
+  const [term, setTerm] = useState(updown ? existing?.row.term ?? "yearly" : "yearly");
+  /**
+   * 升降配的生效日默认**当天**(契约 §5.2「开始日默当天」):原订阅的生效日多半已过去,
+   * 照抄会把承接单做成过去时,截原时「新开始−1 天」早于原开始日 ⇒ 原订阅被压成零天期间。
+   */
+  const defaultStart = updown ? todayText() : existing?.start ?? "";
+  const [startDate, setStartDate] = useState(defaultStart);
+  const [trialMonths, setTrialMonths] = useState<"0" | "1" | "2">(existing?.trialMonths === 1 || existing?.trialMonths === 2 ? String(existing.trialMonths) as "1" | "2" : "0");
+  const [trialDiscount, setTrialDiscount] = useState(existing?.trialDiscount ? String(existing.trialDiscount / 100) : "");
+  const [error, setError] = useState("");
+  const [pending, setPending] = useState(false);
+  const contracts = useLoad(() => orderContractOptions({ customer_id: customerId }), [customerId]);
+  const plans = useLoad(() => orderPlanOptions({ customer_id: customerId }), [customerId]);
+  /**
+   * 原合同明细另取:候选口按「合同未开通」+「条目未被订阅引用」双筛,而升降配的源头合同恰恰
+   * 两条都不满足 ⇒ 原合同及其全部条目都不在 `contract_options` 里。`contract/get@v1` 才给得出
+   * 全量条目(含止期),据此拼出「原合同」候选:下拉回显、条目可选、档位按条目收窄都靠它。
+   */
+  const originalContract = useLoad(
+    () => (updown && originalContractId ? contractGet({ contract_id: originalContractId }) : Promise.resolve(null)),
+    [updown, originalContractId],
+  );
+  const candidates = rowsOf(contracts.data);
+  /**
+   * 「原合同」的带入条目:候选口把**已被订阅引用的条目**也剔了(§5.2「尚未有订阅的条目」),
+   * 而升降配的源头条目恰恰全部被引用 ⇒ 只看候选,原合同会显示成「没有服务构成条目」。
+   * 这里按 `contract/get@v1` 的明细补齐全部条目;明细未到/查不到原条目时用订阅行兜底,
+   * ⛔ 让下拉空着冒充「未选」。
+   */
+  const originalItems: OrderContractItemOption[] = (() => {
+    if (!updown || !existing || !originalContractId) return [];
+    const detail = originalContract.data;
+    const items: OrderContractItemOption[] = rowsOf(detail?.service_items).flatMap((entry) => entry.item_id ? [{
+      item_id: entry.item_id,
+      item_kind: entry.item_kind ?? "plan_based",
+      plan_id: entry.plan_id ?? null,
+      plan_id_derived: entry.derived_plan_id ?? null,
+      plan_name: entry.plan_name ?? entry.derived_plan_name ?? null,
+      quantity: entry.quantity ?? null,
+      annual_price_cents: entry.annual_price_cents ?? null,
+      line_exits: entry.line_exits ?? null,
+      use_category: entry.use_category ?? null,
+      available: true,
+    }] : []);
+    if (originalItemId && !items.some((entry) => entry.item_id === originalItemId)) {
+      items.unshift({
+        item_id: originalItemId,
+        item_kind: existing.row.plan_kind === "custom" ? "custom_spec" : "plan_based",
+        plan_id: existing.planId || null,
+        plan_id_derived: null,
+        plan_name: existing.planName ?? null,
+        quantity: null,
+        annual_price_cents: null,
+        line_exits: existing.exits ?? null,
+        use_category: existing.row.use_category ?? null,
+        available: true,
+      });
+    }
+    return items;
+  })();
+  /** 原合同的候选形状与标签:标签点名「原合同」,免得不带标识地混在可签新合同里。 */
+  const originalOption: OrderContractOption | null = (() => {
+    if (!updown || !existing || !originalContractId) return null;
+    const detail = originalContract.data;
+    const internalNo = detail?.contract_no ?? existing.contractNo ?? originalContractId;
+    const externalNo = detail?.external_no ?? null;
+    const baseLabel = detail ? `${internalNo}${externalNo ? `(外部单号 ${externalNo})` : ""}` : existing.contractNo ?? originalContractId;
+    return {
+      contract_id: originalContractId,
+      contract_no: externalNo ?? existing.contractNo ?? originalContractId,
+      internal_no: internalNo,
+      external_no: externalNo,
+      option_label: `${baseLabel} · 原合同`,
+      start_date: detail?.start_date ?? null,
+      end_date: detail?.end_date ?? null,
+      items: originalItems,
+    };
+  })();
+  /**
+   * 合同下拉=服务端候选 ∪ 原合同(同一份合同⛔ 出现两遍):
+   * 原合同被「已开通」剔出候选 ⇒ 补在最前;仍在候选里 ⇒ 只换标签并补齐条目。
+   */
+  const contractList: OrderContractOption[] = (() => {
+    if (!originalOption) return candidates;
+    const hit = candidates.find((item: OrderContractOption) => item.contract_id === originalOption.contract_id);
+    if (!hit) return [originalOption, ...candidates];
+    const merged = [...originalOption.items, ...rowsOf(hit.items).filter((entry) => !originalOption.items.some((mine) => mine.item_id === entry.item_id))];
+    return candidates.map((item: OrderContractOption) => item.contract_id === originalOption.contract_id
+      ? { ...item, option_label: originalOption.option_label, end_date: item.end_date ?? originalOption.end_date, items: merged }
+      : item);
+  })();
+  const contractItems = rowsOf(contractList.find((item: OrderContractOption) => item.contract_id === contractId)?.items);
+  /**
+   * 候选空态(D-68):后端把「已开通」与**已到期**合同一并剔出候选,候选为空时回 200+`empty_state`
+   * +契约空态句 ⇒ 下拉渲染该句(TC-CU-50 步骤1),⛔ 留一句「请选择该客户的可选合同」冒充还有得选。
+   */
+  const contractEmpty = contracts.loading || contractList.length ? null : contracts.data?.empty_text || CONTRACT_OPTIONS_EMPTY;
+  /**
+   * 写口锁定面(D-69):编辑/详情态后端白名单只有 `trial_months`/`discount_monthly_cents`,
+   * 其余键(`term`/`start_date`/`plan_id`/`contract_id`…)逐键 `11103`/`60222` 拒收 ⇒
+   * 页面在**输入侧**就锁死,⛔ 给出可改错觉(改套餐走升降配,改价另签新合同后新建订阅)。
+   */
+  const editing = context.mode === "edit";
+  const locked = editing || context.mode === "view";
+  const selectedContract = contractList.find((item: OrderContractOption) => item.contract_id === contractId);
+  const selectedItem = contractItems.find((entry) => entry.item_id === itemId);
+  /**
+   * 套餐候选随合同条目收窄(O-15;新建态与升降配态同规则)。
+   *
+   * 后端把「条目档位 ≠ 所选套餐」当业务错拒(实测 `60221`:`条目 CI-0001-1 关联档位 P-002,
+   * 与所选档位 P-008 不匹配`)⇒ 在**输入侧**收窄:条目钉死档位只列该档;未选条目只列该合同
+   * 未订阅条目涉及的档位;还没选合同 ⇒ 不列候选。条目未钉档位(`plan_id` 与 `plan_id_derived`
+   * 都空)时不下约束,避免走投无路。
+   * 升降配态后端按**新合同**反查条目(P5-D1 修正后:载荷可另选新合同),而同屏可选套餐若仍列全目录,
+   * 用户就会选到合同里根本没有的档位,提交必吃 `KLT-M228`(P5-D2)⇒ 与新建态同规则收窄。
+   */
+  const contractPlanIds = new Set(contractItems.map((entry) => entry.plan_id ?? entry.plan_id_derived ?? "").filter(Boolean));
+  const itemPlanId =
+    context.mode === "new" || context.mode === "updown"
+      ? selectedItem?.plan_id ?? selectedItem?.plan_id_derived ?? null
+      : null;
+  const planChoices = rowsOf(plans.data).filter((item: OrderPlanOption) => {
+    if (context.mode !== "new" && context.mode !== "updown") return true;
+    if (itemPlanId) return item.plan_id === itemPlanId;
+    if (!contractId || !contractPlanIds.size) return true;
+    return contractPlanIds.has(item.plan_id);
+  });
+  /**
+   * 升降配的「变更目标」清单(业主要求:原套餐锁死、只挑新套餐)。
+   *
+   * 可承接的组合只有一种来源——**合同的服务构成条目**:后端 `change` 按条目反查档位并强校验
+   * 「条目关联档位 = 所选档位」,所以能换到哪个套餐完全由条目决定,不能直接列全目录。
+   * 这里把 `contractList`(原合同已并入,条目按 `contract/get` 全量补齐)里每个条目的档位摊平,
+   * 选一次即同时定下 `contract_id`/`contract_item_id`/`plan_id`——用户只需认套餐名,
+   * ⛔ 逼他先理解「合同 → 条目 → 档位」三层再自己配对。
+   * 与原订阅同合同/同条目/同档位的组合标成「当前订阅」并禁用:那不是升降配,是原样重开。
+   */
+  const updownTargets = (() => {
+    if (!updown || !existing) return [] as UpdownTarget[];
+    const catalog = new Map(rowsOf(plans.data).map((item: OrderPlanOption) => [item.plan_id, item]));
+    const seen = new Set<string>();
+    const out: UpdownTarget[] = [];
+    for (const contract of contractList) {
+      for (const entry of rowsOf(contract.items)) {
+        const pid = entry.plan_id ?? entry.plan_id_derived ?? "";
+        if (!pid) continue;
+        const key = `${contract.contract_id}::${entry.item_id}::${pid}`;
+        if (seen.has(key)) continue;
+        seen.add(key);
+        const price = catalog.get(pid);
+        /* 目录里明确不可订阅的档位(停用/越权)后端必拒,先在下拉里置灰。 */
+        if (price && price.available === false) continue;
+        out.push({
+          key,
+          contractId: contract.contract_id,
+          contractLabel: contract.contract_no ?? contract.internal_no ?? contract.contract_id,
+          contractInternal: contract.internal_no ?? null,
+          sameContract: contract.contract_id === originalContractId,
+          itemId: entry.item_id,
+          planId: pid,
+          planName: price?.plan_name ?? entry.plan_name ?? pid,
+          annualCents: price?.annual_price_cents ?? entry.annual_price_cents ?? null,
+          settleCents: price?.monthly_settle_cents ?? null,
+          quota: price?.sub_account_quota ?? null,
+          exits: entry.line_exits ?? price?.line_exits ?? null,
+          sameAsOriginal:
+            contract.contract_id === originalContractId && entry.item_id === originalItemId && pid === existing.planId,
+        });
+      }
+    }
+    return out;
+  })();
+  const pickedTarget = updownTargets.find((item) => item.key === targetKey) ?? null;
+  /** 是否存在「换得动」的目标:只剩当前订阅那一项时,等于这条订阅没有可承接的档位。 */
+  const updownHasNew = updownTargets.some((item) => !item.sameAsOriginal);
+  /** 选中新套餐后把三键(合同/条目/档位)一起落到提交状态上,表单其余只读格才跟着变。 */
+  function pickTarget(next: string) {
+    setTargetKey(next);
+    const found = updownTargets.find((item) => item.key === next);
+    setContractId(found?.contractId ?? "");
+    setItemId(found?.itemId ?? "");
+    setPlanId(found?.planId ?? "");
+    setError("");
+  }
+  /** 升降幅度:只拿年订阅价格比,⛔ 拿月结算比(口径不同,比出来没意义)。 */
+  const updownDelta = (() => {
+    if (!pickedTarget) return null;
+    const before = existing?.row.annual_price_cents ?? null;
+    const after = pickedTarget.annualCents;
+    if (before === null || after === null) return { tone: "flat" as const, text: "金额缺少一侧下发,不做涨跌判定" };
+    const diff = after - before;
+    if (diff === 0) return { tone: "flat" as const, text: "年订阅价格不变" };
+    return {
+      tone: diff > 0 ? "up" as const : "down" as const,
+      text: `${diff > 0 ? "升配" : "降配"} ${diff > 0 ? "+" : "−"}${moneyCell(Math.abs(diff)).text}/年`,
+    };
+  })();
+  /**
+   * 当前值不在候选内(编辑态合同已开通/条目已订阅,升降配态原条目不在新合同里)
+   * ⇒ 补一条回显选项,⛔ 让下拉空着冒充「未选」(O-16)。升降配的原合同已并入 `contractList`,
+   * 正常情况下三项都选得中,这层兜底只为脏引用/明细未到时不留空白。
+   */
+  const contractInOptions = contractList.some((item: OrderContractOption) => item.contract_id === contractId);
+  const itemInOptions = contractItems.some((entry) => entry.item_id === itemId);
+  const planInOptions = planChoices.some((item: OrderPlanOption) => item.plan_id === planId);
+  /** 可写性只取服务端结论:新建/升降配始终可提交,编辑要求后端下发 `editable`。 */
+  const writable = context.mode === "new" || context.mode === "updown" || (context.mode === "edit" && existing?.editable === true);
+  const priceOf = planId ? rowsOf(plans.data).find((item: OrderPlanOption) => item.plan_id === planId) : undefined;
+  /** 引导句=三态之外的第四形态:还没选到能带出值的对象,⛔ 判成「取数失败」(D-26/D-29)。 */
+  const pickHint = context.mode === "updown" ? WORD_PICK_PLAN_FIRST : contractId ? WORD_PICK_CONTRACT_ITEM_FIRST : WORD_PICK_CONTRACT_FIRST;
+  /** 线路出口优先取**合同条目**(`plan_options` 对固定档回 `line_exits:null`,条目上才是真值)。 */
+  const exitsText = (() => {
+    const ofRow = (exits: string[] | null | undefined) =>
+      (exits === undefined ? WORD_FETCH_FAILED : exits === null || !exits.length ? WORD_UNCONFIGURED : exits.join("、"));
+    if (locked) return ofRow(existing?.exits);
+    const fromItem = selectedItem?.line_exits;
+    const fromPrice = priceOf?.line_exits;
+    if (!planId && !selectedItem) return pickHint;
+    if (fromItem && fromItem.length) return ofRow(fromItem);
+    if (fromPrice && fromPrice.length) return ofRow(fromPrice);
+    /**
+     * 升降配沿用原合同且固定档在 `plan_options` 回 `line_exits:null` ⇒ 两处都取不到时,
+     * 用原订阅行上服务端当初写入的出口(它才是这条合同条目真正冻过的值)。
+     */
+    if (updown && contractId === originalContractId && existing?.exits?.length) return ofRow(existing.exits);
+    return ofRow(fromPrice);
+  })();
+  /** 订阅方式只读格=服务端 `sub_mode` 的三态结论;`null`(派生档未预置用途分类)⇒ 诚实占位(D-31)。 */
+  const modeText = (() => {
+    // D-32:已选套餐却判不出订阅方式,根因是**该档位没预置用途分类**,不是「还没选条目」
+    // ⇒ 文案点名真实缺口,⛔ 用「待选条目后判定」把人支到走不通的路上。
+    const pending = priceOf && priceOf.use_category === null
+      ? "用途分类未配置(请先在合同条目或目录档位补齐)"
+      : WORD_MODE_PENDING;
+    if (!locked) return planId ? label(ORDER_MODE, priceOf?.sub_mode) || pending : pickHint;
+    if (existing?.modeLabel) return existing.modeLabel;
+    return existing?.row.sub_mode === undefined ? WORD_FETCH_FAILED : pending;
+  })();
+  /** D-72:结束日只读格此前恒显提示语,填了生效日也不预览(服务端实会派生)。 */
+  const endText = (() => {
+    if (context.mode === "edit" || context.mode === "view") return existing?.end ?? WORD_UNCONFIGURED;
+    const chosen = contractList.find((item: OrderContractOption) => item.contract_id === contractId);
+    const preview = previewEnd(startDate, term, chosen?.end_date ?? null);
+    return preview ?? ORDER_END_DATE_READONLY;
+  })();
+  /** 分账号额度:随**所选档位**带出(升降配的对比走「变更后」卡片,⛔ 在这里拼原值)。 */
+  const quotaText = (() => {
+    if (locked) { const v = existing?.quotaSlots; return v === undefined ? WORD_FETCH_FAILED : v === null ? WORD_UNCONFIGURED : String(v); }
+    if (!planId) return pickHint;
+    const v = priceOf?.sub_account_quota ?? pickedTarget?.quota;
+    if (v === undefined || v === null) return WORD_UNCONFIGURED;
+    return String(v);
+  })();
+  const annualText = (() => {
+    if (locked) return textOf(existing?.annual.text);
+    if (!planId) return pickHint;
+    return priceOf?.annual_price_cents === undefined || priceOf.annual_price_cents === null ? WORD_UNCONFIGURED : moneyCell(priceOf.annual_price_cents).text;
+  })();
+  const settleText = (() => {
+    if (locked) return `${textOf(existing?.settle.text)} / 月`;
+    if (!planId) return pickHint;
+    return priceOf?.monthly_settle_cents === undefined || priceOf.monthly_settle_cents === null ? WORD_UNCONFIGURED : `${moneyCell(priceOf.monthly_settle_cents).text} / 月`;
+  })();
+  /** 订单号随合同外部单号冻结:选定合同后把将要冻结的单号显出来,⛔ 只留一句空话(D-40 族)。 */
+  const externalNo = selectedContract?.contract_no ?? (contractId && !contractInOptions ? existing?.contractNo ?? "" : "");
+  const orderText = locked ? textOf(existing?.orderNo, "无运营商订单号") : `由服务端按合同外部单号冻结${externalNo ? `:${externalNo}` : ""}`;
+  /**
+   * 「一项没改」判定:合同/条目/档位/时长/生效日全等于原订阅 ⇒ 提交只会把原订阅截断、
+   * 再生成一份同档位的重复订阅,这不是升降配。升降配的候选里已把「原订阅」那一项禁用,
+   * 这里只兜脏数据(例如原条目既没条目明细也推不出档位)。
+   */
+  const unchanged = updown && existing !== undefined
+    && contractId === originalContractId
+    && itemId === originalItemId
+    && planId === existing.planId
+    && term === (existing.row.term ?? "yearly")
+    && startDate === defaultStart;
+
+  async function submit(event: FormEvent<HTMLFormElement>) {
+    event.preventDefault();
+    if (updown && !pickedTarget) { setError("请先选择要变更到的新套餐(原套餐已锁定,不在可选范围内)。"); return; }
+    if (!editing && !contractId) { setError("请选择合同编号:订阅必须引用该客户已登记且未开通的合同"); return; }
+    if (!editing && (!itemId || !planId || !startDate)) { setError("请选择合同服务构成条目、套餐并填写生效日。"); return; }
+    if (context.mode === "updown" && !existing) return setError("缺少被承接的原订阅。");
+    if (unchanged) return setError("所选组合就是原订阅本身:请换一个档位,或另选承接合同/条目(只改时长/生效日也算重开原档)。");
+    setPending(true);
+    setError("");
+    try {
+      if (context.mode === "edit" && existing) {
+        const discount = trialMonths === "0" || !trialDiscount.trim() ? undefined : yuanToCents(trialDiscount);
+        if (trialMonths !== "0" && trialDiscount.trim() && discount === null) { setError("试用优惠金额须为非负金额,最多两位小数。"); setPending(false); return; }
+        await orderUpdate({
+          subscription_id: existing.no,
+          row_version: Number(existing.rowVersion),
+          trial_months: Number(trialMonths),
+          ...(discount === undefined ? {} : { discount_monthly_cents: discount }),
+        });
+        onSaved("订阅已更新(仅试用与优惠白名单字段可写)。");
+      } else if (context.mode === "updown" && existing) {
+        await orderChange({
+          replaces_subscription_id: existing.no,
+          customer_id: customerId,
+          plan_id: planId,
+          contract_id: contractId,
+          contract_item_id: itemId,
+          term,
+          start_date: startDate,
+          ...(trialMonths === "0" ? {} : { trial_months: Number(trialMonths) }),
+        });
+        onSaved("已创建承接订阅,原订阅保留为历史记录。");
+      } else {
+        const created = await orderCreate({
+          customer_id: customerId,
+          plan_id: planId,
+          contract_id: contractId,
+          contract_item_id: itemId,
+          term,
+          start_date: startDate,
+          ...(trialMonths === "0" ? {} : { trial_months: Number(trialMonths) }),
+        });
+        onSaved(`订阅已创建(${created.subscription_id}),等待网络开通回填。`);
+      }
+    } catch (cause) {
+      setError((cause as Error).message);
+    } finally {
+      setPending(false);
+    }
+  }
+
+  const title = context.mode === "new" ? "新增订阅" : context.mode === "updown" ? `升降配 · ${existing?.planName ?? WORD_FETCH_FAILED}` : context.mode === "edit" ? `编辑订阅 · ${existing?.no}` : `订阅详情 · ${existing?.no}`;
+  return <Dialog title={title} onClose={onClose}>
+    <form className="customer-sub-form" onSubmit={submit}>
+      <p className="customer-sub-context">{customerName} · {customerId}{updown && <span>承接 {existing?.no}:原合同、条目、套餐已锁定(左侧),只需在右侧挑一个「新套餐」;提交后原订阅的有效期截到新订阅生效前一天。</span>}</p>
+      {contracts.error && <div className="customer-sub-alert" role="alert">可选合同取数失败:{contracts.error.message}</div>}
+      {originalContract.error && <div className="customer-sub-alert" role="alert">原合同明细取数失败:{originalContract.error.message}(服务构成条目暂按原订阅当前条目回显)</div>}
+      {plans.error && <div className="customer-sub-alert" role="alert">可选套餐取数失败:{plans.error.message}</div>}
+      {!writable && <div className="customer-sub-alert">{context.mode === "view" ? "详情为只读。需要变更时请新建订阅或办理升降配。" : existing?.editable === undefined ? "写口可见性未随记录下发,按只读呈现。" : "服务端判定本条只读(已到期或已开通计费)。需要变更时请新建订阅。"}</div>}
+      {/*
+        升降配的分栏(业主 2026-11-16):左「原订阅」只读、右「变更后」只有一个新套餐下拉。
+        原套餐此前也画成可选下拉,看着像「在改原订阅」,套餐切换反而看不出来 ⇒ 改成左侧锁定卡。
+        合同与条目不再单独暴露:它们由所选新套餐反推(后端按条目反查档位并强校验匹配)。
+      */}
+      {updown ? <div className="order-change">
+        <section className="order-change-card is-locked" aria-label="原订阅(只读)">
+          <header><h3>原订阅</h3><span>已锁定 · 不可修改</span></header>
+          <dl className="order-change-grid">
+            <div><dt>订单号</dt><dd>{textOf(existing?.no, WORD_UNCONFIGURED)}</dd></div>
+            <div><dt>套餐</dt><dd>{textOf(existing?.planName)}</dd></div>
+            <div><dt>合同编号</dt><dd>{contractText(existing?.contractNo, originalContract.data?.contract_no)}</dd></div>
+            <div><dt>服务构成条目</dt><dd>{textOf(existing?.contractItemId)}</dd></div>
+            <div><dt>订阅时长</dt><dd>{textOf(existing?.termLabel)}</dd></div>
+            <div><dt>期间</dt><dd>{textOf(existing?.start)} 至 {textOf(existing?.end)}</dd></div>
+            <div><dt>订阅价格</dt><dd>{textOf(existing?.annual.text)}</dd></div>
+            <div><dt>月结算标准</dt><dd>{textOf(existing?.settle.text)} / 月</dd></div>
+            <div><dt>分账号额度</dt><dd>{existing?.quotaSlots === undefined ? WORD_FETCH_FAILED : existing.quotaSlots === null ? WORD_UNCONFIGURED : `${existing.quotaSlots} 个`}</dd></div>
+          </dl>
+        </section>
+        <div className="order-change-pivot" aria-hidden="true"><ArrowRight size={18} /><span>变更为</span></div>
+        <section className="order-change-card is-target" aria-label="变更后">
+          <header><h3>变更后</h3><span>{pickedTarget ? "请核对带出的值" : "挑一个要变更到的套餐"}</span></header>
+          <label className="order-change-pick"><span>新套餐 <b>*</b></span>
+            <select value={targetKey} onChange={(event) => pickTarget(event.target.value)} disabled={!updownTargets.length} aria-label="选择要变更到的新套餐">
+              <option value="">{contracts.loading || plans.loading ? "正在读取可承接套餐…" : updownTargets.length ? "请选择新套餐" : "没有可承接的新套餐"}</option>
+              {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>)}
+            </select>
+          </label>
+          {pickedTarget ? <dl className="order-change-grid">
+            <div><dt>变更后套餐</dt><dd>{pickedTarget.planName}</dd></div>
+            <div><dt>承接合同</dt><dd>{contractText(pickedTarget.contractLabel, pickedTarget.contractInternal)}{pickedTarget.sameContract ? "(原合同)" : ""}</dd></div>
+            <div><dt>服务构成条目</dt><dd>{pickedTarget.itemId}</dd></div>
+            <div><dt>订阅价格</dt><dd>{pickedTarget.annualCents === null ? WORD_UNCONFIGURED : moneyCell(pickedTarget.annualCents).text}</dd></div>
+            <div><dt>月结算标准</dt><dd>{pickedTarget.settleCents === null ? WORD_UNCONFIGURED : `${moneyCell(pickedTarget.settleCents).text} / 月`}</dd></div>
+            <div><dt>分账号额度</dt><dd>{pickedTarget.quota === null ? WORD_UNCONFIGURED : `${pickedTarget.quota} 个`}</dd></div>
+            <div><dt>线路出口</dt><dd>{pickedTarget.exits?.length ? pickedTarget.exits.join("、") : WORD_UNCONFIGURED}</dd></div>
+          </dl> : <p className="order-change-note">原套餐与合同条目已锁定;选一个新套餐后,承接合同、条目、订阅价格、月结算与额度会随它带出。</p>}
+          {updownDelta && <div className="order-change-delta"><span className={`order-change-badge is-${updownDelta.tone}`}>{updownDelta.text}</span><span className="order-change-note">按年订阅价格对比</span></div>}
+          {!updownHasNew && !contracts.loading && !plans.loading && <p className="order-change-note is-warn">当前没有可承接的新套餐:原合同 {textOf(existing?.contractNo, originalContractId)} 下没有第二条已绑定档位的服务构成条目,该客户名下也没有其他可选合同。换档需先在第 1 步签一份带新条目的合同,再回到「升降配」。</p>}
+        </section>
+      </div> : <div className="customer-sub-fields">
+        <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>
+        <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>
+        <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>
+      </div>}
+      <div className="customer-sub-fields">
+        {!updown && <label>线路出口(随合同条目)<input readOnly value={exitsText} /></label>}
+        {!updown && <label>订阅方式<input readOnly value={modeText} title={ORDER_MODE_BY_CATEGORY} /></label>}
+        {context.mode === "edit" ? <label><span>订阅时长</span><input readOnly value={existing?.termLabel || WORD_UNCONFIGURED} /></label>
+          : <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>}
+        <label><span>生效日 <b>*</b></span><input disabled={locked} type="date" value={startDate} onChange={(event) => setStartDate(event.target.value)} /></label>
+        <label><span>结束日(服务端派生)</span><input readOnly value={updown && !pickedTarget ? "选定新套餐后按承接合同止期派生" : endText} title="预览=生效日折订阅时长(月末夹紧)再减一天,晚于合同止期则截到合同止期;落库值以服务端为准" /></label>
+        <label>订单号(随合同外部单号)<input readOnly value={orderText} /></label>
+        {!updown && <label>订阅价格<input readOnly value={annualText} title={ORDER_AMOUNT_TITLE} /></label>}
+        {!updown && <label>月结算标准<input readOnly value={settleText} title={ORDER_AMOUNT_TITLE} /></label>}
+        {!updown && <label>分账号额度<input readOnly value={quotaText} title="随所选档位的额度带出" /></label>}
+        <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>
+        {trialMonths !== "0" && <label>试用优惠金额(元/月)<input readOnly={!writable} inputMode="decimal" placeholder="选填,留空不套用正式月费" value={trialDiscount} onChange={(event) => setTrialDiscount(event.target.value)} /></label>}
+        <label>实际开通日<input readOnly value={locked ? (existing?.openedOn === undefined ? WORD_FETCH_FAILED : existing.openedOn || WORD_NOT_OPENED) : WORD_NOT_OPENED} /></label>
+      </div>
+      <p className="customer-sub-hint">{editing ? "编辑态只有「试用优惠期」与「试用优惠金额」两项可改,其余由服务端冻结:换套餐请走「升降配」承接,改价须另签新合同后新建订阅。" : updown ? "升降配只变更「套餐」这一项:原订阅的合同、条目、档位不可改,承接用的合同与条目随新套餐带出。原订阅在新订阅生效前一天结束,历史保留。" : `${ORDER_CREATE_READONLY_NOTE}(${ORDER_AMOUNT_TITLE})。合同期间、订单号与线路出口随合同条目带出,网络开通由运维流程回填。`}</p>
+      {error && <p className="ops-form-error" role="alert">{error}</p>}
+      <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>
+    </form>
+  </Dialog>;
+}
+
+/**
+ * 订阅叠加弹窗(手册 P5 步骤③):在旧订阅上**只改服务结束日期**,走 `/subscription/stack@v1`。
+ *
+ * 套餐、价格、月结算标准与本条订阅的其余字段一律只读呈现,⛔ 在此提交(`stack` 只收 end_date);
+ * 提交前先给出二次确认,确认后才调接口。
+ */
+export function StackEditor({ record, customerName, onClose, onSaved }: {
+  record: OrderView; customerName: string; onClose: () => void; onSaved: (message: string) => void;
+}) {
+  const [endDate, setEndDate] = useState("");
+  const [error, setError] = useState("");
+  const [pending, setPending] = useState(false);
+  const [confirming, setConfirming] = useState(false);
+
+  async function submit(event: FormEvent<HTMLFormElement>) {
+    event.preventDefault();
+    if (!endDate) { setError("请选择叠加后的服务结束日期。"); return; }
+    if (!confirming) { setConfirming(true); return; }
+    setPending(true);
+    setError("");
+    try {
+      await orderStack({ subscription_id: record.no, end_date: endDate });
+      onSaved(`叠加已生效:${record.no} 的服务结束日期改为 ${endDate}。`);
+    } catch (cause) {
+      setError((cause as Error).message);
+      setPending(false);
+      setConfirming(false);
+    }
+  }
+
+  return <Dialog title={`叠加 · ${record.planName ?? WORD_FETCH_FAILED}`} onClose={onClose}>
+    <form className="customer-sub-form" onSubmit={submit}>
+      <p className="customer-sub-context">{customerName} · {record.no} 承接本条订阅,只改服务结束日期。</p>
+      <div className="customer-sub-fields">
+        <label>套餐<input readOnly value={textOf(record.planName)} /></label>
+        <label>合同期间<input readOnly value={`${textOf(record.start)} 至 ${textOf(record.end)}`} /></label>
+        <label>当前结束日<input readOnly value={textOf(record.end)} /></label>
+        <label><span>叠加后结束日 <b>*</b></span><input type="date" disabled={confirming && pending} value={endDate} onChange={(event) => { setEndDate(event.target.value); setConfirming(false); setError(""); }} /></label>
+      </div>
+      <p className="customer-sub-hint">叠加在本条订阅上直接续期:套餐、订阅价格与月结算标准不变,期间由服务端按新结束日生效。</p>
+      {confirming && !error && <div className="customer-sub-alert" role="alertdialog">确认把服务结束日期由「{textOf(record.end)}」改为「{endDate}」?确认后立即生效。</div>}
+      {error && <p className="ops-form-error" role="alert">{error}</p>}
+      <footer><Button type="button" variant="outline" onClick={onClose}>{confirming ? "取消" : "关闭"}</Button><Button type="submit" disabled={pending || !endDate}>{confirming ? (pending ? "提交中…" : "确认叠加") : "下一步"}</Button></footer>
+    </form>
+  </Dialog>;
+}