| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301 |
- /**
- * 册 6《计费与对账出账》数据层(FN-05 对账清单/批次详情、FN-08 账单明细、FN-09 出账配置、FN-10/11 出账更正)。
- *
- * 接线纪律(SEOH 外部项目接入指南):
- * - 本域接口全为 [位](2026-11-11 核实 openapi.yaml 未声明,网关 11001 未声明即拒绝);
- * - 撞 11001 ⇒ 页面进**契约占位分支**(结构按 14 章落位、数据区显式标「后端未下发」),⛔ 演示台账冒充;
- * - 三态口径:KLT-S404 ⇒ 三卡整体不渲染;KLT-S406 ⇒ 单格「取数失败」其余照常;⛔ 回落空集/0。
- */
- import { useCallback, useEffect, useState } from "react";
- import { hasBizCode } from "./api/http";
- import {
- billGetDetail,
- billGetList,
- billingConfigGet,
- billingConfigUpdate,
- correctionCreate,
- correctionDraftGet,
- correctionDraftSave,
- correctionGet,
- correctionGetList,
- reconGetDetail,
- reconGetList,
- reconGetPeriods,
- reconRerun,
- } from "./api/bos";
- import type { BillingConfigResult } from "./api/types";
- import { WORD_FETCH_FAILED } from "./api/lockedCopy";
- import { PERMISSION_PENDING_NOTE, S404_DISCIPLINE } from "./copy-billing";
- /* ── 页面常量 ───────────────────────────────────────────────────── */
- /** `lastClosedMonth()`=最近一个已结束自然月(YYYY-MM,Asia/Shanghai;页面常量,⛔ 进配置项)。 */
- export function lastClosedMonth(now: Date = new Date()): string {
- const y = now.getFullYear();
- const m = now.getMonth(); // 0-based:其值恰为「上一月」的 1-based 月序(0 表示上一年 12 月)
- const yy = m === 0 ? y - 1 : y;
- const mm = m === 0 ? 12 : m;
- return `${yy}-${String(mm).padStart(2, "0")}`;
- }
- /* ── 失败分类(三态口径) ────────────────────────────────────────── */
- export type ReconFailKind = "wiring" | "permission" | "s404" | "s406" | "other";
- export interface ReconFail {
- kind: ReconFailKind;
- message: string;
- }
- /** 统一失败分类:11001=权限待配置(本族路由已在 openapi 声明,未声明时网关回 404/50000);
- * S404=范围过大不渲卡;S406=取数失败;其余=原样 message。
- * ⚠️ 11001 ⛔ 再当「未接线」渲染成占位分支(会让页面谎称接口没交付),也不⛔ 放宽判权装成有权限。 */
- export function classifyReconError(e: unknown): ReconFail {
- if (hasBizCode(e, "11001")) return { kind: "permission", message: PERMISSION_PENDING_NOTE };
- if (hasBizCode(e, "KLT-S404")) return { kind: "s404", message: S404_DISCIPLINE };
- if (hasBizCode(e, "KLT-S406")) return { kind: "s406", message: WORD_FETCH_FAILED };
- return { kind: "other", message: e instanceof Error && e.message ? e.message : WORD_FETCH_FAILED };
- }
- export const isWiring = (fail: ReconFail | null): boolean => fail?.kind === "wiring";
- /* ── 通用取数 hook(依赖数组由调用方给稳态键) ───────────────────── */
- function useFetch<T>(fn: () => Promise<T>, deps: readonly unknown[]): {
- data: T | null;
- loading: boolean;
- fail: ReconFail | null;
- reload: () => void;
- } {
- const [data, setData] = useState<T | null>(null);
- const [loading, setLoading] = useState(true);
- const [fail, setFail] = useState<ReconFail | null>(null);
- const [tick, setTick] = useState(0);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- const run = useCallback(fn, deps);
- useEffect(() => {
- let alive = true;
- setLoading(true);
- run()
- .then((res) => {
- if (!alive) return;
- setData(res);
- setFail(null);
- })
- .catch((e: unknown) => {
- if (!alive) return;
- setData(null);
- setFail(classifyReconError(e));
- })
- .finally(() => {
- if (alive) setLoading(false);
- });
- }, [run, tick]);
- return { data, loading, fail, reload: () => setTick((t) => t + 1) };
- }
- /* ── FN-05 对账清单 ─────────────────────────────────────────────── */
- /** 自然月下拉行集(11104 ⇒ 下拉不可用,⛔ 禁用整页筛选条)。 */
- export function useReconPeriods() {
- return useFetch(() => reconGetPeriods(), []);
- }
- export interface ReconListFilters {
- period: string;
- holderType: string;
- holderKw: string;
- reconcileStatus: string;
- batchStatus: string;
- /** 触发方式(auto/manual;空=全部触发方式)。 */
- trigger: string;
- includeZero: boolean;
- keyword: string;
- page: number;
- }
- export function useReconList(f: ReconListFilters) {
- return useFetch(
- () =>
- reconGetList({
- page: Math.max(0, f.page - 1),
- page_size: 20,
- period: f.period || undefined,
- holder_type: f.holderType || undefined,
- holder_kw: f.holderKw.trim() || undefined,
- reconcile_status: f.reconcileStatus || undefined,
- status: f.batchStatus || undefined,
- trigger_type: f.trigger || undefined,
- include_zero_lines: f.includeZero || undefined,
- keyword: f.keyword.trim() || undefined,
- }),
- [f.period, f.holderType, f.holderKw, f.reconcileStatus, f.batchStatus, f.trigger, f.includeZero, f.keyword, f.page],
- );
- }
- /* ── 批次详情(14.2) ───────────────────────────────────────────── */
- export function useReconDetail(batchNo: string | null) {
- return useFetch(
- () => (batchNo ? reconGetDetail(batchNo) : Promise.reject(new Error("缺批次号"))),
- [batchNo],
- );
- }
- /**
- * 人工补跑(仅 admin;入参只三件)。错误分支(07 章四道闸 60502→60503→60504→60506/KLT-S407):
- * 文案直读后端 message(出路句与动态值由服务端 detail 带出),页面按码决定是否给「查看批次」出口。
- */
- export async function submitReconRerun(d: { holder_type: string; holder_id: string; period: string }) {
- return reconRerun(d);
- }
- /* ── FN-08 账单明细 ─────────────────────────────────────────────── */
- export interface BillListFilters {
- period: string;
- holderType: string;
- keyword: string;
- page: number;
- }
- export function useBillList(f: BillListFilters) {
- return useFetch(
- () =>
- billGetList({
- page: Math.max(0, f.page - 1),
- page_size: 20,
- period: f.period || undefined,
- holder_type: f.holderType || undefined,
- keyword: f.keyword.trim() || undefined,
- }),
- [f.period, f.holderType, f.keyword, f.page],
- );
- }
- export function useBillDetail(detailId: string | null) {
- return useFetch(
- () => (detailId ? billGetDetail(detailId) : Promise.reject(new Error("缺明细标识"))),
- [detailId],
- );
- }
- /**
- * 出账更正「关联账单」候选(契约 14.6:只列已被 executed 批次覆盖过的账——bill/list 应答恒满足)。
- * 在登记弹窗挂载时取一页(page_size 50);未接线(11001)⇒ 候选下拉为空、仍可手工填写(⛔ 把取数失败实现成拒登)。
- */
- export function useBillCandidates() {
- return useFetch(() => billGetList({ page: 0, page_size: 50 }), []);
- }
- /* ── FN-09 出账配置 ─────────────────────────────────────────────── */
- export function useBillingConfig(): {
- data: BillingConfigResult | null;
- loading: boolean;
- fail: ReconFail | null;
- reload: () => void;
- } {
- return useFetch(() => billingConfigGet(), []);
- }
- /** 出账配置写(仅 admin;KLT-S407/60001=row_version 冲突 ⇒ 提示刷新后重试;11103 ⇒ detail.fields[] 红显)。 */
- export async function submitBillingConfigUpdate(d: {
- default_recon_day?: number;
- effective_mode?: string;
- row_version?: number;
- operators?: { operator_id: string; recon_day: number | null; pay_cycle: string }[];
- }) {
- return billingConfigUpdate(d);
- }
- /* ── FN-10/11 出账更正 ──────────────────────────────────────────── */
- export interface CorrectionListFilters {
- period: string;
- keyword: string;
- operatorKeyword: string;
- regionNodeId: string;
- page: number;
- }
- export function useCorrectionList(f: CorrectionListFilters) {
- return useFetch(
- () =>
- correctionGetList({
- page: Math.max(0, f.page - 1),
- page_size: 20,
- period: f.period || undefined,
- keyword: f.keyword.trim() || undefined,
- operator_keyword: f.operatorKeyword.trim() || undefined,
- region_node_id: f.regionNodeId || undefined,
- }),
- [f.period, f.keyword, f.operatorKeyword, f.regionNodeId, f.page],
- );
- }
- export function useCorrectionDetail(id: string | null) {
- return useFetch(
- () => (id ? correctionGet(id) : Promise.reject(new Error("缺更正记录标识"))),
- [id],
- );
- }
- /**
- * 登记出账更正:表单仅两字段(关联账单+错误内容)。
- * KLT-H20501(闸一·认不出是哪笔账)/KLT-H20507(候选带值但不合法)由页面按码分支;
- * ⚠️ ⛔ 传 scope/severity/region_node_id(11103 禁传键)。
- */
- export async function submitCorrectionCreate(d: { bill_detail_id?: string; ref?: string; error_text: string }) {
- return correctionCreate(d);
- }
- /* ── 更正草稿(按登录账号一份、整体覆盖) ──────────────────────────
- * 首选后端 `correction/draft_*@v1`(契约 06-接口清单 §3.2,PK=ctx.user_id,无 user_id 入参);
- * 后端未接线(11001)⇒ 本机 localStorage 暂存(键含登录名,语义同「user × 本机」一份),
- * ⚠️ 暂存不冒充服务端数据、不跨人读写,交付后删除 fallback 分支。
- */
- const DRAFT_KEY_PREFIX = "oss.correction-draft.";
- export async function saveCorrectionDraft(userKey: string, form: { ref?: string; error_text?: string }): Promise<void> {
- try {
- await correctionDraftSave({ form });
- } catch (e) {
- if (!hasBizCode(e, "11001")) throw e;
- localStorage.setItem(`${DRAFT_KEY_PREFIX}${userKey}`, JSON.stringify(form));
- }
- }
- export async function readCorrectionDraft(userKey: string): Promise<{ ref?: string; error_text?: string } | null> {
- try {
- const res = await correctionDraftGet();
- // 契约 `form`=对象(后端已 parse)。这里留一层过渡兜底:仍是 JSON 文本就地 parse,
- // ⛔ 让 `form.ref`/`form.error_text` 取到 undefined、草稿只填回半张窗(缺陷 D-58)。
- const form = typeof res.form === "string" ? parseDraftForm(res.form) : res.form;
- return form && (form.ref || form.error_text) ? form : null;
- } catch (e) {
- if (!hasBizCode(e, "11001")) throw e;
- const raw = localStorage.getItem(`${DRAFT_KEY_PREFIX}${userKey}`);
- return raw ? (JSON.parse(raw) as { ref?: string; error_text?: string }) : null;
- }
- }
- /** 草稿文本 → 对象(解析不了=没有可用草稿,⛔ 抛错打断登记)。 */
- function parseDraftForm(raw: string): { ref?: string; error_text?: string } | null {
- try {
- const parsed: unknown = JSON.parse(raw);
- return parsed && typeof parsed === "object" ? parsed as { ref?: string; error_text?: string } : null;
- } catch {
- return null;
- }
- }
- export async function clearCorrectionDraft(userKey: string): Promise<void> {
- try {
- await correctionDraftSave({ form: {} });
- } catch (e) {
- if (!hasBizCode(e, "11001")) throw e;
- }
- localStorage.removeItem(`${DRAFT_KEY_PREFIX}${userKey}`);
- }
|