Browse Source

feat(web): 套餐三分类前端——两值字典、目录分组、条目收敛与就地建档抽屉

- 字典:use_category 换 plan_family(link/addon),标签与文案统一;旧的
  「用途分类」筛选与展示位随列退役。
- 套餐目录:三页签按 plan_family 插分组行(跨境链路/附加项/未配置),
  addon 行带宽列恒显「—」;新增 PackagePlanEditor 抽屉,新增与编辑共用一套
  表单,交付形态切换即隐藏整组带宽字段(D-18)。
- 合同录入/详情:条目只剩「档位/交付形态(只读)/份数/出口」四格,
  价格与带宽不再出现;换价改走「先建自定义档再引用」;缺档时就地建档后
  草稿原样续填(D-16)。详情与列表读出建档人/建档团队(D-17)。
- 订阅与升降配:份数按形态收敛,addon 不给升降配入口;替换候选只探 link。
- contract-draft 增补 4 条用例:link 份数恒 1、addon 份数可 >1、份数 0/小数
  拦下、条目载荷只含四键(禁传键零残留)。

验证:npm test 130 条 Node 断言 + 77 条 Vitest(8 套件)全过。

Co-authored-by: Cursor <cursoragent@cursor.com>
cg 4 days ago
parent
commit
28554a11f1

+ 17 - 24
web-scaffold/src/components/OrderChangeDialogs.tsx

@@ -13,10 +13,10 @@
 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 { OPTIONS } 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_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";
@@ -152,27 +152,23 @@ export function OrderEditor({ customerId, customerName, context, onClose, onSave
     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,
+      plan_name: entry.plan_name ?? null,
+      item_family: entry.item_family ?? null,
       quantity: entry.quantity ?? null,
-      annual_price_cents: entry.annual_price_cents ?? null,
+      annual_price_cents: entry.sub_account_quota ?? 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,
+        item_family: existing.row.plan_family ?? null,
+        quantity: existing.row.quantity ?? 1,
         annual_price_cents: null,
         line_exits: existing.exits ?? null,
-        use_category: existing.row.use_category ?? null,
         available: true,
       });
     }
@@ -234,10 +230,10 @@ export function OrderEditor({ customerId, customerName, context, onClose, onSave
    * 升降配态后端按**新合同**反查条目(P5-D1 修正后:载荷可另选新合同),而同屏可选套餐若仍列全目录,
    * 用户就会选到合同里根本没有的档位,提交必吃 `KLT-M228`(P5-D2)⇒ 与新建态同规则收窄。
    */
-  const contractPlanIds = new Set(contractItems.map((entry) => entry.plan_id ?? entry.plan_id_derived ?? "").filter(Boolean));
+  const contractPlanIds = new Set(contractItems.map((entry) => entry.plan_id ?? "").filter(Boolean));
   const itemPlanId =
     context.mode === "new" || context.mode === "updown"
-      ? selectedItem?.plan_id ?? selectedItem?.plan_id_derived ?? null
+      ? selectedItem?.plan_id ?? null
       : null;
   const planChoices = rowsOf(plans.data).filter((item: OrderPlanOption) => {
     if (context.mode !== "new" && context.mode !== "updown") return true;
@@ -262,7 +258,7 @@ export function OrderEditor({ customerId, customerName, context, onClose, onSave
     const out: UpdownTarget[] = [];
     for (const contract of contractList) {
       for (const entry of rowsOf(contract.items)) {
-        const pid = entry.plan_id ?? entry.plan_id_derived ?? "";
+        const pid = entry.plan_id ?? "";
         if (!pid) continue;
         const key = `${contract.contract_id}::${entry.item_id}::${pid}`;
         if (seen.has(key)) continue;
@@ -331,7 +327,7 @@ export function OrderEditor({ customerId, customerName, context, onClose, onSave
    * 不可叠加档(用途分类 ≠ 叠加增值)恒 1 —— 界面上也不显示该只读格。
    */
   const itemQuantity = context.mode === "new" ? (selectedItem?.quantity ?? 1) : 1;
-  const stackableItem = (selectedItem?.use_category ?? priceOf?.use_category ?? null) === "value_add";
+  const stackableItem = (selectedItem?.item_family ?? priceOf?.plan_family ?? null) === "addon";
   /** 引导句=三态之外的第四形态:还没选到能带出值的对象,⛔ 判成「取数失败」(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`,条目上才是真值)。 */
@@ -353,14 +349,11 @@ export function OrderEditor({ customerId, customerName, context, onClose, onSave
   })();
   /** 订阅方式只读格=服务端 `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;
+    /** I6 已停用(D-15):订阅方式不再由交付形态派生,新订阅该列恒为空。 */
+    const pending = "订阅方式不再派生(I6 已停用,新订阅不写该值)";
+    if (!locked) return planId ? pending : pickHint;
     if (existing?.modeLabel) return existing.modeLabel;
-    return existing?.row.sub_mode === undefined ? WORD_FETCH_FAILED : pending;
+    return existing?.row.sub_mode === undefined ? WORD_FETCH_FAILED : WORD_MODE_PENDING;
   })();
   /** D-72:结束日只读格此前恒显提示语,填了生效日也不预览(服务端实会派生)。 */
   const endText = (() => {
@@ -505,12 +498,12 @@ export function OrderEditor({ customerId, customerName, context, onClose, onSave
         </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 || !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>
         <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>}
+        {!updown && <label>订阅方式<input readOnly value={modeText} title="订阅方式不再随交付形态派生(I6 已停用)" /></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>

+ 294 - 0
web-scaffold/src/components/PackagePlanEditor.tsx

@@ -0,0 +1,294 @@
+import { useEffect, useId, useMemo, useState, type FormEvent } from "react";
+import { Info, LockKeyhole, Plus, X } from "lucide-react";
+import { FetchError } from "./fetchError";
+import { FIXED_PLAN_LOCKED_FIELDS, PLAN_COST_ITEM_SAVE_NOTE, WORD_FETCH_FAILED } from "../lib/api/lockedCopy";
+import { catalogCreate, catalogCustomerOptions, catalogUpdate, planCostItemList, planCostItemSave, rowsOf } from "../lib/api/bos";
+import type { CatalogPlanRow, IpBandwidthTierListResult, PlanCostItemRow } from "../lib/api/types";
+import { ApiError } from "../lib/api/http";
+import { useLoad, type Load } from "../lib/useLoad";
+import { PLAN_FAMILY } from "../lib/api/labels";
+import { IP_TIER_UNCOMMITTED } from "../domain/contract-items";
+
+/** 目录档位编辑器(套餐页新增/编辑与合同页「就地新建本客户自定义档」共用)。 */
+export type EditorState = { plan?: CatalogPlanRow; owner: string | null; planKind?: "fixed" | "custom"; lockOwner?: boolean };
+export type EditorValues = {
+  name: string; family: string; owner: string; annualPrice: string; quota: string;
+  bandwidthMode: "committed" | "uncommitted" | ""; upload: string; download: string; description: string;
+};
+/** 成本项行=`plan_cost_item` 真实字段面(⛔ 本地「份数」口径,后端无该列)。 */
+type CostDraft = { item_name: string; amount: string; billing_unit: string; remark: string };
+
+const costDraftOf = (row: PlanCostItemRow): CostDraft => ({
+  item_name: row.item_name ?? "",
+  amount: row.amount_cents === null || row.amount_cents === undefined ? "" : String(row.amount_cents / 100),
+  billing_unit: row.billing_unit ?? "",
+  remark: row.remark ?? "",
+});
+
+const costRowOf = (draft: CostDraft): PlanCostItemRow => ({
+  item_name: draft.item_name.trim(),
+  amount_cents: draft.amount.trim() === "" ? null : Math.round(Number(draft.amount) * 100),
+  billing_unit: draft.billing_unit.trim() || null,
+  category: null,
+  remark: draft.remark.trim() || null,
+});
+
+export function formOf(plan: CatalogPlanRow | undefined, owner: string | null): EditorValues {
+  const committed = plan?.bandwidth_committed;
+  return {
+    name: plan?.plan_name ?? "",
+    family: plan?.plan_family ?? (owner === null ? "link" : ""),
+    owner: plan?.customer_id ?? owner ?? "",
+    annualPrice: plan?.annual_price_cents === undefined || plan.annual_price_cents === null ? "" : String(plan.annual_price_cents / 100),
+    quota: plan?.sub_account_quota === undefined || plan.sub_account_quota === null ? "" : String(plan.sub_account_quota),
+    bandwidthMode: committed === undefined ? "" : committed ? "committed" : "uncommitted",
+    upload: plan?.bandwidth_up_mbps === null || plan?.bandwidth_up_mbps === undefined ? "" : String(plan.bandwidth_up_mbps),
+    download: plan?.bandwidth_down_mbps === null || plan?.bandwidth_down_mbps === undefined ? "" : String(plan.bandwidth_down_mbps),
+    description: plan?.plan_desc ?? "",
+  };
+}
+
+const tierKeyOf = (mbps: number | null) => (mbps === null ? IP_TIER_UNCOMMITTED : `mbps-${mbps}`);
+
+function CatalogInfo({ label, children }: { label: string; children: string }) {
+  const id = useId();
+  return <>
+    <button type="button" className="catalog-info" aria-label={label} aria-describedby={id}><Info size={15} aria-hidden="true" /></button>
+    <span id={id} className="catalog-info-tip" role="tooltip">{children}</span>
+  </>;
+}
+
+export function PackagePlanEditor({ state, tiers, onClose, onSaved }: {
+  state: EditorState; tiers: Load<IpBandwidthTierListResult>; onClose: () => void; onSaved: (message: string, savedPlan: CatalogPlanRow | null) => void;
+}) {
+  const original = state.plan;
+  /** 锁定:被引用冻结(K204);页面放开名称/说明/成本项,服务端裁决后原样回显拒绝原因。 */
+  const locked = Boolean(original && original.frozen === true);
+  const isCustom = original ? original.plan_kind === "custom" : (state.planKind ?? (state.owner === null ? "fixed" : "custom")) === "custom";
+  const ownerLocked = Boolean(state.lockOwner);
+  const settlementId = useId();
+  const [values, setValues] = useState(() => formOf(original, state.owner));
+  const [costs, setCosts] = useState<CostDraft[]>([]);
+  const [costsDirty, setCostsDirty] = useState(false);
+  const [error, setError] = useState("");
+  const costLoad = useLoad(
+    () => (original ? planCostItemList({ plan_id: original.plan_id }).then(rowsOf) : Promise.resolve([] as PlanCostItemRow[])),
+    [original?.plan_id],
+  );
+  useEffect(() => {
+    if (original && costLoad.data && !costsDirty) setCosts(costLoad.data.map(costDraftOf));
+  }, [costLoad.data, original, costsDirty]);
+  useEffect(() => {
+    const dialog = document.getElementById("catalog-editor") as HTMLDialogElement | null;
+    const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+    if (!dialog) return;
+    const previousOverflow = document.body.style.overflow;
+    document.body.style.overflow = "hidden";
+    dialog.showModal();
+    return () => { dialog.close(); document.body.style.overflow = previousOverflow; previous?.focus(); };
+  }, []);
+  /** 归属客户可选项:后端下发的操作人可见客户集合,⛔ 前端拼权限。 */
+  const customerOptions = useLoad(() => catalogCustomerOptions().then(rowsOf), []);
+  const field = <K extends keyof EditorValues>(key: K, value: EditorValues[K]) => {
+    setValues((current) => ({ ...current, [key]: value }));
+    setError("");
+  };
+  /** 带宽档位快捷(2026-11-17 业主裁定):套餐配置里维护的档位即带宽权益的预设备选。
+   *  点一条=上下行同值填入;「不承诺带宽」档只切口径、⛔ 清空两格(同 CU-D5 的置灰不清空纪律)。 */
+  const tierPresets = useMemo(() => {
+    const seen = new Set<string>();
+    const rows: { key: string; label: string; mbps: number | null }[] = [];
+    for (const item of tiers.data?.items ?? []) {
+      const key = tierKeyOf(item.bandwidth_tier_mbps ?? null);
+      if (seen.has(key)) continue;
+      seen.add(key);
+      rows.push({ key, label: item.bandwidth_tier_mbps === null ? "不承诺带宽" : item.tier_name || `${item.bandwidth_tier_mbps} 兆`, mbps: item.bandwidth_tier_mbps ?? null });
+    }
+    return rows;
+  }, [tiers.data]);
+  const applyTier = (mbps: number | null) => {
+    setValues((current) => mbps === null
+      ? { ...current, bandwidthMode: "uncommitted" }
+      : { ...current, bandwidthMode: "committed", upload: String(mbps), download: String(mbps) });
+    setError("");
+  };
+  async function submit(event: FormEvent<HTMLFormElement>) {
+    event.preventDefault();
+    const name = values.name.trim();
+    const owner = state.owner === null ? null : values.owner;
+    if (!name) { setError("请填写套餐名称。"); return; }
+    if (owner !== null && !owner) { setError("请选择归属客户。"); return; }
+    if (costLoad.error && costsDirty) { setError("成本项取数失败,整段保存会覆盖后端构成,请重试或放弃本次改动。"); return; }
+    if (!values.family) { setError("请选择交付形态(跨境链路/附加项)。"); return; }
+    const isLink = values.family === "link";
+    let annualPrice = 0;
+    let quota = 0;
+    let upload: number | null = null;
+    let download: number | null = null;
+    if (!locked) {
+      if (!/^\d+(?:\.\d{1,2})?$/.test(values.annualPrice) || !Number.isFinite(Number(values.annualPrice)) || Number(values.annualPrice) < 0 || Number(values.annualPrice) > 10_000_000) {
+        setError("年订阅价格需为非负金额。"); return;
+      }
+      annualPrice = Number(values.annualPrice);
+      if (isLink) {
+        if (!/^\d+$/.test(values.quota) || Number(values.quota) <= 0) { setError("跨境链路档的分账号额度须为正整数。"); return; }
+        quota = Number(values.quota);
+        if (values.bandwidthMode === "") { setError("请选择带宽口径(承诺或不承诺)。"); return; }
+        if (values.bandwidthMode === "committed") {
+          // 文案分档(18 册 R-3):缺格 ⇒ 指名填哪一向;越界 ⇒ 1–1000。两种情形⛔ 共用一句。
+          if (!values.upload.trim()) { setError("请填写上行带宽。"); return; }
+          if (!values.download.trim()) { setError("请填写下行带宽。"); return; }
+          upload = Number(values.upload);
+          download = Number(values.download);
+          if (!/^\d+$/.test(values.upload) || !/^\d+$/.test(values.download) || upload < 1 || upload > 1000 || download < 1 || download > 1000) {
+            setError("上行和下行带宽须分别为 1–1000 Mbps 的整数。"); return;
+          }
+        }
+      } else {
+        // 附加项额度恒 0、不设任何带宽列(D-15/D-18)。
+        quota = 0;
+      }
+    }
+    if (costs.some((cost) => !cost.item_name.trim() || (cost.amount.trim() !== "" && !/^\d+(?:\.\d{1,2})?$/.test(cost.amount.trim())))) {
+      setError("成本项需填写名称,金额留空表示未配置、否则为非负金额。"); return;
+    }
+    const costRows = costs.map(costRowOf);
+    /** 契约:开关关闭⇒上行/下行两格⛔ 提交(服务端记 FALSE +两列 NULL)。 */
+    const bandwidth = isLink
+      ? values.bandwidthMode === "committed" && upload !== null && download !== null
+        ? { bandwidth_committed: true, bandwidth_up_mbps: upload, bandwidth_down_mbps: download }
+        : { bandwidth_committed: false }
+      : { bandwidth_committed: false };
+    try {
+      if (!original) {
+        const created = await catalogCreate({
+          plan_kind: owner === null ? "fixed" : "custom",
+          plan_name: name,
+          plan_family: values.family,
+          annual_price_cents: Math.round(annualPrice * 100),
+          sub_account_quota: quota,
+          ...bandwidth,
+          ...(owner ? { customer_id: owner } : {}),
+          ...(values.description.trim() ? { plan_desc: values.description.trim() } : {}),
+          ...(costRows.length ? { cost_items: costRows } : {}),
+        });
+        /** 就地新建的调用方要拿新档继续填条目 ⇒ 回一份最小行(字段面与列表行同键)。 */
+        onSaved(`${name}已新建。`, {
+          plan_id: created.plan_id,
+          plan_name: name,
+          plan_kind: owner === null ? "fixed" : "custom",
+          plan_family: values.family,
+          annual_price_cents: Math.round(annualPrice * 100),
+          sub_account_quota: quota,
+          bandwidth_committed: bandwidth.bandwidth_committed ? true : false,
+          bandwidth_up_mbps: (bandwidth as { bandwidth_up_mbps?: number | null }).bandwidth_up_mbps ?? null,
+          bandwidth_down_mbps: (bandwidth as { bandwidth_down_mbps?: number | null }).bandwidth_down_mbps ?? null,
+          customer_id: owner || null,
+          status: "active",
+          created_at: "",
+          row_version: "",
+        });
+        return;
+      }
+      await catalogUpdate({
+        plan_id: original.plan_id,
+        plan_name: name,
+        plan_desc: values.description.trim(),
+        ...(locked ? {} : {
+          annual_price_cents: Math.round(annualPrice * 100),
+          sub_account_quota: quota,
+          ...bandwidth,
+        }),
+        ...(original.row_version === undefined || original.row_version === null || original.row_version === "" ? {} : { row_version: Number(original.row_version) }),
+      });
+      if (costsDirty) await planCostItemSave({ plan_id: original.plan_id, items: costRows });
+      onSaved(`${name}已保存。`, original);
+    } catch (e) {
+      setError(e instanceof ApiError ? e.message : "保存失败,请稍后重试。");
+    }
+  }
+  const settlement = locked
+    ? (original?.monthly_settle_cents === null || original?.monthly_settle_cents === undefined ? "" : String(original.monthly_settle_cents / 100))
+    : values.annualPrice && /^\d+(?:\.\d{1,2})?$/.test(values.annualPrice)
+      ? (Math.floor(Math.round(Number(values.annualPrice) * 100) / 12) / 100).toFixed(2)
+      : "";
+  const isLinkValue = values.family === "link";
+  return <dialog id="catalog-editor" className="catalog-editor" aria-labelledby="catalog-editor-title" onCancel={onClose} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
+    <header className="catalog-editor-head"><div><span>{isCustom ? "客户专属套餐" : "公共固定套餐"}</span><h2 id="catalog-editor-title">{original ? "编辑套餐档位" : "新增套餐档位"}</h2></div><button type="button" aria-label="关闭" className="catalog-icon-button" onClick={onClose}><X size={19} /></button></header>
+    <form onSubmit={submit} className="catalog-editor-body">
+      {locked && <div className="catalog-locked-note"><LockKeyhole size={18} /><p>已被 {original?.referred_count ?? "—"} 处引用,字段「{FIXED_PLAN_LOCKED_FIELDS.join("、")}」已锁定;调整价格或额度请新建档位,再升级订阅。</p></div>}
+      <section><h3><span>01</span> 基本信息</h3><label>套餐名称 <em>*</em><input autoFocus required maxLength={60} value={values.name} onChange={(event) => field("name", event.target.value)} placeholder="输入套餐名称" /></label>
+        <div className="catalog-editor-grid">
+          <label>交付形态 <em>*</em>
+            <select disabled={Boolean(original) || locked} value={values.family} onChange={(event) => field("family", event.target.value)}>
+              {!values.family && <option value="">未配置</option>}
+              {Object.entries(PLAN_FAMILY).map(([value, text]) => <option key={value} value={value}>{text}</option>)}
+            </select>
+          </label>
+          <label>订阅周期<input disabled value="按年" /></label>
+        </div>
+        {isCustom && <label>归属客户 <em>*</em>
+          <select disabled={locked || ownerLocked || Boolean(original)} required value={values.owner} onChange={(event) => field("owner", event.target.value)}>
+            <option value="">{customerOptions.loading ? "载入中…" : customerOptions.error ? WORD_FETCH_FAILED : "选择客户"}</option>
+            {(customerOptions.data ?? []).map((item) => <option key={item.customer_id} value={item.customer_id}>{item.customer_name}</option>)}
+          </select>
+          {customerOptions.error && <FetchError message={customerOptions.error.message} onRetry={customerOptions.reload} className="catalog-editor-error" />}
+        </label>}
+      </section>
+      <section>
+        <h3><span>02</span> 价格与额度</h3>
+        <div className="catalog-editor-grid">
+          <label>
+            年订阅价格<span className="sr-only">(元)</span> <em>*</em>
+            <span className="catalog-price-input">
+              <input disabled={locked} inputMode="decimal" value={values.annualPrice} onChange={(event) => field("annualPrice", event.target.value)} placeholder="0.00" />
+              <span className="catalog-price-unit" aria-hidden="true">元</span>
+            </span>
+          </label>
+          <div>
+            <div className="catalog-heading-with-info">
+              <label htmlFor={settlementId}>月结算标准<span className="sr-only">(元)</span></label>
+              <CatalogInfo label="月结算标准说明">年订阅价格除以 12 后向下取整到分。订阅签约时可按合同冻结价格。</CatalogInfo>
+            </div>
+            <span className="catalog-price-input">
+              <input id={settlementId} disabled value={settlement} placeholder="由年价自动计算" />
+              <span className="catalog-price-unit" aria-hidden="true">元</span>
+            </span>
+          </div>
+        </div>
+        {isLinkValue
+          ? <label>分账号额度(个) <em>*</em><input disabled={locked} inputMode="numeric" value={values.quota} onChange={(event) => field("quota", event.target.value)} placeholder="0" /></label>
+          : <label>分账号额度(个)<input disabled value="0(附加项额度恒 0,D-15)" /></label>}
+      </section>
+      {isLinkValue && <section><h3><span>03</span> 带宽与权益</h3><label className="catalog-bandwidth-field">带宽口径<select disabled={locked} value={values.bandwidthMode} onChange={(event) => field("bandwidthMode", event.target.value as EditorValues["bandwidthMode"])}>{values.bandwidthMode === "" && <option value="">未配置</option>}<option value="committed">承诺上下行带宽</option><option value="uncommitted">不承诺带宽</option></select></label>
+        {/* 两格**常驻**、非承诺时置灰但⛔ 清空:卸载再挂载会让回切后输入框回读空串
+            (18 册 CU-D5),且 DOM 与 state 脱节。 */}
+        <div className="catalog-editor-grid"><label>上行带宽(Mbps)<input disabled={locked || values.bandwidthMode !== "committed"} inputMode="numeric" value={values.upload} onChange={(event) => field("upload", event.target.value)} placeholder="1–1000" /></label><label>下行带宽(Mbps)<input disabled={locked || values.bandwidthMode !== "committed"} inputMode="numeric" value={values.download} onChange={(event) => field("download", event.target.value)} placeholder="1–1000" /></label></div>
+        {!locked && tierPresets.length > 0 && <div className="catalog-bandwidth-presets">
+          <span className="catalog-bandwidth-presets-label">档位快捷<small>(取自「线路出口」Tab 的带宽档位)</small></span>
+          <div className="catalog-bandwidth-presets-list">
+            {tierPresets.map((preset) => {
+              const on = preset.mbps === null
+                ? values.bandwidthMode === "uncommitted"
+                : values.bandwidthMode === "committed" && values.upload.trim() === String(preset.mbps) && values.download.trim() === String(preset.mbps);
+              return <button key={preset.key} type="button" aria-pressed={on} className={`catalog-bandwidth-preset${on ? " is-on" : ""}`} title={preset.mbps === null ? "口径设为不承诺带宽(两格仅置灰,⛔ 不清空)" : `上下行各 ${preset.mbps} Mbps`} onClick={() => applyTier(preset.mbps)}>{preset.label}</button>;
+            })}
+          </div>
+        </div>}
+        <p>带宽作为套餐属性保存,首期不按带宽拆分计价。</p></section>}
+      <section><h3><span>{isLinkValue ? "04" : "03"}</span> 套餐说明</h3><label>套餐说明<textarea rows={4} value={values.description} onChange={(event) => field("description", event.target.value)} placeholder="说明适用场景、服务权益和报价口径" /></label></section>
+      <section className="catalog-cost-editor">
+        <div className="catalog-heading-with-info">
+          <h3><span>{isLinkValue ? "05" : "04"}</span> 月成本项</h3>
+          <CatalogInfo label="月成本项说明">{`${PLAN_COST_ITEM_SAVE_NOTE}(整段全量替换,逐行增删不单独提交)`}</CatalogInfo>
+        </div>
+        {costLoad.error && <FetchError message={costLoad.error.message} onRetry={costLoad.reload} className="catalog-editor-error" />}
+        {costs.map((cost, index) => <div className="catalog-cost-editor-row" key={index}><input aria-label={`成本项 ${index + 1} 名称`} maxLength={60} value={cost.item_name} onChange={(event) => { setCostsDirty(true); setCosts((current) => current.map((item, i) => i === index ? { ...item, item_name: event.target.value } : item)); }} placeholder="成本项名称" /><span className="catalog-price-input"><input aria-label={`成本项 ${index + 1} 金额`} inputMode="decimal" value={cost.amount} onChange={(event) => { setCostsDirty(true); setCosts((current) => current.map((item, i) => i === index ? { ...item, amount: event.target.value } : item)); }} placeholder="金额" /></span><button aria-label={`移除成本项 ${index + 1}`} onClick={() => { setCostsDirty(true); setCosts((current) => current.filter((_, i) => i !== index)); }} type="button"><X size={16} /></button></div>)}
+        <button className="catalog-cost-add" onClick={() => { setCostsDirty(true); setCosts((current) => [...current, { item_name: "", amount: "", billing_unit: "", remark: "" }]); }} type="button"><Plus size={15} /> 添加成本项</button>
+      </section>
+      {error && <p className="catalog-editor-error" role="alert">{error}</p>}
+      <footer><button type="button" className="catalog-button catalog-button-secondary" onClick={onClose}>取消</button><button type="submit" className="catalog-button catalog-button-primary">{original ? "保存修改" : "新建套餐"}</button></footer>
+    </form>
+  </dialog>;
+}
+

+ 5 - 6
web-scaffold/src/components/ReferenceDrawer.tsx

@@ -18,7 +18,7 @@ import { FetchError } from "./fetchError";
 import { OpsDrawer, OpsStatus } from "./OperationsKit";
 import { catalogGet, customerGet, orderGet, orderGetList } from "../lib/api/bos";
 import type { CatalogPlanRow, OrderGetResult, OrderListResult } from "../lib/api/types";
-import { ACCT_STATUS, PLAN_KIND, ORDER_MODE, ORDER_STATUS, SUBJECT_TYPE, TERM, USE_CATEGORY, label } from "../lib/api/labels";
+import { ACCT_STATUS, PLAN_FAMILY, PLAN_KIND, ORDER_MODE, ORDER_STATUS, SUBJECT_TYPE, TERM, label } from "../lib/api/labels";
 import { bandwidthTextOfRow, moneyCell } from "../lib/package-catalog";
 import { detailLinkState } from "../lib/detail-navigation";
 import { fmtDate } from "../lib/ticket";
@@ -174,8 +174,7 @@ function PlanPanel({ planId, onOpenCustomer }: {
     <div className="ops-detail-hero">
       <div>
         <span className="ops-tag tone-brand">{label(PLAN_KIND, p.plan_kind) || missing(p.plan_kind)}</span>
-        {p.use_category && <span className="ops-tag tone-info">{label(USE_CATEGORY, p.use_category) || p.use_category}</span>}
-        {p.derived_from_contract_item_id && <span className="ops-tag tone-neutral">合同条目派生</span>}
+        {p.plan_family && <span className="ops-tag tone-info">{label(PLAN_FAMILY, p.plan_family) || p.plan_family}</span>}
       </div>
       <h3>{missing(p.plan_name)}</h3>
       <p>{p.plan_id} · {p.customer_name ?? "平台公共档"}</p>
@@ -186,7 +185,7 @@ function PlanPanel({ planId, onOpenCustomer }: {
         <Row label="套餐编号">{p.plan_id}</Row>
         <Row label="套餐名称">{missing(p.plan_name)}</Row>
         <Row label="套餐种类">{label(PLAN_KIND, p.plan_kind) || missing(p.plan_kind)}</Row>
-        <Row label="用途分类">{label(USE_CATEGORY, p.use_category) || missing(p.use_category)}</Row>
+        <Row label="交付形态">{label(PLAN_FAMILY, p.plan_family) || missing(p.plan_family)}</Row>
         <Row label="年订阅价">{annual.text}</Row>
         <Row label="月结算标准">{monthly.text}</Row>
         <Row label="月成本">{cost.text}</Row>
@@ -243,7 +242,7 @@ function OrderPanel({ orderId, onOpenCustomer }: {
       <div>
         <OpsStatus tone={statusTone(s.status)}>{label(ORDER_STATUS, s.status) || missing(s.status)}</OpsStatus>
         {s.plan_kind && <span className="ops-tag tone-brand">{label(PLAN_KIND, s.plan_kind) || s.plan_kind}</span>}
-        {s.use_category && <span className="ops-tag tone-info">{label(USE_CATEGORY, s.use_category) || s.use_category}</span>}
+        {s.plan_family && <span className="ops-tag tone-info">{label(PLAN_FAMILY, s.plan_family) || s.plan_family}</span>}
       </div>
       <h3>{missing(s.plan_name ?? s.subscription_id)}</h3>
       <p>{s.subscription_id} · {period(s.start_date, s.end_date)}</p>
@@ -253,7 +252,7 @@ function OrderPanel({ orderId, onOpenCustomer }: {
       <dl className="ops-detail-grid">
         <Row label="订单号">{s.subscription_id}</Row>
         <Row label="套餐档">{missing(s.plan_name)}</Row>
-        <Row label="套餐种类 / 用途">{label(PLAN_KIND, s.plan_kind) || missing(s.plan_kind)} / {label(USE_CATEGORY, s.use_category) || missing(s.use_category)}</Row>
+        <Row label="套餐种类 / 形态">{label(PLAN_KIND, s.plan_kind) || missing(s.plan_kind)} / {label(PLAN_FAMILY, s.plan_family) || missing(s.plan_family)}</Row>
         <Row label="订阅方式">{s.sub_mode_label || label(ORDER_MODE, s.sub_mode) || missing(s.sub_mode)}</Row>
         <Row label="订阅时长">{label(TERM, s.term) || missing(s.term)}</Row>
         <Row label="订阅状态">{label(ORDER_STATUS, s.status) || missing(s.status)}</Row>

+ 55 - 5
web-scaffold/src/domain/__tests__/contract-draft.test.ts

@@ -66,7 +66,7 @@ describe("frozenChanges · 编辑口径守卫(两轴独立判定)", () => {
   it("服务构成按条目内容比较:改档位/数量/年价被拦", () => {
     const base = baseline();
     expect(frozenChanges({ ...base, items: [{ ...base.items[0], quantity: 2 }] }, base, allLocked)).toEqual(["服务构成"]);
-    expect(frozenChanges({ ...base, items: [{ ...base.items[0], annualPrice: "999.00" }] }, base, allLocked)).toEqual(["服务构成"]);
+    expect(frozenChanges({ ...base, items: [{ ...base.items[0], planFamily: "addon" }] }, base, allLocked)).toEqual(["服务构成"]);
     // 2026-11-17:IP 条目不属草稿(配置已下线)⇒ 只按服务构成判计费轴。
   });
 
@@ -190,8 +190,8 @@ describe("renewalPrefill · 续签带入(2026-11-17)", () => {
     row_version: "3",
     created_at: "2025-01-01T00:00:00Z",
     service_items: [
-      { item_id: "SI-000009", item_kind: "plan_based", plan_id: "CP-000001", plan_name: "标准套餐", quantity: 1, line_exits: ["香港"] },
-      { item_id: "SI-000010", item_kind: "custom_spec", account_count: 5, bandwidth_down_mbps: 100, bandwidth_up_mbps: 50, annual_price_cents: 600_000, use_category: "office", line_exits: ["新加坡"] },
+      { item_id: "SI-000009", plan_id: "CP-000001", plan_name: "标准套餐", item_family: "link", quantity: 1, line_exits: ["香港"] },
+      { item_id: "SI-000010", plan_id: "CP-000009", plan_name: "单独境外 IP", item_family: "addon", quantity: 2, line_exits: ["新加坡"] },
     ],
   };
 
@@ -206,8 +206,8 @@ describe("renewalPrefill · 续签带入(2026-11-17)", () => {
     expect(p.agentOrg).toBe("省公司");
     expect(p.items).toHaveLength(2);
     expect(p.items.every((item) => item.itemId === null)).toBe(true);
-    expect(p.items.map((item) => item.kind)).toEqual(["plan_based", "custom_spec"]);
-    expect(p.items[1].annualPrice).toBe("6000.00");
+    expect(p.items.map((item) => item.planFamily)).toEqual(["link", "addon"]);
+    expect(p.items[1].quantity).toBe(2);
   });
 
   it("⛔ 带编号/外部单号/结束日/附件/交接日期;生效日取旧止期次日(不早于业务当天)", () => {
@@ -294,3 +294,53 @@ describe("checkItemExits · 出口单选(2026-11-17)", () => {
     }
   });
 });
+
+describe("buildContractWrite · 交付形态只决定份数(D-15/D-18)", () => {
+  const withFamily = (family: string, quantity: number) => {
+    const base = baseline();
+    return { ...base, items: [{ ...base.items[0], planFamily: family, quantity }] };
+  };
+
+  it("link 档份数恒 1:填 2 即拦下并点名跨境链路", () => {
+    const blocked = buildContractWrite(withFamily("link", 2));
+    expect(blocked.ok).toBe(false);
+    if (!blocked.ok) expect(blocked.error).toContain("跨境链路档:份数恒为 1");
+  });
+
+  it("addon 档份数可 > 1:3 份放行,等于 3 个 IP 权益", () => {
+    const built = buildContractWrite(withFamily("addon", 3));
+    expect(built.ok).toBe(true);
+    if (built.ok) expect(built.write.serviceItems[0].quantity).toBe(3);
+  });
+
+  it("份数 0/小数一律拦(两种形态同一句)", () => {
+    for (const quantity of [0, 1.5]) {
+      const blocked = buildContractWrite(withFamily("addon", quantity));
+      expect(blocked.ok).toBe(false);
+      if (!blocked.ok) expect(blocked.error).toContain("正整数");
+    }
+  });
+
+  it("条目载荷只有 item_id/plan_id/quantity/line_exits:⛔ 带价格、带宽、账号数、item_kind", () => {
+    const base = baseline();
+    const built = buildContractWrite({
+      ...base,
+      items: [{ ...base.items[0], planFamily: "addon", quantity: 2, exits: ["美国"] }],
+    });
+    expect(built.ok).toBe(true);
+    if (!built.ok) return;
+    const item = built.write.serviceItems[0] as Record<string, unknown>;
+    expect(Object.keys(item).sort()).toEqual(["item_id", "line_exits", "plan_id", "quantity"]);
+    for (const banned of [
+      "item_kind",
+      "item_family",
+      "annual_price_cents",
+      "monthly_settle_cents",
+      "account_count",
+      "bandwidth_up_mbps",
+      "bandwidth_down_mbps",
+    ]) {
+      expect(item[banned]).toBeUndefined();
+    }
+  });
+});

+ 23 - 55
web-scaffold/src/domain/contract-draft.ts

@@ -20,23 +20,18 @@ import {
   type ContractRequiredKey,
 } from "./contract-items";
 
-/** 服务条目编辑态:直接对齐 `contract/service_item` 写入口径。 */
+/**
+ * 服务条目编辑态:D-15 后条目只剩「档位 × 份数 × 出口」。
+ *
+ * `planFamily` 只做界面判据(`link` 份数恒 1、`addon` 份数可 > 1、IP 汇总只看 `addon`),
+ * 提交时⛔ 回传——形态由后端从所引档位带入(`item_family`)。
+ */
 export type ItemDraft = {
-  kind: "plan_based" | "custom_spec";
   itemId?: string | null;
   planId: string;
   planName: string;
+  planFamily: string;
   quantity: number;
-  accountCount: number;
-  bwDown: number;
-  bwUp: number;
-  annualPrice: string;
-  /**
-   * D-32:自定义规格式条目的用途分类。此前录入表单⛔ 该字段 ⇒ 派生自定义档
-   * `catalog_plan.use_category` 恒 NULL,订阅派生只能显示「用途分类未配置」。
-   * 套餐式条目不录入(值由所引目录档带出,服务端回落)。
-   */
-  useCategory: string;
   exits: string[];
   /** 被替换的原订阅(空串=按新订阅开通);进 `service_items[].succession`,仅新建合同受理。 */
   replacesSubscriptionId: string;
@@ -75,15 +70,10 @@ export const REQUIRED_KEY_BY_DRAFT: Partial<Record<keyof ContractDraft, Contract
 };
 
 export const emptyItem = (): ItemDraft => ({
-  kind: "plan_based",
   planId: "",
   planName: "",
+  planFamily: "",
   quantity: 1,
-  accountCount: 0,
-  bwDown: 0,
-  bwUp: 0,
-  annualPrice: "",
-  useCategory: "",
   exits: [],
   replacesSubscriptionId: "",
   replacementCustomized: false,
@@ -195,18 +185,12 @@ export const emptyDraft = (): ContractDraft => ({
 export const centsToInput = (cents: number | null | undefined) => (cents === null || cents === undefined ? "" : centsToYuanText(cents));
 
 const itemFromRow = (item: ContractServiceItem): ItemDraft => {
-  const custom = item.item_kind === "custom_spec" || !item.plan_id;
   return {
-    kind: custom ? "custom_spec" : "plan_based",
     itemId: item.item_id ?? null,
     planId: item.plan_id ?? "",
     planName: item.plan_name ?? "",
+    planFamily: item.item_family ?? "",
     quantity: item.quantity ?? 1,
-    accountCount: item.account_count ?? 0,
-    bwDown: item.bandwidth_down_mbps ?? 0,
-    bwUp: item.bandwidth_up_mbps ?? 0,
-    annualPrice: centsToInput(item.annual_price_cents),
-    useCategory: item.use_category ?? "",
     exits: item.line_exits ?? [],
     /** 读口回带的条目已落库,编辑合同⛔ 受理替换 ⇒ 草稿一律以「不替换」为基线。 */
     replacesSubscriptionId: "",
@@ -410,40 +394,24 @@ export function buildContractWrite(draft: ContractDraft): ContractWriteResult {
       if (item.replacementCustomized && !item.replacementConfirmed) {
         return { ok: false, error: `条目 ${index + 1}:所选为定制档,请勾选「确认为该定制档替换」后再提交。` };
       }
-      if (item.kind === "plan_based" && item.quantity !== 1) {
+      if (item.quantity !== 1) {
         return { ok: false, error: `条目 ${index + 1}:一条条目只生一份订阅,替换时档位数量须为 1(当前 ${item.quantity})。` };
       }
     }
-    if (item.kind === "plan_based") {
-      if (!item.planId) return { ok: false, error: `条目 ${index + 1} 请选择套餐档位。` };
-      if (!Number.isInteger(item.quantity) || item.quantity < 1) return { ok: false, error: `条目 ${index + 1} 的档位数量需为正整数。` };
-      /** 套餐式⛔ 回传年价/月结算(服务端从目录重取后回 11102)。 */
-      serviceItems.push({
-        item_id: item.itemId ?? undefined,
-        item_kind: "plan_based",
-        plan_id: item.planId,
-        quantity: item.quantity,
-        line_exits: item.exits,
-        ...(replaces ? { succession: { replaces_subscription_id: replaces } } : {}),
-      });
-    } else {
-      if (!Number.isInteger(item.accountCount) || item.accountCount < 1) return { ok: false, error: `条目 ${index + 1} 的账号数需为正整数。` };
-      if (item.bwUp < 0 || item.bwDown < 0 || item.bwUp > 1000 || item.bwDown > 1000) return { ok: false, error: `条目 ${index + 1} 的带宽需为 0–1000 Mbps。` };
-      if (!/^\d+(?:\.\d{1,2})?$/.test(item.annualPrice.trim()) || Number(item.annualPrice) <= 0) return { ok: false, error: `条目 ${index + 1} 为自定义规格,年价必填且需大于 0。` };
-      /** D-32:自定义规格无目录档可回落,用途分类不录=派生档恒 NULL。 */
-      if (!item.useCategory) return { ok: false, error: `条目 ${index + 1} 为自定义规格,请选择用途分类(订阅方式按它派生)。` };
-      serviceItems.push({
-        item_id: item.itemId ?? undefined,
-        item_kind: "custom_spec",
-        account_count: item.accountCount,
-        bandwidth_down_mbps: item.bwDown,
-        bandwidth_up_mbps: item.bwUp,
-        annual_price_cents: yuanTextToCents(item.annualPrice) ?? 0,
-        use_category: item.useCategory || undefined,
-        line_exits: item.exits,
-        ...(replaces ? { succession: { replaces_subscription_id: replaces } } : {}),
-      });
+    if (!item.planId) return { ok: false, error: `条目 ${index + 1} 请选择套餐档位。` };
+    if (!Number.isInteger(item.quantity) || item.quantity < 1) return { ok: false, error: `条目 ${index + 1} 的档位数量需为正整数。` };
+    /** D-15:`link` 份数恒 1(`addon` 份数即个数,可 > 1)。 */
+    if (item.planFamily === "link" && item.quantity !== 1) {
+      return { ok: false, error: `条目 ${index + 1} 为跨境链路档:份数恒为 1(当前 ${item.quantity})。` };
     }
+    /** ⛔ 回传年价/月结算/形态:服务端从目录重取(形态由档位带入)。 */
+    serviceItems.push({
+      item_id: item.itemId ?? undefined,
+      plan_id: item.planId,
+      quantity: item.quantity,
+      line_exits: item.exits,
+      ...(replaces ? { succession: { replaces_subscription_id: replaces } } : {}),
+    });
   }
 
   return {

+ 10 - 8
web-scaffold/src/lib/api/bos.ts

@@ -582,7 +582,7 @@ export const portalPlanBoard = (d: { view?: "board" | "list" } = {}) =>
 export const catalogCreate = (d: {
   plan_kind: string;
   plan_name: string;
-  use_category?: string;
+  plan_family?: string;
   annual_price_cents: number;
   sub_account_quota?: number;
   bandwidth_committed?: boolean;
@@ -597,12 +597,14 @@ export const catalogCreate = (d: {
 /**
  * 编辑套餐档位 [位](契约 §3.1 `/catalog/update@v1`)—— 服务端 diff 判冻结,命中锁定字段 ⇒ `K204`+`referred_count`。
  *
- * 改 `plan_name` 同事务同步未到期订阅 `plan_name`;派生档⛔ 不可编辑(含改名,`11103` 拒)。
+ * 改 `plan_name` 同事务同步未到期订阅 `plan_name`;`plan_kind`/`plan_family` 一律锁定(`K204`)。
  */
 export const catalogUpdate = (d: {
   plan_id: string;
   plan_name?: string;
   annual_price_cents?: number;
+  /** 月结算标准金额:未被引用(未冻结)时可录;冻结后进锁定集。 */
+  monthly_settle_cents?: number;
   sub_account_quota?: number;
   bandwidth_committed?: boolean;
   bandwidth_up_mbps?: number;
@@ -619,7 +621,7 @@ export const catalogGetList = (d?: {
   page_size?: number;
   keyword?: string;
   plan_kind?: string;
-  use_category?: string;
+  plan_family?: string;
   customer_id?: string;
 }) => list<CatalogListResult>("/catalog/get_list@v1", d, d);
 /** 套餐档位详情 [位]。 */
@@ -778,8 +780,8 @@ export const orderChange = (d: {
 /**
  * 替换候选探测 [位](`/subscription/replacement_candidates@v1`,2026-11-17)—— 只读。
  *
- * 合同新建页逐条判定「是否已有可替换的原订阅」:后端统一解析用途分类(`use_category` 优先,
- * 否则取档位)并做候选过滤(同客户 × 同分类 × 同出口、`active`/`pending`、非增值、未被替换过、
+ * 合同新建页逐条判定「是否已有可替换的原订阅」:后端只按档位 `plan_family` 解析并做候选过滤
+ * (同客户 × 同出口 × 双方均 `link`、`active`/`pending`、未被替换过、
  * **且期间与新订阅相交**),与保存期校验**同一份函数** ⇒ 前端⛔ 自造判据。
  * `start_date`/`end_date` 传新合同期间(开始日缺省=业务当天)——它是「替换 vs 到期续签」的唯一判据。
  * `index` 与 `service_items` 0 基下标对齐。
@@ -809,7 +811,7 @@ export const orderGetList = (d?: {
   page_size?: number;
   keyword?: string;
   status?: string;
-  use_category?: string;
+  plan_family?: string;
   term?: string;
 }) => list<OrderListResult>("/subscription/get_list@v1", d, d);
 /** 订阅详情 [位]。 */
@@ -903,13 +905,13 @@ export const orderDelete = (d: { subscription_id: string; snapshot_version?: str
 /**
  * 全部订阅列表 [位](`/subscription/list_all@v1`)—— 数据范围⛔ 合同可见性口径。
  *
- * 可按 `status`/`plan_kind`/`use_category`/`term`/`province_node_id` 过滤;关键词只搜套餐名称/编码。
+ * 可按 `status`/`plan_kind`/`plan_family`/`term`/`province_node_id` 过滤;关键词只搜套餐名称/编码。
  * 页面⛔ 提供客户名与合同编号搜索——这两个入口在页面上不渲染,出现即 `11103`。
  */
 export const orderListAll = (d?: {
   status?: string;
   plan_kind?: string;
-  use_category?: string;
+  plan_family?: string;
   term?: string;
   province_node_id?: string;
   keyword?: string;

+ 12 - 15
web-scaffold/src/lib/api/labels.ts

@@ -123,20 +123,17 @@ export const PLAN_KIND: Record<string, string> = {
   custom: "自定义套餐",
 };
 
-/** `catalog_plan.use_category` 用途分类——五值即固定字典,一期不建字典表、无维护入口。 */
-export const USE_CATEGORY: Record<string, string> = {
-  office: "通用办公",
-  live: "直播高需求",
-  ai: "AI 应用",
-  value_add: "叠加增值",
-  customized: "定制化",
+/**
+ * `catalog_plan.plan_family` 交付形态(D-15,两值固定字典,一期不建字典表、无维护入口)。
+ * `link`=跨境链路(额度 > 0、带带宽、份数恒 1);`addon`=附加项(额度 0、不设带宽、份数 ≥ 1)。
+ */
+export const PLAN_FAMILY: Record<string, string> = {
+  link: "跨境链路",
+  addon: "附加项",
 };
 
-/** `contract_service_item.item_kind` 条目形态(§5.3 两形态)。 */
-export const ITEM_KIND: Record<string, string> = {
-  plan_based: "套餐式",
-  custom_spec: "自定义式",
-};
+/** `contract_service_item.item_family` 条目形态——与档位 `plan_family` 同值域、同词。 */
+export const ITEM_FAMILY: Record<string, string> = PLAN_FAMILY;
 
 /**
  * `cost_item.category` 成本类别三值 —— [实] handler `cost.rs::CATEGORIES`
@@ -161,7 +158,7 @@ export const COST_CYCLE: Record<string, string> = {
   monthly: "每月",
 };
 
-/** `subscription.sub_mode` 订阅方式——由 `use_category` 派生并保存时冻结,⛔ 手工录入。 */
+/** `subscription.sub_mode` 订阅方式——I6 停用后不再派生(新行 NULL),仅作历史值展示。 */
 export const ORDER_MODE: Record<string, string> = {
   upgrade: "仅可升降配",
   stackable: "可叠加",
@@ -192,8 +189,8 @@ export const PAY_CYCLE: Record<string, string> = {
 /** 下拉选项表:值域顺序即展示顺序,⛔ 在页面里各写一份。 */
 export const OPTIONS: Record<string, { value: string; label: string }[]> = {
   plan_kind: Object.entries(PLAN_KIND).map(([value, label]) => ({ value, label })),
-  use_category: Object.entries(USE_CATEGORY).map(([value, label]) => ({ value, label })),
-  item_kind: Object.entries(ITEM_KIND).map(([value, label]) => ({ value, label })),
+  plan_family: Object.entries(PLAN_FAMILY).map(([value, label]) => ({ value, label })),
+  item_family: Object.entries(ITEM_FAMILY).map(([value, label]) => ({ value, label })),
   sub_mode: Object.entries(ORDER_MODE).map(([value, label]) => ({ value, label })),
   term: Object.entries(TERM).map(([value, label]) => ({ value, label })),
   sub_status: Object.entries(ORDER_STATUS).map(([value, label]) => ({ value, label })),

+ 1 - 1
web-scaffold/src/lib/api/ticket.ts

@@ -600,7 +600,7 @@ export type TicketDetail = {
     customer_id: string | null;
     plan_name: string | null;
     plan_kind: string | null;
-    use_category: string | null;
+    plan_family: string | null;
     sub_mode: string | null;
     line_exits: string | null;
     order_no: string | null;

+ 24 - 38
web-scaffold/src/lib/api/types.ts

@@ -1679,7 +1679,7 @@ export type CatalogPlanRow = {
   plan_id: string;
   plan_name: string;
   plan_kind: string;
-  use_category: string | null;
+  plan_family: string | null;
   annual_price_cents: number;
   sub_account_quota: number | null;
   bandwidth_committed: boolean | null;
@@ -1694,11 +1694,14 @@ export type CatalogPlanRow = {
   /** 月成本=年订阅价 ÷ 12 向下取整(三态:null ⇒ 配齐但值为空=未配置) */
   plan_cost_cents?: number | null;
   plan_cost_state?: ValueState;
-  /** 被引用后三字段冻结(用途分类/子账号配额/月结算标准金额) */
+  /** 被引用后三字段冻结(交付形态/子账号配额/月结算标准金额) */
   frozen?: boolean;
   referred_count?: number | null;
-  /** 非空=合同条目派生档 */
-  derived_from_contract_item_id?: string | null;
+  /** D-17 建档归属:账号 ID+快照团队 ID,以及读侧联查出的两个名称。 */
+  created_by?: string | null;
+  created_by_name?: string | null;
+  created_team_id?: string | null;
+  created_team_name?: string | null;
   source_label?: string | null;
   line_exits?: string[] | null;
   monthly_settle_cents?: number | null;
@@ -1802,31 +1805,20 @@ export type CatalogGetResult = CatalogPlanRow & {
 /** 合同服务构成条目(请求与应答同源)。 */
 export type ContractServiceItem = {
   item_id?: string;
-  item_kind?: string;
   plan_id?: string | null;
   quantity?: number;
-  account_count?: number;
-  bandwidth_up_mbps?: number;
-  bandwidth_down_mbps?: number;
+  /** 交付形态回落值:读侧随条目下发,写侧由后端从档位带入(⛔ 前端造值)。 */
+  item_family?: string | null;
   /** 线路出口:2026-11-17 起**单选**(恰 1 个);新建/修改条目多值由后端回 `KLT-L222`。 */
   line_exits?: string[];
-  /* ── 契约 §3.2:custom_spec 必带 annual_price_cents>0、monthly_settle_cents?;plan_based 两键必空 ── */
-  annual_price_cents?: number | null;
-  monthly_settle_cents?: number | null;
-  use_category?: string | null;
   /**
    * 契约内逐条替换(`contract/create@v1` 独有,编辑合同出现即拒):本条目的新订阅顶替哪份原订阅。
    * 只在新建合同受理;`start_date` 缺省=max(业务当天, 合同生效日),结束日恒取合同止期。
    */
   succession?: ContractSuccessionReq | null;
-  /** 用途分类取值来源:`item`=条目自持列,`plan`=回落所引目录档/派生档(D-32 读侧)。 */
-  use_category_source?: string | null;
   plan_name?: string | null;
   /** 所引目录档的分账号额度(D-22:⛔ 依赖目录列表接口才能显示账号数)。 */
   sub_account_quota?: number | null;
-  derived_plan_id?: string | null;
-  derived_plan_name?: string | null;
-  plan_id_derived?: string | null;
   remark?: string | null;
 };
 
@@ -1871,10 +1863,9 @@ export type ContractReplacementResult = {
 export type ReplacementProbeReq = {
   /** 0 基条目下标(缺省=数组位置)。 */
   index?: number;
-  item_kind?: string;
   plan_id?: string | null;
-  /** 缺省时后端回落档位的用途分类。 */
-  use_category?: string | null;
+  /** 缺省时后端回落档位的交付形态。 */
+  plan_family?: string | null;
   line_exits?: string[];
 };
 
@@ -1898,10 +1889,9 @@ export type ReplacementCandidate = {
 /** 一条探测的回执。 */
 export type ReplacementProbeResult = {
   index: number;
-  item_kind?: string | null;
   plan_id?: string | null;
-  /** 后端统一解析出的用途分类(`use_category` 优先,否则取档位)。 */
-  use_category: string;
+  /** 后端统一解析出的交付形态(取自档位)。 */
+  item_family: string;
   line_exit_key: string;
   line_exits: string[];
   /** 本次比对用的新订阅期间(=新合同期间;开始日缺省=业务当天)。 */
@@ -2014,8 +2004,8 @@ export type ContractOrderRef = {
   end_date: string | null;
   /** D-75:订阅方式(`subscription.sub_mode`,建单时由用途分类折算)。此前⛔ 下发 ⇒ 详情「方式」列恒「未配置」。 */
   sub_mode?: string | null;
-  /** 「方式」的判定依据(用途分类)。 */
-  use_category?: string | null;
+  /** 交付形态(随档位冻结)。 */
+  plan_family?: string | null;
   actual_opened_at?: string | null;
   /** D-76:三列随 `orders[]` 下发(整数分);`null`=该订阅确无该值,⛔ 冒充 0。 */
   annual_price_cents?: number | null;
@@ -2200,7 +2190,7 @@ export type OrderRow = {
   contract_item_id: string | null;
   plan_id: string | null;
   plan_name: string | null;
-  use_category: string | null;
+  plan_family: string | null;
   status: string;
   start_date: string | null;
   end_date: string | null;
@@ -2262,19 +2252,17 @@ export type OrderPlanOption = {
   plan_id: string;
   plan_name: string;
   plan_kind: string;
-  use_category: string | null;
+  /** 档位归属客户(固定档=null,自定义档=该客户)。 */
+  owner_customer_id?: string | null;
+  plan_family: string | null;
   annual_price_cents: number;
-  /** 月结算标准金额(`monthly_settle_of` 折算,只读带出;⛔ 进载荷)。 */
+  /** 月结算标准金额(`monthly_settle_of` 折算,只读带出)。 */
   monthly_settle_cents?: number | null;
   sub_account_quota: number | null;
-  bandwidth_committed: boolean | null;
-  bandwidth_up_mbps: number | null;
-  bandwidth_down_mbps: number | null;
   line_exits: string[] | null;
-  sub_mode: string | null;
-  sub_mode_label: string | null;
-  derived: boolean;
-  source_label: string | null;
+  /** 被引用次数/是否已首次引用(改档冻结判据)。 */
+  referred_count?: number | null;
+  first_referred?: boolean | null;
   available: boolean;
   unavailable_reason?: string | null;
 };
@@ -2282,14 +2270,12 @@ export type OrderPlanOption = {
 /** POST /subscription/contract_options@v1 的合同条目(⛔ 出参不含任何「月结算标准金额」键)。 */
 export type OrderContractItemOption = {
   item_id: string;
-  item_kind: string;
   plan_id: string | null;
   plan_name: string | null;
+  item_family: string | null;
   quantity: number | null;
-  plan_id_derived?: string | null;
   annual_price_cents: number | null;
   line_exits: string[] | null;
-  use_category: string | null;
   /** 条目可选性(后端已剔除「已有订阅的条目」,此处再给档位停用等原因)。 */
   available?: boolean | null;
   unavailable_reason?: string | null;

+ 28 - 35
web-scaffold/src/lib/contract-demo.ts

@@ -15,9 +15,20 @@ import { useLoad, type Load } from "./useLoad";
 
 export type ContractSource = "运营商同步" | "界面录入" | "批量导入";
 
-export type ContractItem =
-  | { type: "套餐"; pkg: string; qty: number; exits: string[]; ipCount: number; accounts?: number | null; bandwidth?: string | null; planItemId?: string | null; itemId?: string | null; useCategory?: string | null; useCategorySource?: string | null; derivedPlanName?: string | null; derivedPlanId?: string | null }
-  | { type: "自定义"; accounts: number; bwDown: number; bwUp: number; bwSym?: boolean; exits: string[]; ipCount: number; itemId?: string | null; useCategory?: string | null; useCategorySource?: string | null; derivedPlanName?: string | null; derivedPlanId?: string | null };
+/** 服务条目(D-15):只剩「档位 × 份数 × 出口」,形态来自档位 `plan_family`。 */
+export type ContractItem = {
+  type: "套餐";
+  pkg: string;
+  qty: number;
+  /** `link`/`addon`(档位交付形态)。 */
+  family: string | null;
+  exits: string[];
+  ipCount: number;
+  accounts?: number | null;
+  bandwidth?: string | null;
+  planItemId?: string | null;
+  itemId?: string | null;
+};
 
 export type DemoContract = {
   no: string;
@@ -51,8 +62,8 @@ export type DemoContract = {
   /** 关联订阅(详情口 `contract/get` 才有)。 */
   relatedOrders?: {
     orderId: string; planName: string | null; status: string; startDate: string | null; endDate: string | null;
-    /** D-75:订阅方式与判定依据(用途分类),随 `contract/get` 的 `orders[]` 下发。 */
-    orderMode?: string | null; useCategory?: string | null; actualOpenedAt?: string | null;
+    /** D-75:订阅方式(历史派生值)与交付形态,随 `contract/get` 的 `orders[]` 下发。 */
+    orderMode?: string | null; planFamily?: string | null; actualOpenedAt?: string | null;
     /** D-76:年订阅价/月结算标准(整数分)与订单号。 */
     annualPriceCents?: number | null; monthlySettleCents?: number | null; orderNo?: string | null;
     /** 关联关系落点(2026-11-17):签约条目与服务条目主键/替换来源。 */
@@ -84,7 +95,6 @@ export const contractStatusTone: Record<ContractStatus, StatusTone> = {
 /** 服务构成派生口径:套餐式账号数 = 档位额度 × 数量(按套餐名查目录),自定义式直接取账号数。 */
 export function contractAccountsOf(items: ContractItem[]): number {
   return items.reduce((sum, item) => {
-    if (item.type === "自定义") return sum + item.accounts;
     if (item.accounts !== undefined) return sum + (item.accounts ?? 0);
     const quota = initialCatalogPlans.find((plan) => plan.name === item.pkg)?.quota ?? 0;
     return sum + quota * item.qty;
@@ -100,12 +110,13 @@ export function contractExitsOf(items: ContractItem[]): string[] {
 }
 
 export function contractItemBandwidth(item: ContractItem): string {
-  if (item.type === "套餐") return item.bandwidth ?? initialCatalogPlans.find((plan) => plan.name === item.pkg)?.bandwidth ?? "按档位口径";
-  return `下 ${item.bwDown} / 上 ${item.bwUp} Mbps${item.bwSym ? "(单值按对称)" : ""}`;
+  // 附加项不设带宽(D-18);链路档带宽随目录档位。
+  if (item.family === "addon") return "不设带宽(附加项)";
+  return item.bandwidth ?? initialCatalogPlans.find((plan) => plan.name === item.pkg)?.bandwidth ?? "按档位口径";
 }
 
 export function contractItemBrief(item: ContractItem): string {
-  return item.type === "套餐" ? `${item.pkg} × ${item.qty}` : `自定义式 · 账号 ${item.accounts}`;
+  return `${item.pkg} × ${item.qty}`;
 }
 
 /* ------------------------------------------------------------------ *
@@ -135,37 +146,19 @@ export type ContractRowView = Omit<DemoContract, "source" | "file" | "opened" |
 
 /** 合同服务条目 → 页面两形态;套餐式的分账号额度需由目录额度换算,未取到=未配置。 */
 export function contractItemFromRow(item: ContractServiceItem, quotaById?: Record<string, number | null | undefined>): ContractItem {
-  const exits = item.line_exits ?? [];
-  if (item.item_kind === "custom_spec" || !item.plan_id) {
-    return {
-      type: "自定义",
-      accounts: item.account_count ?? 0,
-      bwDown: item.bandwidth_down_mbps ?? 0,
-      bwUp: item.bandwidth_up_mbps ?? 0,
-      exits,
-      ipCount: 0,
-      itemId: item.item_id ?? null,
-      useCategory: item.use_category ?? null,
-      useCategorySource: item.use_category_source ?? null,
-      derivedPlanName: item.derived_plan_name ?? null,
-      derivedPlanId: item.derived_plan_id ?? null,
-    };
-  }
   return {
     type: "套餐",
     pkg: item.plan_name ?? "",
     qty: item.quantity ?? 1,
-    exits,
-    ipCount: 0,
+    family: item.item_family ?? null,
+    exits: item.line_exits ?? [],
+    // 附加项份数即 IP 个数(D-15);链路档不计 IP。
+    ipCount: item.item_family === "addon" ? item.quantity ?? 1 : 0,
     // 账号额度优先取合同出参自带的档位额度(D-22:⛔ 依赖目录列表才显示得出来),目录表仅作回落
-    accounts: item.sub_account_quota ?? (quotaById ? quotaById[item.plan_id] ?? null : null),
+    accounts: item.sub_account_quota ?? (item.plan_id && quotaById ? quotaById[item.plan_id] ?? null : null),
     bandwidth: null,
-    planItemId: item.plan_id,
+    planItemId: item.plan_id ?? null,
     itemId: item.item_id ?? null,
-    useCategory: item.use_category ?? null,
-    useCategorySource: item.use_category_source ?? null,
-    derivedPlanName: item.derived_plan_name ?? null,
-    derivedPlanId: item.derived_plan_id ?? null,
   };
 }
 
@@ -218,7 +211,7 @@ export function contractFromDetail(row: ContractGetResult, quotaById?: Record<st
       startDate: s.start_date,
       endDate: s.end_date,
       orderMode: s.sub_mode,
-      useCategory: s.use_category,
+      planFamily: s.plan_family,
       actualOpenedAt: s.actual_opened_at,
       annualPriceCents: s.annual_price_cents,
       monthlySettleCents: s.monthly_settle_cents,
@@ -232,7 +225,7 @@ export function contractFromDetail(row: ContractGetResult, quotaById?: Record<st
 
 /** 服务构成派生账号数是否可判:套餐式条目拿不到目录额度时=未配置,⛔ 计 0。 */
 export function contractAccountsKnown(items: ContractItem[]) {
-  return !items.some((item) => item.type === "套餐" && (item.accounts === null || item.accounts === undefined));
+  return !items.some((item) => item.accounts === null || item.accounts === undefined);
 }
 
 /** 合同列表:一次拉取(后端分页与多条件筛选未接线,页面只在本地二次筛选)。 */

+ 4 - 4
web-scaffold/src/lib/order-demo.ts

@@ -92,7 +92,7 @@ export const initialOrders: OrderDemo[] = [
  * ------------------------------------------------------------------ */
 import { orderGetList, orderListAll } from "./api/bos";
 import type { RelatedOrderRef, OrderListResult, OrderRow } from "./api/types";
-import { label, PLAN_KIND, ORDER_MODE, ORDER_STATUS, TERM, USE_CATEGORY } from "./api/labels";
+import { label, PLAN_FAMILY, PLAN_KIND, ORDER_MODE, ORDER_STATUS, TERM } from "./api/labels";
 import { WORD_FETCH_FAILED, WORD_UNCONFIGURED } from "./api/lockedCopy";
 import { moneyCell } from "./package-catalog";
 import { useLoad, type Load } from "./useLoad";
@@ -107,8 +107,8 @@ export type OrderView = {
   contractNo?: string | null;
   planName?: string | null;
   planKindLabel?: string | null;
-  /** 用途分类/订阅方式/规格:未知编码原样显示。 */
-  categoryLabel: string;
+  /** 交付形态/订阅方式/规格:未知编码原样显示。 */
+  familyLabel: string;
   modeLabel: string;
   termLabel: string;
   start?: string | null;
@@ -198,7 +198,7 @@ export function orderView(row: OrderRow): OrderView {
     contractNo: row.contract_no ?? (row.contract_id || null),
     planName: row.plan_name ?? (row.plan_id || null),
     planKindLabel: row.plan_kind === null || row.plan_kind === undefined ? null : label(PLAN_KIND, row.plan_kind),
-    categoryLabel: row.use_category ? label(USE_CATEGORY, row.use_category) : "",
+    familyLabel: row.plan_family ? label(PLAN_FAMILY, row.plan_family) : "",
     modeLabel: row.sub_mode_label ?? (row.sub_mode ? label(ORDER_MODE, row.sub_mode) : ""),
     termLabel: row.term ? label(TERM, row.term) : "",
     start: row.start_date,

+ 8 - 14
web-scaffold/src/lib/package-catalog.ts

@@ -1,18 +1,14 @@
-export const packageCategories = [
-  { name: "通用办公", hint: "一般访问、办公协作与独立 IP 接入" },
-  { name: "直播高需求", hint: "按直播链接与流量需求划分档位" },
-  { name: "AI 应用", hint: "固定上下行带宽的 AI 应用接入" },
-  { name: "叠加增值", hint: "与主档叠加订阅,独立计费" },
-  { name: "定制化", hint: "针对单一客户的专项方案" },
+/** 交付形态两值(D-15):台账分组与筛选用它,⛔ 再用旧的五值用途分类。 */
+export const planFamilies = [
+  { code: "link", name: "跨境链路", hint: "主档:额度 > 0、份数恒 1、带带宽" },
+  { code: "addon", name: "附加项", hint: "叠加订阅:额度 0、不设带宽、按份数" },
 ] as const;
-
-export type PackageCategory = (typeof packageCategories)[number]["name"];
 export type BandwidthMode = "committed" | "uncommitted" | "not-applicable";
 export type PackageCostItem = { name: string; qty: number };
 export type CatalogPlan = {
   id: string;
   name: string;
-  category: PackageCategory;
+  category: string;
   cycle: "按年";
   annualPrice: number;
   monthlySettlement: number;
@@ -61,17 +57,15 @@ import type {
   IpBandwidthTierListResult,
   LineExitListResult,
 } from "./api/types";
-import { USE_CATEGORY } from "./api/labels";
+import { PLAN_FAMILY } from "./api/labels";
 import { useLoad, type Load } from "./useLoad";
 
 /** 金额一律「分 → 元」由后端换算;null 与字段缺失分别对应「未配置」与「取数失败」,⛔ 兜底 0。 */
 export const centsToYuan = (cents: number | null | undefined) => (cents === null || cents === undefined ? null : cents / 100);
 export const yuanToCents = (yuan: string | number) => Math.round(Number(yuan) * 100);
 
-/** 用途分类:后端编码 ↔ 页面中文口径;未下发的编码原样显示,⛔ 猜一个已知分类。 */
-export const categoryLabel = (code: string | null | undefined) => (code ? USE_CATEGORY[code] ?? code : null);
-export const categoryCode = (label: string | null | undefined) =>
-  (label ? Object.entries(USE_CATEGORY).find(([, text]) => text === label)?.[0] ?? null : null);
+/** 交付形态:后端编码 ↔ 页面中文口径;未下发的编码原样显示,⛔ 猜一个已知形态。 */
+export const familyLabel = (code: string | null | undefined) => (code ? PLAN_FAMILY[code] ?? code : null);
 
 /** 目录档带宽:开关为空=未配置,开关为假=未承诺,开关为真但某向缺失=取数失败。 */
 export const bandwidthTextOfRow = (row: CatalogPlanRow): { tone: "val" | "missing"; text: string } => {

+ 45 - 28
web-scaffold/src/pages/ContractDetailPages.tsx

@@ -9,10 +9,10 @@ import { CustomerTeamSelect } from "../components/CustomerTeamSelect";
 import { contractRawByParam } from "../lib/contract-demo";
 import { contractAttachmentDiscard, contractCreate, contractCustomerLookup, contractGet, contractGetList, contractUpdate, rowsOf, subscriptionReplacementCandidates } from "../lib/api/bos";
 import { ApiError } from "../lib/api/http";
-import { OPTIONS, label, PAY_CYCLE, SUBJECT_TYPE, USE_CATEGORY } from "../lib/api/labels";
+import { OPTIONS, label, PAY_CYCLE, PLAN_FAMILY, SUBJECT_TYPE } from "../lib/api/labels";
 import { WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
 import { Tri } from "../components/triState";
-import { useCatalogPlans, useLineExits } from "../lib/package-catalog";
+import { useCatalogPlans, useIpBandwidthTiers, useLineExits } from "../lib/package-catalog";
 import { centsToYuanText, LINE_EXIT_MAX } from "../domain/contract-items";
 import type { ContractMissing, ContractRequiredKey } from "../domain/contract-items";
 import { REQUIRED_KEY_BY_DRAFT, buildContractWrite, businessToday, contractEndFromCycle, draftFromRow, emptyDraft, emptyItem, renewalPrefill, resolveReplacementSelection, type ContractDraft as Draft, type ItemDraft } from "../domain/contract-draft";
@@ -23,6 +23,7 @@ import { uploadContractAttachment, uploadCustomerLicense, type UploadedObject }
 import { contractAttachmentLabel } from "../lib/contract-attachments";
 import { useLoad } from "../lib/useLoad";
 import { useDemoIdentity } from "../lib/demo-session";
+import { PackagePlanEditor, type EditorState } from "../components/PackagePlanEditor";
 import "../styles/operations.css";
 
 /**
@@ -77,6 +78,10 @@ export function ContractEditorPage() {
    */
   const [draft, setDraft] = useState<Draft>(() => ({ ...emptyDraft(), handoverOn: businessToday() }));
   const [customerId, setCustomerId] = useState<string | null>(null);
+  /** D-16:合同录入页就地新建本客户自定义档(打开同一份档位编辑器,归属客户锁定)。 */
+  const [planEditor, setPlanEditor] = useState<EditorState | null>(null);
+  const [planEditorFor, setPlanEditorFor] = useState<number | null>(null);
+  const bandwidthTiers = useIpBandwidthTiers();
   /** 逐条替换候选(0 基条目下标 → 探测结果):仅新建态、已选客户、条目档位/分类与出口齐全时请求。 */
   const [replacementProbes, setReplacementProbes] = useState<Record<number, ReplacementProbe>>({});
   /**
@@ -108,12 +113,11 @@ export function ContractEditorPage() {
     if (editing || !customerId || renewFrom) return [];
     return draft.items.flatMap((item, index) => {
       if (item.exits.length !== 1) return [];
-      const ready = item.kind === "plan_based" ? Boolean(item.planId) : Boolean(item.useCategory);
-      if (!ready) return [];
+      if (!item.planId) return [];
       return [{
         index,
-        item_kind: item.kind,
-        ...(item.kind === "plan_based" ? { plan_id: item.planId } : { use_category: item.useCategory }),
+        plan_id: item.planId,
+        ...(item.planFamily ? { plan_family: item.planFamily } : {}),
         line_exits: item.exits,
       }];
     });
@@ -500,14 +504,31 @@ export function ContractEditorPage() {
     setError("");
   };
   const removeItem = (index: number) => setDraft((current) => ({ ...current, items: current.items.filter((_, i) => i !== index) }));
-  /** 换档位只换档位带出的口径(数量/带宽/价格),⛔ 清空已选出口——出口是独立于档位的目录配置。 */
+  /** 换档位只换档位带出的口径(形态/数量),⛔ 清空已选出口——出口是独立于档位的目录配置。 */
   const pickPlan = (index: number, planId: string) => {
     const plan = plans.find((row) => row.plan_id === planId);
-    // 不可叠加档(用途分类 ≠ 叠加增值)份数恒 1:切档时归 1,界面也不显示数量输入框。
-    patchItem(index, { planId, planName: plan?.plan_name ?? "", ...(plan && plan.use_category !== "value_add" ? { quantity: 1 } : {}) });
+    // 跨境链路份数恒 1;附加项份数可 > 1。
+    patchItem(index, { planId, planName: plan?.plan_name ?? "", planFamily: plan?.plan_family ?? "", ...(plan && plan.plan_family === "link" ? { quantity: 1 } : {}) });
   };
-  /** 可叠加档(叠加增值,例如「单独境外 IP」按个)才允许填份数;其余档份数恒 1。 */
-  const stackablePlan = (planId: string) => plans.find((row) => row.plan_id === planId)?.use_category === "value_add";
+  /** 附加项(例如「单独境外 IP」按个)才允许填份数;链路档份数恒 1。 */
+  const stackablePlan = (planId: string) => plans.find((row) => row.plan_id === planId)?.plan_family === "addon";
+  /** 就地建档回填:新建成功即选中该档并带出形态/份数,⛔ 让人再回目录页找一遍。 */
+  function savedPlanInPlace(message: string, plan: import("../lib/api/types").CatalogPlanRow | null) {
+    const index = planEditorFor;
+    setPlanEditor(null);
+    setPlanEditorFor(null);
+    if (plan && index !== null) {
+      patchItem(index, {
+        planId: plan.plan_id,
+        planName: plan.plan_name,
+        planFamily: plan.plan_family ?? "",
+        ...(plan.plan_family === "link" ? { quantity: 1 } : {}),
+      });
+    }
+    catalog.reload();
+    setError("");
+    if (!plan) setError(message);
+  }
   /** 线路出口**单选**(2026-11-17):点未选项=替换当前选择;再点已选项=清空重选(提交前须补 1 个)。 */
   const toggleExit = (index: number, exit: string) => {
     const item = draft.items[index];
@@ -525,7 +546,7 @@ export function ContractEditorPage() {
       replacementCustomized: Boolean(candidate?.customized),
       replacementConfirmed: false,
       replacementOptOut: false,
-      ...(draft.items[index]?.kind === "plan_based" ? { quantity: 1 } : {}),
+      quantity: 1,
     });
   };
   /** 「改为按新订阅开通」:唯一候选时的显式退出(否则自动选中的那条会被反复写回)。 */
@@ -536,7 +557,7 @@ export function ContractEditorPage() {
       replacesSubscriptionId: optOut ? "" : (only?.subscription_id ?? ""),
       replacementCustomized: optOut ? false : Boolean(only?.customized),
       replacementConfirmed: false,
-      ...(optOut || draft.items[index]?.kind !== "plan_based" ? {} : { quantity: 1 }),
+      quantity: 1,
     });
   };
   /** 出口候选=套餐配置清单;历史数据里已出现的值也保留,避免旧合同编辑时选项凭空消失。 */
@@ -936,7 +957,7 @@ export function ContractEditorPage() {
         </section>
 
         <section className="ops-record-card">
-          <h2>三、服务构成 <span>固定套餐式/自定义规格式</span></h2>
+          <h2>三、服务构成 <span>按目录档位选择(跨境链路 × 1/附加项 × 份数)</span></h2>
           {!plans.length && <p className="contract-form-summary">{catalog.error ? <>套餐配置取数失败:{catalog.error.message}</> : catalog.loading ? "正在载入套餐配置…" : "套餐配置暂无可选档位。"}</p>}
           <div className="ops-contract-items">
             {draft.items.map((item, index) => (
@@ -946,18 +967,13 @@ export function ContractEditorPage() {
                   <Button variant="ghost" size="sm" disabled={draft.items.length === 1} onClick={() => removeItem(index)}><Trash2 size={15} />删除</Button>
                 </header>
                 <div className="ops-form-grid ops-form-grid--business">
-                  <label><span className="ops-field-title">条目形态</span><select value={item.kind} onChange={(event) => patchItem(index, { kind: event.target.value as ItemDraft["kind"] })}><option value="plan_based">固定套餐式</option><option value="custom_spec">自定义规格式</option></select></label>
-                  {item.kind === "plan_based" ? <>
-                    <label><span className="ops-field-title">套餐档位</span><select value={item.planId} onChange={(event) => pickPlan(index, event.target.value)}><option value="">{catalog.loading ? "载入中…" : WORD_UNCONFIGURED}</option>{plans.map((plan) => <option key={plan.plan_id} value={plan.plan_id}>{plan.plan_name}</option>)}</select></label>
-                    {(item.replacesSubscriptionId || stackablePlan(item.planId)) && <label><span className="ops-field-title">档位数量</span><Input type="number" min={1} disabled={Boolean(item.replacesSubscriptionId)} value={item.quantity} onChange={(event) => patchItem(index, { quantity: Number(event.target.value) })} /><span className="ops-field-note">{item.replacesSubscriptionId ? "替换时一条条目只生一份订阅,数量固定为 1。" : "可叠加档按份计价,例如「单独境外 IP」按个叠加;保存后带入订阅。"}</span></label>}
-                  </> : <>
-                    <label><span className="ops-field-title">账号数</span><Input type="number" min={1} value={item.accountCount} onChange={(event) => patchItem(index, { accountCount: Number(event.target.value) })} /></label>
-                    <label><span className="ops-field-title">下行带宽(Mbps)</span><Input type="number" min={0} max={1000} value={item.bwDown} onChange={(event) => patchItem(index, { bwDown: Number(event.target.value) })} /></label>
-                    <label><span className="ops-field-title">上行带宽(Mbps)</span><Input type="number" min={0} max={1000} value={item.bwUp} onChange={(event) => patchItem(index, { bwUp: Number(event.target.value) })} /></label>
-                    <label><span className="ops-field-title">条目年价(元)</span><Input inputMode="decimal" placeholder="0.00" value={item.annualPrice} onChange={(event) => patchItem(index, { annualPrice: event.target.value })} /></label>
-                    {/* D-32:自定义规格补齐「用途分类」——订阅方式与出账分类都按它派生,套餐式由所引目录档带出、此处不录。 */}
-                    <label><span className="ops-field-title">用途分类</span><select value={item.useCategory} onChange={(event) => patchItem(index, { useCategory: event.target.value })}><option value="">请选择用途分类</option>{Object.entries(USE_CATEGORY).map(([value, text]) => <option key={value} value={value}>{text}</option>)}</select></label>
-                  </>}
+                  <label><span className="ops-field-title">套餐档位</span><select value={item.planId} onChange={(event) => pickPlan(index, event.target.value)}><option value="">{catalog.loading ? "载入中…" : WORD_UNCONFIGURED}</option>{plans.map((plan) => <option key={plan.plan_id} value={plan.plan_id}>{plan.plan_name}{plan.plan_family ? `(${label(PLAN_FAMILY, plan.plan_family)})` : ""}</option>)}</select></label>
+                  <label><span className="ops-field-title">交付形态</span><input readOnly value={item.planFamily ? label(PLAN_FAMILY, item.planFamily) : "随所选档位"} /></label>
+                  {stackablePlan(item.planId) && <label><span className="ops-field-title">份数</span><Input type="number" min={1} disabled={Boolean(item.replacesSubscriptionId)} value={item.quantity} onChange={(event) => patchItem(index, { quantity: Number(event.target.value) })} /><span className="ops-field-note">{item.replacesSubscriptionId ? "替换时一条条目只生一份订阅,份数固定为 1。" : "附加项按份计价(例如「单独境外 IP」按个);跨境链路档份数恒 1。"}</span></label>}
+                  <div className="ops-form-span-full">
+                    <Button type="button" variant="outline" size="sm" disabled={!customerId} title={customerId ? "为当前客户新建一个自定义档并直接选中" : "请先选定签约客户"} onClick={() => { setPlanEditorFor(index); setPlanEditor({ owner: customerId, planKind: "custom", lockOwner: true }); }}><Plus size={15} />新建本客户自定义档</Button>
+                    {!customerId && <span className="ops-field-note">选定客户后才能就地新建自定义档(自定义档必须归属一个客户)。</span>}
+                  </div>
                   <fieldset className="ops-form-span-full ops-contract-exit-fieldset">
                     <legend>线路出口(从套餐配置选择,{LINE_EXIT_MAX} 个)</legend>
                     {exitCatalog.error && <FetchError message={exitCatalog.error.message} onRetry={exitCatalog.reload} />}
@@ -985,7 +1001,7 @@ export function ContractEditorPage() {
                     * 0 个=按新订阅开通;1 个=自动选中(可改为按新订阅开通);多个=必须显式选择;
                     * 定制档须勾选确认。判据全在后端,前端只负责呈现与回填 `succession`。
                     */}
-                  {!editing && !renewFrom && customerId && item.exits.length === 1 && (item.kind === "plan_based" ? Boolean(item.planId) : Boolean(item.useCategory)) ? (
+                  {!editing && !renewFrom && customerId && item.exits.length === 1 && Boolean(item.planId) ? (
                     <ReplacementBlock
                       index={index}
                       item={item}
@@ -1001,7 +1017,7 @@ export function ContractEditorPage() {
             ))}
           </div>
           <div className="ops-contract-item-actions">
-            <p className="contract-form-summary"><span><strong>{draft.items.length}</strong> 个构成条目</span><span>套餐式 {draft.items.filter((item) => item.kind === "plan_based").length} · 自定义式 {draft.items.filter((item) => item.kind === "custom_spec").length}</span></p>
+            <p className="contract-form-summary"><span><strong>{draft.items.length}</strong> 个构成条目</span><span>跨境链路 {draft.items.filter((item) => item.planFamily === "link").length} · 附加项 {draft.items.filter((item) => item.planFamily === "addon").length}</span></p>
             <Button variant="outline" size="sm" onClick={() => setDraft((current) => ({ ...current, items: [...current.items, emptyItem()] }))}><Plus size={15} />添加条目</Button>
           </div>
         </section>
@@ -1064,6 +1080,7 @@ export function ContractEditorPage() {
         </section>
       </aside>
     </div>}
+    {planEditor && <PackagePlanEditor state={planEditor} tiers={bandwidthTiers} onClose={() => { setPlanEditor(null); setPlanEditorFor(null); }} onSaved={savedPlanInPlace} />}
   </section>;
 }
 

File diff suppressed because it is too large
+ 24 - 38
web-scaffold/src/pages/ContractRecordPage.tsx


+ 6 - 6
web-scaffold/src/pages/OrderRecordPage.tsx

@@ -13,7 +13,7 @@ import { bandwidthTextOfRow, moneyCell, useCatalogPlans } from "../lib/package-c
 import { rowsOf, customerGet, subAccountGetList } from "../lib/api/bos";
 import { ticketList, statusLabel, typeLabel } from "../lib/api/ticket";
 import { fmtDate } from "../lib/ticket";
-import { ACCT_STATUS, SUBJECT_TYPE, label, USE_CATEGORY } from "../lib/api/labels";
+import { ACCT_STATUS, SUBJECT_TYPE, label, PLAN_FAMILY } from "../lib/api/labels";
 import { regionMountPath } from "../lib/organization-demo";
 import { WORD_FETCH_FAILED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
 import { useLoad } from "../lib/useLoad";
@@ -122,8 +122,8 @@ export function OrderRecordPage() {
   const editReason = item.editable === undefined ? "写口可见性未随记录下发,按只读呈现。" : item.editable ? "服务端判定可写;已开通计费的订阅请新增替换订阅,不改写本条。" : "服务端判定本条只读。";
   const bandwidth = plan ? bandwidthTextOfRow(plan) : null;
   const catalogMatches = plan !== undefined && plan.annual_price_cents === item.row.annual_price_cents && plan.monthly_settle_cents === item.row.monthly_settle_cents;
-  const orderKind = item.categoryLabel === "叠加增值" ? "叠加" : "正式";
-  const catalogMode = item.categoryLabel === "叠加增值" ? "可叠加" : item.categoryLabel === "定制化" ? "单独约定" : "可升降配";
+  const orderKind = item.row.plan_family === "addon" ? "叠加" : "正式";
+  const catalogMode = item.row.plan_family === "addon" ? "可叠加" : "可升降配";
   /**
    * 出账四卡(第 6 册):取订阅行随附的 `billing` 聚合,⛔ 前端按价格×期数推算。
    * 键未下发 ⇒ 取数失败;`no_receivable` ⇒ 四值 `null` → 未配置(⛔ 0 元/「未出账」)。
@@ -181,9 +181,9 @@ export function OrderRecordPage() {
     <section className="order-record-section" aria-labelledby="order-service-title">
       <div className="order-record-section-title"><h2 id="order-service-title">本条订阅</h2></div>
       <div className="order-record-detail-wrap"><table className="order-record-detail"><tbody>
-        <tr><th scope="row">套餐档</th><td>{cell(item.planName)}{plan ? <span className="order-record-inline-note"> · {label(USE_CATEGORY, plan.use_category) || "用途未填"} · 目录年价 {moneyCell(plan.annual_price_cents).text} / 月标准 {moneyCell(plan.monthly_settle_cents).text} · 额度 {plan.sub_account_quota ?? WORD_UNCONFIGURED}</span> : <span className="order-record-inline-note"> · {catalog.error ? `目录档位取数失败:${catalog.error.message}` : "目录档位未取到,本条按冻结价继续计费"}</span>}</td></tr>
+        <tr><th scope="row">套餐档</th><td>{cell(item.planName)}{plan ? <span className="order-record-inline-note"> · {label(PLAN_FAMILY, plan.plan_family) || "形态未填"} · 目录年价 {moneyCell(plan.annual_price_cents).text} / 月标准 {moneyCell(plan.monthly_settle_cents).text} · 额度 {plan.sub_account_quota ?? WORD_UNCONFIGURED}</span> : <span className="order-record-inline-note"> · {catalog.error ? `目录档位取数失败:${catalog.error.message}` : "目录档位未取到,本条按冻结价继续计费"}</span>}</td></tr>
         <tr><th scope="row">冻结价格</th><td>年订阅价格 {moneyCellView(item.annual)} · 月结算标准 {moneyCellView(item.settle)}<span className="order-record-inline-note">({plan ? catalogMatches ? "与当前目录价一致" : "与当前目录价不同,以本条冻结值为准" : "目录档位未取到,以本条冻结值为准"})</span></td></tr>
-        <tr><th scope="row">订阅方式</th><td>{item.modeLabel || WORD_UNCONFIGURED}<span className="order-record-inline-note"> · 该用途分类({item.categoryLabel || WORD_UNCONFIGURED}){catalogMode}</span>{item.original && <> · 替换 <Link to={`/orders/${encodeURIComponent(item.original.subscription_id)}`} state={outgoingState}>{item.original.subscription_id}</Link></>}{item.replacedBy && <> · 已被 <Link to={`/orders/${encodeURIComponent(item.replacedBy.subscription_id)}`} state={outgoingState}>{item.replacedBy.subscription_id}</Link> 替换</>}</td></tr>
+        <tr><th scope="row">订阅方式</th><td>{item.modeLabel || WORD_UNCONFIGURED}<span className="order-record-inline-note"> · 交付形态({item.familyLabel || WORD_UNCONFIGURED}){catalogMode}</span>{item.original && <> · 替换 <Link to={`/orders/${encodeURIComponent(item.original.subscription_id)}`} state={outgoingState}>{item.original.subscription_id}</Link></>}{item.replacedBy && <> · 已被 <Link to={`/orders/${encodeURIComponent(item.replacedBy.subscription_id)}`} state={outgoingState}>{item.replacedBy.subscription_id}</Link> 替换</>}</td></tr>
         <tr><th scope="row">订阅状态</th><td>{item.statusLabel ? <OpsStatus tone={statusTone(item.statusLabel)}>{item.statusLabel}</OpsStatus> : <Tri tone="fail" text={WORD_FETCH_FAILED} />}{item.reason && <span className="order-record-inline-note"> · 办理说明:{item.reason}</span>}</td></tr>
         <tr><th scope="row">起止时间</th><td>{cell(item.start)} 至 {cell(item.end)}<span className="order-record-inline-note"> · 应收从实际开通日与合同生效日的较晚者起算{billableStart ? `(${billableStart})` : "(尚未开通)"}</span></td></tr>
         {item.trialMonths ? <tr><th scope="row">试用优惠</th><td>{item.trialMonths} 个月 · {item.trialDiscount === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : item.trialDiscount === null ? "优惠金额未填写" : `${moneyCell(item.trialDiscount).text} / 月`}</td></tr> : null}
@@ -198,7 +198,7 @@ export function OrderRecordPage() {
 
     {siblings.length > 0 && <section className="order-record-section" aria-labelledby="order-related-title">
       <div className="order-record-section-title"><h2 id="order-related-title">关联订阅(同一合同的其他订阅 {siblings.length} 份)</h2></div>
-      <div className="order-record-table-wrap"><table><thead><tr><th>序号</th><th>套餐 / 用途</th><th>方式</th><th>订阅状态</th><th>期间</th><th>订阅价格</th><th>月标准</th><th>实际开通日</th></tr></thead><tbody>{siblings.map((sibling) => <tr key={sibling.no}><td><Link to={`/orders/${encodeURIComponent(sibling.no)}`} state={outgoingState}>{all.indexOf(sibling) + 1}<ArrowRight size={14} /></Link></td><td>{cell(sibling.planName)}</td><td>{sibling.categoryLabel === "叠加增值" ? "叠加" : "正式"}</td><td>{sibling.statusLabel ? <OpsStatus tone={statusTone(sibling.statusLabel)}>{sibling.statusLabel}</OpsStatus> : <Tri tone="fail" text={WORD_FETCH_FAILED} />}</td><td>{cell(sibling.start)} 至 {cell(sibling.end)}</td><td>{sibling.annual.tone === "val" ? sibling.annual.text : <Tri tone={sibling.annual.tone} text={sibling.annual.text} />}</td><td>{sibling.settle.tone === "val" ? sibling.settle.text : <Tri tone={sibling.settle.tone} text={sibling.settle.text} />}</td><td>{sibling.openedOn === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : sibling.openedOn || <Tri tone="missing" text="未开通" />}</td></tr>)}</tbody></table></div>
+      <div className="order-record-table-wrap"><table><thead><tr><th>序号</th><th>套餐 / 用途</th><th>方式</th><th>订阅状态</th><th>期间</th><th>订阅价格</th><th>月标准</th><th>实际开通日</th></tr></thead><tbody>{siblings.map((sibling) => <tr key={sibling.no}><td><Link to={`/orders/${encodeURIComponent(sibling.no)}`} state={outgoingState}>{all.indexOf(sibling) + 1}<ArrowRight size={14} /></Link></td><td>{cell(sibling.planName)}</td><td>{sibling.row.plan_family === "addon" ? "叠加" : "正式"}</td><td>{sibling.statusLabel ? <OpsStatus tone={statusTone(sibling.statusLabel)}>{sibling.statusLabel}</OpsStatus> : <Tri tone="fail" text={WORD_FETCH_FAILED} />}</td><td>{cell(sibling.start)} 至 {cell(sibling.end)}</td><td>{sibling.annual.tone === "val" ? sibling.annual.text : <Tri tone={sibling.annual.tone} text={sibling.annual.text} />}</td><td>{sibling.settle.tone === "val" ? sibling.settle.text : <Tri tone={sibling.settle.tone} text={sibling.settle.text} />}</td><td>{sibling.openedOn === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : sibling.openedOn || <Tri tone="missing" text="未开通" />}</td></tr>)}</tbody></table></div>
       <p className="order-record-note">这些订阅与本条引用同一份合同{item.orderNo ? `(订单号 ${item.orderNo})` : ""}。合同中每条服务构成条目分别形成订阅,各自冻结价格、计费与开通;点击序号查看详情。</p>
     </section>}
 

+ 40 - 293
web-scaffold/src/pages/PackageManagementPage.tsx

@@ -1,51 +1,29 @@
 import { FilterSelect } from "../components/ui/filter-select";
-import { FetchError } from "../components/fetchError";
-import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, Fragment, type FormEvent } from "react";
+import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, Fragment } from "react";
 import { createPortal } from "react-dom";
-import { CircleHelp, Info, LockKeyhole, PencilLine, Plus, Search, Trash2, X } from "lucide-react";
+import { CircleHelp, LockKeyhole, PencilLine, Plus, Search, Trash2, X } from "lucide-react";
 import { Button } from "../components/ui/button";
 import { Input } from "../components/ui/input";
 import { Tri } from "../components/triState";
 import { NOTICE_DISMISS_MS, OpsTableColumns, OpsTableEmpty } from "../components/OperationsKit";
 import { ListPager } from "../components/ListPager";
-import { COST_BY_COMBINATION, DERIVED_PLAN_EDITABLE, FIXED_PLAN_LOCKED_FIELDS, OPERATOR_ONLY_CONFIG, PLAN_COST_ITEM_SAVE_NOTE, WORD_FETCH_FAILED, WORD_NOT_PROVIDED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
-import { catalogCreate, catalogCustomerOptions, catalogDelete, catalogUpdate, ipBandwidthTierSave, lineExitSave, planCostItemList, planCostItemSave, rowsOf } from "../lib/api/bos";
-import type { CatalogPlanRow, IpBandwidthTierListResult, LineExitListResult, PlanCostItemRow } from "../lib/api/types";
+import { COST_BY_COMBINATION, OPERATOR_ONLY_CONFIG, WORD_FETCH_FAILED, WORD_NOT_PROVIDED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
+import { catalogDelete, ipBandwidthTierSave, lineExitSave } from "../lib/api/bos";
+import type { CatalogPlanRow, IpBandwidthTierListResult, LineExitListResult } from "../lib/api/types";
 import { ApiError } from "../lib/api/http";
 import { useDemoIdentity } from "../lib/demo-session";
-import { bandwidthTextOfRow, categoryCode, categoryLabel, packageCategories, useCatalogPlans, useIpBandwidthTiers, useLineExits } from "../lib/package-catalog";
+import { bandwidthTextOfRow, familyLabel, planFamilies, useCatalogPlans, useIpBandwidthTiers, useLineExits } from "../lib/package-catalog";
 import { exitKey, IP_TIER_UNCOMMITTED, splitExitInput } from "../domain/contract-items";
-import { useLoad, type Load } from "../lib/useLoad";
+import type { Load } from "../lib/useLoad";
 import { slicePage, useLocalPage } from "../lib/list-paging";
 import { useHorizontalOverflow } from "../lib/use-horizontal-overflow";
+import { PackagePlanEditor, type EditorState } from "../components/PackagePlanEditor";
 import "../styles/operations.css";
 import "../styles/packages.css";
 
 /** 目录三视图:固定套餐与自定义套餐各一张台账,线路出口是目录级清单。 */
 type CatalogTab = "fixed" | "custom" | "exits";
-/** `owner` 为归属客户 ID:`null` 表示公共固定档,空串表示「客户专属档但尚未选择归属」。 */
-type EditorState = { plan?: CatalogPlanRow; owner: string | null };
-type EditorValues = {
-  name: string; category: string; owner: string; annualPrice: string; quota: string;
-  bandwidthMode: "committed" | "uncommitted" | ""; upload: string; download: string; description: string;
-};
-/** 成本项行=`plan_cost_item` 真实字段面(⛔ 本地「份数」口径,后端无该列)。 */
-type CostDraft = { item_name: string; amount: string; billing_unit: string; remark: string };
 
-const costDraftOf = (row: PlanCostItemRow): CostDraft => ({
-  item_name: row.item_name ?? "",
-  amount: row.amount_cents === null || row.amount_cents === undefined ? "" : String(row.amount_cents / 100),
-  billing_unit: row.billing_unit ?? "",
-  remark: row.remark ?? "",
-});
-
-const costRowOf = (draft: CostDraft): PlanCostItemRow => ({
-  item_name: draft.item_name.trim(),
-  amount_cents: draft.amount.trim() === "" ? null : Math.round(Number(draft.amount) * 100),
-  billing_unit: draft.billing_unit.trim() || null,
-  category: null,
-  remark: draft.remark.trim() || null,
-});
 
 /** 整数格三态:字段缺失=取数失败,null=未配置,⛔ 显示 0;不给单位时与原型一样只出数字。 */
 function intCell(value: number | null | undefined, unit?: string) {
@@ -78,29 +56,6 @@ function ledgerCostCell(plan: CatalogPlanRow) {
   return <Tri tone="val" text={COST_BY_COMBINATION} title="金额随各客户的「省份 × 运营商」组合不同,不折中成一个数" />;
 }
 
-function formOf(plan: CatalogPlanRow | undefined, owner: string | null): EditorValues {
-  const committed = plan?.bandwidth_committed;
-  return {
-    name: plan?.plan_name ?? "",
-    category: plan ? categoryLabel(plan.use_category) ?? "" : (owner !== null ? "定制化" : "通用办公"),
-    owner: plan?.customer_id ?? owner ?? "",
-    annualPrice: plan?.annual_price_cents === undefined || plan.annual_price_cents === null ? "" : String(plan.annual_price_cents / 100),
-    quota: plan?.sub_account_quota === undefined || plan.sub_account_quota === null ? "" : String(plan.sub_account_quota),
-    bandwidthMode: committed === undefined ? "" : committed ? "committed" : "uncommitted",
-    upload: plan?.bandwidth_up_mbps === null || plan?.bandwidth_up_mbps === undefined ? "" : String(plan.bandwidth_up_mbps),
-    download: plan?.bandwidth_down_mbps === null || plan?.bandwidth_down_mbps === undefined ? "" : String(plan.bandwidth_down_mbps),
-    description: plan?.plan_desc ?? "",
-  };
-}
-
-function CatalogInfo({ label, children }: { label: string; children: string }) {
-  const id = useId();
-  return <>
-    <button type="button" className="catalog-info" aria-label={label} aria-describedby={id}><Info size={15} aria-hidden="true" /></button>
-    <span id={id} className="catalog-info-tip" role="tooltip">{children}</span>
-  </>;
-}
-
 /**
  * 套餐说明:挂在名称右侧的问号图标上,不占一列。图标随行悬停/键盘聚焦显形,点击展开浮层显示说明。
  * 浮层走 body 传送门+fixed,避免被台账滚动容器裁掉;**落在图标的左/右侧而非正下方**,
@@ -160,210 +115,11 @@ function PlanDescNote({ name, desc }: { name: string; desc: string }) {
   </>;
 }
 
-function PackageEditor({ state, tiers, onClose, onSaved }: {
-  state: EditorState; tiers: Load<IpBandwidthTierListResult>; onClose: () => void; onSaved: (message: string, savedPlan: CatalogPlanRow | null) => void;
-}) {
-  const original = state.plan;
-  /** 锁定:被引用冻结(K204)或合同条目派生档;页面放开名称/说明/成本项,服务端裁决后原样回显拒绝原因。 */
-  const derived = Boolean(original?.derived_from_contract_item_id);
-  const locked = Boolean(original && (original.frozen === true || derived));
-  const settlementId = useId();
-  const [values, setValues] = useState(() => formOf(original, state.owner));
-  const [costs, setCosts] = useState<CostDraft[]>([]);
-  const [costsDirty, setCostsDirty] = useState(false);
-  const [error, setError] = useState("");
-  const costLoad = useLoad(
-    () => (original ? planCostItemList({ plan_id: original.plan_id }).then(rowsOf) : Promise.resolve([] as PlanCostItemRow[])),
-    [original?.plan_id],
-  );
-  useEffect(() => {
-    if (original && costLoad.data && !costsDirty) setCosts(costLoad.data.map(costDraftOf));
-  }, [costLoad.data, original, costsDirty]);
-  useEffect(() => {
-    const dialog = document.getElementById("catalog-editor") as HTMLDialogElement | null;
-    const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
-    if (!dialog) return;
-    const previousOverflow = document.body.style.overflow;
-    document.body.style.overflow = "hidden";
-    dialog.showModal();
-    return () => { dialog.close(); document.body.style.overflow = previousOverflow; previous?.focus(); };
-  }, []);
-  /** 归属客户可选项:后端下发的操作人可见客户集合,⛔ 前端拼权限。 */
-  const customerOptions = useLoad(() => catalogCustomerOptions().then(rowsOf), []);
-  const field = <K extends keyof EditorValues>(key: K, value: EditorValues[K]) => {
-    setValues((current) => ({ ...current, [key]: value }));
-    setError("");
-  };
-  /** 带宽档位快捷(2026-11-17 业主裁定):套餐配置里维护的档位即带宽权益的预设备选。
-   *  点一条=上下行同值填入;「不承诺带宽」档只切口径、⛔ 清空两格(同 CU-D5 的置灰不清空纪律)。 */
-  const tierPresets = useMemo(() => {
-    const seen = new Set<string>();
-    const rows: { key: string; label: string; mbps: number | null }[] = [];
-    for (const item of tiers.data?.items ?? []) {
-      const key = tierKeyOf(item.bandwidth_tier_mbps ?? null);
-      if (seen.has(key)) continue;
-      seen.add(key);
-      rows.push({ key, label: item.bandwidth_tier_mbps === null ? "不承诺带宽" : item.tier_name || `${item.bandwidth_tier_mbps} 兆`, mbps: item.bandwidth_tier_mbps ?? null });
-    }
-    return rows;
-  }, [tiers.data]);
-  const applyTier = (mbps: number | null) => {
-    setValues((current) => mbps === null
-      ? { ...current, bandwidthMode: "uncommitted" }
-      : { ...current, bandwidthMode: "committed", upload: String(mbps), download: String(mbps) });
-    setError("");
-  };
-  async function submit(event: FormEvent<HTMLFormElement>) {
-    event.preventDefault();
-    const name = values.name.trim();
-    const owner = state.owner === null ? null : values.owner;
-    if (!name) { setError("请填写套餐名称。"); return; }
-    if (owner !== null && !owner) { setError("请选择归属客户。"); return; }
-    if (costLoad.error && costsDirty) { setError("成本项取数失败,整段保存会覆盖后端构成,请重试或放弃本次改动。"); return; }
-    let annualPrice = 0;
-    let quota = 0;
-    let upload: number | null = null;
-    let download: number | null = null;
-    if (!locked) {
-      if (!/^\d+(?:\.\d{1,2})?$/.test(values.annualPrice) || !Number.isFinite(Number(values.annualPrice)) || Number(values.annualPrice) < 0 || Number(values.annualPrice) > 10_000_000) {
-        setError("年订阅价格需为非负金额。"); return;
-      }
-      if (!/^\d+$/.test(values.quota)) { setError("分账号额度需为非负整数。"); return; }
-      annualPrice = Number(values.annualPrice);
-      quota = Number(values.quota);
-      if (values.bandwidthMode === "") { setError("请选择带宽口径(承诺或不承诺)。"); return; }
-      if (values.bandwidthMode === "committed") {
-        // 文案分档(18 册 R-3):缺格 ⇒ 指名填哪一向;越界 ⇒ 1–1000。两种情形⛔ 共用一句。
-        if (!values.upload.trim()) { setError("请填写上行带宽。"); return; }
-        if (!values.download.trim()) { setError("请填写下行带宽。"); return; }
-        upload = Number(values.upload);
-        download = Number(values.download);
-        if (!/^\d+$/.test(values.upload) || !/^\d+$/.test(values.download) || upload < 1 || upload > 1000 || download < 1 || download > 1000) {
-          setError("上行和下行带宽须分别为 1–1000 Mbps 的整数。"); return;
-        }
-      }
-    }
-    if (costs.some((cost) => !cost.item_name.trim() || (cost.amount.trim() !== "" && !/^\d+(?:\.\d{1,2})?$/.test(cost.amount.trim())))) {
-      setError("成本项需填写名称,金额留空表示未配置、否则为非负金额。"); return;
-    }
-    const costRows = costs.map(costRowOf);
-    /** 契约:开关关闭⇒上行/下行两格⛔ 提交(服务端记 FALSE +两列 NULL)。 */
-    const bandwidth = values.bandwidthMode === "committed" && upload !== null && download !== null
-      ? { bandwidth_committed: true, bandwidth_up_mbps: upload, bandwidth_down_mbps: download }
-      : { bandwidth_committed: false };
-    try {
-      if (!original) {
-        /** 自定义档恒为「定制化」(2026-11-15):弹窗不再让选,载荷固定送 customized。 */
-        const categoryOf = owner === null ? categoryCode(values.category) : "customized";
-        await catalogCreate({
-          plan_kind: owner === null ? "fixed" : "custom",
-          plan_name: name,
-          ...(categoryOf ? { use_category: categoryOf } : {}),
-          annual_price_cents: Math.round(annualPrice * 100),
-          sub_account_quota: quota,
-          ...bandwidth,
-          ...(owner ? { customer_id: owner } : {}),
-          ...(values.description.trim() ? { plan_desc: values.description.trim() } : {}),
-          ...(costRows.length ? { cost_items: costRows } : {}),
-        });
-        onSaved(`${name}已新建。`, null);
-        return;
-      }
-      await catalogUpdate({
-        plan_id: original.plan_id,
-        plan_name: name,
-        plan_desc: values.description.trim(),
-        ...(locked ? {} : {
-          annual_price_cents: Math.round(annualPrice * 100),
-          sub_account_quota: quota,
-          ...bandwidth,
-        }),
-        ...(original.row_version === undefined || original.row_version === null || original.row_version === "" ? {} : { row_version: Number(original.row_version) }),
-      });
-      if (costsDirty) await planCostItemSave({ plan_id: original.plan_id, items: costRows });
-      onSaved(`${name}已保存。`, original);
-    } catch (e) {
-      setError(e instanceof ApiError ? e.message : "保存失败,请稍后重试。");
-    }
-  }
-  const settlement = locked
-    ? (original?.monthly_settle_cents === null || original?.monthly_settle_cents === undefined ? "" : String(original.monthly_settle_cents / 100))
-    : values.annualPrice && /^\d+(?:\.\d{1,2})?$/.test(values.annualPrice)
-      ? (Math.floor(Math.round(Number(values.annualPrice) * 100) / 12) / 100).toFixed(2)
-      : "";
-  return <dialog id="catalog-editor" className="catalog-editor" aria-labelledby="catalog-editor-title" onCancel={onClose} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
-    <header className="catalog-editor-head"><div><span>{state.owner === null ? "公共固定套餐" : "客户专属套餐"}</span><h2 id="catalog-editor-title">{original ? "编辑套餐档位" : "新增套餐档位"}</h2></div><button type="button" aria-label="关闭" className="catalog-icon-button" onClick={onClose}><X size={19} /></button></header>
-    <form onSubmit={submit} className="catalog-editor-body">
-      {locked && <div className="catalog-locked-note"><LockKeyhole size={18} /><p>{derived ? DERIVED_PLAN_EDITABLE : <>已被 {original?.referred_count ?? "—"} 处引用,字段「{FIXED_PLAN_LOCKED_FIELDS.join("、")}」已锁定;调整价格或额度请新建档位,再升级订阅。</>}</p></div>}
-      <section><h3><span>01</span> 基本信息</h3><label>套餐名称 <em>*</em><input autoFocus required maxLength={60} value={values.name} onChange={(event) => field("name", event.target.value)} placeholder="输入套餐名称" /></label>
-        <div className="catalog-editor-grid">{state.owner === null
-          ? <label>用途分类<select disabled={Boolean(original) || locked} value={values.category} onChange={(event) => field("category", event.target.value)}>{!values.category && <option value="">未配置</option>}{packageCategories.filter((item) => item.name !== "定制化" || item.name === values.category).map((item) => <option key={item.name}>{item.name}</option>)}</select></label>
-          : <label>用途分类<input disabled value="定制化" /></label>}<label>订阅周期<input disabled value="按年" /></label></div>
-        {state.owner !== null && <label>归属客户 <em>*</em>
-          <select disabled={locked || Boolean(original)} required value={values.owner} onChange={(event) => field("owner", event.target.value)}>
-            <option value="">{customerOptions.loading ? "载入中…" : customerOptions.error ? WORD_FETCH_FAILED : "选择客户"}</option>
-            {(customerOptions.data ?? []).map((item) => <option key={item.customer_id} value={item.customer_id}>{item.customer_name}</option>)}
-          </select>
-          {customerOptions.error && <FetchError message={customerOptions.error.message} onRetry={customerOptions.reload} className="catalog-editor-error" />}
-        </label>}
-      </section>
-      <section>
-        <h3><span>02</span> 价格与额度</h3>
-        <div className="catalog-editor-grid">
-          <label>
-            年订阅价格<span className="sr-only">(元)</span> <em>*</em>
-            <span className="catalog-price-input">
-              <input disabled={locked} inputMode="decimal" value={values.annualPrice} onChange={(event) => field("annualPrice", event.target.value)} placeholder="0.00" />
-              <span className="catalog-price-unit" aria-hidden="true">元</span>
-            </span>
-          </label>
-          <div>
-            <div className="catalog-heading-with-info">
-              <label htmlFor={settlementId}>月结算标准<span className="sr-only">(元)</span></label>
-              <CatalogInfo label="月结算标准说明">年订阅价格除以 12 后向下取整到分。订阅签约时可按合同冻结价格。</CatalogInfo>
-            </div>
-            <span className="catalog-price-input">
-              <input id={settlementId} disabled value={settlement} placeholder="由年价自动计算" />
-              <span className="catalog-price-unit" aria-hidden="true">元</span>
-            </span>
-          </div>
-        </div>
-        <label>分账号额度(个) <em>*</em><input disabled={locked} inputMode="numeric" value={values.quota} onChange={(event) => field("quota", event.target.value)} placeholder="0" /></label>
-      </section>
-      <section><h3><span>03</span> 带宽与权益</h3><label className="catalog-bandwidth-field">带宽口径<select disabled={locked} value={values.bandwidthMode} onChange={(event) => field("bandwidthMode", event.target.value as EditorValues["bandwidthMode"])}>{values.bandwidthMode === "" && <option value="">未配置</option>}<option value="committed">承诺上下行带宽</option><option value="uncommitted">不承诺带宽</option></select></label>
-        {/* 两格**常驻**、非承诺时置灰但⛔ 清空:卸载再挂载会让回切后输入框回读空串
-            (18 册 CU-D5),且 DOM 与 state 脱节。 */}
-        <div className="catalog-editor-grid"><label>上行带宽(Mbps)<input disabled={locked || values.bandwidthMode !== "committed"} inputMode="numeric" value={values.upload} onChange={(event) => field("upload", event.target.value)} placeholder="1–1000" /></label><label>下行带宽(Mbps)<input disabled={locked || values.bandwidthMode !== "committed"} inputMode="numeric" value={values.download} onChange={(event) => field("download", event.target.value)} placeholder="1–1000" /></label></div>
-        {!locked && tierPresets.length > 0 && <div className="catalog-bandwidth-presets">
-          <span className="catalog-bandwidth-presets-label">档位快捷<small>(取自「线路出口」Tab 的带宽档位)</small></span>
-          <div className="catalog-bandwidth-presets-list">
-            {tierPresets.map((preset) => {
-              const on = preset.mbps === null
-                ? values.bandwidthMode === "uncommitted"
-                : values.bandwidthMode === "committed" && values.upload.trim() === String(preset.mbps) && values.download.trim() === String(preset.mbps);
-              return <button key={preset.key} type="button" aria-pressed={on} className={`catalog-bandwidth-preset${on ? " is-on" : ""}`} title={preset.mbps === null ? "口径设为不承诺带宽(两格仅置灰,⛔ 不清空)" : `上下行各 ${preset.mbps} Mbps`} onClick={() => applyTier(preset.mbps)}>{preset.label}</button>;
-            })}
-          </div>
-        </div>}
-        <p>带宽作为套餐属性保存,首期不按带宽拆分计价。</p><label>套餐说明<textarea rows={4} value={values.description} onChange={(event) => field("description", event.target.value)} placeholder="说明适用场景、服务权益和报价口径" /></label></section>
-      <section className="catalog-cost-editor">
-        <div className="catalog-heading-with-info">
-          <h3><span>04</span> 月成本项</h3>
-          <CatalogInfo label="月成本项说明">{`${PLAN_COST_ITEM_SAVE_NOTE}(整段全量替换,逐行增删不单独提交)`}</CatalogInfo>
-        </div>
-        {costLoad.error && <FetchError message={costLoad.error.message} onRetry={costLoad.reload} className="catalog-editor-error" />}
-        {costs.map((cost, index) => <div className="catalog-cost-editor-row" key={index}><input aria-label={`成本项 ${index + 1} 名称`} maxLength={60} value={cost.item_name} onChange={(event) => { setCostsDirty(true); setCosts((current) => current.map((item, i) => i === index ? { ...item, item_name: event.target.value } : item)); }} placeholder="成本项名称" /><span className="catalog-price-input"><input aria-label={`成本项 ${index + 1} 金额`} inputMode="decimal" value={cost.amount} onChange={(event) => { setCostsDirty(true); setCosts((current) => current.map((item, i) => i === index ? { ...item, amount: event.target.value } : item)); }} placeholder="金额" /></span><button aria-label={`移除成本项 ${index + 1}`} onClick={() => { setCostsDirty(true); setCosts((current) => current.filter((_, i) => i !== index)); }} type="button"><X size={16} /></button></div>)}
-        <button className="catalog-cost-add" onClick={() => { setCostsDirty(true); setCosts((current) => [...current, { item_name: "", amount: "", billing_unit: "", remark: "" }]); }} type="button"><Plus size={15} /> 添加成本项</button>
-      </section>
-      {error && <p className="catalog-editor-error" role="alert">{error}</p>}
-      <footer><button type="button" className="catalog-button catalog-button-secondary" onClick={onClose}>取消</button><button type="submit" className="catalog-button catalog-button-primary">{original ? "保存修改" : "新建套餐"}</button></footer>
-    </form>
-  </dialog>;
-}
-
 /** 台账列宽:序号/操作列固定,其余按阅读需求分配(同合同台账口径)。
  *  套餐说明已收进名称旁问号图标,不再单列;用途分类改由表体内分组行承载,两 Tab 同列(2026-11-15)。 */
 const PLAN_COLUMNS = [58, 250, 122, 122, 108, 96, 168, 84, 118] as const;
+/** 自定义档台账多两列:建档人/建档团队(固定档不加)。 */
+const CUSTOM_PLAN_COLUMNS = [...PLAN_COLUMNS, 132, 132] as const;
 
 /**
  * 自定义档台账行:与固定档同形的精简行(⛔ 档位编号/类型标签/单位后缀/货币符号)。
@@ -380,7 +136,7 @@ function CustomPlanRow({ plan, index, writable, readOnlyNote, onEdit, onDelete }
       <span className="catalog-plan-name">
         <strong title={plan.plan_name || undefined}>{plan.plan_name || <Tri tone="missing" text={WORD_UNCONFIGURED} />}</strong>
         {plan.plan_desc ? <PlanDescNote name={plan.plan_name || plan.plan_id} desc={plan.plan_desc} /> : null}
-        {plan.derived_from_contract_item_id ? <span className="catalog-plan-tag">合同条目派生</span> : null}
+        {plan.plan_family ? <span className="catalog-plan-tag">{familyLabel(plan.plan_family)}</span> : null}
       </span>
       <small className="catalog-plan-owner" title={plan.customer_name ?? undefined}>归属客户 · {plan.customer_name || WORD_UNCONFIGURED}</small>
     </td>
@@ -390,27 +146,23 @@ function CustomPlanRow({ plan, index, writable, readOnlyNote, onEdit, onDelete }
     <td>{intCell(plan.sub_account_quota)}</td>
     <td>{ledgerBandwidth(plan)}</td>
     <td title="后端 referred_count:被合同条目/订阅引用数">{intCell(plan.referred_count)}</td>
-    <td>{plan.derived_from_contract_item_id
-      ? (writable
-        ? <div className="catalog-row-actions"><button type="button" className="is-danger" aria-label="删除套餐" onClick={onDelete} title="派生自定义档是合同条目的只读投影:目录侧无编辑/改名入口,改数回合同条目改;未被订阅引用时可删除"><Trash2 size={15} /></button></div>
-        : <small className="catalog-readonly-note">合同条目派生 · 只读</small>)
-      : writable
-        ? <div className="catalog-row-actions"><button type="button" aria-label="编辑套餐" onClick={onEdit} title="编辑套餐"><PencilLine size={15} /></button><button type="button" className="is-danger" aria-label="删除套餐" onClick={onDelete} title="删除套餐(引用拦截由服务端判定)"><Trash2 size={15} /></button></div>
-        : <small className="catalog-readonly-note">{readOnlyNote}</small>}</td>
+    <td title={plan.created_by ?? undefined}>{plan.created_by_name || <Tri tone="missing" text={WORD_UNCONFIGURED} />}</td>
+    <td title={plan.created_team_id ?? undefined}>{plan.created_team_name || <Tri tone="missing" text={WORD_UNCONFIGURED} />}</td>
+    <td>{writable
+      ? <div className="catalog-row-actions"><button type="button" aria-label="编辑套餐" onClick={onEdit} title="编辑套餐"><PencilLine size={15} /></button><button type="button" className="is-danger" aria-label="删除套餐" onClick={onDelete} title="删除套餐(引用拦截由服务端判定)"><Trash2 size={15} /></button></div>
+      : <small className="catalog-readonly-note">{readOnlyNote}</small>}</td>
   </tr>;
 }
 
 /** 固定档按用途分类分组的一行表头(分组落在表体内,与原型同形):分类名+「X · 口径说明」(X 为订阅方式值,不再冠「订阅方式:」)。
  *  用途分类由本行承载,档位行不再单列该字段(2026-11-15)。 */
-function PlanGroupRow({ title, hint }: { title: string; hint?: string }) {
-  return <tr className="catalog-group-row"><td colSpan={9}><strong>{title}</strong>{hint && <span>{hint}</span>}</td></tr>;
+function PlanGroupRow({ title, hint, colSpan }: { title: string; hint?: string; colSpan: number }) {
+  return <tr className="catalog-group-row"><td colSpan={colSpan}><strong>{title}</strong>{hint && <span>{hint}</span>}</td></tr>;
 }
 
-/** 原型 `pkgSubMode`:用途分类决定订阅方式(叠加增值可叠加、定制化单独约定、其余可升降配)。 */
-function orderModeOf(category: string) {
-  if (category === "叠加增值") return "可叠加";
-  if (category === "定制化") return "单独约定";
-  return "可升降配";
+/** 交付形态对应的订阅方式提示(`link` 可升降配、`addon` 可叠加)。 */
+function orderModeOf(family: string) {
+  return family === "addon" ? "可叠加" : "可升降配";
 }
 
 /**
@@ -427,7 +179,7 @@ function FixedPlanRow({ plan, index, writable, readOnlyNote, onEdit, onDelete }:
       <span className="catalog-plan-name">
         <strong>{plan.plan_name || <Tri tone="missing" text={WORD_UNCONFIGURED} />}</strong>
         {plan.plan_desc ? <PlanDescNote name={plan.plan_name || plan.plan_id} desc={plan.plan_desc} /> : null}
-        {plan.derived_from_contract_item_id ? <span className="catalog-plan-tag">合同条目派生</span> : null}
+        {plan.plan_family ? <span className="catalog-plan-tag">{familyLabel(plan.plan_family)}</span> : null}
       </span>
     </td>
     <td className="catalog-ledger-price">{ledgerMoney(plan.annual_price_cents)}</td>
@@ -436,13 +188,9 @@ function FixedPlanRow({ plan, index, writable, readOnlyNote, onEdit, onDelete }:
     <td>{intCell(plan.sub_account_quota)}</td>
     <td>{ledgerBandwidth(plan)}</td>
     <td title="后端 referred_count:被合同条目/订阅引用数">{intCell(plan.referred_count)}</td>
-    <td>{plan.derived_from_contract_item_id
-      ? (writable
-        ? <div className="catalog-row-actions"><button type="button" className="is-danger" aria-label="删除套餐" onClick={onDelete} title="派生自定义档是合同条目的只读投影:目录侧无编辑/改名入口,改数回合同条目改;未被订阅引用时可删除"><Trash2 size={15} /></button></div>
-        : <small className="catalog-readonly-note">合同条目派生 · 只读</small>)
-      : writable
-        ? <div className="catalog-row-actions"><button type="button" aria-label="编辑套餐" onClick={onEdit} title="编辑套餐"><PencilLine size={15} /></button><button type="button" className="is-danger" aria-label="删除套餐" onClick={onDelete} title="删除套餐(引用拦截由服务端判定)"><Trash2 size={15} /></button></div>
-        : <small className="catalog-readonly-note">{readOnlyNote}</small>}</td>
+    <td>{writable
+      ? <div className="catalog-row-actions"><button type="button" aria-label="编辑套餐" onClick={onEdit} title="编辑套餐"><PencilLine size={15} /></button><button type="button" className="is-danger" aria-label="删除套餐" onClick={onDelete} title="删除套餐(引用拦截由服务端判定)"><Trash2 size={15} /></button></div>
+      : <small className="catalog-readonly-note">{readOnlyNote}</small>}</td>
   </tr>;
 }
 
@@ -730,15 +478,14 @@ export function PackageManagementPage() {
     const timer = window.setTimeout(() => setNotice(""), NOTICE_DISMISS_MS);
     return () => window.clearTimeout(timer);
   }, [notice]);
-  /** 自定义档恒为「定制化」用途分类;用途分类筛选只在固定档 Tab 出现(2026-11-15)。 */
   const isCustomTab = tab === "custom";
-  /** 用途分类改为表体内分组行承载,两个 Tab 同为 9 列(2026-11-15)。 */
-  const ledgerColSpan = 9;
+  /** 自定义档多「建档人/建档团队」两列;固定档仍 9 列。 */
+  const ledgerColSpan = isCustomTab ? 11 : 9;
   /** 检索一次算清,两个 tab 各取自己那一半;计数同源(总则§6.3),⛔ 各算一次。
    *  自定义档没有可选分类,进自定义 Tab 时分类筛选不参与过滤(否则会筛成空表)。 */
   const activeCategory = isCustomTab ? "all" : category;
-  const filtered = useMemo(() => rows.filter((plan) => (activeCategory === "all" || categoryLabel(plan.use_category) === activeCategory)
-    && `${plan.plan_name} ${categoryLabel(plan.use_category) ?? ""} ${bandwidthTextOfRow(plan).text} ${plan.plan_desc ?? ""} ${plan.customer_name ?? ""}`.toLowerCase().includes(search.trim().toLowerCase())), [rows, activeCategory, search]);
+  const filtered = useMemo(() => rows.filter((plan) => (activeCategory === "all" || plan.plan_family === activeCategory)
+    && `${plan.plan_name} ${familyLabel(plan.plan_family) ?? ""} ${bandwidthTextOfRow(plan).text} ${plan.plan_desc ?? ""} ${plan.customer_name ?? ""} ${plan.created_by_name ?? ""} ${plan.created_team_name ?? ""}`.toLowerCase().includes(search.trim().toLowerCase())), [rows, activeCategory, search]);
   const fixed = filtered.filter((plan) => plan.plan_kind !== "custom");
   const custom = filtered.filter((plan) => plan.plan_kind === "custom");
   const fixedCount = rows.filter((plan) => plan.plan_kind !== "custom").length;
@@ -749,12 +496,12 @@ export function PackageManagementPage() {
   /** 固定套餐按用途分类分组,分组行落在表体内;后端不下发 use_category 的档位单列一组,⛔ 静默丢行。
    *  序号取「表内显示顺序」(分组后位置),⛔ 用后端数组下标——否则分组一排序就出现 7 在 6 前面。 */
   const fixedGroups = useMemo(() => {
-    const nameOf = (plan: CatalogPlanRow) => categoryLabel(plan.use_category);
-    const known = packageCategories
-      .map((item) => ({ name: item.name as string, hint: `${orderModeOf(item.name)} · ${item.hint}`, plans: pageRows.filter((plan) => nameOf(plan) === item.name) }))
+    const familyOf = (plan: CatalogPlanRow) => plan.plan_family;
+    const known = planFamilies
+      .map((item) => ({ name: item.name as string, hint: `${orderModeOf(item.code)} · ${item.hint}`, plans: pageRows.filter((plan) => familyOf(plan) === item.code) }))
       .filter((group) => group.plans.length > 0);
-    const uncategorized = pageRows.filter((plan) => !packageCategories.some((item) => item.name === nameOf(plan)));
-    const groups = uncategorized.length ? [...known, { name: WORD_UNCONFIGURED, hint: `用途分类:${WORD_NOT_PROVIDED}`, plans: uncategorized }] : known;
+    const uncategorized = pageRows.filter((plan) => !planFamilies.some((item) => item.code === familyOf(plan)));
+    const groups = uncategorized.length ? [...known, { name: WORD_UNCONFIGURED, hint: `交付形态:${WORD_NOT_PROVIDED}`, plans: uncategorized }] : known;
     let position = 0;
     return groups.map((group) => ({ name: group.name, hint: group.hint, entries: group.plans.map((plan) => ({ plan, position: position++ })) }));
   }, [pageRows]);
@@ -857,7 +604,7 @@ export function PackageManagementPage() {
           <div className="ops-toolbar">
             <label className="ops-search"><Search size={17} /><Input aria-label="搜索套餐" placeholder={isCustomTab ? "搜索名称、带宽、说明或归属客户" : "搜索名称、分类、带宽、说明或归属客户"} value={search} onChange={(event) => { setSearch(event.target.value); paging.resetPage(); }} />{search && <button type="button" aria-label="清空搜索" onClick={() => { setSearch(""); paging.resetPage(); }}><X size={15} /></button>}</label>
             {/* 自定义档恒为「定制化」,没有可选项 ⇒ 该 Tab 不出分类筛选(⛔ 给一个筛完必空的控件)。 */}
-            {!isCustomTab && <FilterSelect icon="type" aria-label="用途分类筛选" value={category} onChange={(event) => { setCategory(event.target.value); paging.resetPage(); }}><option value="all">全部用途分类</option>{packageCategories.map((item) => <option key={item.name}>{item.name}</option>)}</FilterSelect>}
+            {!isCustomTab && <FilterSelect icon="type" aria-label="交付形态筛选" value={category} onChange={(event) => { setCategory(event.target.value); paging.resetPage(); }}><option value="all">全部交付形态</option>{planFamilies.map((item) => <option key={item.code} value={item.code}>{item.name}</option>)}</FilterSelect>}
             {(search || (!isCustomTab && category !== "all")) && <Button variant="ghost" size="sm" onClick={resetFilters}>重置筛选</Button>}
             <span className="catalog-ledger-note">{tab === "custom" ? "自定义套餐只属于一个客户,不进公共目录" : "固定套餐为公共档,所有客户可选"}{truncated ? `;目录共 ${truncated} 条,当前仅载入 ${rows.length} 条` : ""}</span>
             {/* 新增入口跟着 Tab 走:固定档只有总运营能新建,自定义套餐由总运营/运营主账号建。 */}
@@ -866,16 +613,16 @@ export function PackageManagementPage() {
                 ? <button type="button" className="catalog-button catalog-button-primary catalog-toolbar-action" onClick={() => setEditor({ owner: null })}><Plus size={17} />新增固定套餐</button>
                 : <span className="catalog-head-note catalog-toolbar-action">区域运营不能配置公共固定档</span>)
               : (canWrite
-                ? <button type="button" className="catalog-button catalog-button-primary catalog-toolbar-action" onClick={() => setEditor({ owner: "" })}><Plus size={17} />新增自定义套餐</button>
+                ? <button type="button" className="catalog-button catalog-button-primary catalog-toolbar-action" onClick={() => setEditor({ owner: "", planKind: "custom" })}><Plus size={17} />新增自定义套餐</button>
                 : <span className="catalog-head-note catalog-toolbar-action">本角色只读,不能新增自定义套餐</span>)}
           </div>
           <div ref={tableOverflow.ref} tabIndex={0} role="region" aria-label="套餐档位台账,可横向滚动查看字段" className={`measured-table-scroll ops-table-wrap catalog-table-wrap${tableOverflow.overflow ? " has-horizontal-overflow" : ""}${tableOverflow.canScrollLeft ? " can-scroll-left" : ""}${tableOverflow.canScrollRight ? " can-scroll-right" : ""}`}>
             <table className="ops-table catalog-ledger">
-              <OpsTableColumns widths={PLAN_COLUMNS} />
-              <thead><tr><th>序号</th><th>套餐</th><th>年订阅价格</th><th>月结算标准</th><th>月成本</th><th>分账号额度</th><th>总带宽</th><th>订阅量</th><th>操作</th></tr></thead>
+              <OpsTableColumns widths={isCustomTab ? CUSTOM_PLAN_COLUMNS : PLAN_COLUMNS} />
+              <thead><tr><th>序号</th><th>套餐</th><th>年订阅价格</th><th>月结算标准</th><th>月成本</th><th>分账号额度</th><th>总带宽</th><th>订阅量</th>{isCustomTab && <><th>建档人</th><th>建档团队</th></>}<th>操作</th></tr></thead>
               <tbody>
                 {tab === "fixed"
-                  ? fixedGroups.map((group) => <Fragment key={group.name}><PlanGroupRow title={group.name} hint={group.hint} />{group.entries.map(({ plan, position }) => fixedRow(plan, position))}</Fragment>)
+                  ? fixedGroups.map((group) => <Fragment key={group.name}><PlanGroupRow title={group.name} hint={group.hint} colSpan={ledgerColSpan} />{group.entries.map(({ plan, position }) => fixedRow(plan, position))}</Fragment>)
                   : pageRows.map((plan, index) => planRow(plan, index))}
                 {(!catalog.error && visible.length === 0) && <OpsTableEmpty colSpan={ledgerColSpan}>{emptyMessage}</OpsTableEmpty>}
                 {catalog.error && <OpsTableEmpty colSpan={ledgerColSpan}>{emptyMessage}</OpsTableEmpty>}
@@ -887,7 +634,7 @@ export function PackageManagementPage() {
     </div>
     {notice && <div className="catalog-toast" role="status"><span>{notice}</span><button aria-label="关闭提示" onClick={() => setNotice("")}><X size={16} /></button></div>}
     {failure && <div className="catalog-toast" role="alert"><span>{failure}</span><button aria-label="关闭提示" onClick={() => setFailure("")}><X size={16} /></button></div>}
-    {editor && <PackageEditor key={editor.plan?.plan_id ?? `new-${editor.owner ?? "fixed"}`} state={editor} tiers={tiers} onClose={() => setEditor(null)} onSaved={saved} />}
+    {editor && <PackagePlanEditor key={editor.plan?.plan_id ?? `new-${editor.owner ?? "fixed"}`} state={editor} tiers={tiers} onClose={() => setEditor(null)} onSaved={saved} />}
     {deleteTarget && <div className="catalog-confirm-backdrop"><div className="catalog-confirm" role="alertdialog" aria-modal="true" aria-labelledby="catalog-confirm-title">
       {deleteError
         ? <><span className="catalog-confirm-icon"><Trash2 size={20} /></span><h2 id="catalog-confirm-title">无法删除该套餐档位</h2><p>{deleteError}</p>

+ 1 - 1
web-scaffold/src/pages/PartyViewPages.tsx

@@ -772,7 +772,7 @@ export function PartyCustomerListPage({ kind }: { kind: "partner" | "operator" }
 function contractNameOf(row: ContractRow) {
   const items = row.service_items ?? [];
   const names = items
-    .map((item) => item.plan_name ?? item.derived_plan_name ?? (item.item_kind === "custom_spec" ? VIEW_CONFIG_UNSET : null))
+    .map((item) => item.plan_name)
     .filter((name): name is string => Boolean(name && name.trim()));
   if (!names.length) return <Tri tone="missing" text={WORD_UNCONFIGURED} title="本合同未登记服务条目,无法从条目汇总名称(合同数据模型不存名称列)" />;
   return (

+ 2 - 2
web-scaffold/src/pages/WorkOrderRecordPage.tsx

@@ -21,7 +21,7 @@ import { uploadTicketMaterial } from "../lib/api/oss-upload";
 import { classifyTicketError, fmtDate, fmtTime, numText, submitErrorText, useTicketDetail } from "../lib/ticket";
 import { missingGroupsOf } from "../lib/ticket-gaps";
 import { workOrderSteps } from "../lib/work-order-steps";
-import { ACCT_STATUS, label, PLAN_KIND, ORDER_STATUS, USE_CATEGORY } from "../lib/api/labels";
+import { ACCT_STATUS, label, PLAN_FAMILY, PLAN_KIND, ORDER_STATUS } from "../lib/api/labels";
 import {
   BANDWIDTH_TIERS, IP_ROW_FIELDS, IP_TYPES, OVERSEAS_IP_MAX_ROWS,
   ROUTE_FIELDS, ROUTE_MAX_ROWS,
@@ -1135,7 +1135,7 @@ export function WorkOrderRecordPage() {
             <div className="work-order-trace"><span>联系人 / 电话</span><strong>{[refCustomer.contact_name, refCustomer.contact_mobile].filter(Boolean).join(" / ") || "-"}</strong></div>
             <div className="work-order-trace"><span>通信地址</span><strong>{refCustomer.address ?? "-"}</strong></div>
           </> : <p className="work-order-reference-empty">该单未关联客户档案。</p>}
-          {refOrder && <div className="work-order-trace"><span>关联订阅</span><strong><button type="button" className="work-order-trace-link" onClick={() => openRef({ kind: "order", id: refOrder.subscription_id, name: refOrder.plan_name })}>{refOrder.plan_name ?? refOrder.subscription_id}</button></strong><small>{[refOrder.subscription_id, label(PLAN_KIND, refOrder.plan_kind), label(USE_CATEGORY, refOrder.use_category), label(ORDER_STATUS, refOrder.status), refOrder.actual_opened_at ? `实际开通 ${fmtDate(refOrder.actual_opened_at)}` : null].filter(Boolean).join(" · ")}</small></div>}
+          {refOrder && <div className="work-order-trace"><span>关联订阅</span><strong><button type="button" className="work-order-trace-link" onClick={() => openRef({ kind: "order", id: refOrder.subscription_id, name: refOrder.plan_name })}>{refOrder.plan_name ?? refOrder.subscription_id}</button></strong><small>{[refOrder.subscription_id, label(PLAN_KIND, refOrder.plan_kind), label(PLAN_FAMILY, refOrder.plan_family), label(ORDER_STATUS, refOrder.status), refOrder.actual_opened_at ? `实际开通 ${fmtDate(refOrder.actual_opened_at)}` : null].filter(Boolean).join(" · ")}</small></div>}
         </section>
         <section className="work-order-section">
           <h2>追溯与关联</h2>

+ 6 - 4
web-scaffold/tests/domain-foundation.test.mjs

@@ -106,10 +106,12 @@ test("带宽档位=套餐带宽权益的快捷预设(2026-11-17 改用途,
   const catalog = readFileSync(new URL("../src/pages/PackageManagementPage.tsx", import.meta.url), "utf8");
   /** ① 档位清单的下拉顺序已不再服务合同页。 */
   assert.equal(catalog.includes("合同页下拉顺序"), false);
-  /** ② 固定档/自定义档编辑器共用同一个带宽档位快捷控件。 */
-  assert.match(catalog, /tiers=\{tiers\}/);
-  assert.match(catalog, /catalog-bandwidth-presets/);
-  assert.match(catalog, /applyTier/);
+  /** ② 固定档/自定义档编辑器共用同一个带宽档位快捷控件(2026-11-19 抽到 `PackagePlanEditor`)。 */
+  const editor = readFileSync(new URL("../src/components/PackagePlanEditor.tsx", import.meta.url), "utf8");
+  assert.match(catalog, /PackagePlanEditor/);
+  assert.match(editor, /tierPresets/);
+  assert.match(editor, /catalog-bandwidth-presets/);
+  assert.match(editor, /applyTier/);
   /** ③ 合同页不再出现档位快捷(合同只按套餐与份数登记)。 */
   const contract = readFileSync(new URL("../src/pages/ContractDetailPages.tsx", import.meta.url), "utf8");
   assert.equal(contract.includes("catalog-bandwidth-preset"), false);

Some files were not shown because too many files changed in this diff