PackageManagementPage.tsx 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. import { FilterSelect } from "../components/ui/filter-select";
  2. import { PageIntro } from "../components/PageIntro";
  3. import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, Fragment, type ReactNode } from "react";
  4. import { createPortal } from "react-dom";
  5. import { ArrowLeft, CircleHelp, Globe2, Layers3, LockKeyhole, PencilLine, Plus, Search, SlidersHorizontal, Trash2, X } from "lucide-react";
  6. import { Link, useLocation } from "react-router";
  7. import { detailBack } from "../lib/detail-navigation";
  8. import { Button } from "../components/ui/button";
  9. import { Input } from "../components/ui/input";
  10. import { TableValueText, Tri } from "../components/triState";
  11. import { NOTICE_DISMISS_MS, OpsTag, OpsTableColumns, OpsTableEmpty } from "../components/OperationsKit";
  12. import { ListPager } from "../components/ListPager";
  13. import { RecordTabs } from "../components/RecordTabs";
  14. import { COST_BY_COMBINATION, OPERATOR_ONLY_CONFIG, WORD_FETCH_FAILED, WORD_NOT_PROVIDED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
  15. import { catalogDelete, ipBandwidthTierSave, lineExitSave } from "../lib/api/bos";
  16. import type { CatalogPlanRow, IpBandwidthTierListResult, LineExitListResult } from "../lib/api/types";
  17. import { ApiError } from "../lib/api/http";
  18. import { useDemoIdentity } from "../lib/demo-session";
  19. import { familyLabel, planFamilies, useCatalogLedger, useIpBandwidthTiers, useLineExits } from "../lib/package-catalog";
  20. import { exitKey, IP_TIER_UNCOMMITTED, splitExitInput } from "../domain/contract-items";
  21. import type { Load } from "../lib/useLoad";
  22. import { LIST_PAGE_SIZE, useLocalPage } from "../lib/list-paging";
  23. import { isImeComposing } from "../lib/ime";
  24. import { PackagePlanEditor, type EditorState } from "../components/PackagePlanEditor";
  25. import "../styles/operations.css";
  26. import "../styles/packages.css";
  27. /** 目录三视图:固定套餐与自定义套餐各一张台账,线路出口是目录级清单。 */
  28. type CatalogTab = "fixed" | "custom" | "exits";
  29. /** 计数列显示数量和单位,保留缺失与取数失败的提示。 */
  30. function intCell(value: number | null | undefined, unit: "个" | "份") {
  31. if (value === undefined) return <Tri tone="fail" text={WORD_FETCH_FAILED} />;
  32. if (value === null) return <Tri tone="missing" text={WORD_UNCONFIGURED} />;
  33. return <><span className="table-number catalog-number-emphasis">{value}</span><span className="catalog-value-unit"><span className="catalog-value-separator">/</span>{unit}</span></>;
  34. }
  35. /** 价格按年或按月标明单位,成本金额沿用千分位和两位小数。 */
  36. const LEDGER_MONEY = new Intl.NumberFormat("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  37. function ledgerMoney(cents: number | null | undefined, period?: "年" | "月") {
  38. if (cents === undefined) return <Tri tone="fail" text={WORD_FETCH_FAILED} />;
  39. if (cents === null) return <Tri tone="missing" text={WORD_UNCONFIGURED} />;
  40. const amount = LEDGER_MONEY.format(cents / 100);
  41. if (!period) return <span className="table-number">{amount}</span>;
  42. const annual = period === "年";
  43. return (
  44. <span className={annual ? "catalog-price catalog-price-annual" : "catalog-price"} title={`¥${amount}/${period}`}>
  45. <span className="catalog-price-currency">¥</span>
  46. <span className={annual ? "table-annual-price" : "table-number"}>{amount}</span>
  47. <span className="catalog-value-unit"><span className="catalog-value-separator">/</span>{period}</span>
  48. </span>
  49. );
  50. }
  51. /** 总带宽列:addon 恒「—」(D-18);未承诺或未填上下行=「不承诺带宽」(⛔ 冒充取数失败);有值再并显/分显。 */
  52. function ledgerBandwidth(plan: CatalogPlanRow) {
  53. if (plan.plan_family === "addon") return <>{"—"}</>;
  54. if (!plan.bandwidth_committed) return <>不承诺带宽</>;
  55. const up = plan.bandwidth_up_mbps;
  56. const down = plan.bandwidth_down_mbps;
  57. /** 存量 DEFAULT TRUE + 上下行空:语义=未配置带宽=不承诺,⛔ 红字「取数失败」。 */
  58. if (up === null || up === undefined || down === null || down === undefined) return <>不承诺带宽</>;
  59. return <>
  60. {up === down ? "上下行 " : "下行 "}<span className="table-number catalog-number-emphasis">{down}</span>M
  61. {up !== down && <><span className="catalog-value-separator">/</span>上行 <span className="table-number catalog-number-emphasis">{up}</span>M</>}
  62. </>;
  63. }
  64. /** 月成本四态(R-1):ok=金额;unconfigured=未配置;by_combination/缺省=按组合;failed/error=取数失败。 */
  65. function ledgerCostCell(plan: CatalogPlanRow) {
  66. const state = plan.plan_cost_state;
  67. if (state === "failed" || state === "error") {
  68. return <Tri tone="fail" text={WORD_FETCH_FAILED} title={plan.plan_cost_note || undefined} />;
  69. }
  70. if (state === "ok") return ledgerMoney(plan.plan_cost_cents);
  71. if (state === "unconfigured") return <Tri tone="missing" text={WORD_UNCONFIGURED} />;
  72. return <Tri tone="val" text={COST_BY_COMBINATION} title="金额随各客户的「省份 × 运营商」组合不同,不折中成一个数" />;
  73. }
  74. /**
  75. * 套餐说明:挂在名称右侧的问号图标上,不占一列。图标随行悬停/键盘聚焦显形,点击展开浮层显示说明。
  76. * 浮层走 body 传送门+fixed,避免被台账滚动容器裁掉;**落在图标的左/右侧而非正下方**,
  77. * 让指针停在图标上时不会压住浮层正文(正下方时箭头正对浮层首行)。
  78. */
  79. function PlanDescNote({ name, desc }: { name: string; desc: string }) {
  80. const id = useId();
  81. const trigger = useRef<HTMLButtonElement>(null);
  82. const popup = useRef<HTMLDivElement>(null);
  83. const [open, setOpen] = useState(false);
  84. const [position, setPosition] = useState({ top: 0, left: 0 });
  85. useLayoutEffect(() => {
  86. if (!open || !trigger.current || !popup.current) return;
  87. const anchor = trigger.current.getBoundingClientRect();
  88. const box = popup.current.getBoundingClientRect();
  89. const gap = 10;
  90. const clampTop = (top: number) => Math.max(8, Math.min(top, window.innerHeight - box.height - 8));
  91. const rightRoom = window.innerWidth - anchor.right - gap - 8;
  92. const leftRoom = anchor.left - gap - 8;
  93. /** 优先右邻(与图标垂直居中对齐),右边放不下再翻到左边;两侧都放不下才落到下方,留 18px 让指针箭头够不到正文。 */
  94. if (rightRoom >= box.width) {
  95. setPosition({ left: anchor.right + gap, top: clampTop(anchor.top + anchor.height / 2 - box.height / 2) });
  96. } else if (leftRoom >= box.width) {
  97. setPosition({ left: anchor.left - gap - box.width, top: clampTop(anchor.top + anchor.height / 2 - box.height / 2) });
  98. } else {
  99. setPosition({
  100. left: Math.max(8, Math.min(anchor.left + anchor.width / 2, window.innerWidth - box.width - 8)),
  101. top: clampTop(anchor.bottom + 18),
  102. });
  103. }
  104. }, [open]);
  105. useEffect(() => {
  106. if (!open) return;
  107. const close = () => setOpen(false);
  108. /** 点到图标与浮层以外即收(滚动/缩放同样收,浮层不跟着错位)。 */
  109. const outside = (event: PointerEvent) => {
  110. if (!trigger.current?.contains(event.target as Node) && !popup.current?.contains(event.target as Node)) close();
  111. };
  112. const escape = (event: KeyboardEvent) => { if (event.key === "Escape") close(); };
  113. document.addEventListener("pointerdown", outside);
  114. document.addEventListener("keydown", escape);
  115. window.addEventListener("scroll", close, true);
  116. window.addEventListener("resize", close);
  117. return () => {
  118. document.removeEventListener("pointerdown", outside);
  119. document.removeEventListener("keydown", escape);
  120. window.removeEventListener("scroll", close, true);
  121. window.removeEventListener("resize", close);
  122. };
  123. }, [open]);
  124. return <>
  125. <button ref={trigger} type="button" className="catalog-desc-trigger" aria-label={`查看「${name}」的套餐说明`} aria-expanded={open} aria-describedby={open ? id : undefined} title="查看套餐说明" onClick={() => setOpen((current) => !current)}><CircleHelp size={15} aria-hidden="true" /></button>
  126. {open && createPortal(<div ref={popup} id={id} role="dialog" aria-label={`${name} · 套餐说明`} className="catalog-desc-popover" style={position}>
  127. <strong>套餐说明</strong>
  128. <p>{desc}</p>
  129. </div>, document.body)}
  130. </>;
  131. }
  132. /** 台账列宽:序号/操作列固定,其余按阅读需求分配(同合同台账口径)。
  133. * 套餐说明已收进名称旁问号图标,不再单列;用途分类改由表体内分组行承载,两 Tab 同列(2026-11-15)。 */
  134. const PLAN_ACTIONS_WIDTH = 164;
  135. const PLAN_COLUMNS = [58, 246, 132, 124, 96, 86, 150, 78, PLAN_ACTIONS_WIDTH] as const;
  136. /** 自定义档台账多两列:建档人/建档团队(固定档不加)。 */
  137. const CUSTOM_PLAN_COLUMNS = [...PLAN_COLUMNS.slice(0, -1), 106, 112, PLAN_ACTIONS_WIDTH] as const;
  138. /** 小屏将同一行的数据排成卡片,使用独立的可见字段名。 */
  139. function CatalogField({ label, children, title }: {
  140. label: string; children: ReactNode; title?: string;
  141. }) {
  142. return (
  143. <td role="cell" title={title}>
  144. <span className="catalog-field-label" aria-hidden="true">{label}</span>
  145. {children}
  146. </td>
  147. );
  148. }
  149. function PlanRow({ plan, index, custom, writable, readOnlyNote, onEdit, onDelete }: {
  150. plan: CatalogPlanRow; index: number; custom?: boolean; writable: boolean; readOnlyNote: string; onEdit: () => void; onDelete: () => void;
  151. }) {
  152. return <tr className="catalog-plan-row" role="row">
  153. <td role="cell" className="catalog-sequence table-number">{index}</td>
  154. <td role="cell" className="catalog-identity">
  155. <span className="catalog-plan-name">
  156. <strong className="table-cell-title" title={plan.plan_name || undefined}>{plan.plan_name || <Tri tone="missing" text={WORD_UNCONFIGURED} />}</strong>
  157. {plan.plan_desc && <PlanDescNote name={plan.plan_name || plan.plan_id} desc={plan.plan_desc} />}
  158. {plan.plan_family && <OpsTag tone="brand">{familyLabel(plan.plan_family)}</OpsTag>}
  159. </span>
  160. {custom && <small className="catalog-plan-owner" title={plan.customer_name ?? undefined}>归属客户 · <TableValueText>{plan.customer_name || WORD_UNCONFIGURED}</TableValueText></small>}
  161. </td>
  162. <CatalogField label="年订阅价格">{ledgerMoney(plan.annual_price_cents, "年")}</CatalogField>
  163. <CatalogField label="月结算标准">{ledgerMoney(plan.monthly_settle_cents, "月")}</CatalogField>
  164. <CatalogField label="月成本">{ledgerCostCell(plan)}</CatalogField>
  165. <CatalogField label="分账号额度">{intCell(plan.sub_account_quota, "个")}</CatalogField>
  166. <CatalogField label="总带宽">{ledgerBandwidth(plan)}</CatalogField>
  167. <CatalogField label="订阅量" title="被合同条目或订阅引用的数量">{intCell(plan.referred_count, "份")}</CatalogField>
  168. {custom && <>
  169. <CatalogField label="建档人" title={plan.created_by ?? undefined}>{plan.created_by_name || <Tri tone="missing" text={WORD_UNCONFIGURED} />}</CatalogField>
  170. <CatalogField label="建档团队" title={plan.created_team_id ?? undefined}>{plan.created_team_name || <Tri tone="missing" text={WORD_UNCONFIGURED} />}</CatalogField>
  171. </>}
  172. <td role="cell" className="catalog-actions-cell">
  173. {writable ? (
  174. <div className="ops-inline-actions catalog-row-actions">
  175. <button type="button" aria-label="编辑套餐" onClick={onEdit}><PencilLine size={15} aria-hidden="true" />编辑</button>
  176. <button type="button" className="is-danger" aria-label="删除套餐" onClick={onDelete} title="删除套餐(引用拦截由服务端判定)"><Trash2 size={15} aria-hidden="true" />删除</button>
  177. </div>
  178. ) : <span className="catalog-readonly-note" title={readOnlyNote}>只读</span>}
  179. </td>
  180. </tr>;
  181. }
  182. function PlanGroupRow({ title, hint, colSpan }: { title: string; hint: string; colSpan: number }) {
  183. return <tr className="catalog-group-row" role="row">
  184. <td role="cell" colSpan={colSpan}>
  185. <div className="catalog-group-label"><strong><TableValueText>{title}</TableValueText></strong><span>{hint}</span></div>
  186. </td>
  187. </tr>;
  188. }
  189. function orderModeOf(family: string) {
  190. return family === "addon" ? "可叠加" : "可升降配";
  191. }
  192. /** 配置级线路出口。 */
  193. const CATALOG_EXIT_MAX = 200;
  194. type ExitDraftRow = { exit_name: string; price_factor: string };
  195. function LineExitPanel({ writable, exits, onNotice }: { writable: boolean; exits: Load<LineExitListResult>; onNotice: (message: string) => void }) {
  196. const [draft, setDraft] = useState<ExitDraftRow[] | null>(null);
  197. const [input, setInput] = useState("");
  198. const [error, setError] = useState("");
  199. const [saving, setSaving] = useState(false);
  200. /** 删除二次确认:必须手打出口原文才放行(2026-11-15 业主口径:有引用的不许删、没引用的也要二次输入确认)。 */
  201. const [confirm, setConfirm] = useState<{ index: number; name: string; typed: string } | null>(null);
  202. useEffect(() => {
  203. if (draft === null && exits.data) {
  204. setDraft(exits.data.items.map((item) => ({
  205. exit_name: item.exit_name,
  206. price_factor: String(item.price_factor ?? 1),
  207. })));
  208. }
  209. }, [exits.data, draft]);
  210. const savedItems = exits.data?.items ?? [];
  211. const saved: ExitDraftRow[] = savedItems.map((item) => ({
  212. exit_name: item.exit_name,
  213. price_factor: String(item.price_factor ?? 1),
  214. }));
  215. const rows = draft ?? saved;
  216. /** 引用面按归一化键查(后端逐条带出 `ref_count`/`ref_summary`)。 */
  217. const refOf = (name: string) => savedItems.find((item) => item.exit_key === exitKey(name));
  218. const dirty = draft !== null && (
  219. draft.length !== saved.length
  220. || rows.some((row, index) => row.exit_name !== saved[index]?.exit_name || row.price_factor !== saved[index]?.price_factor)
  221. );
  222. function add() {
  223. if (!writable) return;
  224. const incoming = splitExitInput(input);
  225. if (!incoming.length) { setError("请先输入线路出口(国家/地区名称原文)。"); return; }
  226. const seen = new Set(rows.map((row) => exitKey(row.exit_name)));
  227. const next = [...rows];
  228. let duplicated = 0;
  229. let overflow = 0;
  230. for (const raw of incoming) {
  231. if (next.length >= CATALOG_EXIT_MAX) { overflow += 1; continue; }
  232. const key = exitKey(raw);
  233. if (seen.has(key)) { duplicated += 1; continue; }
  234. seen.add(key);
  235. next.push({ exit_name: raw.trim(), price_factor: "1" });
  236. }
  237. setDraft(next);
  238. setInput("");
  239. setError(overflow ? `线路出口最多 ${CATALOG_EXIT_MAX} 条,已忽略 ${overflow} 条。` : duplicated ? `已跳过 ${duplicated} 条重复出口(空白、大小写不区分)。` : "");
  240. }
  241. function askRemove(index: number) {
  242. if (!writable) return;
  243. const name = rows[index]?.exit_name;
  244. if (!name) return;
  245. /** 有引用的出口连确认框都不给:⛔ 让人打完字再吃 400(服务端仍是最终判据)。 */
  246. if ((refOf(name)?.ref_count ?? 0) > 0) {
  247. setError(`「${name}」仍被 ${refOf(name)?.ref_summary || "业务数据"}引用,不能从清单删除;请先到合同/订阅侧处理引用。`);
  248. return;
  249. }
  250. setError("");
  251. setConfirm({ index, name, typed: "" });
  252. }
  253. function confirmRemove() {
  254. if (!confirm) return;
  255. if (confirm.typed.trim() !== confirm.name.trim()) return;
  256. setDraft((current) => (current ?? saved).filter((_, i) => i !== confirm.index));
  257. setConfirm(null);
  258. setError("");
  259. }
  260. function setFactor(index: number, value: string) {
  261. if (!writable) return;
  262. setDraft((current) => (current ?? saved).map((row, i) => (i === index ? { ...row, price_factor: value } : row)));
  263. setError("");
  264. }
  265. /** 计费系数门禁:`(0, 1]`,最多两位小数(与后端 `require_price_factor_scaled` 同源)。 */
  266. function parseFactor(raw: string): number | null {
  267. const text = raw.trim();
  268. if (!text) return null;
  269. if (!/^\d+(?:\.\d{1,2})?$/.test(text)) return null;
  270. const value = Number(text);
  271. if (!Number.isFinite(value) || value <= 0 || value > 1) return null;
  272. return value;
  273. }
  274. async function save() {
  275. if (!writable || saving) return;
  276. for (const [index, row] of rows.entries()) {
  277. if (parseFactor(row.price_factor) === null) {
  278. setError(`第 ${index + 1} 条出口「${row.exit_name}」的计费系数须为大于 0 且不超过 1 的数(最多两位小数)。`);
  279. return;
  280. }
  281. }
  282. setSaving(true);
  283. setError("");
  284. try {
  285. const result = await lineExitSave({
  286. items: rows.map((row) => ({ exit_name: row.exit_name, price_factor: Number(row.price_factor) })),
  287. });
  288. const next = (result.items ?? []).map((item) => ({
  289. exit_name: item.exit_name,
  290. price_factor: String(item.price_factor ?? 1),
  291. }));
  292. setDraft(next);
  293. onNotice(`线路出口已保存(${next.length} 条)。`);
  294. exits.reload();
  295. } catch (e) {
  296. setError(e instanceof ApiError ? e.message : "线路出口保存失败,请稍后重试。");
  297. } finally {
  298. setSaving(false);
  299. }
  300. }
  301. return <section className="catalog-resource" aria-labelledby="catalog-exit-heading">
  302. <div className="catalog-resource-heading">
  303. <div><h2 id="catalog-exit-heading">线路出口清单</h2><p>维护合同可选的国家或地区及对应计费系数。</p></div>
  304. {!exits.error && !(exits.loading && draft === null) && <span className="catalog-exits-count"><b>{rows.length}</b> 条</span>}
  305. </div>
  306. {writable && <div className="catalog-resource-controls">
  307. <Input aria-label="新增线路出口" className="catalog-exits-input" placeholder="输入国家或地区,可用逗号分隔" value={input} onChange={(event) => { setInput(event.target.value); setError(""); }} onKeyDown={(event) => { if (isImeComposing(event)) return; if (event.key === "Enter") { event.preventDefault(); add(); } }} />
  308. <Button variant="outline" size="sm" onClick={add}><Plus size={15} />添加</Button>
  309. <Button size="sm" disabled={!dirty || saving} onClick={save}>{saving ? "保存中…" : "保存出口清单"}</Button>
  310. </div>}
  311. <div className="catalog-exits-body">
  312. <div className="catalog-exits-list">
  313. {exits.error ? <Tri tone="fail" text={WORD_FETCH_FAILED} title={exits.error.message} />
  314. : exits.loading && draft === null ? <Tri tone="missing" text="正在载入…" />
  315. : rows.length ? rows.map((row, index) => {
  316. const refCount = refOf(row.exit_name)?.ref_count ?? 0;
  317. return <div key={`${exitKey(row.exit_name)}-${index}`} className="catalog-exit-row">
  318. <span className="catalog-exit-name">{row.exit_name}</span>
  319. <label className="catalog-exits-factor">
  320. <span>计费系数</span>
  321. <input
  322. aria-label={`${row.exit_name} 计费系数`}
  323. type="number"
  324. min={0.01}
  325. max={1}
  326. step={0.01}
  327. inputMode="decimal"
  328. disabled={!writable}
  329. readOnly={!writable}
  330. aria-invalid={writable && parseFactor(row.price_factor) === null ? true : undefined}
  331. value={row.price_factor}
  332. onChange={(event) => { if (!writable) return; setFactor(index, event.target.value); }}
  333. title="计费系数,默认 1,取值大于 0 且不超过 1(两位小数);最终订阅价=档位价×系数"
  334. />
  335. </label>
  336. {refCount > 0 && <small className="catalog-exits-ref" title={refOf(row.exit_name)?.ref_summary}>{`被 ${refCount} 处引用`}</small>}
  337. {writable && (refCount > 0
  338. ? <button type="button" className="is-locked" aria-label={`${row.exit_name} 已被引用,不能删除`} title={`${refOf(row.exit_name)?.ref_summary || "已被业务数据"}引用,不能删除;请先到合同/订阅侧处理引用`} disabled><LockKeyhole size={15} /></button>
  339. : <button type="button" aria-label={`删除线路出口 ${row.exit_name}`} title="删除需二次输入确认" onClick={() => askRemove(index)}><X size={15} /></button>)}
  340. </div>;
  341. })
  342. : <Tri tone="missing" text="尚未配置线路出口" />}
  343. </div>
  344. {error && <p className="catalog-editor-error" role="alert">{error}</p>}
  345. {!writable && <p className="catalog-resource-note">线路出口由总运营或运营主账号维护。</p>}
  346. <details className="catalog-resource-guide">
  347. <summary>计费与引用规则</summary>
  348. <p>合同条目按清单顺序列出可选出口。计费系数默认 1,取值大于 0 且不超过 1,最多两位小数。订阅价按档位价乘以系数计算,调整系数只影响后续定价。工单竣工按合同条目的核定出口回填。</p>
  349. <p>合同、存量 IP 备案、派生档或订阅引用中的出口不可删除。删除未引用出口需输入原名称确认,保存后整份清单生效。</p>
  350. </details>
  351. </div>
  352. {confirm && <div className="catalog-confirm-backdrop"><div className="catalog-confirm" role="alertdialog" aria-modal="true" aria-labelledby="catalog-exit-confirm-title">
  353. <span className="catalog-confirm-icon"><Trash2 size={20} /></span>
  354. <h2 id="catalog-exit-confirm-title">删除线路出口?</h2>
  355. <p>「{confirm.name}」将从出口清单移除(<strong>保存出口清单</strong>后生效)。请手打出口名称确认本次删除。</p>
  356. <label className="catalog-confirm-input">确认出口名称
  357. <input autoFocus value={confirm.typed} onChange={(event) => setConfirm((current) => current ? { ...current, typed: event.target.value } : current)} placeholder={confirm.name} onKeyDown={(event) => { if (isImeComposing(event)) return; if (event.key === "Enter" && confirm.typed.trim() === confirm.name.trim()) { event.preventDefault(); confirmRemove(); } }} />
  358. </label>
  359. <div><button type="button" className="catalog-button catalog-button-secondary" onClick={() => setConfirm(null)}>取消</button><button type="button" className="catalog-button catalog-button-danger" disabled={confirm.typed.trim() !== confirm.name.trim()} onClick={confirmRemove}>确认删除</button></div>
  360. </div></div>}
  361. </section>;
  362. }
  363. /** 带宽档位目录(2026-11-16 业主裁定,2026-11-17 改用途)。
  364. * ⚠️ 2026-11-17:合同「固定 IP 条目」已下线 ⇒ 本清单改为**套餐带宽权益录入的快捷预设**
  365. * (固定档/自定义档编辑器的「03 带宽与权益」一键带出上/下行),另兼「存量 IP 备案的历史引用」;
  366. * 合同侧不再选择档位,第 5 册回填的 5/10/30 与本清单**互不约束**。 */
  367. const TIER_NAME_MAX = 64;
  368. /** 与后端 `ip_bandwidth_tier::TIER_MBPS_MAX`/套餐档 `BW_MAX` 对齐(D-PKG-19/R-2)。 */
  369. const TIER_MBPS_MAX = 1000;
  370. /** 档位语义键(与后端 `ip_bandwidth_tier::tier_key` 同口径):兆数决定键,名称只是展示。 */
  371. const tierKeyOf = (mbps: number | null) => (mbps === null ? IP_TIER_UNCOMMITTED : `mbps-${mbps}`);
  372. /** 名称去重键=去空白+小写(与后端/线路出口同纪律)。 */
  373. const tierNameKeyOf = (name: string) => name.replace(/\s+/g, "").toLowerCase();
  374. /** 名称「N 兆」与兆数一致性(D-PKG-21);自由文案返回 null。 */
  375. function parseMbpsLabel(name: string): number | null {
  376. const m = name.replace(/\s+/g, "").match(/^(\d+)兆$/);
  377. if (!m) return null;
  378. const n = Number(m[1]);
  379. return Number.isInteger(n) ? n : null;
  380. }
  381. type TierDraft = { tier_name: string; bandwidth_tier_mbps: number | null };
  382. function BandwidthTierPanel({ writable, tiers, onNotice }: { writable: boolean; tiers: Load<IpBandwidthTierListResult>; onNotice: (message: string) => void }) {
  383. const [draft, setDraft] = useState<TierDraft[] | null>(null);
  384. const [name, setName] = useState("");
  385. const [mbps, setMbps] = useState("");
  386. const [error, setError] = useState("");
  387. const [saving, setSaving] = useState(false);
  388. /** 删除二次确认:与出口同一口径——有引用的不许删,没引用的也要手打名称确认。 */
  389. const [confirm, setConfirm] = useState<{ index: number; name: string; typed: string } | null>(null);
  390. useEffect(() => {
  391. if (draft === null && tiers.data) {
  392. setDraft(tiers.data.items.map((item) => ({ tier_name: item.tier_name, bandwidth_tier_mbps: item.bandwidth_tier_mbps })));
  393. }
  394. }, [tiers.data, draft]);
  395. const savedItems = tiers.data?.items ?? [];
  396. const saved: TierDraft[] = savedItems.map((item) => ({ tier_name: item.tier_name, bandwidth_tier_mbps: item.bandwidth_tier_mbps }));
  397. const rows = draft ?? saved;
  398. const refOf = (mbpsValue: number | null) => savedItems.find((item) => tierKeyOf(item.bandwidth_tier_mbps ?? null) === tierKeyOf(mbpsValue));
  399. const dirty = draft !== null && JSON.stringify(draft) !== JSON.stringify(saved);
  400. function add() {
  401. if (!writable) return;
  402. const tierName = name.trim();
  403. if (!tierName) { setError("请先输入档位名称(如「10 兆」「不承诺带宽」)。"); return; }
  404. if (tierName.length > TIER_NAME_MAX) { setError(`档位名称最多 ${TIER_NAME_MAX} 字。`); return; }
  405. const raw = mbps.trim();
  406. let value: number | null = null;
  407. if (raw) {
  408. const n = Number(raw);
  409. if (!Number.isInteger(n) || n < 1 || n > TIER_MBPS_MAX) { setError(`兆数须为 1–${TIER_MBPS_MAX} 的整数;留空=不承诺带宽。`); return; }
  410. value = n;
  411. }
  412. const encoded = parseMbpsLabel(tierName);
  413. if (value !== null && encoded !== null && encoded !== value) {
  414. setError(`档位名「${tierName}」与兆数 ${value} 不一致(名实须同源)。`);
  415. return;
  416. }
  417. const key = tierKeyOf(value);
  418. if (rows.some((row) => tierKeyOf(row.bandwidth_tier_mbps) === key)) {
  419. setError(value === null ? "「不承诺带宽」只能有一条。" : `已有 ${value} 兆的档位(同一兆数只允许一条)。`);
  420. return;
  421. }
  422. const nameKey = tierNameKeyOf(tierName);
  423. if (rows.some((row) => tierNameKeyOf(row.tier_name) === nameKey)) {
  424. setError(`带宽档位名称重复(空白与大小写不区分):${tierName}`);
  425. return;
  426. }
  427. setDraft([...rows, { tier_name: tierName, bandwidth_tier_mbps: value }]);
  428. setName("");
  429. setMbps("");
  430. setError("");
  431. }
  432. function rename(index: number, value: string) {
  433. setDraft((current) => (current ?? saved).map((row, i) => (i === index ? { ...row, tier_name: value } : row)));
  434. }
  435. function askRemove(index: number) {
  436. if (!writable) return;
  437. const row = rows[index];
  438. if (!row) return;
  439. const ref = refOf(row.bandwidth_tier_mbps);
  440. if ((ref?.ref_count ?? 0) > 0) {
  441. setError(`「${row.tier_name}」仍被 ${ref?.ref_summary || "存量 IP 备案"}引用,不能删除;该表已停写,只能由运维清理历史行后再删档位。`);
  442. return;
  443. }
  444. setError("");
  445. setConfirm({ index, name: row.tier_name, typed: "" });
  446. }
  447. function confirmRemove() {
  448. if (!confirm) return;
  449. if (confirm.typed.trim() !== confirm.name.trim()) return;
  450. setDraft((current) => (current ?? saved).filter((_, i) => i !== confirm.index));
  451. setConfirm(null);
  452. setError("");
  453. }
  454. async function save() {
  455. if (!writable || saving) return;
  456. const blank = rows.findIndex((row) => !row.tier_name.trim());
  457. if (blank >= 0) { setError(`第 ${blank + 1} 条档位名称为空,请补齐名称后再保存。`); return; }
  458. const nameKeys = new Set<string>();
  459. for (let i = 0; i < rows.length; i += 1) {
  460. const row = rows[i];
  461. const nk = tierNameKeyOf(row.tier_name.trim());
  462. if (nameKeys.has(nk)) { setError(`带宽档位名称重复(空白与大小写不区分):${row.tier_name.trim()}`); return; }
  463. nameKeys.add(nk);
  464. const encoded = parseMbpsLabel(row.tier_name.trim());
  465. if (row.bandwidth_tier_mbps !== null && encoded !== null && encoded !== row.bandwidth_tier_mbps) {
  466. setError(`第 ${i + 1} 条档位名「${row.tier_name.trim()}」与兆数 ${row.bandwidth_tier_mbps} 不一致(名实须同源)。`);
  467. return;
  468. }
  469. }
  470. setSaving(true);
  471. setError("");
  472. try {
  473. const result = await ipBandwidthTierSave({
  474. items: rows.map((row) => ({ tier_name: row.tier_name.trim(), bandwidth_tier_mbps: row.bandwidth_tier_mbps })),
  475. });
  476. const next = (result.items ?? []).map((item) => ({ tier_name: item.tier_name, bandwidth_tier_mbps: item.bandwidth_tier_mbps }));
  477. setDraft(next);
  478. onNotice(`带宽档位已保存(${next.length} 条)。`);
  479. tiers.reload();
  480. } catch (e) {
  481. setError(e instanceof ApiError ? e.message : "带宽档位保存失败,请稍后重试。");
  482. } finally {
  483. setSaving(false);
  484. }
  485. }
  486. return <section className="catalog-resource" aria-labelledby="catalog-tier-heading">
  487. <div className="catalog-resource-heading">
  488. <div><h2 id="catalog-tier-heading">带宽档位</h2><p>设置套餐编辑时可直接选用的带宽预设。</p></div>
  489. {!tiers.error && !(tiers.loading && draft === null) && <span className="catalog-exits-count"><b>{rows.length}</b> 档</span>}
  490. </div>
  491. {writable && <div className="catalog-resource-controls">
  492. <Input aria-label="新增档位名称" className="catalog-tier-name-input" placeholder="档位名称,如「10 兆」" value={name} onChange={(event) => { setName(event.target.value); setError(""); }} onKeyDown={(event) => { if (isImeComposing(event)) return; if (event.key === "Enter") { event.preventDefault(); add(); } }} />
  493. <Input aria-label="新增档位兆数" className="catalog-tier-mbps-input" inputMode="numeric" placeholder="兆数(可留空)" value={mbps} onChange={(event) => { setMbps(event.target.value); setError(""); }} onKeyDown={(event) => { if (isImeComposing(event)) return; if (event.key === "Enter") { event.preventDefault(); add(); } }} />
  494. <Button variant="outline" size="sm" onClick={add}><Plus size={15} />添加</Button>
  495. <Button size="sm" disabled={!dirty || saving} onClick={save}>{saving ? "保存中…" : "保存档位清单"}</Button>
  496. </div>}
  497. <div className="catalog-exits-body">
  498. <div className="catalog-tier-list">
  499. {tiers.error ? <Tri tone="fail" text={WORD_FETCH_FAILED} title={tiers.error.message} />
  500. : tiers.loading && draft === null ? <Tri tone="missing" text="正在载入…" />
  501. : rows.length ? rows.map((row, index) => {
  502. const ref = refOf(row.bandwidth_tier_mbps);
  503. const refCount = ref?.ref_count ?? 0;
  504. return <div key={tierKeyOf(row.bandwidth_tier_mbps)} className="catalog-tier-row">
  505. {writable
  506. ? <input aria-label={`档位名称 ${index + 1}`} className="catalog-tier-rename" value={row.tier_name} maxLength={TIER_NAME_MAX} onChange={(event) => rename(index, event.target.value)} />
  507. : <span className="catalog-tier-name">{row.tier_name}</span>}
  508. <small className="catalog-tier-mbps">{row.bandwidth_tier_mbps === null ? "不承诺带宽" : `${row.bandwidth_tier_mbps} 兆`}</small>
  509. {refCount > 0 && <small className="catalog-exits-ref" title={ref?.ref_summary ?? undefined}>{`被 ${refCount} 处引用`}</small>}
  510. {writable && (refCount > 0
  511. ? <button type="button" className="is-locked" aria-label={`${row.tier_name} 已被引用,不能删除`} title={`${ref?.ref_summary || "已被存量 IP 备案"}引用,不能删除;该表已停写,需运维清理历史行后再删`} disabled><LockKeyhole size={15} /></button>
  512. : <button type="button" aria-label={`删除档位 ${row.tier_name}`} title="删除需二次输入确认" onClick={() => askRemove(index)}><X size={15} /></button>)}
  513. </div>;
  514. })
  515. : <Tri tone="missing" text="尚未配置带宽档位" />}
  516. </div>
  517. {error && <p className="catalog-editor-error" role="alert">{error}</p>}
  518. {!writable && <p className="catalog-resource-note">带宽档位由总运营或运营主账号维护。</p>}
  519. <details className="catalog-resource-guide">
  520. <summary>档位取值与引用规则</summary>
  521. <p>套餐编辑器按清单顺序提供预设。兆数取值 1–{TIER_MBPS_MAX},同一兆数只能配置一条,留空表示不承诺带宽。工单施工回填仍使用 5、10、30 兆三个固定值。</p>
  522. <p>存量 IP 备案引用中的档位不可删除。删除未引用档位需输入原名称确认,保存后整份清单生效。</p>
  523. </details>
  524. </div>
  525. {confirm && <div className="catalog-confirm-backdrop"><div className="catalog-confirm" role="alertdialog" aria-modal="true" aria-labelledby="catalog-tier-confirm-title">
  526. <span className="catalog-confirm-icon"><Trash2 size={20} /></span>
  527. <h2 id="catalog-tier-confirm-title">删除带宽档位?</h2>
  528. <p>「{confirm.name}」将从档位清单移除(<strong>保存档位清单</strong>后生效)。请手打档位名称确认本次删除。</p>
  529. <label className="catalog-confirm-input">确认档位名称
  530. <input autoFocus value={confirm.typed} onChange={(event) => setConfirm((current) => current ? { ...current, typed: event.target.value } : current)} placeholder={confirm.name} onKeyDown={(event) => { if (isImeComposing(event)) return; if (event.key === "Enter" && confirm.typed.trim() === confirm.name.trim()) { event.preventDefault(); confirmRemove(); } }} />
  531. </label>
  532. <div><button type="button" className="catalog-button catalog-button-secondary" onClick={() => setConfirm(null)}>取消</button><button type="button" className="catalog-button catalog-button-danger" disabled={confirm.typed.trim() !== confirm.name.trim()} onClick={confirmRemove}>确认删除</button></div>
  533. </div></div>}
  534. </section>;
  535. }
  536. export function PackageManagementPage() {
  537. const { state } = useLocation();
  538. const back = detailBack(state, "/packages", "返回套餐配置");
  539. /** 03 章 §3.4 权限三档:固定档写入口=总运营专属;运营主账号只配客户专属档;其余角色只读且不出入口。
  540. * `opsMain`/`opsSub` 在 session 均映成 `regAdmin`,差异只由 `primary` 承载(D-PKG-16)⇒
  541. * 自定义档写入口必须与 `canWriteExits` 同式,⛔ 把子账号放成可点的写按钮。 */
  542. const identity = useDemoIdentity();
  543. const canWrite = !identity || identity.role === "admin" || (identity.role === "regAdmin" && Boolean(identity.primary));
  544. const canWriteFixed = !identity || identity.role === "admin";
  545. /** 线路出口是全局清单,后端只放行总运营/运营主账号(opsSub 同属 regAdmin 但⛔ 可写,见 session ROLE_TO_DEMO)。 */
  546. const canWriteExits = !identity || identity.role === "admin" || (identity.role === "regAdmin" && Boolean(identity.primary));
  547. /** 三视图:固定套餐/自定义套餐/线路出口(2026-11-15 收口,原型同形)。 */
  548. const [tab, setTab] = useState<CatalogTab>("fixed");
  549. const [category, setCategory] = useState<string>("all");
  550. const [search, setSearch] = useState("");
  551. /** R-14 台账收敛:自定义档按建档团队/建档人筛选——**服务端谓词**(`"all"` = 不加谓词)。
  552. * 选项取同一响应的 `facets`(服务端在 base ∧ custom 上聚合),⛔ 用当前页行凑。 */
  553. const [createdTeam, setCreatedTeam] = useState<string>("all");
  554. const [createdBy, setCreatedBy] = useState<string>("all");
  555. /** 关键字下发服务端:短防抖,避免每敲一字打一次列表。 */
  556. const [searchQuery, setSearchQuery] = useState("");
  557. useEffect(() => {
  558. const timer = window.setTimeout(() => setSearchQuery(search.trim()), 300);
  559. return () => window.clearTimeout(timer);
  560. }, [search]);
  561. const isCustomTab = tab === "custom";
  562. const [ledgerPage, setLedgerPage] = useState(0);
  563. const catalog = useCatalogLedger({
  564. enabled: tab !== "exits",
  565. planKind: isCustomTab ? "custom" : "fixed",
  566. planFamily: !isCustomTab && category !== "all" ? category : undefined,
  567. keyword: searchQuery || undefined,
  568. createdBy: isCustomTab && createdBy !== "all" ? createdBy : undefined,
  569. createdTeamId: isCustomTab && createdTeam !== "all" ? createdTeam : undefined,
  570. page: ledgerPage,
  571. pageSize: LIST_PAGE_SIZE,
  572. });
  573. const [editor, setEditor] = useState<EditorState | null>(null);
  574. /** 线路出口/带宽档:仅 exits tab 预拉;编辑器打开时再拉带宽预设(⛔ 进页三请求)。 */
  575. const exits = useLineExits({ enabled: tab === "exits" });
  576. const tiers = useIpBandwidthTiers({ enabled: tab === "exits" || editor !== null });
  577. /**
  578. * 切 fixed/custom 时 useLoad 会短暂保留上一档应答(reload 不闪 loading)。
  579. * 只画与当前 tab 同 `plan_kind` 的行;异种旧行一律丢掉,⛔ 闪成「假 mock」。
  580. */
  581. const expectKind = isCustomTab ? "custom" : "fixed";
  582. const rawItems = catalog.data?.items;
  583. const dataMatchesTab = !catalog.data
  584. || !rawItems?.length
  585. || rawItems.every((plan) => plan.plan_kind === expectKind);
  586. const rows = useMemo(
  587. () => (dataMatchesTab && rawItems ? rawItems.filter((plan) => plan.plan_kind === expectKind) : []),
  588. [rawItems, dataMatchesTab, expectKind],
  589. );
  590. const awaitingTab = tab !== "exits" && (catalog.loading || !dataMatchesTab);
  591. const facets = dataMatchesTab ? catalog.data?.facets : undefined;
  592. const teamOptions = facets?.created_team ?? [];
  593. const creatorOptions = facets?.created_by ?? [];
  594. const [deleteTarget, setDeleteTarget] = useState<CatalogPlanRow | null>(null);
  595. /** K205 拦截后的两栏引用明细:服务端 `blocks.subscriptions`/`blocks.items`(wire 键仍叫 subscriptions)。 */
  596. const [deleteBlocks, setDeleteBlocks] = useState<{ orders: string[]; items: string[] } | null>(null);
  597. const [deleteError, setDeleteError] = useState("");
  598. const [notice, setNotice] = useState("");
  599. const [failure, setFailure] = useState("");
  600. const [deleting, setDeleting] = useState(false);
  601. /** 成功提示到点自动收起(⛔ 挂着等用户点关闭);换新文案重新计时,`failure` 是错误提示,⛔ 自动消失。 */
  602. useEffect(() => {
  603. if (!notice) return;
  604. const timer = window.setTimeout(() => setNotice(""), NOTICE_DISMISS_MS);
  605. return () => window.clearTimeout(timer);
  606. }, [notice]);
  607. /** 自定义档多「建档人/建档团队」两列;固定档仍 9 列。 */
  608. const ledgerColSpan = isCustomTab ? 11 : 9;
  609. const visible = rows;
  610. const kindTotals = catalog.data?.kind_totals;
  611. const fixedCount = kindTotals?.fixed ?? (catalog.data ? 0 : "—");
  612. const customCount = kindTotals?.custom ?? (catalog.data ? 0 : "—");
  613. const listTotal = dataMatchesTab ? Number(catalog.data?.total ?? visible.length) : 0;
  614. const paging = useLocalPage(listTotal, LIST_PAGE_SIZE, ledgerPage);
  615. const pageRows = visible;
  616. const setPage = (next: number) => setLedgerPage(Math.max(0, next));
  617. const resetPage = () => setLedgerPage(0);
  618. /** 固定套餐按用途分类分组,分组行落在表体内;后端不下发 use_category 的档位单列一组,⛔ 静默丢行。
  619. * 序号取「表内显示顺序」(分组后位置),⛔ 用后端数组下标——否则分组一排序就出现 7 在 6 前面。 */
  620. const fixedGroups = useMemo(() => {
  621. const familyOf = (plan: CatalogPlanRow) => plan.plan_family;
  622. const known = planFamilies
  623. .map((item) => ({ name: item.name as string, hint: `${orderModeOf(item.code)} · ${item.hint}`, plans: pageRows.filter((plan) => familyOf(plan) === item.code) }))
  624. .filter((group) => group.plans.length > 0);
  625. const uncategorized = pageRows.filter((plan) => !planFamilies.some((item) => item.code === familyOf(plan)));
  626. const groups = uncategorized.length ? [...known, { name: WORD_UNCONFIGURED, hint: `交付形态:${WORD_NOT_PROVIDED}`, plans: uncategorized }] : known;
  627. let position = 0;
  628. return groups.map((group) => ({ name: group.name, hint: group.hint, entries: group.plans.map((plan) => ({ plan, position: position++ })) }));
  629. }, [pageRows]);
  630. function resetFilters() {
  631. setCategory("all");
  632. setSearch("");
  633. setCreatedTeam("all");
  634. setCreatedBy("all");
  635. resetPage();
  636. }
  637. function switchTab(next: CatalogTab) {
  638. setTab(next);
  639. // 建档人/团队谓词只在自定义档 Tab 生效;切走时一并复位,免得回来时看到一个「隐形」的过滤条件。
  640. setCreatedTeam("all");
  641. setCreatedBy("all");
  642. resetPage();
  643. }
  644. function saved(message: string, plan: CatalogPlanRow | null) {
  645. setEditor(null);
  646. if (plan) setTab(plan.plan_kind === "custom" ? "custom" : "fixed");
  647. setCategory("all");
  648. setSearch("");
  649. setCreatedTeam("all");
  650. setCreatedBy("all");
  651. resetPage();
  652. setFailure("");
  653. setNotice(message);
  654. catalog.reload();
  655. }
  656. const rowIndexBase = ledgerPage * paging.pageSize;
  657. async function remove() {
  658. if (!deleteTarget) return;
  659. setDeleting(true);
  660. try {
  661. const result = await catalogDelete({ plan_id: deleteTarget.plan_id });
  662. setDeleteTarget(null);
  663. setDeleteBlocks(null);
  664. setDeleteError("");
  665. setFailure("");
  666. setNotice(result?.deleted ? `${deleteTarget.plan_name}已删除。` : `未能删除:${result?.suggest ?? "该档位已被合同条目或订阅引用"}`);
  667. catalog.reload();
  668. } catch (e) {
  669. const detail = e instanceof ApiError ? (e.detail as { blocks?: { subscriptions?: unknown; items?: unknown } } | undefined) : undefined;
  670. const orders = Array.isArray(detail?.blocks?.subscriptions) ? detail!.blocks!.subscriptions!.map(String) : [];
  671. const items = Array.isArray(detail?.blocks?.items) ? detail!.blocks!.items!.map(String) : [];
  672. setNotice("");
  673. setFailure("");
  674. if (orders.length || items.length) {
  675. /** K205 两栏:确认框留在原位转成引用清单(订阅/合同条目),⛔ 只弹一句 toast 把份数丢掉。 */
  676. setDeleteError(e instanceof ApiError ? e.message : "该套餐档位已被引用,不能删除。");
  677. setDeleteBlocks({ orders, items });
  678. } else {
  679. setDeleteTarget(null);
  680. setDeleteBlocks(null);
  681. setDeleteError("");
  682. setFailure(e instanceof ApiError ? e.message : "删除失败,请稍后重试。");
  683. }
  684. } finally {
  685. setDeleting(false);
  686. }
  687. }
  688. function closeDelete() {
  689. setDeleteTarget(null);
  690. setDeleteBlocks(null);
  691. setDeleteError("");
  692. }
  693. const canCreate = isCustomTab ? canWrite : canWriteFixed;
  694. const readOnlyNote = isCustomTab ? "自定义套餐由总运营或运营主账号维护。" : OPERATOR_ONLY_CONFIG;
  695. const planRow = (plan: CatalogPlanRow, position: number) => <PlanRow
  696. key={plan.plan_id}
  697. plan={plan}
  698. index={rowIndexBase + position + 1}
  699. custom={isCustomTab}
  700. writable={canCreate}
  701. readOnlyNote={readOnlyNote}
  702. onEdit={() => setEditor({ plan, owner: isCustomTab ? plan.customer_id ?? "" : null })}
  703. onDelete={() => { setDeleteError(""); setDeleteBlocks(null); setDeleteTarget(plan); }}
  704. />;
  705. const hasFilters = Boolean(search || (isCustomTab ? createdBy !== "all" || createdTeam !== "all" : category !== "all"));
  706. const tabs = [
  707. { id: "fixed", title: "固定套餐", description: "签约时均可选用的公共档位", icon: Layers3, count: catalog.error ? "—" : fixedCount },
  708. { id: "custom", title: "自定义套餐", description: "归属指定客户的专属档位", icon: SlidersHorizontal, count: catalog.error ? "—" : customCount },
  709. { id: "exits", title: "线路出口", description: "出口清单与带宽预设", icon: Globe2, count: !exits.error && exits.data ? exits.data.items.length : "—" },
  710. ] as const;
  711. const emptyMessage = catalog.error
  712. ? `无法加载套餐:${catalog.error.message}`
  713. : awaitingTab
  714. ? "正在加载套餐…"
  715. : hasFilters
  716. ? "没有符合筛选条件的套餐档,可重置筛选后再看。"
  717. : tab === "custom" ? "目录里还没有自定义套餐档。" : "目录里还没有固定套餐档。";
  718. return <section className="ops-page ops-page--packages package-catalog">
  719. {back.to !== "/packages" && <Link className="ops-back-link" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label}</Link>}
  720. <header className="catalog-page-head">
  721. <h1>套餐配置</h1>
  722. <PageIntro>管理签约可选的套餐、订阅价格和交付配置。</PageIntro>
  723. </header>
  724. <RecordTabs prefix="catalog" className="catalog-tabs" label="套餐配置视图" active={tab} onChange={switchTab}
  725. tabs={tabs.map(({ id, title, description, count, icon: Icon }) => ({
  726. id, count, label: <>
  727. <span className="catalog-tab-icon"><Icon size={18} aria-hidden="true" /></span>
  728. <span className="catalog-tab-copy"><strong>{title}</strong><small>{description}</small></span>
  729. </>,
  730. }))}
  731. />
  732. {tabs.filter(({ id }) => id !== tab).map(({ id }) => (
  733. <div key={id} id={`catalog-panel-${id}`} role="tabpanel" aria-labelledby={`catalog-tab-${id}`} hidden />
  734. ))}
  735. {tab === "exits"
  736. ? <div id="catalog-panel-exits" role="tabpanel" aria-labelledby="catalog-tab-exits" className="catalog-exits-panel">
  737. <LineExitPanel writable={canWriteExits} exits={exits} onNotice={(message) => { setFailure(""); setNotice(message); }} />
  738. <BandwidthTierPanel writable={canWriteExits} tiers={tiers} onNotice={(message) => { setFailure(""); setNotice(message); }} />
  739. </div>
  740. : <div id={`catalog-panel-${tab}`} role="tabpanel" aria-labelledby={`catalog-tab-${tab}`} className="catalog-tabpanel">
  741. <div className="catalog-ledger-toolbar">
  742. <div className="catalog-filters">
  743. <label className="ops-search"><Search size={17} aria-hidden="true" /><Input aria-label="搜索套餐" placeholder={isCustomTab ? "搜索套餐名称或归属客户" : "搜索套餐名称、带宽或说明"} value={search} onChange={(event) => { setSearch(event.target.value); resetPage(); }} />{search && <button type="button" aria-label="清空搜索" onClick={() => { setSearch(""); resetPage(); }}><X size={15} aria-hidden="true" /></button>}</label>
  744. {/* 自定义档恒为「定制化」,没有可选项 ⇒ 该 Tab 不出分类筛选(⛔ 给一个筛完必空的控件)。 */}
  745. {!isCustomTab && <FilterSelect icon="type" aria-label="交付形态筛选" value={category} onChange={(event) => { setCategory(event.target.value); resetPage(); }}><option value="all">全部交付形态</option>{planFamilies.map((item) => <option key={item.code} value={item.code}>{item.name}</option>)}</FilterSelect>}
  746. {/* R-14:自定义档越滚越多 ⇒ 按建档团队/建档人收敛。选项取服务端 facets,⛔ 当前页行。
  747. 固定档不提供(共享目录,不是谁的台账)。 */}
  748. {isCustomTab && <>
  749. <FilterSelect icon="task" aria-label="建档团队筛选" value={createdTeam} onChange={(event) => { setCreatedTeam(event.target.value); resetPage(); }}>
  750. <option value="all">全部建档团队</option>
  751. {teamOptions.map((item) => <option key={item.value} value={item.value}>{item.label}({item.count})</option>)}
  752. </FilterSelect>
  753. <FilterSelect icon="assignment" aria-label="建档人筛选" value={createdBy} onChange={(event) => { setCreatedBy(event.target.value); resetPage(); }}>
  754. <option value="all">全部建档人</option>
  755. {creatorOptions.map((item) => <option key={item.value} value={item.value}>{item.label}({item.count})</option>)}
  756. </FilterSelect>
  757. </>}
  758. {hasFilters && <Button variant="ghost" size="sm" onClick={resetFilters}>重置筛选</Button>}
  759. </div>
  760. {canCreate ? (
  761. <button type="button" className="catalog-button catalog-button-primary" onClick={() => setEditor(isCustomTab ? { owner: "", planKind: "custom" } : { owner: null })}>
  762. <Plus size={16} aria-hidden="true" />{isCustomTab ? "新增自定义套餐" : "新增固定套餐"}
  763. </button>
  764. ) : <span className="catalog-head-note"><LockKeyhole size={14} aria-hidden="true" />{readOnlyNote}</span>}
  765. </div>
  766. <div tabIndex={0} role="region" aria-label="套餐档位列表" className="ops-table-wrap catalog-table-wrap">
  767. <table role="table" className={`ops-table catalog-ledger${isCustomTab ? " catalog-ledger-custom" : ""}`} aria-busy={awaitingTab && !catalog.error}>
  768. <OpsTableColumns widths={isCustomTab ? CUSTOM_PLAN_COLUMNS : PLAN_COLUMNS} />
  769. <thead role="rowgroup"><tr role="row">{[
  770. "序号", "套餐", "年订阅价格", "月结算标准", "月成本", "分账号额度", "总带宽", "订阅量",
  771. ...(isCustomTab ? ["建档人", "建档团队"] : []),
  772. "操作",
  773. ].map((column) => <th role="columnheader" scope="col" key={column}>{column}</th>)}</tr></thead>
  774. <tbody role="rowgroup">
  775. {tab === "fixed"
  776. ? fixedGroups.map((group) => <Fragment key={group.name}><PlanGroupRow title={group.name} hint={group.hint} colSpan={ledgerColSpan} />{group.entries.map(({ plan, position }) => planRow(plan, position))}</Fragment>)
  777. : pageRows.map((plan, index) => planRow(plan, index))}
  778. {(catalog.error || visible.length === 0) && <OpsTableEmpty colSpan={ledgerColSpan}>
  779. <div className="catalog-empty"><span>{emptyMessage}</span>{catalog.error && <Button variant="outline" size="sm" onClick={catalog.reload}>重试</Button>}</div>
  780. </OpsTableEmpty>}
  781. </tbody>
  782. </table>
  783. </div>
  784. <ListPager total={listTotal} page={paging.safePage} pageSize={paging.pageSize} onPageChange={setPage} unit="档" />
  785. </div>}
  786. {notice && <div className="catalog-toast" role="status"><span>{notice}</span><button aria-label="关闭提示" onClick={() => setNotice("")}><X size={16} /></button></div>}
  787. {failure && <div className="catalog-toast" role="alert"><span>{failure}</span><button aria-label="关闭提示" onClick={() => setFailure("")}><X size={16} /></button></div>}
  788. {editor && <PackagePlanEditor key={editor.plan?.plan_id ?? `new-${editor.owner ?? "fixed"}`} state={editor} tiers={tiers} onClose={() => setEditor(null)} onSaved={saved} />}
  789. {deleteTarget && <div className="catalog-confirm-backdrop"><div className="catalog-confirm" role="alertdialog" aria-modal="true" aria-labelledby="catalog-confirm-title">
  790. {deleteError
  791. ? <><span className="catalog-confirm-icon"><Trash2 size={20} /></span><h2 id="catalog-confirm-title">无法删除该套餐档位</h2><p>{deleteError}</p>
  792. {deleteBlocks && <div className="catalog-confirm-blocks">
  793. <div><h3>{`引用该档位的订阅(${deleteBlocks.orders.length})`}</h3>{deleteBlocks.orders.length ? <ul>{deleteBlocks.orders.map((id) => <li key={id}>{id}</li>)}</ul> : <small>无</small>}</div>
  794. <div><h3>{`引用该档位的合同条目(${deleteBlocks.items.length})`}</h3>{deleteBlocks.items.length ? <ul>{deleteBlocks.items.map((id) => <li key={id}>{id}</li>)}</ul> : <small>无</small>}</div>
  795. </div>}
  796. <div><button type="button" className="catalog-button catalog-button-secondary" onClick={closeDelete}>关闭</button></div></>
  797. : <><span className="catalog-confirm-icon"><Trash2 size={20} /></span><h2 id="catalog-confirm-title">删除套餐档位?</h2><p>“{deleteTarget.plan_name}”删除后将从目录中移除。此操作无法撤销。</p><div><button type="button" className="catalog-button catalog-button-secondary" onClick={closeDelete}>取消</button><button type="button" className="catalog-button catalog-button-danger" disabled={deleting} onClick={remove}>{deleting ? "删除中…" : "确认删除"}</button></div></>}
  798. </div></div>}
  799. </section>;
  800. }