| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180 |
- /**
- * 预警/报警「发生 · 处置」逐日趋势(票 71 返工,维护者 2026-10-29 第 2 条反馈)。
- *
- * ── 为什么推翻上一版 ──
- * 上一版画的是「平均结案时长折线」,实测**画不出线**:后端 `durationTrend` 是**小时**桶、
- * 且只有「有样本的小时」才有值 —— 近 7 天 169 个桶里只有 1 个有样本,按日聚合后
- * 整个窗口只有**一个点**,一个点连不成线(维护者原话「只有点没有线」)。
- * 根本问题不是画法,是**素材**:平均时长变化慢、样本稀,本来就不适合当日频走势。
- *
- * 维护者改判的口径(本文件的唯一职责):
- * 「统计所选时间范围内,每一日的**总预警/报警数**、**新增数**及**处置数**」。
- *
- * ── 三条线各自的定义(都要能逐日复算,不许互相顶替)──
- * · **新增数** = 当天**发布**的条数(`eventTime` 落在当天);
- * · **处置数** = 当天**走到本族终态**的条数(预警 CLOSED / 报警 HANDLED,
- * 取该事件的 `updatedTime` 作为处置时刻);
- * · **总数** = **截至当天结束**的累计条数(`eventTime` ≤ 当天结束)。
- * 它必然 ≥ 新增数,且单调不减 —— 与「新增」是两个不同的问题(累计规模 vs 当日增量)。
- *
- * ── 两处如实说明(都必须上屏,不能只活在这段注释里)──
- * 1. **处置时刻的精度**:后端事件端点没有独立的「处置完成时刻」字段,
- * 只能用 `updatedTime`。它是**最近更新时间**,对已终态的事件是处置时刻的**上界**
- * (研究实测见 `research/alarm-backlog-data.md`:未处理记录的 updatedTime 可晚于
- * eventTime 数十小时)。所以「处置数」的日期归属可能有偏差,块上必须写明。
- * 2. **总数为累计口径**,不是「当天存在过的总数」。
- *
- * ── 不补 0 的边界 ──
- * 事件行取全(分页取到底)才算得准。取不全 ⇒ 整块返回 `null` 序列 + 原因码,
- * 由视图层如实说「这条线为什么不画」,**不拿半份数据画一条偏小的假线**。
- */
- import { terminalStatuses, statusText, statusVocabulary } from './eventStatusVocab.js'
- import { DEFAULT_BACKLOG_TIME_ZONE, parseInstant } from './alarmBacklog.js'
- /** 算不出逐日趋势的原因码(视图层据此给文案;空串=正常)。 */
- export const INCIDENT_TREND_GAP = {
- NONE: '',
- NO_EVENTS: 'NO_EVENTS',
- PARTIAL: 'PARTIAL',
- BAD_WINDOW: 'BAD_WINDOW',
- UNKNOWN_STATUS: 'UNKNOWN_STATUS',
- }
- /** `YYYY-MM-DD` 在某时区的当天起点(epoch ms);解析不了回 NaN。 */
- function startOfDayEpoch(dateKey, timeZone) {
- const matched = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dateKey == null ? '' : dateKey).trim())
- if (!matched) return NaN
- const naive = Date.UTC(Number(matched[1]), Number(matched[2]) - 1, Number(matched[3]), 0, 0, 0, 0)
- // 用当日中午反解偏移,避免夏令时切换日 00:00 可能不存在的问题。
- const probe = naive + 12 * 3600 * 1000
- const offsetMinutes = offsetOf(probe, timeZone)
- return Number.isFinite(offsetMinutes) ? naive - offsetMinutes * 60000 : NaN
- }
- /** 复用 alarmBacklog 的偏移反解(不在这里另写一份时区算术)。 */
- function offsetOf(epochMs, timeZone) {
- const parts = new Intl.DateTimeFormat('en-US', {
- timeZone,
- hourCycle: 'h23',
- year: 'numeric',
- month: '2-digit',
- day: '2-digit',
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit',
- }).formatToParts(new Date(epochMs))
- const map = Object.fromEntries(parts.map((part) => [part.type, part.value]))
- const asUtc = Date.UTC(Number(map.year), Number(map.month) - 1, Number(map.day), Number(map.hour) % 24, Number(map.minute), Number(map.second))
- return Math.round((asUtc - epochMs) / 60000)
- }
- /**
- * 某 epoch 时刻落在哪个业务日(`YYYY-MM-DD`)。用 `Intl` 而不是本地时区,
- * 保证与后端 `Asia/Shanghai` 的分桶同一口径(跨时区部署不会整体错一天)。
- */
- export function businessDate(epochMs, timeZone = DEFAULT_BACKLOG_TIME_ZONE) {
- if (!Number.isFinite(epochMs)) return ''
- const parts = new Intl.DateTimeFormat('en-CA', {
- timeZone,
- year: 'numeric',
- month: '2-digit',
- day: '2-digit',
- }).formatToParts(new Date(epochMs))
- const map = Object.fromEntries(parts.map((part) => [part.type, part.value]))
- return `${map.year}-${map.month}-${map.day}`
- }
- /**
- * 窗口内的逐日发生/处置趋势。
- *
- * @param {object} input
- * @param {Array<{eventNo?: string, status?: string, eventTime?: string, updatedTime?: string}>} input.events 事件行(需带 status)
- * @param {string} input.family `WARNING`/`ALARM`(决定哪一态算终态)
- * @param {string} input.startTime ISO 窗口起点(含)
- * @param {string} input.endTime ISO 窗口终点(含)
- * @param {string} [input.timeZone] 业务时区
- * @param {boolean} [input.complete] 事件行是否**取全**(分页截断时 false)
- * @returns {{days: Array<{date: string, total: number|null, added: number, handled: number}>|null, reason: string}}
- */
- export function dailyIncidentTrend({ events, family, startTime, endTime, timeZone = DEFAULT_BACKLOG_TIME_ZONE, complete = true } = {}) {
- const start = parseInstant(startTime, timeZone)
- const end = parseInstant(endTime, timeZone)
- if (!Number.isFinite(start) || !Number.isFinite(end) || start > end) {
- return { days: null, reason: INCIDENT_TREND_GAP.BAD_WINDOW }
- }
- // 取不全 ⇒ 不画线:少一页会让「新增/处置」整段偏低,而偏低看不出来。
- if (!complete) return { days: null, reason: INCIDENT_TREND_GAP.PARTIAL }
- const list = Array.isArray(events) ? events : []
- if (!list.length) return { days: null, reason: INCIDENT_TREND_GAP.NO_EVENTS }
- // 票 71 返工(维护者 2026-10-29 第 3 条):第三条线由「累计」改为「**未处置**」。
- // 口径:某条事件「已处置」=它的当前状态属于本族的**终态**(预警已解除 CLOSED、
- // 报警已处理 HANDLED),处置时刻取 `updatedTime`。于是:
- // 未处置(D) = 创建于 D 及以前 且 处置时刻晚于 D(或从未处置)
- // 三条线因此满足**可断言的恒等式**:未处置(D) = 未处置(D-1) + 新增(D) − 处置(D)。
- // 维护者 2026-10-30 第 3 次反馈:处置必须与 KPI 卡同口径 —— 预警的处置率分子是「已解除」、
- // 报警是「已处理」,都是**终态**。此前用 handledStatuses(预警把已处置也算进去)导致
- // 趋势的处置合计(6)与 KPI 处置率分子(已解除 4)对不上 —— 这就是「图例与数据对不上」。
- const handledSet = new Set(terminalStatuses(family))
- const added = new Map()
- const handled = new Map()
- // 每条事件只留两个时刻:创建时刻 at、处置时刻 handledAt(未处置为 null)。
- const facts = []
- for (const event of list) {
- const status = String((event && event.status) || '').trim().toUpperCase()
- // 认不出的状态:不进处置(不知道它是不是处置过)—— 但**必须**在返回值里报出来,
- // 否则「处置数偏低」会被当成真实业务数据(词表出现新值的典型症状)。
- const known = status !== '' && statusText(family, status) !== status
- const at = parseInstant(event && event.eventTime, timeZone)
- const handledAtRaw = parseInstant(event && (event.updatedTime || event.eventTime), timeZone)
- const handledAt = known && handledSet.has(status) && Number.isFinite(handledAtRaw) ? handledAtRaw : null
- if (!Number.isFinite(at)) continue
- facts.push({ at, handledAt })
- if (at >= start && at <= end) {
- const day = businessDate(at, timeZone)
- added.set(day, (added.get(day) || 0) + 1)
- }
- if (handledAt !== null && handledAt >= start && handledAt <= end) {
- const day = businessDate(handledAt, timeZone)
- handled.set(day, (handled.get(day) || 0) + 1)
- }
- }
- // 逐日骨架:窗口覆盖的每一个业务日都要在位(缺的日子是**真实 0**,不是缺失 ——
- // 「当天没有新增」是可断言的业务事实,与「这条线没取到数据」是两件事)。
- const days = []
- for (let cursor = startOfDayEpoch(businessDate(start, timeZone), timeZone); cursor <= end; cursor += 24 * 3600 * 1000) {
- const date = businessDate(cursor, timeZone)
- if (!date) break
- if (days.length && days[days.length - 1].date === date) continue
- const dayEnd = cursor + 24 * 3600 * 1000 - 1
- // 未处置:创建于当日结束前、且(此刻仍未处置 或 处置时刻晚于当日结束)。
- // 窗口起点之前创建、当日仍未处置的也计入 —— 那才是「截至当日还压着多少」。
- const pending = facts.filter((fact) => fact.at <= dayEnd && (fact.handledAt === null || fact.handledAt > dayEnd)).length
- days.push({
- date,
- added: added.get(date) || 0,
- handled: handled.get(date) || 0,
- pending,
- })
- }
- // 判据必须认「词表里有没有这个码」,不能拿 statusText 返回值与原码比较 ——
- // 未登记码现在统一显示「状态未知」(CONTEXT.md 业务编码/状态词表),回原码的旧比较
- // 会让未知状态永远判不出来,处置数静默偏低(票 71 B13 的红线)。
- const vocabulary = statusVocabulary(family)
- const unknown = list.some((event) => {
- const status = String((event && event.status) || '').trim().toUpperCase()
- return status === '' || !Object.hasOwn(vocabulary, status)
- })
- return { days, reason: unknown ? INCIDENT_TREND_GAP.UNKNOWN_STATUS : INCIDENT_TREND_GAP.NONE }
- }
- /** 原因码 → 界面那句话(缺数据时说清「为什么这条线不画」)。 */
- export function incidentTrendGapText(reason, family) {
- const label = String(family || '').toUpperCase() === 'ALARM' ? '报警' : '预警'
- if (reason === INCIDENT_TREND_GAP.PARTIAL) return `事件未取全(分页截断),逐日${label}趋势不画,避免给出偏低的假线`
- if (reason === INCIDENT_TREND_GAP.NO_EVENTS) return `本窗口没有${label}记录`
- if (reason === INCIDENT_TREND_GAP.BAD_WINDOW) return '统计窗口不合法,逐日趋势不画'
- if (reason === INCIDENT_TREND_GAP.UNKNOWN_STATUS) return `出现未登记的状态码,处置数可能偏低(已按原码显示)`
- return ''
- }
|