| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476 |
- import { useHorizontalOverflow } from "../lib/use-horizontal-overflow";
- import { FilterIcon, FilterSelect } from "../components/ui/filter-select";
- import { TreeSelect } from "../components/ui/tree-select";
- import { useEffect, useMemo, useState } from "react";
- import { ArrowRight, CalendarDays, Check, Info, RotateCcw, Scan, Search, X } from "lucide-react";
- import { Button } from "../components/ui/button";
- import { Input } from "../components/ui/input";
- import {
- defaultReconcileDay, initialSettlementScopes,
- type DemoSettlementScope,
- } from "../lib/settlement-demo";
- import { ALL_ORG_COLLECTIONS, descendants } from "../lib/organization-demo";
- import { regionTreeNodes } from "../lib/region-tree";
- import { currentSharePartyTypes, hasShareTerms, sharePartiesFromOrganization, type CurrentSharePartyType } from "../lib/share-party-view";
- import { Tri } from "../components/triState";
- import { WORD_FETCH_FAILED, WORD_NOT_PROVIDED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
- import { hasBizCode } from "../lib/api/http";
- import { operatorUpdate } from "../lib/api/bos";
- import type { BillingConfigOperatorRow, EffectiveMode, HolderType } from "../lib/api/types";
- import { submitBillingConfigUpdate, useBillingConfig } from "../lib/recon";
- import { SHARE_TERMS_UNSET, settleTextFromSnapshot } from "../lib/settle-text";
- import { shareSummaryKey, useShareParamSummary, type ShareSummaryState } from "../lib/share-summary";
- import { PARTY_NO_STATEMENT, PARTY_SCOPE_NOTE } from "../lib/copy-views";
- import {
- BACKEND_NOT_WIRED,
- BILLING_CONFIG_WIRING_NOTE,
- CONFIG_CONFLICT_NOTE,
- CONFIG_DEFAULT_DAY_SCOPE_NOTE,
- CONFIG_FIXED_CONFIRM,
- CONFIG_MODE_EXTRA_CONFIRM,
- CONFIG_SAVED_NOTE,
- EFFECTIVE_MODE_NOTE,
- EFFECTIVE_MODE_TEXT,
- operatorDayText,
- } from "../lib/copy-billing";
- import { useBusinessView } from "../lib/use-business-view";
- import { onboardingRegions } from "../lib/customer-onboarding";
- import { OpsDrawer, OpsNotice, OpsStatus, OpsTag, OpsTableEmpty, OpsTableColumns } from "../components/OperationsKit";
- import "../styles/operations.css";
- import "../styles/reconciliation-settings.css";
- function Tabs<T extends string>({ value, onChange, options }: { value: T; onChange: (value: T) => void; options: readonly T[] }) {
- return <div className="ops-tabs" role="group">{options.map((item) => <button key={item} type="button" aria-pressed={value === item} className={value === item ? "active" : ""} onClick={() => onChange(item)}>{item}</button>)}</div>;
- }
- /** 分成方档案行(第 1 册三类档案真源)。 */
- type SharePartyRow = ReturnType<typeof sharePartiesFromOrganization>[number];
- /** 档案类型中文值 → HolderType 后端编码(share_param_summary 入参)。 */
- const PARTY_HOLDER_TYPE: Record<CurrentSharePartyType, HolderType> = {
- 运营商: "operator",
- 合伙人: "partner",
- 运维团队: "ops_team",
- };
- /**
- * 分成管理(册 4 契约 14.1 分成方列表+14.2 分成金额弹窗;FN-04 旧形态已作废,⛔ 再用 `share_rule/*` 派生视图):
- * - 列表行源=第 1 册三类档案(organization 真源,regAdmin 按 onboardingRegions 收窄);
- * - 「分成方式」「分成取值」唯一来源=`share_param_summary` 读口([位] 未在 OpenAPI 声明 ⇒ 未接线期两列「后端未下发」;
- * KLT-S406 ⇒ 只该两列「取数失败」,其余照常);
- * - 状态列=档案两列派生(已配分成/未配分成中性渲染),不依赖读口 ⇒ 读口失败照常;
- * - 行操作只有「分成金额」⇒ 契约 14.2 弹窗(四卡+历史分成清单+取值摘要只读),⛔ 路由页/规则表/保存按钮/方式下拉;
- * - 前端⛔ 分成写入口:KLT-S20001(分成写口未对运营支撑前端开放)。
- */
- export function ShareRulePage() {
- const tableOverflow = useHorizontalOverflow();
- const remaining = Math.max(1180, tableOverflow.width) - 560;
- const columnWidths = [64, remaining * .57, 156, remaining * .43, 120, 90, 130];
- const { identity, organization } = useBusinessView(ALL_ORG_COLLECTIONS);
- const allowedRegions = useMemo(() => new Set(onboardingRegions(organization, identity)), [organization, identity]);
- const rows = useMemo(() => sharePartiesFromOrganization(organization, {
- customerRegions: identity?.role === "regAdmin" ? allowedRegions : undefined,
- }), [organization, identity, allowedRegions]);
- /** 契约 14.1.3:列表页一次调用(⛔ 逐行请求);[位] 未接线 ⇒ fail="wiring"(两列「后端未下发」)。 */
- const summaryRefs = useMemo(() => rows.map((row) => ({ holder_type: PARTY_HOLDER_TYPE[row.type], holder_id: row.id })), [rows]);
- const summary = useShareParamSummary(summaryRefs);
- const [region, setRegion] = useState("");
- const [kind, setKind] = useState<"全部" | CurrentSharePartyType>("全部");
- const [state, setState] = useState("全部状态");
- const [search, setSearch] = useState("");
- const [detail, setDetail] = useState<SharePartyRow | null>(null);
- const regionTree = regionTreeNodes(organization.regions, [...allowedRegions]);
- const regionScope = region ? new Set(descendants(organization, region)) : null;
- const filtered = rows.filter((row) =>
- (!regionScope || regionScope.has(row.region)) &&
- (kind === "全部" || row.type === kind) &&
- (state === "全部状态" || (hasShareTerms(row) ? "已配分成" : "未配分成") === state) &&
- `${row.displayName} ${row.type} ${row.note} ${row.regionLabel}`.toLowerCase().includes(search.trim().toLowerCase()),
- );
- const hasFilter = region !== "" || kind !== "全部" || state !== "全部状态" || search !== "";
- function reset() { setRegion(""); setKind("全部"); setState("全部状态"); setSearch(""); }
- /** 「分成方式与取值」格三态:wiring ⇒ 后端未下发;S406 ⇒ 取数失败(只这两列,其余照常);命中 ⇒ settleText 单源;未配 ⇒ 中性「未配分成」。 */
- function termsCell(row: SharePartyRow) {
- if (summary.fail === "wiring") return <Tri tone="missing" text={WORD_NOT_PROVIDED} title="share_param_summary 读口未在 OpenAPI 声明(待 klt-bos 交付)⇒ 两列待接线" />;
- if (summary.fail) return <Tri tone="fail" text={WORD_FETCH_FAILED} title={summary.fail === "s406" ? "KLT-S406:只这两列取数失败,其余照常;⛔ 整页不渲染" : summary.message} />;
- const item = summary.items.get(shareSummaryKey(PARTY_HOLDER_TYPE[row.type], row.id));
- if (!item) return <Tri tone="missing" text={WORD_NOT_PROVIDED} title="读口应答未覆盖该方" />;
- if (!item.configured) return <small>{SHARE_TERMS_UNSET}</small>;
- return <strong>{settleTextFromSnapshot(item.share_mode, item.share_value)}</strong>;
- }
- return <section className="ops-page ops-page--rules">
- <header className="ops-heading"><div><p className="ops-eyebrow"><span /> REVENUE SHARING / 分成与对账</p><h1>分成管理</h1><p>本页以分成方为维度:一行一个运营商、合伙人或运维团队,看这一方用什么方式分成、比例或金额是多少、当前是否生效。</p></div></header>
- <div className="ops-list-shell"><div className="ops-list-heading"><div><h2>分成方(共 {rows.length} 方,当前显示 {filtered.length} 方)</h2><p>行源=第 1 册三类档案;「分成方式与取值」列唯一来源= share_param_summary 读口({summary.fail === "wiring" ? "未在 OpenAPI 声明,待 klt-bos 交付 ⇒ 该列标「后端未下发」" : summary.fail ? "本次取数失败" : "已接线"})。点击「分成金额」打开契约 14.2 只读弹窗。</p></div></div>
- <div className="ops-toolbar flex-wrap">
- <label className="ops-search"><Search size={17} /><Input aria-label="搜索分成方" placeholder="搜索分成方名称、类型或区域" value={search} onChange={(event) => setSearch(event.target.value)} />{search && <button type="button" aria-label="清空搜索" onClick={() => setSearch("")}><X size={15} /></button>}</label>
- <TreeSelect treeData={regionTree} value={region} onChange={setRegion} clearable icon={<FilterIcon kind="region" />} ariaLabel="所属区域(含下级)" placeholder="全部区域" />
- <FilterSelect icon="type" aria-label="分成方类型筛选" value={kind} onChange={(event) => setKind(event.target.value as "全部" | CurrentSharePartyType)}><option value="全部">全部类型</option>{currentSharePartyTypes.map((item) => <option key={item} value={item}>{item}</option>)}</FilterSelect>
- <FilterSelect icon="status" aria-label="分成状态筛选" value={state} onChange={(event) => setState(event.target.value)}><option>全部状态</option><option>已配分成</option><option>未配分成</option></FilterSelect>
- {hasFilter && <Button variant="ghost" size="sm" onClick={reset}>重置筛选</Button>}
- </div>
- <div ref={tableOverflow.ref} tabIndex={0} role="region" aria-label="分成方台账,可横向滚动查看字段" className={`measured-table-scroll ops-table-wrap share-ledger-scroll${tableOverflow.overflow ? " has-horizontal-overflow" : ""}${tableOverflow.width >= 640 ? " can-pin-identity" : ""}${tableOverflow.canScrollLeft ? " can-scroll-left" : ""}${tableOverflow.canScrollRight ? " can-scroll-right" : ""}`}><table className="ops-table share-ledger"><OpsTableColumns widths={columnWidths} /><thead><tr><th>序号</th><th>分成方</th><th>分成方类型</th><th>分成方式与取值</th><th>状态</th><th>分成客户</th><th>操作</th></tr></thead><tbody>{filtered.map((row, index) => <tr key={row.id}>
- <td><span className="ops-mono">{String(index + 1).padStart(2, "0")}</span></td>
- <td><strong title={row.displayName}>{row.displayName}</strong><small title={row.note}>{row.note}</small></td>
- <td><OpsTag tone={row.type === "合伙人" ? "brand" : row.type === "运营商" ? "info" : "neutral"}>{row.type}</OpsTag></td>
- <td className="org-maintenance-share">{termsCell(row)}</td>
- <td>{hasShareTerms(row) ? <OpsStatus tone="success">已配分成</OpsStatus> : <small>未配分成</small>}</td>
- <td><span className="ops-money">{row.customerCount} 家</span></td>
- <td><button type="button" className="ops-table-action" onClick={() => setDetail(row)} title="契约 14.2:弹窗出四卡+历史分成清单(只读),⛔ 规则表/保存按钮/方式下拉">分成金额 <ArrowRight size={14} /></button></td>
- </tr>)}{!filtered.length && <OpsTableEmpty colSpan={7}>{rows.length ? "没有符合筛选条件的分成方,可重置四组筛选" : "第 1 册档案里还没有运营商/合伙人/运维团队(分成方行源为空)"}</OpsTableEmpty>}</tbody></table></div>
- <footer className="ops-list-footer"><Info size={15} />「分成方式与取值」列=share_param_summary 读口(列表页一次调用,⛔ 逐行);「已配分成/未配分成」状态与分成客户数=第 1 册档案两列与在册客户派生。前端⛔ 分成写入口(KLT-S20001);该方取值对其名下全部客户统一生效。</footer>
- </div>
- {detail && <ShareAmountDialog row={detail} summary={summary} onClose={() => setDetail(null)} />}
- </section>;
- }
- /**
- * 契约 14.2 分成金额弹窗(只读):
- * 四卡=累计分成金额/已分成期数(第 6 册对账聚合未上线 ⇒ 恒「未配置」,⛔ 编 0)+分成客户数/分成方式(share_param_summary 本册现算);
- * 取值摘要只读+「对该方名下全部客户统一生效」;⛔ 规则表/保存按钮/方式下拉;⛔ 客户数编辑;
- * 11104 ⇒ 与「该方不存在」同一句并关弹窗(待详情读口接线后落位,见下)。
- * ⚠️ 历史分成清单数据源=第 8 册「对方只读视图」详情读口:册 8 接口清单(06)无本场景读口(2026-11-11 核实)
- * ⇒ 本区为契约占位骨架+「后端未下发」标格,⛔ 造请求到不存在的接口、⛔ 读演示台账;缺口已登记。
- */
- function ShareAmountDialog({ row, summary, onClose }: { row: SharePartyRow; summary: ShareSummaryState; onClose: () => void }) {
- const wiring = summary.fail === "wiring";
- const failed = summary.fail !== null && !wiring;
- const item = summary.items.get(shareSummaryKey(PARTY_HOLDER_TYPE[row.type], row.id)) ?? null;
- /** 卡 4/取值摘要与列表两列同源(读口未接线 ⇒ 后端未下发;⛔ 回落档案两列)。 */
- const termsView = wiring ? WORD_NOT_PROVIDED : failed ? WORD_FETCH_FAILED
- : item ? (item.configured ? settleTextFromSnapshot(item.share_mode, item.share_value) : SHARE_TERMS_UNSET) : WORD_NOT_PROVIDED;
- const customerCountView = wiring ? WORD_NOT_PROVIDED : failed ? WORD_FETCH_FAILED
- : item ? `${item.customer_count} 家` : WORD_NOT_PROVIDED;
- return <div className="ops-confirm-backdrop" role="presentation" onMouseDown={onClose}><div className="ops-batch-dialog ops-cost-def-dialog" role="dialog" aria-modal="true" aria-labelledby="share-amount-title" onMouseDown={(event) => event.stopPropagation()}>
- <header><div><p>分成管理 / 分成金额</p><h2 id="share-amount-title">{row.displayName} · 分成金额</h2><p>{row.type} · {row.regionLabel || "—"}</p></div><Button variant="ghost" size="icon" aria-label="关闭" onClick={onClose}><X size={18} /></Button></header>
- <div className="ops-batch-dialog-body">
- <div className="ops-cost-cards">
- <article className="ops-cost-card"><span>累计分成金额</span><strong>{WORD_UNCONFIGURED}</strong><small>第 6 册对账聚合未上线——一期不接,⛔ 读演示台账</small></article>
- <article className="ops-cost-card"><span>已分成期数</span><strong>{WORD_UNCONFIGURED}</strong><small>第 6 册对账聚合未上线——同上口径</small></article>
- <article className="ops-cost-card"><span>分成客户数</span><strong>{customerCountView}</strong><small>share_param_summary 本册现算</small></article>
- <article className="ops-cost-card"><span>分成方式</span><strong>{termsView}</strong><small>share_param_summary 现行值</small></article>
- </div>
- <p className="ops-import-note">取值摘要(只读):{termsView} · {PARTY_SCOPE_NOTE}。⛔ 方式下拉与保存按钮——取值变更走运维流程(一期不接)。</p>
- <h3>历史分成清单</h3>
- <div className="ops-table-wrap"><table className="ops-table"><thead><tr><th>期次</th><th>计算过程</th><th>金额</th><th>对账指向</th></tr></thead><tbody>
- <tr><td colSpan={4}><Tri tone="missing" text={WORD_NOT_PROVIDED} title="数据源=第 8 册「对方只读视图」详情读口(接口清单无本场景读口)⇒ 契约占位骨架;就绪后逐行出「计算过程+对账指向」" /></td></tr>
- </tbody></table></div>
- <p className="ops-import-note">每行须给出计算过程,并指到对应对账单据;该方本期未出账 ⇒「{PARTY_NO_STATEMENT}」。数据源未接线 ⇒ 本区为契约占位骨架(已登记缺口)。</p>
- </div>
- <footer><Button variant="outline" onClick={onClose}>关闭</Button></footer>
- </div></div>;
- }
- export function SettlementScopePage() {
- const [records] = useState(initialSettlementScopes);
- const [kind, setKind] = useState<"全部" | DemoSettlementScope["kind"]>("全部");
- const [search, setSearch] = useState("");
- const [selectedId, setSelectedId] = useState<string | null>(null);
- const selected = records.find((item) => item.id === selectedId) ?? null;
- const stats = useMemo(() => ({
- enabled: records.filter((item) => item.enabled).length,
- operator: records.filter((item) => item.kind === "运营商").length,
- partner: records.filter((item) => item.kind === "合伙人").length,
- customers: records.reduce((sum, item) => sum + item.customerCount, 0),
- }), [records]);
- const filtered = useMemo(() => records.filter((item) =>
- (kind === "全部" || item.kind === kind) &&
- `${item.id} ${item.name} ${item.target}`.toLowerCase().includes(search.trim().toLowerCase()),
- ), [records, kind, search]);
- const hasFilter = kind !== "全部" || search !== "";
- return <section className="ops-page ops-page--scopes">
- <header className="ops-heading"><div><p className="ops-eyebrow"><span /> SETTLEMENT SCOPE / 分成与结算</p><h1>结算范围</h1><p>为运营商和合伙人圈定参与结算的区域与客户;到达对账日时按已启用范围出批次。</p></div></header>
- <div className="ops-overview"><div className="ops-overview-lead"><span><Scan size={23} /></span><div><small>结算范围</small><strong>{records.length.toString().padStart(2, "0")}</strong><p>启用中 {stats.enabled} 个</p></div></div><div className="ops-overview-stats"><div><span>运营商范围</span><strong>{stats.operator.toString().padStart(2, "0")}</strong></div><div><span>合伙人范围</span><strong>{stats.partner.toString().padStart(2, "0")}</strong></div><div><span>覆盖客户</span><strong>{stats.customers}</strong></div><div><span>停用</span><strong>{(records.length - stats.enabled).toString().padStart(2, "0")}</strong></div></div></div>
- <div className="ops-list-shell"><div className="ops-list-heading"><div><h2>范围台账</h2><p>对账日未单独设置时跟随系统默认对账日。</p></div><span>共 {filtered.length} 条结果</span></div>
- <Tabs value={kind} onChange={setKind} options={["全部", "运营商", "合伙人"] as const} />
- <div className="ops-toolbar">
- <label className="ops-search"><Search size={17} /><Input aria-label="搜索范围" placeholder="搜索范围名称或归属对象" value={search} onChange={(event) => setSearch(event.target.value)} />{search && <button type="button" aria-label="清空搜索" onClick={() => setSearch("")}><X size={15} /></button>}</label>
- {hasFilter && <Button variant="ghost" size="sm" onClick={() => { setKind("全部"); setSearch(""); }}>重置筛选</Button>}
- </div>
- <div className="ops-table-wrap"><table className="ops-table"><thead><tr><th>范围</th><th>归属对象</th><th>覆盖区域</th><th>客户</th><th>对账日</th><th>状态</th><th><span className="sr-only">操作</span></th></tr></thead><tbody>{filtered.map((item) => <tr key={item.id}>
- <td><strong>{item.name}</strong><small>{item.id}</small></td>
- <td><OpsTag tone={item.kind === "运营商" ? "info" : "brand"}>{item.kind}</OpsTag><small>{item.target}</small></td>
- <td>{item.regionPaths.join("、")}</td>
- <td><span className="ops-money">{item.customerCount} 家</span></td>
- <td><span className="ops-money">{item.reconcileDay ? `每月 ${item.reconcileDay} 日` : "默认对账日"}</span></td>
- <td><OpsStatus tone={item.enabled ? "success" : "neutral"}>{item.enabled ? "启用中" : "停用"}</OpsStatus></td>
- <td><button type="button" className="ops-table-action" aria-label={`查看${item.name}详情`} onClick={() => setSelectedId(item.id)}>详情 <ArrowRight size={14} /></button></td>
- </tr>)}{!filtered.length && <OpsTableEmpty colSpan={7}>没有符合筛选条件的结算范围。</OpsTableEmpty>}</tbody></table></div>
- <footer className="ops-list-footer"><Info size={15} />范围与客户绑定的服务端校验待后端契约确定后接入。</footer>
- </div>
- {selected && <ScopeDetail item={selected} onClose={() => setSelectedId(null)} />}
- </section>;
- }
- function ScopeDetail({ item, onClose }: { item: DemoSettlementScope; onClose: () => void }) {
- return <OpsDrawer title={item.name} subtitle={`结算范围 / ${item.id}`} onClose={onClose}>
- <div className="ops-detail">
- <div className="ops-detail-hero"><div><OpsTag tone={item.kind === "运营商" ? "info" : "brand"}>{item.kind}</OpsTag><OpsStatus tone={item.enabled ? "success" : "neutral"}>{item.enabled ? "启用中" : "停用"}</OpsStatus></div><h3>{item.target}</h3><p>{item.regionPaths.join("、")}</p></div>
- <section><h4>范围配置</h4><dl className="ops-detail-grid">
- <div><dt>覆盖客户</dt><dd>{item.customerCount} 家</dd></div>
- <div><dt>对账日</dt><dd>{item.reconcileDay ? `每月 ${item.reconcileDay} 日(单独设置)` : `跟随系统默认 · 每月 ${defaultReconcileDay} 日`}</dd></div>
- </dl></section>
- <p className="ops-detail-footnote"><Info size={16} />到达对账日时,每日任务对已启用范围自动出上一自然月批次;人工补跑的批次固定结算上一结束月。</p>
- </div>
- </OpsDrawer>;
- }
- /* ═══ 出账配置(FN-09,册 6 §14.4) ════════════════════════════════════
- * 数据源=billing/config_get@v1、config_update@v1 stub(全 [位],openapi.yaml 未声明 ⇒ 11001 契约占位分支);
- * 逐运营商行内写复用 operator/update@v1(契约 §14.4 写语义,⛔ 新开 billing/operator_day@v1;
- * recon_day/pay_cycle 两入参 openapi.yaml 未声明,待 klt-bos 补声明,已登记缺口清单)。
- * 三处保存均先确认:首行「变更前 → 变更后」+CONFIG_FIXED_CONFIRM 逐字固定句(+按类型追加句)。
- * ⛔ 合伙人/运维团队自定义对账日;⛔ localStorage 台账冒充配置真源(旧 `oss-demo-billing-*` 台账键已随册 4 接线移除)。
- */
- /** 待确认的保存意图(三处保存共用一套确认框)。 */
- type PendingConfigSave =
- | { kind: "day"; next: number }
- | { kind: "mode"; next: EffectiveMode }
- | { kind: "operator"; row: BillingConfigOperatorRow; nextDay: number | null; nextCycle: string };
- export function ReconciliationSettingsPage() {
- const { identity } = useBusinessView([]);
- // 仅 admin 可保存;opsMain/opsSub 不渲染保存按钮且服务端同拒(demo 角色 regAdmin=opsMain,只读)。
- const isAdmin = !identity || identity.role === "admin";
- const config = useBillingConfig();
- const data = config.data;
- const wiring = config.fail?.kind === "wiring";
- // 默认对账日契约初值 5(U-56,⛔ 1);响应下发后以服务端值为准。
- const [draftDay, setDraftDay] = useState<number>(5);
- const [draftMode, setDraftMode] = useState<EffectiveMode>("period_snapshot");
- useEffect(() => {
- if (!data) return;
- setDraftDay(data.default_recon_day);
- setDraftMode(data.effective_mode);
- }, [data]);
- const [pending, setPending] = useState<PendingConfigSave | null>(null);
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState("");
- const [notice, setNotice] = useState("");
- const editable = isAdmin && !wiring && Boolean(data);
- const followDefaultNames = (data?.operators ?? []).filter((row) => row.recon_day == null).map((row) => row.name);
- /** 确认框行集:首行「变更前 → 变更后」+逐字固定句+按类型追加句。 */
- function pendingLines(): string[] {
- if (!pending || !data) return [];
- if (pending.kind === "day") {
- return [
- `默认对账日:每月 ${data.default_recon_day} 日 → 每月 ${pending.next} 日`,
- CONFIG_FIXED_CONFIRM,
- `${CONFIG_DEFAULT_DAY_SCOPE_NOTE}:${followDefaultNames.length ? followDefaultNames.join("、") : "(当前无跟随系统默认的运营商)"}`,
- ];
- }
- if (pending.kind === "mode") {
- return [
- `生效时点:${EFFECTIVE_MODE_TEXT[data.effective_mode]} → ${EFFECTIVE_MODE_TEXT[pending.next]}`,
- CONFIG_FIXED_CONFIRM,
- CONFIG_MODE_EXTRA_CONFIRM,
- ];
- }
- return [
- `${pending.row.name}:${operatorDayText(pending.row.recon_day, data.default_recon_day)} → ${operatorDayText(pending.nextDay, data.default_recon_day)},付款周期 ${pending.row.pay_cycle ?? "未设置"} → ${pending.nextCycle || "未设置"}`,
- CONFIG_FIXED_CONFIRM,
- ];
- }
- function doSave() {
- if (!pending || !data) return;
- setBusy(true);
- setError("");
- const request =
- pending.kind === "day"
- ? submitBillingConfigUpdate({ default_recon_day: pending.next, row_version: data.row_version }).then(() => undefined)
- : pending.kind === "mode"
- ? submitBillingConfigUpdate({ effective_mode: pending.next, row_version: data.row_version }).then(() => undefined)
- : operatorUpdate({
- operator_id: pending.row.operator_id,
- name: pending.row.name,
- brand: pending.row.brand ?? "",
- region_node_id: pending.row.region_node_id ?? "",
- recon_day: pending.nextDay,
- pay_cycle: pending.nextCycle,
- }).then(() => undefined);
- request
- .then(() => {
- // 成功提示按 effective_mode 二选一(契约:由后端随配置返回;未下发 ⇒ CONFIG_SAVED_NOTE 常量兜底)。
- const modeAfter = pending.kind === "mode" ? pending.next : data.effective_mode;
- setPending(null);
- setNotice(CONFIG_SAVED_NOTE[modeAfter]);
- config.reload();
- })
- .catch((e: unknown) => {
- // KLT-S407/60001=乐观锁并发冲突 ⇒ 提示刷新后重试;11103 ⇒ detail.fields[] 逐字段红显(本页唯一可红显字段=对账日)。
- const message = e instanceof Error && e.message ? e.message : "";
- setError(hasBizCode(e, "KLT-S407") || hasBizCode(e, "60001") ? message || CONFIG_CONFLICT_NOTE : message || "保存失败,请重试。");
- })
- .finally(() => setBusy(false));
- }
- return (
- <section className="ops-page billing-settings-page">
- <header className="ops-heading">
- <div>
- <p className="ops-eyebrow"><span /> BILLING CONFIG / 分成与对账</p>
- <h1>出账配置</h1>
- <p>设置系统默认对账日与生效时点,并维护运营商的对账日覆盖与付款周期。</p>
- </div>
- </header>
- {wiring && <p className="ops-import-note" role="status">{BILLING_CONFIG_WIRING_NOTE}</p>}
- {config.fail && !wiring && (
- <p className="ops-form-error" role="alert">{config.fail.message} <Button variant="ghost" size="sm" onClick={config.reload}>重试</Button></p>
- )}
- <section className="billing-default-card" aria-labelledby="billing-default-title">
- <header className="billing-default-heading">
- <span className="billing-default-icon" aria-hidden="true"><CalendarDays size={21} /></span>
- <h2 id="billing-default-title">全局出账规则</h2>
- </header>
- <section className="billing-default-row" aria-labelledby="billing-day-title">
- <div className="billing-default-copy">
- <h3 id="billing-day-title">系统默认对账日</h3>
- <p>未单独设置的运营商统一按此日期出账(⛔ 合伙人/运维团队不可自定义对账日)。</p>
- </div>
- <div className="billing-default-current">
- <span>当前默认</span>
- <strong>{data ? `每月 ${data.default_recon_day} 日` : wiring ? BACKEND_NOT_WIRED : "—"}</strong>
- </div>
- <div className="billing-default-edit">
- <label htmlFor="billing-default-day">调整对账日</label>
- <div>
- <span className="ops-select">
- <select disabled={!editable} id="billing-default-day" value={draftDay} onChange={(event) => setDraftDay(Number(event.target.value))}>
- {Array.from({ length: 28 }, (_, index) => index + 1).map((value) => <option key={value} value={value}>每月 {value} 日</option>)}
- </select>
- </span>
- {isAdmin && <Button disabled={!editable || !data || draftDay === data.default_recon_day} onClick={() => setPending({ kind: "day", next: draftDay })}><Check size={16} />保存默认值</Button>}
- </div>
- </div>
- </section>
- <section className="billing-default-row" aria-labelledby="billing-mode-title">
- <div className="billing-default-copy">
- <h3 id="billing-mode-title">生效时点</h3>
- {/* 单选旁固定说明句(2026-11-02 定案新增,⛔ 按场景改写)。 */}
- <p>{EFFECTIVE_MODE_NOTE}</p>
- </div>
- <div className="billing-default-current">
- <span>当前模式</span>
- <strong>{data ? EFFECTIVE_MODE_TEXT[data.effective_mode] : wiring ? BACKEND_NOT_WIRED : "—"}</strong>
- </div>
- <div className="billing-default-edit">
- <label htmlFor="billing-data-mode">调整生效时点</label>
- <div>
- <span className="ops-select">
- <select disabled={!editable} id="billing-data-mode" value={draftMode} onChange={(event) => setDraftMode(event.target.value as EffectiveMode)}>
- <option value="period_snapshot">{EFFECTIVE_MODE_TEXT.period_snapshot}</option>
- <option value="live_at_billing">{EFFECTIVE_MODE_TEXT.live_at_billing}</option>
- </select>
- </span>
- {isAdmin && <Button disabled={!editable || !data || draftMode === data.effective_mode} onClick={() => setPending({ kind: "mode", next: draftMode })}><Check size={16} />保存生效时点</Button>}
- </div>
- </div>
- </section>
- </section>
- <section className="billing-operators ops-list-shell" aria-labelledby="billing-operators-title">
- <div className="ops-list-heading">
- <div><h2 id="billing-operators-title">运营商出账设置</h2><p>对账日可跟随默认值或单独指定(两态靠取值本身区分,⛔ 另加徽标);付款周期按运营商合同约定记录。</p></div>
- <span>{(data?.operators ?? []).length} 家运营商 · {(data?.operators ?? []).filter((row) => row.recon_day != null).length} 家单独设置</span>
- </div>
- <div className="ops-table-wrap billing-table-wrap" role="region" aria-label="运营商出账设置" tabIndex={0}>
- <table className="ops-table billing-table billing-ledger">
- <OpsTableColumns widths={[260, 240, 200, 220]} />
- <thead><tr><th>运营商 / 所属区域</th><th>对账日</th><th>付款周期</th><th>操作</th></tr></thead>
- <tbody>
- {(data?.operators ?? []).map((row) => (
- <BillingOperatorRow key={row.operator_id} row={row} defaultDay={data?.default_recon_day ?? draftDay}
- canSave={editable} onSave={(nextDay, nextCycle) => setPending({ kind: "operator", row, nextDay, nextCycle })} />
- ))}
- {!(data?.operators ?? []).length && (
- <OpsTableEmpty colSpan={4}>
- {config.loading ? "加载中…" : wiring ? `出账配置待后端接线,运营商对账日暂不可读(${BACKEND_NOT_WIRED})。` : "暂无可配置出账的运营商。"}
- </OpsTableEmpty>
- )}
- </tbody>
- </table>
- </div>
- </section>
- <aside className="billing-guidance">
- <Info size={17} />
- <div><strong>出账规则</strong><p>对账日限每月 1–28 日,当天核算上一已结束自然月。付款周期只记录付款节奏,不触发扣款;合伙人与运维团队始终跟随系统默认对账日。</p></div>
- </aside>
- {pending && (
- <div className="ops-confirm-backdrop" role="presentation" onMouseDown={() => !busy && setPending(null)}>
- <div className="ops-confirm" role="alertdialog" aria-modal="true" aria-labelledby="billing-config-confirm" onMouseDown={(event) => event.stopPropagation()}>
- <h2 id="billing-config-confirm">确认保存出账配置</h2>
- {pendingLines().map((line) => <p key={line}>{line}</p>)}
- {error && <p className="ops-form-error" role="alert">{error}</p>}
- <div>
- <Button variant="outline" onClick={() => setPending(null)} disabled={busy}>取消</Button>
- <Button onClick={doSave} disabled={busy}>{busy ? "保存中…" : "确认保存"}</Button>
- </div>
- </div>
- </div>
- )}
- {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
- </section>
- );
- }
- function BillingOperatorRow({ row, defaultDay, canSave, onSave }: {
- row: BillingConfigOperatorRow;
- defaultDay: number;
- canSave: boolean;
- onSave: (nextDay: number | null, nextCycle: string) => void;
- }) {
- const [draftDay, setDraftDay] = useState(row.recon_day === null ? "" : String(row.recon_day));
- const [draftCycle, setDraftCycle] = useState(row.pay_cycle ?? "");
- useEffect(() => {
- setDraftDay(row.recon_day === null ? "" : String(row.recon_day));
- setDraftCycle(row.pay_cycle ?? "");
- }, [row.recon_day, row.pay_cycle]);
- const changed = draftDay !== (row.recon_day === null ? "" : String(row.recon_day)) || draftCycle !== (row.pay_cycle ?? "");
- const reset = () => {
- setDraftDay(row.recon_day === null ? "" : String(row.recon_day));
- setDraftCycle(row.pay_cycle ?? "");
- };
- // 行内写复用 operator/update@v1(name/brand/region_node_id 必传):config_get 未下发后两列 ⇒ 禁用并说明。
- const rowWritable = Boolean(row.brand && row.region_node_id);
- return (
- <tr>
- <td><strong title={row.name}>{row.name}</strong><small title={row.region_label ?? ""}>{row.region_label ?? "—"}</small></td>
- <td>
- <label className="billing-field">
- <span className="sr-only">{row.name}对账日</span>
- <select disabled={!canSave} aria-label={`${row.name}对账日`} value={draftDay} onChange={(event) => setDraftDay(event.target.value)}>
- <option value="">跟随系统默认({defaultDay} 日)</option>
- {Array.from({ length: 28 }, (_, index) => index + 1).map((value) => <option key={value} value={value}>每月 {value} 日</option>)}
- </select>
- </label>
- </td>
- <td>
- <label className="billing-field">
- <span className="sr-only">{row.name}付款周期</span>
- <select disabled={!canSave} aria-label={`${row.name}付款周期`} value={draftCycle} onChange={(event) => setDraftCycle(event.target.value)}>
- <option value="">未设置</option>
- {["月付", "两月付", "季付"].map((cycle) => <option key={cycle} value={cycle}>{cycle}</option>)}
- </select>
- </label>
- </td>
- <td>
- <div className="billing-row-actions">
- {changed && <button aria-label={`撤销${row.name}的修改`} className="ops-table-action" onClick={reset} type="button"><RotateCcw size={14} />撤销</button>}
- <Button disabled={!canSave || !changed || !rowWritable} size="sm"
- title={!rowWritable ? "档案字段未随配置下发,行内保存暂不可用(待 klt-bos 在 config_get 补 brand/region_node_id,或 operator/update@v1 放开部分更新)" : undefined}
- onClick={() => onSave(draftDay ? Number(draftDay) : null, draftCycle)}>保存</Button>
- </div>
- </td>
- </tr>
- );
- }
|