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/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 查工序下所有需签步骤(need_operator_sign OR need_inspector_sign)。 func needSignSteps(ctx context.Context, client *ent.Client, flowId int) ([]*ent.ProcessStep, error) { return client.ProcessStep.Query(). Where(processstep.FlowId(flowId), processstep.Or(processstep.NeedOperatorSign(true), processstep.NeedInspectorSign(true))).All(ctx) } // 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 } // CallSign 呼叫签字:本工序所有需签步骤落操作工签字(本轮)+ 内容指纹,暴露给巡检端待签任务。 // 一轮=一次呼叫:先算历史最大轮次(含已撤销),再在**同一事务**里「撤旧轮 + 逐步骤写新轮」。 // 事务保证不出现「旧轮撤了、新轮写一半」——任一步失败整体回滚。 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() } }() // 事务内直接 Update(revokeScope 收 *ent.Client,这里用 tx 的同构 builder 写同一语义), // 保证撤旧与写新原子;历史记录保留不物理删。 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) for _, ps := range steps { _, err = tx.StepSignRecord.Create(). SetSn(req.Sn).SetOrderNo(req.OrderNo).SetFlowId(req.FlowId). SetStationNo(req.StationNo).SetStepId(ps.ID).SetStepName(ps.Name). SetSignRole("OPERATOR").SetResult("OK").SetSignedBy(operator). SetRound(round).SetSource("call").SetFingerprint(fingerprint).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 } 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 = "操作工" } // P1-3 后端闸门:只有「签字中/待整改」允许撤回;签字齐全(READY)后拒绝, // 防止直接调接口绕过前端 canRevoke 隐藏、一键作废检验员合格结论。 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 // P1-3:撤回只在「签字中/待整改」出现;签字齐全(READY)后不允许一键作废检验员结论。 // 状态还没算出来,这里先按 round>0 置位,下面 switch 定完状态后再按状态纠偏。 vo.CanRevoke = round > 0 if round == 0 { for _, ps := range steps { vo.Steps = append(vo.Steps, StepSignState{StepId: ps.ID, StepName: ps.Name, NeedOperatorSign: ps.NeedOperatorSign, 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 } opByStep := map[int]string{} inspByStep := map[int]struct{ result, signer string }{} for _, r := range recs { switch r.SignRole { case "OPERATOR": opByStep[r.StepId] = r.SignedBy case "INSPECTOR": inspByStep[r.StepId] = struct{ result, signer string }{r.Result, r.SignedBy} } } hasNG, allOK := false, true for _, ps := range steps { st := StepSignState{StepId: ps.ID, StepName: ps.Name, NeedOperatorSign: ps.NeedOperatorSign, NeedInspectorSign: ps.NeedInspectorSign, OperatorSigned: opByStep[ps.ID] != ""} if iv, ok := inspByStep[ps.ID]; ok { st.InspectorResult, st.InspectorSigner = iv.result, iv.signer } if ps.NeedOperatorSign && !st.OperatorSigned { allOK = false } if ps.NeedInspectorSign { if st.InspectorResult == "NG" { hasNG, allOK = true, false // 实测修正:NG 必须置 hasNG=true 才能推导 RECTIFY(待整改) } 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 // 签字已齐全,撤回入口关闭(P1-3) default: vo.State, vo.Message = "SIGNING", "检验员签字中,请等待确认后再报工" } return vo, nil } // InspectorSign 检验员签 OK/NG:签在本轮(操作工已呼叫的最新未撤销轮次)。 // 前置:步骤需检验员签字,且本轮有操作工签字;同一轮重复签拒绝,避免并发覆盖结论。 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 / 工位号 / 步骤") } 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("该步骤未配置「需检验员签字」,无需签字确认") } // 本轮 = 该步骤最新未撤销 OPERATOR 签字的轮次(呼叫签字时落) opRec, e := client.StepSignRecord.Query(). Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo), stepsignrecord.StepId(req.StepId), stepsignrecord.SignRole("OPERATOR"), stepsignrecord.Revoked(false), stepsignrecord.SignedByNEQ("")). Order(ent.Desc(stepsignrecord.FieldRound), ent.Desc(stepsignrecord.FieldID)).First(ctx) if e != nil || opRec == nil { return errors.New("操作工尚未呼叫签字,检验员不能先签") } round := opRec.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).Save(ctx) if err != nil && isUniqueSignViolation(err) { return errors.New("该步骤本轮已签字,请勿重复提交") } if err == nil { s.notifyStationSign(req.StationNo, req.Sn) // P0-2:合格/不合格都即时通知工位终端 } return err } // notifyStationSign 检验员签字 OK/NG 落库后,经 SSE 广播 station.sign 通知工位终端即时拉签字状态。 // 载荷只带工位号+SN(终端按工位过滤、收到后拉 GET /api/sign/status 取权威状态),不塞整份状态。 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 // 虚拟/线下工位无终端 SSE 订阅 } // 2026-11-30:工位号必须发数字,终端 alertstream 按 struct{StationNo int} 解析; // 早先发字符串 "1" 会解析失败导致 station.sign 事件被过滤丢弃,只剩 5 秒轮询兜底。 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 聚合「操作工已呼叫签字、待检验员签字确认」的工艺步骤(巡检终端「待签任务」数据源)。 // 基数=OPERATOR 未撤销签字;**只保留 needInspectorSign=true 的步骤**(P1-1:只配操作工签字的步骤 // 不进检验员待签列表,否则永久挂单且触发假超时);剔除同 (sn,stationNo,stepId,round) 已有检验员签字的。 // 超时预警已从本查询接口移除,改由定时扫描 ScanSignTimeout 每分钟落(P1-2)。 func (s *Service) PendingSigns(ctx context.Context, f PendingSignFilter) ([]StepSignVO, int, error) { client := s.ctx.EntClient q := client.StepSignRecord.Query(). Where(stepsignrecord.SignRole("OPERATOR"), 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)) } ops, err := q.Order(ent.Desc(stepsignrecord.FieldID)).All(ctx) if err != nil { return nil, 0, err } // 标记哪些 (sn,stationNo,stepId,round) 已有检验员签字(OK 或 NG 均已处理,按轮次匹配)。 // NG 后该轮不再待签:工人整改后重新呼叫=新一轮,重回待签列表,避免检验员对同一轮重复签。 type signKey struct { sn, stationNo string stepId, round int } inspectorDone := map[signKey]bool{} 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}] = true } list := make([]StepSignVO, 0, len(ops)) for _, r := range ops { k := signKey{r.Sn, r.StationNo, r.StepId, r.Round} if inspectorDone[k] { continue } // P1-1:只列真正需要检验员签字的步骤——只配操作工签字的步骤不进待签列表 ps, pe := client.ProcessStep.Get(ctx, r.StepId) if pe != nil || !ps.NeedInspectorSign { continue } signedAt := r.SignedAt.Format("2006-01-02 15:04:05") 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: signedAt, Round: r.Round, Source: r.Source, OperatorSigner: r.SignedBy, OperatorSignedAt: signedAt, HasInspectorSign: false, }) } 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 } // 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) // 不过滤 revoked:NG 后工人整改重新呼叫会作废旧轮,但检验员判过的 NG 仍需回看(P2-3 目的)。 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 { // 工人是否已对该轮整改后重新呼叫:新一轮 OPERATOR 签字存在即视为整改中/已重呼 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("OPERATOR"), 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, }) } return list, nil } // PendingAuditFilter 待审核查询过滤(审核人「待审任务」数据源,独立 gate,不在本次签字循环内)。 type PendingAuditFilter struct { Sn string `json:"sn"` OrderNo string `json:"orderNo"` StationNo string `json:"stationNo"` Page int `json:"page"` PageSize int `json:"pageSize"` } // AuditorSignReq 审核人复核签字请求。 type AuditorSignReq struct { Sn string `json:"sn"` OrderNo string `json:"orderNo"` StationNo string `json:"stationNo"` StepId int `json:"stepId"` Result string `json:"result"` Remark string `json:"remark"` } // AuditorSign 审核人复核签字(独立 gate,保持现状):前置签字满足后落 AUDITOR OK/NG; // NG 撤销该步骤本轮已有的操作工/检验员签字,退回重做。 func (s *Service) AuditorSign(ctx context.Context, req AuditorSignReq, 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 / 工位号 / 步骤") } 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.NeedAudit { return errors.New("该步骤未配置「需审核人复核」,无需审核") } result := strings.ToUpper(strings.TrimSpace(req.Result)) if result != "OK" && result != "NG" { result = "OK" } round, err := newestRound(ctx, client, req.Sn, req.StationNo, ps.FlowId) if err != nil { return err } if round <= 0 { return errors.New("操作工尚未呼叫签字,审核人不能先审") } if ps.NeedInspectorSign { inspOK, 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), stepsignrecord.Result("OK"), stepsignrecord.SignedByNEQ("")).Exist(ctx) if e != nil { return e } if !inspOK { return errors.New("检验员尚未签字确认,审核人不能先审") } } exists, e := client.StepSignRecord.Query(). Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo), stepsignrecord.StepId(req.StepId), stepsignrecord.SignRole("AUDITOR"), stepsignrecord.Round(round), stepsignrecord.Revoked(false)).Exist(ctx) if e != nil { return e } if exists { return errors.New("本轮已审核,请勿重复提交") } if result == "NG" { _, _ = client.StepSignRecord.Update(). Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo), stepsignrecord.StepId(req.StepId), stepsignrecord.Round(round), stepsignrecord.SignRoleIn("OPERATOR", "INSPECTOR"), stepsignrecord.Revoked(false)). SetRevoked(true).SetRevokedBy(operator). SetRevokedAt(time.Now()).SetRevokeReason("审核不通过,退回重做").Save(ctx) } _, err = client.StepSignRecord.Create(). SetSn(req.Sn).SetOrderNo(req.OrderNo).SetFlowId(ps.FlowId). SetStationNo(req.StationNo).SetStepId(req.StepId).SetStepName(ps.Name). SetSignRole("AUDITOR").SetResult(result).SetSignedBy(operator). SetRound(round).SetSource("audit").SetRemark(req.Remark).Save(ctx) if err != nil && isUniqueSignViolation(err) { return errors.New("该步骤本轮已审核,请勿重复提交") } return err } // PendingAudits 聚合「前置签字已满足、待审核人复核」的工艺步骤(独立 gate)。 func (s *Service) PendingAudits(ctx context.Context, f PendingAuditFilter) ([]StepSignVO, int, error) { client := s.ctx.EntClient q := client.StepSignRecord.Query(). Where(stepsignrecord.SignRole("OPERATOR"), 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)) } ops, 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 } inspOK := map[signKey]bool{} auditOK := map[signKey]bool{} insp, e := client.StepSignRecord.Query(). Where(stepsignrecord.SignRoleIn("INSPECTOR", "AUDITOR"), stepsignrecord.Revoked(false), stepsignrecord.SignedByNEQ("")).All(ctx) if e != nil { return nil, 0, e } for _, r := range insp { k := signKey{r.Sn, r.StationNo, r.StepId, r.Round} if r.SignRole == "INSPECTOR" && r.Result == "OK" { inspOK[k] = true } if r.SignRole == "AUDITOR" && r.Result == "OK" { auditOK[k] = true } } list := make([]StepSignVO, 0, len(ops)) for _, r := range ops { k := signKey{r.Sn, r.StationNo, r.StepId, r.Round} if auditOK[k] { continue } ps, e := client.ProcessStep.Get(ctx, r.StepId) if e != nil || !ps.NeedAudit { continue } if ps.NeedInspectorSign && !inspOK[k] { continue } signedAt := r.SignedAt.Format("2006-01-02 15:04:05") 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: signedAt, Round: r.Round, Source: r.Source, OperatorSigner: r.SignedBy, OperatorSignedAt: signedAt, }) } 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 }