package logic import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "sort" "strconv" "strings" "time" "bj_power_mes/ent" "bj_power_mes/ent/processstep" "bj_power_mes/ent/stepcriterion" "bj_power_mes/ent/stepsignrecord" ) // ============ 签字循环(2026-11-30 重构定稿)============ // 旧模型:操作工签字随报工落库,检验员只校验「历史步骤」(seq0 时限定工序。 // 轮次在「报检」时整工序统一 +1,呼叫与检验共用同一轮次号。 func newestRound(ctx context.Context, client *ent.Client, sn, stationNo string, flowId int) (int, error) { q := client.StepSignRecord.Query(). Where(stepsignrecord.Sn(sn), stepsignrecord.StationNo(stationNo), stepsignrecord.Revoked(false)) if flowId > 0 { q = q.Where(stepsignrecord.FlowId(flowId)) } recs, err := q.All(ctx) if err != nil { return 0, err } max := 0 for _, r := range recs { if r.Round > max { max = r.Round } } return max, nil } // maxRoundEver 取该 SN 历史上出现过的最大轮次(**包含已撤销记录**,跨工序)。 // 报检必须用这个函数、不能用 newestRound:撤旧轮后未撤销记录清空,newestRound 会回退到 0, // 新一轮又从 1 起,撞 (sn,station_no,step_id,sign_role,round) 唯一键。 func maxRoundEver(ctx context.Context, client *ent.Client, sn string) (int, error) { recs, err := client.StepSignRecord.Query(). Where(stepsignrecord.Sn(sn)).All(ctx) if err != nil { return 0, err } max := 0 for _, r := range recs { if r.Round > max { max = r.Round } } return max, nil } // needSignSteps 查工序下所有需检验员签字的步骤。 // 操作工签字概念已删除;工人自检(needCheck)走独立闸门,不在此列。 func needSignSteps(ctx context.Context, client *ent.Client, flowId int) ([]*ent.ProcessStep, error) { return client.ProcessStep.Query(). Where(processstep.FlowId(flowId), processstep.NeedInspectorSign(true)).All(ctx) } // processStepsByIDs 批量取步骤(替代逐条 Get,避免 N+1)。 func processStepsByIDs(ctx context.Context, client *ent.Client, ids []int) (map[int]*ent.ProcessStep, error) { out := map[int]*ent.ProcessStep{} if len(ids) == 0 { return out, nil } rows, err := client.ProcessStep.Query().Where(processstep.IDIn(ids...)).All(ctx) if err != nil { return nil, err } for _, ps := range rows { out[ps.ID] = ps } return out, nil } // revokeScope 作废指定范围未撤销的签字(整轮作废/撤回/改数据),历史记录保留不物理删。 func revokeScope(ctx context.Context, client *ent.Client, sn, stationNo string, flowId int, by, reason string) error { _, err := client.StepSignRecord.Update(). Where(stepsignrecord.Sn(sn), stepsignrecord.StationNo(stationNo), stepsignrecord.Revoked(false), stepsignrecord.FlowId(flowId)). SetRevoked(true).SetRevokedBy(by).SetRevokedAt(time.Now()).SetRevokeReason(reason).Save(ctx) return err } // revokeAllSnSigns 作废该 SN 全部未撤销签字(报废/暂存退库等离场场景,留痕不物理删)。 // 重上线不复用旧轮:maxRoundEver 统计含已撤销记录,新一轮 round 单调+1。 func revokeAllSnSigns(ctx context.Context, client *ent.Client, sn, by, reason string) error { if sn == "" { return nil } _, err := client.StepSignRecord.Update(). Where(stepsignrecord.Sn(sn), stepsignrecord.Revoked(false)). SetRevoked(true).SetRevokedBy(by).SetRevokedAt(time.Now()).SetRevokeReason(reason).Save(ctx) return err } // CallSign 报检:本工序所有需检验步骤落 CALL 呼叫记录(步骤快照 + 内容指纹),暴露给巡检端待签任务。 // 一轮=一次呼叫:先算历史最大轮次(含已撤销),再在**同一事务**里「撤旧轮 + 逐步骤写新轮」。 // 事务保证不出现「旧轮撤了、新轮写一半」——任一步失败整体回滚。 func (s *Service) CallSign(ctx context.Context, req CallSignReq, operator string) (*CallSignResult, error) { req.Sn = strings.TrimSpace(req.Sn) req.StationNo = strings.TrimSpace(req.StationNo) if req.Sn == "" || req.StationNo == "" || req.FlowId <= 0 { return nil, errors.New("报检参数不完整:缺少 SN / 工位 / 工序") } if operator == "" { operator = strings.TrimSpace(req.Operator) } if operator == "" { return nil, errors.New("未获取到操作工身份,请重新登录后再报检") } client := s.ctx.EntClient steps, err := needSignSteps(ctx, client, req.FlowId) if err != nil { return nil, err } if len(steps) == 0 { return &CallSignResult{State: "READY", NeedSign: false, Message: "本工序无需检验签字,可直接报工"}, nil } // 轮次取历史最大(含已撤销),保证 NG/撤回后重新呼叫轮次单调不回退。 maxRound, err := maxRoundEver(ctx, client, req.Sn) if err != nil { return nil, err } round := maxRound + 1 // 撤旧 + 写新放同一事务:任一步失败整体回滚。 tx, terr := client.Tx(ctx) if terr != nil { return nil, terr } committed := false defer func() { if !committed { _ = tx.Rollback() } }() if _, err := tx.StepSignRecord.Update(). Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo), stepsignrecord.FlowId(req.FlowId), stepsignrecord.Revoked(false)). SetRevoked(true).SetRevokedBy(operator).SetRevokedAt(time.Now()). SetRevokeReason("重新报检,上一轮作废").Save(ctx); err != nil { return nil, err } fingerprint := calcContentFingerprint(req.Steps, req.Binds) // 步骤载荷按 stepId 建索引,落快照用 snapshot := map[int]StepDataReq{} for _, sd := range req.Steps { snapshot[sd.StepId] = sd } for _, ps := range steps { sv, stxt, checked, pid := "", "", false, int64(0) if sd, ok := snapshot[ps.ID]; ok { sv = strconv.FormatFloat(sd.Value, 'f', -1, 64) stxt = sd.Text checked = sd.Checked pid = int64(sd.ProcessId) } _, err = tx.StepSignRecord.Create(). SetSn(req.Sn).SetOrderNo(req.OrderNo).SetFlowId(req.FlowId). SetStationNo(req.StationNo).SetStepId(ps.ID).SetStepName(ps.Name). SetSignRole("CALL").SetResult("OK").SetSignedBy(operator). SetRound(round).SetSource("call").SetFingerprint(fingerprint). SetStepValue(sv).SetStepText(stxt).SetStepChecked(checked).SetProcessId(pid).Save(ctx) if err != nil { if isUniqueSignViolation(err) { return nil, errors.New("重复报检,请稍后重试") } return nil, err } } committed = true if err := tx.Commit(); err != nil { return nil, err } // 新呼叫落库即广播 station.sign,巡检端 SSE 订阅收到后即时刷新待签列表。 s.notifyStationSign(req.StationNo, req.Sn) return &CallSignResult{Round: round, State: "SIGNING", NeedSign: true, Message: "已报检,请等待检验员确认;检验合格后再报工"}, nil } // RevokeSign 撤回呼叫:本工序本轮全部签字作废,回到作业中,可整改后重新报检。 func (s *Service) RevokeSign(ctx context.Context, req RevokeSignReq, operator string) error { req.Sn = strings.TrimSpace(req.Sn) req.StationNo = strings.TrimSpace(req.StationNo) if req.Sn == "" || req.StationNo == "" || req.FlowId <= 0 { return errors.New("撤回参数不完整:缺少 SN / 工位 / 工序") } if operator == "" { operator = strings.TrimSpace(req.Operator) } if operator == "" { operator = "操作工" } st, err := s.SignStatus(ctx, SignStatusReq{Sn: req.Sn, OrderNo: req.OrderNo, FlowId: req.FlowId, StationNo: req.StationNo}) if err != nil { return err } if st.State != "SIGNING" && st.State != "RECTIFY" { return errors.New("当前状态为「" + st.State + "」,只有报检中或待整改时才能撤回") } return revokeScope(ctx, s.ctx.EntClient, req.Sn, req.StationNo, req.FlowId, operator, "操作工撤回报检") } // SignStatus 三档签字状态:从签字记录推导,终端进页面/报工前拉取覆盖本地缓存。 func (s *Service) SignStatus(ctx context.Context, req SignStatusReq) (*SignStatusVO, error) { req.Sn = strings.TrimSpace(req.Sn) req.StationNo = strings.TrimSpace(req.StationNo) if req.Sn == "" || req.StationNo == "" || req.FlowId <= 0 { return nil, errors.New("签字状态查询参数不完整") } client := s.ctx.EntClient steps, err := needSignSteps(ctx, client, req.FlowId) if err != nil { return nil, err } vo := &SignStatusVO{State: "WORKING", Message: "作业中,完成后请点「报检」", Steps: make([]StepSignState, 0, len(steps))} if len(steps) == 0 { vo.NeedSign = false vo.State = "READY" vo.Message = "本工序无需检验签字,可直接报工" return vo, nil } vo.NeedSign = true round, err := newestRound(ctx, client, req.Sn, req.StationNo, req.FlowId) if err != nil { return nil, err } vo.Round = round vo.CanRevoke = round > 0 if round == 0 { for _, ps := range steps { vo.Steps = append(vo.Steps, StepSignState{StepId: ps.ID, StepName: ps.Name, NeedInspectorSign: ps.NeedInspectorSign}) } return vo, nil } recs, err := client.StepSignRecord.Query(). Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo), stepsignrecord.FlowId(req.FlowId), stepsignrecord.Revoked(false), stepsignrecord.Round(round)).All(ctx) if err != nil { return nil, err } type inspInfo struct{ result, signer, remark, signedAt string } inspByStep := map[int]inspInfo{} for _, r := range recs { if r.SignRole == "INSPECTOR" { inspByStep[r.StepId] = inspInfo{r.Result, r.SignedBy, r.Remark, r.SignedAt.Format("2006-01-02 15:04:05")} } } hasNG, allOK := false, true for _, ps := range steps { st := StepSignState{StepId: ps.ID, StepName: ps.Name, NeedInspectorSign: ps.NeedInspectorSign} if iv, ok := inspByStep[ps.ID]; ok { st.InspectorResult, st.InspectorSigner, st.InspectorRemark, st.InspectorSignedAt = iv.result, iv.signer, iv.remark, iv.signedAt } if st.InspectorResult == "NG" { hasNG, allOK = true, false } else if st.InspectorResult != "OK" { allOK = false } vo.Steps = append(vo.Steps, st) } switch { case hasNG: vo.State, vo.Message = "RECTIFY", "检验不合格,请按检验意见整改后重新报检" case allOK: vo.State, vo.Message = "READY", "检验签字已齐全,可以报工" vo.CanRevoke = false default: vo.State, vo.Message = "SIGNING", "检验员签字中,请等待确认后再报工" } return vo, nil } // InspectorSign 检验员签 OK/NG:签在本轮 CALL 轮次。 // 前置:步骤需检验员签字,且本轮有 CALL 呼叫;禁止签字人等于该轮呼叫人/操作人(自查禁止)。 func (s *Service) InspectorSign(ctx context.Context, req InspectorSignReq, operator string) error { req.Sn = strings.TrimSpace(req.Sn) req.StationNo = strings.TrimSpace(req.StationNo) req.OrderNo = strings.TrimSpace(req.OrderNo) if req.Sn == "" || req.StationNo == "" || req.StepId <= 0 { return errors.New("签字参数不完整:缺少 SN / 工位号 / 步骤") } operator = strings.TrimSpace(operator) if operator == "" { return errors.New("未获取到检验员身份,请重新登录") } client := s.ctx.EntClient ps, err := client.ProcessStep.Get(ctx, req.StepId) if err != nil { return errors.New("工艺步骤不存在:" + itoa(req.StepId)) } if !ps.NeedInspectorSign { return errors.New("该步骤未配置「需检验员签字」,无需签字确认") } // 本轮 = 该步骤最新未撤销 CALL 呼叫的轮次 callRec, e := client.StepSignRecord.Query(). Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo), stepsignrecord.StepId(req.StepId), stepsignrecord.SignRole("CALL"), stepsignrecord.Revoked(false), stepsignrecord.SignedByNEQ("")). Order(ent.Desc(stepsignrecord.FieldRound), ent.Desc(stepsignrecord.FieldID)).First(ctx) if e != nil || callRec == nil { return errors.New("工人尚未报检,检验员不能先签") } if strings.TrimSpace(callRec.SignedBy) != "" && strings.EqualFold(strings.TrimSpace(callRec.SignedBy), operator) { return errors.New("禁止自签:本轮报检人就是当前登录人,请换检验员确认") } round := callRec.Round exists, e := client.StepSignRecord.Query(). Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo), stepsignrecord.StepId(req.StepId), stepsignrecord.SignRole("INSPECTOR"), stepsignrecord.Round(round), stepsignrecord.Revoked(false)).Exist(ctx) if e != nil { return e } if exists { return errors.New("本轮已签字,如需更改结论请先撤回报检后重新签字") } result := strings.ToUpper(strings.TrimSpace(req.Result)) if result != "OK" && result != "NG" { return errors.New("请选择合格或不合格") } _, err = client.StepSignRecord.Create(). SetSn(req.Sn).SetOrderNo(req.OrderNo).SetFlowId(ps.FlowId). SetStationNo(req.StationNo).SetStepId(req.StepId).SetStepName(ps.Name). SetSignRole("INSPECTOR").SetResult(result). SetSignedBy(operator).SetRound(round). SetSource("inspect").SetRemark(req.Remark). SetStepValue(callRec.StepValue).SetStepText(callRec.StepText). SetStepChecked(callRec.StepChecked).SetProcessId(callRec.ProcessId). SetFingerprint(callRec.Fingerprint).Save(ctx) if err != nil && isUniqueSignViolation(err) { return errors.New("该步骤本轮已签字,请勿重复提交") } if err == nil { s.notifyStationSign(req.StationNo, req.Sn) // 合格/不合格都即时通知工位终端 } return err } // notifyStationSign 检验员签字 OK/NG 落库后,经 SSE 广播 station.sign 通知工位终端即时拉签字状态。 func (s *Service) notifyStationSign(stationNo, sn string) { if s.ctx == nil || s.ctx.SSE == nil || stationNo == "" { return } n, _ := strconv.Atoi(stationNo) if n <= 0 { return } if b, err := json.Marshal(map[string]any{"stationNo": n, "sn": sn}); err == nil { s.ctx.SSE.Publish("station.sign", string(b)) } } // isUniqueSignViolation 判定是否为签字唯一索引冲突(并发签字竞态) func isUniqueSignViolation(err error) bool { if err == nil { return false } msg := strings.ToLower(err.Error()) return strings.Contains(msg, "duplicate key") || strings.Contains(msg, "violates unique constraint") || strings.Contains(msg, "step_sign_record") } // PendingSignFilter 待检验员签字查询过滤。 type PendingSignFilter struct { Sn string `json:"sn"` OrderNo string `json:"orderNo"` StationNo string `json:"stationNo"` Page int `json:"page"` PageSize int `json:"pageSize"` } // PendingSigns 聚合「工人已报检、待检验员签字确认」的工艺步骤(巡检终端「待签任务」数据源)。 // 基数=CALL 未撤销呼叫;只保留 needInspectorSign=true 的步骤;剔除同 (sn,stationNo,stepId,round) 已有检验员签字的。 // 超时预警已从本查询接口移除,改由定时扫描 ScanSignTimeout 每分钟落。 func (s *Service) PendingSigns(ctx context.Context, f PendingSignFilter) ([]StepSignVO, int, error) { client := s.ctx.EntClient q := client.StepSignRecord.Query(). Where(stepsignrecord.SignRole("CALL"), stepsignrecord.Revoked(false), stepsignrecord.SignedByNEQ("")) if f.Sn != "" { q = q.Where(stepsignrecord.Sn(f.Sn)) } if f.OrderNo != "" { q = q.Where(stepsignrecord.OrderNo(f.OrderNo)) } if f.StationNo != "" { q = q.Where(stepsignrecord.StationNo(f.StationNo)) } calls, err := q.Order(ent.Desc(stepsignrecord.FieldID)).All(ctx) if err != nil { return nil, 0, err } type signKey struct { sn, stationNo string stepId, round int } inspectorDone := map[signKey]*ent.StepSignRecord{} insp, e := client.StepSignRecord.Query(). Where(stepsignrecord.SignRole("INSPECTOR"), stepsignrecord.Revoked(false), stepsignrecord.SignedByNEQ("")).All(ctx) if e != nil { return nil, 0, e } for _, r := range insp { inspectorDone[signKey{r.Sn, r.StationNo, r.StepId, r.Round}] = r } // 批量取步骤配置(N+1 → 一次 IDIn) ids := make([]int, 0, len(calls)) for _, r := range calls { ids = append(ids, r.StepId) } stepMap, err := processStepsByIDs(ctx, client, ids) if err != nil { return nil, 0, err } // 批量取考核标准(按 stepId) critMap, err := stepCriterionByStepIDs(ctx, client, ids) if err != nil { return nil, 0, err } list := make([]StepSignVO, 0, len(calls)) for _, r := range calls { k := signKey{r.Sn, r.StationNo, r.StepId, r.Round} if _, ok := inspectorDone[k]; ok { continue } ps, ok := stepMap[r.StepId] if !ok || !ps.NeedInspectorSign { continue } signedAt := r.SignedAt.Format("2006-01-02 15:04:05") vo := StepSignVO{ ID: r.ID, Sn: r.Sn, OrderNo: r.OrderNo, FlowId: r.FlowId, StationNo: r.StationNo, StepId: r.StepId, StepName: r.StepName, SignRole: r.SignRole, Result: r.Result, SignedBy: r.SignedBy, SignedAt: signedAt, Round: r.Round, Source: r.Source, StepValue: r.StepValue, StepText: r.StepText, StepChecked: r.StepChecked, ProcessId: r.ProcessId, HasInspectorSign: false, } if c, ok2 := critMap[r.StepId]; ok2 { vo.CriterionName = c.Name vo.CriterionLogic = c.Logic vo.CriterionDetail = criterionText(c) } list = append(list, vo) } total := len(list) ps := f.PageSize if ps <= 0 { ps = 50 } pg := f.Page if pg <= 0 { pg = 1 } start := (pg - 1) * ps if start >= total { return []StepSignVO{}, total, nil } end := start + ps if end > total { end = total } return list[start:end], total, nil } // stepCriterionByStepIDs 批量取步骤考核标准(不存在返回空 map)。 func stepCriterionByStepIDs(ctx context.Context, client *ent.Client, stepIDs []int) (map[int]*ent.StepCriterion, error) { out := map[int]*ent.StepCriterion{} if len(stepIDs) == 0 { return out, nil } rows, err := client.StepCriterion.Query().Where(stepcriterion.StepIdIn(stepIDs...)).All(ctx) if err != nil { return nil, err } for _, c := range rows { if _, ok := out[c.StepId]; !ok { out[c.StepId] = c } } return out, nil } // criterionText 考核标准可读文本(供待签弹窗展示) func criterionText(c *ent.StepCriterion) string { if c == nil { return "" } name := c.Name if name == "" { name = "指标" } switch c.Logic { case "GE": return fmt.Sprintf("%s ≥ %s", name, strconv.FormatFloat(c.Target, 'f', -1, 64)) case "LE": return fmt.Sprintf("%s ≤ %s", name, strconv.FormatFloat(c.Target, 'f', -1, 64)) case "GT": return fmt.Sprintf("%s > %s", name, strconv.FormatFloat(c.Target, 'f', -1, 64)) case "LT": return fmt.Sprintf("%s < %s", name, strconv.FormatFloat(c.Target, 'f', -1, 64)) case "RANGE": lo, hi := "", "" if c.Min != nil { lo = strconv.FormatFloat(*c.Min, 'f', -1, 64) } if c.Max != nil { hi = strconv.FormatFloat(*c.Max, 'f', -1, 64) } return fmt.Sprintf("%s ∈ [%s,%s]", name, lo, hi) case "EQUAL": return fmt.Sprintf("%s = %s", name, strconv.FormatFloat(c.Target, 'f', -1, 64)) default: return name } } // PendingSignCount 待签角标轻量计数(不加载 VO、不做步骤/考核标准批量回查)。 // 口径与 PendingSigns 一致:CALL 未撤销 + 步骤需检验员签字 + 该轮尚无 INSPECTOR 签字。 // 走 SQL COUNT + NOT EXISTS,避免菜单角标每次拉全量待签列表。 func (s *Service) PendingSignCount(ctx context.Context) (int, error) { sqlDB := s.ctx.SQLDB if sqlDB == nil { return 0, nil } const q = `SELECT COUNT(*) FROM step_sign_record c WHERE c.sign_role = 'CALL' AND c.revoked = false AND COALESCE(c.signed_by,'') <> '' AND EXISTS (SELECT 1 FROM process_step ps WHERE ps.id = c.step_id AND ps.need_inspector_sign = true) AND NOT EXISTS ( SELECT 1 FROM step_sign_record i WHERE i.sign_role = 'INSPECTOR' AND i.revoked = false AND i.sn = c.sn AND i.station_no = c.station_no AND i.step_id = c.step_id AND i.round = c.round )` var n int if err := sqlDB.QueryRowContext(ctx, q).Scan(&n); err != nil { return 0, err } return n, nil } // SignRejectedFilter 已判不合格查询过滤(P2-3:检验员回看自己刚判过的 NG 项,只读)。 type SignRejectedFilter struct { Days int `json:"days"` // 最近 N 天,默认 7 } // SignRejected 近 N 天检验员判 NG 的签字记录(P2-3):NG 后该轮从待签列表消失(避免重复签), // 但检验员需要看到自己刚判过的项及其理由。只读、不建表、不分页大改(上限 200 条)。 func (s *Service) SignRejected(ctx context.Context, f SignRejectedFilter) ([]StepSignVO, error) { days := f.Days if days <= 0 { days = 7 } if days > 90 { days = 90 } since := time.Now().AddDate(0, 0, -days) recs, err := s.ctx.EntClient.StepSignRecord.Query(). Where(stepsignrecord.SignRole("INSPECTOR"), stepsignrecord.Result("NG"), stepsignrecord.SignedByNEQ(""), stepsignrecord.SignedAtGTE(since)). Order(ent.Desc(stepsignrecord.FieldID)).Limit(200).All(ctx) if err != nil { return nil, err } list := make([]StepSignVO, 0, len(recs)) for _, r := range recs { rehandled := false if newer, e := s.ctx.EntClient.StepSignRecord.Query(). Where(stepsignrecord.Sn(r.Sn), stepsignrecord.StationNo(r.StationNo), stepsignrecord.StepId(r.StepId), stepsignrecord.SignRole("CALL"), stepsignrecord.Revoked(false), stepsignrecord.RoundGT(r.Round)).Exist(ctx); e == nil { rehandled = newer } list = append(list, StepSignVO{ ID: r.ID, Sn: r.Sn, OrderNo: r.OrderNo, FlowId: r.FlowId, StationNo: r.StationNo, StepId: r.StepId, StepName: r.StepName, SignRole: r.SignRole, Result: r.Result, SignedBy: r.SignedBy, SignedAt: r.SignedAt.Format("2006-01-02 15:04:05"), Round: r.Round, Source: r.Source, Revoked: r.Revoked, Remark: r.Remark, Rehandled: rehandled, StepValue: r.StepValue, StepText: r.StepText, StepChecked: r.StepChecked, ProcessId: r.ProcessId, }) } return list, nil }