| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824 |
- import { FilterSelect } from "../components/ui/filter-select";
- import { PageIntro } from "../components/PageIntro";
- import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, Fragment, type ReactNode } from "react";
- import { createPortal } from "react-dom";
- import { ArrowLeft, CircleHelp, Globe2, Layers3, LockKeyhole, PencilLine, Plus, Search, SlidersHorizontal, Trash2, X } from "lucide-react";
- import { Link, useLocation } from "react-router";
- import { detailBack } from "../lib/detail-navigation";
- import { Button } from "../components/ui/button";
- import { Input } from "../components/ui/input";
- import { TableValueText, Tri } from "../components/triState";
- import { NOTICE_DISMISS_MS, OpsTag, OpsTableColumns, OpsTableEmpty } from "../components/OperationsKit";
- import { ListPager } from "../components/ListPager";
- import { RecordTabs } from "../components/RecordTabs";
- import { COST_BY_COMBINATION, OPERATOR_ONLY_CONFIG, WORD_FETCH_FAILED, WORD_NOT_PROVIDED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
- import { catalogDelete, ipBandwidthTierSave, lineExitSave } from "../lib/api/bos";
- import type { CatalogPlanRow, IpBandwidthTierListResult, LineExitListResult } from "../lib/api/types";
- import { ApiError } from "../lib/api/http";
- import { useDemoIdentity } from "../lib/demo-session";
- import { familyLabel, planFamilies, useCatalogLedger, useIpBandwidthTiers, useLineExits } from "../lib/package-catalog";
- import { exitKey, IP_TIER_UNCOMMITTED, splitExitInput } from "../domain/contract-items";
- import type { Load } from "../lib/useLoad";
- import { LIST_PAGE_SIZE, useLocalPage } from "../lib/list-paging";
- import { isImeComposing } from "../lib/ime";
- import { PackagePlanEditor, type EditorState } from "../components/PackagePlanEditor";
- import "../styles/operations.css";
- import "../styles/packages.css";
- /** 目录三视图:固定套餐与自定义套餐各一张台账,线路出口是目录级清单。 */
- type CatalogTab = "fixed" | "custom" | "exits";
- /** 计数列显示数量和单位,保留缺失与取数失败的提示。 */
- function intCell(value: number | null | undefined, unit: "个" | "份") {
- if (value === undefined) return <Tri tone="fail" text={WORD_FETCH_FAILED} />;
- if (value === null) return <Tri tone="missing" text={WORD_UNCONFIGURED} />;
- return <><span className="table-number catalog-number-emphasis">{value}</span><span className="catalog-value-unit"><span className="catalog-value-separator">/</span>{unit}</span></>;
- }
- /** 价格按年或按月标明单位,成本金额沿用千分位和两位小数。 */
- const LEDGER_MONEY = new Intl.NumberFormat("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
- function ledgerMoney(cents: number | null | undefined, period?: "年" | "月") {
- if (cents === undefined) return <Tri tone="fail" text={WORD_FETCH_FAILED} />;
- if (cents === null) return <Tri tone="missing" text={WORD_UNCONFIGURED} />;
- const amount = LEDGER_MONEY.format(cents / 100);
- if (!period) return <span className="table-number">{amount}</span>;
- const annual = period === "年";
- return (
- <span className={annual ? "catalog-price catalog-price-annual" : "catalog-price"} title={`¥${amount}/${period}`}>
- <span className="catalog-price-currency">¥</span>
- <span className={annual ? "table-annual-price" : "table-number"}>{amount}</span>
- <span className="catalog-value-unit"><span className="catalog-value-separator">/</span>{period}</span>
- </span>
- );
- }
- /** 总带宽列:addon 恒「—」(D-18);未承诺或未填上下行=「不承诺带宽」(⛔ 冒充取数失败);有值再并显/分显。 */
- function ledgerBandwidth(plan: CatalogPlanRow) {
- if (plan.plan_family === "addon") return <>{"—"}</>;
- if (!plan.bandwidth_committed) return <>不承诺带宽</>;
- const up = plan.bandwidth_up_mbps;
- const down = plan.bandwidth_down_mbps;
- /** 存量 DEFAULT TRUE + 上下行空:语义=未配置带宽=不承诺,⛔ 红字「取数失败」。 */
- if (up === null || up === undefined || down === null || down === undefined) return <>不承诺带宽</>;
- return <>
- {up === down ? "上下行 " : "下行 "}<span className="table-number catalog-number-emphasis">{down}</span>M
- {up !== down && <><span className="catalog-value-separator">/</span>上行 <span className="table-number catalog-number-emphasis">{up}</span>M</>}
- </>;
- }
- /** 月成本四态(R-1):ok=金额;unconfigured=未配置;by_combination/缺省=按组合;failed/error=取数失败。 */
- function ledgerCostCell(plan: CatalogPlanRow) {
- const state = plan.plan_cost_state;
- if (state === "failed" || state === "error") {
- return <Tri tone="fail" text={WORD_FETCH_FAILED} title={plan.plan_cost_note || undefined} />;
- }
- if (state === "ok") return ledgerMoney(plan.plan_cost_cents);
- if (state === "unconfigured") return <Tri tone="missing" text={WORD_UNCONFIGURED} />;
- return <Tri tone="val" text={COST_BY_COMBINATION} title="金额随各客户的「省份 × 运营商」组合不同,不折中成一个数" />;
- }
- /**
- * 套餐说明:挂在名称右侧的问号图标上,不占一列。图标随行悬停/键盘聚焦显形,点击展开浮层显示说明。
- * 浮层走 body 传送门+fixed,避免被台账滚动容器裁掉;**落在图标的左/右侧而非正下方**,
- * 让指针停在图标上时不会压住浮层正文(正下方时箭头正对浮层首行)。
- */
- function PlanDescNote({ name, desc }: { name: string; desc: string }) {
- const id = useId();
- const trigger = useRef<HTMLButtonElement>(null);
- const popup = useRef<HTMLDivElement>(null);
- const [open, setOpen] = useState(false);
- const [position, setPosition] = useState({ top: 0, left: 0 });
- useLayoutEffect(() => {
- if (!open || !trigger.current || !popup.current) return;
- const anchor = trigger.current.getBoundingClientRect();
- const box = popup.current.getBoundingClientRect();
- const gap = 10;
- const clampTop = (top: number) => Math.max(8, Math.min(top, window.innerHeight - box.height - 8));
- const rightRoom = window.innerWidth - anchor.right - gap - 8;
- const leftRoom = anchor.left - gap - 8;
- /** 优先右邻(与图标垂直居中对齐),右边放不下再翻到左边;两侧都放不下才落到下方,留 18px 让指针箭头够不到正文。 */
- if (rightRoom >= box.width) {
- setPosition({ left: anchor.right + gap, top: clampTop(anchor.top + anchor.height / 2 - box.height / 2) });
- } else if (leftRoom >= box.width) {
- setPosition({ left: anchor.left - gap - box.width, top: clampTop(anchor.top + anchor.height / 2 - box.height / 2) });
- } else {
- setPosition({
- left: Math.max(8, Math.min(anchor.left + anchor.width / 2, window.innerWidth - box.width - 8)),
- top: clampTop(anchor.bottom + 18),
- });
- }
- }, [open]);
- useEffect(() => {
- if (!open) return;
- const close = () => setOpen(false);
- /** 点到图标与浮层以外即收(滚动/缩放同样收,浮层不跟着错位)。 */
- const outside = (event: PointerEvent) => {
- if (!trigger.current?.contains(event.target as Node) && !popup.current?.contains(event.target as Node)) close();
- };
- const escape = (event: KeyboardEvent) => { if (event.key === "Escape") close(); };
- document.addEventListener("pointerdown", outside);
- document.addEventListener("keydown", escape);
- window.addEventListener("scroll", close, true);
- window.addEventListener("resize", close);
- return () => {
- document.removeEventListener("pointerdown", outside);
- document.removeEventListener("keydown", escape);
- window.removeEventListener("scroll", close, true);
- window.removeEventListener("resize", close);
- };
- }, [open]);
- return <>
- <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>
- {open && createPortal(<div ref={popup} id={id} role="dialog" aria-label={`${name} · 套餐说明`} className="catalog-desc-popover" style={position}>
- <strong>套餐说明</strong>
- <p>{desc}</p>
- </div>, document.body)}
- </>;
- }
- /** 台账列宽:序号/操作列固定,其余按阅读需求分配(同合同台账口径)。
- * 套餐说明已收进名称旁问号图标,不再单列;用途分类改由表体内分组行承载,两 Tab 同列(2026-11-15)。 */
- const PLAN_ACTIONS_WIDTH = 164;
- const PLAN_COLUMNS = [58, 246, 132, 124, 96, 86, 150, 78, PLAN_ACTIONS_WIDTH] as const;
- /** 自定义档台账多两列:建档人/建档团队(固定档不加)。 */
- const CUSTOM_PLAN_COLUMNS = [...PLAN_COLUMNS.slice(0, -1), 106, 112, PLAN_ACTIONS_WIDTH] as const;
- /** 小屏将同一行的数据排成卡片,使用独立的可见字段名。 */
- function CatalogField({ label, children, title }: {
- label: string; children: ReactNode; title?: string;
- }) {
- return (
- <td role="cell" title={title}>
- <span className="catalog-field-label" aria-hidden="true">{label}</span>
- {children}
- </td>
- );
- }
- function PlanRow({ plan, index, custom, writable, readOnlyNote, onEdit, onDelete }: {
- plan: CatalogPlanRow; index: number; custom?: boolean; writable: boolean; readOnlyNote: string; onEdit: () => void; onDelete: () => void;
- }) {
- return <tr className="catalog-plan-row" role="row">
- <td role="cell" className="catalog-sequence table-number">{index}</td>
- <td role="cell" className="catalog-identity">
- <span className="catalog-plan-name">
- <strong className="table-cell-title" title={plan.plan_name || undefined}>{plan.plan_name || <Tri tone="missing" text={WORD_UNCONFIGURED} />}</strong>
- {plan.plan_desc && <PlanDescNote name={plan.plan_name || plan.plan_id} desc={plan.plan_desc} />}
- {plan.plan_family && <OpsTag tone="brand">{familyLabel(plan.plan_family)}</OpsTag>}
- </span>
- {custom && <small className="catalog-plan-owner" title={plan.customer_name ?? undefined}>归属客户 · <TableValueText>{plan.customer_name || WORD_UNCONFIGURED}</TableValueText></small>}
- </td>
- <CatalogField label="年订阅价格">{ledgerMoney(plan.annual_price_cents, "年")}</CatalogField>
- <CatalogField label="月结算标准">{ledgerMoney(plan.monthly_settle_cents, "月")}</CatalogField>
- <CatalogField label="月成本">{ledgerCostCell(plan)}</CatalogField>
- <CatalogField label="分账号额度">{intCell(plan.sub_account_quota, "个")}</CatalogField>
- <CatalogField label="总带宽">{ledgerBandwidth(plan)}</CatalogField>
- <CatalogField label="订阅量" title="被合同条目或订阅引用的数量">{intCell(plan.referred_count, "份")}</CatalogField>
- {custom && <>
- <CatalogField label="建档人" title={plan.created_by ?? undefined}>{plan.created_by_name || <Tri tone="missing" text={WORD_UNCONFIGURED} />}</CatalogField>
- <CatalogField label="建档团队" title={plan.created_team_id ?? undefined}>{plan.created_team_name || <Tri tone="missing" text={WORD_UNCONFIGURED} />}</CatalogField>
- </>}
- <td role="cell" className="catalog-actions-cell">
- {writable ? (
- <div className="ops-inline-actions catalog-row-actions">
- <button type="button" aria-label="编辑套餐" onClick={onEdit}><PencilLine size={15} aria-hidden="true" />编辑</button>
- <button type="button" className="is-danger" aria-label="删除套餐" onClick={onDelete} title="删除套餐(引用拦截由服务端判定)"><Trash2 size={15} aria-hidden="true" />删除</button>
- </div>
- ) : <span className="catalog-readonly-note" title={readOnlyNote}>只读</span>}
- </td>
- </tr>;
- }
- function PlanGroupRow({ title, hint, colSpan }: { title: string; hint: string; colSpan: number }) {
- return <tr className="catalog-group-row" role="row">
- <td role="cell" colSpan={colSpan}>
- <div className="catalog-group-label"><strong><TableValueText>{title}</TableValueText></strong><span>{hint}</span></div>
- </td>
- </tr>;
- }
- function orderModeOf(family: string) {
- return family === "addon" ? "可叠加" : "可升降配";
- }
- /** 配置级线路出口。 */
- const CATALOG_EXIT_MAX = 200;
- type ExitDraftRow = { exit_name: string; price_factor: string };
- function LineExitPanel({ writable, exits, onNotice }: { writable: boolean; exits: Load<LineExitListResult>; onNotice: (message: string) => void }) {
- const [draft, setDraft] = useState<ExitDraftRow[] | null>(null);
- const [input, setInput] = useState("");
- const [error, setError] = useState("");
- const [saving, setSaving] = useState(false);
- /** 删除二次确认:必须手打出口原文才放行(2026-11-15 业主口径:有引用的不许删、没引用的也要二次输入确认)。 */
- const [confirm, setConfirm] = useState<{ index: number; name: string; typed: string } | null>(null);
- useEffect(() => {
- if (draft === null && exits.data) {
- setDraft(exits.data.items.map((item) => ({
- exit_name: item.exit_name,
- price_factor: String(item.price_factor ?? 1),
- })));
- }
- }, [exits.data, draft]);
- const savedItems = exits.data?.items ?? [];
- const saved: ExitDraftRow[] = savedItems.map((item) => ({
- exit_name: item.exit_name,
- price_factor: String(item.price_factor ?? 1),
- }));
- const rows = draft ?? saved;
- /** 引用面按归一化键查(后端逐条带出 `ref_count`/`ref_summary`)。 */
- const refOf = (name: string) => savedItems.find((item) => item.exit_key === exitKey(name));
- const dirty = draft !== null && (
- draft.length !== saved.length
- || rows.some((row, index) => row.exit_name !== saved[index]?.exit_name || row.price_factor !== saved[index]?.price_factor)
- );
- function add() {
- if (!writable) return;
- const incoming = splitExitInput(input);
- if (!incoming.length) { setError("请先输入线路出口(国家/地区名称原文)。"); return; }
- const seen = new Set(rows.map((row) => exitKey(row.exit_name)));
- const next = [...rows];
- let duplicated = 0;
- let overflow = 0;
- for (const raw of incoming) {
- if (next.length >= CATALOG_EXIT_MAX) { overflow += 1; continue; }
- const key = exitKey(raw);
- if (seen.has(key)) { duplicated += 1; continue; }
- seen.add(key);
- next.push({ exit_name: raw.trim(), price_factor: "1" });
- }
- setDraft(next);
- setInput("");
- setError(overflow ? `线路出口最多 ${CATALOG_EXIT_MAX} 条,已忽略 ${overflow} 条。` : duplicated ? `已跳过 ${duplicated} 条重复出口(空白、大小写不区分)。` : "");
- }
- function askRemove(index: number) {
- if (!writable) return;
- const name = rows[index]?.exit_name;
- if (!name) return;
- /** 有引用的出口连确认框都不给:⛔ 让人打完字再吃 400(服务端仍是最终判据)。 */
- if ((refOf(name)?.ref_count ?? 0) > 0) {
- setError(`「${name}」仍被 ${refOf(name)?.ref_summary || "业务数据"}引用,不能从清单删除;请先到合同/订阅侧处理引用。`);
- return;
- }
- setError("");
- setConfirm({ index, name, typed: "" });
- }
- function confirmRemove() {
- if (!confirm) return;
- if (confirm.typed.trim() !== confirm.name.trim()) return;
- setDraft((current) => (current ?? saved).filter((_, i) => i !== confirm.index));
- setConfirm(null);
- setError("");
- }
- function setFactor(index: number, value: string) {
- if (!writable) return;
- setDraft((current) => (current ?? saved).map((row, i) => (i === index ? { ...row, price_factor: value } : row)));
- setError("");
- }
- /** 计费系数门禁:`(0, 1]`,最多两位小数(与后端 `require_price_factor_scaled` 同源)。 */
- function parseFactor(raw: string): number | null {
- const text = raw.trim();
- if (!text) return null;
- if (!/^\d+(?:\.\d{1,2})?$/.test(text)) return null;
- const value = Number(text);
- if (!Number.isFinite(value) || value <= 0 || value > 1) return null;
- return value;
- }
- async function save() {
- if (!writable || saving) return;
- for (const [index, row] of rows.entries()) {
- if (parseFactor(row.price_factor) === null) {
- setError(`第 ${index + 1} 条出口「${row.exit_name}」的计费系数须为大于 0 且不超过 1 的数(最多两位小数)。`);
- return;
- }
- }
- setSaving(true);
- setError("");
- try {
- const result = await lineExitSave({
- items: rows.map((row) => ({ exit_name: row.exit_name, price_factor: Number(row.price_factor) })),
- });
- const next = (result.items ?? []).map((item) => ({
- exit_name: item.exit_name,
- price_factor: String(item.price_factor ?? 1),
- }));
- setDraft(next);
- onNotice(`线路出口已保存(${next.length} 条)。`);
- exits.reload();
- } catch (e) {
- setError(e instanceof ApiError ? e.message : "线路出口保存失败,请稍后重试。");
- } finally {
- setSaving(false);
- }
- }
- return <section className="catalog-resource" aria-labelledby="catalog-exit-heading">
- <div className="catalog-resource-heading">
- <div><h2 id="catalog-exit-heading">线路出口清单</h2><p>维护合同可选的国家或地区及对应计费系数。</p></div>
- {!exits.error && !(exits.loading && draft === null) && <span className="catalog-exits-count"><b>{rows.length}</b> 条</span>}
- </div>
- {writable && <div className="catalog-resource-controls">
- <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(); } }} />
- <Button variant="outline" size="sm" onClick={add}><Plus size={15} />添加</Button>
- <Button size="sm" disabled={!dirty || saving} onClick={save}>{saving ? "保存中…" : "保存出口清单"}</Button>
- </div>}
- <div className="catalog-exits-body">
- <div className="catalog-exits-list">
- {exits.error ? <Tri tone="fail" text={WORD_FETCH_FAILED} title={exits.error.message} />
- : exits.loading && draft === null ? <Tri tone="missing" text="正在载入…" />
- : rows.length ? rows.map((row, index) => {
- const refCount = refOf(row.exit_name)?.ref_count ?? 0;
- return <div key={`${exitKey(row.exit_name)}-${index}`} className="catalog-exit-row">
- <span className="catalog-exit-name">{row.exit_name}</span>
- <label className="catalog-exits-factor">
- <span>计费系数</span>
- <input
- aria-label={`${row.exit_name} 计费系数`}
- type="number"
- min={0.01}
- max={1}
- step={0.01}
- inputMode="decimal"
- disabled={!writable}
- readOnly={!writable}
- aria-invalid={writable && parseFactor(row.price_factor) === null ? true : undefined}
- value={row.price_factor}
- onChange={(event) => { if (!writable) return; setFactor(index, event.target.value); }}
- title="计费系数,默认 1,取值大于 0 且不超过 1(两位小数);最终订阅价=档位价×系数"
- />
- </label>
- {refCount > 0 && <small className="catalog-exits-ref" title={refOf(row.exit_name)?.ref_summary}>{`被 ${refCount} 处引用`}</small>}
- {writable && (refCount > 0
- ? <button type="button" className="is-locked" aria-label={`${row.exit_name} 已被引用,不能删除`} title={`${refOf(row.exit_name)?.ref_summary || "已被业务数据"}引用,不能删除;请先到合同/订阅侧处理引用`} disabled><LockKeyhole size={15} /></button>
- : <button type="button" aria-label={`删除线路出口 ${row.exit_name}`} title="删除需二次输入确认" onClick={() => askRemove(index)}><X size={15} /></button>)}
- </div>;
- })
- : <Tri tone="missing" text="尚未配置线路出口" />}
- </div>
- {error && <p className="catalog-editor-error" role="alert">{error}</p>}
- {!writable && <p className="catalog-resource-note">线路出口由总运营或运营主账号维护。</p>}
- <details className="catalog-resource-guide">
- <summary>计费与引用规则</summary>
- <p>合同条目按清单顺序列出可选出口。计费系数默认 1,取值大于 0 且不超过 1,最多两位小数。订阅价按档位价乘以系数计算,调整系数只影响后续定价。工单竣工按合同条目的核定出口回填。</p>
- <p>合同、存量 IP 备案、派生档或订阅引用中的出口不可删除。删除未引用出口需输入原名称确认,保存后整份清单生效。</p>
- </details>
- </div>
- {confirm && <div className="catalog-confirm-backdrop"><div className="catalog-confirm" role="alertdialog" aria-modal="true" aria-labelledby="catalog-exit-confirm-title">
- <span className="catalog-confirm-icon"><Trash2 size={20} /></span>
- <h2 id="catalog-exit-confirm-title">删除线路出口?</h2>
- <p>「{confirm.name}」将从出口清单移除(<strong>保存出口清单</strong>后生效)。请手打出口名称确认本次删除。</p>
- <label className="catalog-confirm-input">确认出口名称
- <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(); } }} />
- </label>
- <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>
- </div></div>}
- </section>;
- }
- /** 带宽档位目录(2026-11-16 业主裁定,2026-11-17 改用途)。
- * ⚠️ 2026-11-17:合同「固定 IP 条目」已下线 ⇒ 本清单改为**套餐带宽权益录入的快捷预设**
- * (固定档/自定义档编辑器的「03 带宽与权益」一键带出上/下行),另兼「存量 IP 备案的历史引用」;
- * 合同侧不再选择档位,第 5 册回填的 5/10/30 与本清单**互不约束**。 */
- const TIER_NAME_MAX = 64;
- /** 与后端 `ip_bandwidth_tier::TIER_MBPS_MAX`/套餐档 `BW_MAX` 对齐(D-PKG-19/R-2)。 */
- const TIER_MBPS_MAX = 1000;
- /** 档位语义键(与后端 `ip_bandwidth_tier::tier_key` 同口径):兆数决定键,名称只是展示。 */
- const tierKeyOf = (mbps: number | null) => (mbps === null ? IP_TIER_UNCOMMITTED : `mbps-${mbps}`);
- /** 名称去重键=去空白+小写(与后端/线路出口同纪律)。 */
- const tierNameKeyOf = (name: string) => name.replace(/\s+/g, "").toLowerCase();
- /** 名称「N 兆」与兆数一致性(D-PKG-21);自由文案返回 null。 */
- function parseMbpsLabel(name: string): number | null {
- const m = name.replace(/\s+/g, "").match(/^(\d+)兆$/);
- if (!m) return null;
- const n = Number(m[1]);
- return Number.isInteger(n) ? n : null;
- }
- type TierDraft = { tier_name: string; bandwidth_tier_mbps: number | null };
- function BandwidthTierPanel({ writable, tiers, onNotice }: { writable: boolean; tiers: Load<IpBandwidthTierListResult>; onNotice: (message: string) => void }) {
- const [draft, setDraft] = useState<TierDraft[] | null>(null);
- const [name, setName] = useState("");
- const [mbps, setMbps] = useState("");
- const [error, setError] = useState("");
- const [saving, setSaving] = useState(false);
- /** 删除二次确认:与出口同一口径——有引用的不许删,没引用的也要手打名称确认。 */
- const [confirm, setConfirm] = useState<{ index: number; name: string; typed: string } | null>(null);
- useEffect(() => {
- if (draft === null && tiers.data) {
- setDraft(tiers.data.items.map((item) => ({ tier_name: item.tier_name, bandwidth_tier_mbps: item.bandwidth_tier_mbps })));
- }
- }, [tiers.data, draft]);
- const savedItems = tiers.data?.items ?? [];
- const saved: TierDraft[] = savedItems.map((item) => ({ tier_name: item.tier_name, bandwidth_tier_mbps: item.bandwidth_tier_mbps }));
- const rows = draft ?? saved;
- const refOf = (mbpsValue: number | null) => savedItems.find((item) => tierKeyOf(item.bandwidth_tier_mbps ?? null) === tierKeyOf(mbpsValue));
- const dirty = draft !== null && JSON.stringify(draft) !== JSON.stringify(saved);
- function add() {
- if (!writable) return;
- const tierName = name.trim();
- if (!tierName) { setError("请先输入档位名称(如「10 兆」「不承诺带宽」)。"); return; }
- if (tierName.length > TIER_NAME_MAX) { setError(`档位名称最多 ${TIER_NAME_MAX} 字。`); return; }
- const raw = mbps.trim();
- let value: number | null = null;
- if (raw) {
- const n = Number(raw);
- if (!Number.isInteger(n) || n < 1 || n > TIER_MBPS_MAX) { setError(`兆数须为 1–${TIER_MBPS_MAX} 的整数;留空=不承诺带宽。`); return; }
- value = n;
- }
- const encoded = parseMbpsLabel(tierName);
- if (value !== null && encoded !== null && encoded !== value) {
- setError(`档位名「${tierName}」与兆数 ${value} 不一致(名实须同源)。`);
- return;
- }
- const key = tierKeyOf(value);
- if (rows.some((row) => tierKeyOf(row.bandwidth_tier_mbps) === key)) {
- setError(value === null ? "「不承诺带宽」只能有一条。" : `已有 ${value} 兆的档位(同一兆数只允许一条)。`);
- return;
- }
- const nameKey = tierNameKeyOf(tierName);
- if (rows.some((row) => tierNameKeyOf(row.tier_name) === nameKey)) {
- setError(`带宽档位名称重复(空白与大小写不区分):${tierName}`);
- return;
- }
- setDraft([...rows, { tier_name: tierName, bandwidth_tier_mbps: value }]);
- setName("");
- setMbps("");
- setError("");
- }
- function rename(index: number, value: string) {
- setDraft((current) => (current ?? saved).map((row, i) => (i === index ? { ...row, tier_name: value } : row)));
- }
- function askRemove(index: number) {
- if (!writable) return;
- const row = rows[index];
- if (!row) return;
- const ref = refOf(row.bandwidth_tier_mbps);
- if ((ref?.ref_count ?? 0) > 0) {
- setError(`「${row.tier_name}」仍被 ${ref?.ref_summary || "存量 IP 备案"}引用,不能删除;该表已停写,只能由运维清理历史行后再删档位。`);
- return;
- }
- setError("");
- setConfirm({ index, name: row.tier_name, typed: "" });
- }
- function confirmRemove() {
- if (!confirm) return;
- if (confirm.typed.trim() !== confirm.name.trim()) return;
- setDraft((current) => (current ?? saved).filter((_, i) => i !== confirm.index));
- setConfirm(null);
- setError("");
- }
- async function save() {
- if (!writable || saving) return;
- const blank = rows.findIndex((row) => !row.tier_name.trim());
- if (blank >= 0) { setError(`第 ${blank + 1} 条档位名称为空,请补齐名称后再保存。`); return; }
- const nameKeys = new Set<string>();
- for (let i = 0; i < rows.length; i += 1) {
- const row = rows[i];
- const nk = tierNameKeyOf(row.tier_name.trim());
- if (nameKeys.has(nk)) { setError(`带宽档位名称重复(空白与大小写不区分):${row.tier_name.trim()}`); return; }
- nameKeys.add(nk);
- const encoded = parseMbpsLabel(row.tier_name.trim());
- if (row.bandwidth_tier_mbps !== null && encoded !== null && encoded !== row.bandwidth_tier_mbps) {
- setError(`第 ${i + 1} 条档位名「${row.tier_name.trim()}」与兆数 ${row.bandwidth_tier_mbps} 不一致(名实须同源)。`);
- return;
- }
- }
- setSaving(true);
- setError("");
- try {
- const result = await ipBandwidthTierSave({
- items: rows.map((row) => ({ tier_name: row.tier_name.trim(), bandwidth_tier_mbps: row.bandwidth_tier_mbps })),
- });
- const next = (result.items ?? []).map((item) => ({ tier_name: item.tier_name, bandwidth_tier_mbps: item.bandwidth_tier_mbps }));
- setDraft(next);
- onNotice(`带宽档位已保存(${next.length} 条)。`);
- tiers.reload();
- } catch (e) {
- setError(e instanceof ApiError ? e.message : "带宽档位保存失败,请稍后重试。");
- } finally {
- setSaving(false);
- }
- }
- return <section className="catalog-resource" aria-labelledby="catalog-tier-heading">
- <div className="catalog-resource-heading">
- <div><h2 id="catalog-tier-heading">带宽档位</h2><p>设置套餐编辑时可直接选用的带宽预设。</p></div>
- {!tiers.error && !(tiers.loading && draft === null) && <span className="catalog-exits-count"><b>{rows.length}</b> 档</span>}
- </div>
- {writable && <div className="catalog-resource-controls">
- <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(); } }} />
- <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(); } }} />
- <Button variant="outline" size="sm" onClick={add}><Plus size={15} />添加</Button>
- <Button size="sm" disabled={!dirty || saving} onClick={save}>{saving ? "保存中…" : "保存档位清单"}</Button>
- </div>}
- <div className="catalog-exits-body">
- <div className="catalog-tier-list">
- {tiers.error ? <Tri tone="fail" text={WORD_FETCH_FAILED} title={tiers.error.message} />
- : tiers.loading && draft === null ? <Tri tone="missing" text="正在载入…" />
- : rows.length ? rows.map((row, index) => {
- const ref = refOf(row.bandwidth_tier_mbps);
- const refCount = ref?.ref_count ?? 0;
- return <div key={tierKeyOf(row.bandwidth_tier_mbps)} className="catalog-tier-row">
- {writable
- ? <input aria-label={`档位名称 ${index + 1}`} className="catalog-tier-rename" value={row.tier_name} maxLength={TIER_NAME_MAX} onChange={(event) => rename(index, event.target.value)} />
- : <span className="catalog-tier-name">{row.tier_name}</span>}
- <small className="catalog-tier-mbps">{row.bandwidth_tier_mbps === null ? "不承诺带宽" : `${row.bandwidth_tier_mbps} 兆`}</small>
- {refCount > 0 && <small className="catalog-exits-ref" title={ref?.ref_summary ?? undefined}>{`被 ${refCount} 处引用`}</small>}
- {writable && (refCount > 0
- ? <button type="button" className="is-locked" aria-label={`${row.tier_name} 已被引用,不能删除`} title={`${ref?.ref_summary || "已被存量 IP 备案"}引用,不能删除;该表已停写,需运维清理历史行后再删`} disabled><LockKeyhole size={15} /></button>
- : <button type="button" aria-label={`删除档位 ${row.tier_name}`} title="删除需二次输入确认" onClick={() => askRemove(index)}><X size={15} /></button>)}
- </div>;
- })
- : <Tri tone="missing" text="尚未配置带宽档位" />}
- </div>
- {error && <p className="catalog-editor-error" role="alert">{error}</p>}
- {!writable && <p className="catalog-resource-note">带宽档位由总运营或运营主账号维护。</p>}
- <details className="catalog-resource-guide">
- <summary>档位取值与引用规则</summary>
- <p>套餐编辑器按清单顺序提供预设。兆数取值 1–{TIER_MBPS_MAX},同一兆数只能配置一条,留空表示不承诺带宽。工单施工回填仍使用 5、10、30 兆三个固定值。</p>
- <p>存量 IP 备案引用中的档位不可删除。删除未引用档位需输入原名称确认,保存后整份清单生效。</p>
- </details>
- </div>
- {confirm && <div className="catalog-confirm-backdrop"><div className="catalog-confirm" role="alertdialog" aria-modal="true" aria-labelledby="catalog-tier-confirm-title">
- <span className="catalog-confirm-icon"><Trash2 size={20} /></span>
- <h2 id="catalog-tier-confirm-title">删除带宽档位?</h2>
- <p>「{confirm.name}」将从档位清单移除(<strong>保存档位清单</strong>后生效)。请手打档位名称确认本次删除。</p>
- <label className="catalog-confirm-input">确认档位名称
- <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(); } }} />
- </label>
- <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>
- </div></div>}
- </section>;
- }
- export function PackageManagementPage() {
- const { state } = useLocation();
- const back = detailBack(state, "/packages", "返回套餐配置");
- /** 03 章 §3.4 权限三档:固定档写入口=总运营专属;运营主账号只配客户专属档;其余角色只读且不出入口。
- * `opsMain`/`opsSub` 在 session 均映成 `regAdmin`,差异只由 `primary` 承载(D-PKG-16)⇒
- * 自定义档写入口必须与 `canWriteExits` 同式,⛔ 把子账号放成可点的写按钮。 */
- const identity = useDemoIdentity();
- const canWrite = !identity || identity.role === "admin" || (identity.role === "regAdmin" && Boolean(identity.primary));
- const canWriteFixed = !identity || identity.role === "admin";
- /** 线路出口是全局清单,后端只放行总运营/运营主账号(opsSub 同属 regAdmin 但⛔ 可写,见 session ROLE_TO_DEMO)。 */
- const canWriteExits = !identity || identity.role === "admin" || (identity.role === "regAdmin" && Boolean(identity.primary));
- /** 三视图:固定套餐/自定义套餐/线路出口(2026-11-15 收口,原型同形)。 */
- const [tab, setTab] = useState<CatalogTab>("fixed");
- const [category, setCategory] = useState<string>("all");
- const [search, setSearch] = useState("");
- /** R-14 台账收敛:自定义档按建档团队/建档人筛选——**服务端谓词**(`"all"` = 不加谓词)。
- * 选项取同一响应的 `facets`(服务端在 base ∧ custom 上聚合),⛔ 用当前页行凑。 */
- const [createdTeam, setCreatedTeam] = useState<string>("all");
- const [createdBy, setCreatedBy] = useState<string>("all");
- /** 关键字下发服务端:短防抖,避免每敲一字打一次列表。 */
- const [searchQuery, setSearchQuery] = useState("");
- useEffect(() => {
- const timer = window.setTimeout(() => setSearchQuery(search.trim()), 300);
- return () => window.clearTimeout(timer);
- }, [search]);
- const isCustomTab = tab === "custom";
- const [ledgerPage, setLedgerPage] = useState(0);
- const catalog = useCatalogLedger({
- enabled: tab !== "exits",
- planKind: isCustomTab ? "custom" : "fixed",
- planFamily: !isCustomTab && category !== "all" ? category : undefined,
- keyword: searchQuery || undefined,
- createdBy: isCustomTab && createdBy !== "all" ? createdBy : undefined,
- createdTeamId: isCustomTab && createdTeam !== "all" ? createdTeam : undefined,
- page: ledgerPage,
- pageSize: LIST_PAGE_SIZE,
- });
- const [editor, setEditor] = useState<EditorState | null>(null);
- /** 线路出口/带宽档:仅 exits tab 预拉;编辑器打开时再拉带宽预设(⛔ 进页三请求)。 */
- const exits = useLineExits({ enabled: tab === "exits" });
- const tiers = useIpBandwidthTiers({ enabled: tab === "exits" || editor !== null });
- /**
- * 切 fixed/custom 时 useLoad 会短暂保留上一档应答(reload 不闪 loading)。
- * 只画与当前 tab 同 `plan_kind` 的行;异种旧行一律丢掉,⛔ 闪成「假 mock」。
- */
- const expectKind = isCustomTab ? "custom" : "fixed";
- const rawItems = catalog.data?.items;
- const dataMatchesTab = !catalog.data
- || !rawItems?.length
- || rawItems.every((plan) => plan.plan_kind === expectKind);
- const rows = useMemo(
- () => (dataMatchesTab && rawItems ? rawItems.filter((plan) => plan.plan_kind === expectKind) : []),
- [rawItems, dataMatchesTab, expectKind],
- );
- const awaitingTab = tab !== "exits" && (catalog.loading || !dataMatchesTab);
- const facets = dataMatchesTab ? catalog.data?.facets : undefined;
- const teamOptions = facets?.created_team ?? [];
- const creatorOptions = facets?.created_by ?? [];
- const [deleteTarget, setDeleteTarget] = useState<CatalogPlanRow | null>(null);
- /** K205 拦截后的两栏引用明细:服务端 `blocks.subscriptions`/`blocks.items`(wire 键仍叫 subscriptions)。 */
- const [deleteBlocks, setDeleteBlocks] = useState<{ orders: string[]; items: string[] } | null>(null);
- const [deleteError, setDeleteError] = useState("");
- const [notice, setNotice] = useState("");
- const [failure, setFailure] = useState("");
- const [deleting, setDeleting] = useState(false);
- /** 成功提示到点自动收起(⛔ 挂着等用户点关闭);换新文案重新计时,`failure` 是错误提示,⛔ 自动消失。 */
- useEffect(() => {
- if (!notice) return;
- const timer = window.setTimeout(() => setNotice(""), NOTICE_DISMISS_MS);
- return () => window.clearTimeout(timer);
- }, [notice]);
- /** 自定义档多「建档人/建档团队」两列;固定档仍 9 列。 */
- const ledgerColSpan = isCustomTab ? 11 : 9;
- const visible = rows;
- const kindTotals = catalog.data?.kind_totals;
- const fixedCount = kindTotals?.fixed ?? (catalog.data ? 0 : "—");
- const customCount = kindTotals?.custom ?? (catalog.data ? 0 : "—");
- const listTotal = dataMatchesTab ? Number(catalog.data?.total ?? visible.length) : 0;
- const paging = useLocalPage(listTotal, LIST_PAGE_SIZE, ledgerPage);
- const pageRows = visible;
- const setPage = (next: number) => setLedgerPage(Math.max(0, next));
- const resetPage = () => setLedgerPage(0);
- /** 固定套餐按用途分类分组,分组行落在表体内;后端不下发 use_category 的档位单列一组,⛔ 静默丢行。
- * 序号取「表内显示顺序」(分组后位置),⛔ 用后端数组下标——否则分组一排序就出现 7 在 6 前面。 */
- const fixedGroups = useMemo(() => {
- const familyOf = (plan: CatalogPlanRow) => plan.plan_family;
- const known = planFamilies
- .map((item) => ({ name: item.name as string, hint: `${orderModeOf(item.code)} · ${item.hint}`, plans: pageRows.filter((plan) => familyOf(plan) === item.code) }))
- .filter((group) => group.plans.length > 0);
- const uncategorized = pageRows.filter((plan) => !planFamilies.some((item) => item.code === familyOf(plan)));
- const groups = uncategorized.length ? [...known, { name: WORD_UNCONFIGURED, hint: `交付形态:${WORD_NOT_PROVIDED}`, plans: uncategorized }] : known;
- let position = 0;
- return groups.map((group) => ({ name: group.name, hint: group.hint, entries: group.plans.map((plan) => ({ plan, position: position++ })) }));
- }, [pageRows]);
- function resetFilters() {
- setCategory("all");
- setSearch("");
- setCreatedTeam("all");
- setCreatedBy("all");
- resetPage();
- }
- function switchTab(next: CatalogTab) {
- setTab(next);
- // 建档人/团队谓词只在自定义档 Tab 生效;切走时一并复位,免得回来时看到一个「隐形」的过滤条件。
- setCreatedTeam("all");
- setCreatedBy("all");
- resetPage();
- }
- function saved(message: string, plan: CatalogPlanRow | null) {
- setEditor(null);
- if (plan) setTab(plan.plan_kind === "custom" ? "custom" : "fixed");
- setCategory("all");
- setSearch("");
- setCreatedTeam("all");
- setCreatedBy("all");
- resetPage();
- setFailure("");
- setNotice(message);
- catalog.reload();
- }
- const rowIndexBase = ledgerPage * paging.pageSize;
- async function remove() {
- if (!deleteTarget) return;
- setDeleting(true);
- try {
- const result = await catalogDelete({ plan_id: deleteTarget.plan_id });
- setDeleteTarget(null);
- setDeleteBlocks(null);
- setDeleteError("");
- setFailure("");
- setNotice(result?.deleted ? `${deleteTarget.plan_name}已删除。` : `未能删除:${result?.suggest ?? "该档位已被合同条目或订阅引用"}`);
- catalog.reload();
- } catch (e) {
- const detail = e instanceof ApiError ? (e.detail as { blocks?: { subscriptions?: unknown; items?: unknown } } | undefined) : undefined;
- const orders = Array.isArray(detail?.blocks?.subscriptions) ? detail!.blocks!.subscriptions!.map(String) : [];
- const items = Array.isArray(detail?.blocks?.items) ? detail!.blocks!.items!.map(String) : [];
- setNotice("");
- setFailure("");
- if (orders.length || items.length) {
- /** K205 两栏:确认框留在原位转成引用清单(订阅/合同条目),⛔ 只弹一句 toast 把份数丢掉。 */
- setDeleteError(e instanceof ApiError ? e.message : "该套餐档位已被引用,不能删除。");
- setDeleteBlocks({ orders, items });
- } else {
- setDeleteTarget(null);
- setDeleteBlocks(null);
- setDeleteError("");
- setFailure(e instanceof ApiError ? e.message : "删除失败,请稍后重试。");
- }
- } finally {
- setDeleting(false);
- }
- }
- function closeDelete() {
- setDeleteTarget(null);
- setDeleteBlocks(null);
- setDeleteError("");
- }
- const canCreate = isCustomTab ? canWrite : canWriteFixed;
- const readOnlyNote = isCustomTab ? "自定义套餐由总运营或运营主账号维护。" : OPERATOR_ONLY_CONFIG;
- const planRow = (plan: CatalogPlanRow, position: number) => <PlanRow
- key={plan.plan_id}
- plan={plan}
- index={rowIndexBase + position + 1}
- custom={isCustomTab}
- writable={canCreate}
- readOnlyNote={readOnlyNote}
- onEdit={() => setEditor({ plan, owner: isCustomTab ? plan.customer_id ?? "" : null })}
- onDelete={() => { setDeleteError(""); setDeleteBlocks(null); setDeleteTarget(plan); }}
- />;
- const hasFilters = Boolean(search || (isCustomTab ? createdBy !== "all" || createdTeam !== "all" : category !== "all"));
- const tabs = [
- { id: "fixed", title: "固定套餐", description: "签约时均可选用的公共档位", icon: Layers3, count: catalog.error ? "—" : fixedCount },
- { id: "custom", title: "自定义套餐", description: "归属指定客户的专属档位", icon: SlidersHorizontal, count: catalog.error ? "—" : customCount },
- { id: "exits", title: "线路出口", description: "出口清单与带宽预设", icon: Globe2, count: !exits.error && exits.data ? exits.data.items.length : "—" },
- ] as const;
- const emptyMessage = catalog.error
- ? `无法加载套餐:${catalog.error.message}`
- : awaitingTab
- ? "正在加载套餐…"
- : hasFilters
- ? "没有符合筛选条件的套餐档,可重置筛选后再看。"
- : tab === "custom" ? "目录里还没有自定义套餐档。" : "目录里还没有固定套餐档。";
- return <section className="ops-page ops-page--packages package-catalog">
- {back.to !== "/packages" && <Link className="ops-back-link" to={back.to} state={back.state}><ArrowLeft size={16} aria-hidden="true" />{back.label}</Link>}
- <header className="catalog-page-head">
- <h1>套餐配置</h1>
- <PageIntro>管理签约可选的套餐、订阅价格和交付配置。</PageIntro>
- </header>
- <RecordTabs prefix="catalog" className="catalog-tabs" label="套餐配置视图" active={tab} onChange={switchTab}
- tabs={tabs.map(({ id, title, description, count, icon: Icon }) => ({
- id, count, label: <>
- <span className="catalog-tab-icon"><Icon size={18} aria-hidden="true" /></span>
- <span className="catalog-tab-copy"><strong>{title}</strong><small>{description}</small></span>
- </>,
- }))}
- />
- {tabs.filter(({ id }) => id !== tab).map(({ id }) => (
- <div key={id} id={`catalog-panel-${id}`} role="tabpanel" aria-labelledby={`catalog-tab-${id}`} hidden />
- ))}
- {tab === "exits"
- ? <div id="catalog-panel-exits" role="tabpanel" aria-labelledby="catalog-tab-exits" className="catalog-exits-panel">
- <LineExitPanel writable={canWriteExits} exits={exits} onNotice={(message) => { setFailure(""); setNotice(message); }} />
- <BandwidthTierPanel writable={canWriteExits} tiers={tiers} onNotice={(message) => { setFailure(""); setNotice(message); }} />
- </div>
- : <div id={`catalog-panel-${tab}`} role="tabpanel" aria-labelledby={`catalog-tab-${tab}`} className="catalog-tabpanel">
- <div className="catalog-ledger-toolbar">
- <div className="catalog-filters">
- <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>
- {/* 自定义档恒为「定制化」,没有可选项 ⇒ 该 Tab 不出分类筛选(⛔ 给一个筛完必空的控件)。 */}
- {!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>}
- {/* R-14:自定义档越滚越多 ⇒ 按建档团队/建档人收敛。选项取服务端 facets,⛔ 当前页行。
- 固定档不提供(共享目录,不是谁的台账)。 */}
- {isCustomTab && <>
- <FilterSelect icon="task" aria-label="建档团队筛选" value={createdTeam} onChange={(event) => { setCreatedTeam(event.target.value); resetPage(); }}>
- <option value="all">全部建档团队</option>
- {teamOptions.map((item) => <option key={item.value} value={item.value}>{item.label}({item.count})</option>)}
- </FilterSelect>
- <FilterSelect icon="assignment" aria-label="建档人筛选" value={createdBy} onChange={(event) => { setCreatedBy(event.target.value); resetPage(); }}>
- <option value="all">全部建档人</option>
- {creatorOptions.map((item) => <option key={item.value} value={item.value}>{item.label}({item.count})</option>)}
- </FilterSelect>
- </>}
- {hasFilters && <Button variant="ghost" size="sm" onClick={resetFilters}>重置筛选</Button>}
- </div>
- {canCreate ? (
- <button type="button" className="catalog-button catalog-button-primary" onClick={() => setEditor(isCustomTab ? { owner: "", planKind: "custom" } : { owner: null })}>
- <Plus size={16} aria-hidden="true" />{isCustomTab ? "新增自定义套餐" : "新增固定套餐"}
- </button>
- ) : <span className="catalog-head-note"><LockKeyhole size={14} aria-hidden="true" />{readOnlyNote}</span>}
- </div>
- <div tabIndex={0} role="region" aria-label="套餐档位列表" className="ops-table-wrap catalog-table-wrap">
- <table role="table" className={`ops-table catalog-ledger${isCustomTab ? " catalog-ledger-custom" : ""}`} aria-busy={awaitingTab && !catalog.error}>
- <OpsTableColumns widths={isCustomTab ? CUSTOM_PLAN_COLUMNS : PLAN_COLUMNS} />
- <thead role="rowgroup"><tr role="row">{[
- "序号", "套餐", "年订阅价格", "月结算标准", "月成本", "分账号额度", "总带宽", "订阅量",
- ...(isCustomTab ? ["建档人", "建档团队"] : []),
- "操作",
- ].map((column) => <th role="columnheader" scope="col" key={column}>{column}</th>)}</tr></thead>
- <tbody role="rowgroup">
- {tab === "fixed"
- ? 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>)
- : pageRows.map((plan, index) => planRow(plan, index))}
- {(catalog.error || visible.length === 0) && <OpsTableEmpty colSpan={ledgerColSpan}>
- <div className="catalog-empty"><span>{emptyMessage}</span>{catalog.error && <Button variant="outline" size="sm" onClick={catalog.reload}>重试</Button>}</div>
- </OpsTableEmpty>}
- </tbody>
- </table>
- </div>
- <ListPager total={listTotal} page={paging.safePage} pageSize={paging.pageSize} onPageChange={setPage} unit="档" />
- </div>}
- {notice && <div className="catalog-toast" role="status"><span>{notice}</span><button aria-label="关闭提示" onClick={() => setNotice("")}><X size={16} /></button></div>}
- {failure && <div className="catalog-toast" role="alert"><span>{failure}</span><button aria-label="关闭提示" onClick={() => setFailure("")}><X size={16} /></button></div>}
- {editor && <PackagePlanEditor key={editor.plan?.plan_id ?? `new-${editor.owner ?? "fixed"}`} state={editor} tiers={tiers} onClose={() => setEditor(null)} onSaved={saved} />}
- {deleteTarget && <div className="catalog-confirm-backdrop"><div className="catalog-confirm" role="alertdialog" aria-modal="true" aria-labelledby="catalog-confirm-title">
- {deleteError
- ? <><span className="catalog-confirm-icon"><Trash2 size={20} /></span><h2 id="catalog-confirm-title">无法删除该套餐档位</h2><p>{deleteError}</p>
- {deleteBlocks && <div className="catalog-confirm-blocks">
- <div><h3>{`引用该档位的订阅(${deleteBlocks.orders.length})`}</h3>{deleteBlocks.orders.length ? <ul>{deleteBlocks.orders.map((id) => <li key={id}>{id}</li>)}</ul> : <small>无</small>}</div>
- <div><h3>{`引用该档位的合同条目(${deleteBlocks.items.length})`}</h3>{deleteBlocks.items.length ? <ul>{deleteBlocks.items.map((id) => <li key={id}>{id}</li>)}</ul> : <small>无</small>}</div>
- </div>}
- <div><button type="button" className="catalog-button catalog-button-secondary" onClick={closeDelete}>关闭</button></div></>
- : <><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></>}
- </div></div>}
- </section>;
- }
|