【MES · 工位终端状态感知(11-28 第十三节拍板)】 - 新增 station_terminal_state / station_terminal_event 两表:当前状态镜像 + 状态变化流水 - 在线判定走既有 SSE 长连接存活:建连/断连/30s ping 心跳,90s 无心跳判离线,零 HTTP 轮询 - 登录/退出/暂停/恢复由终端事件驱动上报;新增「终端状态」管理页(produce.terminalstate,仅超级管理员):看在线/登录/操作人/接单/下班判定/心跳,抽屉看状态流水 - 库管代退料前置条件②「工人已下班」据此判定:未登录或终端离线任一即下班 【工位终端 · 全厂统一账号(11-28 拍板)】 - 删除本地账号表与 seed,登录直连 MES 用户表;本地 SQLite 只剩操作日志+登录态,断网不能换人 - SSE 客户端携带本机固定工位号,MES 据连接存活映射该工位在线状态 【单号短号规则(11-27 拍板)】 - 叫料单 MR / 叫料包 PK / 转产退库 TR / 配送单 DL:改「前缀+YYMMDD+3位当天序号」,每天从 001 归零、超 999 进 4 位 - MR 与 TR 同列不同前缀独立计数不撞号;进程内互斥分配 + DB 唯一索引兜底;历史时间戳号一律不动 【退料闭环(11-28)】 - 退库单新增 sn_list:工位提交的待退 SN 清单落库,收货逐颗扫码核对(不按批次分组、允许跨批次混合,所属批次系统按 SN 带出,库管不必填) - 收货改大数量必须有实物依据:SN 件以精确扫描的最终清单为准(条数相等且不重复);批次件必须落到真实启用的四级库位,禁止凭空加库存 - 余量参考值口径定稿(N4):应剩余量 = 实际备料 − 已消耗 − 已退 − 已损耗 - 损耗台账取消「后审核批注」:删 status/comment/commenter/commented_at 字段,WMS 确认收货当场落账闭环,MES 台账只读 【日排产 · 两种 PENDING 区分(11-26 口径定稿)】 - daily_plan 新增 discarded 废弃标记:停用打标、新建不打标;额度只算 CONFIRMED + 未废弃 PENDING - 工单管「要干几台」、日排产管「按天从哪个工位领多少料」,两张账不合并不互倒推;排产合计可小于工单数(缺口靠借料/补料审批摆出,不自动兜底) 【其他】 - SN 查询大小写脱敏(11-27):存储原样不强制大小写,匹配 LOWER(sn)=LOWER(?),扫 ABC-0001 与 abc-0001 命中同一件 - 拧紧枪人工跳过链路:设备未连接时人工跳过上报,「拧紧跳过(设备未连接)」前缀单独列示,不写 torque_record 绝不冒充设备结果 - 单据流转提示规则表全量 35 条(MES 18 + WMS 17):常驻提示条、单号可复制;单号字段逐条对后端响应实测,取不到不显示复制按钮 - PLC 快照缓存/对账、产线清线、绩效与拧紧枪配置页同步修正 【文档】 - 新增《临时结束.md》2026-11-26 日排产/叫料/完工口径大讨论定稿(含状态专项结论与被推翻旧说法留档);问题临时.md 全量更新
333 lines
13 KiB
Go
333 lines
13 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)
|
||
}
|
||
|
||
// MessageAlertTypes 消息通知类预警白名单(2026-11-25 拍板:铃铛与待办分家)。
|
||
// 铃铛只挂「看一眼即已读」的纯消息;需要人干活的业务待办/需处置异常一律不进铃铛,
|
||
// 只在预警中心页与左侧「异常告警」菜单角标呈现。新增消息型预警时在此登记一行;
|
||
// 业务待办型(torque_ng/task_overdue/call_overdue/agv_failed/backup_overdue/
|
||
// line_cache_full/flow_cache_full/flow_transit_timeout/qty_diff/flow_all_paused/
|
||
// wms_not_configured/agv_dispatch_fail/agv_free_robot_fail/agv_pending_fail/
|
||
// agv_pending_timeout/agv_manual_arrive_fail/agv_unload_timeout)严禁加入本清单。
|
||
var MessageAlertTypes = []string{
|
||
"inspection_ng", // 检验不合格
|
||
"emergency_call", // 应急呼叫
|
||
"material_shortage_predict", // 断料推算
|
||
"plc_mes_mismatch", // PLC对账差异
|
||
"material_sync_pull_failed", // 物料拉取失败
|
||
"trial_wms_dispose_fail", // 试验核销失败
|
||
"agv_rcs_fail", // RCS通讯失败
|
||
"agv_rcs_warn", // 海康AGV告警
|
||
"agv_unknown_callback", // 未知任务回调
|
||
"agv_plc_unavailable", // 派车前传感器不可读
|
||
"agv_force_dispatch", // 强制派车
|
||
"dock_sensor_mismatch", // 传感器台账不符
|
||
"force_pick_marked", // 强提风险标记
|
||
"agv_loaded_mismatch", // 取消后仍载货
|
||
}
|
||
|
||
// UnreadMessageAlertCount 未读「消息通知类」预警数(顶栏铃铛专用口径):只统计白名单类型。
|
||
func (s *Service) UnreadMessageAlertCount(ctx context.Context) (int, error) {
|
||
return s.ctx.EntClient.Alert.Query().
|
||
Where(alert.Status("UNREAD"), alert.TypeIn(MessageAlertTypes...)).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
|
||
}
|
||
|
||
// CreateAlertDedup 带时间窗去重的预警创建(2026-11-16 通信类预警专用):
|
||
// 同 type+target 在 windowMin 分钟内已有 UNREAD 预警时跳过,防轮询场景刷爆预警中心。
|
||
// 返回 (true, nil)=实际落库;(false, nil)=窗口内已有同款被去重。
|
||
func (s *Service) CreateAlertDedup(ctx context.Context, typ, level, target, message string, windowMin int) (bool, error) {
|
||
if windowMin <= 0 {
|
||
windowMin = 10
|
||
}
|
||
if windowMin > 1440 {
|
||
windowMin = 1440 // 上限 1 天,防误传超长窗口永久吞预警
|
||
}
|
||
since := time.Now().Add(-time.Duration(windowMin) * time.Minute)
|
||
cnt, cerr := s.ctx.EntClient.Alert.Query().Where(
|
||
alert.TypeEQ(typ),
|
||
alert.StatusEQ("UNREAD"),
|
||
alert.TargetEQ(target),
|
||
alert.CreatedAtGTE(since),
|
||
).Count(ctx)
|
||
if cerr == nil && cnt > 0 {
|
||
return false, nil
|
||
}
|
||
if err := s.CreateAlert(ctx, typ, level, target, message); err != nil {
|
||
return false, err
|
||
}
|
||
return true, nil
|
||
}
|
||
|
||
// 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("当前终端未确定工位,请重新登录并选择工位")
|
||
}
|
||
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
|
||
}
|
||
|
||
// ResolveAllAlerts 全部标记为已读:把当前所有未读预警批量置 READ,记录处置人与处置时间,
|
||
// 返回本次实际处置条数(已读幂等,不重复计数)。与单条处置同一闭环口径。
|
||
func (s *Service) ResolveAllAlerts(ctx context.Context, operator string) (int, error) {
|
||
ids, err := s.ctx.EntClient.Alert.Query().Where(alert.Status("UNREAD")).IDs(ctx)
|
||
if err != nil {
|
||
return 0, err
|
||
}
|
||
if len(ids) == 0 {
|
||
return 0, nil
|
||
}
|
||
n, err := s.ctx.EntClient.Alert.Update().
|
||
Where(alert.IDIn(ids...), alert.Status("UNREAD")).
|
||
SetStatus("READ").SetResolvedAt(time.Now()).SetResolvedBy(operator).Save(ctx)
|
||
return n, 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 / station_alarm):enabled 即命中,忽略阈值比较(B2.3)。
|
||
// 阈值比较型(inventory_low / task_overdue 等)仍按方向 + 阈值判定。
|
||
eventType := typ == "torque_ng" || typ == "inspection_ng" || typ == "station_alarm"
|
||
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
|
||
}
|