SettlementRecordPages.tsx 59 KB

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