incidentTrend.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. /**
  2. * 预警/报警「发生 · 处置」逐日趋势(票 71 返工,维护者 2026-10-29 第 2 条反馈)。
  3. *
  4. * ── 为什么推翻上一版 ──
  5. * 上一版画的是「平均结案时长折线」,实测**画不出线**:后端 `durationTrend` 是**小时**桶、
  6. * 且只有「有样本的小时」才有值 —— 近 7 天 169 个桶里只有 1 个有样本,按日聚合后
  7. * 整个窗口只有**一个点**,一个点连不成线(维护者原话「只有点没有线」)。
  8. * 根本问题不是画法,是**素材**:平均时长变化慢、样本稀,本来就不适合当日频走势。
  9. *
  10. * 维护者改判的口径(本文件的唯一职责):
  11. * 「统计所选时间范围内,每一日的**总预警/报警数**、**新增数**及**处置数**」。
  12. *
  13. * ── 三条线各自的定义(都要能逐日复算,不许互相顶替)──
  14. * · **新增数** = 当天**发布**的条数(`eventTime` 落在当天);
  15. * · **处置数** = 当天**走到本族终态**的条数(预警 CLOSED / 报警 HANDLED,
  16. * 取该事件的 `updatedTime` 作为处置时刻);
  17. * · **总数** = **截至当天结束**的累计条数(`eventTime` ≤ 当天结束)。
  18. * 它必然 ≥ 新增数,且单调不减 —— 与「新增」是两个不同的问题(累计规模 vs 当日增量)。
  19. *
  20. * ── 两处如实说明(都必须上屏,不能只活在这段注释里)──
  21. * 1. **处置时刻的精度**:后端事件端点没有独立的「处置完成时刻」字段,
  22. * 只能用 `updatedTime`。它是**最近更新时间**,对已终态的事件是处置时刻的**上界**
  23. * (研究实测见 `research/alarm-backlog-data.md`:未处理记录的 updatedTime 可晚于
  24. * eventTime 数十小时)。所以「处置数」的日期归属可能有偏差,块上必须写明。
  25. * 2. **总数为累计口径**,不是「当天存在过的总数」。
  26. *
  27. * ── 不补 0 的边界 ──
  28. * 事件行取全(分页取到底)才算得准。取不全 ⇒ 整块返回 `null` 序列 + 原因码,
  29. * 由视图层如实说「这条线为什么不画」,**不拿半份数据画一条偏小的假线**。
  30. */
  31. import { terminalStatuses, statusText, statusVocabulary } from './eventStatusVocab.js'
  32. import { DEFAULT_BACKLOG_TIME_ZONE, parseInstant } from './alarmBacklog.js'
  33. /** 算不出逐日趋势的原因码(视图层据此给文案;空串=正常)。 */
  34. export const INCIDENT_TREND_GAP = {
  35. NONE: '',
  36. NO_EVENTS: 'NO_EVENTS',
  37. PARTIAL: 'PARTIAL',
  38. BAD_WINDOW: 'BAD_WINDOW',
  39. UNKNOWN_STATUS: 'UNKNOWN_STATUS',
  40. }
  41. /** `YYYY-MM-DD` 在某时区的当天起点(epoch ms);解析不了回 NaN。 */
  42. function startOfDayEpoch(dateKey, timeZone) {
  43. const matched = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dateKey == null ? '' : dateKey).trim())
  44. if (!matched) return NaN
  45. const naive = Date.UTC(Number(matched[1]), Number(matched[2]) - 1, Number(matched[3]), 0, 0, 0, 0)
  46. // 用当日中午反解偏移,避免夏令时切换日 00:00 可能不存在的问题。
  47. const probe = naive + 12 * 3600 * 1000
  48. const offsetMinutes = offsetOf(probe, timeZone)
  49. return Number.isFinite(offsetMinutes) ? naive - offsetMinutes * 60000 : NaN
  50. }
  51. /** 复用 alarmBacklog 的偏移反解(不在这里另写一份时区算术)。 */
  52. function offsetOf(epochMs, timeZone) {
  53. const parts = new Intl.DateTimeFormat('en-US', {
  54. timeZone,
  55. hourCycle: 'h23',
  56. year: 'numeric',
  57. month: '2-digit',
  58. day: '2-digit',
  59. hour: '2-digit',
  60. minute: '2-digit',
  61. second: '2-digit',
  62. }).formatToParts(new Date(epochMs))
  63. const map = Object.fromEntries(parts.map((part) => [part.type, part.value]))
  64. const asUtc = Date.UTC(Number(map.year), Number(map.month) - 1, Number(map.day), Number(map.hour) % 24, Number(map.minute), Number(map.second))
  65. return Math.round((asUtc - epochMs) / 60000)
  66. }
  67. /**
  68. * 某 epoch 时刻落在哪个业务日(`YYYY-MM-DD`)。用 `Intl` 而不是本地时区,
  69. * 保证与后端 `Asia/Shanghai` 的分桶同一口径(跨时区部署不会整体错一天)。
  70. */
  71. export function businessDate(epochMs, timeZone = DEFAULT_BACKLOG_TIME_ZONE) {
  72. if (!Number.isFinite(epochMs)) return ''
  73. const parts = new Intl.DateTimeFormat('en-CA', {
  74. timeZone,
  75. year: 'numeric',
  76. month: '2-digit',
  77. day: '2-digit',
  78. }).formatToParts(new Date(epochMs))
  79. const map = Object.fromEntries(parts.map((part) => [part.type, part.value]))
  80. return `${map.year}-${map.month}-${map.day}`
  81. }
  82. /**
  83. * 窗口内的逐日发生/处置趋势。
  84. *
  85. * @param {object} input
  86. * @param {Array<{eventNo?: string, status?: string, eventTime?: string, updatedTime?: string}>} input.events 事件行(需带 status)
  87. * @param {string} input.family `WARNING`/`ALARM`(决定哪一态算终态)
  88. * @param {string} input.startTime ISO 窗口起点(含)
  89. * @param {string} input.endTime ISO 窗口终点(含)
  90. * @param {string} [input.timeZone] 业务时区
  91. * @param {boolean} [input.complete] 事件行是否**取全**(分页截断时 false)
  92. * @returns {{days: Array<{date: string, total: number|null, added: number, handled: number}>|null, reason: string}}
  93. */
  94. export function dailyIncidentTrend({ events, family, startTime, endTime, timeZone = DEFAULT_BACKLOG_TIME_ZONE, complete = true } = {}) {
  95. const start = parseInstant(startTime, timeZone)
  96. const end = parseInstant(endTime, timeZone)
  97. if (!Number.isFinite(start) || !Number.isFinite(end) || start > end) {
  98. return { days: null, reason: INCIDENT_TREND_GAP.BAD_WINDOW }
  99. }
  100. // 取不全 ⇒ 不画线:少一页会让「新增/处置」整段偏低,而偏低看不出来。
  101. if (!complete) return { days: null, reason: INCIDENT_TREND_GAP.PARTIAL }
  102. const list = Array.isArray(events) ? events : []
  103. if (!list.length) return { days: null, reason: INCIDENT_TREND_GAP.NO_EVENTS }
  104. // 票 71 返工(维护者 2026-10-29 第 3 条):第三条线由「累计」改为「**未处置**」。
  105. // 口径:某条事件「已处置」=它的当前状态属于本族的**终态**(预警已解除 CLOSED、
  106. // 报警已处理 HANDLED),处置时刻取 `updatedTime`。于是:
  107. // 未处置(D) = 创建于 D 及以前 且 处置时刻晚于 D(或从未处置)
  108. // 三条线因此满足**可断言的恒等式**:未处置(D) = 未处置(D-1) + 新增(D) − 处置(D)。
  109. // 维护者 2026-10-30 第 3 次反馈:处置必须与 KPI 卡同口径 —— 预警的处置率分子是「已解除」、
  110. // 报警是「已处理」,都是**终态**。此前用 handledStatuses(预警把已处置也算进去)导致
  111. // 趋势的处置合计(6)与 KPI 处置率分子(已解除 4)对不上 —— 这就是「图例与数据对不上」。
  112. const handledSet = new Set(terminalStatuses(family))
  113. const added = new Map()
  114. const handled = new Map()
  115. // 每条事件只留两个时刻:创建时刻 at、处置时刻 handledAt(未处置为 null)。
  116. const facts = []
  117. for (const event of list) {
  118. const status = String((event && event.status) || '').trim().toUpperCase()
  119. // 认不出的状态:不进处置(不知道它是不是处置过)—— 但**必须**在返回值里报出来,
  120. // 否则「处置数偏低」会被当成真实业务数据(词表出现新值的典型症状)。
  121. const known = status !== '' && statusText(family, status) !== status
  122. const at = parseInstant(event && event.eventTime, timeZone)
  123. const handledAtRaw = parseInstant(event && (event.updatedTime || event.eventTime), timeZone)
  124. const handledAt = known && handledSet.has(status) && Number.isFinite(handledAtRaw) ? handledAtRaw : null
  125. if (!Number.isFinite(at)) continue
  126. facts.push({ at, handledAt })
  127. if (at >= start && at <= end) {
  128. const day = businessDate(at, timeZone)
  129. added.set(day, (added.get(day) || 0) + 1)
  130. }
  131. if (handledAt !== null && handledAt >= start && handledAt <= end) {
  132. const day = businessDate(handledAt, timeZone)
  133. handled.set(day, (handled.get(day) || 0) + 1)
  134. }
  135. }
  136. // 逐日骨架:窗口覆盖的每一个业务日都要在位(缺的日子是**真实 0**,不是缺失 ——
  137. // 「当天没有新增」是可断言的业务事实,与「这条线没取到数据」是两件事)。
  138. const days = []
  139. for (let cursor = startOfDayEpoch(businessDate(start, timeZone), timeZone); cursor <= end; cursor += 24 * 3600 * 1000) {
  140. const date = businessDate(cursor, timeZone)
  141. if (!date) break
  142. if (days.length && days[days.length - 1].date === date) continue
  143. const dayEnd = cursor + 24 * 3600 * 1000 - 1
  144. // 未处置:创建于当日结束前、且(此刻仍未处置 或 处置时刻晚于当日结束)。
  145. // 窗口起点之前创建、当日仍未处置的也计入 —— 那才是「截至当日还压着多少」。
  146. const pending = facts.filter((fact) => fact.at <= dayEnd && (fact.handledAt === null || fact.handledAt > dayEnd)).length
  147. days.push({
  148. date,
  149. added: added.get(date) || 0,
  150. handled: handled.get(date) || 0,
  151. pending,
  152. })
  153. }
  154. // 判据必须认「词表里有没有这个码」,不能拿 statusText 返回值与原码比较 ——
  155. // 未登记码现在统一显示「状态未知」(CONTEXT.md 业务编码/状态词表),回原码的旧比较
  156. // 会让未知状态永远判不出来,处置数静默偏低(票 71 B13 的红线)。
  157. const vocabulary = statusVocabulary(family)
  158. const unknown = list.some((event) => {
  159. const status = String((event && event.status) || '').trim().toUpperCase()
  160. return status === '' || !Object.hasOwn(vocabulary, status)
  161. })
  162. return { days, reason: unknown ? INCIDENT_TREND_GAP.UNKNOWN_STATUS : INCIDENT_TREND_GAP.NONE }
  163. }
  164. /** 原因码 → 界面那句话(缺数据时说清「为什么这条线不画」)。 */
  165. export function incidentTrendGapText(reason, family) {
  166. const label = String(family || '').toUpperCase() === 'ALARM' ? '报警' : '预警'
  167. if (reason === INCIDENT_TREND_GAP.PARTIAL) return `事件未取全(分页截断),逐日${label}趋势不画,避免给出偏低的假线`
  168. if (reason === INCIDENT_TREND_GAP.NO_EVENTS) return `本窗口没有${label}记录`
  169. if (reason === INCIDENT_TREND_GAP.BAD_WINDOW) return '统计窗口不合法,逐日趋势不画'
  170. if (reason === INCIDENT_TREND_GAP.UNKNOWN_STATUS) return `出现未登记的状态码,处置数可能偏低(已按原码显示)`
  171. return ''
  172. }