/** * 工单计数(册 5,2026-11-17 界面重构;Wave F:一次 `include_status_totals`)。 * * 服务端没有独立「按状态计数」口;`/ticket/todo_counts@v1` 只给业务口径。 * 台账状态 Tab 与总览 KPI 要的是**该身份可见范围内**各状态张数:改前=逐状态 * `list page_size=1`(进页 5 路与主列表争 UDS);改后=一次 `include_status_totals`。 * * 纪律: * - ⛔ 用当页行数冒充总数; * - ⛔ 失败折成 0:任一路失败即整体 `error`,页面把数字渲染成 `—`; * - 整份 `status_totals` 缺失/类型错误 ⇒ 抛错(D-03),⛔ 伪装成真实 0; * - 个别非法计数值省略该键(D-04),调用方渲染 `—`,⛔ NaN/负张数上屏; * - 一次页面只发一次;状态集合变化才重取。 */ import { ApiError } from "./api/http.ts"; import * as ticketApi from "./api/ticket.ts"; import { useLoad } from "./useLoad.ts"; /** 单状态张数;取不到(失败/未取/非法)时调用方渲染 `—`。 */ export type StatusCounts = Partial>; /** 只留能带进 `statuses` 的合法状态码。 */ const KNOWN = new Set([ "unassigned", "pending", "processing", "completed", "rejected", "settled", "terminated", ]); /** * 解析单个状态计数:键缺失 ⇒ 真实 0;值非法 ⇒ `undefined`(调用方渲染 `—`)。 * 合法=有限、非负整数(JSON 数字;⛔ 字符串垃圾、NaN、负数、小数)。 */ function parseStatusTotal(raw: unknown): number | undefined { if (raw === undefined) return 0; if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0 || !Number.isInteger(raw)) return undefined; return raw; } /** * 一次取回可见范围内各状态 `total`(服务端 `status_totals`)。 * * @param statuses 需要计数的状态码(顺序无关;键是状态码本身) */ export function useTicketStatusCounts(statuses: readonly string[]) { const key = [...new Set(statuses)].filter((s) => KNOWN.has(s)).sort().join(","); // 空集合=停拉:enabled=false,⛔ 立刻 return {}(会误记 shown,真正开拉后 KPI 不再进「…」)。 return useLoad(async () => { const wanted = key.split(","); const r = await ticketApi.ticketList({ page: 1, page_size: 1, include_status_totals: true }); const raw = r.status_totals; // D-03:整份缺失/null/数组/非对象 ⇒ 未知,⛔ 折成 {} 再填 0。 if (raw == null || typeof raw !== "object" || Array.isArray(raw)) { throw new ApiError(null, "状态计数结构异常"); } const totals = raw as Record; const out: StatusCounts = {}; for (const status of wanted) { const n = parseStatusTotal(Object.prototype.hasOwnProperty.call(totals, status) ? totals[status] : undefined); // D-04:非法值不写入 ⇒ Partial 保持 undefined ⇒ KPI「—」;合法/缺键照常。 if (n !== undefined) out[status] = n; } return out; }, [key], Boolean(key)); }