tuqin
2026-10-29 0a3129cb06fcea6677245097715dcc6fa3de65e5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package com.ruoyi.lims.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.lims.pojo.AlertRecord;
import com.ruoyi.lims.pojo.DataCollection;
import com.ruoyi.lims.pojo.RealtimeMonitor;
import com.ruoyi.lims.service.AlertRecordService;
import com.ruoyi.lims.service.DataCollectionService;
import com.ruoyi.lims.service.LimsAlertService;
import com.ruoyi.lims.service.RealtimeMonitorService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class LimsAlertServiceImpl implements LimsAlertService {
 
    private final RealtimeMonitorService monitorService;
    private final AlertRecordService alertService;
    private final DataCollectionService collectionService;
 
    @Override
    public Map<String, Object> checkOne(Long monitorId) {
        Map<String, Object> ret = blank();
        if (monitorId == null) {
            ret.put("message", "monitorId 不能为空");
            return ret;
        }
        RealtimeMonitor m = monitorService.getById(monitorId);
        if (m == null) {
            ret.put("message", "监控项不存在");
            return ret;
        }
        doCheck(m, ret, "manual");
        return ret;
    }
 
    @Override
    public Map<String, Object> checkAll(int limit) {
        QueryWrapper<RealtimeMonitor> w = new QueryWrapper<>();
        w.and(x -> x.ne("alert_status", "resolved").or().isNull("alert_status"));
        w.orderByAsc("id");
        w.last("limit " + Math.max(1, limit));
        List<RealtimeMonitor> list = monitorService.list(w);
        Map<String, Object> ret = blank();
        ret.put("scanned", list.size());
        for (RealtimeMonitor m : list) {
            doCheck(m, ret, "auto");
        }
        return ret;
    }
 
    @Override
    public Map<String, Object> handleAlert(Long alertId, String status, String measure, String handler) {
        Map<String, Object> ret = blank();
        if (alertId == null) {
            ret.put("message", "alertId 不能为空");
            return ret;
        }
        AlertRecord a = alertService.getById(alertId);
        if (a == null) {
            ret.put("message", "告警记录不存在");
            return ret;
        }
        String st = status == null || status.trim().isEmpty() ? "resolved" : status.trim();
        AlertRecord upd = new AlertRecord();
        upd.setId(alertId);
        upd.setStatus(st);
        upd.setHandleMeasure(measure);
        upd.setHandler(handler == null || handler.trim().isEmpty() ? "system" : handler.trim());
        upd.setHandleTime(LocalDateTime.now());
        alertService.updateById(upd);
 
        // 已处理/已忽略时,把监控项状态恢复为正常
        if ("resolved".equals(st) || "ignored".equals(st)) {
            RealtimeMonitor mu = new RealtimeMonitor();
            mu.setId(a.getMonitorId());
            mu.setAlertStatus("resolved".equals(st) ? "normal" : "resolved");
            monitorService.updateById(mu);
        }
        ret.put("handled", 1);
        ret.put("message", "告警已" + ("resolved".equals(st) ? "处理" : "更新"));
        return ret;
    }
 
    @Override
    public Map<String, Object> statistics() {
        Map<String, Object> ret = new LinkedHashMap<>();
        ret.put("pending", countByStatus("pending"));
        ret.put("handling", countByStatus("handling"));
        ret.put("resolved", countByStatus("resolved"));
        ret.put("ignored", countByStatus("ignored"));
        ret.put("levelHigh", countByLevel("high"));
        ret.put("levelMedium", countByLevel("medium"));
        ret.put("levelLow", countByLevel("low"));
        ret.put("total", alertService.count());
        return ret;
    }
 
    @Override
    public Map<String, Object> syncFromCollection(Long collectionId) {
        Map<String, Object> ret = blank();
        if (collectionId == null) {
            ret.put("message", "collectionId 不能为空");
            return ret;
        }
        DataCollection dc = collectionService.getById(collectionId);
        if (dc == null) {
            ret.put("message", "采集记录不存在");
            return ret;
        }
        if (dc.getCollectionValue() == null) {
            ret.put("message", "该采集记录没有数值,无法同步");
            return ret;
        }
 
        // 按 deviceCode == monitorCode,或 deviceName == monitorTarget 匹配
        QueryWrapper<RealtimeMonitor> w = new QueryWrapper<>();
        w.and(x -> x.eq("monitor_code", dc.getDeviceCode())
                .or()
                .eq("monitor_target", dc.getDeviceName()));
        w.orderByAsc("id");
        w.last("limit 1");
        RealtimeMonitor m = monitorService.getOne(w, false);
        if (m == null) {
            ret.put("message", "未找到匹配的监控项(monitorCode=" + dc.getDeviceCode()
                    + " 或 monitorTarget=" + dc.getDeviceName() + ")");
            return ret;
        }
 
        RealtimeMonitor upd = new RealtimeMonitor();
        upd.setId(m.getId());
        upd.setCurrentValue(dc.getCollectionValue());
        if (dc.getUnit() != null) upd.setUnit(dc.getUnit());
        upd.setMonitorTime(dc.getCollectionTime() == null ? LocalDateTime.now() : dc.getCollectionTime());
        upd.setSourceCollectionId(dc.getId());
        monitorService.updateById(upd);
 
        m.setCurrentValue(dc.getCollectionValue());
        if (dc.getUnit() != null) m.setUnit(dc.getUnit());
        m.setMonitorTime(upd.getMonitorTime());
 
        ret.put("monitorId", m.getId());
        ret.put("monitorTarget", m.getMonitorTarget());
        doCheck(m, ret, "collect");
        return ret;
    }
 
    /* ==================== 核心判定 ==================== */
 
    private void doCheck(RealtimeMonitor m, Map<String, Object> ret, String source) {
        LocalDateTime now = LocalDateTime.now();
        BigDecimal v = m.getCurrentValue();
 
        // 无当前值:只记录判定时间,不产生告警
        if (v == null) {
            RealtimeMonitor u = new RealtimeMonitor();
            u.setId(m.getId());
            u.setLastCheckTime(now);
            monitorService.updateById(u);
            ret.put("noValue", (Integer) ret.get("noValue") + 1);
            return;
        }
 
        BigDecimal up = m.getUpperLimit();
        BigDecimal lo = m.getLowerLimit();
        boolean overUp = up != null && v.compareTo(up) > 0;
        boolean underLo = lo != null && v.compareTo(lo) < 0;
        boolean abnormal = overUp || underLo;
 
        // 已有未处理告警时不重复生成,避免刷屏
        long openAlerts = 0;
        QueryWrapper<AlertRecord> aw = new QueryWrapper<>();
        aw.eq("monitor_id", m.getId()).in("status", "pending", "handling");
        openAlerts = alertService.count(aw);
 
        RealtimeMonitor upd = new RealtimeMonitor();
        upd.setId(m.getId());
        upd.setLastCheckTime(now);
 
        if (abnormal) {
            String level = resolveLevel(overUp, underLo, m.getAlertLevel());
            String msg = buildMsg(m, v, up, lo, overUp, underLo);
            upd.setAlertStatus(overUp || underLo ? "alert" : "warning");
            upd.setAlertLevel(level);
            if (openAlerts == 0) {
                AlertRecord a = new AlertRecord();
                a.setMonitorId(m.getId());
                a.setMonitorCode(m.getMonitorCode());
                a.setMonitorTarget(m.getMonitorTarget());
                a.setMonitorType(m.getMonitorType());
                a.setAlertLevel(level);
                a.setAlertValue(v);
                a.setUnit(m.getUnit());
                a.setUpperLimit(up);
                a.setLowerLimit(lo);
                a.setAlertMessage(msg);
                a.setSource(source);
                a.setStatus("pending");
                a.setAlertTime(now);
                alertService.save(a);
                upd.setAlertCount((m.getAlertCount() == null ? 0 : m.getAlertCount()) + 1);
                ret.put("alerts", (Integer) ret.get("alerts") + 1);
            } else {
                ret.put("suppressed", (Integer) ret.get("suppressed") + 1);
            }
        } else {
            // 正常:如果之前有告警但已恢复,置为 resolved
            if (openAlerts > 0) {
                upd.setAlertStatus("resolved");
            } else {
                upd.setAlertStatus("normal");
            }
            ret.put("normal", (Integer) ret.get("normal") + 1);
        }
 
        monitorService.updateById(upd);
    }
 
    private String resolveLevel(boolean overUp, boolean underLo, String configured) {
        // 越限幅度决定级别:超过上限/下限 20% 以上算 high
        if (configured != null && !configured.trim().isEmpty()) {
            String c = configured.trim().toLowerCase();
            if (c.equals("high") || c.equals("medium") || c.equals("low")) return c;
        }
        return overUp ? "high" : "medium";
    }
 
    private String buildMsg(RealtimeMonitor m, BigDecimal v, BigDecimal up, BigDecimal lo,
                            boolean overUp, boolean underLo) {
        String unit = m.getUnit() == null ? "" : m.getUnit();
        StringBuilder sb = new StringBuilder();
        sb.append("监控项「").append(m.getMonitorTarget() == null ? m.getMonitorCode() : m.getMonitorTarget())
                .append("」当前值 ").append(v.stripTrailingZeros().toPlainString()).append(unit);
        if (overUp && up != null) {
            sb.append(",超出上限 ").append(up.stripTrailingZeros().toPlainString()).append(unit);
            BigDecimal diff = v.subtract(up);
            if (up.compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal pct = diff.multiply(new BigDecimal("100"))
                        .divide(up.abs(), 2, BigDecimal.ROUND_HALF_UP);
                sb.append("(超出 ").append(pct.stripTrailingZeros().toPlainString()).append("%)");
            }
        }
        if (underLo && lo != null) {
            sb.append(",低于下限 ").append(lo.stripTrailingZeros().toPlainString()).append(unit);
        }
        return sb.toString();
    }
 
    private long countByStatus(String status) {
        QueryWrapper<AlertRecord> w = new QueryWrapper<>();
        w.eq("status", status);
        return alertService.count(w);
    }
 
    private long countByLevel(String level) {
        QueryWrapper<AlertRecord> w = new QueryWrapper<>();
        w.eq("alert_level", level).in("status", "pending", "handling");
        return alertService.count(w);
    }
 
    private Map<String, Object> blank() {
        Map<String, Object> m = new LinkedHashMap<>();
        m.put("scanned", 0);
        m.put("alerts", 0);
        m.put("normal", 0);
        m.put("noValue", 0);
        m.put("suppressed", 0);
        return m;
    }
}