SettlementPages.tsx 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. import { useHorizontalOverflow } from "../lib/use-horizontal-overflow";
  2. import { FilterIcon, FilterSelect } from "../components/ui/filter-select";
  3. import { TreeSelect } from "../components/ui/tree-select";
  4. import { useEffect, useMemo, useState } from "react";
  5. import { ArrowRight, CalendarDays, Check, Info, RotateCcw, Scan, Search, X } from "lucide-react";
  6. import { Button } from "../components/ui/button";
  7. import { Input } from "../components/ui/input";
  8. import {
  9. defaultReconcileDay, initialSettlementScopes,
  10. type DemoSettlementScope,
  11. } from "../lib/settlement-demo";
  12. import { ALL_ORG_COLLECTIONS, descendants } from "../lib/organization-demo";
  13. import { regionTreeNodes } from "../lib/region-tree";
  14. import { currentSharePartyTypes, hasShareTerms, sharePartiesFromOrganization, type CurrentSharePartyType } from "../lib/share-party-view";
  15. import { Tri } from "../components/triState";
  16. import { WORD_FETCH_FAILED, WORD_NOT_PROVIDED, WORD_UNCONFIGURED } from "../lib/api/lockedCopy";
  17. import { hasBizCode } from "../lib/api/http";
  18. import { operatorUpdate } from "../lib/api/bos";
  19. import type { BillingConfigOperatorRow, EffectiveMode, HolderType } from "../lib/api/types";
  20. import { submitBillingConfigUpdate, useBillingConfig } from "../lib/recon";
  21. import { SHARE_TERMS_UNSET, settleTextFromSnapshot } from "../lib/settle-text";
  22. import { shareSummaryKey, useShareParamSummary, type ShareSummaryState } from "../lib/share-summary";
  23. import { PARTY_NO_STATEMENT, PARTY_SCOPE_NOTE } from "../lib/copy-views";
  24. import {
  25. BACKEND_NOT_WIRED,
  26. BILLING_CONFIG_WIRING_NOTE,
  27. CONFIG_CONFLICT_NOTE,
  28. CONFIG_DEFAULT_DAY_SCOPE_NOTE,
  29. CONFIG_FIXED_CONFIRM,
  30. CONFIG_MODE_EXTRA_CONFIRM,
  31. CONFIG_SAVED_NOTE,
  32. EFFECTIVE_MODE_NOTE,
  33. EFFECTIVE_MODE_TEXT,
  34. operatorDayText,
  35. } from "../lib/copy-billing";
  36. import { useBusinessView } from "../lib/use-business-view";
  37. import { onboardingRegions } from "../lib/customer-onboarding";
  38. import { OpsDrawer, OpsNotice, OpsStatus, OpsTag, OpsTableEmpty, OpsTableColumns } from "../components/OperationsKit";
  39. import "../styles/operations.css";
  40. import "../styles/reconciliation-settings.css";
  41. function Tabs<T extends string>({ value, onChange, options }: { value: T; onChange: (value: T) => void; options: readonly T[] }) {
  42. 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>;
  43. }
  44. /** 分成方档案行(第 1 册三类档案真源)。 */
  45. type SharePartyRow = ReturnType<typeof sharePartiesFromOrganization>[number];
  46. /** 档案类型中文值 → HolderType 后端编码(share_param_summary 入参)。 */
  47. const PARTY_HOLDER_TYPE: Record<CurrentSharePartyType, HolderType> = {
  48. 运营商: "operator",
  49. 合伙人: "partner",
  50. 运维团队: "ops_team",
  51. };
  52. /**
  53. * 分成管理(册 4 契约 14.1 分成方列表+14.2 分成金额弹窗;FN-04 旧形态已作废,⛔ 再用 `share_rule/*` 派生视图):
  54. * - 列表行源=第 1 册三类档案(organization 真源,regAdmin 按 onboardingRegions 收窄);
  55. * - 「分成方式」「分成取值」唯一来源=`share_param_summary` 读口([位] 未在 OpenAPI 声明 ⇒ 未接线期两列「后端未下发」;
  56. * KLT-S406 ⇒ 只该两列「取数失败」,其余照常);
  57. * - 状态列=档案两列派生(已配分成/未配分成中性渲染),不依赖读口 ⇒ 读口失败照常;
  58. * - 行操作只有「分成金额」⇒ 契约 14.2 弹窗(四卡+历史分成清单+取值摘要只读),⛔ 路由页/规则表/保存按钮/方式下拉;
  59. * - 前端⛔ 分成写入口:KLT-S20001(分成写口未对运营支撑前端开放)。
  60. */
  61. export function ShareRulePage() {
  62. const tableOverflow = useHorizontalOverflow();
  63. const remaining = Math.max(1180, tableOverflow.width) - 560;
  64. const columnWidths = [64, remaining * .57, 156, remaining * .43, 120, 90, 130];
  65. const { identity, organization } = useBusinessView(ALL_ORG_COLLECTIONS);
  66. const allowedRegions = useMemo(() => new Set(onboardingRegions(organization, identity)), [organization, identity]);
  67. const rows = useMemo(() => sharePartiesFromOrganization(organization, {
  68. customerRegions: identity?.role === "regAdmin" ? allowedRegions : undefined,
  69. }), [organization, identity, allowedRegions]);
  70. /** 契约 14.1.3:列表页一次调用(⛔ 逐行请求);[位] 未接线 ⇒ fail="wiring"(两列「后端未下发」)。 */
  71. const summaryRefs = useMemo(() => rows.map((row) => ({ holder_type: PARTY_HOLDER_TYPE[row.type], holder_id: row.id })), [rows]);
  72. const summary = useShareParamSummary(summaryRefs);
  73. const [region, setRegion] = useState("");
  74. const [kind, setKind] = useState<"全部" | CurrentSharePartyType>("全部");
  75. const [state, setState] = useState("全部状态");
  76. const [search, setSearch] = useState("");
  77. const [detail, setDetail] = useState<SharePartyRow | null>(null);
  78. const regionTree = regionTreeNodes(organization.regions, [...allowedRegions]);
  79. const regionScope = region ? new Set(descendants(organization, region)) : null;
  80. const filtered = rows.filter((row) =>
  81. (!regionScope || regionScope.has(row.region)) &&
  82. (kind === "全部" || row.type === kind) &&
  83. (state === "全部状态" || (hasShareTerms(row) ? "已配分成" : "未配分成") === state) &&
  84. `${row.displayName} ${row.type} ${row.note} ${row.regionLabel}`.toLowerCase().includes(search.trim().toLowerCase()),
  85. );
  86. const hasFilter = region !== "" || kind !== "全部" || state !== "全部状态" || search !== "";
  87. function reset() { setRegion(""); setKind("全部"); setState("全部状态"); setSearch(""); }
  88. /** 「分成方式与取值」格三态:wiring ⇒ 后端未下发;S406 ⇒ 取数失败(只这两列,其余照常);命中 ⇒ settleText 单源;未配 ⇒ 中性「未配分成」。 */
  89. function termsCell(row: SharePartyRow) {
  90. if (summary.fail === "wiring") return <Tri tone="missing" text={WORD_NOT_PROVIDED} title="share_param_summary 读口未在 OpenAPI 声明(待 klt-bos 交付)⇒ 两列待接线" />;
  91. if (summary.fail) return <Tri tone="fail" text={WORD_FETCH_FAILED} title={summary.fail === "s406" ? "KLT-S406:只这两列取数失败,其余照常;⛔ 整页不渲染" : summary.message} />;
  92. const item = summary.items.get(shareSummaryKey(PARTY_HOLDER_TYPE[row.type], row.id));
  93. if (!item) return <Tri tone="missing" text={WORD_NOT_PROVIDED} title="读口应答未覆盖该方" />;
  94. if (!item.configured) return <small>{SHARE_TERMS_UNSET}</small>;
  95. return <strong>{settleTextFromSnapshot(item.share_mode, item.share_value)}</strong>;
  96. }
  97. return <section className="ops-page ops-page--rules">
  98. <header className="ops-heading"><div><p className="ops-eyebrow"><span /> REVENUE SHARING / 分成与对账</p><h1>分成管理</h1><p>本页以分成方为维度:一行一个运营商、合伙人或运维团队,看这一方用什么方式分成、比例或金额是多少、当前是否生效。</p></div></header>
  99. <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>
  100. <div className="ops-toolbar flex-wrap">
  101. <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>
  102. <TreeSelect treeData={regionTree} value={region} onChange={setRegion} clearable icon={<FilterIcon kind="region" />} ariaLabel="所属区域(含下级)" placeholder="全部区域" />
  103. <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>
  104. <FilterSelect icon="status" aria-label="分成状态筛选" value={state} onChange={(event) => setState(event.target.value)}><option>全部状态</option><option>已配分成</option><option>未配分成</option></FilterSelect>
  105. {hasFilter && <Button variant="ghost" size="sm" onClick={reset}>重置筛选</Button>}
  106. </div>
  107. <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}>
  108. <td><span className="ops-mono">{String(index + 1).padStart(2, "0")}</span></td>
  109. <td><strong title={row.displayName}>{row.displayName}</strong><small title={row.note}>{row.note}</small></td>
  110. <td><OpsTag tone={row.type === "合伙人" ? "brand" : row.type === "运营商" ? "info" : "neutral"}>{row.type}</OpsTag></td>
  111. <td className="org-maintenance-share">{termsCell(row)}</td>
  112. <td>{hasShareTerms(row) ? <OpsStatus tone="success">已配分成</OpsStatus> : <small>未配分成</small>}</td>
  113. <td><span className="ops-money">{row.customerCount} 家</span></td>
  114. <td><button type="button" className="ops-table-action" onClick={() => setDetail(row)} title="契约 14.2:弹窗出四卡+历史分成清单(只读),⛔ 规则表/保存按钮/方式下拉">分成金额 <ArrowRight size={14} /></button></td>
  115. </tr>)}{!filtered.length && <OpsTableEmpty colSpan={7}>{rows.length ? "没有符合筛选条件的分成方,可重置四组筛选" : "第 1 册档案里还没有运营商/合伙人/运维团队(分成方行源为空)"}</OpsTableEmpty>}</tbody></table></div>
  116. <footer className="ops-list-footer"><Info size={15} />「分成方式与取值」列=share_param_summary 读口(列表页一次调用,⛔ 逐行);「已配分成/未配分成」状态与分成客户数=第 1 册档案两列与在册客户派生。前端⛔ 分成写入口(KLT-S20001);该方取值对其名下全部客户统一生效。</footer>
  117. </div>
  118. {detail && <ShareAmountDialog row={detail} summary={summary} onClose={() => setDetail(null)} />}
  119. </section>;
  120. }
  121. /**
  122. * 契约 14.2 分成金额弹窗(只读):
  123. * 四卡=累计分成金额/已分成期数(第 6 册对账聚合未上线 ⇒ 恒「未配置」,⛔ 编 0)+分成客户数/分成方式(share_param_summary 本册现算);
  124. * 取值摘要只读+「对该方名下全部客户统一生效」;⛔ 规则表/保存按钮/方式下拉;⛔ 客户数编辑;
  125. * 11104 ⇒ 与「该方不存在」同一句并关弹窗(待详情读口接线后落位,见下)。
  126. * ⚠️ 历史分成清单数据源=第 8 册「对方只读视图」详情读口:册 8 接口清单(06)无本场景读口(2026-11-11 核实)
  127. * ⇒ 本区为契约占位骨架+「后端未下发」标格,⛔ 造请求到不存在的接口、⛔ 读演示台账;缺口已登记。
  128. */
  129. function ShareAmountDialog({ row, summary, onClose }: { row: SharePartyRow; summary: ShareSummaryState; onClose: () => void }) {
  130. const wiring = summary.fail === "wiring";
  131. const failed = summary.fail !== null && !wiring;
  132. const item = summary.items.get(shareSummaryKey(PARTY_HOLDER_TYPE[row.type], row.id)) ?? null;
  133. /** 卡 4/取值摘要与列表两列同源(读口未接线 ⇒ 后端未下发;⛔ 回落档案两列)。 */
  134. const termsView = wiring ? WORD_NOT_PROVIDED : failed ? WORD_FETCH_FAILED
  135. : item ? (item.configured ? settleTextFromSnapshot(item.share_mode, item.share_value) : SHARE_TERMS_UNSET) : WORD_NOT_PROVIDED;
  136. const customerCountView = wiring ? WORD_NOT_PROVIDED : failed ? WORD_FETCH_FAILED
  137. : item ? `${item.customer_count} 家` : WORD_NOT_PROVIDED;
  138. 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()}>
  139. <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>
  140. <div className="ops-batch-dialog-body">
  141. <div className="ops-cost-cards">
  142. <article className="ops-cost-card"><span>累计分成金额</span><strong>{WORD_UNCONFIGURED}</strong><small>第 6 册对账聚合未上线——一期不接,⛔ 读演示台账</small></article>
  143. <article className="ops-cost-card"><span>已分成期数</span><strong>{WORD_UNCONFIGURED}</strong><small>第 6 册对账聚合未上线——同上口径</small></article>
  144. <article className="ops-cost-card"><span>分成客户数</span><strong>{customerCountView}</strong><small>share_param_summary 本册现算</small></article>
  145. <article className="ops-cost-card"><span>分成方式</span><strong>{termsView}</strong><small>share_param_summary 现行值</small></article>
  146. </div>
  147. <p className="ops-import-note">取值摘要(只读):{termsView} · {PARTY_SCOPE_NOTE}。⛔ 方式下拉与保存按钮——取值变更走运维流程(一期不接)。</p>
  148. <h3>历史分成清单</h3>
  149. <div className="ops-table-wrap"><table className="ops-table"><thead><tr><th>期次</th><th>计算过程</th><th>金额</th><th>对账指向</th></tr></thead><tbody>
  150. <tr><td colSpan={4}><Tri tone="missing" text={WORD_NOT_PROVIDED} title="数据源=第 8 册「对方只读视图」详情读口(接口清单无本场景读口)⇒ 契约占位骨架;就绪后逐行出「计算过程+对账指向」" /></td></tr>
  151. </tbody></table></div>
  152. <p className="ops-import-note">每行须给出计算过程,并指到对应对账单据;该方本期未出账 ⇒「{PARTY_NO_STATEMENT}」。数据源未接线 ⇒ 本区为契约占位骨架(已登记缺口)。</p>
  153. </div>
  154. <footer><Button variant="outline" onClick={onClose}>关闭</Button></footer>
  155. </div></div>;
  156. }
  157. export function SettlementScopePage() {
  158. const [records] = useState(initialSettlementScopes);
  159. const [kind, setKind] = useState<"全部" | DemoSettlementScope["kind"]>("全部");
  160. const [search, setSearch] = useState("");
  161. const [selectedId, setSelectedId] = useState<string | null>(null);
  162. const selected = records.find((item) => item.id === selectedId) ?? null;
  163. const stats = useMemo(() => ({
  164. enabled: records.filter((item) => item.enabled).length,
  165. operator: records.filter((item) => item.kind === "运营商").length,
  166. partner: records.filter((item) => item.kind === "合伙人").length,
  167. customers: records.reduce((sum, item) => sum + item.customerCount, 0),
  168. }), [records]);
  169. const filtered = useMemo(() => records.filter((item) =>
  170. (kind === "全部" || item.kind === kind) &&
  171. `${item.id} ${item.name} ${item.target}`.toLowerCase().includes(search.trim().toLowerCase()),
  172. ), [records, kind, search]);
  173. const hasFilter = kind !== "全部" || search !== "";
  174. return <section className="ops-page ops-page--scopes">
  175. <header className="ops-heading"><div><p className="ops-eyebrow"><span /> SETTLEMENT SCOPE / 分成与结算</p><h1>结算范围</h1><p>为运营商和合伙人圈定参与结算的区域与客户;到达对账日时按已启用范围出批次。</p></div></header>
  176. <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>
  177. <div className="ops-list-shell"><div className="ops-list-heading"><div><h2>范围台账</h2><p>对账日未单独设置时跟随系统默认对账日。</p></div><span>共 {filtered.length} 条结果</span></div>
  178. <Tabs value={kind} onChange={setKind} options={["全部", "运营商", "合伙人"] as const} />
  179. <div className="ops-toolbar">
  180. <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>
  181. {hasFilter && <Button variant="ghost" size="sm" onClick={() => { setKind("全部"); setSearch(""); }}>重置筛选</Button>}
  182. </div>
  183. <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}>
  184. <td><strong>{item.name}</strong><small>{item.id}</small></td>
  185. <td><OpsTag tone={item.kind === "运营商" ? "info" : "brand"}>{item.kind}</OpsTag><small>{item.target}</small></td>
  186. <td>{item.regionPaths.join("、")}</td>
  187. <td><span className="ops-money">{item.customerCount} 家</span></td>
  188. <td><span className="ops-money">{item.reconcileDay ? `每月 ${item.reconcileDay} 日` : "默认对账日"}</span></td>
  189. <td><OpsStatus tone={item.enabled ? "success" : "neutral"}>{item.enabled ? "启用中" : "停用"}</OpsStatus></td>
  190. <td><button type="button" className="ops-table-action" aria-label={`查看${item.name}详情`} onClick={() => setSelectedId(item.id)}>详情 <ArrowRight size={14} /></button></td>
  191. </tr>)}{!filtered.length && <OpsTableEmpty colSpan={7}>没有符合筛选条件的结算范围。</OpsTableEmpty>}</tbody></table></div>
  192. <footer className="ops-list-footer"><Info size={15} />范围与客户绑定的服务端校验待后端契约确定后接入。</footer>
  193. </div>
  194. {selected && <ScopeDetail item={selected} onClose={() => setSelectedId(null)} />}
  195. </section>;
  196. }
  197. function ScopeDetail({ item, onClose }: { item: DemoSettlementScope; onClose: () => void }) {
  198. return <OpsDrawer title={item.name} subtitle={`结算范围 / ${item.id}`} onClose={onClose}>
  199. <div className="ops-detail">
  200. <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>
  201. <section><h4>范围配置</h4><dl className="ops-detail-grid">
  202. <div><dt>覆盖客户</dt><dd>{item.customerCount} 家</dd></div>
  203. <div><dt>对账日</dt><dd>{item.reconcileDay ? `每月 ${item.reconcileDay} 日(单独设置)` : `跟随系统默认 · 每月 ${defaultReconcileDay} 日`}</dd></div>
  204. </dl></section>
  205. <p className="ops-detail-footnote"><Info size={16} />到达对账日时,每日任务对已启用范围自动出上一自然月批次;人工补跑的批次固定结算上一结束月。</p>
  206. </div>
  207. </OpsDrawer>;
  208. }
  209. /* ═══ 出账配置(FN-09,册 6 §14.4) ════════════════════════════════════
  210. * 数据源=billing/config_get@v1、config_update@v1 stub(全 [位],openapi.yaml 未声明 ⇒ 11001 契约占位分支);
  211. * 逐运营商行内写复用 operator/update@v1(契约 §14.4 写语义,⛔ 新开 billing/operator_day@v1;
  212. * recon_day/pay_cycle 两入参 openapi.yaml 未声明,待 klt-bos 补声明,已登记缺口清单)。
  213. * 三处保存均先确认:首行「变更前 → 变更后」+CONFIG_FIXED_CONFIRM 逐字固定句(+按类型追加句)。
  214. * ⛔ 合伙人/运维团队自定义对账日;⛔ localStorage 台账冒充配置真源(旧 `oss-demo-billing-*` 台账键已随册 4 接线移除)。
  215. */
  216. /** 待确认的保存意图(三处保存共用一套确认框)。 */
  217. type PendingConfigSave =
  218. | { kind: "day"; next: number }
  219. | { kind: "mode"; next: EffectiveMode }
  220. | { kind: "operator"; row: BillingConfigOperatorRow; nextDay: number | null; nextCycle: string };
  221. export function ReconciliationSettingsPage() {
  222. const { identity } = useBusinessView([]);
  223. // 仅 admin 可保存;opsMain/opsSub 不渲染保存按钮且服务端同拒(demo 角色 regAdmin=opsMain,只读)。
  224. const isAdmin = !identity || identity.role === "admin";
  225. const config = useBillingConfig();
  226. const data = config.data;
  227. const wiring = config.fail?.kind === "wiring";
  228. // 默认对账日契约初值 5(U-56,⛔ 1);响应下发后以服务端值为准。
  229. const [draftDay, setDraftDay] = useState<number>(5);
  230. const [draftMode, setDraftMode] = useState<EffectiveMode>("period_snapshot");
  231. useEffect(() => {
  232. if (!data) return;
  233. setDraftDay(data.default_recon_day);
  234. setDraftMode(data.effective_mode);
  235. }, [data]);
  236. const [pending, setPending] = useState<PendingConfigSave | null>(null);
  237. const [busy, setBusy] = useState(false);
  238. const [error, setError] = useState("");
  239. const [notice, setNotice] = useState("");
  240. const editable = isAdmin && !wiring && Boolean(data);
  241. const followDefaultNames = (data?.operators ?? []).filter((row) => row.recon_day == null).map((row) => row.name);
  242. /** 确认框行集:首行「变更前 → 变更后」+逐字固定句+按类型追加句。 */
  243. function pendingLines(): string[] {
  244. if (!pending || !data) return [];
  245. if (pending.kind === "day") {
  246. return [
  247. `默认对账日:每月 ${data.default_recon_day} 日 → 每月 ${pending.next} 日`,
  248. CONFIG_FIXED_CONFIRM,
  249. `${CONFIG_DEFAULT_DAY_SCOPE_NOTE}:${followDefaultNames.length ? followDefaultNames.join("、") : "(当前无跟随系统默认的运营商)"}`,
  250. ];
  251. }
  252. if (pending.kind === "mode") {
  253. return [
  254. `生效时点:${EFFECTIVE_MODE_TEXT[data.effective_mode]} → ${EFFECTIVE_MODE_TEXT[pending.next]}`,
  255. CONFIG_FIXED_CONFIRM,
  256. CONFIG_MODE_EXTRA_CONFIRM,
  257. ];
  258. }
  259. return [
  260. `${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 || "未设置"}`,
  261. CONFIG_FIXED_CONFIRM,
  262. ];
  263. }
  264. function doSave() {
  265. if (!pending || !data) return;
  266. setBusy(true);
  267. setError("");
  268. const request =
  269. pending.kind === "day"
  270. ? submitBillingConfigUpdate({ default_recon_day: pending.next, row_version: data.row_version }).then(() => undefined)
  271. : pending.kind === "mode"
  272. ? submitBillingConfigUpdate({ effective_mode: pending.next, row_version: data.row_version }).then(() => undefined)
  273. : operatorUpdate({
  274. operator_id: pending.row.operator_id,
  275. name: pending.row.name,
  276. brand: pending.row.brand ?? "",
  277. region_node_id: pending.row.region_node_id ?? "",
  278. recon_day: pending.nextDay,
  279. pay_cycle: pending.nextCycle,
  280. }).then(() => undefined);
  281. request
  282. .then(() => {
  283. // 成功提示按 effective_mode 二选一(契约:由后端随配置返回;未下发 ⇒ CONFIG_SAVED_NOTE 常量兜底)。
  284. const modeAfter = pending.kind === "mode" ? pending.next : data.effective_mode;
  285. setPending(null);
  286. setNotice(CONFIG_SAVED_NOTE[modeAfter]);
  287. config.reload();
  288. })
  289. .catch((e: unknown) => {
  290. // KLT-S407/60001=乐观锁并发冲突 ⇒ 提示刷新后重试;11103 ⇒ detail.fields[] 逐字段红显(本页唯一可红显字段=对账日)。
  291. const message = e instanceof Error && e.message ? e.message : "";
  292. setError(hasBizCode(e, "KLT-S407") || hasBizCode(e, "60001") ? message || CONFIG_CONFLICT_NOTE : message || "保存失败,请重试。");
  293. })
  294. .finally(() => setBusy(false));
  295. }
  296. return (
  297. <section className="ops-page billing-settings-page">
  298. <header className="ops-heading">
  299. <div>
  300. <p className="ops-eyebrow"><span /> BILLING CONFIG / 分成与对账</p>
  301. <h1>出账配置</h1>
  302. <p>设置系统默认对账日与生效时点,并维护运营商的对账日覆盖与付款周期。</p>
  303. </div>
  304. </header>
  305. {wiring && <p className="ops-import-note" role="status">{BILLING_CONFIG_WIRING_NOTE}</p>}
  306. {config.fail && !wiring && (
  307. <p className="ops-form-error" role="alert">{config.fail.message} <Button variant="ghost" size="sm" onClick={config.reload}>重试</Button></p>
  308. )}
  309. <section className="billing-default-card" aria-labelledby="billing-default-title">
  310. <header className="billing-default-heading">
  311. <span className="billing-default-icon" aria-hidden="true"><CalendarDays size={21} /></span>
  312. <h2 id="billing-default-title">全局出账规则</h2>
  313. </header>
  314. <section className="billing-default-row" aria-labelledby="billing-day-title">
  315. <div className="billing-default-copy">
  316. <h3 id="billing-day-title">系统默认对账日</h3>
  317. <p>未单独设置的运营商统一按此日期出账(⛔ 合伙人/运维团队不可自定义对账日)。</p>
  318. </div>
  319. <div className="billing-default-current">
  320. <span>当前默认</span>
  321. <strong>{data ? `每月 ${data.default_recon_day} 日` : wiring ? BACKEND_NOT_WIRED : "—"}</strong>
  322. </div>
  323. <div className="billing-default-edit">
  324. <label htmlFor="billing-default-day">调整对账日</label>
  325. <div>
  326. <span className="ops-select">
  327. <select disabled={!editable} id="billing-default-day" value={draftDay} onChange={(event) => setDraftDay(Number(event.target.value))}>
  328. {Array.from({ length: 28 }, (_, index) => index + 1).map((value) => <option key={value} value={value}>每月 {value} 日</option>)}
  329. </select>
  330. </span>
  331. {isAdmin && <Button disabled={!editable || !data || draftDay === data.default_recon_day} onClick={() => setPending({ kind: "day", next: draftDay })}><Check size={16} />保存默认值</Button>}
  332. </div>
  333. </div>
  334. </section>
  335. <section className="billing-default-row" aria-labelledby="billing-mode-title">
  336. <div className="billing-default-copy">
  337. <h3 id="billing-mode-title">生效时点</h3>
  338. {/* 单选旁固定说明句(2026-11-02 定案新增,⛔ 按场景改写)。 */}
  339. <p>{EFFECTIVE_MODE_NOTE}</p>
  340. </div>
  341. <div className="billing-default-current">
  342. <span>当前模式</span>
  343. <strong>{data ? EFFECTIVE_MODE_TEXT[data.effective_mode] : wiring ? BACKEND_NOT_WIRED : "—"}</strong>
  344. </div>
  345. <div className="billing-default-edit">
  346. <label htmlFor="billing-data-mode">调整生效时点</label>
  347. <div>
  348. <span className="ops-select">
  349. <select disabled={!editable} id="billing-data-mode" value={draftMode} onChange={(event) => setDraftMode(event.target.value as EffectiveMode)}>
  350. <option value="period_snapshot">{EFFECTIVE_MODE_TEXT.period_snapshot}</option>
  351. <option value="live_at_billing">{EFFECTIVE_MODE_TEXT.live_at_billing}</option>
  352. </select>
  353. </span>
  354. {isAdmin && <Button disabled={!editable || !data || draftMode === data.effective_mode} onClick={() => setPending({ kind: "mode", next: draftMode })}><Check size={16} />保存生效时点</Button>}
  355. </div>
  356. </div>
  357. </section>
  358. </section>
  359. <section className="billing-operators ops-list-shell" aria-labelledby="billing-operators-title">
  360. <div className="ops-list-heading">
  361. <div><h2 id="billing-operators-title">运营商出账设置</h2><p>对账日可跟随默认值或单独指定(两态靠取值本身区分,⛔ 另加徽标);付款周期按运营商合同约定记录。</p></div>
  362. <span>{(data?.operators ?? []).length} 家运营商 · {(data?.operators ?? []).filter((row) => row.recon_day != null).length} 家单独设置</span>
  363. </div>
  364. <div className="ops-table-wrap billing-table-wrap" role="region" aria-label="运营商出账设置" tabIndex={0}>
  365. <table className="ops-table billing-table billing-ledger">
  366. <OpsTableColumns widths={[260, 240, 200, 220]} />
  367. <thead><tr><th>运营商 / 所属区域</th><th>对账日</th><th>付款周期</th><th>操作</th></tr></thead>
  368. <tbody>
  369. {(data?.operators ?? []).map((row) => (
  370. <BillingOperatorRow key={row.operator_id} row={row} defaultDay={data?.default_recon_day ?? draftDay}
  371. canSave={editable} onSave={(nextDay, nextCycle) => setPending({ kind: "operator", row, nextDay, nextCycle })} />
  372. ))}
  373. {!(data?.operators ?? []).length && (
  374. <OpsTableEmpty colSpan={4}>
  375. {config.loading ? "加载中…" : wiring ? `出账配置待后端接线,运营商对账日暂不可读(${BACKEND_NOT_WIRED})。` : "暂无可配置出账的运营商。"}
  376. </OpsTableEmpty>
  377. )}
  378. </tbody>
  379. </table>
  380. </div>
  381. </section>
  382. <aside className="billing-guidance">
  383. <Info size={17} />
  384. <div><strong>出账规则</strong><p>对账日限每月 1–28 日,当天核算上一已结束自然月。付款周期只记录付款节奏,不触发扣款;合伙人与运维团队始终跟随系统默认对账日。</p></div>
  385. </aside>
  386. {pending && (
  387. <div className="ops-confirm-backdrop" role="presentation" onMouseDown={() => !busy && setPending(null)}>
  388. <div className="ops-confirm" role="alertdialog" aria-modal="true" aria-labelledby="billing-config-confirm" onMouseDown={(event) => event.stopPropagation()}>
  389. <h2 id="billing-config-confirm">确认保存出账配置</h2>
  390. {pendingLines().map((line) => <p key={line}>{line}</p>)}
  391. {error && <p className="ops-form-error" role="alert">{error}</p>}
  392. <div>
  393. <Button variant="outline" onClick={() => setPending(null)} disabled={busy}>取消</Button>
  394. <Button onClick={doSave} disabled={busy}>{busy ? "保存中…" : "确认保存"}</Button>
  395. </div>
  396. </div>
  397. </div>
  398. )}
  399. {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
  400. </section>
  401. );
  402. }
  403. function BillingOperatorRow({ row, defaultDay, canSave, onSave }: {
  404. row: BillingConfigOperatorRow;
  405. defaultDay: number;
  406. canSave: boolean;
  407. onSave: (nextDay: number | null, nextCycle: string) => void;
  408. }) {
  409. const [draftDay, setDraftDay] = useState(row.recon_day === null ? "" : String(row.recon_day));
  410. const [draftCycle, setDraftCycle] = useState(row.pay_cycle ?? "");
  411. useEffect(() => {
  412. setDraftDay(row.recon_day === null ? "" : String(row.recon_day));
  413. setDraftCycle(row.pay_cycle ?? "");
  414. }, [row.recon_day, row.pay_cycle]);
  415. const changed = draftDay !== (row.recon_day === null ? "" : String(row.recon_day)) || draftCycle !== (row.pay_cycle ?? "");
  416. const reset = () => {
  417. setDraftDay(row.recon_day === null ? "" : String(row.recon_day));
  418. setDraftCycle(row.pay_cycle ?? "");
  419. };
  420. // 行内写复用 operator/update@v1(name/brand/region_node_id 必传):config_get 未下发后两列 ⇒ 禁用并说明。
  421. const rowWritable = Boolean(row.brand && row.region_node_id);
  422. return (
  423. <tr>
  424. <td><strong title={row.name}>{row.name}</strong><small title={row.region_label ?? ""}>{row.region_label ?? "—"}</small></td>
  425. <td>
  426. <label className="billing-field">
  427. <span className="sr-only">{row.name}对账日</span>
  428. <select disabled={!canSave} aria-label={`${row.name}对账日`} value={draftDay} onChange={(event) => setDraftDay(event.target.value)}>
  429. <option value="">跟随系统默认({defaultDay} 日)</option>
  430. {Array.from({ length: 28 }, (_, index) => index + 1).map((value) => <option key={value} value={value}>每月 {value} 日</option>)}
  431. </select>
  432. </label>
  433. </td>
  434. <td>
  435. <label className="billing-field">
  436. <span className="sr-only">{row.name}付款周期</span>
  437. <select disabled={!canSave} aria-label={`${row.name}付款周期`} value={draftCycle} onChange={(event) => setDraftCycle(event.target.value)}>
  438. <option value="">未设置</option>
  439. {["月付", "两月付", "季付"].map((cycle) => <option key={cycle} value={cycle}>{cycle}</option>)}
  440. </select>
  441. </label>
  442. </td>
  443. <td>
  444. <div className="billing-row-actions">
  445. {changed && <button aria-label={`撤销${row.name}的修改`} className="ops-table-action" onClick={reset} type="button"><RotateCcw size={14} />撤销</button>}
  446. <Button disabled={!canSave || !changed || !rowWritable} size="sm"
  447. title={!rowWritable ? "档案字段未随配置下发,行内保存暂不可用(待 klt-bos 在 config_get 补 brand/region_node_id,或 operator/update@v1 放开部分更新)" : undefined}
  448. onClick={() => onSave(draftDay ? Number(draftDay) : null, draftCycle)}>保存</Button>
  449. </div>
  450. </td>
  451. </tr>
  452. );
  453. }