261 lines
9.3 KiB
Go
261 lines
9.3 KiB
Go
package logic
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"strings"
|
||
"time"
|
||
|
||
"bj_power_mes/ent"
|
||
"bj_power_mes/ent/alert"
|
||
"bj_power_mes/ent/alertrule"
|
||
)
|
||
|
||
// CreateAlertRule 新增预警规则
|
||
func (s *Service) CreateAlertRule(ctx context.Context, name, typ, notifyChannels string, threshold float64, enabled bool, createdBy string) error {
|
||
if name == "" || typ == "" {
|
||
return errors.New("规则名称与类型必填")
|
||
}
|
||
_, err := s.ctx.EntClient.AlertRule.Create().
|
||
SetName(name).SetType(typ).SetThreshold(threshold).
|
||
SetNotifyChannels(notifyChannels).SetEnabled(enabled).SetCreatedBy(createdBy).Save(ctx)
|
||
return err
|
||
}
|
||
|
||
// UpdateAlertRule 修改预警规则
|
||
func (s *Service) UpdateAlertRule(ctx context.Context, id int, name, typ, notifyChannels string, threshold float64, enabled bool) error {
|
||
if id <= 0 {
|
||
return errors.New("规则ID无效")
|
||
}
|
||
if name == "" || typ == "" {
|
||
return errors.New("规则名称与类型必填")
|
||
}
|
||
_, err := s.ctx.EntClient.AlertRule.UpdateOneID(id).
|
||
SetName(name).SetType(typ).SetThreshold(threshold).
|
||
SetNotifyChannels(notifyChannels).SetEnabled(enabled).Save(ctx)
|
||
return err
|
||
}
|
||
|
||
// DeleteAlertRule 删除预警规则
|
||
func (s *Service) DeleteAlertRule(ctx context.Context, id int) error {
|
||
if id <= 0 {
|
||
return errors.New("规则ID无效")
|
||
}
|
||
return s.ctx.EntClient.AlertRule.DeleteOneID(id).Exec(ctx)
|
||
}
|
||
|
||
// ListAlertRules 查询全部预警规则
|
||
func (s *Service) ListAlertRules(ctx context.Context) ([]*ent.AlertRule, error) {
|
||
return s.ctx.EntClient.AlertRule.Query().
|
||
Order(ent.Desc(alertrule.FieldCreatedAt), ent.Desc(alertrule.FieldID)).All(ctx)
|
||
}
|
||
|
||
// AlertQuery 预警查询条件:status/type/level 空=不限;from/to 为 YYYY-MM-DD(空=不限);page<=0 表示不分页。
|
||
type AlertQuery struct {
|
||
Status string
|
||
Type string
|
||
Level string // 级别筛选(遗留5):信息/警告/严重,空=不限
|
||
From string
|
||
To string
|
||
OrderNo string // 工单号(模糊,客户第12条:记录查看加一项看工单号查询)
|
||
Page int
|
||
PageSize int
|
||
}
|
||
|
||
// ListAlerts 查询预警消息(支持 级别/状态/类型/时间范围筛选 + 分页),返回当前页数据与命中总数
|
||
func (s *Service) ListAlerts(ctx context.Context, q AlertQuery) ([]*ent.Alert, int, error) {
|
||
query := s.ctx.EntClient.Alert.Query()
|
||
if q.Status != "" {
|
||
query = query.Where(alert.Status(q.Status))
|
||
}
|
||
if q.Type != "" {
|
||
query = query.Where(alert.Type(q.Type))
|
||
}
|
||
if q.Level != "" {
|
||
query = query.Where(alert.Level(q.Level))
|
||
}
|
||
if q.From != "" {
|
||
if f, err := time.Parse("2006-01-02", q.From); err == nil {
|
||
query = query.Where(alert.CreatedAtGTE(f))
|
||
}
|
||
}
|
||
if q.To != "" {
|
||
if t, err := time.Parse("2006-01-02", q.To); err == nil {
|
||
query = query.Where(alert.CreatedAtLT(t.Add(24 * time.Hour)))
|
||
}
|
||
}
|
||
if q.OrderNo != "" {
|
||
query = query.Where(alert.OrderNoContainsFold(q.OrderNo))
|
||
}
|
||
total, err := query.Count(ctx)
|
||
if err != nil {
|
||
return nil, 0, err
|
||
}
|
||
if q.Page > 0 {
|
||
size := q.PageSize
|
||
if size <= 0 {
|
||
size = 20
|
||
}
|
||
query = query.Offset((q.Page - 1) * size).Limit(size)
|
||
}
|
||
list, err := query.Order(ent.Desc(alert.FieldCreatedAt), ent.Desc(alert.FieldID)).All(ctx)
|
||
return list, total, err
|
||
}
|
||
|
||
// UnreadAlertCount 未读预警数
|
||
func (s *Service) UnreadAlertCount(ctx context.Context) (int, error) {
|
||
return s.ctx.EntClient.Alert.Query().Where(alert.Status("UNREAD")).Count(ctx)
|
||
}
|
||
|
||
// MarkAlertRead 标记预警已读
|
||
func (s *Service) MarkAlertRead(ctx context.Context, id int) error {
|
||
if id <= 0 {
|
||
return errors.New("预警ID无效")
|
||
}
|
||
_, err := s.ctx.EntClient.Alert.UpdateOneID(id).SetStatus("READ").Save(ctx)
|
||
return err
|
||
}
|
||
|
||
// CreateAlert 直写一条预警(遗留5 告警框架第一阶段,业务事件入口,不走规则阈值):
|
||
// CreateAlert(type, level, target, message)——type=业务类型(如 torque_ng)、
|
||
// level=级别(信息/警告/严重)、target=目标对象(工位/库房/SN)、message=预警内容。
|
||
// message 同时落 title(超长按字节安全截断)与 content,状态 UNREAD,待预警中心处置。
|
||
func (s *Service) CreateAlert(ctx context.Context, typ, level, target, message string) error {
|
||
if strings.TrimSpace(typ) == "" || strings.TrimSpace(message) == "" {
|
||
return errors.New("预警类型与内容必填")
|
||
}
|
||
// title/content 按字节安全截断(对齐 schema MaxLen:title 255 / content 500)。
|
||
// ent 的 MaxLen 按【字节】校验,中文 3 字节/字;若按 rune 截断,中文仍会超字节限
|
||
// (曾致 T6/T7 对账预警 title 恒超 120 字节、落预警中心失败),故按 rune 边界回退截断。
|
||
title := truncateUTF8(message, 255)
|
||
content := truncateUTF8(message, 500)
|
||
a, err := s.ctx.EntClient.Alert.Create().
|
||
SetRuleId(0).SetType(typ).SetLevel(level).SetTarget(target).
|
||
SetTitle(title).SetContent(content).
|
||
SetStatus("UNREAD").Save(ctx)
|
||
if err == nil {
|
||
s.publishStationAlert(a) // 写入成功即向工位订阅者广播(谁受影响谁播报)
|
||
}
|
||
return err
|
||
}
|
||
|
||
// publishStationAlert 报警写入成功后经 SSE Hub 广播 station.alert 事件(载荷=报警 JSON)。
|
||
// 终端侧按「工位N」自行过滤(Hub 是广播语义,按工位点对点过滤交给唯一消费者=终端后端)。
|
||
func (s *Service) publishStationAlert(a *ent.Alert) {
|
||
if s.ctx.SSE == nil || a == nil {
|
||
return
|
||
}
|
||
if b, jerr := json.Marshal(a); jerr == nil {
|
||
s.ctx.SSE.Publish("station.alert", string(b))
|
||
}
|
||
}
|
||
|
||
// StationAlerts 工位终端「本工位相关报警」查询(谁受影响谁播报):
|
||
// 取最近 minutes 分钟内未处置(UNREAD)、且 目标或内容 命中「工位N」的报警。
|
||
// 工位相关报警写入约定:target="工位N"(plc_mismatch)或 content 含「工位N」(torque_ng);
|
||
// 缺料/叫料/设备类报警后续落库时按同约定写 target,即自动进入本查询。
|
||
func (s *Service) StationAlerts(ctx context.Context, stationNo, minutes int) ([]*ent.Alert, error) {
|
||
if stationNo <= 0 {
|
||
return nil, errors.New("缺少有效的 stationNo")
|
||
}
|
||
if minutes <= 0 {
|
||
minutes = 10
|
||
}
|
||
if minutes > 120 {
|
||
minutes = 120 // 时间窗封顶 2 小时,防止终端误传超长窗口拉爆查询
|
||
}
|
||
tgt := fmt.Sprintf("工位%d", stationNo)
|
||
since := time.Now().Add(-time.Duration(minutes) * time.Minute)
|
||
return s.ctx.EntClient.Alert.Query().
|
||
Where(
|
||
alert.Status("UNREAD"),
|
||
alert.CreatedAtGTE(since),
|
||
alert.Or(alert.TargetEQ(tgt), alert.ContentContainsFold(tgt)),
|
||
).
|
||
Order(ent.Desc(alert.FieldCreatedAt), ent.Desc(alert.FieldID)).
|
||
Limit(20).
|
||
All(ctx)
|
||
}
|
||
|
||
// truncateUTF8 按字节安全截断:最多保留 maxBytes 字节,且按 rune 边界回退,
|
||
// 不切断 UTF-8 多字节字符(中文 3 字节/字),避免 ent MaxLen(按字节校验)失败。
|
||
func truncateUTF8(s string, maxBytes int) string {
|
||
if len(s) <= maxBytes {
|
||
return s
|
||
}
|
||
b := make([]byte, 0, maxBytes)
|
||
for _, r := range s {
|
||
rb := []byte(string(r))
|
||
if len(b)+len(rb) > maxBytes {
|
||
break
|
||
}
|
||
b = append(b, rb...)
|
||
}
|
||
return string(b)
|
||
}
|
||
|
||
// ResolveAlert 处置预警(POST /alerts/:id/resolve):置 READ 并记录处置人与处置时间,
|
||
// 形成闭环(谁在何时处置);重复处置幂等(已处置直接成功)。
|
||
func (s *Service) ResolveAlert(ctx context.Context, id int, operator string) error {
|
||
if id <= 0 {
|
||
return errors.New("预警ID无效")
|
||
}
|
||
a, err := s.ctx.EntClient.Alert.Get(ctx, id)
|
||
if err != nil {
|
||
return errors.New("预警不存在")
|
||
}
|
||
if a.Status == "READ" {
|
||
return nil // 幂等:已处置
|
||
}
|
||
_, err = s.ctx.EntClient.Alert.UpdateOneID(id).
|
||
SetStatus("READ").SetResolvedAt(time.Now()).SetResolvedBy(operator).Save(ctx)
|
||
return err
|
||
}
|
||
|
||
// alertDirection 阈值比较方向:inventory_low 为 <=,其余为 >=
|
||
func alertDirection(typ string) int {
|
||
if typ == "inventory_low" {
|
||
return -1
|
||
}
|
||
return 1
|
||
}
|
||
|
||
// Evaluate 预警规则评估:遍历启用且类型匹配的规则,命中阈值则写 alert 消息。
|
||
// 由业务事件触发(如拧紧不合格),也可手动调用。
|
||
// orderNo:关联工单号(可空),写入 alert.order_no 供预警中心按工单号检索。
|
||
func (s *Service) Evaluate(ctx context.Context, typ string, value float64, title, content, refType, refId, orderNo string) {
|
||
rules, err := s.ctx.EntClient.AlertRule.Query().
|
||
Where(alertrule.Type(typ), alertrule.Enabled(true)).All(ctx)
|
||
if err != nil || len(rules) == 0 {
|
||
return
|
||
}
|
||
// 事件触发型(torque_ng / inspection_ng):enabled 即命中,忽略阈值比较(B2.3)。
|
||
// 阈值比较型(inventory_low / task_overdue 等)仍按方向 + 阈值判定。
|
||
eventType := typ == "torque_ng" || typ == "inspection_ng"
|
||
for _, r := range rules {
|
||
hit := true
|
||
if !eventType {
|
||
dir := alertDirection(typ)
|
||
hit = (dir == 1 && value >= r.Threshold) || (dir == -1 && value <= r.Threshold)
|
||
}
|
||
if !hit {
|
||
continue
|
||
}
|
||
_ = s.createAlert(ctx, r.ID, typ, title, content, refType, refId, orderNo, r.NotifyChannels)
|
||
}
|
||
}
|
||
|
||
func (s *Service) createAlert(ctx context.Context, ruleId int, typ, title, content, refType, refId, orderNo, receiver string) error {
|
||
a, err := s.ctx.EntClient.Alert.Create().
|
||
SetRuleId(ruleId).SetType(typ).SetTitle(truncateUTF8(title, 255)).
|
||
SetContent(truncateUTF8(content, 500)).SetRefType(refType).SetRefId(refId).
|
||
SetOrderNo(orderNo).
|
||
SetReceiver(receiver).SetStatus("UNREAD").Save(ctx)
|
||
if err == nil {
|
||
s.publishStationAlert(a) // 规则命中路径同样广播(如 inventory_low 落库后终端可感知)
|
||
}
|
||
return err
|
||
}
|