recon.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /**
  2. * 册 6《计费与对账出账》数据层(FN-05 对账清单/批次详情、FN-08 账单明细、FN-09 出账配置、FN-10/11 出账更正)。
  3. *
  4. * 接线纪律(SEOH 外部项目接入指南):
  5. * - 本域接口全为 [位](2026-11-11 核实 openapi.yaml 未声明,网关 11001 未声明即拒绝);
  6. * - 撞 11001 ⇒ 页面进**契约占位分支**(结构按 14 章落位、数据区显式标「后端未下发」),⛔ 演示台账冒充;
  7. * - 三态口径:KLT-S404 ⇒ 三卡整体不渲染;KLT-S406 ⇒ 单格「取数失败」其余照常;⛔ 回落空集/0。
  8. */
  9. import { useCallback, useEffect, useState } from "react";
  10. import { hasBizCode } from "./api/http";
  11. import {
  12. billGetDetail,
  13. billGetList,
  14. billingConfigGet,
  15. billingConfigUpdate,
  16. correctionCreate,
  17. correctionDraftGet,
  18. correctionDraftSave,
  19. correctionGet,
  20. correctionGetList,
  21. reconGetDetail,
  22. reconGetList,
  23. reconGetPeriods,
  24. reconRerun,
  25. } from "./api/bos";
  26. import type { BillingConfigResult } from "./api/types";
  27. import { WORD_FETCH_FAILED } from "./api/lockedCopy";
  28. import { PERMISSION_PENDING_NOTE, S404_DISCIPLINE } from "./copy-billing";
  29. /* ── 页面常量 ───────────────────────────────────────────────────── */
  30. /** `lastClosedMonth()`=最近一个已结束自然月(YYYY-MM,Asia/Shanghai;页面常量,⛔ 进配置项)。 */
  31. export function lastClosedMonth(now: Date = new Date()): string {
  32. const y = now.getFullYear();
  33. const m = now.getMonth(); // 0-based:其值恰为「上一月」的 1-based 月序(0 表示上一年 12 月)
  34. const yy = m === 0 ? y - 1 : y;
  35. const mm = m === 0 ? 12 : m;
  36. return `${yy}-${String(mm).padStart(2, "0")}`;
  37. }
  38. /* ── 失败分类(三态口径) ────────────────────────────────────────── */
  39. export type ReconFailKind = "wiring" | "permission" | "s404" | "s406" | "other";
  40. export interface ReconFail {
  41. kind: ReconFailKind;
  42. message: string;
  43. }
  44. /** 统一失败分类:11001=权限待配置(本族路由已在 openapi 声明,未声明时网关回 404/50000);
  45. * S404=范围过大不渲卡;S406=取数失败;其余=原样 message。
  46. * ⚠️ 11001 ⛔ 再当「未接线」渲染成占位分支(会让页面谎称接口没交付),也不⛔ 放宽判权装成有权限。 */
  47. export function classifyReconError(e: unknown): ReconFail {
  48. if (hasBizCode(e, "11001")) return { kind: "permission", message: PERMISSION_PENDING_NOTE };
  49. if (hasBizCode(e, "KLT-S404")) return { kind: "s404", message: S404_DISCIPLINE };
  50. if (hasBizCode(e, "KLT-S406")) return { kind: "s406", message: WORD_FETCH_FAILED };
  51. return { kind: "other", message: e instanceof Error && e.message ? e.message : WORD_FETCH_FAILED };
  52. }
  53. export const isWiring = (fail: ReconFail | null): boolean => fail?.kind === "wiring";
  54. /* ── 通用取数 hook(依赖数组由调用方给稳态键) ───────────────────── */
  55. function useFetch<T>(fn: () => Promise<T>, deps: readonly unknown[]): {
  56. data: T | null;
  57. loading: boolean;
  58. fail: ReconFail | null;
  59. reload: () => void;
  60. } {
  61. const [data, setData] = useState<T | null>(null);
  62. const [loading, setLoading] = useState(true);
  63. const [fail, setFail] = useState<ReconFail | null>(null);
  64. const [tick, setTick] = useState(0);
  65. // eslint-disable-next-line react-hooks/exhaustive-deps
  66. const run = useCallback(fn, deps);
  67. useEffect(() => {
  68. let alive = true;
  69. setLoading(true);
  70. run()
  71. .then((res) => {
  72. if (!alive) return;
  73. setData(res);
  74. setFail(null);
  75. })
  76. .catch((e: unknown) => {
  77. if (!alive) return;
  78. setData(null);
  79. setFail(classifyReconError(e));
  80. })
  81. .finally(() => {
  82. if (alive) setLoading(false);
  83. });
  84. }, [run, tick]);
  85. return { data, loading, fail, reload: () => setTick((t) => t + 1) };
  86. }
  87. /* ── FN-05 对账清单 ─────────────────────────────────────────────── */
  88. /** 自然月下拉行集(11104 ⇒ 下拉不可用,⛔ 禁用整页筛选条)。 */
  89. export function useReconPeriods() {
  90. return useFetch(() => reconGetPeriods(), []);
  91. }
  92. export interface ReconListFilters {
  93. period: string;
  94. holderType: string;
  95. holderKw: string;
  96. reconcileStatus: string;
  97. batchStatus: string;
  98. /** 触发方式(auto/manual;空=全部触发方式)。 */
  99. trigger: string;
  100. includeZero: boolean;
  101. keyword: string;
  102. page: number;
  103. }
  104. export function useReconList(f: ReconListFilters) {
  105. return useFetch(
  106. () =>
  107. reconGetList({
  108. page: Math.max(0, f.page - 1),
  109. page_size: 20,
  110. period: f.period || undefined,
  111. holder_type: f.holderType || undefined,
  112. holder_kw: f.holderKw.trim() || undefined,
  113. reconcile_status: f.reconcileStatus || undefined,
  114. status: f.batchStatus || undefined,
  115. trigger_type: f.trigger || undefined,
  116. include_zero_lines: f.includeZero || undefined,
  117. keyword: f.keyword.trim() || undefined,
  118. }),
  119. [f.period, f.holderType, f.holderKw, f.reconcileStatus, f.batchStatus, f.trigger, f.includeZero, f.keyword, f.page],
  120. );
  121. }
  122. /* ── 批次详情(14.2) ───────────────────────────────────────────── */
  123. export function useReconDetail(batchNo: string | null) {
  124. return useFetch(
  125. () => (batchNo ? reconGetDetail(batchNo) : Promise.reject(new Error("缺批次号"))),
  126. [batchNo],
  127. );
  128. }
  129. /**
  130. * 人工补跑(仅 admin;入参只三件)。错误分支(07 章四道闸 60502→60503→60504→60506/KLT-S407):
  131. * 文案直读后端 message(出路句与动态值由服务端 detail 带出),页面按码决定是否给「查看批次」出口。
  132. */
  133. export async function submitReconRerun(d: { holder_type: string; holder_id: string; period: string }) {
  134. return reconRerun(d);
  135. }
  136. /* ── FN-08 账单明细 ─────────────────────────────────────────────── */
  137. export interface BillListFilters {
  138. period: string;
  139. holderType: string;
  140. keyword: string;
  141. page: number;
  142. }
  143. export function useBillList(f: BillListFilters) {
  144. return useFetch(
  145. () =>
  146. billGetList({
  147. page: Math.max(0, f.page - 1),
  148. page_size: 20,
  149. period: f.period || undefined,
  150. holder_type: f.holderType || undefined,
  151. keyword: f.keyword.trim() || undefined,
  152. }),
  153. [f.period, f.holderType, f.keyword, f.page],
  154. );
  155. }
  156. export function useBillDetail(detailId: string | null) {
  157. return useFetch(
  158. () => (detailId ? billGetDetail(detailId) : Promise.reject(new Error("缺明细标识"))),
  159. [detailId],
  160. );
  161. }
  162. /**
  163. * 出账更正「关联账单」候选(契约 14.6:只列已被 executed 批次覆盖过的账——bill/list 应答恒满足)。
  164. * 在登记弹窗挂载时取一页(page_size 50);未接线(11001)⇒ 候选下拉为空、仍可手工填写(⛔ 把取数失败实现成拒登)。
  165. */
  166. export function useBillCandidates() {
  167. return useFetch(() => billGetList({ page: 0, page_size: 50 }), []);
  168. }
  169. /* ── FN-09 出账配置 ─────────────────────────────────────────────── */
  170. export function useBillingConfig(): {
  171. data: BillingConfigResult | null;
  172. loading: boolean;
  173. fail: ReconFail | null;
  174. reload: () => void;
  175. } {
  176. return useFetch(() => billingConfigGet(), []);
  177. }
  178. /** 出账配置写(仅 admin;KLT-S407/60001=row_version 冲突 ⇒ 提示刷新后重试;11103 ⇒ detail.fields[] 红显)。 */
  179. export async function submitBillingConfigUpdate(d: {
  180. default_recon_day?: number;
  181. effective_mode?: string;
  182. row_version?: number;
  183. operators?: { operator_id: string; recon_day: number | null; pay_cycle: string }[];
  184. }) {
  185. return billingConfigUpdate(d);
  186. }
  187. /* ── FN-10/11 出账更正 ──────────────────────────────────────────── */
  188. export interface CorrectionListFilters {
  189. period: string;
  190. keyword: string;
  191. operatorKeyword: string;
  192. regionNodeId: string;
  193. page: number;
  194. }
  195. export function useCorrectionList(f: CorrectionListFilters) {
  196. return useFetch(
  197. () =>
  198. correctionGetList({
  199. page: Math.max(0, f.page - 1),
  200. page_size: 20,
  201. period: f.period || undefined,
  202. keyword: f.keyword.trim() || undefined,
  203. operator_keyword: f.operatorKeyword.trim() || undefined,
  204. region_node_id: f.regionNodeId || undefined,
  205. }),
  206. [f.period, f.keyword, f.operatorKeyword, f.regionNodeId, f.page],
  207. );
  208. }
  209. export function useCorrectionDetail(id: string | null) {
  210. return useFetch(
  211. () => (id ? correctionGet(id) : Promise.reject(new Error("缺更正记录标识"))),
  212. [id],
  213. );
  214. }
  215. /**
  216. * 登记出账更正:表单仅两字段(关联账单+错误内容)。
  217. * KLT-H20501(闸一·认不出是哪笔账)/KLT-H20507(候选带值但不合法)由页面按码分支;
  218. * ⚠️ ⛔ 传 scope/severity/region_node_id(11103 禁传键)。
  219. */
  220. export async function submitCorrectionCreate(d: { bill_detail_id?: string; ref?: string; error_text: string }) {
  221. return correctionCreate(d);
  222. }
  223. /* ── 更正草稿(按登录账号一份、整体覆盖) ──────────────────────────
  224. * 首选后端 `correction/draft_*@v1`(契约 06-接口清单 §3.2,PK=ctx.user_id,无 user_id 入参);
  225. * 后端未接线(11001)⇒ 本机 localStorage 暂存(键含登录名,语义同「user × 本机」一份),
  226. * ⚠️ 暂存不冒充服务端数据、不跨人读写,交付后删除 fallback 分支。
  227. */
  228. const DRAFT_KEY_PREFIX = "oss.correction-draft.";
  229. export async function saveCorrectionDraft(userKey: string, form: { ref?: string; error_text?: string }): Promise<void> {
  230. try {
  231. await correctionDraftSave({ form });
  232. } catch (e) {
  233. if (!hasBizCode(e, "11001")) throw e;
  234. localStorage.setItem(`${DRAFT_KEY_PREFIX}${userKey}`, JSON.stringify(form));
  235. }
  236. }
  237. export async function readCorrectionDraft(userKey: string): Promise<{ ref?: string; error_text?: string } | null> {
  238. try {
  239. const res = await correctionDraftGet();
  240. // 契约 `form`=对象(后端已 parse)。这里留一层过渡兜底:仍是 JSON 文本就地 parse,
  241. // ⛔ 让 `form.ref`/`form.error_text` 取到 undefined、草稿只填回半张窗(缺陷 D-58)。
  242. const form = typeof res.form === "string" ? parseDraftForm(res.form) : res.form;
  243. return form && (form.ref || form.error_text) ? form : null;
  244. } catch (e) {
  245. if (!hasBizCode(e, "11001")) throw e;
  246. const raw = localStorage.getItem(`${DRAFT_KEY_PREFIX}${userKey}`);
  247. return raw ? (JSON.parse(raw) as { ref?: string; error_text?: string }) : null;
  248. }
  249. }
  250. /** 草稿文本 → 对象(解析不了=没有可用草稿,⛔ 抛错打断登记)。 */
  251. function parseDraftForm(raw: string): { ref?: string; error_text?: string } | null {
  252. try {
  253. const parsed: unknown = JSON.parse(raw);
  254. return parsed && typeof parsed === "object" ? parsed as { ref?: string; error_text?: string } : null;
  255. } catch {
  256. return null;
  257. }
  258. }
  259. export async function clearCorrectionDraft(userKey: string): Promise<void> {
  260. try {
  261. await correctionDraftSave({ form: {} });
  262. } catch (e) {
  263. if (!hasBizCode(e, "11001")) throw e;
  264. }
  265. localStorage.removeItem(`${DRAFT_KEY_PREFIX}${userKey}`);
  266. }