| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236 |
- 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 <Tri tone="fail" text={WORD_FETCH_FAILED} />;
- if (value === null || value === "") return <Tri tone="missing" text={missing} />;
- 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 : <Tri tone={c.tone} text={c.text} title="金额取数失败=接口未下发该键;未配置=后端明确回 null" />);
- const exitsView = (exits: string[] | null | undefined) =>
- (exits === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : exits === null || !exits.length ? <Tri tone="missing" text={WORD_UNCONFIGURED} /> : exits.join("、"));
- function Dialog({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
- const ref = useRef<HTMLDialogElement>(null);
- useEffect(() => {
- const dialog = ref.current;
- if (!dialog) return;
- const previous = document.activeElement as HTMLElement | null;
- dialog.showModal();
- return () => { dialog.close(); previous?.focus(); };
- }, []);
- return <dialog ref={ref} className="customer-sub-dialog" aria-labelledby="customer-sub-dialog-title" onCancel={onClose} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
- <header><div><span>套餐订阅管理</span><h2 id="customer-sub-dialog-title">{title}</h2></div><button type="button" aria-label="关闭" onClick={onClose}><X size={19} /></button></header>
- {children}
- </dialog>;
- }
- /**
- * 订阅办理弹窗:新建走 `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<HTMLFormElement>) {
- 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 <Dialog title={title} onClose={onClose}>
- <form className="customer-sub-form" onSubmit={submit}>
- <p className="customer-sub-context">{customerName} · {customerId}{context.mode === "updown" && <span>承接 {existing?.no};新合同的期间与出口由服务端写入新订阅。</span>}</p>
- {contracts.error && <div className="customer-sub-alert" role="alert">可选合同取数失败:{contracts.error.message}</div>}
- {plans.error && <div className="customer-sub-alert" role="alert">可选套餐取数失败:{plans.error.message}</div>}
- {!writable && <div className="customer-sub-alert">{context.mode === "view" ? "详情为只读。需要变更时请新建订阅或办理升降配。" : existing?.editable === undefined ? "写口可见性未随记录下发,按只读呈现。" : "服务端判定本条只读(已到期或已开通计费)。需要变更时请新建订阅。"}</div>}
- <div className="customer-sub-fields">
- <label><span>合同编号 <b>*</b></span><select disabled={!writable} value={contractId} onChange={(event) => { setContractId(event.target.value); setItemId(""); setError(""); }}><option value="">{contracts.loading ? "正在读取可选合同…" : "请选择该客户的可选合同"}</option>{rowsOf(contracts.data).map((item: SubscriptionContractOption) => <option key={item.contract_id} value={item.contract_id}>{item.contract_no}</option>)}</select></label>
- <label><span>合同服务构成条目 <b>*</b></span><select disabled={!writable || !contractId} value={itemId} onChange={(event) => { setItemId(event.target.value); setPlanId(""); setError(""); }}><option value="">{contractId ? "请选择服务构成条目" : WORD_UNCONFIGURED}</option>{contractItems.map((item) => <option key={item.item_id} value={item.item_id}>{item.plan_name ?? item.item_kind}{item.quantity ? ` × ${item.quantity}` : ""}</option>)}</select></label>
- <label><span>套餐 <b>*</b></span><select disabled={!writable} value={planId} onChange={(event) => { setPlanId(event.target.value); setError(""); }}><option value="">{plans.loading ? "正在读取可选套餐…" : "请选择套餐"}</option>{planChoices.map((item: SubscriptionPlanOption) => <option key={item.plan_id} value={item.plan_id} disabled={item.available === false}>{item.plan_name}{item.available === false ? ` · ${item.unavailable_reason ?? "不可订阅"}` : ""}</option>)}</select></label>
- <label>线路出口(随合同条目)<input readOnly value={(() => { const exits = context.mode === "new" || context.mode === "updown" ? priceOf?.line_exits : existing?.exits; return exits === undefined ? WORD_FETCH_FAILED : exits === null || !exits.length ? WORD_UNCONFIGURED : exits.join("、"); })()} /></label>
- <label>订阅方式<input readOnly value={context.mode === "new" || context.mode === "updown" ? (priceOf ? "由套餐用途分类派生" : WORD_UNCONFIGURED) : existing?.modeLabel ?? WORD_UNCONFIGURED} /></label>
- {context.mode === "edit" ? <label>订阅时长<input readOnly value={existing?.termLabel || WORD_UNCONFIGURED} /></label>
- : <label>订阅时长 <b>*</b><select value={term} onChange={(event) => setTerm(event.target.value)}>{OPTIONS.term.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</select></label>}
- <label>生效日 <b>*</b><input disabled={!writable} type="date" value={startDate} onChange={(event) => setStartDate(event.target.value)} /></label>
- <label>结束日(服务端派生)<input readOnly value={context.mode === "edit" || context.mode === "view" ? existing?.end ?? WORD_UNCONFIGURED : SUB_END_DATE_READONLY} /></label>
- <label>订单号(随合同外部单号)<input readOnly value={context.mode === "new" || context.mode === "updown" ? "由服务端按合同外部单号冻结" : textOf(existing?.orderNo, "无运营商订单号")} /></label>
- <label>订阅价格<input readOnly value={context.mode === "new" || context.mode === "updown" ? (priceOf?.annual_price_cents === undefined || priceOf.annual_price_cents === null ? WORD_UNCONFIGURED : moneyCell(priceOf.annual_price_cents).text) : textOf(existing?.annual.text)} /></label>
- <label>月结算标准<input readOnly value={context.mode === "new" || context.mode === "updown" ? "由服务端按套餐目录带出" : `${textOf(existing?.settle.text)} / 月`} /></label>
- <label>分账号额度<input readOnly value={existing ? (existing.quotaSlots === undefined ? WORD_FETCH_FAILED : existing.quotaSlots === null ? WORD_UNCONFIGURED : String(existing.quotaSlots)) : priceOf?.sub_account_quota ?? WORD_UNCONFIGURED} /></label>
- <label>试用优惠期<select disabled={!writable} value={trialMonths} onChange={(event) => setTrialMonths(event.target.value as "0" | "1" | "2")}><option value="0">不试用</option><option value="1">1 个月</option><option value="2">2 个月</option></select></label>
- {trialMonths !== "0" && <label>试用优惠金额(元/月)<input readOnly={!writable} inputMode="decimal" placeholder="选填,留空不套用正式月费" value={trialDiscount} onChange={(event) => setTrialDiscount(event.target.value)} /></label>}
- <label>实际开通日<input readOnly value={existing?.openedOn === undefined ? WORD_FETCH_FAILED : existing.openedOn || WORD_NOT_OPENED} /></label>
- </div>
- <p className="customer-sub-hint">{SUB_CREATE_READONLY_NOTE}({SUB_AMOUNT_TITLE})。合同期间、订单号与线路出口随合同条目带出,网络开通由运维流程回填。</p>
- {error && <p className="ops-form-error" role="alert">{error}</p>}
- <footer><Button type="button" variant="outline" onClick={onClose}>{writable ? "取消" : "关闭"}</Button>{writable && <Button type="submit" disabled={pending || !contractId || !itemId || !planId || !startDate}>{context.mode === "edit" ? "保存订阅" : context.mode === "updown" ? "创建承接订阅" : "创建订阅"}</Button>}</footer>
- </form>
- </Dialog>;
- }
- 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<EditorContext | null>(null);
- const [confirm, setConfirm] = useState<SubscriptionView | null>(null);
- const [deleteBlocked, setDeleteBlocked] = useState("");
- const [pendingDelete, setPendingDelete] = useState(false);
- const [notice, setNotice] = useState("");
- if (subs.loading) return <section className="ops-page"><Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} />{back.label}</Link><div className="ops-empty"><h1>正在从订阅接口读取该客户的订阅…</h1></div></section>;
- if (subs.error) return <section className="ops-page"><Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} />{back.label}</Link><div className="ops-empty"><h1>订阅取数失败</h1><p role="alert">{subs.error.message}</p><Button variant="ghost" size="sm" onClick={() => subs.reload()}>重试</Button></div></section>;
- 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 <section className="ops-page customer-sub-page">
- <Link to={back.to} state={back.state} className="ops-back-link"><ArrowLeft size={16} />{back.label}</Link>
- <header className="ops-heading"><div><h1>套餐订阅管理</h1><p>{customer?.name ?? cell(rows[0]?.customer)} · {customerId}</p></div>{!view.readOnly && <Button onClick={() => setContext({ mode: "new" })}><Plus size={16} />新增订阅</Button>}</header>
- <div className="customer-sub-overview"><div><span>客户账户</span>{customer ? <OpsStatus tone={customer.status === "在用" ? "success" : customer.status === "停用" ? "danger" : "warning"}>{customer.status}</OpsStatus> : <Tri tone="missing" text={WORD_UNCONFIGURED} title="客户档案属第 1 册口径,未关联到该客户主键" />}</div><div><span>全部订阅</span><strong>{rows.length}</strong></div><div><span>生效中</span><strong>{active}</strong></div><div><span>分账号额度</span><strong>{customer?.quota ?? <Tri tone="missing" text={WORD_UNCONFIGURED} title="额度由第 1 册客户档案给出" />}</strong></div>{customer && <Link className="ops-card-link" to={`/customers/${customer.no}`} state={outgoingState}>查看客户档案 <ArrowRight size={15} /></Link>}</div>
- <div className="ops-list-shell"><div className="ops-list-heading"><div><h2>全部订阅</h2><p>升降配、叠加与到期记录均保留;新增和变更从本页办理。</p></div><span>共 {rows.length} 条</span></div>
- <div ref={tableOverflow.ref} className={`measured-table-scroll ops-table-wrap${tableOverflow.overflow ? " has-horizontal-overflow" : ""}`}><table className="ops-table customer-sub-table"><colgroup>{Array.from({ length: 9 }, (_, index) => <col key={index} />)}</colgroup><thead><tr><th>套餐 / 合同 / 订单号</th><th>线路出口</th><th>方式</th><th>状态</th><th>合同期间</th><th>订阅价格</th><th>月结算标准</th><th>实际开通日</th><th>操作</th></tr></thead><tbody>{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: <ArrowRight size={14} />, info: false, show: true, onSelect: () => navigate(`/subscriptions/${encodeURIComponent(item.no)}`, { state: outgoingState }) },
- { key: "updown", label: "升降配", icon: <RefreshCw size={15} />, show: canUpdown, onSelect: () => setContext({ mode: "updown", record: item }) },
- { key: "edit", label: "编辑", icon: <PencilLine size={15} />, show: item.editable === true, onSelect: () => setContext({ mode: "edit", record: item }) },
- { key: "delete", label: "删除", icon: <Trash2 size={15} />, 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 <tr key={item.no}><td title={`${item.planName ?? WORD_UNCONFIGURED} · ${item.contractNo ?? WORD_UNCONFIGURED} · ${item.orderNo ?? "无订单号"}`}><strong>{cell(item.planName)}</strong><small>{cell(item.contractNo)} · {cell(item.orderNo, "无订单号")}</small></td><td title={item.exits?.join("、") ?? ""}>{exitsView(item.exits)}</td><td>{cell(item.modeLabel)}</td><td>{item.statusLabel ? <OpsStatus tone={statusTone(item.statusLabel)}>{item.statusLabel}</OpsStatus> : <Tri tone="fail" text={WORD_FETCH_FAILED} title="订阅状态编码未下发" />}{item.replacedBy && <small>已由 {item.replacedBy.subscription_id} 承接</small>}</td><td title={`${item.start ?? WORD_UNCONFIGURED} 至 ${item.end ?? WORD_UNCONFIGURED}`}><strong className="customer-sub-date">{cell(item.start)}</strong><small>至 {cell(item.end)}</small></td><td><strong>{moneyView(item.annual)}</strong></td><td>{moneyView(item.settle)}</td><td title={item.openedOn ?? WORD_NOT_OPENED}><span className="customer-sub-date">{item.openedOn === undefined ? <Tri tone="fail" text={WORD_FETCH_FAILED} /> : item.openedOn || <Tri tone="missing" text={WORD_NOT_OPENED} />}</span></td><td><div className="ops-inline-actions">{visible.map((action) => <button key={action.key} type="button" className={[action.danger && "is-danger", action.info && "is-info"].filter(Boolean).join(" ") || undefined} onClick={(event) => { event.stopPropagation(); action.onSelect(); }}>{action.key === "view" ? <>{action.label}{action.icon}</> : <>{action.icon}{action.label}</>}</button>)}{moreItems.length > 0 && <OpsMore items={moreItems} />}</div></td></tr>;
- })}</tbody></table></div>
- {!rows.length && <div className="ops-empty"><h3>还没有订阅</h3><p>先为客户登记一份合同,再新增套餐订阅。</p></div>}
- <footer className="ops-list-footer">合同与套餐候选由服务端按当前账号可见范围下发;线路出口、订单号和期间随合同条目带出。</footer>
- </div>
- {context && <SubscriptionEditor key={`${context.mode}-${context.record?.no ?? "new"}`} customerId={customerId} customerName={customer?.name ?? rows[0]?.customer ?? customerId} context={context} onClose={() => setContext(null)} onSaved={(message) => { setContext(null); setNotice(message); subs.reload(); }} />}
- {confirm && <div className="ops-confirm-backdrop"><div className="ops-confirm" role="alertdialog" aria-modal="true" aria-labelledby="customer-sub-confirm-title"><h2 id="customer-sub-confirm-title">删除订阅?</h2><p>{confirm.planName ?? WORD_UNCONFIGURED} · {confirm.no}。是否可删除由服务端按引用关系判定,页面⛔ 自行放行。</p>{deleteBlocked && <p className="ops-form-error" role="alert">{deleteBlocked}</p>}<div><Button variant="outline" onClick={() => { setConfirm(null); setDeleteBlocked(""); }}>取消</Button><Button variant="destructive" disabled={pendingDelete} onClick={removeSubscription}>{pendingDelete ? "提交中…" : "确认删除"}</Button></div></div></div>}
- {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
- </section>;
- }
|