ソースを参照

feat(front-end): 套餐目录/合同/订阅页面接入与标签、三态组件补齐

新增 CatalogPage、ContractsPage、ContractDetailPage、SubscriptionsPage、
SubscriptionDetailPage、EntSubscriptionsPage 与订阅表单弹窗,配套
lockedCopy 逐字文案、triState 三态组件、labels 枚举标签与路由权限接线。
cg 1 週間 前
親
コミット
70dab56b95

+ 70 - 13
front-end/src/App.tsx

@@ -1,5 +1,5 @@
 import { Navigate, Route, Routes } from "react-router-dom";
-import { firstRoute } from "./auth/nav";
+import { firstRoute, routesFor } from "./auth/nav";
 import { useSession } from "./auth/session";
 import { getToken } from "./api/http";
 import { Btn } from "./components/ui";
@@ -16,6 +16,13 @@ import { OperatorsPage } from "./pages/OperatorsPage";
 import { PartnersPage } from "./pages/PartnersPage";
 import { RegionsPage } from "./pages/RegionsPage";
 import { SubAccountsPage } from "./pages/SubAccountsPage";
+// 第3册:套餐目录/合同管理/订阅维护(默认导出,与本册既有页面一致的骨架范式)
+import CatalogPage from "./pages/CatalogPage";
+import ContractDetailPage from "./pages/ContractDetailPage";
+import ContractsPage from "./pages/ContractsPage";
+import EntSubscriptionsPage from "./pages/EntSubscriptionsPage";
+import SubscriptionDetailPage from "./pages/SubscriptionDetailPage";
+import SubscriptionsPage from "./pages/SubscriptionsPage";
 
 function Guard({ children }: { children: React.ReactNode }) {
   const { ctx, loading, error, reload } = useSession();
@@ -39,6 +46,19 @@ function Guard({ children }: { children: React.ReactNode }) {
   return <>{children}</>;
 }
 
+/**
+ * 路由级权限守卫(BOS-01):`Guard` 只证明「已登录且有角色」,此前任何身份地址栏直连
+ * `#/regions`/`#/imports` 都会渲染出页面骨架,要等后端回 `11001`/`60058` 才拦住。
+ * 这里以 `routesFor` 为唯一真源(菜单与路由同一张表,⛔ 两处清单各写一份):越界不渲染
+ * 页面骨架,直接落回本角色侧栏首项。带参路由(`customers/:id`)按顶层段传 `route`。
+ */
+function RequireRole({ route, children }: { route: string; children: React.ReactNode }) {
+  const { ctx } = useSession();
+  const role = ctx?.role_code;
+  if (role && !routesFor(role).includes(route)) return <Navigate to={`/${firstRoute(role)}`} replace />;
+  return <>{children}</>;
+}
+
 export default function App() {
   const { ctx } = useSession();
   return (
@@ -50,18 +70,55 @@ export default function App() {
           <Guard>
             <Routes>
               <Route index element={<Navigate to={firstRoute(ctx?.role_code)} replace />} />
-              <Route path="home" element={<HomePage />} />
-              <Route path="regions" element={<RegionsPage />} />
-              <Route path="operators" element={<OperatorsPage />} />
-              <Route path="partners" element={<PartnersPage />} />
-              <Route path="entteams" element={<EntTeamsPage />} />
-              <Route path="opsteams" element={<OpsTeamsPage />} />
-              <Route path="members" element={<MembersPage />} />
-              <Route path="customers" element={<CustomersPage />} />
-              <Route path="customers/:id" element={<CustomerDetailPage />} />
-              <Route path="imports" element={<ImportBatchesPage />} />
-              <Route path="subaccounts" element={<SubAccountsPage />} />
-              <Route path="audit" element={<AuditPage />} />
+              <Route path="home" element={<RequireRole route="home"><HomePage /></RequireRole>} />
+              <Route path="regions" element={<RequireRole route="regions"><RegionsPage /></RequireRole>} />
+              <Route path="operators" element={<RequireRole route="operators"><OperatorsPage /></RequireRole>} />
+              <Route path="partners" element={<RequireRole route="partners"><PartnersPage /></RequireRole>} />
+              <Route path="entteams" element={<RequireRole route="entteams"><EntTeamsPage /></RequireRole>} />
+              <Route path="opsteams" element={<RequireRole route="opsteams"><OpsTeamsPage /></RequireRole>} />
+              <Route path="members" element={<RequireRole route="members"><MembersPage /></RequireRole>} />
+              <Route path="customers" element={<RequireRole route="customers"><CustomersPage /></RequireRole>} />
+              <Route
+                path="customers/:id"
+                element={
+                  <RequireRole route="customers">
+                    <CustomerDetailPage />
+                  </RequireRole>
+                }
+              />
+              <Route
+                path="customers/:id/subs"
+                element={
+                  <RequireRole route="customers">
+                    <EntSubscriptionsPage />
+                  </RequireRole>
+                }
+              />
+              <Route path="catalog" element={<RequireRole route="catalog"><CatalogPage /></RequireRole>} />
+              <Route path="contracts" element={<RequireRole route="contracts"><ContractsPage /></RequireRole>} />
+              <Route
+                path="contracts/:id"
+                element={
+                  <RequireRole route="contracts">
+                    <ContractDetailPage />
+                  </RequireRole>
+                }
+              />
+              <Route path="subs" element={<RequireRole route="subs"><SubscriptionsPage /></RequireRole>} />
+              <Route
+                path="subs/:id"
+                element={
+                  <RequireRole route="subs">
+                    <SubscriptionDetailPage />
+                  </RequireRole>
+                }
+              />
+              <Route path="imports" element={<RequireRole route="imports"><ImportBatchesPage /></RequireRole>} />
+              <Route
+                path="subaccounts"
+                element={<RequireRole route="subaccounts"><SubAccountsPage /></RequireRole>}
+              />
+              <Route path="audit" element={<RequireRole route="audit"><AuditPage /></RequireRole>} />
               <Route path="*" element={<Navigate to={firstRoute(ctx?.role_code)} replace />} />
             </Routes>
           </Guard>

+ 160 - 13
front-end/src/api/bos.ts

@@ -23,6 +23,7 @@ import type {
   AuditListResult,
   AuthContext,
   CatalogCreateResult,
+  CatalogDeleteResult,
   CatalogGetResult,
   CatalogListResult,
   CatalogUpdateResult,
@@ -31,9 +32,11 @@ import type {
   CostItemListResult,
   CostItemSaveResult,
   ContractCreateResult,
+  ContractDeleteResult,
   ContractGetResult,
   ContractIpEntry,
   ContractListResult,
+  ContractLookupResult,
   ContractServiceItem,
   ContractUpdateResult,
   CustomerAttributionResult,
@@ -45,6 +48,8 @@ import type {
   CustomerInfluence,
   CustomerListResult,
   CustomerMoveRegionResult,
+  CustomerOption,
+  ListOf,
   CustomerUpdateResult,
   EntTeamCreateResult,
   EntTeamDeleteResult,
@@ -92,6 +97,8 @@ import type {
   PartnerScopeSaveResult,
   PartnerUpdateResult,
   PingInfo,
+  PlanCostItemRow,
+  PlanCostItemSaveResult,
   ReconAccountCreateResult,
   ReconAccountGetResult,
   RegionChangeLogResult,
@@ -108,12 +115,23 @@ import type {
   SubAccountListResult,
   SubAccountUpdateResult,
   SubscriptionChangeResult,
+  SubscriptionContractOption,
   SubscriptionCreateResult,
+  SubscriptionDeleteCheckResult,
+  SubscriptionDeleteResult,
   SubscriptionGetResult,
   SubscriptionListResult,
+  SubscriptionPlanOption,
   SubscriptionStackResult,
+  SubscriptionUpdateResult,
 } from "./types";
 
+/** 列表口归一化:兼容裸数组与 `{items: []}` 两种 `data` 形状。 */
+export function rowsOf<T>(v: ListOf<T>): T[] {
+  if (!v) return [];
+  return Array.isArray(v) ? v : (v.items ?? []);
+}
+
 /* ── 系统健康(3) ─────────────────────────────────────────────── */
 
 /** 健康检查 [实] —— 服务存活探测,无需登录。 */
@@ -429,21 +447,35 @@ export const subAccountGetList = (d: { customer_id: string; page?: number; page_
 export const subAccountUpdate = (d: { sub_account_id: string; display_name?: string; network_account_name?: string }) =>
   post<SubAccountUpdateResult>("/sub_account/update@v1", d);
 
-/* ── 套餐档位(4) ─────────────────────────────────────────────── */
+/* ── 套餐档位(catalog 8)─────────────────────────────────────── */
 
-/** 新建套餐档位 [位] —— 自定义档必填 customer_id;拒收 monthly_settle_cents/sub_mode/first_referred_at。 */
+/**
+ * 新建套餐档位 [位](契约 §3.1 `/catalog/create@v1`)—— 权限顺序=权限→冻结→字段。
+ *
+ * `opsMain` 自定义档=限负责范围内客户(⛔ Admin-only);固定档载荷出现 `customer_id` ⇒ `11103`。
+ * 带宽契约=上行/下行两格+承诺开关:开关关闭⇒两格⛔ 不提交(服务端记 `FALSE` +两列 `NULL`)。
+ * ⛔ 载荷键:`monthly_settle_cents`/`sub_mode`/`first_referred_at`(`11103`+「该字段由系统带出,不接受录入」)。
+ */
 export const catalogCreate = (d: {
   plan_kind: string;
   plan_name: string;
-  use_category: string;
+  use_category?: string;
   annual_price_cents: number;
   sub_account_quota?: number;
   bandwidth_committed?: boolean;
   bandwidth_up_mbps?: number;
   bandwidth_down_mbps?: number;
   customer_id?: string;
+  line_exits?: string[];
+  plan_desc?: string;
+  sort_no?: number;
+  cost_items?: PlanCostItemRow[];
 }) => post<CatalogCreateResult>("/catalog/create@v1", d);
-/** 编辑套餐档位 [位] —— use_category 建后不可改;被订阅引用冻结后多数字段只读。 */
+/**
+ * 编辑套餐档位 [位](契约 §3.1 `/catalog/update@v1`)—— 服务端 diff 判冻结,命中锁定字段 ⇒ `K204`+`referred_count`。
+ *
+ * 改 `plan_name` 同事务同步未到期订阅 `plan_name`;派生档⛔ 不可编辑(含改名,`11103` 拒)。
+ */
 export const catalogUpdate = (d: {
   plan_id: string;
   plan_name?: string;
@@ -452,6 +484,10 @@ export const catalogUpdate = (d: {
   bandwidth_committed?: boolean;
   bandwidth_up_mbps?: number;
   bandwidth_down_mbps?: number;
+  line_exits?: string[];
+  plan_desc?: string;
+  sort_no?: number;
+  cost_items?: PlanCostItemRow[];
   row_version?: number;
 }) => post<CatalogUpdateResult>("/catalog/update@v1", d);
 /** 套餐档位列表 [位] —— 按 plan_kind 等条件筛选。 */
@@ -484,8 +520,15 @@ export const contractCreate = (d: {
   attachment_url?: string;
   service_items?: ContractServiceItem[];
   ip_entries?: ContractIpEntry[];
+  /** `customer_lookup` 未命中时的自由录入资料:同事务先建档再签本合同(⚠️ 第二步失败不清理客户)。 */
+  customer_free_text?: string;
 }) => post<ContractCreateResult>("/contract/create@v1", d);
-/** 编辑合同 [位] —— 编号与签约客户不可改;条目按 item_id 三向对比增删改。 */
+/**
+ * 编辑合同 [位](契约 §3.2 `/contract/update@v1`)—— `admin`/`opsMain` only,`opsMember` ⇒ `KLT-P301`。
+ *
+ * 编号与签约客户⛔ 可改(出现 ⇒ `L214`);条目三向对比;移除被 `subscription.contract_item_id`
+ * 引用的条目 ⇒ `L213`(指明哪条条目、被哪几份订阅引用)。
+ */
 export const contractUpdate = (d: {
   contract_id: string;
   row_version: number;
@@ -509,24 +552,36 @@ export const contractGetList = (d?: {
   keyword?: string;
   customer_id?: string;
   status?: string;
+  /** 是否已开通三态(派生自工单回填):取数失败只坏这一列,整行⛔ 消失 */
+  opened?: boolean;
 }) => list<ContractListResult>("/contract/get_list@v1", d, d);
 /** 合同详情 [位] —— 含服务条目与 IP 条件。 */
 export const contractGet = (d: { contract_id: string }) => post<ContractGetResult>("/contract/get@v1", d);
 
 /* ── 订阅(5) ─────────────────────────────────────────────────── */
 
-/** 新建订阅 [位] —— 拒收 line_exits/sub_mode/order_no、新建时 end_date、opened_at。 */
+/**
+ * 新建订阅 [位](契约 §3.3 `/subscription/create@v1`)—— 「订阅时长」`term` 是唯一决定期间与价格的输入项。
+ *
+ * ⛔ 载荷键:`annual_price_cents`/`monthly_settle_cents`/`end_date`/`actual_opened_at`/
+ * `line_exits`/`sub_mode`/`order_no`(六项只读+实际开通日,出现即 `11103`)。
+ * 出参=整行+六项只读值+`quota_changed`。
+ */
 export const subscriptionCreate = (d: {
   customer_id: string;
   plan_id: string;
   contract_id: string;
   contract_item_id: string;
+  term: string;
   start_date: string;
-  annual_price_cents: number;
-  monthly_settle_cents: number;
-  use_category?: string;
+  trial_months?: number;
+  remark?: string;
 }) => post<SubscriptionCreateResult>("/subscription/create@v1", d);
-/** 订阅升降配 [位] —— 须填 replaces_subscription_id 且使用新的 contract_id。 */
+/**
+ * 订阅升降配 [位](契约 §3.3 `/subscription/change@v1`)—— `replaces_subscription_id` 必填,
+ * 两金额改由服务端派生(⛔ `annual_price_cents`/`monthly_settle_cents`);原合同出现 ⇒ `11103`。
+ * ⚠️ 弹窗不做出口一致性校验(需求明文「出口不同也照样承接」)。
+ */
 export const subscriptionChange = (d: {
   replaces_subscription_id: string;
   customer_id: string;
@@ -534,9 +589,9 @@ export const subscriptionChange = (d: {
   contract_id: string;
   contract_item_id: string;
   start_date: string;
-  annual_price_cents: number;
-  monthly_settle_cents: number;
-  use_category?: string;
+  term?: string;
+  trial_months?: number;
+  remark?: string;
 }) => post<SubscriptionChangeResult>("/subscription/change@v1", d);
 /** 订阅叠加或白名单更新 [位] —— 仅两金额+end_date 等白名单字段可写。 */
 export const subscriptionStack = (d: {
@@ -557,10 +612,102 @@ export const subscriptionGetList = (d?: {
   page_size?: number;
   keyword?: string;
   status?: string;
+  use_category?: string;
+  term?: string;
 }) => list<SubscriptionListResult>("/subscription/get_list@v1", d, d);
 /** 订阅详情 [位]。 */
 export const subscriptionGet = (d: { subscription_id: string }) => post<SubscriptionGetResult>("/subscription/get@v1", d);
 
+/* ── 第3册新增写口与派生口(契约 §3 缺口补齐)───────────────────── */
+
+/** 可选客户集合 [位](`/catalog/customer_options@v1`)—— 出参=操作人可见客户集合(自定义档归属客户)。 */
+export const catalogCustomerOptions = () => list<ListOf<CustomerOption>>("/catalog/customer_options@v1");
+
+/**
+ * 档位删除预检+删除 [位](`/catalog/delete@v1`)—— 删除四步:冻结→引用拦截→处置指引→物理删除。
+ *
+ * 被引用 ⇒ 不删、置 `frozen`、返 `referred_count` 与订阅/条目清单;处置指引原样透出服务端 `suggest`。
+ */
+export const catalogDelete = (d: { plan_id: string }) => post<CatalogDeleteResult>("/catalog/delete@v1", d);
+
+/**
+ * 随附成本项列表 [位](`/plan_cost_item/get_list@v1`,`status='active'` 升序全量、不分页)。
+ *
+ * ⛔ 出现任何汇总键(`amount_total_cents`/`total`/`monthly_cost_cents`)——列表不显示合计。
+ */
+export const planCostItemList = (d: { plan_id: string }) => list<ListOf<PlanCostItemRow>>("/plan_cost_item/get_list@v1", d);
+
+/** 保存随附成本项 [位](`/plan_cost_item/save@v1`)—— 整段全量替换,⛔ 逐行增删改。 */
+export const planCostItemSave = (d: { plan_id: string; items: PlanCostItemRow[] }) =>
+  post<PlanCostItemSaveResult>("/plan_cost_item/save@v1", d);
+
+/**
+ * 签约客户检索 [位](`/contract/customer_lookup@v1`)—— 三种命中方式:信用码→证件号→名称模糊。
+ *
+ * ⛔ 未命中不报错:`matched=false`+空数组 ⇒ 表单转自由录入(页面⛔ 红叉、⛔ 11102)。
+ */
+export const contractCustomerLookup = (d: { credit_code?: string; identity_no?: string; customer_name?: string }) =>
+  post<ContractLookupResult>("/contract/customer_lookup@v1", d);
+
+/**
+ * 删除合同 [位](`/contract/delete@v1`)—— 有订阅引用⇒拦截;无引用但工单未到终态⇒拦截;
+ * 无引用且工单终态或无工单⇒物理删除。拦截清单原样透出服务端 `detail`。
+ */
+export const contractDelete = (d: { contract_id: string }) => post<ContractDeleteResult>("/contract/delete@v1", d);
+
+/**
+ * 可选套餐 [位](`/subscription/plan_options@v1`)—— 同一次返回该客户自定义档(含派生档)+全部固定档,
+ * 出参含 `plan_kind`/`line_exits[]`/`sub_mode`+派生标识与来源。
+ */
+export const subscriptionPlanOptions = (d: { customer_id: string }) =>
+  list<ListOf<SubscriptionPlanOption>>("/subscription/plan_options@v1", d);
+
+/**
+ * 可选合同条目 [位](`/subscription/contract_options@v1`)—— 出参含 `contract_no`/`item_kind`/
+ * `plan_id`/`plan_id_derived`。⛔ 出参不含任何「月结算标准金额」键(金额一律取套餐)。
+ */
+export const subscriptionContractOptions = (d: { customer_id: string }) =>
+  list<ListOf<SubscriptionContractOption>>("/subscription/contract_options@v1", d);
+
+/**
+ * 编辑订阅 [位](`/subscription/update@v1`)—— 白名单只有 `trial_months`/`discount_monthly_cents`;
+ * 载荷出现其他字段(合同、合同条目、状态、线路出口、两个金额)⇒ `11103`+`detail.fields[].reason`。
+ */
+export const subscriptionUpdate = (d: {
+  subscription_id: string;
+  trial_months?: number;
+  discount_monthly_cents?: number;
+  row_version?: number;
+}) => post<SubscriptionUpdateResult>("/subscription/update@v1", d);
+
+/**
+ * 删除订阅预检 [位](`/subscription/delete_check@v1`)—— 账单明细取数失败=`deletable` 保持 `false`;
+ * 返回 `snapshot_version` ⇒ `delete` 须带。预检未通过⇒确认按钮⛔ 解锁。
+ */
+export const subscriptionDeleteCheck = (d: { subscription_id: string }) =>
+  post<SubscriptionDeleteCheckResult>("/subscription/delete_check@v1", d);
+
+/** 删除订阅 [位](`/subscription/delete@v1`)—— 确认弹窗先列 `delete_check` 拦截清单,再点确认。 */
+export const subscriptionDelete = (d: { subscription_id: string; snapshot_version?: string }) =>
+  post<SubscriptionDeleteResult>("/subscription/delete@v1", d);
+
+/**
+ * 全部订阅列表 [位](`/subscription/list_all@v1`)—— 数据范围⛔ 合同可见性口径。
+ *
+ * 可按 `status`/`plan_kind`/`use_category`/`term`/`province_node_id` 过滤;关键词只搜套餐名称/编码。
+ * 页面⛔ 提供客户名与合同编号搜索——这两个入口在页面上不渲染,出现即 `11103`。
+ */
+export const subscriptionListAll = (d?: {
+  status?: string;
+  plan_kind?: string;
+  use_category?: string;
+  term?: string;
+  province_node_id?: string;
+  keyword?: string;
+  page?: number;
+  page_size?: number;
+}) => list<SubscriptionListResult>("/subscription/list_all@v1", d, d);
+
 /* ── 成本与分成(8) ───────────────────────────────────────────── */
 
 /** 保存成本项定义 [位] —— 仅 admin;拒收金额、客户、运营商、省份、cycle、is_system。 */

+ 9 - 0
front-end/src/api/http.ts

@@ -37,6 +37,15 @@ export type Page<T> = {
 
 export const TOKEN_KEY = "klt.bos.accessToken";
 
+/**
+ * 业务码判定:信封 `code` 是数字,设计文档里的字母码(`K204`/`M225`/`L213`…)只出现在
+ * `message` 前缀,页面按此判定分支(⛔ 据文案措辞猜分支,命中即用 `detail` 原文渲染)。
+ */
+export function hasBizCode(e: unknown, code: string): boolean {
+  const a = e as ApiError | null;
+  return `${a?.code ?? ""}`.includes(code) || (a?.message ?? "").includes(code);
+}
+
 export function getToken(): string | null {
   return sessionStorage.getItem(TOKEN_KEY);
 }

+ 62 - 0
front-end/src/api/labels.ts

@@ -105,3 +105,65 @@ export function label(dict: Record<string, string>, v: string | null | undefined
   if (!v) return "";
   return dict[v] ?? v;
 }
+
+/* ══ 第3册:套餐目录/合同/订阅(值域真源=02-数据模型本域表列注释)══ */
+
+/** `catalog_plan.plan_kind` 套餐种类。 */
+export const PLAN_KIND: Record<string, string> = {
+  fixed: "固定套餐",
+  custom: "自定义套餐",
+};
+
+/** `catalog_plan.use_category` 用途分类——五值即固定字典,一期不建字典表、无维护入口。 */
+export const USE_CATEGORY: Record<string, string> = {
+  office: "通用办公",
+  live: "直播高需求",
+  ai: "AI 应用",
+  value_add: "叠加增值",
+  customized: "定制化",
+};
+
+/** `contract_service_item.item_kind` 条目形态(§5.3 两形态)。 */
+export const ITEM_KIND: Record<string, string> = {
+  plan_based: "套餐式",
+  custom_spec: "自定义式",
+};
+
+/** `subscription.sub_mode` 订阅方式——由 `use_category` 派生并保存时冻结,⛔ 手工录入。 */
+export const SUB_MODE: Record<string, string> = {
+  upgrade: "仅可升降配",
+  stackable: "可叠加",
+  customized: "单独约定",
+};
+
+/** `subscription.term` 订阅时长/付款周期三值(⛔ 显示英文码)。 */
+export const TERM: Record<string, string> = {
+  yearly: "按年",
+  quarterly: "按季度",
+  monthly: "按月",
+};
+
+/** `subscription.status` 三态(⛔ 第四次态「作废」——功能不存在)。 */
+export const SUB_STATUS: Record<string, string> = {
+  pending: "待生效",
+  active: "生效中",
+  expired: "已到期",
+};
+
+/** `operator.pay_cycle` 合同付款周期。 */
+export const PAY_CYCLE: Record<string, string> = {
+  yearly: "年付",
+  quarterly: "季付",
+  monthly: "月付",
+};
+
+/** 下拉选项表:值域顺序即展示顺序,⛔ 在页面里各写一份。 */
+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 })),
+  sub_mode: Object.entries(SUB_MODE).map(([value, label]) => ({ value, label })),
+  term: Object.entries(TERM).map(([value, label]) => ({ value, label })),
+  sub_status: Object.entries(SUB_STATUS).map(([value, label]) => ({ value, label })),
+  pay_cycle: Object.entries(PAY_CYCLE).map(([value, label]) => ({ value, label })),
+};

+ 85 - 0
front-end/src/api/lockedCopy.ts

@@ -0,0 +1,85 @@
+/**
+ * 第3册「锁定文案」唯一真源(订阅14.5 文案锁定表)。
+ *
+ * 这些句子与**判定同源**,页面内⛔ 复制粘贴同句、⛔ 另写同义文案(14.5:任一改写都是口径事故)。
+ * 由服务端 `detail` 返回的句子(`K205`/`M227`/`M229`/`M224`/`11103` 的 `detail.fields[].reason`)
+ * 不在这里重复——那些一律直读后端 `message`/`detail`,前端不拼句子。
+ */
+
+/* ── 14.6 新增订阅:六项只读 ─────────────────────────────────── */
+
+/** 六项只读字段名(灰显、⛔ 不进载荷)。 */
+export const SUB_CREATE_READONLY_FIELDS = [
+  "线路出口",
+  "订阅方式",
+  "订单号",
+  "结束日",
+  "年订阅价格",
+  "月结算标准金额",
+] as const;
+
+/** 六项只读+「实际开通日」的说明句(14.1.3 新增订阅行/14.6)。 */
+export const SUB_CREATE_READONLY_NOTE =
+  "线路出口、订阅方式、订单号、结束日、年订阅价格、月结算标准金额六项由所选套餐与合同条目带出,只读灰显、不写入载荷;「实际开通日」同样只读:新建时恒空,唯一写入方是工单回填。";
+
+/** 两个金额格 title 固定文案(✅ 2026-11-04 口径)。 */
+export const SUB_AMOUNT_TITLE = "由所选套餐的目录价带出,不可手工改写;改价请另签新合同后新建订阅";
+
+/** 编辑订阅时「结束日只读」的一行说明(14.6)。 */
+export const SUB_END_DATE_READONLY = "结束日只读:提前终止请发起服务停用,由回填结果截断";
+
+/* ── 14.5 跨页共用常量 ───────────────────────────────────────── */
+
+/** 仅总运营可配置(固定档列表行尾,运营主账号视角)。 */
+export const OPERATOR_ONLY_CONFIG = "仅总运营可配置";
+
+/** 订阅列表状态列表头注(跨零点滞后的解释不另写第二段)。 */
+export const SUB_STATUS_DAILY_NOTE = "状态按日终刷新";
+
+/** 订阅详情顶部两卡片之间(⛔ 改成「仅供参考」)。 */
+export const NOT_GROSS_PROFIT = "两者相减不代表毛利";
+
+/** 14.4 三态三词,严格区分,任一混用都是口径事故。 */
+export const WORD_FETCH_FAILED = "取数失败";
+export const WORD_UNCONFIGURED = "未配置";
+export const WORD_NOT_OPENED = "未开通";
+
+/** 订阅方式灰显旁的说明(套餐弹窗与订阅弹窗共用)。 */
+export const SUB_MODE_BY_CATEGORY = "由用途分类决定";
+
+/** 派生档来源标识(订阅弹窗与套餐目录两处共用;带该标识的档位在目录内只读)。 */
+export const DERIVED_PLAN_BADGE = "合同条目派生";
+
+/** 派生档在目录侧的可编辑范围(仅名称/说明/排序)。 */
+export const DERIVED_PLAN_EDITABLE = "合同条目派生档为只读投影,仅名称/说明/排序可编辑,改数请回合同条目修改";
+
+/** 固定档被引用后冻结的三字段。 */
+export const FIXED_PLAN_LOCKED_FIELDS = ["用途分类", "子账号配额", "月结算标准金额"] as const;
+
+/* ── 14.2 行 2:合同新增没有套餐选择器 ───────────────────────── */
+
+/** 自定义式条目不指定固定套餐(⛔ 套餐选择器、⛔ 只读档位卡片)。 */
+export const CONTRACT_ITEM_NO_PLAN_PICKER =
+  "合同新增的自定义式条目没有套餐选择器:本条目录入规格与价格,保存后由系统同事务派生自定义档(只读投影),此处不显示套餐选择器、也不显示只读档位卡片。";
+
+/** 套餐式条目挂已有档位(与上句同屏,说明两种条目的分野)。 */
+export const CONTRACT_PLAN_BASED_HINT = "套餐式条目在此选择已有档位,档位参数只读带出,不在合同里改写。";
+
+/* ── 升降配同屏「截止规则」(14.6)────────────────────────────── */
+
+export const UPGRADE_CUTOFF_RULE = "原订阅截止于新订阅开始日的前一天并转为已到期";
+
+/** 全部订阅页的办理入口说明(§5.2:该页不渲染新增/编辑/删除)。 */
+export const SUBS_READONLY_ENTRY = "办理入口在客户管理的套餐订阅管理页";
+
+/** 删除订阅的一行提示(14.6)。 */
+export const SUB_DELETE_PLAN_LOCK_NOTE = "档位锁定不因删除而回退";
+
+/** 保存随附成本项的一行提示(14.6)。 */
+export const PLAN_COST_ITEM_SAVE_NOTE = "保存后此后出账按新构成计入,已出账月份保留当月快照";
+
+/** 月成本三态:固定档恒显示「按组合」(14.4)。 */
+export const COST_BY_COMBINATION = "按组合";
+
+/** 悬停构成的空态(不是错误)。 */
+export const COST_ITEM_EMPTY = "暂无随附成本项";

+ 216 - 7
front-end/src/api/types.ts

@@ -1273,6 +1273,12 @@ export type SubAccountUpdateResult = {
 
 /* ══ 套餐档位 ═════════════════════════════════════════════════════ */
 
+/** 三态取值口径:成功取到值 / 未配置 / 取数失败(后端⛔ 回退 0 冒充缺值)。 */
+export type ValueState = "ok" | "unconfigured" | "error";
+
+/** 列表口 `data` 的两种形状:裸数组,或 `{items: []}` 包一层(`rowsOf` 归一化)。 */
+export type ListOf<T> = T[] | { items?: T[] | null } | null | undefined;
+
 export type CatalogPlanRow = {
   plan_id: string;
   plan_name: string;
@@ -1288,6 +1294,31 @@ export type CatalogPlanRow = {
   status: string;
   created_at: string;
   row_version: string;
+  /* ── 契约 §3.1 get_list 行内新增读键(后端未就位时为 undefined,页面按「未配置」渲染) ── */
+  /** 月成本=年订阅价 ÷ 12 向下取整(三态:null ⇒ 配齐但值为空=未配置) */
+  plan_cost_cents?: number | null;
+  plan_cost_state?: ValueState;
+  /** 被引用后三字段冻结(用途分类/子账号配额/月结算标准金额) */
+  frozen?: boolean;
+  referred_count?: number | null;
+  /** 非空=合同条目派生档 */
+  derived_from_contract_item_id?: string | null;
+  source_label?: string | null;
+  line_exits?: string[] | null;
+  monthly_settle_cents?: number | null;
+  plan_desc?: string | null;
+  sort_no?: number | null;
+};
+
+/** 套餐随附成本项(`plan_cost_item`)。 */
+export type PlanCostItemRow = {
+  item_id?: string;
+  item_name: string;
+  amount_cents: number | null;
+  billing_unit: string | null;
+  category: string | null;
+  remark: string | null;
+  sort_no?: number | null;
 };
 
 /** POST /catalog/create@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ plan_id: null, req }`。 */
@@ -1296,16 +1327,38 @@ export type CatalogCreateResult = { plan_id: string };
 /** POST /catalog/update@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 与 create 同形(`{ plan_id: null, req }`)。 */
 export type CatalogUpdateResult = { plan_id: string; updated: boolean };
 
+/** POST /catalog/delete@v1 —— 删除四步(冻结→引用拦截→处置指引→物理删除)。 */
+export type CatalogDeleteResult = {
+  deleted: boolean;
+  frozen?: boolean;
+  referred_count?: number | null;
+  blocks?: { subscriptions?: unknown[]; items?: unknown[] };
+  suggest?: string | null;
+};
+
+/** POST /catalog/customer_options@v1 —— 操作人可见客户集合。 */
+export type CustomerOption = { customer_id: string; customer_name: string };
+
+/** POST /plan_cost_item/save@v1 —— 整段全量替换。 */
+export type PlanCostItemSaveResult = { items: PlanCostItemRow[]; saved_count?: number };
+
 /** POST /catalog/get_list@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ items: [] }`(无 total)。 */
 export type CatalogListResult = {
   items: CatalogPlanRow[];
+  /** 同一次请求按 plan_kind 分组返回,⛔ 两次请求 */
+  fixed?: CatalogPlanRow[];
+  custom?: CatalogPlanRow[];
   total?: number;
   page?: number;
   page_size?: number;
 };
 
 /** POST /catalog/get@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ plan: <请求体回显> }`。 */
-export type CatalogGetResult = CatalogPlanRow;
+export type CatalogGetResult = CatalogPlanRow & {
+  cost_items?: PlanCostItemRow[];
+  locked_fields?: string[];
+  editable_fields?: string[];
+};
 
 /* ══ 合同 ═════════════════════════════════════════════════════════ */
 
@@ -1319,6 +1372,13 @@ export type ContractServiceItem = {
   bandwidth_up_mbps?: number;
   bandwidth_down_mbps?: number;
   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;
+  plan_name?: string | null;
+  plan_id_derived?: string | null;
+  remark?: string | null;
 };
 
 /** 合同 IP 条件条目(spec 未定义内部字段,前端按自由对象处理)。 */
@@ -1345,6 +1405,47 @@ export type ContractRow = {
   ip_entries?: ContractIpEntry[];
   created_at: string;
   row_version: string;
+  /* ── 契约 §3.2:是否已开通三态(取数失败只坏这一列,整行不消失) ── */
+  opened?: boolean | null;
+  opened_state?: ValueState;
+  /** 合同来源标识 */
+  source_label?: string | null;
+  /** 自由录入的客户资料(customer_lookup 未命中时) */
+  customer_free_text?: string | null;
+  /** 实际开通日:本册只读,唯一写入方=工单回填 */
+  actual_opened_at?: string | null;
+};
+
+/** POST /contract/customer_lookup@v1 的三种命中方式。 */
+export type ContractLookupType = "credit_code" | "identity" | "keyword";
+
+export type ContractLookupCustomer = {
+  customer_id: string;
+  customer_name: string;
+  identity_no_masked?: string | null;
+  province_name?: string | null;
+};
+
+/** POST /contract/customer_lookup@v1 —— ⛔ 未命中不报错,matched=false 转自由录入。 */
+export type ContractLookupResult = {
+  matched: boolean;
+  customers: ContractLookupCustomer[];
+};
+
+/** 合同详情「关联订阅」面板行(订阅§4.4)。 */
+export type ContractSubscriptionRef = {
+  subscription_id: string;
+  plan_name: string | null;
+  status: string;
+  start_date: string | null;
+  end_date: string | null;
+};
+
+/** POST /contract/delete@v1 —— 引用拦截+工单状态拦截。 */
+export type ContractDeleteResult = {
+  deleted: boolean;
+  blocks?: { subscriptions?: unknown[]; tickets?: unknown[] };
+  ticket_state?: string | null;
 };
 
 /** POST /contract/create@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ contract_id: null, req }`。 */
@@ -1356,13 +1457,17 @@ export type ContractUpdateResult = { contract_id: string; updated: boolean };
 /** POST /contract/get_list@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ items: [] }`。 */
 export type ContractListResult = {
   items: ContractRow[];
+  /** 统计卡与列表同谓词 */
+  stats?: { total: number; opened: number; not_opened: number };
   total?: number;
   page?: number;
   page_size?: number;
 };
 
 /** POST /contract/get@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ contract: <请求体回显> }`。 */
-export type ContractGetResult = ContractRow;
+export type ContractGetResult = ContractRow & {
+  subscriptions?: ContractSubscriptionRef[];
+};
 
 /* ══ 订阅 ═════════════════════════════════════════════════════════ */
 
@@ -1386,13 +1491,112 @@ export type SubscriptionRow = {
   replaces_subscription_id: string | null;
   created_at: string;
   row_version: string;
+  /* ── 契约 §3.3 get_list / list_all / get 读键 ── */
+  contract_no?: string | null;
+  plan_kind?: string | null;
+  /** 档位归属客户:固定档=平台方,自定义档=该客户 */
+  plan_owner_customer_id?: string | null;
+  sub_mode?: string | null;
+  sub_mode_label?: string | null;
+  /** 规格(年付/季付/月付三值,⛔ 显示英文码) */
+  term?: string | null;
+  trial_months?: number | null;
+  discount_monthly_cents?: number | null;
+  /** 线路出口(数组) */
+  line_exits?: string[] | null;
+  line_exit_key?: string | null;
+  /** 工单号:本册只读,写入方在第4册 */
+  order_no?: string | null;
+  /** 实际开通日:本册只读,唯一写入方=工单回填 */
+  actual_opened_at?: string | null;
+  /** 月成本三态 */
+  plan_cost_cents?: number | null;
+  plan_cost_state?: ValueState;
+  /** 写口可见性由后端给出,前端⛔ 自行推导 */
+  editable?: boolean;
+  reason?: string | null;
+  /** 升降配承接:本条替代了谁 / 谁替代了本条 */
+  replaced_by?: RelatedSubscriptionRef | null;
+  original?: RelatedSubscriptionRef | null;
+};
+
+/** 升降配承接关系的对照行(订阅§5.4 条件面板)。 */
+export type RelatedSubscriptionRef = {
+  subscription_id: string;
+  plan_name?: string | null;
+  status?: string | null;
+  term?: string | null;
+  annual_price_cents?: number | null;
+  monthly_settle_cents?: number | null;
+  start_date?: string | null;
+  end_date?: string | null;
 };
 
-/** POST /subscription/create@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ subscription_id: null, req }`。 */
-export type SubscriptionCreateResult = { subscription_id: string; status?: string };
+/** POST /subscription/plan_options@v1 —— 该客户自定义档(含派生档)+全部固定档。 */
+export type SubscriptionPlanOption = {
+  plan_id: string;
+  plan_name: string;
+  plan_kind: string;
+  use_category: string | null;
+  annual_price_cents: number;
+  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;
+  available: boolean;
+  unavailable_reason?: string | null;
+};
+
+/** POST /subscription/contract_options@v1 的合同条目(⛔ 出参不含任何「月结算标准金额」键)。 */
+export type SubscriptionContractItemOption = {
+  item_id: string;
+  item_kind: string;
+  plan_id: string | null;
+  plan_name: string | null;
+  quantity: number | null;
+  plan_id_derived?: string | null;
+  annual_price_cents: number | null;
+  line_exits: string[] | null;
+  use_category: string | null;
+};
 
-/** POST /subscription/change@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 与 create 同形。 */
-export type SubscriptionChangeResult = { subscription_id: string; replaces_subscription_id?: string };
+export type SubscriptionContractOption = {
+  contract_id: string;
+  contract_no: string;
+  start_date: string | null;
+  end_date: string | null;
+  items: SubscriptionContractItemOption[];
+};
+
+/** POST /subscription/create@v1 —— 出参=整行+六项只读值+quota_changed。 */
+export type SubscriptionCreateResult = SubscriptionRow & { quota_changed?: boolean | null };
+
+/** POST /subscription/change@v1 —— 出参=新行+截原结果。 */
+export type SubscriptionChangeResult = SubscriptionRow & {
+  replaced_subscription_id?: string | null;
+  cut_end_date?: string | null;
+  quota_changed?: boolean | null;
+};
+
+/** POST /subscription/update@v1 —— 白名单只有 trial_months/discount_monthly_cents。 */
+export type SubscriptionUpdateResult = SubscriptionRow & { updated?: boolean };
+
+/** POST /subscription/delete_check@v1 —— 命中账单明细则 delete 按钮不解锁。 */
+export type SubscriptionDeleteCheckResult = {
+  deletable: boolean;
+  blocks?: { billing_details?: unknown[]; change_chain?: unknown[] };
+  /** 账单明细取数失败=deletable 保持 false */
+  billing_state?: ValueState;
+  snapshot_version?: string | null;
+};
+
+/** POST /subscription/delete@v1 */
+export type SubscriptionDeleteResult = { deleted: boolean; quota_released?: number | null };
 
 /** POST /subscription/stack@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 与 create 同形。 */
 export type SubscriptionStackResult = { subscription_id: string; updated_fields?: string[] };
@@ -1406,7 +1610,12 @@ export type SubscriptionListResult = {
 };
 
 /** POST /subscription/get@v1 —— ⚠️ 后端待实现,契约以此为准。当前 handler 返回 `{ subscription: <请求体回显> }`。 */
-export type SubscriptionGetResult = SubscriptionRow;
+export type SubscriptionGetResult = SubscriptionRow & {
+  related?: {
+    replaced_by?: RelatedSubscriptionRef | null;
+    original?: RelatedSubscriptionRef | null;
+  } | null;
+};
 
 /* ══ 成本与分成 ═══════════════════════════════════════════════════ */
 

+ 37 - 14
front-end/src/auth/nav.ts

@@ -8,8 +8,9 @@ const isGroup = (n: NavItem): n is Group => "children" in n;
 export { isGroup };
 
 /**
- * 角色 → 菜单树(册1+册2 范围)。
- * 菜单只负责隐藏入口;每个页面仍会被后端鉴权二次裁决。
+ * 角色 → 菜单树(册1+册2 范围),同时是**路由级鉴权的唯一真源**(`routesFor`):
+ * 菜单收口 + `App.tsx::RequireRole` 双层,页面内再由后端 AC 裁决。
+ * ⚠️ 新增页面必须同步登记进本表,否则会被 `RequireRole` 判为越界而落回首页。
  */
 const ALL: Record<string, NavItem> = {
   gOrg: {
@@ -33,6 +34,17 @@ const ALL: Record<string, NavItem> = {
       { route: "subaccounts", label: "分账号" },
     ],
   },
+  // 第3册:套餐目录/合同管理/全部订阅(只读视图)。⛔ 挂进 `gCust`——那组 partner 也在用,
+  // 而「全部订阅」是跨客户只读视图,办理入口在客户详情的套餐订阅管理页。
+  gPlan: {
+    key: "plan",
+    label: "套餐与合同",
+    children: [
+      { route: "catalog", label: "套餐目录" },
+      { route: "contracts", label: "合同管理" },
+      { route: "subs", label: "全部订阅" },
+    ],
+  },
   gSys: {
     key: "sys",
     label: "系统",
@@ -43,28 +55,31 @@ const ALL: Record<string, NavItem> = {
 const leaf = (route: string, label: string): Leaf => ({ route, label });
 
 const NAV: Record<RoleCode, NavItem[]> = {
-  admin: [leaf("home", "概览"), ALL.gOrg, ALL.gCust, leaf("audit", "审计日志")],
-  opsMain: [leaf("home", "概览"), ALL.gOrg, ALL.gCust, leaf("audit", "审计日志")],
-  opsSub: [leaf("home", "概览"), ALL.gOrg, ALL.gCust],
+  admin: [leaf("home", "概览"), ALL.gOrg, ALL.gCust, ALL.gPlan, leaf("audit", "审计日志")],
+  // 运营主账号保留「组织与区域」组(手册 08 册 TC-OR-11 步骤 3:主账号侧栏**有**该组,
+  // 差异只在子账号),页内写入口与数据按负责范围收窄。
+  opsMain: [leaf("home", "概览"), ALL.gOrg, ALL.gCust, ALL.gPlan, leaf("audit", "审计日志")],
+  // 运营子账号:去「组织与区域」整组(TC-AC-05/TC-OR-11),数据范围不变。
+  opsSub: [leaf("home", "概览"), ALL.gCust, ALL.gPlan],
   teamLead: [
     leaf("home", "概览"),
     { key: "t", label: "我的团队", children: [{ route: "members", label: "成员账号" }] },
     ALL.gCust,
+    // ⛔ 挂 gPlan:套餐目录/合同管理/全部订阅都是运营侧口径
+    // (订阅册 §5.2「办理入口在客户管理的套餐订阅管理页」,`list_all` 是跨客户运营视图),
+    // 团队长是客户侧角色,客户详情内也⛔ 渲染该入口。
   ],
-  ops: [leaf("home", "概览"), ALL.gCust],
+  ops: [leaf("home", "概览"), ALL.gCust, ALL.gPlan],
   partner: [leaf("home", "概览"), ALL.gCust],
   operator: [
     leaf("home", "概览"),
     { key: "ro", label: "客户(只读)", children: [{ route: "customers", label: "客户清单" }] },
   ],
-  enterprise: [
-    leaf("home", "概览"),
-    { key: "me", label: "我的账号", children: [{ route: "subaccounts", label: "分账号" }] },
-  ],
-  sub: [
-    leaf("home", "概览"),
-    { key: "me", label: "我的账号", children: [{ route: "subaccounts", label: "分账号" }] },
-  ],
+  // 「分账号」是本公司下属分账号的维护页,⛔ 挂在「我的账号」下(该分组原先除它无别项,
+  // 点开侧栏集合不变、像个空分组)。客户主账号的自助改密(TC-AC-14)是另一个入口,待补。
+  enterprise: [leaf("home", "概览"), leaf("subaccounts", "分账号")],
+  // 下属分账号本人:维护分账号是客户主账号的权限(TC-AC-04 步骤 4/TC-CU-62),侧栏不给入口。
+  sub: [leaf("home", "概览")],
 };
 
 export function navFor(role: RoleCode | undefined): NavItem[] {
@@ -73,6 +88,14 @@ export function navFor(role: RoleCode | undefined): NavItem[] {
   return NAV[role] ?? [];
 }
 
+/**
+ * 角色可进入的路由集合(分组展开成叶子)。⚠️ 分组对象没有 `route`,
+ * ⛔ 只比对 `navFor` 顶层项——那样「组织与区域」「客户与订阅」组内的路由会全判越界。
+ */
+export function routesFor(role: RoleCode | undefined): string[] {
+  return navFor(role).flatMap((n) => (isGroup(n) ? n.children.map((c) => c.route) : [n.route]));
+}
+
 export function firstRoute(role: RoleCode | undefined): string {
   const items = navFor(role);
   for (const n of items) {

+ 6 - 1
front-end/src/auth/session.tsx

@@ -104,7 +104,12 @@ export function useSession() {
   return useContext(Ctx);
 }
 
-/** 权限判定只用于「隐藏入口」;真正的裁决在后端(总则§16.5)。 */
+/**
+ * 权限判定只用于「隐藏入口」;真正的裁决在后端(总则§16.5)。
+ * ⚠️ 「隐藏入口」不等于「进不去」:路由层必须按 `routesFor` 二次校验(`App.tsx::RequireRole`),
+ * 越界不得渲染页面骨架——本轮 P0(BOS-01)的成因正是只做了这一层。
+ * 另:`ctx.permissions` 后端尚未下发(`types.ts`),本函数当前恒 false,⛔ 拿它当守卫用。
+ */
 export function useCan() {
   const { ctx } = useSession();
   return useCallback(

+ 56 - 0
front-end/src/components/triState.tsx

@@ -0,0 +1,56 @@
+/**
+ * 三态单元格(订阅14.4「缺失与失败的区分」全站唯一实现)。
+ *
+ * 三个回落词严格区分,任一混用都是口径事故:
+ * - `取数失败` = 调用失败,渲染 `.f-err`;
+ * - `未配置` = 数据不存在,灰字;
+ * - `未开通` = 真实业务态,灰字(合同「是否已开通」列专用)。
+ *
+ * 后端⛔ 回退 `0` 冒充缺值;前端同样⛔ 把 `null`/缺字段渲染成 `¥0.00`。
+ */
+import type { ReactNode } from "react";
+import { WORD_FETCH_FAILED } from "../api/lockedCopy";
+import type { ValueState } from "../api/types";
+
+export type TriTone = "val" | "missing" | "fail";
+
+/** 后端三态键优先;后端未回该键时按「有没有取到值」回落(⛔ 把缺值显示成 0)。 */
+export function triTone(state: ValueState | undefined, hasValue: boolean): TriTone {
+  if (state === "error") return "fail";
+  if (state === "unconfigured") return "missing";
+  if (!hasValue) return "missing";
+  return "val";
+}
+
+export function Tri({
+  tone,
+  text,
+  title,
+  note,
+}: {
+  tone: TriTone;
+  text: string;
+  title?: string;
+  note?: ReactNode;
+}) {
+  return (
+    <>
+      {tone === "fail" ? (
+        <span className="f-err" title={title ?? WORD_FETCH_FAILED}>
+          {text}
+        </span>
+      ) : tone === "missing" ? (
+        <span className="note" title={title}>
+          {text}
+        </span>
+      ) : (
+        <span title={title}>{text}</span>
+      )}
+      {note ? (
+        <span className="note" style={{ marginLeft: 6 }}>
+          {note}
+        </span>
+      ) : null}
+    </>
+  );
+}

+ 11 - 3
front-end/src/components/ui.tsx

@@ -462,16 +462,24 @@ export function Async({
   isEmpty,
   children,
   emptyText,
+  cols,
 }: {
   error: unknown;
   loading?: boolean;
   isEmpty?: boolean;
   children: ReactNode;
   emptyText?: string;
+  /** 骨架直接挂在 `tbody` 里时传列数:错误/加载/空态一律铺成通栏 `tr>td`,⛔ 让 `p`/`div` 直接作 `tbody` 的子节点。 */
+  cols?: number;
 }) {
-  if (error) return <ErrorBox error={error} />;
-  if (loading) return <Loading />;
-  if (isEmpty) return <Empty text={emptyText} />;
+  const row = (node: ReactNode) => (
+    <tr>
+      <td colSpan={cols}>{node}</td>
+    </tr>
+  );
+  if (error) return cols ? row(<ErrorBox error={error} />) : <ErrorBox error={error} />;
+  if (loading) return cols ? row(<Loading />) : <Loading />;
+  if (isEmpty) return cols ? row(emptyText) : <Empty text={emptyText} />;
   return <>{children}</>;
 }
 

+ 552 - 0
front-end/src/pages/CatalogPage.tsx

@@ -0,0 +1,552 @@
+/**
+ * 套餐目录(路由 `catalog`)—— 页面契约 14.1。
+ *
+ * 两张表(固定档/自定义档)**一次请求**按 `plan_kind` 分组(`/catalog/get_list@v1`),⛔ 两次请求。
+ * 写口只走 `catalog/create`/`catalog/update`/`catalog/delete`;随附成本项走整段 `plan_cost_item/save`。
+ *
+ * 禁止入口清单(14.1 底部,逐条不渲染):档位列表的状态列按钮与批量操作、导出、规格列、
+ * 子账号配额列、成本构成列合计、成本构成行删除按钮、批量设置成本构成、成本构成历史、档位复制。
+ */
+import { useCallback, useRef, useState } from "react";
+import { catalogCreate, catalogCustomerOptions, catalogDelete, catalogGet, catalogGetList, catalogUpdate, planCostItemList, planCostItemSave, rowsOf } from "../api/bos";
+import { label, OPTIONS, PLAN_KIND, SUB_MODE, USE_CATEGORY } from "../api/labels";
+import {
+  COST_ITEM_EMPTY,
+  DERIVED_PLAN_BADGE,
+  DERIVED_PLAN_EDITABLE,
+  FIXED_PLAN_LOCKED_FIELDS,
+  OPERATOR_ONLY_CONFIG,
+  PLAN_COST_ITEM_SAVE_NOTE,
+  SUB_MODE_BY_CATEGORY,
+  WORD_FETCH_FAILED,
+  WORD_UNCONFIGURED,
+} from "../api/lockedCopy";
+import { hasBizCode } from "../api/http";
+import type { CatalogPlanRow, PlanCostItemRow } from "../api/types";
+import { Async, Btn, Cell, ErrorBox, Field, Modal, Notice, Pager, Panel, Pill, day, money, seq } from "../components/ui";
+import { Tri, triTone } from "../components/triState";
+import { Shell } from "../layout/Shell";
+import { useSession } from "../auth/session";
+import { useForm, useLoad, useSubmit } from "../hooks/useLoad";
+
+/** 月成本单元格:三态+悬停看构成(`plan_cost_item/get_list`,悬停发起、失败即「取数失败」)。 */
+function CostCell({ plan }: { plan: CatalogPlanRow }) {
+  const [pop, setPop] = useState<{ items?: PlanCostItemRow[]; error?: unknown } | null>(null);
+  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+  const open = useCallback(async () => {
+    setPop({});
+    try {
+      const items = await planCostItemList({ plan_id: plan.plan_id });
+      setPop({ items: rowsOf(items) });
+    } catch (e) {
+      setPop({ error: e });
+    }
+  }, [plan.plan_id]);
+
+  const tone = triTone(plan.plan_cost_state, plan.plan_cost_cents !== null && plan.plan_cost_cents !== undefined);
+  const text = tone === "val" ? money(plan.plan_cost_cents) : tone === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED;
+
+  return (
+    <span
+      style={{ position: "relative" }}
+      onMouseEnter={() => {
+        if (timer.current) clearTimeout(timer.current);
+        timer.current = setTimeout(open, 200);
+      }}
+      onMouseLeave={() => {
+        if (timer.current) clearTimeout(timer.current);
+        setPop(null);
+      }}
+    >
+      <Tri tone={tone} text={text} title="悬停查看月成本构成" />
+      {pop ? (
+        <span className="qtip" style={{ whiteSpace: "nowrap" }}>
+          {pop.error ? WORD_FETCH_FAILED : pop.items ? (pop.items.length ? pop.items.map((it) => `${it.item_name} ${money(it.amount_cents)}`).join(";") : COST_ITEM_EMPTY) : "读取中…"}
+        </span>
+      ) : null}
+    </span>
+  );
+}
+
+/** 带宽三态单元格:未承诺(开关关,无数字)/未填(承诺但某向为空)/未配置(该向取数失败)。 */
+function BandwidthCell({ plan }: { plan: CatalogPlanRow }) {
+  if (plan.bandwidth_committed === null || plan.bandwidth_committed === undefined) {
+    return <Tri tone="missing" text={WORD_UNCONFIGURED} />;
+  }
+  if (!plan.bandwidth_committed) return <Tri tone="missing" text="未承诺" />;
+  const up = plan.bandwidth_up_mbps;
+  const down = plan.bandwidth_down_mbps;
+  if (up === null || up === undefined || down === null || down === undefined) {
+    const fail = plan.bandwidth_up_mbps === undefined && plan.bandwidth_down_mbps === undefined;
+    return <Tri tone={fail ? "fail" : "missing"} text={fail ? WORD_FETCH_FAILED : "未填"} title="已承诺带宽,但上/下行至少一路为空" />;
+  }
+  return (
+    <span>
+      上行 {up} / 下行 {down} Mbps
+    </span>
+  );
+}
+
+/** 随附成本项整段编辑器:整段编辑+「添加成本项」+「清空本段」,⛔ 逐行删除按钮、⛔ 合计。 */
+function CostItemsEditor({ items, onChange }: { items: PlanCostItemRow[]; onChange: (v: PlanCostItemRow[]) => void }) {
+  const patch = (i: number, k: keyof PlanCostItemRow, v: string) => {
+    const next = items.map((it, idx) => {
+      if (idx !== i) return it;
+      if (k === "amount_cents") return { ...it, amount_cents: v === "" ? null : Math.round(Number(v) * 100) };
+      return { ...it, [k]: v };
+    });
+    onChange(next);
+  };
+  return (
+    <>
+      <table className="sub">
+        <thead>
+          <tr>
+            <th>名称</th>
+            <th>金额</th>
+            <th>计费单位</th>
+            <th>分类</th>
+            <th>说明</th>
+          </tr>
+        </thead>
+        <tbody>
+          {items.length === 0 ? (
+            <tr>
+              <td colSpan={5}>
+                <span className="note">{COST_ITEM_EMPTY}</span>
+              </td>
+            </tr>
+          ) : (
+            items.map((it, i) => (
+              <tr key={i}>
+                <td>
+                  <input value={it.item_name ?? ""} onChange={(e) => patch(i, "item_name", e.target.value)} />
+                </td>
+                <td>
+                  <input
+                    type="number"
+                    min={0}
+                    step="0.01"
+                    value={it.amount_cents === null || it.amount_cents === undefined ? "" : String(it.amount_cents / 100)}
+                    onChange={(e) => patch(i, "amount_cents", e.target.value)}
+                  />
+                </td>
+                <td>
+                  <input value={it.billing_unit ?? ""} onChange={(e) => patch(i, "billing_unit", e.target.value)} />
+                </td>
+                <td>
+                  <input value={it.category ?? ""} onChange={(e) => patch(i, "category", e.target.value)} />
+                </td>
+                <td>
+                  <input value={it.remark ?? ""} onChange={(e) => patch(i, "remark", e.target.value)} />
+                </td>
+              </tr>
+            ))
+          )}
+        </tbody>
+      </table>
+      <div className="row" style={{ marginTop: 8 }}>
+        <Btn ghost onClick={() => onChange([...items, { item_name: "", amount_cents: null, billing_unit: null, category: null, remark: null }])}>
+          添加成本项
+        </Btn>
+        <Btn ghost onClick={() => onChange([])}>
+          清空本段
+        </Btn>
+      </div>
+      <p className="note">{PLAN_COST_ITEM_SAVE_NOTE}</p>
+    </>
+  );
+}
+
+const EMPTY_COST: PlanCostItemRow[] = [];
+
+export default function CatalogPage() {
+  const { ctx } = useSession();
+  const isAdmin = ctx?.role_code === "admin";
+  const [f, setF] = useState({ keyword: "", use_category: "", page: 1, page_size: 20 });
+  const [draft, setDraft] = useState<{ plan?: CatalogPlanRow; kind: string; customers?: { customer_id: string; customer_name: string }[] } | null>(null);
+  const [del, setDel] = useState<{ plan: CatalogPlanRow; result?: unknown; error?: unknown } | null>(null);
+  const [detail, setDetail] = useState<{ plan: CatalogPlanRow; cost_items?: PlanCostItemRow[]; locked?: boolean; referred?: number | null } | null>(null);
+  const [costItems, setCostItems] = useState<PlanCostItemRow[]>(EMPTY_COST);
+  const form = useForm({
+    plan_name: "",
+    use_category: "office",
+    customer_id: "",
+    annual_price_cents: "",
+    sub_account_quota: "",
+    bandwidth_committed: "1",
+    bandwidth_up_mbps: "",
+    bandwidth_down_mbps: "",
+    plan_desc: "",
+    sort_no: "",
+  });
+  const sub = useSubmit();
+
+  const list = useLoad(
+    () => catalogGetList({ keyword: f.keyword || undefined, use_category: f.use_category || undefined, page: f.page - 1, page_size: f.page_size }),
+    [f.keyword, f.use_category, f.page, f.page_size],
+  );
+
+  const rows = list.data?.items ?? [];
+  /** 一次请求后按 plan_kind 前端分组;后端如回 `fixed`/`custom` 两段则优先使用。 */
+  const fixed = list.data?.fixed ?? rows.filter((r) => r.plan_kind === "fixed");
+  const custom = list.data?.custom ?? rows.filter((r) => r.plan_kind !== "fixed");
+
+  const openCreate = async (kind: string) => {
+    form.reset({
+      plan_name: "",
+      use_category: kind === "fixed" ? "office" : "customized",
+      customer_id: "",
+      annual_price_cents: "",
+      sub_account_quota: "",
+      bandwidth_committed: "1",
+      bandwidth_up_mbps: "",
+      bandwidth_down_mbps: "",
+      plan_desc: "",
+      sort_no: "",
+    });
+    setCostItems(EMPTY_COST);
+    setDetail(null);
+    const customers = kind === "custom" ? rowsOf(await catalogCustomerOptions().catch(() => [])) : [];
+    setDraft({ kind, customers });
+  };
+
+  const openEdit = async (plan: CatalogPlanRow) => {
+    const [g, costs] = await Promise.all([
+      catalogGet({ plan_id: plan.plan_id }).catch(() => null),
+      planCostItemList({ plan_id: plan.plan_id })
+        .then(rowsOf)
+        .catch(() => [] as PlanCostItemRow[]),
+    ]);
+    const p = g ?? plan;
+    const items = g?.cost_items ?? costs ?? EMPTY_COST;
+    form.reset({
+      plan_name: p.plan_name ?? "",
+      use_category: p.use_category ?? "",
+      customer_id: p.customer_id ?? "",
+      annual_price_cents: p.annual_price_cents === null || p.annual_price_cents === undefined ? "" : String(p.annual_price_cents / 100),
+      sub_account_quota: p.sub_account_quota === null || p.sub_account_quota === undefined ? "" : String(p.sub_account_quota),
+      bandwidth_committed: p.bandwidth_committed === false ? "0" : "1",
+      bandwidth_up_mbps: p.bandwidth_up_mbps === null || p.bandwidth_up_mbps === undefined ? "" : String(p.bandwidth_up_mbps),
+      bandwidth_down_mbps: p.bandwidth_down_mbps === null || p.bandwidth_down_mbps === undefined ? "" : String(p.bandwidth_down_mbps),
+      plan_desc: p.plan_desc ?? "",
+      sort_no: p.sort_no === null || p.sort_no === undefined ? "" : String(p.sort_no),
+    });
+    setCostItems(items);
+    setDetail({ plan: p, cost_items: items, locked: p.frozen === true, referred: p.referred_count });
+    setDraft({ plan: p, kind: p.plan_kind, customers: p.customer_id ? [{ customer_id: p.customer_id, customer_name: p.customer_name ?? p.customer_id }] : [] });
+  };
+
+  const committed = form.get("bandwidth_committed") !== "0";
+  const isEdit = !!draft?.plan;
+  const isFixed = (draft?.plan?.plan_kind ?? draft?.kind) === "fixed";
+  const derived = draft?.plan?.derived_from_contract_item_id !== null && draft?.plan?.derived_from_contract_item_id !== undefined;
+  const locked = detail?.locked === true || derived;
+
+  const save = async () => {
+    let frozen = false;
+    const ok = await sub.run(async () => {
+      if (!form.get("plan_name")) throw new Error("请填写套餐名称");
+      if (!isEdit && !form.get("annual_price_cents")) throw new Error("请填写年订阅价格");
+      const price = Math.round(Number(form.get("annual_price_cents") || 0) * 100);
+      const items = costItems.filter((it) => (it.item_name ?? "").trim() !== "");
+      try {
+        if (draft?.plan) {
+          const r = await catalogUpdate({
+            plan_id: draft.plan.plan_id,
+            plan_name: form.get("plan_name"),
+            annual_price_cents: locked ? undefined : price,
+            sub_account_quota: locked || !form.get("sub_account_quota") ? undefined : Number(form.get("sub_account_quota")),
+            bandwidth_committed: committed,
+            bandwidth_up_mbps: committed && form.get("bandwidth_up_mbps") ? Number(form.get("bandwidth_up_mbps")) : undefined,
+            bandwidth_down_mbps: committed && form.get("bandwidth_down_mbps") ? Number(form.get("bandwidth_down_mbps")) : undefined,
+            plan_desc: form.get("plan_desc") || undefined,
+            sort_no: form.get("sort_no") ? Number(form.get("sort_no")) : undefined,
+          });
+          // 随附成本项=整段全量替换(`plan_cost_item/save`),⛔ 逐行增删改
+          await planCostItemSave({ plan_id: draft.plan.plan_id, items });
+          return r;
+        }
+        return await catalogCreate({
+          plan_kind: draft?.kind ?? "fixed",
+          plan_name: form.get("plan_name"),
+          use_category: form.get("use_category") || undefined,
+          annual_price_cents: price,
+          sub_account_quota: form.get("sub_account_quota") ? Number(form.get("sub_account_quota")) : undefined,
+          bandwidth_committed: committed,
+          bandwidth_up_mbps: committed && form.get("bandwidth_up_mbps") ? Number(form.get("bandwidth_up_mbps")) : undefined,
+          bandwidth_down_mbps: committed && form.get("bandwidth_down_mbps") ? Number(form.get("bandwidth_down_mbps")) : undefined,
+          customer_id: draft?.kind === "custom" ? form.get("customer_id") || undefined : undefined,
+          plan_desc: form.get("plan_desc") || undefined,
+          sort_no: form.get("sort_no") ? Number(form.get("sort_no")) : undefined,
+          cost_items: items,
+        });
+      } catch (e) {
+        frozen = hasBizCode(e, "K204");
+        throw e;
+      }
+    });
+    if (ok) {
+      setDraft(null);
+      await list.reload();
+      return ok;
+    }
+    // K204 引用冻结:整表单失败+只读横幅+重取 catalog/get 驱动状态
+    if (frozen && draft?.plan) {
+      const g = await catalogGet({ plan_id: draft.plan.plan_id }).catch(() => null);
+      if (g) setDetail({ plan: g, cost_items: g.cost_items, locked: true, referred: g.referred_count });
+    }
+    return ok;
+  };
+
+  const doDelete = async () => {
+    if (!del) return;
+    let removed = false;
+    const ok = await sub.run(async () => {
+      const r = await catalogDelete({ plan_id: del.plan.plan_id });
+      removed = r.deleted === true;
+      if (!removed) setDel((d) => (d ? { ...d, result: r } : d));
+      return r;
+    });
+    if (ok && removed) {
+      setDel(null);
+      await list.reload();
+    }
+  };
+
+  const table = (rowsOfKind: CatalogPlanRow[], kind: "fixed" | "custom") => (
+    <Panel
+      title={label(PLAN_KIND, kind)}
+      extra={
+        <Btn ghost onClick={() => openCreate(kind)}>
+          新增{label(PLAN_KIND, kind)}
+        </Btn>
+      }
+    >
+      <table>
+        <thead>
+          <tr>
+            <th>序号</th>
+            <th>套餐名称</th>
+            <th>年订阅价格</th>
+            <th>月成本</th>
+            <th>带宽</th>
+            <th>用途分类</th>
+            <th>订阅方式</th>
+            <th>状态</th>
+            <th>引用数</th>
+            <th>操作</th>
+          </tr>
+        </thead>
+        <tbody>
+          <Async error={list.error} loading={list.loading} isEmpty={rowsOfKind.length === 0} emptyText={`暂无${label(PLAN_KIND, kind)}`} cols={10}>
+            {rowsOfKind.map((p, i) => {
+              const isDerived = p.derived_from_contract_item_id !== null && p.derived_from_contract_item_id !== undefined;
+              return (
+                <tr key={p.plan_id}>
+                  <td>{seq(f.page, f.page_size, i)}</td>
+                  <td>
+                    {p.plan_name}
+                    {isDerived ? (
+                      <>
+                        {" "}
+                        <span className="ref-tag">{DERIVED_PLAN_BADGE}</span>
+                        <div className="note">
+                          {p.source_label ?? ""}
+                          {p.customer_name ? `|${p.customer_name}` : ""}
+                        </div>
+                      </>
+                    ) : null}
+                  </td>
+                  <td>{money(p.annual_price_cents)}</td>
+                  <td>
+                    <CostCell plan={p} />
+                  </td>
+                  <td>
+                    <BandwidthCell plan={p} />
+                  </td>
+                  <td>
+                    <Cell v={label(USE_CATEGORY, p.use_category)} />
+                  </td>
+                  <td>
+                    <Cell v={label(SUB_MODE, p.use_category ? subModeOf(p.use_category) : null)} />
+                    <span className="note" style={{ marginLeft: 6 }}>
+                      {SUB_MODE_BY_CATEGORY}
+                    </span>
+                  </td>
+                  <td>
+                    <Pill text={p.frozen ? "已冻结" : p.status === "active" ? "在用" : p.status} />
+                  </td>
+                  <td>{p.referred_count === null || p.referred_count === undefined ? <span className="note">{WORD_UNCONFIGURED}</span> : p.referred_count}</td>
+                  <td>
+                    <div className="row">
+                      <Btn ghost onClick={() => openEdit(p)}>
+                        编辑
+                      </Btn>
+                      <Btn ghost danger onClick={() => setDel({ plan: p })}>
+                        删除
+                      </Btn>
+                      {!isAdmin && kind === "fixed" ? <span className="note">{OPERATOR_ONLY_CONFIG}</span> : null}
+                    </div>
+                  </td>
+                </tr>
+              );
+            })}
+          </Async>
+        </tbody>
+      </table>
+    </Panel>
+  );
+
+  return (
+    <Shell route="catalog" title="套餐目录" hint="固定档仅总部管理员可建;自定义档限负责范围内客户;被引用后相关字段冻结。">
+      <Panel title="套餐目录" note="月成本为派生只读值(年订阅价 ÷ 12 向下取整),悬停可看随附成本项构成;两张表同一次请求取数。">
+        <div className="filters">
+          <label className="f-item">
+            关键词
+            <input
+              placeholder="套餐名称"
+              value={f.keyword}
+              onChange={(e) => setF((s) => ({ ...s, keyword: e.target.value, page: 1 }))}
+            />
+          </label>
+          <label className="f-item">
+            用途分类
+            <select value={f.use_category} onChange={(e) => setF((s) => ({ ...s, use_category: e.target.value, page: 1 }))}>
+              <option value="">全部</option>
+              {OPTIONS.use_category.map((o) => (
+                <option key={o.value} value={o.value}>
+                  {o.label}
+                </option>
+              ))}
+            </select>
+          </label>
+          <span className="note">默认全量返回,无省份与日期筛选</span>
+        </div>
+      </Panel>
+      {table(fixed, "fixed")}
+      {table(custom, "custom")}
+      {list.data ? (
+        <Pager page={f.page} page_size={f.page_size} total={list.data.total ?? rows.length} onChange={(p) => setF((s) => ({ ...s, page: p }))} />
+      ) : null}
+
+      {draft ? (
+        <Modal wide title={`${isEdit ? "编辑" : "新增"}${label(PLAN_KIND, draft.kind)}`} onClose={() => setDraft(null)}>
+          {locked ? <Notice tone="warn">{derived ? DERIVED_PLAN_EDITABLE : `${FIXED_PLAN_LOCKED_FIELDS.join("、")}已被引用(${detail?.referred ?? 0} 处),本表单为只读。`}</Notice> : null}
+          <div className="form-grid">
+            <Field label="套餐名称" required>
+              <input {...form.bind("plan_name")} />
+            </Field>
+            {isEdit ? (
+              <Field label="用途分类" hint={locked ? "由用途分类决定,被引用后锁定" : undefined}>
+                <span>{label(USE_CATEGORY, form.get("use_category")) || "—"}</span>
+              </Field>
+            ) : isFixed ? (
+              <Field label="用途分类" required>
+                <select {...form.bind("use_category")}>
+                  {OPTIONS.use_category.map((o) => (
+                    <option key={o.value} value={o.value}>
+                      {o.label}
+                    </option>
+                  ))}
+                </select>
+              </Field>
+            ) : (
+              <Field label="用途分类" hint={SUB_MODE_BY_CATEGORY}>
+                <select {...form.bind("use_category")}>
+                  {OPTIONS.use_category.map((o) => (
+                    <option key={o.value} value={o.value}>
+                      {o.label}
+                    </option>
+                  ))}
+                </select>
+              </Field>
+            )}
+            {isFixed ? null : (
+              <Field label="归属客户" required={!isEdit}>
+                {isEdit ? (
+                  <span>{draft?.plan?.customer_name ?? "—"}</span>
+                ) : (
+                  <select {...form.bind("customer_id")}>
+                    <option value="">请选择</option>
+                    {(draft?.customers ?? []).map((c) => (
+                      <option key={c.customer_id} value={c.customer_id}>
+                        {c.customer_name}
+                      </option>
+                    ))}
+                  </select>
+                )}
+              </Field>
+            )}
+            <Field label="年订阅价格(元)" required hint={locked ? "被引用后锁定,不可编辑" : undefined}>
+              {locked ? <span>{money(Math.round(Number(form.get("annual_price_cents") || 0) * 100))}</span> : <input type="number" min={0} step="0.01" {...form.bind("annual_price_cents")} />}
+            </Field>
+            <Field label="子账号配额" hint={locked ? "被引用后锁定" : "留空=不限"}>
+              {locked ? <span>{form.get("sub_account_quota") || "不限"}</span> : <input type="number" min={0} {...form.bind("sub_account_quota")} />}
+            </Field>
+            <Field label="承诺带宽">
+              <select {...form.bind("bandwidth_committed")}>
+                <option value="1">承诺</option>
+                <option value="0">不承诺</option>
+              </select>
+            </Field>
+            <Field label="上行带宽(Mbps)" hint={committed ? undefined : "开关关闭⇒两格不提交"}>
+              <input type="number" min={0} disabled={!committed} {...form.bind("bandwidth_up_mbps")} />
+            </Field>
+            <Field label="下行带宽(Mbps)">
+              <input type="number" min={0} disabled={!committed} {...form.bind("bandwidth_down_mbps")} />
+            </Field>
+            <Field label="说明">
+              <input {...form.bind("plan_desc")} />
+            </Field>
+            <Field label="排序">
+              <input type="number" min={0} {...form.bind("sort_no")} />
+            </Field>
+          </div>
+          <h3 style={{ marginTop: 14 }}>随附成本项(整段编辑)</h3>
+          <CostItemsEditor items={costItems} onChange={setCostItems} />
+          {sub.error ? <ErrorBox error={sub.error} /> : null}
+          <div className="form-actions" style={{ marginTop: 12 }}>
+            <Btn onClick={save} disabled={sub.busy}>
+              {sub.busy ? "提交中…" : "保存"}
+            </Btn>
+            <Btn ghost onClick={() => setDraft(null)}>
+              取消
+            </Btn>
+          </div>
+        </Modal>
+      ) : null}
+
+      {del ? (
+        <Modal title={`删除${label(PLAN_KIND, del.plan.plan_kind)}「${del.plan.plan_name}」`} onClose={() => setDel(null)}>
+          <p>
+            档位编码:<code>{del.plan.plan_id}</code>,创建日期:{day(del.plan.created_at)}
+          </p>
+          <p className="note">月成本 {money(del.plan.plan_cost_cents ?? undefined)} 为派生只读值,此处不提供编辑入口;月结算标准金额由套餐带出,不可录入。</p>
+          {del.result ? (
+            <Notice tone="warn">
+              <strong>该档位已被引用,不能删除。</strong>
+              <pre style={{ whiteSpace: "pre-wrap", margin: "6px 0 0" }}>{JSON.stringify(del.result, null, 2)}</pre>
+            </Notice>
+          ) : null}
+          {sub.error ? <ErrorBox error={sub.error} /> : null}
+          <div className="form-actions" style={{ marginTop: 12 }}>
+            <Btn danger onClick={doDelete} disabled={sub.busy}>
+              {sub.busy ? "提交中…" : "确认删除"}
+            </Btn>
+            <Btn ghost onClick={() => setDel(null)}>
+              取消
+            </Btn>
+          </div>
+        </Modal>
+      ) : null}
+    </Shell>
+  );
+}
+
+/** 用途分类→订阅方式(后端 `sub_mode` 由服务端派生并冻结;缺字段时按映射兜底显示)。 */
+function subModeOf(useCategory: string): string | null {
+  const map: Record<string, string> = { office: "upgrade", live: "upgrade", ai: "stackable", value_add: "stackable", customized: "customized" };
+  return map[useCategory] ?? null;
+}

+ 237 - 0
front-end/src/pages/ContractDetailPage.tsx

@@ -0,0 +1,237 @@
+/**
+ * 合同详情(路由 `contracts/:id`)—— 页面契约 14.2 列 2。
+ *
+ * 三段:基础信息/服务构成条目/关联订阅;「是否已开通」取数失败只坏该列。
+ * ⛔ 合同详情不提供套餐列、⛔ 订阅状态列按钮、⛔ 月成本列。
+ */
+import { useState } from "react";
+import { Link, useNavigate, useParams } from "react-router-dom";
+import { contractDelete, contractGet } from "../api/bos";
+import { label, ITEM_KIND, PAY_CYCLE, SUB_STATUS } from "../api/labels";
+import { DERIVED_PLAN_BADGE, SUB_STATUS_DAILY_NOTE, WORD_FETCH_FAILED, WORD_NOT_OPENED } from "../api/lockedCopy";
+import type { ContractGetResult } from "../api/types";
+import { Btn, ErrorBox, Loading, Modal, Notice, Panel, Pill, day, datetime, money, seq } from "../components/ui";
+import { Tri, triTone } from "../components/triState";
+import { Shell } from "../layout/Shell";
+import { useSession } from "../auth/session";
+import { useLoad, useSubmit } from "../hooks/useLoad";
+
+export default function ContractDetailPage() {
+  const { id = "" } = useParams();
+  const nav = useNavigate();
+  const { ctx } = useSession();
+  const canWrite = ctx?.role_code === "admin" || ctx?.role_code === "opsMain";
+  const [del, setDel] = useState(false);
+  const s = useSubmit();
+  const d = useLoad(() => contractGet({ contract_id: id }), [id]);
+  const raw = d.data as (ContractGetResult & { contract?: ContractGetResult }) | undefined;
+  const c = raw?.contract ?? raw;
+
+  if (d.loading && !c)
+    return (
+      <Shell route="contracts" title="合同详情" hint="三段:基础信息/服务构成条目/关联订阅。">
+        <Loading />
+      </Shell>
+    );
+  if (!c)
+    return (
+      <Shell route="contracts" title="合同详情" hint="三段:基础信息/服务构成条目/关联订阅。">
+        <ErrorBox error={d.error ?? new Error("合同不存在")} />
+        <Btn ghost onClick={d.reload}>
+          重新加载
+        </Btn>
+      </Shell>
+    );
+
+  const openedTone = triTone(c.opened_state, c.opened !== null && c.opened !== undefined);
+  const openedText = openedTone === "fail" ? WORD_FETCH_FAILED : openedTone === "missing" ? WORD_NOT_OPENED : c.opened ? "已开通" : WORD_NOT_OPENED;
+
+  const doDelete = async () => {
+    const ok = await s.run(() => contractDelete({ contract_id: c.contract_id }));
+    if (ok) nav("/contracts");
+  };
+
+  return (
+    <Shell route="contracts" title={`合同详情 ${c.contract_no}`} hint="合同列表与详情不提供套餐列、订阅状态列按钮与月成本列。">
+      <Panel
+        title={`合同 ${c.contract_no}`}
+        extra={
+          <div className="row">
+            <Link to={`/customers/${c.customer_id}`}>签约客户:{c.customer_name}</Link>
+            {canWrite ? (
+              <Btn ghost danger onClick={() => setDel(true)}>
+                删除合同
+              </Btn>
+            ) : null}
+            <Btn ghost onClick={() => nav("/contracts")}>
+              返回列表
+            </Btn>
+          </div>
+        }
+        note={`开始日 ${day(c.start_date)} | 结束日 ${day(c.end_date)} | 是否已开通:${openedText}`}
+        noteTitle="「是否已开通」派生自工单回填结果;取数失败只影响本项显示"
+      >
+        <div className="kv">
+          <div>
+            <span className="note">合同编号</span>
+            <div>{c.contract_no}</div>
+          </div>
+          <div>
+            <span className="note">签约客户</span>
+            <div>{c.customer_name}</div>
+          </div>
+          <div>
+            <span className="note">外部合同号</span>
+            <div>{c.external_no || "—"}</div>
+          </div>
+          <div>
+            <span className="note">付款周期</span>
+            <div>{label(PAY_CYCLE, c.pay_cycle) || "—"}</div>
+          </div>
+          <div>
+            <span className="note">合同金额</span>
+            <div>{c.contract_amount_cents === null || c.contract_amount_cents === undefined ? "—" : money(c.contract_amount_cents)}</div>
+          </div>
+          <div>
+            <span className="note">状态</span>
+            <div>
+              <Pill text={c.status === "active" ? "履行中" : c.status === "expired" ? "已到期" : c.status} />
+            </div>
+          </div>
+          <div>
+            <span className="note">是否已开通</span>
+            <div>
+              <Tri tone={openedTone} text={openedText} title={openedTone === "fail" ? WORD_FETCH_FAILED : "派生自工单回填结果"} />
+            </div>
+          </div>
+          <div>
+            <span className="note">实际开通日</span>
+            <div>{day(c.actual_opened_at ?? null)}</div>
+          </div>
+          <div>
+            <span className="note">合同扫描件(随合同留档)</span>
+            <div>{c.attachment_url ? <a href={c.attachment_url}>{c.attachment_url}</a> : "—"}</div>
+          </div>
+          <div>
+            <span className="note">创建时间</span>
+            <div>{datetime(c.created_at)}</div>
+          </div>
+        </div>
+      </Panel>
+
+      <Panel title="服务构成条目">
+        <table>
+          <thead>
+            <tr>
+              <th>序号</th>
+              <th>条目形态</th>
+              <th>套餐</th>
+              <th>数量</th>
+              <th>账户数</th>
+              <th>上行/下行(Mbps)</th>
+              <th>年订阅价格</th>
+              <th>月结算标准金额</th>
+            </tr>
+          </thead>
+          <tbody>
+            {(c.service_items ?? []).length === 0 ? (
+              <tr>
+                <td colSpan={8}>
+                  <span className="note">本合同暂无服务构成条目</span>
+                </td>
+              </tr>
+            ) : (
+              (c.service_items ?? []).map((it, i) => (
+                <tr key={it.item_id ?? i}>
+                  <td>{seq(1, 20, i)}</td>
+                  <td>{label(ITEM_KIND, it.item_kind)}</td>
+                  <td>
+                    {it.item_kind === "custom_spec" ? (
+                      <span className="note">不指定固定套餐</span>
+                    ) : (
+                      <span>
+                        {it.plan_name ?? it.plan_id ?? "—"}
+                        {it.plan_id_derived ? (
+                          <span className="ref-tag" style={{ marginLeft: 6 }}>
+                            {DERIVED_PLAN_BADGE}
+                          </span>
+                        ) : null}
+                      </span>
+                    )}
+                  </td>
+                  <td>{it.quantity ?? "—"}</td>
+                  <td>{it.account_count ?? "—"}</td>
+                  <td>
+                    {it.bandwidth_up_mbps ?? "—"} / {it.bandwidth_down_mbps ?? "—"}
+                  </td>
+                  <td>{it.annual_price_cents === null || it.annual_price_cents === undefined ? "取套餐" : money(it.annual_price_cents)}</td>
+                  <td>{it.monthly_settle_cents === null || it.monthly_settle_cents === undefined ? "取套餐" : money(it.monthly_settle_cents)}</td>
+                </tr>
+              ))
+            )}
+          </tbody>
+        </table>
+      </Panel>
+
+      <Panel title="关联订阅" note={SUB_STATUS_DAILY_NOTE} noteTitle="状态列口径列头注:跨零点滞后的解释不另写第二段">
+        <table>
+          <thead>
+            <tr>
+              <th>序号</th>
+              <th>订阅编号</th>
+              <th>套餐</th>
+              <th>状态</th>
+              <th>开始日</th>
+              <th>结束日</th>
+              <th>操作</th>
+            </tr>
+          </thead>
+          <tbody>
+            {(d.data?.subscriptions ?? []).length === 0 ? (
+              <tr>
+                <td colSpan={7}>
+                  <span className="note">本合同暂无关联订阅</span>
+                </td>
+              </tr>
+            ) : (
+              (d.data?.subscriptions ?? []).map((sb, i) => (
+                <tr key={sb.subscription_id}>
+                  <td>{seq(1, 20, i)}</td>
+                  <td>
+                    <Link to={`/subs/${sb.subscription_id}`}>{sb.subscription_id}</Link>
+                  </td>
+                  <td>{sb.plan_name ?? "—"}</td>
+                  <td>
+                    <Pill text={label(SUB_STATUS, sb.status)} />
+                  </td>
+                  <td>{day(sb.start_date)}</td>
+                  <td>{day(sb.end_date)}</td>
+                  <td>
+                    <Btn ghost onClick={() => nav(`/subs/${sb.subscription_id}`)}>
+                      详情
+                    </Btn>
+                  </td>
+                </tr>
+              ))
+            )}
+          </tbody>
+        </table>
+      </Panel>
+
+      {del ? (
+        <Modal title={`删除合同 ${c.contract_no}`} onClose={() => setDel(false)}>
+          <Notice>有订阅引用的合同将被拦截;无引用但关联工单未到终态同样拦截,拦截清单原文如下。</Notice>
+          {s.error ? <ErrorBox error={s.error} /> : null}
+          <div className="form-actions" style={{ marginTop: 12 }}>
+            <Btn danger onClick={doDelete} disabled={s.busy}>
+              {s.busy ? "提交中…" : "确认删除"}
+            </Btn>
+            <Btn ghost onClick={() => setDel(false)}>
+              取消
+            </Btn>
+          </div>
+        </Modal>
+      ) : null}
+    </Shell>
+  );
+}

+ 492 - 0
front-end/src/pages/ContractsPage.tsx

@@ -0,0 +1,492 @@
+/**
+ * 合同管理(路由 `contracts`)—— 页面契约 14.2。
+ *
+ * 写口只走 `contract/create`/`contract/update`/`contract/delete`;客户检索走 `contract/customer_lookup`。
+ * 「是否已开通」列派生自工单回填:三态、取数失败只坏该列(整行⛔ 消失、其他列⛔ 变「未开通」)。
+ *
+ * 禁止入口清单(14.2 底部,逐条不渲染):自定义式条目的套餐选择器与只读档位卡片、合同级规格单选、
+ * 合同级月成本输入、合同级成本构成区、合同列表的套餐列、订阅状态列、月成本列。
+ */
+import { useState } from "react";
+import { useNavigate } from "react-router-dom";
+import { catalogGetList, contractCreate, contractCustomerLookup, contractDelete, contractGetList, contractUpdate, rowsOf } from "../api/bos";
+import { hasBizCode } from "../api/http";
+import { label, OPTIONS, PAY_CYCLE } from "../api/labels";
+import { CONTRACT_ITEM_NO_PLAN_PICKER, CONTRACT_PLAN_BASED_HINT, WORD_FETCH_FAILED, WORD_NOT_OPENED } from "../api/lockedCopy";
+import type { CatalogPlanRow, ContractLookupCustomer, ContractRow, ContractServiceItem } from "../api/types";
+import { Async, Btn, Cell, ErrorBox, Field, Modal, Notice, Pager, Panel, Pill, day, seq } from "../components/ui";
+import { Tri, triTone } from "../components/triState";
+import { Shell } from "../layout/Shell";
+import { useSession } from "../auth/session";
+import { useForm, useLoad, useSubmit } from "../hooks/useLoad";
+
+/** 是否已开通三态(14.2 列 1):三态单元格,取数失败只坏本列。 */
+function OpenedCell({ c }: { c: ContractRow }) {
+  const tone = triTone(c.opened_state, c.opened !== null && c.opened !== undefined);
+  const text = tone === "fail" ? WORD_FETCH_FAILED : tone === "missing" ? WORD_NOT_OPENED : c.opened ? "已开通" : WORD_NOT_OPENED;
+  return <Tri tone={tone} text={text} title={tone === "fail" ? WORD_FETCH_FAILED : "派生自工单回填结果"} />;
+}
+
+/** 服务构成条目编辑器:`plan_based` 选已有档位、`custom_spec` 无套餐选择器(两格:年价必填+月结算选填)。 */
+function ItemsEditor({
+  items,
+  plans,
+  onChange,
+}: {
+  items: ContractServiceItem[];
+  plans: CatalogPlanRow[];
+  onChange: (v: ContractServiceItem[]) => void;
+}) {
+  const patch = (i: number, p: Partial<ContractServiceItem>) => onChange(items.map((it, idx) => (idx === i ? { ...it, ...p } : it)));
+  const yuan = (v: number | null | undefined) => (v === null || v === undefined ? "" : String(v / 100));
+  const cents = (v: string) => (v === "" ? null : Math.round(Number(v) * 100));
+  return (
+    <>
+      <table className="sub">
+        <thead>
+          <tr>
+            <th>条目形态</th>
+            <th>套餐</th>
+            <th>数量</th>
+            <th>账户数</th>
+            <th>上行/下行(Mbps)</th>
+            <th>年订阅价格(元)</th>
+            <th>月结算标准金额(元)</th>
+          </tr>
+        </thead>
+        <tbody>
+          {items.length === 0 ? (
+            <tr>
+              <td colSpan={7}>
+                <span className="note">至少添加一条服务构成条目</span>
+              </td>
+            </tr>
+          ) : (
+            items.map((it, i) => {
+              const custom = (it.item_kind ?? "custom_spec") === "custom_spec";
+              return (
+                <tr key={i}>
+                  <td>
+                    <select value={it.item_kind ?? "custom_spec"} onChange={(e) => patch(i, { item_kind: e.target.value, plan_id: null })}>
+                      {OPTIONS.item_kind.map((o) => (
+                        <option key={o.value} value={o.value}>
+                          {o.label}
+                        </option>
+                      ))}
+                    </select>
+                  </td>
+                  <td>
+                    {custom ? (
+                      <span className="note">不指定固定套餐</span>
+                    ) : (
+                      <select value={it.plan_id ?? ""} onChange={(e) => patch(i, { plan_id: e.target.value || null })}>
+                        <option value="">请选择档位</option>
+                        {plans.map((p) => (
+                          <option key={p.plan_id} value={p.plan_id}>
+                            {p.plan_name}
+                          </option>
+                        ))}
+                      </select>
+                    )}
+                  </td>
+                  <td>
+                    <input type="number" min={1} value={it.quantity ?? 1} onChange={(e) => patch(i, { quantity: Number(e.target.value) })} />
+                  </td>
+                  <td>
+                    <input type="number" min={0} value={it.account_count ?? ""} onChange={(e) => patch(i, { account_count: e.target.value === "" ? undefined : Number(e.target.value) })} />
+                  </td>
+                  <td>
+                    <input type="number" min={0} style={{ width: 70 }} value={it.bandwidth_up_mbps ?? ""} onChange={(e) => patch(i, { bandwidth_up_mbps: e.target.value === "" ? undefined : Number(e.target.value) })} />
+                    /
+                    <input type="number" min={0} style={{ width: 70 }} value={it.bandwidth_down_mbps ?? ""} onChange={(e) => patch(i, { bandwidth_down_mbps: e.target.value === "" ? undefined : Number(e.target.value) })} />
+                  </td>
+                  <td>
+                    {custom ? (
+                      <input type="number" min={0} step="0.01" value={yuan(it.annual_price_cents)} onChange={(e) => patch(i, { annual_price_cents: cents(e.target.value) })} />
+                    ) : (
+                      <span className="note">取套餐</span>
+                    )}
+                  </td>
+                  <td>
+                    {custom ? (
+                      <input type="number" min={0} step="0.01" value={yuan(it.monthly_settle_cents)} onChange={(e) => patch(i, { monthly_settle_cents: cents(e.target.value) })} />
+                    ) : (
+                      <span className="note">取套餐</span>
+                    )}
+                  </td>
+                  <td>
+                    <Btn ghost onClick={() => onChange(items.filter((_, idx) => idx !== i))}>
+                      移除
+                    </Btn>
+                  </td>
+                </tr>
+              );
+            })
+          )}
+        </tbody>
+      </table>
+      <div className="row" style={{ marginTop: 8 }}>
+        <Btn ghost onClick={() => onChange([...items, { item_kind: "custom_spec", quantity: 1 }])}>
+          添加条目
+        </Btn>
+      </div>
+      <p className="note">{CONTRACT_ITEM_NO_PLAN_PICKER}</p>
+      <p className="note">{CONTRACT_PLAN_BASED_HINT}</p>
+    </>
+  );
+}
+
+export default function ContractsPage() {
+  const nav = useNavigate();
+  const { ctx } = useSession();
+  const canWrite = ctx?.role_code === "admin" || ctx?.role_code === "opsMain";
+  const [f, setF] = useState({ keyword: "", opened: "", page: 1, page_size: 20 });
+  const [draft, setDraft] = useState<{ contract?: ContractRow } | null>(null);
+  const [del, setDel] = useState<{ contract: ContractRow; blocks?: unknown } | null>(null);
+  const [items, setItems] = useState<ContractServiceItem[]>([]);
+  const [lookup, setLookup] = useState<{ keyword?: string; matched: boolean; customers: ContractLookupCustomer[] } | null>(null);
+  const [freeText, setFreeText] = useState("");
+  const form = useForm({
+    contract_no: "",
+    customer_id: "",
+    credit_code: "",
+    identity_no: "",
+    customer_name: "",
+    external_no: "",
+    start_date: "",
+    end_date: "",
+    pay_cycle: "yearly",
+    attachment_url: "",
+  });
+  const sub = useSubmit();
+
+  const list = useLoad(
+    () =>
+      contractGetList({
+        keyword: f.keyword || undefined,
+        opened: f.opened === "" ? undefined : f.opened === "1",
+        page: f.page - 1,
+        page_size: f.page_size,
+      }),
+    [f.keyword, f.opened, f.page, f.page_size],
+  );
+  const plans = useLoad(() => catalogGetList({ page: 1, page_size: 200 }), []);
+
+  const rows = list.data?.items ?? [];
+  const stats = list.data?.stats;
+
+  const openCreate = () => {
+    form.reset({ contract_no: "", customer_id: "", credit_code: "", identity_no: "", customer_name: "", external_no: "", start_date: "", end_date: "", pay_cycle: "yearly", attachment_url: "" });
+    setItems([{ item_kind: "custom_spec", quantity: 1 }]);
+    setLookup(null);
+    setFreeText("");
+    sub.clear();
+    setDraft({});
+  };
+
+  const openEdit = (c: ContractRow) => {
+    form.reset({
+      contract_no: c.contract_no ?? "",
+      customer_id: c.customer_id ?? "",
+      credit_code: "",
+      identity_no: "",
+      customer_name: c.customer_name ?? "",
+      external_no: c.external_no ?? "",
+      start_date: c.start_date ?? "",
+      end_date: c.end_date ?? "",
+      pay_cycle: c.pay_cycle ?? "yearly",
+      attachment_url: c.attachment_url ?? "",
+    });
+    setItems(c.service_items ?? []);
+    setLookup(null);
+    setFreeText("");
+    sub.clear();
+    setDraft({ contract: c });
+  };
+
+  /** 三种命中方式:信用码→证件号→名称模糊;未命中⛔ 报错,转自由录入。 */
+  const doLookup = async () => {
+    const d = {
+      credit_code: form.get("credit_code") || undefined,
+      identity_no: form.get("identity_no") || undefined,
+      customer_name: form.get("customer_name") || undefined,
+    };
+    if (!d.credit_code && !d.identity_no && !d.customer_name) return;
+    try {
+      const r = await contractCustomerLookup(d);
+      setLookup({ keyword: d.credit_code ?? d.identity_no ?? d.customer_name, matched: r.matched, customers: r.customers ?? [] });
+    } catch (e) {
+      setLookup({ matched: false, customers: [], keyword: "" });
+      sub.run(async () => {
+        throw e;
+      });
+    }
+  };
+
+  const save = async () => {
+    const ok = await sub.run(async () => {
+      if (!form.get("start_date") || !form.get("end_date")) throw new Error("请填写开始日与结束日");
+      if (items.length === 0) throw new Error("至少添加一条服务构成条目");
+      for (const it of items) {
+        if ((it.item_kind ?? "custom_spec") === "custom_spec" && !it.annual_price_cents) throw new Error("自定义式条目的年订阅价格必填");
+        if ((it.item_kind ?? "custom_spec") === "plan_based" && !it.plan_id) throw new Error("套餐式条目需选择已有档位");
+      }
+      const payload = {
+        external_no: form.get("external_no") || undefined,
+        start_date: form.get("start_date"),
+        end_date: form.get("end_date"),
+        pay_cycle: form.get("pay_cycle") || undefined,
+        attachment_url: form.get("attachment_url") || undefined,
+        service_items: items,
+        ip_entries: [],
+      };
+      if (draft?.contract) {
+        // 合同编号与签约客户不可改(出现 ⇒ L214),故不进载荷
+        return contractUpdate({ contract_id: draft.contract.contract_id, row_version: Number(draft.contract.row_version), ...payload });
+      }
+      if (!form.get("customer_id") && !freeText.trim()) throw new Error("请检索签约客户,或改用自由录入");
+      return contractCreate({
+        contract_no: form.get("contract_no") || undefined,
+        customer_id: form.get("customer_id") || undefined,
+        customer_free_text: freeText.trim() || undefined,
+        external_no: form.get("external_no") || undefined,
+        start_date: form.get("start_date"),
+        end_date: form.get("end_date"),
+        pay_cycle: form.get("pay_cycle") || "yearly",
+        attachment_url: form.get("attachment_url") || undefined,
+        service_items: items,
+        ip_entries: [],
+      });
+    });
+    if (ok) {
+      setDraft(null);
+      await list.reload();
+      return ok;
+    }
+    if (hasBizCode(sub.error, "L213") || hasBizCode(sub.error, "L214")) return ok; // 拦截清单由行内 ErrorBox 透出
+    return ok;
+  };
+
+  const doDelete = async () => {
+    if (!del) return;
+    let removed = false;
+    const ok = await sub.run(async () => {
+      const r = await contractDelete({ contract_id: del.contract.contract_id });
+      removed = r.deleted === true;
+      if (!removed) setDel((d) => (d ? { ...d, blocks: r.blocks ?? r } : d));
+      return r;
+    });
+    if (ok && removed) {
+      setDel(null);
+      await list.reload();
+    }
+  };
+
+  const editing = !!draft?.contract;
+
+  return (
+    <Shell route="contracts" title="合同管理" hint="合同新增没有套餐选择器;编辑时合同编号与签约客户只读渲染,不提供改写入口。">
+      <Panel title="合同管理" note="合同是订阅的唯一来源;「是否已开通」派生自工单回填,取数失败只坏该列。">
+        <div className="filters">
+          <label className="f-item">
+            关键词
+            <input placeholder="合同编号/签约客户" value={f.keyword} onChange={(e) => setF((s) => ({ ...s, keyword: e.target.value, page: 1 }))} />
+          </label>
+          <label className="f-item">
+            是否已开通
+            <select value={f.opened} onChange={(e) => setF((s) => ({ ...s, opened: e.target.value, page: 1 }))}>
+              <option value="">全部</option>
+              <option value="1">已开通</option>
+              <option value="0">未开通</option>
+            </select>
+          </label>
+          {canWrite ? (
+            <Btn onClick={openCreate}>新增合同</Btn>
+          ) : null}
+        </div>
+        {stats ? (
+          <div className="cards">
+            <div className="card">
+              <div className="card-k">合同总数</div>
+              <div className="card-v">{stats.total}</div>
+            </div>
+            <div className="card">
+              <div className="card-k">已开通</div>
+              <div className="card-v">{stats.opened}</div>
+            </div>
+            <div className="card">
+              <div className="card-k">未开通</div>
+              <div className="card-v">{stats.not_opened}</div>
+            </div>
+          </div>
+        ) : null}
+      </Panel>
+
+      <Panel title="合同列表">
+        <table>
+          <thead>
+            <tr>
+              <th>序号</th>
+              <th>合同编号</th>
+              <th>签约客户</th>
+              <th>服务构成</th>
+              <th>开始日</th>
+              <th>结束日</th>
+              <th>付款周期</th>
+              <th>是否已开通</th>
+              <th>状态</th>
+              <th>操作</th>
+            </tr>
+          </thead>
+          <tbody>
+            <Async error={list.error} loading={list.loading} isEmpty={rows.length === 0} emptyText="暂无合同" cols={10}>
+              {rows.map((c, i) => (
+                <tr key={c.contract_id}>
+                  <td>{seq(f.page, f.page_size, i)}</td>
+                  <td>
+                    <a onClick={() => nav(`/contracts/${c.contract_id}`)}>{c.contract_no}</a>
+                  </td>
+                  <td>
+                    <Cell v={c.customer_name} />
+                  </td>
+                  <td>{(c.service_items ?? []).length} 条</td>
+                  <td>{day(c.start_date)}</td>
+                  <td>{day(c.end_date)}</td>
+                  <td>
+                    <Cell v={label(PAY_CYCLE, c.pay_cycle)} />
+                  </td>
+                  <td>
+                    <OpenedCell c={c} />
+                  </td>
+                  <td>
+                    <Pill text={c.status === "active" ? "履行中" : c.status === "expired" ? "已到期" : c.status} />
+                  </td>
+                  <td>
+                    <div className="row">
+                      <Btn ghost onClick={() => nav(`/contracts/${c.contract_id}`)}>
+                        详情
+                      </Btn>
+                      {canWrite ? (
+                        <>
+                          <Btn ghost onClick={() => openEdit(c)}>
+                            编辑
+                          </Btn>
+                          <Btn ghost danger onClick={() => setDel({ contract: c })}>
+                            删除
+                          </Btn>
+                        </>
+                      ) : null}
+                    </div>
+                  </td>
+                </tr>
+              ))}
+            </Async>
+          </tbody>
+        </table>
+        {list.data ? <Pager page={f.page} page_size={f.page_size} total={list.data.total ?? rows.length} onChange={(p) => setF((s) => ({ ...s, page: p }))} /> : null}
+      </Panel>
+
+      {draft ? (
+        <Modal wide title={editing ? `编辑合同 ${draft.contract?.contract_no}` : "新增合同"} onClose={() => setDraft(null)}>
+          <div className="form-grid">
+            <Field label="合同编号" required hint={editing ? "只读:合同编号不可修改(L214)" : undefined}>
+              {editing ? <span>{draft.contract?.contract_no}</span> : <input placeholder="留空由服务端生成" {...form.bind("contract_no")} />}
+            </Field>
+            <Field label="签约客户" required hint={editing ? "只读:签约客户不可修改(L214)" : undefined}>
+              {editing ? (
+                <span>{draft.contract?.customer_name}</span>
+              ) : (
+                <>
+                  <input placeholder="统一社会信用代码" {...form.bind("credit_code")} />
+                  <input placeholder="证件号" {...form.bind("identity_no")} />
+                  <input placeholder="客户名称" {...form.bind("customer_name")} />
+                  <div className="row" style={{ marginTop: 6 }}>
+                    <Btn ghost onClick={doLookup}>
+                      检索客户
+                    </Btn>
+                  </div>
+                </>
+              )}
+            </Field>
+            {!editing ? (
+              <Field label="检索结果" hint="命中即选中;未命中可自由录入(同事务先建档再签本合同)">
+                {lookup === null ? (
+                  <span className="note">尚未检索</span>
+                ) : lookup.matched ? (
+                  <select value={form.get("customer_id")} onChange={(e) => form.set("customer_id", e.target.value)}>
+                    <option value="">请选择客户</option>
+                    {lookup.customers.map((c) => (
+                      <option key={c.customer_id} value={c.customer_id}>
+                        {c.customer_name}
+                        {c.identity_no_masked ? `(${c.identity_no_masked})` : ""}
+                      </option>
+                    ))}
+                  </select>
+                ) : (
+                  <textarea rows={2} placeholder="未命中系统客户:请填写客户名称与证件信息(自由录入)" value={freeText} onChange={(e) => setFreeText(e.target.value)} />
+                )}
+              </Field>
+            ) : null}
+            <Field label="外部合同号">
+              <input {...form.bind("external_no")} />
+            </Field>
+            <Field label="开始日" required>
+              <input type="date" {...form.bind("start_date")} />
+            </Field>
+            <Field label="结束日" required>
+              <input type="date" {...form.bind("end_date")} />
+            </Field>
+            <Field label="付款周期">
+              <select {...form.bind("pay_cycle")}>
+                {OPTIONS.pay_cycle.map((o) => (
+                  <option key={o.value} value={o.value}>
+                    {o.label}
+                  </option>
+                ))}
+              </select>
+            </Field>
+            <Field label="合同扫描件" hint="随合同留档">
+              <input {...form.bind("attachment_url")} />
+            </Field>
+          </div>
+          <h3 style={{ marginTop: 14 }}>服务构成条目</h3>
+          <ItemsEditor items={items} plans={rowsOf(plans.data?.items ?? [])} onChange={setItems} />
+          {sub.error ? <ErrorBox error={sub.error} /> : null}
+          <div className="form-actions" style={{ marginTop: 12 }}>
+            <Btn onClick={save} disabled={sub.busy}>
+              {sub.busy ? "提交中…" : "保存"}
+            </Btn>
+            <Btn ghost onClick={() => setDraft(null)}>
+              取消
+            </Btn>
+          </div>
+        </Modal>
+      ) : null}
+
+      {del ? (
+        <Modal title={`删除合同 ${del.contract.contract_no}`} onClose={() => setDel(null)}>
+          <p className="note">
+            签约客户:{del.contract.customer_name},期间 {day(del.contract.start_date)} 至 {day(del.contract.end_date)}
+          </p>
+          {del.blocks ? (
+            <Notice tone="warn">
+              <strong>该合同不可删除,以下为拦截清单:</strong>
+              <pre style={{ whiteSpace: "pre-wrap", margin: "6px 0 0" }}>{JSON.stringify(del.blocks, null, 2)}</pre>
+            </Notice>
+          ) : (
+            <Notice>有订阅引用的合同将被拦截;无引用但关联工单未到终态同样拦截。</Notice>
+          )}
+          {sub.error ? <ErrorBox error={sub.error} /> : null}
+          <div className="form-actions" style={{ marginTop: 12 }}>
+            <Btn danger onClick={doDelete} disabled={sub.busy}>
+              {sub.busy ? "提交中…" : "确认删除"}
+            </Btn>
+            <Btn ghost onClick={() => setDel(null)}>
+              取消
+            </Btn>
+          </div>
+        </Modal>
+      ) : null}
+    </Shell>
+  );
+}

+ 5 - 5
front-end/src/pages/CustomerDetailPage.tsx

@@ -1,7 +1,7 @@
 import { useState, type ReactNode } from "react";
 import { useNavigate, useParams } from "react-router-dom";
 import { useSession } from "../auth/session";
-import { ACCT_STATUS, SUBJECT_TYPE, label } from "../api/labels";
+import { ACCT_STATUS, SUBJECT_TYPE, SUB_STATUS, label } from "../api/labels";
 import {
   customerAttributionUpdate,
   customerDelete,
@@ -448,9 +448,9 @@ export function CustomerDetailPage() {
             <Btn warn disabled title="发起服务停用要建工单,工单接口属第 2 册,本期未接入">
               发起服务停用
             </Btn>
-            <Btn disabled title="订阅的新增/升降配/叠加走 subscription/create 等接口,本期后端未实现">
-              套餐订阅管理
-            </Btn>
+            {adminLike && (
+              <Btn onClick={() => nav(`/customers/${id}/subs`)}>套餐订阅管理</Btn>
+            )}
           </>
         }
         note={
@@ -500,7 +500,7 @@ export function CustomerDetailPage() {
                     <Cell v={null} />
                   </td>
                   <td>
-                    <Pill text={s.status || "—"} />
+                    <Pill text={label(SUB_STATUS, s.status) || "—"} />
                   </td>
                   <td>
                     {s.start_date || s.end_date ? `${s.start_date ?? "—"} 至 ${s.end_date ?? "—"}` : <Cell v={null} />}

+ 216 - 0
front-end/src/pages/EntSubscriptionsPage.tsx

@@ -0,0 +1,216 @@
+/**
+ * 套餐订阅管理(路由 `customers/:id/subs`)—— 页面契约 14.1.3/14.4/14.6。
+ *
+ * 本客户范围内订阅的**唯一办理入口**(「全部订阅」只读,办理一律落回本页)。
+ * 行操作只有「详情」「编辑」「升降配」「删除」四项:⛔ 状态列任何按钮、⛔ 批量状态操作、
+ * ⛔ 暂停/恢复/到期不续约/取消/改结束日/提前终止。
+ *
+ * 禁止入口清单(逐条不渲染):额度有效期、按使用率调整额度、额度调整原因、
+ * 月成本与成本构成输入、套餐复制、套餐改名同步、状态列按钮与批量。
+ */
+import { useState } from "react";
+import { Link, useParams } from "react-router-dom";
+import { customerGet, rowsOf, subscriptionGetList } from "../api/bos";
+import { label, OPTIONS, SUB_STATUS, TERM } from "../api/labels";
+import { SUB_STATUS_DAILY_NOTE, WORD_FETCH_FAILED, WORD_UNCONFIGURED } from "../api/lockedCopy";
+import type { SubscriptionRow } from "../api/types";
+import { Async, Btn, Cell, Field, Pager, Panel, Pill, day, datetime, money, seq } from "../components/ui";
+import { Tri, triTone } from "../components/triState";
+import { Shell } from "../layout/Shell";
+import { useSession } from "../auth/session";
+import { useLoad } from "../hooks/useLoad";
+import { SubscriptionDeleteDialog, SubscriptionFormDialog } from "./SubscriptionFormDialog";
+
+type Mode = "create" | "change" | "edit";
+
+export default function EntSubscriptionsPage() {
+  const { id = "" } = useParams();
+  const { ctx } = useSession();
+  const canWrite = ["admin", "opsMain", "opsSub", "teamLead", "ops"].includes(ctx?.role_code ?? "");
+  const [f, setF] = useState({ keyword: "", status: "", use_category: "", term: "", page: 1, page_size: 20 });
+  const [dialog, setDialog] = useState<{ mode: Mode; row?: SubscriptionRow } | null>(null);
+  const [del, setDel] = useState<SubscriptionRow | null>(null);
+
+  const cust = useLoad(() => customerGet({ customer_id: id }), [id]);
+  const list = useLoad(
+    () =>
+      subscriptionGetList({
+        customer_id: id,
+        keyword: f.keyword || undefined,
+        status: f.status || undefined,
+        use_category: f.use_category || undefined,
+        term: f.term || undefined,
+        page: f.page - 1,
+        page_size: f.page_size,
+      }),
+    [id, f.keyword, f.status, f.use_category, f.term, f.page, f.page_size],
+  );
+
+  const rows = rowsOf(list.data);
+  const customerName = cust.data?.customer?.customer_name ?? rows[0]?.customer_name ?? id;
+
+  /** 编辑能力取服务端 `editable`+`reason`;后端未回该键时不禁用(由后端在提交时兜底拦截)。 */
+  const editBlocked = (r: SubscriptionRow) => r.editable === false;
+
+  return (
+    <Shell route="customers" title={`套餐订阅管理 · ${customerName}`} hint="本页是本客户订阅的唯一办理入口;状态由服务端按日终刷新,前端只读。">
+      <Panel
+        title="本客户订阅"
+        extra={
+          <div className="row">
+            <Link to={`/customers/${id}`}>返回客户详情</Link>
+            {canWrite ? (
+              <Btn onClick={() => setDialog({ mode: "create" })}>新增订阅</Btn>
+            ) : null}
+          </div>
+        }
+        note="「新增订阅」的套餐下拉只列可订阅档位并带出来源标识;合同下拉两层(合同 → 该合同下尚未建订阅的条目),选定条目才决定线路出口。"
+      >
+        <div className="filters">
+          <Field label="关键词">
+            <input
+              value={f.keyword}
+              onChange={(e) => setF({ ...f, keyword: e.target.value, page: 1 })}
+              placeholder="套餐名称/编码/合同编号"
+            />
+          </Field>
+          <Field label="状态">
+            <select value={f.status} onChange={(e) => setF({ ...f, status: e.target.value, page: 1 })}>
+              <option value="">全部</option>
+              {OPTIONS.sub_status.map((o) => (
+                <option key={o.value} value={o.value}>
+                  {o.label}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="用途分类">
+            <select value={f.use_category} onChange={(e) => setF({ ...f, use_category: e.target.value, page: 1 })}>
+              <option value="">全部</option>
+              {OPTIONS.use_category.map((o) => (
+                <option key={o.value} value={o.value}>
+                  {o.label}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="订阅规格">
+            <select value={f.term} onChange={(e) => setF({ ...f, term: e.target.value, page: 1 })}>
+              <option value="">全部</option>
+              {OPTIONS.term.map((o) => (
+                <option key={o.value} value={o.value}>
+                  {o.label}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <div className="row" style={{ alignItems: "flex-end" }}>
+            <Btn ghost onClick={list.reload}>
+              查询
+            </Btn>
+          </div>
+        </div>
+
+        <Async loading={list.loading && rows.length === 0} error={list.error} isEmpty={rows.length === 0} emptyText="该客户暂无订阅记录">
+          <table>
+            <thead>
+              <tr>
+                <th>序号</th>
+                <th>订阅编号</th>
+                <th>套餐</th>
+                <th>规格</th>
+                <th>
+                  状态
+                  <span className="th-note">{SUB_STATUS_DAILY_NOTE}</span>
+                </th>
+                <th>开始日</th>
+                <th>结束日</th>
+                <th>合同编号/订单号</th>
+                <th>月结算标准金额</th>
+                <th>月成本</th>
+                <th>额度</th>
+                <th>操作</th>
+              </tr>
+            </thead>
+            <tbody>
+              {rows.map((r, i) => {
+                const costTone = triTone(r.plan_cost_state, r.plan_cost_cents !== null && r.plan_cost_cents !== undefined);
+                return (
+                  <tr key={r.subscription_id}>
+                    <td>{seq(1, 20, i)}</td>
+                    <td>{r.subscription_id}</td>
+                    <td>{r.plan_name ?? "—"}</td>
+                    <td>{label(TERM, r.term) || "—"}</td>
+                    <td>
+                      <Pill text={label(SUB_STATUS, r.status)} />
+                      {r.status === "pending" && r.actual_opened_at ? (
+                        <div className="note">回填时间 {datetime(r.actual_opened_at)}</div>
+                      ) : null}
+                    </td>
+                    <td>{day(r.start_date)}</td>
+                    <td>{day(r.end_date)}</td>
+                    <td>
+                      {r.contract_no ? <Link to={`/contracts/${r.contract_id}`}>{r.contract_no}</Link> : r.contract_id}
+                      <div className="note">订单号 {r.order_no || "—"}</div>
+                    </td>
+                    <td>
+                      <Cell v={r.monthly_settle_cents === null || r.monthly_settle_cents === undefined ? null : money(r.monthly_settle_cents)} />
+                    </td>
+                    <td>
+                      <Tri
+                        tone={costTone}
+                        text={costTone === "val" ? money(r.plan_cost_cents) : costTone === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED}
+                      />
+                    </td>
+                    <td>计入额度 {r.quota_slots}</td>
+                    <td>
+                      <div className="row">
+                        <Link to={`/subs/${r.subscription_id}`}>详情</Link>
+                        {canWrite ? (
+                          <>
+                            <Btn
+                              ghost
+                              disabled={r.status !== "active" || editBlocked(r)}
+                              title={editBlocked(r) ? (r.reason ?? "服务端判定不可编辑") : r.status !== "active" ? "仅生效中订阅可编辑" : undefined}
+                              onClick={() => setDialog({ mode: "edit", row: r })}
+                            >
+                              编辑
+                            </Btn>
+                            <Btn
+                              ghost
+                              disabled={r.status !== "active" || editBlocked(r)}
+                              title={editBlocked(r) ? (r.reason ?? "服务端判定不可变更") : r.status !== "active" ? "升降配只在生效中行提供" : undefined}
+                              onClick={() => setDialog({ mode: "change", row: r })}
+                            >
+                              升降配
+                            </Btn>
+                            <Btn ghost danger onClick={() => setDel(r)}>
+                              删除
+                            </Btn>
+                          </>
+                        ) : null}
+                      </div>
+                    </td>
+                  </tr>
+                );
+              })}
+            </tbody>
+          </table>
+          <Pager page={f.page} page_size={f.page_size} total={list.data?.total ?? rows.length} onChange={(p) => setF({ ...f, page: p })} />
+        </Async>
+      </Panel>
+
+      {dialog ? (
+        <SubscriptionFormDialog
+          mode={dialog.mode}
+          customerId={id}
+          customerName={customerName}
+          original={dialog.row ?? null}
+          onClose={() => setDialog(null)}
+          onDone={list.reload}
+        />
+      ) : null}
+      {del ? <SubscriptionDeleteDialog sub={del} onClose={() => setDel(null)} onDeleted={list.reload} /> : null}
+    </Shell>
+  );
+}

+ 10 - 6
front-end/src/pages/HomePage.tsx

@@ -11,6 +11,7 @@ import {
   regionTree,
 } from "../api/bos";
 import { ROLE_LABEL, useSession } from "../auth/session";
+import { routesFor } from "../auth/nav";
 import { Btn, KpiCard, Panel } from "../components/ui";
 import { useLoad } from "../hooks/useLoad";
 import { Shell } from "../layout/Shell";
@@ -42,27 +43,30 @@ export function HomePage() {
     custAll.loading || custInUse.loading || custNotOpened.loading || operators.loading || partners.loading;
 
   const scope = "当前登录身份可见范围(后端下发)";
+  // 待办卡的跳转目标与路由守卫同源(`routesFor`):侧栏收口后,指向越界域的按钮会撞上
+  // `RequireRole` 弹回首页,成了死链 ⇒ 本身份不可达的域⛔ 给跳转按钮。
+  const canGo = (r: string) => routesFor(ctx?.role_code).includes(r);
   const todos = [
     {
       name: "客户账号未开通",
       basis: "建档后主账号仍未开通/未激活,客户无法登录自助门户",
       count: n(custNotOpened),
-      go: () => nav("/customers"),
-      goText: "去处理",
+      go: canGo("customers") ? () => nav("/customers") : null,
+      goText: canGo("customers") ? "去处理" : "",
     },
     {
       name: "批量导入部分成功,存在失败明细",
       basis: "导入批次内有校验失败行,需修正后续传或重新导入",
       count: n(importPending),
-      go: () => nav("/imports"),
-      goText: "去补跑",
+      go: canGo("imports") ? () => nav("/imports") : null,
+      goText: canGo("imports") ? "去补跑" : "",
     },
     {
       name: "区域挂载申请待认领",
       basis: "悬空挂载申请(主体已建、区域尚未确认),需区域管理员指定承接",
       count: orphans.data?.dangling_count ?? null,
-      go: () => nav("/regions"),
-      goText: "去区域",
+      go: canGo("regions") ? () => nav("/regions") : null,
+      goText: canGo("regions") ? "去区域" : "",
     },
     {
       name: "新装/维修工单待分派",

+ 15 - 0
front-end/src/pages/SubAccountsPage.tsx

@@ -33,6 +33,21 @@ export function SubAccountsPage() {
   const isMain = ctx?.subject_type === "customer";
   const [customerId, setCustomerId] = useState(ownId);
 
+  // 维护分账号是客户主账号/运营侧的权限(TC-AC-04 步骤 4/TC-CU-62):下属分账号本人
+  // ⛔ 可进入本页。`navFor("sub")` 已收掉侧栏入口、`RequireRole` 拦地址栏深链,这里兜最后一层
+  // ——后端 `sub_account/get_list` 对分账号身份并不拒(只看 `customer_id`),⛔ 靠它兜底。
+  if (ctx?.subject_type === "sub_account") {
+    return (
+      <Shell route="subaccounts" title="下属分账号" hint={HINT}>
+        <Panel title="无权限维护分账号">
+          <p className="note">
+            分账号的姓名维护由客户主账号办理,下属分账号本人不可进入本页。如需修改姓名,请联系本公司主账号或对接运营。
+          </p>
+        </Panel>
+      </Shell>
+    );
+  }
+
   return (
     <Shell route="subaccounts" title="下属分账号" hint={HINT}>
       {customerId ? (

+ 351 - 0
front-end/src/pages/SubscriptionDetailPage.tsx

@@ -0,0 +1,351 @@
+/**
+ * 订阅详情(路由 `subs/:id`)—— 页面契约 14.3/14.4。
+ *
+ * 面板顺序照契约 §3.3:基础信息/订阅周期/金额/线路出口/额度;
+ * `original`/`replaced_by` 任一非空时追加「关联订阅」面板(⛔ 并入基础信息面板)。
+ * 跨册面板(计费与出账=第6册、关联工单=第5册)未接线 ⇒ **整面板「未配置」**,⛔ 渲染 0/空态。
+ *
+ * 禁止入口清单(逐条不渲染):额度有效期、按使用率调整额度、额度调整原因、月成本与成本构成输入、
+ * 状态列按钮与批量、暂停/恢复/到期不续约/取消/改结束日/提前终止。
+ */
+import { useState } from "react";
+import { Link, useParams } from "react-router-dom";
+import { contractGet, subscriptionGet } from "../api/bos";
+import { label, ITEM_KIND, PAY_CYCLE, SUB_STATUS, TERM } from "../api/labels";
+import {
+  NOT_GROSS_PROFIT,
+  OPERATOR_ONLY_CONFIG,
+  SUB_AMOUNT_TITLE,
+  SUB_END_DATE_READONLY,
+  SUB_STATUS_DAILY_NOTE,
+  SUBS_READONLY_ENTRY,
+  UPGRADE_CUTOFF_RULE,
+  WORD_FETCH_FAILED,
+  WORD_UNCONFIGURED,
+} from "../api/lockedCopy";
+import { Card, Panel, Pill, Btn, ErrorBox, Loading, Notice, day, datetime, money } from "../components/ui";
+import { Tri, triTone } from "../components/triState";
+import { Shell } from "../layout/Shell";
+import { useSession } from "../auth/session";
+import { useLoad } from "../hooks/useLoad";
+import { SubscriptionDeleteDialog, SubscriptionFormDialog } from "./SubscriptionFormDialog";
+
+export default function SubscriptionDetailPage() {
+  const { id = "" } = useParams();
+  const { ctx } = useSession();
+  const canWrite = ["admin", "opsMain", "opsSub", "teamLead", "ops"].includes(ctx?.role_code ?? "");
+  const [dialog, setDialog] = useState<{ mode: "change" | "edit" } | null>(null);
+  const [del, setDel] = useState(false);
+
+  const d = useLoad(() => subscriptionGet({ subscription_id: id }), [id]);
+  const s = d.data;
+  const ct = useLoad(() => (s?.contract_id ? contractGet({ contract_id: s.contract_id }) : Promise.resolve(null)), [s?.contract_id]);
+
+  if (d.loading && !s)
+    return (
+      <Shell route="subs" title="订阅详情" hint={SUBS_READONLY_ENTRY}>
+        <Loading />
+      </Shell>
+    );
+  if (!s)
+    return (
+      <Shell route="subs" title="订阅详情" hint={SUBS_READONLY_ENTRY}>
+        <ErrorBox error={d.error ?? new Error("订阅不存在")} />
+        <Btn ghost onClick={d.reload}>
+          重新加载
+        </Btn>
+      </Shell>
+    );
+
+  const costTone = triTone(s.plan_cost_state, s.plan_cost_cents !== null && s.plan_cost_cents !== undefined);
+  const related = s.related ?? null;
+  const hasRelated = !!related?.original || !!related?.replaced_by;
+  const editBlocked = s.editable === false;
+  const showProfitNote =
+    s.annual_price_cents !== null && s.annual_price_cents !== undefined && s.plan_cost_cents !== null && s.plan_cost_cents !== undefined;
+
+  return (
+    <Shell route="subs" title={`订阅详情 ${s.subscription_id}`} hint={SUBS_READONLY_ENTRY}>
+      <div className="cards">
+        <Card label="年订阅价格" value={money(s.annual_price_cents)} sub={SUB_AMOUNT_TITLE} />
+        <Card
+          label="月成本"
+          value={costTone === "val" ? money(s.plan_cost_cents) : costTone === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED}
+          sub={OPERATOR_ONLY_CONFIG}
+        />
+        <Card label="已出账金额" value={WORD_UNCONFIGURED} sub="计费与出账面板未接线(第6册),整面板「未配置」,不以 0 冒充" />
+        <Card label="已出账期数" value={WORD_UNCONFIGURED} sub="同上:缺值与失败三态区分,⛔ 回退 0 期" />
+      </div>
+      {showProfitNote ? <Notice>「年订阅价格」与「月成本」是两条独立口径:{NOT_GROSS_PROFIT}。</Notice> : null}
+
+      <Panel
+        title="基础信息"
+        extra={
+          <div className="row">
+            {canWrite ? (
+              <>
+                <Btn
+                  ghost
+                  disabled={s.status !== "active" || editBlocked}
+                  title={editBlocked ? (s.reason ?? "服务端判定不可编辑") : s.status !== "active" ? "仅生效中订阅可编辑" : undefined}
+                  onClick={() => setDialog({ mode: "edit" })}
+                >
+                  编辑
+                </Btn>
+                <Btn
+                  ghost
+                  disabled={s.status !== "active" || editBlocked}
+                  title={editBlocked ? (s.reason ?? "服务端判定不可变更") : s.status !== "active" ? "升降配只在生效中行提供" : undefined}
+                  onClick={() => setDialog({ mode: "change" })}
+                >
+                  升降配
+                </Btn>
+                <Btn ghost danger onClick={() => setDel(true)}>
+                  删除
+                </Btn>
+              </>
+            ) : null}
+            <Btn ghost onClick={d.reload}>
+              刷新
+            </Btn>
+          </div>
+        }
+        note={`状态由服务端按日终刷新:${SUB_STATUS_DAILY_NOTE};跨零点滞后的解释不另写第二段。`}
+      >
+        <div className="kv">
+          <div>
+            <span className="note">订阅编号</span>
+            <div>{s.subscription_id}</div>
+          </div>
+          <div>
+            <span className="note">归属客户</span>
+            <div>
+              <Link to={`/customers/${s.customer_id}`}>{s.customer_name ?? s.customer_id}</Link>
+            </div>
+          </div>
+          <div>
+            <span className="note">关联合同</span>
+            <div>
+              <Link to={`/contracts/${s.contract_id}`}>{s.contract_no ?? s.contract_id}</Link>
+            </div>
+          </div>
+          <div>
+            <span className="note">合同条目</span>
+            <div>{s.contract_item_id ?? "—"}</div>
+          </div>
+          <div>
+            <span className="note">套餐</span>
+            <div>{s.plan_name ?? "—"}</div>
+          </div>
+          <div>
+            <span className="note">订阅方式</span>
+            <div>{s.sub_mode_label ?? s.sub_mode ?? "—"}</div>
+          </div>
+          <div>
+            <span className="note">状态</span>
+            <div>
+              <Pill text={label(SUB_STATUS, s.status)} />
+            </div>
+          </div>
+          <div>
+            <span className="note">订单号</span>
+            <div>{s.order_no || "—"}</div>
+          </div>
+          <div>
+            <span className="note">实际开通日</span>
+            <div title="本册不提供写入入口;唯一写入方=工单回填">
+              {s.actual_opened_at ? datetime(s.actual_opened_at) : "—"}
+              {s.status === "pending" ? (
+                <span className="note" style={{ marginLeft: 6 }}>
+                  回填前保持待开通
+                </span>
+              ) : null}
+            </div>
+          </div>
+          <div>
+            <span className="note">创建时间</span>
+            <div>{datetime(s.created_at)}</div>
+          </div>
+        </div>
+      </Panel>
+
+      <Panel title="订阅周期" note="结束日只读;提前终止请发起服务停用,由回填结果截断。">
+        <div className="kv">
+          <div>
+            <span className="note">订阅时长</span>
+            <div>{label(TERM, s.term) || "—"}</div>
+          </div>
+          <div>
+            <span className="note">开始日</span>
+            <div>{day(s.start_date)}</div>
+          </div>
+          <div>
+            <span className="note">结束日</span>
+            <div title={SUB_END_DATE_READONLY}>{day(s.end_date)}</div>
+          </div>
+          <div>
+            <span className="note">试用月数</span>
+            <div>{s.trial_months ?? 0}</div>
+          </div>
+          <div>
+            <span className="note">生效日</span>
+            <div>{s.effective_date ? day(s.effective_date) : "—"}</div>
+          </div>
+          <div>
+            <span className="note">到期日</span>
+            <div>{s.expire_date ? day(s.expire_date) : "—"}</div>
+          </div>
+        </div>
+      </Panel>
+
+      <Panel title="金额">
+        <div className="kv">
+          <div>
+            <span className="note">年订阅价格</span>
+            <div>{money(s.annual_price_cents)}</div>
+          </div>
+          <div>
+            <span className="note">月结算标准金额</span>
+            <div>{money(s.monthly_settle_cents)}</div>
+          </div>
+          <div>
+            <span className="note">月折让金额</span>
+            <div>{s.discount_monthly_cents === null || s.discount_monthly_cents === undefined ? "—" : money(s.discount_monthly_cents)}</div>
+          </div>
+          <div>
+            <span className="note">月成本</span>
+            <div>
+              <Tri
+                tone={costTone}
+                text={costTone === "val" ? money(s.plan_cost_cents) : costTone === "fail" ? WORD_FETCH_FAILED : WORD_UNCONFIGURED}
+                title={OPERATOR_ONLY_CONFIG}
+              />
+            </div>
+          </div>
+        </div>
+        {showProfitNote ? <p className="note">{NOT_GROSS_PROFIT}</p> : null}
+      </Panel>
+
+      <Panel title="线路出口">
+        {(s.line_exits ?? []).length === 0 ? (
+          <span className="note">{WORD_UNCONFIGURED}</span>
+        ) : (
+          <div className="row">{(s.line_exits ?? []).map((x) => <Pill key={x} text={x} />)}</div>
+        )}
+      </Panel>
+
+      <Panel title="额度" note="额度=本订阅计入的分账号额度,由服务端落库并驱动分账号补建;⛔ 额度有效期、⛔ 按使用率调整额度、⛔ 额度调整原因。">
+        <div className="kv">
+          <div>
+            <span className="note">计入额度</span>
+            <div>{s.quota_slots}</div>
+          </div>
+          <div>
+            <span className="note">额度来源</span>
+            <div>{s.plan_kind === "custom" ? "自定义档(含合同条目派生)" : "固定档快照"}</div>
+          </div>
+        </div>
+      </Panel>
+
+      {hasRelated ? (
+        <Panel title="关联订阅" note="原值/新值两列原样展示,⛔ 自算差额、⛔ 合并进基础信息面板。">
+          <table className="sub">
+            <thead>
+              <tr>
+                <th>关系</th>
+                <th>订阅编号</th>
+                <th>套餐</th>
+                <th>状态</th>
+                <th>起止</th>
+                <th>结束日</th>
+              </tr>
+            </thead>
+            <tbody>
+              {related?.original ? (
+                <tr>
+                  <td>被本订阅替换的原订阅</td>
+                  <td>
+                    <Link to={`/subs/${related.original.subscription_id}`}>{related.original.subscription_id}</Link>
+                  </td>
+                  <td>{related.original.plan_name ?? "—"}</td>
+                  <td>
+                    <Pill text={label(SUB_STATUS, related.original.status)} />
+                  </td>
+                  <td>
+                    {day(related.original.start_date)} ~ {day(related.original.end_date)}
+                  </td>
+                  <td title={UPGRADE_CUTOFF_RULE}>{day(related.original.end_date)}</td>
+                </tr>
+              ) : null}
+              {related?.replaced_by ? (
+                <tr>
+                  <td>由本订阅派生的新订阅</td>
+                  <td>
+                    <Link to={`/subs/${related.replaced_by.subscription_id}`}>{related.replaced_by.subscription_id}</Link>
+                  </td>
+                  <td>{related.replaced_by.plan_name ?? "—"}</td>
+                  <td>
+                    <Pill text={label(SUB_STATUS, related.replaced_by.status)} />
+                  </td>
+                  <td>
+                    {day(related.replaced_by.start_date)} ~ {day(related.replaced_by.end_date)}
+                  </td>
+                  <td>{day(related.replaced_by.end_date)}</td>
+                </tr>
+              ) : null}
+            </tbody>
+          </table>
+          <p className="note">{UPGRADE_CUTOFF_RULE}</p>
+        </Panel>
+      ) : null}
+
+      <Panel title="计费与出账">
+        <Notice tone="warn">
+          {WORD_UNCONFIGURED}——该面板口径属第6册(出账与对账),本册未接线;整面板按「未配置」呈现,⛔ 以 0 元/0 期冒充真实数值。
+        </Notice>
+      </Panel>
+
+      <Panel title="关联工单">
+        <Notice tone="warn">{WORD_UNCONFIGURED}——工单口径属第5册,本册未接线;「是否已开通」的实际开通日由工单回填,本页只读。</Notice>
+      </Panel>
+
+      <Panel title="合同文件">
+        {ct.loading ? <Loading /> : null}
+        {ct.error ? <ErrorBox error={ct.error} /> : null}
+        {ct.data ? (
+          <div className="kv">
+            <div>
+              <span className="note">合同编号</span>
+              <div>{ct.data.contract_no}</div>
+            </div>
+            <div>
+              <span className="note">合同扫描件</span>
+              <div>{ct.data.attachment_url ? <a href={ct.data.attachment_url}>查看扫描件</a> : "—"}</div>
+            </div>
+            <div>
+              <span className="note">付款周期</span>
+              <div>{label(PAY_CYCLE, ct.data.pay_cycle) || "—"}</div>
+            </div>
+            <div>
+              <span className="note">条目形态</span>
+              <div>{ct.data.service_items?.length ? label(ITEM_KIND, ct.data.service_items[0].item_kind) : "—"}</div>
+            </div>
+          </div>
+        ) : null}
+        <p className="note">合同扫描件随合同留档,⛔ 复制到订阅侧。</p>
+      </Panel>
+
+      {dialog ? (
+        <SubscriptionFormDialog
+          mode={dialog.mode}
+          customerId={s.customer_id}
+          customerName={s.customer_name}
+          original={s}
+          onClose={() => setDialog(null)}
+          onDone={d.reload}
+        />
+      ) : null}
+      {del ? <SubscriptionDeleteDialog sub={s} onClose={() => setDel(false)} onDeleted={d.reload} /> : null}
+    </Shell>
+  );
+}

+ 498 - 0
front-end/src/pages/SubscriptionFormDialog.tsx

@@ -0,0 +1,498 @@
+/**
+ * 订阅写弹窗(新增/升降配/编辑)+ 删除弹窗 —— 第3册两个入口共用同一组件。
+ *
+ * 字段口径(页面契约 14.1.3/14.3/14.6):
+ * - 只读六项=线路出口/订阅方式/订单号/结束日/年订阅价格/月结算标准金额,⛔ 出现在提交载荷;
+ * - 实际开通日恒为只读空值,唯一写入方=工单回填;
+ * - 时长三值切换就地重算结束日(仅本地预览),两金额只读;
+ * - ⛔ 月成本/成本构成输入,⛔ 按使用率调整额度,⛔ 额度有效期;
+ * - `M225`/`M226` 冲突 ⇒ 关闭弹窗并刷新列表,⛔ 只禁用提交按钮;
+ * - 删除确认按钮在服务端返回可删(`delete_check.deletable`)之前不解锁。
+ */
+import { useEffect, useState, type ReactNode } from "react";
+import { Link } from "react-router-dom";
+import {
+  rowsOf,
+  subscriptionChange,
+  subscriptionContractOptions,
+  subscriptionCreate,
+  subscriptionDelete,
+  subscriptionDeleteCheck,
+  subscriptionPlanOptions,
+  subscriptionUpdate,
+} from "../api/bos";
+import { hasBizCode } from "../api/http";
+import { label, OPTIONS, TERM } from "../api/labels";
+import {
+  SUB_AMOUNT_TITLE,
+  SUB_CREATE_READONLY_FIELDS,
+  SUB_CREATE_READONLY_NOTE,
+  SUB_DELETE_PLAN_LOCK_NOTE,
+  SUB_END_DATE_READONLY,
+  SUB_MODE_BY_CATEGORY,
+  UPGRADE_CUTOFF_RULE,
+  WORD_FETCH_FAILED,
+} from "../api/lockedCopy";
+import type {
+  SubscriptionContractItemOption,
+  SubscriptionContractOption,
+  SubscriptionDeleteCheckResult,
+  SubscriptionPlanOption,
+  SubscriptionRow,
+} from "../api/types";
+import { Btn, ErrorBox, Field, Loading, Modal, Notice, Pill, day, datetime, money } from "../components/ui";
+
+const pad = (n: number) => String(n).padStart(2, "0");
+
+/** 本地「今天」(⛔ toISOString:东八区零点会整体前移一天)。 */
+function today(): string {
+  const d = new Date();
+  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+}
+
+/** 时长⇒结束日预览(仅用于就地重算显示,⛔ 随表单提交)。 */
+function termEnd(start: string, term: string): string {
+  if (!start) return "";
+  const e = new Date(`${start}T00:00:00`);
+  if (Number.isNaN(e.getTime())) return "";
+  if (term === "yearly") e.setFullYear(e.getFullYear() + 1);
+  else if (term === "quarterly") e.setMonth(e.getMonth() + 3);
+  else e.setMonth(e.getMonth() + 1);
+  e.setDate(e.getDate() - 1);
+  return `${e.getFullYear()}-${pad(e.getMonth() + 1)}-${pad(e.getDate())}`;
+}
+
+/** 只读灰显单元格(⛔ 置灰输入框:值不可改写也不进载荷)。 */
+function Ro({ children, title }: { children: ReactNode; title?: string }) {
+  return (
+    <span className="ro" title={title}>
+      {children}
+    </span>
+  );
+}
+
+/** M225/M226 ⇒ 关闭弹窗并让父级刷新。 */
+const isConflict = (e: unknown) => hasBizCode(e, "M225") || hasBizCode(e, "M226");
+
+export type SubscriptionDialogProps = {
+  mode: "create" | "change" | "edit";
+  customerId: string;
+  customerName?: string | null;
+  original?: SubscriptionRow | null;
+  onClose: () => void;
+  onDone: () => void;
+};
+
+export function SubscriptionFormDialog({ mode, customerId, customerName, original, onClose, onDone }: SubscriptionDialogProps) {
+  const [contracts, setContracts] = useState<SubscriptionContractOption[]>([]);
+  const [plans, setPlans] = useState<SubscriptionPlanOption[]>([]);
+  const [loadErr, setLoadErr] = useState<unknown>(null);
+  const [loading, setLoading] = useState(mode !== "edit");
+  const [busy, setBusy] = useState(false);
+  const [err, setErr] = useState<unknown>(null);
+
+  const [contractId, setContractId] = useState("");
+  const [itemId, setItemId] = useState("");
+  const [term, setTerm] = useState("yearly");
+  const [startDate, setStartDate] = useState(mode === "edit" ? (original?.start_date ?? today()) : today());
+  const [trialMonths, setTrialMonths] = useState(original?.trial_months ? String(original.trial_months) : "");
+  const [discount, setDiscount] = useState(
+    original?.discount_monthly_cents === null || original?.discount_monthly_cents === undefined ? "" : String(original.discount_monthly_cents / 100),
+  );
+  const [remark, setRemark] = useState("");
+
+  useEffect(() => {
+    if (mode === "edit") return;
+    let alive = true;
+    (async () => {
+      setLoading(true);
+      try {
+        const [cs, ps] = await Promise.all([
+          subscriptionContractOptions({ customer_id: customerId }).catch((e) => {
+            setLoadErr(e);
+            return [];
+          }),
+          subscriptionPlanOptions({ customer_id: customerId }).catch(() => []),
+        ]);
+        if (!alive) return;
+        setContracts(rowsOf(cs));
+        setPlans(rowsOf(ps));
+      } finally {
+        if (alive) setLoading(false);
+      }
+    })();
+    return () => {
+      alive = false;
+    };
+  }, [mode, customerId]);
+
+  const contract = contracts.find((c) => c.contract_id === contractId) ?? null;
+  const items: SubscriptionContractItemOption[] = contract?.items ?? [];
+  const item = items.find((it) => it.item_id === itemId) ?? null;
+  const planId = item?.plan_id ?? item?.plan_id_derived ?? null;
+  const planOpt = plans.find((p) => p.plan_id === planId) ?? null;
+
+  const annual = planOpt?.annual_price_cents ?? item?.annual_price_cents ?? null;
+  const settle = (planOpt as (SubscriptionPlanOption & { monthly_settle_cents?: number | null }) | null)?.monthly_settle_cents ?? null;
+  const endPreview = termEnd(startDate, term);
+  const derived = item?.plan_id_derived !== null && item?.plan_id_derived !== undefined;
+
+  const submit = async () => {
+    setErr(null);
+    if (mode === "edit") {
+      if (original?.editable === false) {
+        setErr(new Error(original.reason ?? "本订阅不可编辑"));
+        return;
+      }
+      setBusy(true);
+      try {
+        await subscriptionUpdate({
+          subscription_id: original?.subscription_id ?? "",
+          trial_months: trialMonths === "" ? undefined : Number(trialMonths),
+          discount_monthly_cents: discount === "" ? undefined : Math.round(Number(discount) * 100),
+          row_version: original?.row_version ? Number(original.row_version) : undefined,
+        });
+        onDone();
+        onClose();
+      } catch (e) {
+        if (isConflict(e)) {
+          onDone();
+          onClose();
+          return;
+        }
+        setErr(e);
+      } finally {
+        setBusy(false);
+      }
+      return;
+    }
+
+    if (!contractId || !itemId || !planId) {
+      setErr(new Error("请选择关联合同与合同条目(套餐由条目带出)"));
+      return;
+    }
+    if (!startDate) {
+      setErr(new Error("请选择开始日"));
+      return;
+    }
+    setBusy(true);
+    try {
+      if (mode === "create") {
+        await subscriptionCreate({
+          customer_id: customerId,
+          plan_id: planId,
+          contract_id: contractId,
+          contract_item_id: itemId,
+          term,
+          start_date: startDate,
+          trial_months: trialMonths === "" ? undefined : Number(trialMonths),
+          remark: remark || undefined,
+        });
+      } else {
+        await subscriptionChange({
+          replaces_subscription_id: original?.subscription_id ?? "",
+          customer_id: customerId,
+          plan_id: planId,
+          contract_id: contractId,
+          contract_item_id: itemId,
+          start_date: startDate,
+          term,
+          trial_months: trialMonths === "" ? undefined : Number(trialMonths),
+          remark: remark || undefined,
+        });
+      }
+      onDone();
+      onClose();
+    } catch (e) {
+      if (isConflict(e)) {
+        // M225 时间重叠/M226 条目已建订阅:⛔ 改判据重交,关弹窗刷新后按列表实况重选。
+        onDone();
+        onClose();
+        return;
+      }
+      setErr(e);
+    } finally {
+      setBusy(false);
+    }
+  };
+
+  const title = mode === "create" ? "新增订阅" : mode === "change" ? "升降配" : "编辑订阅";
+
+  return (
+    <Modal title={title} onClose={onClose} wide>
+      {loading ? <Loading /> : null}
+      {loadErr ? <ErrorBox error={loadErr} /> : null}
+
+      {mode === "change" ? (
+        <>
+          <Notice>{UPGRADE_CUTOFF_RULE}</Notice>
+          <table className="sub">
+            <thead>
+              <tr>
+                <th>对照项</th>
+                <th>原值</th>
+                <th>新值</th>
+              </tr>
+            </thead>
+            <tbody>
+              <tr>
+                <td>套餐</td>
+                <td>{original?.plan_name ?? "—"}</td>
+                <td>{planOpt?.plan_name ?? item?.plan_name ?? "待选择"}</td>
+              </tr>
+              <tr>
+                <td>规格</td>
+                <td>{original?.term ? label(TERM, original.term) : "—"}</td>
+                <td>{label(TERM, term) || "—"}</td>
+              </tr>
+              <tr>
+                <td>年订阅价格</td>
+                <td>{original?.annual_price_cents === null || original?.annual_price_cents === undefined ? "—" : money(original.annual_price_cents)}</td>
+                <td>{annual === null ? "—" : money(annual)}</td>
+              </tr>
+              <tr>
+                <td>起止</td>
+                <td>
+                  {day(original?.start_date ?? null)} ~ {day(original?.end_date ?? null)}
+                </td>
+                <td>
+                  {day(startDate)} ~ {endPreview ? day(endPreview) : "—"}
+                </td>
+              </tr>
+              <tr>
+                <td>线路出口</td>
+                <td>{(original?.line_exits ?? []).join("、") || "—"}</td>
+                <td>{(item?.line_exits ?? []).join("、") || "待选择"}</td>
+              </tr>
+            </tbody>
+          </table>
+        </>
+      ) : null}
+
+      <div className="form-grid">
+        <Field label="归属客户">
+          <Ro>{customerName ?? customerId}</Ro>
+        </Field>
+
+        {mode === "edit" ? (
+          <>
+            <Field label="订阅编号">
+              <Ro>{original?.subscription_id ?? "—"}</Ro>
+            </Field>
+            <Field label="套餐">
+              <Ro>{original?.plan_name ?? "—"}</Ro>
+            </Field>
+            <Field label="年订阅价格">
+              <Ro title={SUB_AMOUNT_TITLE}>
+                {original?.annual_price_cents === null || original?.annual_price_cents === undefined ? "—" : money(original.annual_price_cents)}
+              </Ro>
+            </Field>
+            <Field label="试用月数" error={trialMonths !== "" && Number(trialMonths) < 0 ? "不能为负数" : undefined}>
+              <input type="number" min={0} value={trialMonths} onChange={(e) => setTrialMonths(e.target.value)} />
+            </Field>
+            <Field label="月折让金额(只影响月结算标准金额)">
+              <input type="number" min={0} step="0.01" value={discount} onChange={(e) => setDiscount(e.target.value)} />
+            </Field>
+            <Field label="结束日">
+              <Ro title={SUB_END_DATE_READONLY}>{day(original?.end_date ?? null)}</Ro>
+            </Field>
+            <Field label="实际开通日">
+              <Ro title="本册不提供写入入口">
+                {original?.actual_opened_at ? datetime(original.actual_opened_at) : "—"}
+              </Ro>
+            </Field>
+          </>
+        ) : (
+          <>
+            <Field label="关联合同(该客户未建订阅的合同)">
+              <select
+                value={contractId}
+                onChange={(e) => {
+                  setContractId(e.target.value);
+                  setItemId("");
+                }}
+              >
+                <option value="">请选择</option>
+                {contracts.map((c) => (
+                  <option key={c.contract_id} value={c.contract_id}>
+                    {c.contract_no}
+                  </option>
+                ))}
+              </select>
+            </Field>
+            <Field label="合同条目(选定条目才决定出口)" error={!contractId && items.length === 0 ? "先选择合同" : undefined}>
+              <select value={itemId} onChange={(e) => setItemId(e.target.value)} disabled={!contract}>
+                <option value="">请选择</option>
+                {items.map((it) => (
+                  <option key={it.item_id} value={it.item_id}>
+                    {it.item_kind === "custom_spec" ? "不指定固定套餐" : it.plan_name ?? it.plan_id}
+                    {`(${it.quantity ?? "—"} 份 · ${(it.line_exits ?? []).join("、") || "未配置出口"})`}
+                  </option>
+                ))}
+              </select>
+            </Field>
+            <Field label="套餐(由条目带出)">
+              <Ro>
+                {planId ? `${planOpt?.plan_name ?? item?.plan_name ?? planId}` : "待选择"}
+                {derived ? " · 合同条目派生" : ""}
+              </Ro>
+            </Field>
+            <Field label="订阅时长">
+              <select value={term} onChange={(e) => setTerm(e.target.value)}>
+                {OPTIONS.term.map((o) => (
+                  <option key={o.value} value={o.value}>
+                    {o.label}
+                  </option>
+                ))}
+              </select>
+            </Field>
+            <Field label="开始日">
+              <input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
+            </Field>
+            <Field label="试用月数(选填)">
+              <input type="number" min={0} value={trialMonths} onChange={(e) => setTrialMonths(e.target.value)} />
+            </Field>
+            <Field label="备注(选填)">
+              <input value={remark ?? ""} onChange={(e) => setRemark(e.target.value)} />
+            </Field>
+          </>
+        )}
+      </div>
+
+      {mode !== "edit" ? (
+        <div className="form-grid" style={{ marginTop: 10 }}>
+          <Field label={SUB_CREATE_READONLY_FIELDS[0]}>
+            <Ro>{(item?.line_exits ?? []).join("、") || "待选择"}</Ro>
+          </Field>
+          <Field label={SUB_CREATE_READONLY_FIELDS[1]}>
+            <Ro title={SUB_MODE_BY_CATEGORY}>
+              {item?.use_category ? SUB_MODE_BY_CATEGORY : "待选择"}
+            </Ro>
+          </Field>
+          <Field label={SUB_CREATE_READONLY_FIELDS[2]}>
+            <Ro>计费写入</Ro>
+          </Field>
+          <Field label={SUB_CREATE_READONLY_FIELDS[3]}>
+            <Ro title="时长切换时就地重算,不随表单提交">{endPreview || "待选择"}</Ro>
+          </Field>
+          <Field label={SUB_CREATE_READONLY_FIELDS[4]}>
+            <Ro title={SUB_AMOUNT_TITLE}>{annual === null ? "待选择" : money(annual)}</Ro>
+          </Field>
+          <Field label={SUB_CREATE_READONLY_FIELDS[5]}>
+            <Ro title={SUB_AMOUNT_TITLE}>{settle === null ? "由套餐带出" : money(settle)}</Ro>
+          </Field>
+          <Field label="实际开通日">
+            <Ro title="唯一写入方=工单回填,本册不提供入口">—</Ro>
+          </Field>
+        </div>
+      ) : null}
+
+      {mode !== "edit" ? <p className="note">{SUB_CREATE_READONLY_NOTE}</p> : null}
+
+      {err ? <ErrorBox error={err} /> : null}
+
+      <div className="form-actions">
+        <Btn onClick={submit} disabled={busy || (mode !== "edit" && loading)}>
+          {busy ? "提交中…" : mode === "change" ? "确认升降配" : mode === "edit" ? "保存" : "确认新增"}
+        </Btn>
+        <Btn ghost onClick={onClose}>
+          取消
+        </Btn>
+      </div>
+    </Modal>
+  );
+}
+
+/**
+ * 删除订阅确认弹窗:打开即调 `subscription/delete_check`,命中账单明细或变更链时
+ * 在确认按钮之前原文列出命中项并关闭入口;`billing_state="error"` 渲染「取数失败」同样不解锁。
+ */
+export function SubscriptionDeleteDialog({
+  sub,
+  onClose,
+  onDeleted,
+}: {
+  sub: SubscriptionRow;
+  onClose: () => void;
+  onDeleted: () => void;
+}) {
+  const [check, setCheck] = useState<SubscriptionDeleteCheckResult | null>(null);
+  const [checkErr, setCheckErr] = useState<unknown>(null);
+  const [busy, setBusy] = useState(false);
+  const [err, setErr] = useState<unknown>(null);
+
+  useEffect(() => {
+    let alive = true;
+    subscriptionDeleteCheck({ subscription_id: sub.subscription_id })
+      .then((r) => alive && setCheck(r))
+      .catch((e) => alive && setCheckErr(e));
+    return () => {
+      alive = false;
+    };
+  }, [sub.subscription_id]);
+
+  const fetchFail = check?.billing_state === "error" || !!checkErr;
+  const blocked = !check || !check.deletable || fetchFail;
+  const hits = check?.blocks;
+
+  const doDelete = async () => {
+    setErr(null);
+    setBusy(true);
+    try {
+      await subscriptionDelete({ subscription_id: sub.subscription_id, snapshot_version: check?.snapshot_version ?? undefined });
+      onDeleted();
+      onClose();
+    } catch (e) {
+      setErr(e);
+    } finally {
+      setBusy(false);
+    }
+  };
+
+  return (
+    <Modal title={`删除订阅 ${sub.subscription_id}`} onClose={onClose}>
+      <Notice>
+        <Pill text={label(TERM, sub.term) || sub.term} /> {sub.plan_name ?? "—"} | {day(sub.start_date)} ~ {day(sub.end_date)}
+      </Notice>
+      <p className="note">{SUB_DELETE_PLAN_LOCK_NOTE}</p>
+
+      {fetchFail ? (
+        <div className="alert">
+          {checkErr ? <ErrorBox error={checkErr} /> : null}
+          {checkErr ? null : <span>{WORD_FETCH_FAILED}——账单明细计数取数失败,确认按钮不解锁。</span>}
+        </div>
+      ) : !check ? (
+        <Loading />
+      ) : blocked ? (
+        <div className="alert">
+          {hits?.billing_details?.length ? <div>命中账单明细:{hits.billing_details.map(String).join("、")}</div> : null}
+          {hits?.change_chain?.length ? <div>变更链:{hits.change_chain.map(String).join("、")}</div> : null}
+          {!hits?.billing_details?.length && !hits?.change_chain?.length ? <div>服务端判定不可删除</div> : null}
+          <div style={{ marginTop: 6 }}>
+            有账单明细的记录⛔ 删除;请改为发起服务停用。 <Link to={`/subs/${sub.subscription_id}`}>前往订阅详情发起停用</Link>
+          </div>
+        </div>
+      ) : (
+        <p className="note">服务端校验通过(无账单明细、无变更链引用),可确认删除。</p>
+      )}
+
+      {err ? (
+        <ErrorBox error={err} />
+      ) : null}
+      {hasBizCode(err, "M227") ? (
+        <Notice>
+          已出账的生效订阅⛔ 删除,改走服务停用:请在订阅详情页发起(服务端原文见上)。
+        </Notice>
+      ) : null}
+
+      <div className="form-actions">
+        <Btn danger onClick={doDelete} disabled={blocked || busy}>
+          {busy ? "提交中…" : "确认删除"}
+        </Btn>
+        <Btn ghost onClick={onClose}>
+          取消
+        </Btn>
+      </div>
+    </Modal>
+  );
+}

+ 136 - 0
front-end/src/pages/SubscriptionsPage.tsx

@@ -0,0 +1,136 @@
+/**
+ * 全部订阅(路由 `subs`)—— 页面契约 14.1.3/14.6。
+ *
+ * **只读视图**:行操作只有「详情」,⛔ 渲染「新增」「编辑」「升降配」「删除」任何一项,
+ * 办理一律由文案指向客户管理的套餐订阅管理页(`SUBS_READONLY_ENTRY`)。
+ * 状态列只读+列头注「状态按日终刷新」;⛔ 状态列按钮、⛔ 批量状态操作、⛔ 导出、⛔ 跨客户关键词。
+ */
+import { useState } from "react";
+import { Link } from "react-router-dom";
+import { rowsOf, subscriptionListAll } from "../api/bos";
+import { hasBizCode } from "../api/http";
+import { label, OPTIONS, SUB_STATUS, TERM } from "../api/labels";
+import { SUB_STATUS_DAILY_NOTE, SUBS_READONLY_ENTRY } from "../api/lockedCopy";
+import { Async, Btn, ErrorBox, Field, Notice, Pager, Panel, Pill, day, seq } from "../components/ui";
+import { Shell } from "../layout/Shell";
+import { useLoad } from "../hooks/useLoad";
+
+export default function SubscriptionsPage() {
+  const [f, setF] = useState({ status: "", use_category: "", term: "", keyword: "", page: 1, page_size: 20 });
+  const list = useLoad(
+    () =>
+      subscriptionListAll({
+        status: f.status || undefined,
+        use_category: f.use_category || undefined,
+        term: f.term || undefined,
+        keyword: f.keyword || undefined,
+        page: f.page - 1,
+        page_size: f.page_size,
+      }),
+    [f.status, f.use_category, f.term, f.keyword, f.page, f.page_size],
+  );
+
+  const rows = rowsOf(list.data);
+  /** `L214`:关键词跨客户 ⇒ 服务端拒绝,原文透出并提示改用客户维度筛选。 */
+  const crossCustomer = hasBizCode(list.error, "L214");
+
+  return (
+    <Shell route="subs" title="全部订阅" hint="本页是只读视图;所有办理入口在客户管理的套餐订阅管理页。">
+      <Panel title="全部订阅" note={SUBS_READONLY_ENTRY}>
+        <div className="filters">
+          <Field label="状态">
+            <select value={f.status} onChange={(e) => setF({ ...f, status: e.target.value, page: 1 })}>
+              <option value="">全部</option>
+              {OPTIONS.sub_status.map((o) => (
+                <option key={o.value} value={o.value}>
+                  {o.label}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="用途分类">
+            <select value={f.use_category} onChange={(e) => setF({ ...f, use_category: e.target.value, page: 1 })}>
+              <option value="">全部</option>
+              {OPTIONS.use_category.map((o) => (
+                <option key={o.value} value={o.value}>
+                  {o.label}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="订阅规格">
+            <select value={f.term} onChange={(e) => setF({ ...f, term: e.target.value, page: 1 })}>
+              <option value="">全部</option>
+              {OPTIONS.term.map((o) => (
+                <option key={o.value} value={o.value}>
+                  {o.label}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="关键词(仅套餐名称与编码)" error={crossCustomer ? "已限定在本账号可见客户范围内,请改用客户维度进入" : undefined}>
+            <input value={f.keyword} onChange={(e) => setF({ ...f, keyword: e.target.value, page: 1 })} placeholder="套餐名称/编码" />
+          </Field>
+          <div className="row" style={{ alignItems: "flex-end" }}>
+            <Btn ghost onClick={list.reload}>
+              查询
+            </Btn>
+          </div>
+        </div>
+
+        {list.error && !crossCustomer ? <ErrorBox error={list.error} /> : null}
+        {crossCustomer ? <Notice>关键词命中本账号可见范围之外的客户已被服务端拒绝(原文见下方),请从客户管理进入该客户的订阅页。</Notice> : null}
+
+        <Async loading={list.loading && rows.length === 0} error={null} isEmpty={rows.length === 0} emptyText="没有符合条件的订阅">
+          <table>
+            <thead>
+              <tr>
+                <th>序号</th>
+                <th>订阅编号</th>
+                <th>客户</th>
+                <th>合同编号</th>
+                <th>套餐</th>
+                <th>规格</th>
+                <th>
+                  状态
+                  <span className="th-note">{SUB_STATUS_DAILY_NOTE}</span>
+                </th>
+                <th>开始日</th>
+                <th>结束日</th>
+                <th>额度</th>
+                <th>操作</th>
+              </tr>
+            </thead>
+            <tbody>
+              {rows.map((r, i) => (
+                <tr key={r.subscription_id}>
+                  <td>{seq(1, 20, i)}</td>
+                  <td>{r.subscription_id}</td>
+                  <td>
+                    <Link to={`/customers/${r.customer_id}`}>{r.customer_name ?? r.customer_id}</Link>
+                  </td>
+                  <td>
+                    {r.contract_no ? <Link to={`/contracts/${r.contract_id}`}>{r.contract_no}</Link> : r.contract_id}
+                    <div className="note">订单号 {r.order_no || "—"}</div>
+                  </td>
+                  <td>{r.plan_name ?? "—"}</td>
+                  <td>{label(TERM, r.term) || "—"}</td>
+                  <td>
+                    <Pill text={label(SUB_STATUS, r.status)} />
+                  </td>
+                  <td>{day(r.start_date)}</td>
+                  <td>{day(r.end_date)}</td>
+                  <td>计入额度 {r.quota_slots}</td>
+                  <td>
+                    <Link to={`/subs/${r.subscription_id}`}>详情</Link>
+                  </td>
+                </tr>
+              ))}
+            </tbody>
+          </table>
+          <Pager page={f.page} page_size={f.page_size} total={list.data?.total ?? rows.length} onChange={(p) => setF({ ...f, page: p })} />
+        </Async>
+      </Panel>
+    </Shell>
+  );
+}

+ 57 - 0
front-end/src/styles/app.css

@@ -84,3 +84,60 @@ table td.num {
   color: var(--ink);
   margin-bottom: 8px;
 }
+
+/* ── 第3册(套餐目录/合同/订阅)补的四个结构类,配色沿用 :root ── */
+
+/* 悬停浮层:套餐月成本构成(plan_cost_item/get_list 悬停发起) */
+.qtip {
+  position: absolute;
+  left: 0;
+  top: 100%;
+  z-index: 60;
+  margin-top: 4px;
+  padding: 6px 9px;
+  border: 1px solid var(--line);
+  border-radius: 6px;
+  background: #fff;
+  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.14);
+  font-size: 12px;
+  line-height: 1.7;
+  color: var(--ink);
+}
+
+/* 弹窗内的嵌套子表(随附成本项、服务构成条目) */
+table.sub {
+  margin: 0;
+  font-size: 12.5px;
+}
+table.sub th,
+table.sub td {
+  padding: 5px 6px;
+}
+table.sub input,
+table.sub select {
+  min-width: 88px;
+  padding: 4px 6px;
+}
+
+/* 只读灰显项(新增订阅六项+实际开通日):⛔ 置灰输入框,只读渲染 */
+.ro {
+  display: block;
+  padding: 7px 9px;
+  border: 1px dashed var(--line);
+  border-radius: 6px;
+  background: #f4f1ea;
+  color: var(--muted);
+  font-size: 13px;
+  line-height: 1.5;
+  word-break: break-all;
+}
+
+/* 列头注(状态列「状态按日终刷新」等) */
+.th-note {
+  display: block;
+  margin-top: 2px;
+  font-weight: 400;
+  font-size: 11.5px;
+  line-height: 1.4;
+  opacity: 0.78;
+}