import { useEffect, useId, useMemo, useState, type FormEvent } from "react"; import { FieldHint } from "./ui/field-hint"; import { LockKeyhole, Plus, X } from "lucide-react"; import { FetchError } from "./fetchError"; import { planLockedFieldLabels, PLAN_COST_ITEM_SAVE_NOTE, WORD_FETCH_FAILED } from "../lib/api/lockedCopy"; import { catalogCreate, catalogCustomerOptions, catalogUpdate, planCostItemList, planCostItemSave, rowsOf } from "../lib/api/bos"; import type { CatalogPlanRow, IpBandwidthTierListResult, PlanCostItemRow } from "../lib/api/types"; import { ApiError } from "../lib/api/http"; import { useLoad, type Load } from "../lib/useLoad"; import { COST_BILLING_UNIT, COST_CATEGORY, PLAN_FAMILY } from "../lib/api/labels"; import { IP_TIER_UNCOMMITTED } from "../domain/contract-items"; /** 目录档位编辑器(套餐页新增/编辑与合同页「就地新建本客户自定义档」共用)。 */ export type EditorState = { plan?: CatalogPlanRow; owner: string | null; planKind?: "fixed" | "custom"; lockOwner?: boolean }; export type EditorValues = { name: string; family: string; owner: string; annualPrice: string; quota: string; bandwidthMode: "committed" | "uncommitted" | ""; upload: string; download: string; description: string; }; /** 成本项行=`plan_cost_item` 真实字段面(⛔ 本地「份数」口径,后端无该列)。 */ type CostDraft = { item_name: string; amount: string; billing_unit: string; category: string; remark: string }; /** 与后端 `COST_ITEMS_MAX`/openapi `maxItems: 50` 对齐。 */ const COST_ITEMS_MAX = 50; /** 与后端 `NAME_MAX`/`QUOTA_MAX` 对齐。 */ const PLAN_NAME_MAX = 128; const QUOTA_MAX = 9999; const BILLING_OPTIONS = Object.entries(COST_BILLING_UNIT); const CATEGORY_OPTIONS = Object.entries(COST_CATEGORY); const costDraftOf = (row: PlanCostItemRow): CostDraft => ({ item_name: row.item_name ?? "", amount: row.amount_cents === null || row.amount_cents === undefined ? "" : String(row.amount_cents / 100), billing_unit: row.billing_unit ?? "", category: row.category ?? "", remark: row.remark ?? "", }); const costRowOf = (draft: CostDraft): PlanCostItemRow => ({ item_name: draft.item_name.trim(), amount_cents: draft.amount.trim() === "" ? null : Math.round(Number(draft.amount) * 100), billing_unit: draft.billing_unit.trim() || null, category: draft.category.trim() || null, remark: draft.remark.trim() || null, }); const emptyCost = (): CostDraft => ({ item_name: "", amount: "", billing_unit: "", category: "", remark: "" }); export function formOf(plan: CatalogPlanRow | undefined, owner: string | null): EditorValues { const committed = plan?.bandwidth_committed; const up = plan?.bandwidth_up_mbps; const down = plan?.bandwidth_down_mbps; /** 存量 DEFAULT TRUE + 上下行空:按「不承诺」回显,⛔ 开成承诺态却两格空白。 */ const bandwidthMode: EditorValues["bandwidthMode"] = committed === undefined || committed === null ? "" : committed && up != null && down != null ? "committed" : "uncommitted"; return { name: plan?.plan_name ?? "", family: plan?.plan_family ?? (owner === null ? "link" : ""), owner: plan?.customer_id ?? owner ?? "", annualPrice: plan?.annual_price_cents === undefined || plan.annual_price_cents === null ? "" : String(plan.annual_price_cents / 100), quota: plan?.sub_account_quota === undefined || plan.sub_account_quota === null ? "" : String(plan.sub_account_quota), bandwidthMode, upload: up === null || up === undefined ? "" : String(up), download: down === null || down === undefined ? "" : String(down), description: plan?.plan_desc ?? "", }; } const tierKeyOf = (mbps: number | null) => (mbps === null ? IP_TIER_UNCOMMITTED : `mbps-${mbps}`); function CatalogInfo({ label, children }: { label: string; children: string }) { return {children}; } export function PackagePlanEditor({ state, tiers, onClose, onSaved }: { state: EditorState; tiers: Load; onClose: () => void; onSaved: (message: string, savedPlan: CatalogPlanRow | null) => void; }) { const original = state.plan; /** 锁定:被引用冻结(K204);页面放开名称/说明/成本项,服务端裁决后原样回显拒绝原因。 */ const locked = Boolean(original && original.frozen === true); const isCustom = original ? original.plan_kind === "custom" : (state.planKind ?? (state.owner === null ? "fixed" : "custom")) === "custom"; const ownerLocked = Boolean(state.lockOwner); const settlementId = useId(); const [values, setValues] = useState(() => formOf(original, state.owner)); const [costs, setCosts] = useState([]); const [costsDirty, setCostsDirty] = useState(false); const [error, setError] = useState(""); const costLoad = useLoad( () => (original ? planCostItemList({ plan_id: original.plan_id }).then(rowsOf) : Promise.resolve([] as PlanCostItemRow[])), [original?.plan_id], ); useEffect(() => { if (original && costLoad.data && !costsDirty) setCosts(costLoad.data.map(costDraftOf)); }, [costLoad.data, original, costsDirty]); useEffect(() => { const dialog = document.getElementById("catalog-editor") as HTMLDialogElement | null; const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; if (!dialog) return; const previousOverflow = document.body.style.overflow; document.body.style.overflow = "hidden"; dialog.showModal(); return () => { dialog.close(); document.body.style.overflow = previousOverflow; previous?.focus(); }; }, []); /** 归属客户可选项:后端下发的操作人可见客户集合,⛔ 前端拼权限。 */ const customerOptions = useLoad(() => catalogCustomerOptions().then(rowsOf), []); const field = (key: K, value: EditorValues[K]) => { setValues((current) => ({ ...current, [key]: value })); setError(""); }; /** 带宽档位快捷(2026-11-17 业主裁定):套餐配置里维护的档位即带宽权益的预设备选。 * 点一条=上下行同值填入;「不承诺带宽」档只切口径、⛔ 清空两格(同 CU-D5 的置灰不清空纪律)。 */ const tierPresets = useMemo(() => { const seen = new Set(); const rows: { key: string; label: string; mbps: number | null }[] = []; for (const item of tiers.data?.items ?? []) { const key = tierKeyOf(item.bandwidth_tier_mbps ?? null); if (seen.has(key)) continue; seen.add(key); rows.push({ key, label: item.bandwidth_tier_mbps === null ? "不承诺带宽" : item.tier_name || `${item.bandwidth_tier_mbps} 兆`, mbps: item.bandwidth_tier_mbps ?? null }); } return rows; }, [tiers.data]); const applyTier = (mbps: number | null) => { setValues((current) => mbps === null ? { ...current, bandwidthMode: "uncommitted" } : { ...current, bandwidthMode: "committed", upload: String(mbps), download: String(mbps) }); setError(""); }; async function submit(event: FormEvent) { event.preventDefault(); const name = values.name.trim(); const owner = state.owner === null ? null : values.owner; if (!name) { setError("请填写套餐名称。"); return; } if (owner !== null && !owner) { setError("请选择归属客户。"); return; } if (costLoad.error && costsDirty) { setError("成本项取数失败,整段保存会覆盖后端构成,请重试或放弃本次改动。"); return; } if (!values.family) { setError("请选择交付形态(跨境链路/叠加服务)。"); return; } const isLink = values.family === "link"; let annualPrice = 0; let quota = 0; let upload: number | null = null; let download: number | null = null; if (!locked) { if (!/^\d+(?:\.\d{1,2})?$/.test(values.annualPrice) || !Number.isFinite(Number(values.annualPrice)) || Number(values.annualPrice) < 0 || Number(values.annualPrice) > 10_000_000) { setError("年订阅价格需为非负金额。"); return; } annualPrice = Number(values.annualPrice); if (isLink) { if (!/^\d+$/.test(values.quota) || Number(values.quota) <= 0) { setError("跨境链路档的分账号额度须为正整数。"); return; } quota = Number(values.quota); if (quota > QUOTA_MAX) { setError(`分账号额度须在 1~${QUOTA_MAX} 之间。`); return; } if (values.bandwidthMode === "") { setError("请选择带宽口径(承诺或不承诺)。"); return; } if (values.bandwidthMode === "committed") { // 成对校验(D-PKG-05):缺格 ⇒ 指名填哪一向;越界 ⇒ 1–1000。 if (!values.upload.trim()) { setError("请填写上行带宽(承诺带宽时上下行须成对填写)。"); return; } if (!values.download.trim()) { setError("请填写下行带宽(承诺带宽时上下行须成对填写)。"); return; } upload = Number(values.upload); download = Number(values.download); if (!/^\d+$/.test(values.upload) || !/^\d+$/.test(values.download) || upload < 1 || upload > 1000 || download < 1 || download > 1000) { setError("上行和下行带宽须分别为 1–1000 Mbps 的整数。"); return; } } } else { // 叠加服务额度恒 0、不设任何带宽列(D-15/D-18)。 quota = 0; } } if (costs.length > COST_ITEMS_MAX) { setError(`成本项最多 ${COST_ITEMS_MAX} 条,请删减后重试。`); return; } if (costs.some((cost) => !cost.item_name.trim() || (cost.amount.trim() !== "" && !/^\d+(?:\.\d{1,2})?$/.test(cost.amount.trim())))) { setError("成本项需填写名称,金额留空表示未配置、否则为非负金额。"); return; } const costRows = costs.map(costRowOf); /** 契约:开关关闭⇒上行/下行两格⛔ 提交(服务端记 FALSE +两列 NULL)。 */ const bandwidth = isLink ? values.bandwidthMode === "committed" && upload !== null && download !== null ? { bandwidth_committed: true, bandwidth_up_mbps: upload, bandwidth_down_mbps: download } : { bandwidth_committed: false } : { bandwidth_committed: false }; try { if (!original) { const created = await catalogCreate({ plan_kind: owner === null ? "fixed" : "custom", plan_name: name, plan_family: values.family, annual_price_cents: Math.round(annualPrice * 100), sub_account_quota: quota, ...bandwidth, ...(owner ? { customer_id: owner } : {}), ...(values.description.trim() ? { plan_desc: values.description.trim() } : {}), ...(costRows.length ? { cost_items: costRows } : {}), }); /** 就地新建的调用方要拿新档继续填条目 ⇒ 回一份最小行(字段面与列表行同键)。 */ onSaved(`${name}已新建。`, { plan_id: created.plan_id, plan_name: name, plan_kind: owner === null ? "fixed" : "custom", plan_family: values.family, annual_price_cents: Math.round(annualPrice * 100), sub_account_quota: quota, bandwidth_committed: bandwidth.bandwidth_committed ? true : false, bandwidth_up_mbps: (bandwidth as { bandwidth_up_mbps?: number | null }).bandwidth_up_mbps ?? null, bandwidth_down_mbps: (bandwidth as { bandwidth_down_mbps?: number | null }).bandwidth_down_mbps ?? null, customer_id: owner || null, status: "active", created_at: "", row_version: "", }); return; } await catalogUpdate({ plan_id: original.plan_id, plan_name: name, plan_desc: values.description.trim(), ...(locked ? {} : { annual_price_cents: Math.round(annualPrice * 100), sub_account_quota: quota, ...bandwidth, }), ...(original.row_version === undefined || original.row_version === null || original.row_version === "" ? {} : { row_version: Number(original.row_version) }), }); if (costsDirty) await planCostItemSave({ plan_id: original.plan_id, items: costRows }); onSaved(`${name}已保存。`, original); } catch (e) { setError(e instanceof ApiError ? e.message : "保存失败,请稍后重试。"); } } const settlement = locked ? (original?.monthly_settle_cents === null || original?.monthly_settle_cents === undefined ? "" : String(original.monthly_settle_cents / 100)) : values.annualPrice && /^\d+(?:\.\d{1,2})?$/.test(values.annualPrice) ? (Math.floor(Math.round(Number(values.annualPrice) * 100) / 12) / 100).toFixed(2) : ""; const isLinkValue = values.family === "link"; const lockedLabels = planLockedFieldLabels(original?.locked_fields); return { if (event.target === event.currentTarget) onClose(); }}>
{isCustom ? "客户专属套餐" : "公共固定套餐"}

{original ? "编辑套餐档位" : "新增套餐档位"}

{locked &&

已被 {original?.referred_count ?? "—"} 处引用,字段「{lockedLabels.join("、")}」已锁定;调整价格或额度请新建档位,再升级订阅。

}

01 基本信息

{isCustom && }

02 价格与额度

年订阅价格除以 12 后向下取整到分。订阅签约时可按合同冻结价格。
{isLinkValue ? : }
{isLinkValue &&

03 带宽与权益

{/* 两格**常驻**、非承诺时置灰但⛔ 清空:卸载再挂载会让回切后输入框回读空串 (18 册 CU-D5),且 DOM 与 state 脱节。 */}
{!locked && tierPresets.length > 0 &&
档位快捷(取自「线路出口」Tab 的带宽档位)
{tierPresets.map((preset) => { const on = preset.mbps === null ? values.bandwidthMode === "uncommitted" : values.bandwidthMode === "committed" && values.upload.trim() === String(preset.mbps) && values.download.trim() === String(preset.mbps); return ; })}
}

带宽作为套餐属性保存,首期不按带宽拆分计价。

}

{isLinkValue ? "04" : "03"} 套餐说明