ticket.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /**
  2. * 册 5《工单与开停交付》数据层(列表/待分派队列/详情/报文待处置/闭环配置)。
  3. *
  4. * 接线纪律(SEOH 外部项目接入指南):
  5. * - 31 口已在 `openapi.yaml` 登记并经网关放行,权限键由网关按注册中心元数据计算,
  6. * 因此**没有**"接口未接线"这一档可言;真回 `11001` 只剩两种情形,必须分开渲染:
  7. * · 原文含「未在 OpenAPI 声明/方法」⇒ 网关侧声明缺失(`kind: wiring`,配"待后端声明"文案);
  8. * · 其余 11001 ⇒ 服务间认证/权限键未配置(`kind: permission`)。
  9. * - `11104` = **越权与查无同码**(工单§3.6 防线四),⛔ 把它当"接口未实现"或"记录不存在"说破;
  10. * - 失败⛔ 回退空集(`useLoad` 已保证 `data` 仅在成功时下发),空集与失败必须分屏。
  11. *
  12. * 分页:后端 **1 基**(`dbx::page_norm`:`unwrap_or(1)`,offset=`(page-1)*size`,代码证实),
  13. * UI 页码直接透传,⛔ 再做 0/1 基换算。
  14. */
  15. import { ApiError, hasBizCode } from "./api/http.ts";
  16. import { useLoad } from "./useLoad.ts";
  17. import * as ticketApi from "./api/ticket.ts";
  18. import type {
  19. ClosureConfig,
  20. MessagePendingResult,
  21. PendingQueueResult,
  22. TicketDetail,
  23. TicketListResult,
  24. TodoCounts,
  25. TraceResult,
  26. } from "./api/ticket.ts";
  27. /** 每页 20 条(全站口径;后端对 page_size 有上限,⛔ 传超大值)。 */
  28. export const TICKET_PAGE_SIZE = 20;
  29. /** 后端与 UI 同为 1 基:仅归一非法页码。 */
  30. export const normPage = (uiPage: number) => Math.max(1, uiPage || 1);
  31. export type TicketFailKind = "wiring" | "permission" | "other";
  32. export type TicketFail = { kind: TicketFailKind; message: string };
  33. /**
  34. * 四类口径(`wiring`/`permission`/`other` + `useLoad` 的成功空集)⇒ 页面分别渲染。
  35. * 文案用后端回执原文(`lockedCopy`),⛔ 改写、⛔ 拼接猜测。
  36. */
  37. export function classifyTicketError(e: unknown): TicketFail {
  38. const a = e as ApiError | null;
  39. const raw = a?.message ?? "请求失败";
  40. const detail = typeof a?.detail === "string" ? a.detail : "";
  41. const text = `${raw}${detail}`;
  42. if (hasBizCode(e, "11001") && /未在 OpenAPI 声明|方法/.test(text))
  43. return { kind: "wiring", message: raw };
  44. // ⚠️ 服务侧角色闸门(`guard::gate`)走的是 `BosError::forbidden_role` ⇒ 出参是
  45. // `code=60058`/`error_code=KLT-P301`,⛔ 回 `11104`(那是参数校验族)。只认 11104 会把
  46. // 「无权」判成 `other`,页面于是跳过友好文案、把"当前角色 X 不在服务侧允许的角色集内
  47. // (网关放行≠服务放行,总则§8.4)"这句内部措辞原样甩给用户。
  48. if (hasBizCode(e, "11001") || hasBizCode(e, "11104") || hasBizCode(e, "60058") || hasBizCode(e, "KLT-P301"))
  49. return { kind: "permission", message: raw };
  50. return { kind: "other", message: raw };
  51. }
  52. /** 列表筛选(与 `/ticket/list@v1` 的 `ListReq` 逐字同名:多选数组、日期 `YYYY-MM-DD`)。 */
  53. export type TicketListFilters = {
  54. keyword?: string;
  55. ticket_types?: string[];
  56. statuses?: string[];
  57. /** 回填来源三值:manual/unicom_feedback/mixed */
  58. sources?: string[];
  59. date_from?: string;
  60. date_to?: string;
  61. /** 责任人=本人(只有 `me` 一个取值,服务端按会话解析):「我的待办」的唯一收窄口径。 */
  62. assignee?: string;
  63. };
  64. const clean = (o: Record<string, unknown>) =>
  65. Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== null && v !== ""));
  66. /** 工单列表(服务端分页+过滤;⛔ 前端合并多次请求拼行集,契约 14.3:164)。
  67. *
  68. * `pageSize` 默认 {@link TICKET_PAGE_SIZE};调用方可升到 100(服务端 `page_norm` 上限)
  69. * 供「我的待办」这类按期限分组的一次性取数,⛔ 超过 100(服务端会夹到 100,页面却按 120 算)。 */
  70. export function useTicketList(
  71. filters: TicketListFilters,
  72. page: number,
  73. pageSize: number = TICKET_PAGE_SIZE,
  74. opts?: { enabled?: boolean },
  75. ) {
  76. const enabled = opts?.enabled !== false;
  77. const params = clean({ ...filters, page: normPage(page), page_size: Math.min(Math.max(1, pageSize), 100) });
  78. // enabled 交给 useLoad:停拉时⛔ 用已解决的空 rows 占位(会误记 shown,真正开拉后不再进 loading)。
  79. return useLoad<TicketListResult>(
  80. () => ticketApi.ticketList(params),
  81. [JSON.stringify(params)],
  82. enabled,
  83. );
  84. }
  85. /** 待分派队列。
  86. *
  87. * `includeCandidates=false`(默认):只要 total/行卡片(徽标/总览/队列首屏),服务端跳过候选人装配。
  88. * 指定成员时再按工单现拉 `include_candidates:true`(Wave F:首屏 ~2 UDS,避免热后 11 跳)。
  89. */
  90. /** D-05:成功信封须带数组 `rows` 与非负整数 `total`;缺字段/垃圾值抛错,⛔ 伪装空队列或直接上屏。 */
  91. function assertPendingQueue(r: PendingQueueResult): PendingQueueResult {
  92. if (!Array.isArray(r.rows)) throw new ApiError(null, "待分派队列结构异常");
  93. const total = r.total as unknown;
  94. if (typeof total !== "number" || !Number.isFinite(total) || total < 0 || !Number.isInteger(total)) {
  95. throw new ApiError(null, "待分派队列结构异常");
  96. }
  97. return r;
  98. }
  99. export function usePendingQueue(
  100. f: { ticket_types?: string[]; assign_team_id?: string; keyword?: string },
  101. page: number,
  102. pageSize: number = TICKET_PAGE_SIZE,
  103. opts?: { includeCandidates?: boolean },
  104. ) {
  105. const includeCandidates = opts?.includeCandidates === true;
  106. const body = {
  107. ...f,
  108. page: normPage(page),
  109. page_size: Math.min(Math.max(1, pageSize), 100),
  110. include_candidates: includeCandidates,
  111. };
  112. return useLoad<PendingQueueResult>(
  113. () => ticketApi.ticketPendingQueue(body).then(assertPendingQueue),
  114. [JSON.stringify(clean(body as Record<string, unknown>))],
  115. );
  116. }
  117. /**
  118. * 四件套待办计数(红点唯一来源;口径见 `note`)。
  119. *
  120. * ⚠️ `enabled=false` 时不发请求:`/ticket/todo_counts@v1` 是**运营侧内部口径**,
  121. * 服务端对 `enterprise`/`sub`(客户角色)直接 60058。客户侧页面(工单进度)不渲染
  122. * 依赖该计数的三张 KPI,故按 `enabled` 关掉请求,避免每次进页刷一条红色失败。
  123. */
  124. export function useTodoCounts(enabled = true) {
  125. // enabled 交给 useLoad:停拉时⛔ Promise.resolve(null) 占位(会误记 shown)。
  126. return useLoad<TodoCounts>(() => ticketApi.ticketTodoCounts(), [], enabled);
  127. }
  128. /** `/work-orders/:id` 的 URL 段 → 详情定位参数。
  129. *
  130. * 同一条路由服务两侧:运营侧链接带内部主键(纯数字),客户门户只该带业务工单号
  131. * (`T-YYYYMMDD-NN`,必含非数字)。⛔ 让客户侧 URL 出现主键,也⛔ 让运营侧改链接。 */
  132. export function ticketLocator(raw: string): ticketApi.TicketDetailIn {
  133. const v = (raw ?? "").trim();
  134. return /^\d+$/.test(v) ? { ticket_id: v } : { ticket_no: v };
  135. }
  136. /** 工单详情(`read_event=true` 推进 pending→processing;终态回 KLT-G20401 由调用方忽略)。 */
  137. export function useTicketDetail(ticketId: string, readEvent: boolean) {
  138. const locator = ticketLocator(ticketId);
  139. return useLoad<TicketDetail>(
  140. async () => {
  141. try {
  142. return await ticketApi.ticketDetail({ ...locator, read_event: readEvent });
  143. } catch (e) {
  144. // 已终态的单"读"不推进状态:服务端把这条当业务冲突回,⛔ 因此整页报错,改为静默重取。
  145. if (readEvent && hasBizCode(e, "KLT-G20401")) return ticketApi.ticketDetail(locator);
  146. throw e;
  147. }
  148. },
  149. [ticketId, readEvent],
  150. );
  151. }
  152. /** 报文待处置清单(unmatched/conflict)。 */
  153. export function useMessagePending(page: number) {
  154. const params = { page: normPage(page), page_size: TICKET_PAGE_SIZE };
  155. return useLoad<MessagePendingResult>(() => ticketApi.messagePending(params), [page]);
  156. }
  157. /** 闭环方式配置(仅运营侧三类身份,交付侧 11104 ⇒ 页面渲染"无权查看")。 */
  158. export function useClosureConfig() {
  159. return useLoad<ClosureConfig>(() => ticketApi.ticketConfigGet(), []);
  160. }
  161. /** 全链路追溯(§3.7.3 单票四段;四键至少一键:工单号/订单号/竣工单号/ticket_id)。 */
  162. export function useTrace(d: ticketApi.TraceIn) {
  163. const key = JSON.stringify(d);
  164. return useLoad<TraceResult>(() => ticketApi.ticketTrace(d), [key]);
  165. }
  166. /* ── 展示helper ── */
  167. /** `"2026-11-13 09:12:03+08"` → `2026.11.13 09:12`(工单台账沿用 `.work-order-date` 的点分口径)。 */
  168. export function fmtTime(v?: string | null) {
  169. if (!v) return "-";
  170. const m = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})/.exec(v);
  171. return m ? `${m[1]}.${m[2]}.${m[3]} ${m[4]}:${m[5]}` : v.slice(0, 16);
  172. }
  173. export const fmtDate = (v?: string | null) => (v ? v.slice(0, 10).replaceAll("-", ".") : "-");
  174. /** 金额/数量这类 `::text` 出来的数字列,⛔ 直接 `Number()` 后当 0 渲染。 */
  175. export const numText = (v: unknown, suffix = "") => {
  176. if (v === null || v === undefined || v === "") return "-";
  177. const n = Number(v);
  178. return Number.isFinite(n) ? `${n}${suffix}` : String(v);
  179. };
  180. /**
  181. * 提交失败的可读文本:后端 `code`+`message` **原样透出**(工单§5.2 的拦截全靠这两个数字定位)。
  182. *
  183. * 存在理由:处理链弹窗原先只回一句「提交失败」——`60404 必填组不齐`、`60408 应用数量全零`
  184. * 这些能直接指向缺口的码被吞掉了,运维只能反复点提交猜。⛔ 在本函数里改写文案,只补码不改意。
  185. */
  186. export function submitErrorText(e: unknown, fallback = "提交失败,请稍后重试"): string {
  187. const a = e as { code?: number | null; message?: string } | null;
  188. const msg = (a?.message ?? "").trim();
  189. if (a?.code !== null && a?.code !== undefined) {
  190. return `后端拒绝(code ${a.code}):${msg || "后端未给出原因,请联系管理员查网关日志"}`;
  191. }
  192. return msg || fallback;
  193. }
  194. /**
  195. * `60404` 的缺口组名(`detail.missing_groups[].group_id`)见 `./ticket-gaps.ts`。
  196. */