/** * 册 6《计费与对账出账》四页:FN-05 对账清单(14.1)、批次详情(14.2)、FN-08 账单明细与明细详情(14.3)。 * * 接线状态(2026-11-11 核实):bos.recon/* 与 bos.bill/* 未在 openapi.yaml 声明 ⇒ 网关 11001 未声明即拒绝。 * 撞 11001 ⇒ 契约占位分支(结构按 14 章落位、横幅标明待接线、数据区「后端未下发」); * ⛔ 用 settlement-demo/settlement-retries 本地台账冒充真接口(=绕过,本版起不再作为本页数据源)。 * 文案唯一真源 ../lib/copy-billing(逐字复制自册 6 契约 14 章/05 章 §5.1,⛔ 手打转述); * 「分成方式与取值」列走 ../lib/settle-text 单源(册 4 settle_text,⛔ 本册自造分成取值文案)。 * 禁项:⛔「按金额分成本期不计算」「未对账」「已打回」字样;⛔ 出账状态与批次状态混列;⛔ history.back()。 */ import { useEffect, useId, useState, type FormEvent, type ReactNode } from "react"; import { PageIntro } from "../components/PageIntro"; import { ArrowLeft, ArrowRight, Building2, Calculator, CalendarClock, CalendarDays, ChevronDown, CircleDollarSign, ClipboardList, Download, FilePenLine, FileSpreadsheet, ListFilter, Receipt, RefreshCw, ScrollText, Search, TriangleAlert, X } from "lucide-react"; import { Link, useLocation, useNavigate, useParams, useSearchParams } from "react-router"; import { Button } from "../components/ui/button"; import { SearchInput } from "../components/ui/search-input"; import { FilterSelect } from "../components/ui/filter-select"; import { MonthFilter } from "../components/ui/month-filter"; import { ServerListPager } from "../components/ListPager"; import { OpsDialog, OpsNotice, OpsStatus, OpsTableColumns, OpsTableEmpty, OpsTag, type OpsTone } from "../components/OperationsKit"; import { RecordTabs } from "../components/RecordTabs"; import { useDemoIdentity } from "../lib/demo-session"; import { entTeamGetList, operatorGetList, partnerGetList, reconExportDetail, reconExportList } from "../lib/api/bos"; import type { BillDetailResult, HolderType, ReconBatchStatus, ReconcileStatus, ReconDetailResult } from "../lib/api/types"; import type { StatusTone } from "../domain/statuses"; import { WORD_FETCH_FAILED } from "../lib/api/lockedCopy"; import { settleTextFromSnapshot } from "../lib/settle-text"; import { useHorizontalOverflow } from "../lib/use-horizontal-overflow"; import { detailBack, detailLinkState, useDetailLinkState, type DetailLinkState } from "../lib/detail-navigation"; import { lastClosedMonth, submitReconRerun, useBillDetail, useBillList, useReconDetail, useReconList, } from "../lib/recon"; import { ACTION_FLAG_PENDING_NOTE, BACK_TO_BILL_LIST, BACK_TO_RECON_LIST, BACKEND_NOT_WIRED, BASE_FLOOR_NOTE, BATCH_STATUS_TEXT, BILL_WIRING_NOTE, COST_UNCONFIGURED_NOTE, EXECUTOR_SYSTEM, EXPORT_EMPTY_NOTE, exportResultNote, HOLDER_TYPE_TEXT, periodProgressLine, PROGRESS_COLLAPSE, PROGRESS_EXPAND, RECON_WIRING_NOTE, RECONCILE_STATUS_TEXT, RERUN_DIALOG_TITLE, RERUN_NO_EMPTY_BATCH_NOTE, RERUN_SUBMIT, RERUN_VOID_NOTE, rerunMonthBoundNote, rerunScopeLine, S404_EMPTY_NOTE, saveReconExportCsv, STAT_CARDS, TICKET_GAP_LABEL, TRIGGER_TYPE_TEXT, VOIDED_BY_PREFIX, ZERO_NOTE_TEXT, } from "../lib/copy-billing"; import "../styles/operations.css"; import "../styles/settlement-records.css"; /* ── 本地小工具 ─────────────────────────────────────────────────── */ /** 金额列以 `_cents`(分)下发;界面统一两位小数元。 */ const moneyFromCents = (cents: number): string => `¥${(cents / 100).toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; /** 三态格:null ⇒ 「取数失败」(KLT-S406 单格语义),⛔ 回落 0。 */ const moneyCell = (cents: number | null): string => (cents == null ? WORD_FETCH_FAILED : moneyFromCents(cents)); const reconcileTone: Record = { settled: "success", abnormal: "danger", unsettled: "neutral" }; const batchTone: Record = { pending: "neutral", executed: "success", failed: "danger", voided: "neutral" }; const holderTone: Record = { operator: "brand", partner: "info", ops_team: "warning" }; /** * 执行时间本地化:后端 `CAST(executed_at AS TEXT)` 下发 UTC 裸串(`2026-11-13 03:49:40.05+00`), * 直接入列既难读又与手册「执行时间」口径不符 ⇒ 按浏览器时区显示,原文留 `title` 可核。 */ function localTime(iso: string): string { const d = new Date(iso.includes("T") ? iso : iso.replace(" ", "T")); if (Number.isNaN(d.getTime())) return iso; const p = (n: number) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`; } /** * 执行人可读化:优先绑定表用户名(`operator_username`);NULL ⇒「系统」(对账§14.2); * 只有裸 seoh 用户 ID 时标明是 ID,⛔ 把裸 ID 当人名直接渲染。 */ function executorText(e: { operator_user_id: string | null; operator_username?: string | null }): string { const name = e.operator_username?.trim(); if (name) return name; return e.operator_user_id ? `用户 ${e.operator_user_id}` : EXECUTOR_SYSTEM; } const batchPath = (holderId: string, batchNo: string) => `/settlement-batches/${encodeURIComponent(holderId)}/${encodeURIComponent(batchNo)}`; /** URL 搜索参数筛选(返回列表时保留条件;⛔ 路由级收敛另行处理)。 */ function useListFilters() { const { state } = useLocation(); const [params, setParams] = useSearchParams(); const get = (key: string) => params.get(key) ?? ""; const set = (key: string, value: string, resetPage = false) => setParams((current) => { const next = new URLSearchParams(current); if (resetPage) next.delete("page"); if (value) next.set(key, value); else next.delete(key); return next; }, { replace: true, state }); const reset = () => setParams({}, { replace: true, state }); return { get, set, reset }; } /** 失败原因行末红点(fail_reason 原文悬浮;⚠️ 不是 KLT-* 码,对账§7.1 末格)。 */ function FailDot({ reason }: { reason: string | null }) { if (!reason) return null; return ●; } /* ── 人工补跑对话框(14.1 动作矩阵:仅 admin;入参只三件) ────────── */ function RerunDialog({ onClose }: { onClose: () => void }) { const navigate = useNavigate(); const returnState = useDetailLinkState(); const typeId = useId(); const holderInputId = useId(); const [maxMonth] = useState(lastClosedMonth); const [holderType, setHolderType] = useState("operator"); const [holders, setHolders] = useState<{ id: string; name: string }[] | null>(null); const [holdersError, setHoldersError] = useState(""); const [holderId, setHolderId] = useState(""); const [period, setPeriod] = useState(maxMonth); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [holderRetry, setHolderRetry] = useState(0); // 分成方候选=第 1 册三类档案真源列表口(⛔ 本地台账);切换类型时重拉。 useEffect(() => { let alive = true; setHolders(null); setHoldersError(""); setHolderId(""); // ⚠️ bos 列表接口 `page` 以 0 为首页(同 `organization-demo.ts::pagedAll`)⇒ 传 1 会跳过首页, // dev 数据不足一页时候选恒空(补跑弹窗打不开)。 const load = holderType === "operator" ? operatorGetList({ page: 0, page_size: 100 }).then((r) => (r.items ?? []).map((o) => ({ id: o.operator_id, name: o.name }))) : holderType === "partner" ? partnerGetList({ page: 0, page_size: 100 }).then((r) => (r.items ?? []).map((p) => ({ id: p.partner_id, name: p.name }))) : entTeamGetList({ page: 0, page_size: 100 }).then((r) => (r.items ?? []).map((t) => ({ id: t.team_id, name: t.team_name }))); load .then((rows) => { if (!alive) return; setHolders(rows); setHolderId(rows[0]?.id ?? ""); }) .catch((e: unknown) => { if (alive) setHoldersError(e instanceof Error ? e.message : WORD_FETCH_FAILED); }); return () => { alive = false; }; }, [holderType, holderRetry]); function submit(event: FormEvent) { event.preventDefault(); if (busy) return; if (!holderId || !period) { setError(!holderId ? "请选择分成方。" : "请选择自然月。"); return; } setBusy(true); setError(""); submitReconRerun({ holder_type: holderType, holder_id: holderId, period }) .then((res) => { onClose(); navigate(batchPath(holderId, res.batch_no), { state: returnState, }); }) .catch((e: unknown) => { // 四道闸(60502→60503→60504→60506)/KLT-S407:文案直读后端 message(出路句由服务端带出)。 setError(e instanceof Error && e.message ? e.message : "补跑失败,请重试。"); setBusy(false); }); } // 弹窗须写明补跑对象(分成方名称+月份),⛔ 只回显 ID。 const holderName = holders?.find((h) => h.id === holderId)?.name; const close = () => { if (!busy) onClose(); }; return (
{ setError(""); setHolderType(event.target.value as HolderType); }}>
账期 { setPeriod(value); setError(""); }} maxMonth={maxMonth} allowAll={false} />
{ setHolderId(event.target.value); setError(""); }}> {!holders?.length && } {holders?.map((h) => )} {holdersError &&

{holdersError}

}
{error &&

{error}

}
); } /* ── FN-05 对账清单(14.1) ─────────────────────────────────────── */ type SettlementLedgerColumn = { label: string; width: number; numeric?: boolean }; const settlementActionWidth = 84; const statementColumns: readonly SettlementLedgerColumn[] = [ { label: "对账单号", width: 172 }, { label: "分成方", width: 180 }, { label: "自然月", width: 80 }, { label: "应出账日期", width: 104 }, { label: "触发方式", width: 88 }, { label: "明细条数", width: 86, numeric: true }, { label: "总金额", width: 112, numeric: true }, { label: "分成金额", width: 116, numeric: true }, { label: "出账状态", width: 98 }, { label: "批次状态", width: 104 }, { label: "执行人", width: 106 }, ]; const billColumns: readonly SettlementLedgerColumn[] = [ { label: "分成方", width: 164 }, { label: "自然月", width: 80 }, { label: "客户", width: 180 }, { label: "订阅", width: 192 }, { label: "计费天数", width: 90, numeric: true }, { label: "分成基数", width: 112, numeric: true }, { label: "本方分成金额", width: 124, numeric: true }, { label: "对账单号", width: 164 }, ]; function useSettlementLedgerTable(columns: readonly SettlementLedgerColumn[]) { const { ref, width, overflow, canScrollLeft, canScrollRight } = useHorizontalOverflow(); const minContentWidth = columns.reduce((sum, column) => sum + column.width, 0); const contentWidth = Math.max(minContentWidth, width - settlementActionWidth); const widths = columns.map((column) => contentWidth * (column.width / minContentWidth)).concat(settlementActionWidth); const className = [ "measured-table-scroll ops-table-wrap settlement-ledger-scroll", overflow && "has-horizontal-overflow", width >= 900 && "can-pin-identity", canScrollLeft && "can-scroll-left", canScrollRight && "can-scroll-right", ].filter(Boolean).join(" "); return { ref, className, widths, minWidth: minContentWidth + settlementActionWidth }; } function SettlementLedgerHead({ columns }: { columns: readonly SettlementLedgerColumn[] }) { return {columns.map(({ label, numeric }) => {label})} 操作 ; } function SettlementHolderCell({ name, type }: { name: string; type: HolderType }) { return {name || —}
{HOLDER_TYPE_TEXT[type]}
; } export function SettlementStatementListPage() { const identity = useDemoIdentity(); const listState = useDetailLinkState(); const back = detailBack(listState.previousState, "/settlement-batches", BACK_TO_RECON_LIST); const filters = useListFilters(); const table = useSettlementLedgerTable(statementColumns); const progressId = useId(); // 导出当前结果(B):admin/opsMain/opsSub(demo 角色无 opsSub);⛔ teamLead/partner/operator。 const canExportAll = !identity || identity.role === "admin" || identity.role === "regAdmin"; const isAdmin = !identity || identity.role === "admin"; const monthParam = filters.get("month"); // 无参数时显示全部自然月,同时兼容旧链接的 month=all。 const month = monthParam === "all" ? "" : monthParam; const type = filters.get("type"); const party = filters.get("party"); const reconcile = filters.get("reconcile"); const status = filters.get("status"); const trigger = filters.get("trigger"); const zero = filters.get("zero") === "1"; const q = filters.get("q"); const page = Number(filters.get("page") || "1") || 1; const hasFilter = Boolean(month || type || party || reconcile || status || trigger || zero || q); const list = useReconList({ period: month, holderType: type, holderKw: party, reconcileStatus: reconcile, batchStatus: status, trigger, includeZero: zero, keyword: q, page, }); const data = list.data; const wiring = list.fail?.kind === "wiring"; const s404 = list.fail?.kind === "s404"; const rows = data?.items ?? []; const total = data?.total ?? 0; const pageSize = 20; const [notice, setNotice] = useState(""); const [runOpen, setRunOpen] = useState(false); const [progressOpen, setProgressOpen] = useState(false); const [exporting, setExporting] = useState(false); async function exportAll() { if (exporting || list.loading) return; // 筛选无结果 ⇒ 只提示、不导出、无错误码(14.1 动作矩阵)。 if (!rows.length) { setNotice(EXPORT_EMPTY_NOTE); return; } setExporting(true); try { const result = await reconExportList({ period: month || undefined, holder_type: type || undefined, status: status || undefined }); setNotice(saveReconExportCsv(result) ? exportResultNote(result) : EXPORT_EMPTY_NOTE); } catch (e: unknown) { setNotice(e instanceof Error && e.message ? e.message : WORD_FETCH_FAILED); } finally { setExporting(false); } } return (
{back.to !== "/settlement-batches" &&
); } /* ── 批次详情(14.2) ───────────────────────────────────────────── */ const batchRecordTabs = [ { id: "overview", label: "批次概况" }, { id: "bills", label: "账单明细" }, { id: "execution", label: "执行与追溯" }, ] as const; type BatchRecordTab = typeof batchRecordTabs[number]["id"]; export function SettlementStatementRecordPage() { const { no } = useParams(); return ; } function BatchRecordPage({ no }: { no?: string }) { const identity = useDemoIdentity(); const navigate = useNavigate(); const location = useLocation(); const back = detailBack(location.state, "/settlement-batches", BACK_TO_RECON_LIST); const [tab, setTab] = useState(() => batchRecordTabs.find(({ id }) => id === location.state?.statementTab)?.id ?? "overview"); const outgoingState = detailLinkState(location.pathname + location.search + location.hash, { ...location.state, statementTab: tab }); const detail = useReconDetail(no ?? null); const batch = detail.data; const wiring = detail.fail?.kind === "wiring"; const isAdmin = !identity || identity.role === "admin"; const flagsPending = batch != null && (batch.can_export == null || (isAdmin && (batch.can_rerun == null || batch.can_correct == null))); const [confirmRerun, setConfirmRerun] = useState(false); const [rerunError, setRerunError] = useState(""); const [rerunning, setRerunning] = useState(false); const [exporting, setExporting] = useState(false); const [notice, setNotice] = useState(""); async function runRerun(event: FormEvent) { event.preventDefault(); if (!batch || !isAdmin || batch.can_rerun !== true || rerunning) return; setRerunning(true); setRerunError(""); try { const result = await submitReconRerun({ holder_type: batch.holder_type, holder_id: batch.holder_id, period: batch.period }); setConfirmRerun(false); navigate(batchPath(batch.holder_id, result.batch_no), { state: outgoingState }); } catch (error) { setRerunError(error instanceof Error && error.message ? error.message : "补跑失败,请重试。"); } finally { setRerunning(false); } } async function exportDetail() { if (!batch || batch.can_export !== true || exporting) return; setExporting(true); try { const result = await reconExportDetail({ batch_id: batch.batch_no }); setNotice(saveReconExportCsv(result) ? exportResultNote(result) : EXPORT_EMPTY_NOTE); } catch (error) { setNotice(error instanceof Error && error.message ? error.message : WORD_FETCH_FAILED); } finally { setExporting(false); } } function closeRerun() { if (!rerunning) setConfirmRerun(false); } const batchNumber = batch?.batch_no ?? no; return (
); } function BatchRecordPanel({ tab, active, children }: { tab: BatchRecordTab; active: BatchRecordTab; children: ReactNode }) { return ; } function BatchRecordContent({ batch, tab, onTabChange, linkState, flagsPending }: { batch: ReconDetailResult; tab: BatchRecordTab; onTabChange: (tab: BatchRecordTab) => void; linkState: DetailLinkState; flagsPending: boolean; }) { const missing = —; const gapText = batch.ticket_gap_failed ? WORD_FETCH_FAILED : BACKEND_NOT_WIRED; const gapCount = batch.ticket_gap_failed ? null : batch.ticket_gap_count; const tabs = batchRecordTabs.map((item) => ({ ...item, count: item.id === "bills" ? batch.detail_count : undefined })); return <>
{batch.detail_count}条
{moneyFromCents(batch.base_cents)}本批有效账单的分成基数合计
{moneyFromCents(batch.share_cents)}
{gapCount == null ? {gapText} : <>{gapCount}个}
对账单号
{batch.batch_no}
分成方
{batch.holder_name || missing}
自然月
{batch.period}
应出账日期
{batch.recon_date || missing}
{batch.cost_unconfigured.length > 0 &&
}
批次状态
{BATCH_STATUS_TEXT[batch.status]}
触发方式
{TRIGGER_TYPE_TEXT[batch.trigger_type]}
执行人
{executorText(batch)}
执行时间
{batch.executed_at ? localTime(batch.executed_at) : missing}
{(batch.status === "failed" || batch.status === "voided") && batch.fail_reason &&
} {batch.status === "voided" && batch.voided_by_batch_no &&

{VOIDED_BY_PREFIX} {batch.voided_by_batch_no}

} {flagsPending &&

{ACTION_FLAG_PENDING_NOTE},动作暂不可用。

}
; } const batchBillColumns: readonly SettlementLedgerColumn[] = [ { label: "客户", width: 160 }, { label: "订阅标识", width: 180 }, { label: "应收金额", width: 104, numeric: true }, { label: "分成基数", width: 104, numeric: true }, { label: "分成方式与取值", width: 124 }, { label: "本方分成金额", width: 120, numeric: true }, { label: "恒 0 说明", width: 132 }, ]; function BatchBillingTable({ items, linkState }: { items: ReconDetailResult["items"]; linkState: DetailLinkState }) { const table = useSettlementLedgerTable(batchBillColumns); return
{items.map((line) => { const shareRule = settleTextFromSnapshot(line.share_mode, line.share_value); const zeroNote = line.zero_note ? ZERO_NOTE_TEXT[line.zero_note] : undefined; return ; })} {!items.length && 本批无明细行。}
{line.customer_name} {line.subscription_label} {moneyFromCents(line.receivable_cents)} {moneyFromCents(line.share_base_cents)} {shareRule} {moneyFromCents(line.share_amount_cents)} {zeroNote ?? —} 详情
; } /* ── FN-08 账单明细(14.3 列表) ─────────────────────────────────── */ export function SettlementBillListPage() { const listNavState = useDetailLinkState(); const filters = useListFilters(); const table = useSettlementLedgerTable(billColumns); const q = filters.get("q"); const type = filters.get("type"); const monthParam = filters.get("month"); const month = monthParam === "all" ? "" : monthParam; const page = Number(filters.get("page") || "1") || 1; const hasFilter = Boolean(q || type || month); const list = useBillList({ period: month, holderType: type, keyword: q, page }); const wiring = list.fail?.kind === "wiring"; const rows = list.data?.items ?? []; const total = list.data?.total ?? 0; const pageSize = 20; return (

账单明细

对账有差异时,按客户和账期追到具体订阅,逐项核对应收、成本和分成。
{wiring &&

{BILL_WIRING_NOTE}

}
{ filters.set("page", ""); filters.set("type", event.target.value); }}> filters.set("month", value, true)} /> {hasFilter && }
{rows.map((row) => ( ))} {!rows.length && ( {list.loading ? "加载中…" : wiring ? "账单明细接口待后端接线,数据暂不可读。" : "没有符合筛选条件的账单明细。"} )}
{row.period} {row.customer_name} {row.subscription_label} {row.billing_days} 天 {moneyFromCents(row.share_base_cents)} {moneyFromCents(row.share_amount_cents)} {row.batch_no} 详情
filters.set("page", String(next))} />
{list.fail && !wiring && (

{list.fail.message}

)}
); } /* ── FN-08 明细详情(14.3) ──────────────────────────────────────── */ const billRecordTabs = [ { id: "billing", label: "计费概况" }, { id: "costs", label: "成本明细" }, { id: "reconciliation", label: "分成与对账" }, { id: "accounts", label: "分账号计费" }, ] as const; type BillRecordTab = typeof billRecordTabs[number]["id"]; function BillRecordPanel({ tab, active, children }: { tab: BillRecordTab; active: BillRecordTab; children: ReactNode }) { return ; } function BillBatchLink({ holderId, number, linkState }: { holderId: string; number: string; linkState: DetailLinkState }) { return {number}