iboard/server/alert-engine.js
2026-08-06 15:39:59 +08:00

47 lines
1.7 KiB
JavaScript

import { prisma } from './db.js'
// 跨源对比: 同 (indicatorName, period) 多源数据差异超阈值则插 Alert
// conn: mysql2 连接
// 阈值: 绝对差 >= 0.01 且 相对差 >= 1%
// 返回 { inserted, scanned }
const ABS_TOL = 0.01
const REL_TOL = 0.01
export async function checkAfterRefresh(conn) {
// conn 是 mysql2 连接, 走原始 SQL
const [rows] = await conn.execute(`
SELECT ia.name AS indicatorName, a.period, ia.source, a.value
FROM IndicatorPoint a
JOIN Indicator ia ON a.indicatorId = ia.id
ORDER BY ia.name, a.period
`)
const groups = new Map()
for (const r of rows) {
const k = r.indicatorName + '|' + r.period
if (!groups.has(k)) groups.set(k, [])
groups.get(k).push({ source: r.source, value: Number(r.value) })
}
let inserted = 0
for (const [k, arr] of groups) {
if (arr.length < 2) continue
const sources = new Set(arr.map((x) => x.source))
if (sources.size < 2) continue
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
const A = arr[i], B = arr[j]
const diff = Math.abs(A.value - B.value)
const base = Math.max(Math.abs(A.value), Math.abs(B.value), 1e-9)
const ratio = diff / base
if (diff < ABS_TOL || ratio < REL_TOL) continue
const [name, period] = k.split('|')
const [r] = await conn.execute(
'INSERT INTO `Alert` (`indicatorName`, `period`, `valueA`, `valueB`, `sourceA`, `sourceB`, `diff`, `diffRatio`, `createdAt`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(3))',
[name, period, A.value, B.value, A.source, B.source, diff, ratio],
)
if (r.affectedRows === 1) inserted++
}
}
}
return { inserted, scanned: rows.length }
}