This commit is contained in:
SunYF
2026-10-26 16:32:35 +08:00
parent 4b14f9540a
commit f86feb2271
99 changed files with 1652 additions and 521 deletions
+8 -2
View File
@@ -231,9 +231,15 @@ func (s *Service) Evaluate(ctx context.Context, typ string, value float64, title
if err != nil || len(rules) == 0 {
return
}
dir := alertDirection(typ)
// 事件触发型(torque_ng / inspection_ng):enabled 即命中,忽略阈值比较(B2.3)。
// 阈值比较型(inventory_low / task_overdue 等)仍按方向 + 阈值判定。
eventType := typ == "torque_ng" || typ == "inspection_ng"
for _, r := range rules {
hit := (dir == 1 && value >= r.Threshold) || (dir == -1 && value <= r.Threshold)
hit := true
if !eventType {
dir := alertDirection(typ)
hit = (dir == 1 && value >= r.Threshold) || (dir == -1 && value <= r.Threshold)
}
if !hit {
continue
}
+7 -2
View File
@@ -535,8 +535,13 @@ func (s *Service) DeleteRole(ctx context.Context, id int) error {
return s.ctx.EntClient.Role.DeleteOneID(id).Exec(ctx)
}
func (s *Service) ListRoles(ctx context.Context) ([]*ent.Role, error) {
return s.ctx.EntClient.Role.Query().Order(ent.Asc(role.FieldID)).All(ctx)
func (s *Service) ListRoles(ctx context.Context, keyword string) ([]*ent.Role, error) {
q := s.ctx.EntClient.Role.Query().Order(ent.Asc(role.FieldID))
if keyword != "" {
kw := keyword
q = q.Where(role.Or(role.NameContainsFold(kw), role.CodeContainsFold(kw)))
}
return q.All(ctx)
}
type PermissionReq struct {
@@ -109,6 +109,9 @@ type FrontDashboard struct {
Trends FrontTrends `json:"trends"`
// Alarms 仅用于前端语音播报(D2),不渲染到屏幕(报喜不报忧)。
Alarms []AlarmItem `json:"alarms"`
// RefreshSeconds 看板轮询兜底刷新间隔(秒,1~10),由 dashboard.refresh.seconds 配置驱动;
// 仅影响 SSE 实时通道不可用时的 HTTP 轮询周期,SSE 可用时不依赖此值。
RefreshSeconds int `json:"refreshSeconds"`
}
// DashboardFrontSnapshot 看板前端快照:富聚合 → 前端契约映射,走同一缓存(60s + 防击穿)。
@@ -118,7 +121,9 @@ func (s *Service) DashboardFrontSnapshot(ctx context.Context) (*FrontDashboard,
if err != nil {
return nil, err
}
return mapFrontDashboard(rich), nil
f := mapFrontDashboard(rich)
f.RefreshSeconds = s.CfgInt(ctx, CfgDashboardRefreshSeconds, 5)
return f, nil
})
}
@@ -193,6 +193,14 @@ func (s *Service) CreateInspection(ctx context.Context, req InspectionReq, opera
}
}
// B2.3 检验不合格 → 触发 inspection_ng 预警(事件触发型,enabled 即命中,忽略阈值):
// 仅结论 NG 时触发;走 Evaluate 经 alert_rule(enabled) 门控,与拧紧/库存/超期预警同一框架。
if result == "NG" {
s.Evaluate(ctx, "inspection_ng", 1, "检验不合格",
"检验记录不合格:类型="+category+" SN="+req.Sn+" 工位"+string(req.StationNo),
"inspection_record", req.Sn, req.OrderNo)
}
// 完工检(FINAL)结论触发成品回流入库(方案A:完工检合格才入库,完工确认仅代表生产完成):
// 已通过→入库(合格)、部分通过→入库(合格)、不合格/报废→不入库待返修;
// WMS 调用结果以提示透出,不阻断检验留痕(与上方库存联动同降级策略)。
+15 -5
View File
@@ -147,10 +147,12 @@ func materialUpsertOf(m *ent.Material) wmsclient.MaterialUpsert {
}
}
// pushMaterialToWMS 推单行到 WMS(同步调用):成功清 sync_pending,失败置位等待重推(不 panic)。
// pushMaterialToWMS 推单行到 WMS(同步调用):成功清 sync_pending,失败置位并记入事件日志(不再自动重推,改为页面手动推送)。
func (s *Service) pushMaterialToWMS(ctx context.Context, m *ent.Material) error {
if err := s.ctx.Wms.UpsertMaterialToWMS(ctx, materialUpsertOf(m)); err != nil {
_ = s.ctx.EntClient.Material.UpdateOneID(m.ID).SetSyncPending(true).Exec(ctx)
payload := map[string]any{"code": m.Code, "error": err.Error()}
s.ctx.EventLog.Write(ctx, "material.sync.failed", "", "", "material", m.Code, "推送物料到 WMS 失败", payload)
return err
}
_ = s.ctx.EntClient.Material.UpdateOneID(m.ID).SetSyncPending(false).Exec(ctx)
@@ -174,7 +176,7 @@ func (s *Service) RetryPendingMaterialPushes(ctx context.Context) int {
return okCnt
}
// RetryPendingMaterialPushesAsync 异步重推(列表请求顺带触发,不阻塞响应,失败静默)。
// RetryPendingMaterialPushesAsync 异步重推(保留供管理员「重推全部」使用;列表请求不再自动触发)。
func (s *Service) RetryPendingMaterialPushesAsync() {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
@@ -185,6 +187,15 @@ func (s *Service) RetryPendingMaterialPushesAsync() {
}()
}
// RetryProductTypeSync 手动重推单行物料到 WMS(页面「手动推送」按钮触发,替代原列表自动重推)。
func (s *Service) RetryProductTypeSync(ctx context.Context, id int) error {
m, err := s.ctx.EntClient.Material.Get(ctx, id)
if err != nil {
return err
}
return s.pushMaterialToWMS(ctx, m)
}
// PullMaterialsFromWMSAsync 从 WMS 全量分页拉取物料 upsert 到本地(M7 冷启动补齐)。
// 仅在本地为空时调用——若本地已有 pending 行,说明本地存在未推 WMS 的改动,禁止被 WMS 旧值覆盖。
// 失败静默记日志,不阻塞用户。
@@ -219,8 +230,8 @@ func (s *Service) PullMaterialsFromWMSAsync() {
}()
}
// EnsureMaterialCacheAsync 列表请求顺带的缓存维护(M3/M7):本地为空才异步全量拉取;重推 pending 行。
// 均为异步,不阻塞响应。
// EnsureMaterialCacheAsync 列表请求顺带的缓存维护(M7):本地为空才异步全量拉取补齐。
// 不再自动重推 sync_pending 行(改为页面「手动推送」按钮触发),避免静默重试掩盖同步故障。
func (s *Service) EnsureMaterialCacheAsync() {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -230,5 +241,4 @@ func (s *Service) EnsureMaterialCacheAsync() {
s.PullMaterialsFromWMSAsync()
}
}()
s.RetryPendingMaterialPushesAsync()
}
+15 -23
View File
@@ -52,7 +52,7 @@ type FlowVO struct {
// ListFlows 查询工艺流程(可按工位号过滤:只认「工位绑定」页的绑定关系 station.flow_id;
// pp 非空时按引用该工艺的产品工艺名称反查过滤)。page>0 时真分页返回 map{total,list,page,pageSize}(管理页用);page=0 全量数组(工位终端兼容)
func (s *Service) ListFlows(ctx context.Context, stationNo int, pp string, page, pageSize int) (any, error) {
func (s *Service) ListFlows(ctx context.Context, stationNo int, pp, name, status string, stepMin, page, pageSize int) (any, error) {
q := s.ctx.EntClient.ProcessFlow.Query().
Order(ent.Asc(processflow.FieldID))
flows, err := q.All(ctx)
@@ -82,6 +82,14 @@ func (s *Service) ListFlows(ctx context.Context, stationNo int, pp string, page,
continue
}
}
// 名称模糊过滤(大小写无关)
if name != "" && !strings.Contains(strings.ToLower(f.Name), strings.ToLower(name)) {
continue
}
// 状态过滤(ACTIVE/INACTIVE,空=全部)
if status != "" && f.Status != status {
continue
}
vo := &FlowVO{
Id: f.ID, Name: f.Name,
PdfFile: f.PdfFile, Status: f.Status, Remark: f.Remark,
@@ -93,6 +101,10 @@ func (s *Service) ListFlows(ctx context.Context, stationNo int, pp string, page,
if vo.ProductProcesses = ppNames[f.ID]; vo.ProductProcesses == nil {
vo.ProductProcesses = []string{}
}
// 工序数下限过滤(stepMin>0 时只保留工序数≥阈值者)
if stepMin > 0 && len(vo.Steps) < stepMin {
continue
}
// 产品工艺反查过滤(模糊,大小写无关)
if pp != "" && !ppContainsFold(vo.ProductProcesses, pp) {
continue
@@ -331,12 +343,6 @@ func (s *Service) SaveStation(ctx context.Context, req StationReq, operator stri
ve.Add("name", "请填写工位名称", "在「工位名称」输入框填写名称后保存")
}
stype := "LINE"
if req.StationType != nil {
stype = *req.StationType
if stype != "LINE" && stype != "OFFLINE" {
ve.Add("stationType", "工位类型仅支持 线上位(LINE)/线下位(OFFLINE)", "类型改为 LINE(连 PLC)或 OFFLINE(不连 PLC)")
}
}
if req.FlowId != nil && *req.FlowId > 0 {
flow, fErr := s.ctx.EntClient.ProcessFlow.Get(ctx, *req.FlowId)
if fErr != nil {
@@ -368,14 +374,6 @@ func (s *Service) SaveStation(ctx context.Context, req StationReq, operator stri
}
// 更新分支:字段错误 + 规则3守卫(托盘在位/在途指令)全部收集,一次性返回
ve := verr.New()
if req.StationType != nil {
t := *req.StationType
if t != "LINE" && t != "OFFLINE" {
ve.Add("stationType", "工位类型仅支持 线上位(LINE)/线下位(OFFLINE)", "类型改为 LINE(连 PLC)或 OFFLINE(不连 PLC)")
} else if st.IsBuiltin && t != st.StationType {
ve.Add("stationType", "内置工位不允许修改工位类型", "内置工位对应实体产线固定位置(连 PLC、按顺序流转),只能改名称/绑定/终端页签")
}
}
// 仅改名称:flowId 不传(nil)保留原绑定;0=解绑;>0=绑定指定启用流程。
// 规则3(2026-10-20 拍板,2026-10-20 下午改 fail-closed→fail-open):改绑定关系(含解绑)前,
// 过「在途指令/托盘在位」双检(两条同时收集,不串行)。
@@ -420,14 +418,8 @@ if req.FlowId != nil {
if err := ve.OrNil(); err != nil {
return err
}
upd := s.ctx.EntClient.Station.UpdateOneID(st.ID).SetName(req.Name)
if req.StationType != nil {
t := *req.StationType
if !st.IsBuiltin {
upd.SetStationType(t)
}
}
if req.FlowId != nil {
upd := s.ctx.EntClient.Station.UpdateOneID(st.ID).SetName(req.Name)
if req.FlowId != nil {
upd.SetFlowId(bindFlow) // 0=解绑
}
// 终端可见页签:传 nil=不改;传空数组=清空(全部显示);传列表=按配置显示
+19 -1
View File
@@ -70,7 +70,7 @@ type ProductProcessVO struct {
// ListProductProcesses 产品工艺列表(分页;筛选:产品编码/状态/工艺反查/关键字)。
// page>0 真分页返回 map{total,list,page,pageSize};page=0 返回全量数组(工单页下拉用)。
func (s *Service) ListProductProcesses(ctx context.Context, productCode, status string, flowId int, keyword string, page, pageSize int) (any, error) {
func (s *Service) ListProductProcesses(ctx context.Context, productCode, status string, flowId int, keyword, name string, stepMin, stepMax int, page, pageSize int) (any, error) {
q := s.ctx.EntClient.ProductProcess.Query()
if productCode != "" {
q = q.Where(productprocess.ProductCodeContainsFold(productCode))
@@ -86,6 +86,9 @@ func (s *Service) ListProductProcesses(ctx context.Context, productCode, status
)
q = q.Where(kw)
}
if name != "" {
q = q.Where(productprocess.NameContainsFold(name))
}
// 工艺反查:只要包含该工艺的产品工艺
if flowId > 0 {
items, err := s.ctx.EntClient.ProductProcessItem.Query().
@@ -161,6 +164,21 @@ func (s *Service) ListProductProcesses(ctx context.Context, productCode, status
vo.Executable, vo.NotReady = ppExecutable(vo)
out = append(out, vo)
}
// 工序数范围过滤:按产品工艺的工艺顺序/工序条目数(vo.Flows 长度)
if stepMin > 0 || stepMax > 0 {
kept := make([]*ProductProcessVO, 0, len(out))
for _, vo := range out {
n := len(vo.Flows)
if stepMin > 0 && n < stepMin {
continue
}
if stepMax > 0 && n > stepMax {
continue
}
kept = append(kept, vo)
}
out = kept
}
if page > 0 {
total := len(out)
start := (page - 1) * pageSize
+24 -7
View File
@@ -291,21 +291,38 @@ func (s *Service) Seed(ctx context.Context) error {
}
// seedAlertRules 预警规则占位(幂等):按 type 幂等插入,已有行(含人工改过的阈值/启用态)一律不动。
// 常用类型:torque_ng=拧紧扭矩不合格 / inspection_ng=检验不合格 / inventory_low=库存低于阈值 / task_overdue=任务超期。
// 常用类型:inspection_ng=检验不合格 / inventory_low=库存低于阈值 / task_overdue=任务超期。
func seedAlertRules(ctx context.Context, s *Service) {
placeholders := []struct{ typ, name string }{
{"torque_ng", "拧紧扭矩不合格预警"},
{"inspection_ng", "检验不合格预警"},
{"inventory_low", "库存低于阈值预警"},
{"task_overdue", "任务超期预警"},
// 存量 torque_ng 规则保留历史但置为禁用:拧紧报警已改由基础配置 torque.ng.alert.enabled 开关控制(B2.2),
// 不再走预警规则表;不删除,便于追溯。
if _, err := s.ctx.EntClient.AlertRule.Update().
Where(alertrule.Type("torque_ng")).SetEnabled(false).Save(ctx); err != nil {
_ = err // 表为空时影响 0 行属正常,非致命
}
// inspection_ng 默认启用(事件触发型,出现检验不合格即报警,阈值不使用);
// inventory_low / task_overdue 默认停用(占位,由实施按需启用)。
placeholders := []struct {
typ string
name string
enabled bool
}{
{"inspection_ng", "检验不合格预警", true},
{"inventory_low", "库存低于阈值预警", false},
{"task_overdue", "任务超期预警", false},
}
for _, p := range placeholders {
// B2.3 幂等对齐:占位规则以 seed 定义的启用态为准(inspection_ng 强制启用,inventory_low/task_overdue 默认停用)。
// 既有行一并校正——避免"已存在却被历史 seed 置为禁用"导致检验不合格预警不触发(这正是 B2.3 要修的 bug)。
if ok, _ := s.ctx.EntClient.AlertRule.Query().Where(alertrule.Type(p.typ)).Exist(ctx); ok {
if _, e := s.ctx.EntClient.AlertRule.Update().
Where(alertrule.Type(p.typ)).SetEnabled(p.enabled).Save(ctx); e != nil {
_ = e
}
continue
}
if _, err := s.ctx.EntClient.AlertRule.Create().
SetName(p.name).SetType(p.typ).SetThreshold(0).
SetEnabled(false).SetCreatedBy("seed").Save(ctx); err != nil {
SetEnabled(p.enabled).SetCreatedBy("seed").Save(ctx); err != nil {
continue // 单条失败不阻断其余占位
}
}
+2 -2
View File
@@ -102,6 +102,6 @@ func (s *Service) CountSemiIn(ctx context.Context, sn string) int {
}
// ListEventLogs 操作日志查询(按工单号/操作人;operators 为候选列表,任一命中即算)
func (s *Service) ListEventLogs(ctx context.Context, orderNo string, operators []string, eventType string, fromMs, toMs int64, page, pageSize int) ([]*ent.EventLog, int, error) {
return s.ctx.EventLog.Query(ctx, eventType, orderNo, operators, fromMs, toMs, page, pageSize)
func (s *Service) ListEventLogs(ctx context.Context, orderNo string, operators []string, eventType, entityType string, fromMs, toMs int64, page, pageSize int) ([]*ent.EventLog, int, error) {
return s.ctx.EventLog.Query(ctx, eventType, orderNo, operators, entityType, fromMs, toMs, page, pageSize)
}
+22
View File
@@ -31,6 +31,10 @@ const (
CfgPipelineCache = "pipeline_cache"
// CfgAllowCrossDay 允许叫非今日排产的料(B5 跨日:1=允许(默认,工位端预警提示),0=禁止)
CfgAllowCrossDay = "call.allow_cross_day"
// CfgTorqueNgAlert 拧紧不合格报警开关(B2.1):1=开启(默认,拧紧扭矩不合格立即落预警),0=关闭(只写 step_data + 置待处置标记,不落预警)
CfgTorqueNgAlert = "torque.ng.alert.enabled"
// CfgDashboardRefreshSeconds 看板大屏轮询兜底刷新间隔(秒,1~10):仅影响 SSE 实时通道不可用时的 HTTP 轮询周期(默认 5)
CfgDashboardRefreshSeconds = "dashboard.refresh.seconds"
)
// startedAt 服务启动时刻(本机信息展示用)
@@ -46,6 +50,8 @@ type SettingsVO struct {
LogRetentionDays int `json:"logRetentionDays"` // 事件日志保留天数(0=不清理)
PipelineCache int `json:"pipelineCache"` // 滚筒线缓存模式(1=缓存并行,0=串行;预留,PLC 真机接入时生效)
AllowCrossDay int `json:"allowCrossDay"` // 允许叫非今日排产的料(1=允许(默认),0=禁止)
TorqueNgAlert bool `json:"torqueNgAlert"` // 拧紧不合格报警开关(1=开启,0=关闭)
DashboardRefreshSeconds int `json:"dashboardRefreshSeconds"` // 看板轮询兜底刷新间隔(秒,1~10)
// 本机基础信息(只读)
LocalIPs []string `json:"localIPs"` // 本机内网 IPv4 列表
@@ -65,6 +71,8 @@ type SettingsReq struct {
LogRetentionDays *int `json:"logRetentionDays"`
PipelineCache *int `json:"pipelineCache"`
AllowCrossDay *int `json:"allowCrossDay"`
TorqueNgAlert *bool `json:"torqueNgAlert"` // B2.1 拧紧不合格报警开关(nil=不改)
DashboardRefreshSeconds *int `json:"dashboardRefreshSeconds"` // 看板轮询兜底刷新间隔(秒,nil=不改)
}
// defaults 建议默认值(未配置时生效)
@@ -75,6 +83,8 @@ var settingsDefaults = map[string]int{
CfgLogRetention: 0,
CfgPipelineCache: 0,
CfgAllowCrossDay: 1,
CfgTorqueNgAlert: 1, // B2.1 默认开启拧紧不合格报警
CfgDashboardRefreshSeconds: 5, // 看板轮询兜底刷新间隔(秒)
}
// GetSettings 读取基础设置 + 本机信息。DB 读失败时按默认值返回(设置页必须能打开)。
@@ -93,6 +103,8 @@ func (s *Service) GetSettings(ctx context.Context) (*SettingsVO, error) {
LogRetentionDays: cfgIntFrom(kv, CfgLogRetention),
PipelineCache: cfgIntFrom(kv, CfgPipelineCache),
AllowCrossDay: cfgIntFrom(kv, CfgAllowCrossDay),
TorqueNgAlert: s.CfgInt(ctx, CfgTorqueNgAlert, 1) == 1, // B2.1 默认开启
DashboardRefreshSeconds: cfgIntFrom(kv, CfgDashboardRefreshSeconds),
LocalIPs: localIPv4s(),
ListenAddr: fmt.Sprintf("%s:%d", s.ctx.Config.Host, s.ctx.Config.Port),
DBInfo: fmt.Sprintf("%s:%d/%s", s.ctx.Config.Database.Host, s.ctx.Config.Database.Port, s.ctx.Config.Database.Dbname),
@@ -126,6 +138,7 @@ func (s *Service) SaveSettings(ctx context.Context, req SettingsReq, operator st
{CfgLogRetention, req.LogRetentionDays, 0, 3650, "事件日志保留天数(0=不清理)"},
{CfgPipelineCache, req.PipelineCache, 0, 1, "滚筒线缓存模式(1=启用缓存位并行流转,0=串行不缓存);预留配置,PLC 真机接入时生效"},
{CfgAllowCrossDay, req.AllowCrossDay, 0, 1, "允许叫非今日排产的料(1=允许,工位端预警提示;0=禁止)"},
{CfgDashboardRefreshSeconds, req.DashboardRefreshSeconds, 1, 10, "看板轮询兜底刷新间隔(秒,1~10,仅 SSE 不可用时的 HTTP 轮询周期)"},
}
for _, it := range items {
if it.val == nil {
@@ -138,6 +151,15 @@ func (s *Service) SaveSettings(ctx context.Context, req SettingsReq, operator st
return err
}
}
if req.TorqueNgAlert != nil {
v := 0
if *req.TorqueNgAlert {
v = 1
}
if err := s.upsertConfig(ctx, CfgTorqueNgAlert, strconv.Itoa(v), "拧紧不合格报警开关(1=开启,0=关闭)"); err != nil {
return err
}
}
if req.WmsBaseURL != nil {
u := strings.TrimSpace(*req.WmsBaseURL)
if err := s.upsertConfig(ctx, CfgWmsBaseURL, u, "WMS 服务地址(保存即生效)"); err != nil {
+13 -1
View File
@@ -102,7 +102,19 @@ func (s *Service) evaluateTorqueCriterion(ctx context.Context, sn, stationNo str
SetTorqueNgPending(true).SetTorqueNgAt(time.Now()).SetTorqueNgBy(operator).Save(ctx); e != nil {
log.Printf("[torque] 置拧紧不合格标记失败 sn=%s: %v", sn, e)
}
s.Evaluate(ctx, "torque_ng", 1, "拧紧扭矩不合格", "SN="+sn+" 工位"+stationNo, "torque_record", sn, orderNo)
// B2.1 拧紧报警改由基础配置 torque.ng.alert.enabled 开关控制(不再走预警规则表):
// 开关开启(默认) → 直接 CreateAlert 落预警(绕过 Evaluate 的阈值比较);
// 开关关闭 → 只写 step_data + 置 torque_ng_pending(已在上面完成),不落 alert。
if s.CfgInt(ctx, CfgTorqueNgAlert, 1) == 1 {
// 直写预警(绕过 Evaluate 阈值比较);target 含「工位N」供终端按工位过滤,message 带工单号便于中心检索
msg := "拧紧扭矩不合格:SN=" + sn + " 工位" + stationNo
if orderNo != "" {
msg += " 工单" + orderNo
}
if err := s.CreateAlert(ctx, "torque_ng", "critical", "SN="+sn+" 工位"+stationNo, msg); err != nil {
log.Printf("[torque] 写拧紧不合格预警失败 sn=%s: %v", sn, err)
}
}
}
}