SettlementRecordPages.tsx 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. /**
  2. * 册 6《计费与对账出账》四页:FN-05 对账清单(14.1)、批次详情(14.2)、FN-08 账单明细与明细详情(14.3)。
  3. *
  4. * 接线状态(2026-11-11 核实):bos.recon/* 与 bos.bill/* 未在 openapi.yaml 声明 ⇒ 网关 11001 未声明即拒绝。
  5. * 撞 11001 ⇒ 契约占位分支(结构按 14 章落位、横幅标明待接线、数据区「后端未下发」);
  6. * ⛔ 用 settlement-demo/settlement-retries 本地台账冒充真接口(=绕过,本版起不再作为本页数据源)。
  7. * 文案唯一真源 ../lib/copy-billing(逐字复制自册 6 契约 14 章/05 章 §5.1,⛔ 手打转述);
  8. * 「分成方式与取值」列走 ../lib/settle-text 单源(册 4 settle_text,⛔ 本册自造分成取值文案)。
  9. * 禁项:⛔「按金额分成本期不计算」「未对账」「已打回」字样;⛔ 出账状态与批次状态混列;⛔ history.back()。
  10. */
  11. import { useEffect, useId, useState, type FormEvent, type ReactNode } from "react";
  12. import { PageIntro } from "../components/PageIntro";
  13. import { ArrowLeft, ArrowRight, Building2, Calculator, CalendarClock, CalendarDays, ChevronDown, CircleDollarSign, Download, FileSpreadsheet, ListFilter, Receipt, RefreshCw, ScrollText, Search, TriangleAlert, X } from "lucide-react";
  14. import { Link, useLocation, useNavigate, useParams, useSearchParams } from "react-router";
  15. import { Button } from "../components/ui/button";
  16. import { SearchInput } from "../components/ui/search-input";
  17. import { FilterSelect } from "../components/ui/filter-select";
  18. import { MonthFilter } from "../components/ui/month-filter";
  19. import { ServerListPager } from "../components/ListPager";
  20. import { OpsDialog, OpsNotice, OpsStatus, OpsTableColumns, OpsTableEmpty, OpsTag, type OpsTone } from "../components/OperationsKit";
  21. import { RecordTabs } from "../components/RecordTabs";
  22. import { useDemoIdentity } from "../lib/demo-session";
  23. import { entTeamGetList, operatorGetList, partnerGetList, reconExportDetail, reconExportList } from "../lib/api/bos";
  24. import type { BillDetailResult, HolderType, ReconBatchStatus, ReconcileStatus, ReconDetailResult } from "../lib/api/types";
  25. import type { StatusTone } from "../domain/statuses";
  26. import { WORD_FETCH_FAILED } from "../lib/api/lockedCopy";
  27. import { settleTextFromSnapshot } from "../lib/settle-text";
  28. import { useHorizontalOverflow } from "../lib/use-horizontal-overflow";
  29. import {
  30. lastClosedMonth, submitReconRerun,
  31. useBillDetail, useBillList, useReconDetail, useReconList, useReconPeriods,
  32. } from "../lib/recon";
  33. import {
  34. ACTION_FLAG_PENDING_NOTE,
  35. ALL_PERIODS_LABEL,
  36. BACK_TO_BILL_DETAIL,
  37. BACK_TO_BILL_LIST,
  38. BACK_TO_CORRECTIONS,
  39. BACK_TO_RECON_DETAIL,
  40. BACK_TO_RECON_LIST,
  41. BACKEND_NOT_WIRED,
  42. BASE_FLOOR_NOTE,
  43. BATCH_STATUS_TEXT,
  44. BILL_WIRING_NOTE,
  45. COST_UNCONFIGURED_NOTE,
  46. EXECUTOR_SYSTEM,
  47. EXPORT_EMPTY_NOTE,
  48. exportResultNote,
  49. HOLDER_TYPE_TEXT,
  50. MONTH_NO_BATCH_NOTE,
  51. PERIODS_UNAVAILABLE,
  52. periodProgressLine,
  53. PROGRESS_COLLAPSE,
  54. PROGRESS_EXPAND,
  55. RECON_WIRING_NOTE,
  56. RECONCILE_STATUS_TEXT,
  57. RERUN_DIALOG_TITLE,
  58. RERUN_NO_EMPTY_BATCH_NOTE,
  59. RERUN_SUBMIT,
  60. RERUN_VOID_NOTE,
  61. rerunMonthBoundNote,
  62. rerunScopeLine,
  63. S404_EMPTY_NOTE,
  64. saveReconExportCsv,
  65. STAT_CARDS,
  66. TICKET_GAP_LABEL,
  67. ticketGapText,
  68. TRIGGER_TYPE_TEXT,
  69. VOIDED_BY_PREFIX,
  70. ZERO_NOTE_TEXT,
  71. } from "../lib/copy-billing";
  72. import "../styles/operations.css";
  73. import "../styles/settlement-records.css";
  74. /* ── 本地小工具 ─────────────────────────────────────────────────── */
  75. /** 金额列以 `_cents`(分)下发;界面统一两位小数元。 */
  76. const moneyFromCents = (cents: number): string =>
  77. `¥${(cents / 100).toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  78. /** 三态格:null ⇒ 「取数失败」(KLT-S406 单格语义),⛔ 回落 0。 */
  79. const moneyCell = (cents: number | null): string => (cents == null ? WORD_FETCH_FAILED : moneyFromCents(cents));
  80. const reconcileTone: Record<ReconcileStatus, StatusTone> = { settled: "success", abnormal: "danger", unsettled: "neutral" };
  81. const batchTone: Record<ReconBatchStatus, StatusTone> = { pending: "neutral", executed: "success", failed: "danger", voided: "neutral" };
  82. const holderTone: Record<HolderType, OpsTone> = { operator: "brand", partner: "info", ops_team: "warning" };
  83. /**
  84. * 执行时间本地化:后端 `CAST(executed_at AS TEXT)` 下发 UTC 裸串(`2026-11-13 03:49:40.05+00`),
  85. * 直接入列既难读又与手册「执行时间」口径不符 ⇒ 按浏览器时区显示,原文留 `title` 可核。
  86. */
  87. function localTime(iso: string): string {
  88. const d = new Date(iso.includes("T") ? iso : iso.replace(" ", "T"));
  89. if (Number.isNaN(d.getTime())) return iso;
  90. const p = (n: number) => String(n).padStart(2, "0");
  91. return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
  92. }
  93. /**
  94. * 执行人可读化:优先绑定表用户名(`operator_username`);NULL ⇒「系统」(对账§14.2);
  95. * 只有裸 seoh 用户 ID 时标明是 ID,⛔ 把裸 ID 当人名直接渲染。
  96. */
  97. function executorText(e: { operator_user_id: string | null; operator_username?: string | null }): string {
  98. const name = e.operator_username?.trim();
  99. if (name) return name;
  100. return e.operator_user_id ? `用户 ${e.operator_user_id}` : EXECUTOR_SYSTEM;
  101. }
  102. const batchPath = (holderId: string, batchNo: string) =>
  103. `/settlement-batches/${encodeURIComponent(holderId)}/${encodeURIComponent(batchNo)}`;
  104. /** URL 搜索参数筛选(返回列表时保留条件;⛔ 路由级收敛另行处理)。 */
  105. function useListFilters() {
  106. const [params, setParams] = useSearchParams();
  107. const get = (key: string) => params.get(key) ?? "";
  108. const set = (key: string, value: string, resetPage = false) =>
  109. setParams((current) => {
  110. const next = new URLSearchParams(current);
  111. if (resetPage) next.delete("page");
  112. if (value) next.set(key, value);
  113. else next.delete(key);
  114. return next;
  115. }, { replace: true });
  116. const reset = () => setParams({}, { replace: true });
  117. return { get, set, reset };
  118. }
  119. /** 失败原因行末红点(fail_reason 原文悬浮;⚠️ 不是 KLT-* 码,对账§7.1 末格)。 */
  120. function FailDot({ reason }: { reason: string | null }) {
  121. if (!reason) return null;
  122. return <span className="statement-failure-mark" title={reason} aria-label={reason}>●</span>;
  123. }
  124. /* ── 人工补跑对话框(14.1 动作矩阵:仅 admin;入参只三件) ────────── */
  125. function RerunDialog({ onClose }: { onClose: () => void }) {
  126. const navigate = useNavigate();
  127. const location = useLocation();
  128. const typeId = useId();
  129. const holderInputId = useId();
  130. const [maxMonth] = useState(lastClosedMonth);
  131. const [holderType, setHolderType] = useState<HolderType>("operator");
  132. const [holders, setHolders] = useState<{ id: string; name: string }[] | null>(null);
  133. const [holdersError, setHoldersError] = useState("");
  134. const [holderId, setHolderId] = useState("");
  135. const [period, setPeriod] = useState(maxMonth);
  136. const [error, setError] = useState("");
  137. const [busy, setBusy] = useState(false);
  138. const [holderRetry, setHolderRetry] = useState(0);
  139. // 分成方候选=第 1 册三类档案真源列表口(⛔ 本地台账);切换类型时重拉。
  140. useEffect(() => {
  141. let alive = true;
  142. setHolders(null);
  143. setHoldersError("");
  144. setHolderId("");
  145. // ⚠️ bos 列表接口 `page` 以 0 为首页(同 `organization-demo.ts::pagedAll`)⇒ 传 1 会跳过首页,
  146. // dev 数据不足一页时候选恒空(补跑弹窗打不开)。
  147. const load =
  148. holderType === "operator"
  149. ? operatorGetList({ page: 0, page_size: 100 }).then((r) => (r.items ?? []).map((o) => ({ id: o.operator_id, name: o.name })))
  150. : holderType === "partner"
  151. ? partnerGetList({ page: 0, page_size: 100 }).then((r) => (r.items ?? []).map((p) => ({ id: p.partner_id, name: p.name })))
  152. : entTeamGetList({ page: 0, page_size: 100 }).then((r) => (r.items ?? []).map((t) => ({ id: t.team_id, name: t.team_name })));
  153. load
  154. .then((rows) => {
  155. if (!alive) return;
  156. setHolders(rows);
  157. setHolderId(rows[0]?.id ?? "");
  158. })
  159. .catch((e: unknown) => {
  160. if (alive) setHoldersError(e instanceof Error ? e.message : WORD_FETCH_FAILED);
  161. });
  162. return () => {
  163. alive = false;
  164. };
  165. }, [holderType, holderRetry]);
  166. function submit(event: FormEvent) {
  167. event.preventDefault();
  168. if (busy) return;
  169. if (!holderId || !period) {
  170. setError(!holderId ? "请选择分成方。" : "请选择自然月。");
  171. return;
  172. }
  173. setBusy(true);
  174. setError("");
  175. submitReconRerun({ holder_type: holderType, holder_id: holderId, period })
  176. .then((res) => {
  177. onClose();
  178. navigate(batchPath(holderId, res.batch_no), {
  179. state: { from: location.pathname, listSearch: location.search },
  180. });
  181. })
  182. .catch((e: unknown) => {
  183. // 四道闸(60502→60503→60504→60506)/KLT-S407:文案直读后端 message(出路句由服务端带出)。
  184. setError(e instanceof Error && e.message ? e.message : "补跑失败,请重试。");
  185. setBusy(false);
  186. });
  187. }
  188. // 弹窗须写明补跑对象(分成方名称+月份),⛔ 只回显 ID。
  189. const holderName = holders?.find((h) => h.id === holderId)?.name;
  190. const close = () => { if (!busy) onClose(); };
  191. return (
  192. <OpsDialog title={RERUN_DIALOG_TITLE} className="statement-run-dialog" onClose={close}>
  193. <form onSubmit={submit}>
  194. <div className="statement-run-body">
  195. <fieldset className="statement-run-fields" aria-label="补跑条件" disabled={busy}>
  196. <div className="statement-run-field">
  197. <label htmlFor={typeId}>分成方类型</label>
  198. <FilterSelect id={typeId} icon="type" value={holderType} onChange={(event) => {
  199. setError("");
  200. setHolderType(event.target.value as HolderType);
  201. }}>
  202. <option value="operator">{HOLDER_TYPE_TEXT.operator}</option>
  203. <option value="partner">{HOLDER_TYPE_TEXT.partner}</option>
  204. <option value="ops_team">{HOLDER_TYPE_TEXT.ops_team}</option>
  205. </FilterSelect>
  206. </div>
  207. <div className="statement-run-field">
  208. <span>账期</span>
  209. <MonthFilter value={period} onChange={(value) => { setPeriod(value); setError(""); }} maxMonth={maxMonth} allowAll={false} />
  210. </div>
  211. <div className="statement-run-field statement-run-party">
  212. <label htmlFor={holderInputId}>分成方</label>
  213. <FilterSelect id={holderInputId} icon="operator" value={holderId} placeholder={!holderId} disabled={!holders?.length}
  214. onChange={(event) => { setHolderId(event.target.value); setError(""); }}>
  215. {!holders?.length && <option value="">{holdersError ? "分成方加载失败" : holders ? "暂无可选分成方" : "正在加载分成方…"}</option>}
  216. {holders?.map((h) => <option key={h.id} value={h.id}>{h.name}</option>)}
  217. </FilterSelect>
  218. {holdersError && <div className="statement-run-load-error">
  219. <p role="alert">{holdersError}</p>
  220. <Button variant="ghost" size="sm" onClick={() => setHolderRetry((value) => value + 1)}>重试</Button>
  221. </div>}
  222. </div>
  223. </fieldset>
  224. <div className="statement-run-scope">
  225. <CalendarClock size={19} aria-hidden="true" />
  226. <div>
  227. <strong>{holderName ? rerunScopeLine(holderName, period) : "选择分成方后即可确认补跑范围"}</strong>
  228. <p>{rerunMonthBoundNote(maxMonth)}</p>
  229. </div>
  230. </div>
  231. <div className="statement-run-impact">
  232. <TriangleAlert size={16} aria-hidden="true" />
  233. <div><p>{RERUN_VOID_NOTE}</p><p>{RERUN_NO_EMPTY_BATCH_NOTE}</p></div>
  234. </div>
  235. {error && <p className="ops-form-error statement-run-error" role="alert">{error}</p>}
  236. </div>
  237. <footer>
  238. <Button variant="outline" type="button" onClick={close} disabled={busy}>取消</Button>
  239. <Button type="submit" disabled={busy || !holderId || !period}>{busy ? "正在补跑…" : RERUN_SUBMIT}</Button>
  240. </footer>
  241. </form>
  242. </OpsDialog>
  243. );
  244. }
  245. /* ── FN-05 对账清单(14.1) ─────────────────────────────────────── */
  246. const statementColumns = [
  247. { label: "对账单号", width: 168 }, { label: "分成方", width: 190 },
  248. { label: "自然月", width: 86 }, { label: "应出账日期", width: 108 },
  249. { label: "触发方式", width: 92 }, { label: "明细条数", width: 84 },
  250. { label: "总金额", width: 112 }, { label: "分成金额", width: 116 },
  251. { label: "出账状态", width: 98 }, { label: "批次状态", width: 114 },
  252. { label: "执行人", width: 100 }, { label: "操作", width: 80 },
  253. ];
  254. const statementTableWidth = statementColumns.reduce((sum, column) => sum + column.width, 0);
  255. export function SettlementStatementListPage() {
  256. const identity = useDemoIdentity();
  257. const location = useLocation();
  258. const filters = useListFilters();
  259. const tableOverflow = useHorizontalOverflow();
  260. const progressId = useId();
  261. // 导出当前结果(B):admin/opsMain/opsSub(demo 角色无 opsSub);⛔ teamLead/partner/operator。
  262. const canExportAll = !identity || identity.role === "admin" || identity.role === "regAdmin";
  263. const isAdmin = !identity || identity.role === "admin";
  264. const lastClosedPeriod = lastClosedMonth();
  265. const monthParam = filters.get("month");
  266. // 无参数时显示全部自然月,同时兼容旧链接的 month=all。
  267. const month = monthParam === "all" ? "" : monthParam;
  268. const type = filters.get("type");
  269. const party = filters.get("party");
  270. const reconcile = filters.get("reconcile");
  271. const status = filters.get("status");
  272. const trigger = filters.get("trigger");
  273. const zero = filters.get("zero") === "1";
  274. const q = filters.get("q");
  275. const page = Number(filters.get("page") || "1") || 1;
  276. const hasFilter = Boolean(month || type || party || reconcile || status || trigger || zero || q);
  277. const periodsFetch = useReconPeriods();
  278. // D-19:下拉选项=接口期次 ∪ 上一个已结束自然月(与人工补跑弹窗 `lastClosedMonth()` 同基准)。
  279. // 仅有历史批、尚无「上月」批时,仍须能选上月(可能空表),⛔ 静默退到更早月造成「弹窗说 10 月、清单只到 9 月」。
  280. const periods = (() => {
  281. const raw = periodsFetch.data?.periods ?? null;
  282. if (!raw) return null;
  283. if (raw.includes(lastClosedPeriod)) return raw;
  284. return [lastClosedPeriod, ...raw];
  285. })();
  286. // 仅纠正不在选项内的显式月份(例如旧书签中的月份)。
  287. const [monthFallback, setMonthFallback] = useState(false);
  288. useEffect(() => {
  289. if (!periods?.length) return;
  290. if (!month || periods.includes(month)) {
  291. setMonthFallback(false);
  292. return;
  293. }
  294. filters.set("month", periods[0], true);
  295. setMonthFallback(true);
  296. // eslint-disable-next-line react-hooks/exhaustive-deps
  297. }, [periods, month]);
  298. const list = useReconList({
  299. period: month,
  300. holderType: type,
  301. holderKw: party,
  302. reconcileStatus: reconcile,
  303. batchStatus: status,
  304. trigger,
  305. includeZero: zero,
  306. keyword: q,
  307. page,
  308. });
  309. const data = list.data;
  310. const wiring = list.fail?.kind === "wiring";
  311. const s404 = list.fail?.kind === "s404";
  312. const rows = data?.items ?? [];
  313. const total = data?.total ?? 0;
  314. const pageSize = 20;
  315. const [notice, setNotice] = useState("");
  316. const [runOpen, setRunOpen] = useState(false);
  317. const [progressOpen, setProgressOpen] = useState(false);
  318. const [exporting, setExporting] = useState(false);
  319. const tableClass = [
  320. "measured-table-scroll ops-table-wrap statement-ledger-scroll",
  321. tableOverflow.overflow && "has-horizontal-overflow",
  322. tableOverflow.width >= 900 && "can-pin-identity",
  323. tableOverflow.canScrollLeft && "can-scroll-left",
  324. tableOverflow.canScrollRight && "can-scroll-right",
  325. ].filter(Boolean).join(" ");
  326. const listState = { from: "/settlement-batches", listSearch: location.search };
  327. async function exportAll() {
  328. if (exporting || list.loading) return;
  329. // 筛选无结果 ⇒ 只提示、不导出、无错误码(14.1 动作矩阵)。
  330. if (!rows.length) {
  331. setNotice(EXPORT_EMPTY_NOTE);
  332. return;
  333. }
  334. setExporting(true);
  335. try {
  336. const result = await reconExportList({ period: month || undefined, holder_type: type || undefined, status: status || undefined });
  337. setNotice(saveReconExportCsv(result) ? exportResultNote(result) : EXPORT_EMPTY_NOTE);
  338. } catch (e: unknown) {
  339. setNotice(e instanceof Error && e.message ? e.message : WORD_FETCH_FAILED);
  340. } finally {
  341. setExporting(false);
  342. }
  343. }
  344. return (
  345. <section className="ops-page reconcile-index page-fill page-fill-window">
  346. <header className="ops-heading statement-heading">
  347. <div>
  348. <h1>对账清单</h1>
  349. <PageIntro>每个账期出账后,按分成方核对批次状态和结算结果。</PageIntro>
  350. </div>
  351. {(canExportAll || isAdmin) && <div className="statement-heading-actions">
  352. {canExportAll && <Button variant="outline" disabled={list.loading || exporting} onClick={exportAll}>
  353. <Download size={16} aria-hidden="true" />{exporting ? "正在导出…" : "导出当前结果"}
  354. </Button>}
  355. {isAdmin && <Button onClick={() => setRunOpen(true)}><RefreshCw size={16} aria-hidden="true" />人工补跑</Button>}
  356. </div>}
  357. </header>
  358. {runOpen && <RerunDialog onClose={() => setRunOpen(false)} />}
  359. {/* 接线占位横幅(klt-bos recon/* 未交付;交付后本分支自然失效) */}
  360. {wiring && <p className="ops-import-note" role="status">{RECON_WIRING_NOTE}</p>}
  361. {periodsFetch.fail && !wiring && <p className="ops-import-note" role="status">{PERIODS_UNAVAILABLE}</p>}
  362. {monthFallback && !rows.length && <p className="ops-import-note" role="status">{MONTH_NO_BATCH_NOTE}</p>}
  363. {/* ② 三统计卡:与列表同一响应同一行集;S404 ⇒ 整体不渲染(不是显示 0);单格 null ⇒「取数失败」。 */}
  364. {!s404 && (wiring || data) && (
  365. <div className="statement-totals" role="group" aria-label="当前筛选结果统计">
  366. {STAT_CARDS.map((card) => {
  367. const value = data?.stats[`total_${card.key}_cents`] ?? null;
  368. return (
  369. <div key={card.key} data-total={card.key}>
  370. <span>{card.title}</span>
  371. <strong className={wiring || value == null ? "statement-total-empty" : undefined}>{wiring ? BACKEND_NOT_WIRED : moneyCell(value)}</strong>
  372. <small>{card.subtitle}</small>
  373. </div>
  374. );
  375. })}
  376. </div>
  377. )}
  378. {/* ③-1 期次出账进度(常驻;只随自然月变化,⛔ 随其余筛选变;后端未下发 ⇒ 不渲)。 */}
  379. {data?.progress && (
  380. <section className="statement-progress" aria-label="期次出账进度">
  381. <div className="statement-progress-line">
  382. <CalendarClock size={18} aria-hidden="true" />
  383. <p role="status">{periodProgressLine(data.progress)}</p>
  384. <Button variant="ghost" size="sm" aria-expanded={progressOpen} aria-controls={progressId} onClick={() => setProgressOpen((v) => !v)}>
  385. {progressOpen ? PROGRESS_COLLAPSE : PROGRESS_EXPAND}<ChevronDown size={14} aria-hidden="true" />
  386. </Button>
  387. </div>
  388. <div id={progressId} hidden={!progressOpen} className="ops-table-wrap statement-progress-table">
  389. {progressOpen && (
  390. <table className="ops-table">
  391. <thead><tr><th>分成方</th><th>建档区域</th><th>对账日</th><th>本期应出账日期</th><th>状态</th><th>对账单号</th></tr></thead>
  392. <tbody>
  393. {data.progress.items.map((item) => (
  394. <tr key={`${item.holder_type}-${item.holder_id}`}>
  395. <td>
  396. <strong className="table-cell-title" title={item.holder_name}>{item.holder_name}</strong>
  397. <OpsTag tone={holderTone[item.holder_type]}>{HOLDER_TYPE_TEXT[item.holder_type]}</OpsTag>
  398. </td>
  399. <td>{item.region_label ?? <span className="table-placeholder">—</span>}</td>
  400. <td>{item.recon_day} 日</td>
  401. <td>{item.expected_date}</td>
  402. <td>{item.status}</td>
  403. <td className="ops-mono">{item.batch_no ?? <span className="table-placeholder">—</span>}</td>
  404. </tr>
  405. ))}
  406. </tbody>
  407. </table>
  408. )}
  409. </div>
  410. </section>
  411. )}
  412. {/* ④ 批次清单 */}
  413. <div className="reconcile-ledger list-shell-fill">
  414. {/* ③ 筛选条:自然月(periods 口)/分成方类型/分成方(可搜)/出账状态/批次状态/对账单号关键字/零明细开关/重置筛选。 */}
  415. <div className="ops-toolbar reconcile-filters statement-filters" role="group" aria-label="对账清单筛选">
  416. <label className="ops-search">
  417. <Search size={17} aria-hidden="true" />
  418. <SearchInput aria-label="搜索对账单号" placeholder="搜索对账单号" value={q}
  419. onCommit={(value) => filters.set("q", value, true)} />
  420. {q && <button type="button" aria-label="清空对账单号" onClick={() => filters.set("q", "", true)}><X size={15} aria-hidden="true" /></button>}
  421. </label>
  422. <label className="ops-search">
  423. <Search size={17} aria-hidden="true" />
  424. <SearchInput aria-label="搜索分成方" placeholder="搜索分成方" value={party}
  425. onCommit={(value) => filters.set("party", value, true)} />
  426. {party && <button type="button" aria-label="清空分成方" onClick={() => filters.set("party", "", true)}><X size={15} aria-hidden="true" /></button>}
  427. </label>
  428. <MonthFilter value={month} availableMonths={periods ?? (month ? [month] : [])} onChange={(value) => filters.set("month", value, true)} />
  429. <FilterSelect icon="type" aria-label="分成方类型" value={type} onChange={(event) => filters.set("type", event.target.value, true)}>
  430. <option value="">全部类型</option>
  431. <option value="operator">{HOLDER_TYPE_TEXT.operator}</option>
  432. <option value="partner">{HOLDER_TYPE_TEXT.partner}</option>
  433. <option value="ops_team">{HOLDER_TYPE_TEXT.ops_team}</option>
  434. </FilterSelect>
  435. {/* 出账状态与批次状态是两个独立下拉(⚠️ 合并=缺陷);出账状态⛔ 出现「待执行」「已作废」。 */}
  436. <FilterSelect icon="status" aria-label="出账状态" value={reconcile} onChange={(event) => filters.set("reconcile", event.target.value, true)}>
  437. <option value="">全部出账状态</option>
  438. <option value="settled">{RECONCILE_STATUS_TEXT.settled}</option>
  439. <option value="abnormal">{RECONCILE_STATUS_TEXT.abnormal}</option>
  440. <option value="unsettled">{RECONCILE_STATUS_TEXT.unsettled}</option>
  441. </FilterSelect>
  442. <FilterSelect icon="task" aria-label="批次状态" value={status} onChange={(event) => filters.set("status", event.target.value, true)}>
  443. <option value="">全部批次状态</option>
  444. <option value="pending">{BATCH_STATUS_TEXT.pending}</option>
  445. <option value="executed">{BATCH_STATUS_TEXT.executed}</option>
  446. <option value="failed">{BATCH_STATUS_TEXT.failed}</option>
  447. <option value="voided">{BATCH_STATUS_TEXT.voided}</option>
  448. </FilterSelect>
  449. {/* 触发方式(手册步序:批次状态之后、关键字之前):只两值,⛔ 第三值。 */}
  450. <FilterSelect icon="action" aria-label="触发方式" value={trigger} onChange={(event) => filters.set("trigger", event.target.value, true)}>
  451. <option value="">全部触发方式</option>
  452. {(["manual", "auto"] as const).map((key) => <option key={key} value={key}>{TRIGGER_TYPE_TEXT[key]}</option>)}
  453. </FilterSelect>
  454. <Button variant={zero ? "default" : "outline"} size="sm" className="h-[38px] shrink-0" aria-pressed={zero}
  455. onClick={() => filters.set("zero", zero ? "" : "1", true)}><ListFilter size={15} aria-hidden="true" />零明细批次</Button>
  456. {hasFilter && <Button variant="ghost" size="sm" onClick={() => { filters.reset(); setMonthFallback(false); }}>重置筛选</Button>}
  457. </div>
  458. {/* S404 触顶 ⇒ 不渲染三卡与列表(⚠️ 禁止静默截断)。 */}
  459. <div className={tableClass} ref={tableOverflow.ref} role="region" aria-label="对账批次,可横向滚动查看字段" tabIndex={0}>
  460. {s404 ? <p className="ops-import-note" role="alert">{S404_EMPTY_NOTE}</p> : (
  461. <table className="ops-table statement-ledger" style={{ minWidth: statementTableWidth }}>
  462. <OpsTableColumns widths={statementColumns.map(({ width }) => width)} />
  463. <thead>
  464. <tr>{statementColumns.map(({ label }) => <th key={label} scope="col">{label}</th>)}</tr>
  465. </thead>
  466. <tbody>
  467. {rows.map((row) => (
  468. <tr key={row.batch_no}>
  469. <td>
  470. <span className="table-cell-title" title={row.batch_no}>{row.batch_no}</span>
  471. </td>
  472. <td><strong className="table-cell-title" title={row.holder_name}>{row.holder_name}</strong>
  473. <div className="statement-holder-type"><OpsTag tone={holderTone[row.holder_type]}>{HOLDER_TYPE_TEXT[row.holder_type]}</OpsTag></div>
  474. </td>
  475. <td><span className="ops-mono">{row.period}</span></td>
  476. <td>{row.recon_date}</td>
  477. <td><OpsTag tone={row.trigger_type === "manual" ? "warning" : "neutral"}>{TRIGGER_TYPE_TEXT[row.trigger_type]}</OpsTag></td>
  478. <td><span className="table-number">{row.detail_count}</span><span className="statement-unit"> 条</span></td>
  479. <td><span className="table-number" title={moneyFromCents(row.base_cents)}>{moneyFromCents(row.base_cents)}</span></td>
  480. <td><span className="table-number statement-share" title={moneyFromCents(row.share_cents)}>{moneyFromCents(row.share_cents)}</span></td>
  481. <td><OpsStatus tone={reconcileTone[row.reconcile_status]}>{RECONCILE_STATUS_TEXT[row.reconcile_status]}</OpsStatus></td>
  482. <td>
  483. <div className="statement-batch-status">
  484. <OpsStatus tone={batchTone[row.status]}>{BATCH_STATUS_TEXT[row.status]}</OpsStatus>
  485. {row.status === "failed" && <FailDot reason={row.fail_reason} />}
  486. </div>
  487. </td>
  488. <td title={executorText(row)}>{executorText(row)}</td>
  489. <td>
  490. <Link className="ops-table-action" to={batchPath(row.holder_id, row.batch_no)} state={listState}>
  491. 详情<ArrowRight size={14} aria-hidden="true" />
  492. </Link>
  493. </td>
  494. </tr>
  495. ))}
  496. {!rows.length && (
  497. <OpsTableEmpty colSpan={statementColumns.length}>
  498. {list.loading ? "加载中…" : wiring ? "对账接口待后端接线,批次数据暂不可读。" : "没有符合筛选条件的对账清单。"}
  499. </OpsTableEmpty>
  500. )}
  501. </tbody>
  502. </table>
  503. )}
  504. </div>
  505. {!s404 && (
  506. <ServerListPager
  507. total={total}
  508. page={page}
  509. pageSize={pageSize}
  510. onPageChange={(next) => filters.set("page", String(next))}
  511. />
  512. )}
  513. </div>
  514. {list.fail && !wiring && !s404 && (
  515. <p className="ops-form-error" role="alert">{list.fail.message} <Button variant="ghost" size="sm" onClick={list.reload}>重试</Button></p>
  516. )}
  517. {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
  518. </section>
  519. );
  520. }
  521. /* ── 批次详情(14.2) ───────────────────────────────────────────── */
  522. export function SettlementStatementRecordPage() {
  523. const identity = useDemoIdentity();
  524. const navigate = useNavigate();
  525. const location = useLocation();
  526. const { no } = useParams();
  527. const state = (location.state ?? {}) as { from?: string; listSearch?: string };
  528. // 返回恒回进来那一页(总则§16.11;⛔ history.back());账单明细来路带 listSearch 保留筛选。
  529. const back = state.from === "/correction-notes"
  530. ? { to: "/correction-notes", label: BACK_TO_CORRECTIONS }
  531. : state.from?.startsWith("/settlement-bills/")
  532. ? { to: state.from, label: BACK_TO_BILL_DETAIL }
  533. : state.from === "/settlement-bills"
  534. ? { to: `/settlement-bills${state.listSearch ?? ""}`, label: BACK_TO_BILL_LIST }
  535. : { to: `/settlement-batches${state.listSearch ?? ""}`, label: BACK_TO_RECON_LIST };
  536. const detail = useReconDetail(no ?? null);
  537. const d = detail.data;
  538. const wiring = detail.fail?.kind === "wiring";
  539. const isAdmin = !identity || identity.role === "admin";
  540. const [confirmRerun, setConfirmRerun] = useState(false);
  541. const [rerunError, setRerunError] = useState("");
  542. const [busy, setBusy] = useState(false);
  543. const [notice, setNotice] = useState("");
  544. function runRerun() {
  545. if (!d) return;
  546. setBusy(true);
  547. setRerunError("");
  548. submitReconRerun({ holder_type: d.holder_type, holder_id: d.holder_id, period: d.period })
  549. .then((res) => {
  550. setConfirmRerun(false);
  551. // 补跑成功 ⇒ 原批次作废、生成新批;直接落到新批详情(来路保留)。
  552. navigate(batchPath(d.holder_id, res.batch_no), { state: location.state, replace: true });
  553. })
  554. .catch((e: unknown) => {
  555. // 四道闸(60502→60503→60504→60506)/KLT-S407:文案直读后端 message。
  556. setRerunError(e instanceof Error && e.message ? e.message : "补跑失败,请重试。");
  557. setBusy(false);
  558. });
  559. }
  560. function exportDetail() {
  561. if (!d) return;
  562. reconExportDetail({ batch_id: d.batch_no })
  563. .then((res) => setNotice(saveReconExportCsv(res) ? exportResultNote(res) : EXPORT_EMPTY_NOTE))
  564. .catch((e: unknown) => setNotice(e instanceof Error && e.message ? e.message : WORD_FETCH_FAILED));
  565. }
  566. return (
  567. <article className="ops-page reconcile-record">
  568. <Link className="ops-back-link" to={back.to}><ArrowLeft size={16} />{back.label}</Link>
  569. {wiring && <p className="ops-import-note" role="status">{RECON_WIRING_NOTE}</p>}
  570. {detail.fail && !wiring && (
  571. <p className="ops-form-error" role="alert">{detail.fail.message} <Button variant="ghost" size="sm" onClick={detail.reload}>重试</Button></p>
  572. )}
  573. {/* 契约占位分支:八字段头结构落位、值格「后端未下发」。 */}
  574. {(wiring || (!d && detail.loading)) && (
  575. <header className="reconcile-record-hero">
  576. <div className="reconcile-record-symbol"><FileSpreadsheet size={27} /></div>
  577. <div>
  578. <span className="reconcile-record-eyebrow">RECONCILIATION / {no}</span>
  579. <h1>批次详情</h1>
  580. <p>{detail.loading && !wiring ? "加载中…" : BACKEND_NOT_WIRED}</p>
  581. </div>
  582. </header>
  583. )}
  584. {d && <BatchDetailBody
  585. d={d}
  586. isAdmin={isAdmin}
  587. onRerun={() => { setRerunError(""); setConfirmRerun(true); }}
  588. onExport={exportDetail}
  589. onCorrect={() => navigate("/correction-notes", { state: { ref: d.batch_no } })}
  590. lineState={{ from: location.pathname }}
  591. />}
  592. {confirmRerun && d && (
  593. <div className="ops-confirm-backdrop" role="presentation" onMouseDown={() => !busy && setConfirmRerun(false)}>
  594. <div className="ops-confirm" role="alertdialog" aria-modal="true" aria-labelledby="rerun-confirm-title" onMouseDown={(event) => event.stopPropagation()}>
  595. <h2 id="rerun-confirm-title">{RERUN_DIALOG_TITLE}</h2>
  596. <p>{rerunScopeLine(d.holder_name, d.period)}</p>
  597. {/* failed 批补跑区追加句(§8.6 界面唯一落点之一)。 */}
  598. {d.status === "failed" && <p>{RERUN_VOID_NOTE}</p>}
  599. {rerunError && <p className="ops-form-error" role="alert">{rerunError}</p>}
  600. <div>
  601. <Button variant="outline" onClick={() => setConfirmRerun(false)} disabled={busy}>取消</Button>
  602. <Button onClick={runRerun} disabled={busy}>{busy ? "提交中…" : RERUN_SUBMIT}</Button>
  603. </div>
  604. </div>
  605. </div>
  606. )}
  607. {notice && <OpsNotice message={notice} onClose={() => setNotice("")} />}
  608. </article>
  609. );
  610. }
  611. function BatchDetailBody({ d, isAdmin, onRerun, onExport, onCorrect, lineState }: {
  612. d: ReconDetailResult;
  613. isAdmin: boolean;
  614. onRerun: () => void;
  615. onExport: () => void;
  616. onCorrect: () => void;
  617. lineState: { from: string };
  618. }) {
  619. // 动作可用性=服务端布尔位(与对账§5.5.4 同源常量;⚠️ 前端按角色自猜=第二套判据)。
  620. // null ⇒ 后端未下发 ⇒ 禁用+「可操作性位后端未下发」说明。
  621. const rerunEnabled = isAdmin && d.can_rerun === true;
  622. const exportEnabled = d.can_export === true;
  623. const correctEnabled = isAdmin && d.can_correct === true;
  624. const flagPending = d.can_rerun == null || d.can_export == null || d.can_correct == null;
  625. return (
  626. <>
  627. <header className="reconcile-record-hero">
  628. <div className="reconcile-record-symbol"><FileSpreadsheet size={27} /></div>
  629. <div>
  630. <span className="reconcile-record-eyebrow">RECONCILIATION / {d.batch_no}</span>
  631. <h1>批次详情</h1>
  632. <p>
  633. <strong>{d.holder_name}</strong>
  634. <span>{HOLDER_TYPE_TEXT[d.holder_type]}</span>
  635. <span>自然月 {d.period}</span>
  636. <span>{TRIGGER_TYPE_TEXT[d.trigger_type]}触发 · {executorText(d)}执行</span>
  637. </p>
  638. <div className="reconcile-hero-pills">
  639. <OpsStatus tone={batchTone[d.status]}>{BATCH_STATUS_TEXT[d.status]}</OpsStatus>
  640. <OpsTag tone={d.trigger_type === "manual" ? "warning" : "neutral"}>{TRIGGER_TYPE_TEXT[d.trigger_type]}触发</OpsTag>
  641. </div>
  642. </div>
  643. </header>
  644. <div className="reconcile-record-stats">
  645. <div><span>明细条数</span><strong>{d.detail_count}</strong><small>本批有效行现算,作废行不计</small></div>
  646. <div><span>总金额</span><strong>{moneyFromCents(d.base_cents)}</strong><small>本批有效行应收基数合计</small></div>
  647. <div><span>分成金额</span><strong>{moneyFromCents(d.share_cents)}</strong><small>本批有效行分成金额合计</small></div>
  648. <div>
  649. <span>{TICKET_GAP_LABEL}</span>
  650. <strong>{d.ticket_gap_failed ? WORD_FETCH_FAILED : d.ticket_gap_count == null ? BACKEND_NOT_WIRED : ticketGapText(d.ticket_gap_count)}</strong>
  651. <small>{TICKET_GAP_LABEL}按工单台账现算(0 个缺口与取数失败是两回事)</small>
  652. </div>
  653. </div>
  654. <section className="reconcile-record-section">
  655. <div className="reconcile-record-section-head">
  656. <div><h2>执行结果</h2><p>批次动作与执行说明。</p></div>
  657. <div style={{ display: "flex", gap: 8 }}>
  658. {isAdmin && (
  659. <Button variant="outline" onClick={onRerun} disabled={!rerunEnabled} title={d.can_rerun == null ? ACTION_FLAG_PENDING_NOTE : undefined}>人工补跑</Button>
  660. )}
  661. <Button variant="outline" onClick={onExport} disabled={!exportEnabled} title={d.can_export == null ? ACTION_FLAG_PENDING_NOTE : undefined}>
  662. <Download size={15} />导出本批账单明细
  663. </Button>
  664. {isAdmin && (
  665. <Button variant="outline" onClick={onCorrect} disabled={!correctEnabled} title={d.can_correct == null ? ACTION_FLAG_PENDING_NOTE : undefined}>登记更正</Button>
  666. )}
  667. </div>
  668. </div>
  669. {flagPending && <p className="reconcile-footnote">{ACTION_FLAG_PENDING_NOTE},动作暂不可用。</p>}
  670. {/* 失败原因只在 failed/voided 时渲染;voided 必带「由哪一次补跑作废」链接。 */}
  671. {(d.status === "failed" || d.status === "voided") && d.fail_reason && (
  672. <p className="ops-form-error" role="alert">{d.fail_reason}</p>
  673. )}
  674. {d.status === "voided" && d.voided_by_batch_no && (
  675. <p className="reconcile-footnote">
  676. {VOIDED_BY_PREFIX}
  677. <Link className="ops-table-action" to={batchPath(d.holder_id, d.voided_by_batch_no)}>{d.voided_by_batch_no} <ArrowRight size={14} /></Link>
  678. 作废。
  679. </p>
  680. )}
  681. {/* 成本未配置提示一行(不发通知、不建提醒表;不说"异常")。 */}
  682. {d.cost_unconfigured.length > 0 && (
  683. <p className="reconcile-footnote">{COST_UNCONFIGURED_NOTE}:{d.cost_unconfigured.join("、")}</p>
  684. )}
  685. </section>
  686. <section className="reconcile-record-section">
  687. <div className="reconcile-record-section-head">
  688. <span>01</span>
  689. <div><h2>本批账单明细</h2><p>{d.holder_name} · {d.period} · {d.detail_count} 条</p></div>
  690. </div>
  691. <div className="ops-table-wrap">
  692. <table className="ops-table" style={{ minWidth: 980 }}>
  693. <thead><tr><th>客户</th><th>订阅标识</th><th>应收金额</th><th>分成基数</th><th>分成方式与取值</th><th>本方分成金额</th><th>恒 0 说明</th><th>操作</th></tr></thead>
  694. <tbody>
  695. {d.items.map((line) => (
  696. <tr key={line.bill_detail_id}>
  697. <td><strong>{line.customer_name}</strong></td>
  698. <td>{line.subscription_label}</td>
  699. <td><span className="ops-money">{moneyFromCents(line.receivable_cents)}</span></td>
  700. <td><span className="ops-money">{moneyFromCents(line.share_base_cents)}</span></td>
  701. <td className="table-number">{settleTextFromSnapshot(line.share_mode, line.share_value)}</td>
  702. <td><strong className="reconcile-money">{moneyFromCents(line.share_amount_cents)}</strong></td>
  703. {/* zero_note 如实展示并解释为什么是 0(⛔ 隐藏 0 金额行)。 */}
  704. <td>{line.zero_note ? ZERO_NOTE_TEXT[line.zero_note] : <span className="table-placeholder">—</span>}</td>
  705. <td>
  706. <Link className="ops-table-action" to={`/settlement-bills/${encodeURIComponent(line.bill_detail_id)}`} state={lineState}>
  707. 详情
  708. </Link>
  709. </td>
  710. </tr>
  711. ))}
  712. {!d.items.length && <OpsTableEmpty colSpan={8}>本批无明细行。</OpsTableEmpty>}
  713. </tbody>
  714. </table>
  715. </div>
  716. </section>
  717. <section className="reconcile-record-section">
  718. <div className="reconcile-record-section-head"><span>02</span><div><h2>执行与口径</h2><p>批次八字段头与状态说明。</p></div></div>
  719. <dl className="reconcile-record-facts">
  720. <div><dt>对账单号</dt><dd>{d.batch_no}</dd></div>
  721. <div><dt>分成方</dt><dd>{d.holder_name} · {HOLDER_TYPE_TEXT[d.holder_type]}</dd></div>
  722. <div><dt>自然月</dt><dd>{d.period}</dd></div>
  723. <div><dt>应出账日期</dt><dd title="该分成方该自然月的应出账日期=自然月次月的对账日;「每月 N 日」的对账日口径见「出账配置」">{d.recon_date ?? "—"}</dd></div>
  724. <div><dt>批次状态</dt><dd>{BATCH_STATUS_TEXT[d.status]}</dd></div>
  725. <div><dt>执行人</dt><dd title={d.operator_user_id ?? undefined}>{executorText(d)}</dd></div>
  726. <div><dt>执行时间</dt><dd title={d.executed_at ?? undefined}>{d.executed_at ? localTime(d.executed_at) : "—"}</dd></div>
  727. <div><dt>触发方式</dt><dd>{TRIGGER_TYPE_TEXT[d.trigger_type]}</dd></div>
  728. </dl>
  729. <p className="reconcile-footnote">状态以批次当前记录为准。执行失败的批次由总运营补跑;账单差错通过出账更正登记。</p>
  730. </section>
  731. </>
  732. );
  733. }
  734. /* ── FN-08 账单明细(14.3 列表) ─────────────────────────────────── */
  735. export function SettlementBillListPage() {
  736. const location = useLocation();
  737. const filters = useListFilters();
  738. const q = filters.get("q");
  739. const type = filters.get("type");
  740. const month = filters.get("month");
  741. const page = Number(filters.get("page") || "1") || 1;
  742. const hasFilter = Boolean(q || type || month);
  743. // 详情/批次返回时拼回本串,保留筛选(D-2;对齐对账清单 listSearch)。
  744. const listNavState = { from: "/settlement-bills" as const, listSearch: location.search };
  745. const periodsFetch = useReconPeriods();
  746. const periods = periodsFetch.data?.periods ?? null;
  747. const list = useBillList({ period: month, holderType: type, keyword: q, page });
  748. const wiring = list.fail?.kind === "wiring";
  749. const rows = list.data?.items ?? [];
  750. const total = list.data?.total ?? 0;
  751. const pageSize = 20;
  752. return (
  753. <section className="ops-page bill-index page-fill page-fill-window">
  754. <header className="reconcile-page-heading">
  755. <div>
  756. <p className="ops-eyebrow"><span /> BILLING LINES / 分成与对账</p>
  757. <h1>账单明细</h1>
  758. <PageIntro>对账有差异时,按客户和账期追到具体订阅,逐项核对应收、成本和分成。</PageIntro>
  759. </div>
  760. </header>
  761. {wiring && <p className="ops-import-note" role="status">{BILL_WIRING_NOTE}</p>}
  762. <div className="reconcile-ledger list-shell-fill">
  763. <div className="reconcile-filters">
  764. <label className="ops-search">
  765. <Search size={17} />
  766. <SearchInput aria-label="搜索账单明细" placeholder="搜索分成方、客户、订阅或单号" value={q}
  767. onCommit={(value) => { filters.set("page", ""); filters.set("q", value); }} />
  768. {q && <button type="button" aria-label="清空搜索" onClick={() => filters.set("q", "")}><X size={15} /></button>}
  769. </label>
  770. <FilterSelect icon="type" aria-label="分成方类型" value={type} onChange={(event) => { filters.set("page", ""); filters.set("type", event.target.value); }}>
  771. <option value="">全部类型</option>
  772. <option value="operator">{HOLDER_TYPE_TEXT.operator}</option>
  773. <option value="partner">{HOLDER_TYPE_TEXT.partner}</option>
  774. <option value="ops_team">{HOLDER_TYPE_TEXT.ops_team}</option>
  775. </FilterSelect>
  776. <FilterSelect icon="month" aria-label="自然月" value={month} onChange={(event) => { filters.set("page", ""); filters.set("month", event.target.value); }}>
  777. <option value="">{ALL_PERIODS_LABEL}</option>
  778. {(periods ?? []).map((p) => <option key={p} value={p}>{p}</option>)}
  779. </FilterSelect>
  780. {hasFilter && <Button variant="ghost" size="sm" onClick={filters.reset}>重置筛选</Button>}
  781. </div>
  782. <div className="ops-table-wrap">
  783. <table className="ops-table">
  784. <OpsTableColumns widths={[180, 90, 170, 200, 90, 120, 130, 160, 76]} />
  785. <thead><tr><th>分成方</th><th>自然月</th><th>客户</th><th>订阅</th><th>计费天数</th><th>分成基数</th><th>本方分成金额</th><th>对账单号</th><th>操作</th></tr></thead>
  786. <tbody>
  787. {rows.map((row) => (
  788. <tr key={row.bill_detail_id}>
  789. <td><OpsTag tone={holderTone[row.holder_type]}>{HOLDER_TYPE_TEXT[row.holder_type]}</OpsTag> <strong className="table-cell-title">{row.holder_name}</strong></td>
  790. <td><span className="ops-mono">{row.period}</span></td>
  791. <td>{row.customer_name}</td>
  792. <td>{row.subscription_label}</td>
  793. <td className="table-number">{row.billing_days} 天</td>
  794. <td><span className="ops-money">{moneyFromCents(row.share_base_cents)}</span></td>
  795. <td><strong className="reconcile-money">{moneyFromCents(row.share_amount_cents)}</strong></td>
  796. <td>
  797. <Link className="reconcile-row-link" title={row.batch_no} to={batchPath(row.holder_id, row.batch_no)} state={listNavState}>
  798. {row.batch_no}<ArrowRight size={14} />
  799. </Link>
  800. </td>
  801. <td>
  802. <Link className="ops-table-action" to={`/settlement-bills/${encodeURIComponent(row.bill_detail_id)}`} state={listNavState}>
  803. 详情
  804. </Link>
  805. </td>
  806. </tr>
  807. ))}
  808. {!rows.length && (
  809. <OpsTableEmpty colSpan={9}>
  810. {list.loading ? "加载中…" : wiring ? "账单明细接口待后端接线,数据暂不可读。" : "没有符合筛选条件的账单明细。"}
  811. </OpsTableEmpty>
  812. )}
  813. </tbody>
  814. </table>
  815. </div>
  816. <ServerListPager
  817. total={total}
  818. page={page}
  819. pageSize={pageSize}
  820. onPageChange={(next) => filters.set("page", String(next))}
  821. />
  822. </div>
  823. {list.fail && !wiring && (
  824. <p className="ops-form-error" role="alert">{list.fail.message} <Button variant="ghost" size="sm" onClick={list.reload}>重试</Button></p>
  825. )}
  826. </section>
  827. );
  828. }
  829. /* ── FN-08 明细详情(14.3) ──────────────────────────────────────── */
  830. const billRecordTabs = [
  831. { id: "billing", label: "计费概况" },
  832. { id: "costs", label: "成本明细" },
  833. { id: "reconciliation", label: "分成与对账" },
  834. { id: "accounts", label: "分账号计费" },
  835. ] as const;
  836. type BillRecordTab = typeof billRecordTabs[number]["id"];
  837. function BillRecordPanel({ tab, active, children }: { tab: BillRecordTab; active: BillRecordTab; children: ReactNode }) {
  838. return <section className="ops-record-card record-tab-panel bill-record-panel" id={`bill-record-panel-${tab}`}
  839. role="tabpanel" aria-labelledby={`bill-record-tab-${tab}`} tabIndex={0} hidden={active !== tab}>
  840. {children}
  841. </section>;
  842. }
  843. function BillBatchLink({ holderId, number, from }: { holderId: string; number: string; from: string }) {
  844. return <Link className="ops-table-action bill-record-batch-link" to={batchPath(holderId, number)} state={{ from }}>
  845. <span>{number}</span><ArrowRight size={14} aria-hidden="true" />
  846. </Link>;
  847. }
  848. function BillRecordContent({ bill, from }: { bill: BillDetailResult; from: string }) {
  849. const [tab, setTab] = useState<BillRecordTab>("billing");
  850. const actualCost = bill.cost_deduct_cents ?? (bill.receivable_cents - bill.share_base_cents);
  851. const costCapped = bill.base_floor_protected || (
  852. bill.cost_should_deduct_cents != null && bill.cost_deduct_cents != null && bill.cost_should_deduct_cents > bill.cost_deduct_cents
  853. );
  854. const missing = <span className="table-placeholder">—</span>;
  855. return <>
  856. {/* 尾月对齐前后的应收放在同一摘要内,切换页签时仍可对照。 */}
  857. <dl className="customer-record-metrics bill-record-metrics" aria-label="账单金额摘要">
  858. <div>
  859. <dt><Calculator size={16} aria-hidden="true" />尾月对齐前应收</dt>
  860. <dd><strong>{moneyFromCents(bill.pre_align_cents)}</strong></dd>
  861. </div>
  862. <div className="bill-record-metric-primary">
  863. <dt><Receipt size={16} aria-hidden="true" />本期应收(对齐后)</dt>
  864. <dd><strong>{moneyFromCents(bill.receivable_cents)}</strong></dd>
  865. </div>
  866. <div>
  867. <dt><Calculator size={16} aria-hidden="true" />分成基数</dt>
  868. <dd><strong>{moneyFromCents(bill.share_base_cents)}</strong></dd>
  869. </div>
  870. <div>
  871. <dt><CircleDollarSign size={16} aria-hidden="true" />本方分成金额</dt>
  872. <dd><strong className="bill-record-share">{moneyFromCents(bill.share_amount_cents)}</strong>
  873. {bill.zero_note && <small>{ZERO_NOTE_TEXT[bill.zero_note]}</small>}
  874. </dd>
  875. </div>
  876. </dl>
  877. <div className="record-tabs-frame">
  878. <RecordTabs prefix="bill-record" label="账单明细详情视图" tabs={billRecordTabs} active={tab} onChange={setTab} />
  879. <BillRecordPanel tab="billing" active={tab}>
  880. {bill.receivable_calc && <div className="bill-record-calculation">
  881. <Calculator size={17} aria-hidden="true" />
  882. <div><h2>应收计算</h2><p>{bill.receivable_calc}</p></div>
  883. </div>}
  884. <dl className="ops-record-summary bill-record-facts">
  885. <div><dt>计费区间</dt><dd>{(bill.bill_from || bill.bill_to) ? `${bill.bill_from || "—"} ~ ${bill.bill_to || "—"}` : missing}</dd></div>
  886. <div><dt>计费天数</dt><dd>{bill.billing_days} 天</dd></div>
  887. <div><dt>当月天数</dt><dd>{bill.month_days == null ? missing : `${bill.month_days} 天`}</dd></div>
  888. <div><dt>是否不满月</dt><dd>{bill.partial_month ? "是" : "否"}</dd></div>
  889. <div><dt>计费标准单价</dt><dd>{bill.settle_std_cents == null ? missing : moneyFromCents(bill.settle_std_cents)}</dd></div>
  890. <div><dt>订阅份数</dt><dd>{bill.quantity == null ? missing : `${bill.quantity} 份`}</dd></div>
  891. </dl>
  892. </BillRecordPanel>
  893. <BillRecordPanel tab="costs" active={tab}>
  894. <dl className="ops-record-summary bill-record-facts">
  895. <div><dt>成本实扣</dt><dd>{moneyFromCents(actualCost)}</dd></div>
  896. {bill.cost_should_deduct_cents != null && <div><dt>成本应扣(封顶前)</dt><dd>{moneyFromCents(bill.cost_should_deduct_cents)}</dd></div>}
  897. </dl>
  898. {costCapped && <p className="bill-record-note" role="note">成本已按应收封顶(应扣大于实扣时,分成基数按 0 保护)。</p>}
  899. <div className="ops-table-wrap bill-record-table">
  900. <table className="ops-table" aria-label="成本快照">
  901. <OpsTableColumns widths={[40, 22, 14, 24]} />
  902. <thead><tr><th scope="col">成本项</th><th scope="col" className="bill-record-number">单价</th><th scope="col" className="bill-record-number">倍率</th><th scope="col" className="bill-record-number">应扣</th></tr></thead>
  903. <tbody>
  904. {bill.costs.map((cost, i) => {
  905. const price = cost.price_cents ?? cost.amount_cents;
  906. const should = cost.cost_cents ?? cost.fold;
  907. return <tr key={`${cost.item_id ?? cost.item_name}-${i}`}>
  908. <td><div className="bill-record-table-title"><strong className="table-cell-title">{cost.item_name}</strong>{!cost.configured && <OpsTag tone="warning">未配置</OpsTag>}</div></td>
  909. <td className="bill-record-number">{price == null ? missing : <span className="table-number">{moneyFromCents(price)}</span>}</td>
  910. <td className="bill-record-number">{cost.multiplier == null ? missing : <span className="table-number">{cost.multiplier}</span>}</td>
  911. <td className="bill-record-number">{should == null ? missing : <span className="table-number">{moneyFromCents(should)}</span>}</td>
  912. </tr>;
  913. })}
  914. {!bill.costs.length && <OpsTableEmpty colSpan={4}>本行无成本快照。</OpsTableEmpty>}
  915. </tbody>
  916. </table>
  917. </div>
  918. </BillRecordPanel>
  919. <BillRecordPanel tab="reconciliation" active={tab}>
  920. <dl className="ops-record-summary bill-record-facts">
  921. <div><dt>分成方</dt><dd>{bill.holder_name || missing}</dd></div>
  922. <div><dt>分成方式与取值</dt><dd>{settleTextFromSnapshot(bill.share_mode, bill.share_value)}</dd></div>
  923. <div><dt>所属对账单号</dt><dd><BillBatchLink holderId={bill.holder_id} number={bill.batch_no} from={from} /></dd></div>
  924. </dl>
  925. {bill.base_floor_protected && <p className="bill-record-note" role="note">{BASE_FLOOR_NOTE}</p>}
  926. {/* 仅在服务端下发其他分成方时展示。 */}
  927. {bill.other_parties != null && bill.other_parties.length > 0 && <div className="ops-table-wrap bill-record-table">
  928. <table className="ops-table" aria-label="其他分成方">
  929. <OpsTableColumns widths={[40, 23, 37]} />
  930. <thead><tr><th scope="col">其他分成方</th><th scope="col" className="bill-record-number">分成金额</th><th scope="col">对账单号</th></tr></thead>
  931. <tbody>
  932. {bill.other_parties.map((party, i) => <tr key={`${party.holder_type}-${party.holder_name}-${i}`}>
  933. <td><div className="bill-record-table-title"><strong className="table-cell-title">{party.holder_name}</strong><OpsTag tone={holderTone[party.holder_type]}>{HOLDER_TYPE_TEXT[party.holder_type]}</OpsTag></div></td>
  934. <td className="bill-record-number"><span className="table-number">{moneyFromCents(party.share_amount_cents)}</span></td>
  935. <td>{party.batch_no && party.holder_id ? <BillBatchLink holderId={party.holder_id} number={party.batch_no} from={from} /> : party.batch_no ?? missing}</td>
  936. </tr>)}
  937. </tbody>
  938. </table>
  939. </div>}
  940. </BillRecordPanel>
  941. <BillRecordPanel tab="accounts" active={tab}>
  942. {bill.account_days_failed ? <p className="bill-record-note bill-record-error" role="alert">{WORD_FETCH_FAILED}</p>
  943. : bill.account_days == null ? <p className="bill-record-placeholder">{BACKEND_NOT_WIRED}</p>
  944. : <div className="ops-table-wrap bill-record-table">
  945. <table className="ops-table" aria-label="逐账号在期天数">
  946. <OpsTableColumns widths={[70, 30]} />
  947. <thead><tr><th scope="col">分账号</th><th scope="col" className="bill-record-number">在期天数</th></tr></thead>
  948. <tbody>
  949. {bill.account_days.map((row, i) => <tr key={`${row.sub_account_label}-${i}`}>
  950. <td><strong className="table-cell-title">{row.sub_account_label}</strong></td>
  951. <td className="bill-record-number"><span className="table-number">{row.in_period_days}</span> 天</td>
  952. </tr>)}
  953. {!bill.account_days.length && <OpsTableEmpty colSpan={2}>本期无在期分账号。</OpsTableEmpty>}
  954. </tbody>
  955. </table>
  956. </div>}
  957. </BillRecordPanel>
  958. </div>
  959. </>;
  960. }
  961. export function SettlementBillRecordPage() {
  962. const { index } = useParams();
  963. const location = useLocation();
  964. const state = (location.state ?? {}) as { from?: string; listSearch?: string };
  965. const back = state.from === "/correction-notes"
  966. ? { to: "/correction-notes", label: BACK_TO_CORRECTIONS }
  967. : state.from?.startsWith("/settlement-batches/")
  968. ? { to: state.from, label: BACK_TO_RECON_DETAIL }
  969. : { to: `/settlement-bills${state.from === "/settlement-bills" ? (state.listSearch ?? "") : ""}`, label: BACK_TO_BILL_LIST };
  970. const detail = useBillDetail(index ?? null);
  971. const bill = detail.data;
  972. const wiring = detail.fail?.kind === "wiring";
  973. return (
  974. <article className="ops-page ops-record-page record-detail bill-record">
  975. <Link className="ops-back-link" to={back.to}><ArrowLeft size={16} aria-hidden="true" />{back.label.replace(/^←\s*/, "")}</Link>
  976. <header className="customer-record-masthead bill-record-masthead">
  977. <div className="customer-hero-symbol" aria-hidden="true"><FileSpreadsheet size={26} /></div>
  978. <div className="customer-hero-copy">
  979. <p className="customer-record-id">BILLING LINE <span aria-hidden="true">·</span> <span>{bill?.bill_detail_id ?? index}</span></p>
  980. <h1 className="customer-record-title">账单明细详情</h1>
  981. {bill && <div className="customer-record-tags bill-record-context">
  982. <span className="customer-record-meta">
  983. <OpsTag tone={holderTone[bill.holder_type]}>{HOLDER_TYPE_TEXT[bill.holder_type]}</OpsTag>
  984. {bill.holder_name && <strong>{bill.holder_name}</strong>}
  985. </span>
  986. <span className="customer-record-meta"><CalendarDays size={14} aria-hidden="true" /><span>自然月 {bill.period}</span></span>
  987. {bill.customer_name && <span className="customer-record-meta"><Building2 size={14} aria-hidden="true" /><span>{bill.customer_name}</span></span>}
  988. {bill.subscription_label && <span className="customer-record-meta"><ScrollText size={14} aria-hidden="true" /><span>{bill.subscription_label}</span></span>}
  989. </div>}
  990. </div>
  991. </header>
  992. {wiring && <p className="ops-import-note" role="status">{BILL_WIRING_NOTE}</p>}
  993. {detail.fail && !wiring && <p className="ops-form-error" role="alert">
  994. {detail.fail.message} <Button variant="ghost" size="sm" onClick={detail.reload}>重试</Button>
  995. </p>}
  996. {!bill && detail.loading && <p className="bill-record-placeholder" role="status">正在读取账单明细…</p>}
  997. {bill && <BillRecordContent key={bill.bill_detail_id} bill={bill} from={location.pathname} />}
  998. </article>
  999. );
  1000. }