import { useBusinessView } from "../lib/use-business-view"; import { useEffect, useRef, useState, type FormEvent, type ReactNode } from "react"; import { ArrowLeft, ArrowRight, PencilLine, Plus, RefreshCw, Trash2, X } from "lucide-react"; import { Link, useLocation, useNavigate, useParams } from "react-router"; import { Button } from "../components/ui/button"; import { OpsMore, OpsNotice, OpsStatus, type OpsMoreItem } from "../components/OperationsKit"; import { Tri } from "../components/triState"; import { subscriptionView, useAllSubscriptions, type SubscriptionView } from "../lib/subscription-demo"; import { OPTIONS } from "../lib/api/labels"; import { SUB_AMOUNT_TITLE, SUB_CREATE_READONLY_NOTE, SUB_END_DATE_READONLY, WORD_FETCH_FAILED, WORD_NOT_OPENED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy"; import { moneyCell, yuanToCents } from "../lib/package-catalog"; import { rowsOf, subscriptionChange, subscriptionContractOptions, subscriptionCreate, subscriptionDelete, subscriptionPlanOptions, subscriptionUpdate } from "../lib/api/bos"; import type { SubscriptionContractOption, SubscriptionPlanOption } from "../lib/api/types"; import { useLoad } from "../lib/useLoad"; import { detailBack, detailLinkState } from "../lib/detail-navigation"; import { useHorizontalOverflow } from "../lib/use-horizontal-overflow"; import "../styles/operations.css"; type Mode = "new" | "edit" | "view" | "updown"; type EditorContext = { mode: Mode; record?: SubscriptionView }; const statusTone = (status: string) => status === "生效中" ? "success" : status === "已到期" ? "neutral" : "warning"; /** 三态文本格:键缺失=取数失败,null=未配置,⛔ 用 0/「—」冒充有值。 */ function cell(value: string | null | undefined, missing: string = WORD_UNCONFIGURED) { if (value === undefined) return ; if (value === null || value === "") return ; return value; } /** 只读输入框只能用字符串:三态在这里落到锁定文案,⛔ 用「—」或 0 冒充。 */ const textOf = (value: string | null | undefined, missing: string = WORD_UNCONFIGURED) => (value === undefined ? WORD_FETCH_FAILED : value === null || value === "" ? missing : value); const moneyView = (c: { tone: "val" | "missing" | "fail"; text: string }) => (c.tone === "val" ? c.text : ); const exitsView = (exits: string[] | null | undefined) => (exits === undefined ? : exits === null || !exits.length ? : exits.join("、")); function Dialog({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) { const ref = useRef(null); useEffect(() => { const dialog = ref.current; if (!dialog) return; const previous = document.activeElement as HTMLElement | null; dialog.showModal(); return () => { dialog.close(); previous?.focus(); }; }, []); return { if (event.target === event.currentTarget) onClose(); }}>
套餐订阅管理

{title}

{children}
; } /** * 订阅办理弹窗:新建走 `create`、升降配走 `change`、编辑只放开白名单字段走 `update`。 * * 价格、月标准、结束日、实际开通日、线路出口、订单号六项只读,由服务端按套餐目录与合同条目带出; * ⛔ 在此提交或改写它们(出现即 `11103`)。 */ function SubscriptionEditor({ customerId, customerName, context, onClose, onSaved }: { customerId: string; customerName: string; context: EditorContext; onClose: () => void; onSaved: (message: string) => void; }) { const existing = context.record; const [contractId, setContractId] = useState(context.mode === "new" ? "" : existing?.contractId ?? ""); const [itemId, setItemId] = useState(context.mode === "new" ? "" : existing?.contractItemId ?? ""); const [planId, setPlanId] = useState(context.mode === "new" ? "" : existing?.planId ?? ""); const [term, setTerm] = useState("yearly"); const [startDate, setStartDate] = useState(existing?.start ?? ""); const [trialMonths, setTrialMonths] = useState<"0" | "1" | "2">(existing?.trialMonths === 1 || existing?.trialMonths === 2 ? String(existing.trialMonths) as "1" | "2" : "0"); const [trialDiscount, setTrialDiscount] = useState(existing?.trialDiscount ? String(existing.trialDiscount / 100) : ""); const [error, setError] = useState(""); const [pending, setPending] = useState(false); const contracts = useLoad(() => subscriptionContractOptions({ customer_id: customerId }), [customerId]); const plans = useLoad(() => subscriptionPlanOptions({ customer_id: customerId }), [customerId]); const contractItems = rowsOf(rowsOf(contracts.data).find((item: SubscriptionContractOption) => item.contract_id === contractId)?.items); /** * 合同条目已钉死档位时,套餐下拉只列该档。 * * 后端把「条目档位 ≠ 所选套餐」当业务错拒(实测 `60221`:`条目 CI-0001-1 关联档位 P-002, * 与所选档位 P-008 不匹配`);⛔ 让用户先选错再报错——在**输入侧**就按条目收窄。 * 条目未钉档位(`plan_id` 与 `plan_id_derived` 都空)时不下约束,保持全量可选。 */ const itemPlanId = (() => { const item = contractItems.find((entry) => entry.item_id === itemId); return item ? item.plan_id ?? item.plan_id_derived ?? null : null; })(); const planChoices = rowsOf(plans.data).filter((item: SubscriptionPlanOption) => !itemPlanId || item.plan_id === itemPlanId); /** 可写性只取服务端结论:新建/升降配始终可提交,编辑要求后端下发 `editable`。 */ const writable = context.mode === "new" || context.mode === "updown" || (context.mode === "edit" && existing?.editable === true); const priceOf = planId ? rowsOf(plans.data).find((item: SubscriptionPlanOption) => item.plan_id === planId) : undefined; async function submit(event: FormEvent) { event.preventDefault(); if (!contractId || !itemId || !planId || !startDate) { setError("请选择合同、合同服务构成条目、套餐并填写生效日。"); return; } if (context.mode === "updown" && !existing) return setError("缺少被承接的原订阅。"); setPending(true); setError(""); try { if (context.mode === "edit" && existing) { const discount = trialMonths === "0" || !trialDiscount.trim() ? undefined : yuanToCents(trialDiscount); if (trialMonths !== "0" && trialDiscount.trim() && discount === null) { setError("试用优惠金额须为非负金额,最多两位小数。"); setPending(false); return; } await subscriptionUpdate({ subscription_id: existing.no, row_version: Number(existing.rowVersion), trial_months: Number(trialMonths), ...(discount === undefined ? {} : { discount_monthly_cents: discount }), }); onSaved("订阅已更新(仅试用与优惠白名单字段可写)。"); } else if (context.mode === "updown" && existing) { await subscriptionChange({ replaces_subscription_id: existing.no, customer_id: customerId, plan_id: planId, contract_id: contractId, contract_item_id: itemId, start_date: startDate, ...(trialMonths === "0" ? {} : { trial_months: Number(trialMonths) }), }); onSaved("已创建承接订阅,原订阅保留为历史记录。"); } else { const created = await subscriptionCreate({ customer_id: customerId, plan_id: planId, contract_id: contractId, contract_item_id: itemId, term, start_date: startDate, ...(trialMonths === "0" ? {} : { trial_months: Number(trialMonths) }), }); onSaved(`订阅已创建(${created.subscription_id}),等待网络开通回填。`); } } catch (cause) { setError((cause as Error).message); setPending(false); } } const title = context.mode === "new" ? "新增订阅" : context.mode === "updown" ? `升降配 · ${existing?.planName ?? WORD_FETCH_FAILED}` : context.mode === "edit" ? `编辑订阅 · ${existing?.no}` : `订阅详情 · ${existing?.no}`; return

{customerName} · {customerId}{context.mode === "updown" && 承接 {existing?.no};新合同的期间与出口由服务端写入新订阅。}

{contracts.error &&
可选合同取数失败:{contracts.error.message}
} {plans.error &&
可选套餐取数失败:{plans.error.message}
} {!writable &&
{context.mode === "view" ? "详情为只读。需要变更时请新建订阅或办理升降配。" : existing?.editable === undefined ? "写口可见性未随记录下发,按只读呈现。" : "服务端判定本条只读(已到期或已开通计费)。需要变更时请新建订阅。"}
}
{context.mode === "edit" ? : } {trialMonths !== "0" && }

{SUB_CREATE_READONLY_NOTE}({SUB_AMOUNT_TITLE})。合同期间、订单号与线路出口随合同条目带出,网络开通由运维流程回填。

{error &&

{error}

}
{writable && }
; } export function CustomerSubscriptionsPage() { const view = useBusinessView([]); const location = useLocation(); const navigate = useNavigate(); const { no } = useParams(); const param = decodeURIComponent(no ?? ""); const back = detailBack(location.state, param ? `/customers/${encodeURIComponent(param)}` : "/customers", "返回客户档案"); const outgoingState = detailLinkState(location.pathname, location.state); const tableOverflow = useHorizontalOverflow(); /** 客户档案(第 1 册口径)只提供主体信息;订阅台账改走 `list_all` 后本地按客户主键归集。 */ const customer = view.customers.find((item) => item.no === param); const subs = useAllSubscriptions(); const all = subs.data === undefined ? [] : rowsOf(subs.data).map(subscriptionView); const rows = all.filter((item) => item.customerId === param || (customer && item.customer === customer.name)); const customerId = rows[0]?.customerId || customer?.no || param; const [context, setContext] = useState(null); const [confirm, setConfirm] = useState(null); const [deleteBlocked, setDeleteBlocked] = useState(""); const [pendingDelete, setPendingDelete] = useState(false); const [notice, setNotice] = useState(""); if (subs.loading) return
{back.label}

正在从订阅接口读取该客户的订阅…

; if (subs.error) return
{back.label}

订阅取数失败

{subs.error.message}

; const active = rows.filter((item) => item.statusLabel === "生效中").length; async function removeSubscription() { if (!confirm) return; setPendingDelete(true); setDeleteBlocked(""); try { const result = await subscriptionDelete({ subscription_id: confirm.no }); if (result && result.deleted === false) setDeleteBlocked("服务端未删除本条订阅(应答未给出原因);是否仍被引用由服务端判定,页面⛔ 自行放行。"); else { setConfirm(null); setNotice("订阅已删除。"); subs.reload(); } } catch (cause) { setDeleteBlocked((cause as Error).message); } finally { setPendingDelete(false); } } return
{back.label}

套餐订阅管理

{customer?.name ?? cell(rows[0]?.customer)} · {customerId}

{!view.readOnly && }
客户账户{customer ? {customer.status} : }
全部订阅{rows.length}
生效中{active}
分账号额度{customer?.quota ?? }
{customer && 查看客户档案 }

全部订阅

升降配、叠加与到期记录均保留;新增和变更从本页办理。

共 {rows.length} 条
{Array.from({ length: 9 }, (_, index) => )}{rows.map((item) => { const canUpdown = item.statusLabel === "生效中"; const subActions: { key: string; label: string; icon: ReactNode; danger?: boolean; info?: boolean; show: boolean; onSelect: () => void }[] = [ { key: "view", label: "详情", icon: , info: false, show: true, onSelect: () => navigate(`/subscriptions/${encodeURIComponent(item.no)}`, { state: outgoingState }) }, { key: "updown", label: "升降配", icon: , show: canUpdown, onSelect: () => setContext({ mode: "updown", record: item }) }, { key: "edit", label: "编辑", icon: , show: item.editable === true, onSelect: () => setContext({ mode: "edit", record: item }) }, { key: "delete", label: "删除", icon: , danger: true, show: true, onSelect: () => { setDeleteBlocked(""); setConfirm(item); } }, ]; const shown = subActions.filter((action) => action.show && (!view.readOnly || action.key === "view")); const visible = shown.slice(0, 3); const moreItems: OpsMoreItem[] = shown.slice(3).map(({ key, label, icon, onSelect }) => ({ key, label, icon, onSelect })); return ; })}
套餐 / 合同 / 订单号线路出口方式状态合同期间订阅价格月结算标准实际开通日操作
{cell(item.planName)}{cell(item.contractNo)} · {cell(item.orderNo, "无订单号")}{exitsView(item.exits)}{cell(item.modeLabel)}{item.statusLabel ? {item.statusLabel} : }{item.replacedBy && 已由 {item.replacedBy.subscription_id} 承接}{cell(item.start)}至 {cell(item.end)}{moneyView(item.annual)}{moneyView(item.settle)}{item.openedOn === undefined ? : item.openedOn || }
{visible.map((action) => )}{moreItems.length > 0 && }
{!rows.length &&

还没有订阅

先为客户登记一份合同,再新增套餐订阅。

}
合同与套餐候选由服务端按当前账号可见范围下发;线路出口、订单号和期间随合同条目带出。
{context && setContext(null)} onSaved={(message) => { setContext(null); setNotice(message); subs.reload(); }} />} {confirm &&

删除订阅?

{confirm.planName ?? WORD_UNCONFIGURED} · {confirm.no}。是否可删除由服务端按引用关系判定,页面⛔ 自行放行。

{deleteBlocked &&

{deleteBlocked}

}
} {notice && setNotice("")} />}
; }