【全系统 · 接驳台编码终版统一(12-01 用户拍板)】
- 新增 dockcode 包作为唯一真源:工位接驳台 = GW{工位号}{Z|Y}(Z=左/Y=右,工位1~10同一规则,废除左右互换),库房 = JBT21 不变
- 编码即海康 RCS 地图点位码:落库/界面/下发 RCS/读 PLC 传感器全用同一套;旧 DOCK01~20 全量废弃,系统内无第二套编号、无换算层
- dock 表去 side 字段;agv_task.target_dock、line_point、看板点位态与中文名、dockLabel 工具全部改 GW 规则
- 产线布局说明.md 同步终版(图纸名 GxZ/GxY 与 AGV 码 GWxZ/GWxY 一一对应;注明 RCS 图与主线流向图相差 180°,读图一律以 GW 码为准)
【MES · 签字模型二次重构(11-30 实测后定稿)】
- _OPERATOR 签字整体废除:工艺步骤删 needOperatorSign / needAudit / auditRole 字段,签字角色改 CALL(工人报检呼叫)+ INSPECTOR(检验员审核签)
- 呼叫时落步骤录入快照(stepValue/stepText/stepChecked/processId),供检验员查看与指纹比对;「待签任务」只认检验员签名步骤
- 「签字复核」(AuditPending 页面 + produce.audit 菜单 + 路由)整套删除
【MES · 台账续流根因修复(11-30 对账发现)】
- 流转目标「G6」与 line_point.point_no「6」对不上导致到位落账查不到、却先释放源位→工件从调度消失;新增 ledgerPointByTarget 归一
- settleDirect/settleInTransit 改为先占目标位、成功才释放源位;目标被占原样保留,工件进缓存位排队(实测 C2 排队不再丢件)
【WMS · 末级库位强校验与上架移库】
- 新增 LocationCascade 四级联动选择器(区/架/层/号,只从启用 level=4 节点派生);手工入库、半成品/成品入库、隔离库位一律四级必填且命中启用节点
- 新增上架/移库 relocate:只改四级库位与 updated_at,不动质量状态/数量/锁定量;不合格与锁定行同样允许移库;支持 ids 逐行指定或 scope 按物料+原库位整组搬
- MES 新增 WMS 自动回流库位配置(半成品/成品各一组末级库位,默认值 1区/1架/1层/1号,存 sys_config 可改)
【MES · 统一口径与工程整改】
- 新增 workpiece_location:工单详情工件列表/WIP/追溯三处共用位置判定(SCRAPPED→DONE→SEMI_STORED→在 StationNo→在途→待流转)
- 新增 workorder_close_warn:工单完工/取消时汇总各工位实物余料出一条预警,不阻断关单
- 分页下沉:新增 pagination 工具,同步失败台账(两端)改 Count+LIMIT/OFFSET 真分页,列表不再全量切片
- 全网对账/孤儿扫描(问题临时.md 第25/26节):10 类关系边断言实测,给出 8 条可重复巡检项
【文档】
- 产线布局说明.md 按 GW 编码终版重写;问题临时.md 新增 24.7 闭环实测、25 全网对账、26 补料→配送→报工人库闭环
742 lines
28 KiB
Go
742 lines
28 KiB
Go
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 重构定稿)============
|
||
// 旧模型:操作工签字随报工落库,检验员只校验「历史步骤」(seq<k),k 恒为 1 → 检验员签字分支永不生效。
|
||
// 新模型(一步一步签,每步按自身配置 need_inspector_sign):
|
||
// 1. 工人干完 → 点「报检」(CallSign):本工艺所有需检验步骤落 CALL 呼叫记录(步骤录入快照 + 内容指纹);
|
||
// 2. 检验员在巡检端「待签任务」对需检验步骤签 OK / NG(InspectorSign,签在本轮);
|
||
// 3. OK 后工人再点一次「报工」——报工闸门校验本轮所有需检验步骤 INSPECTOR=OK 齐全 + 指纹未变才放行;
|
||
// 4. NG → 待整改,工人改完再次报检(新一轮,round+1,上一轮作废);
|
||
// 5. 撤回呼叫(RevokeSign)=本轮全部 CALL/INSPECTOR 签字作废,历史保留不物理删。
|
||
// 三档状态(SignStatus)全部从签字记录推导,不建表、不存终端:WORKING/SIGNING/RECTIFY/READY。
|
||
|
||
// signTimeoutMinutes 报检后检验员未签的超时阈值(分钟);超时落预警中心+异常告警角标,不进铃铛。
|
||
const signTimeoutMinutes = 30
|
||
|
||
// StepSignVO 签字记录视图对象,返回给前端(巡检终端「待签任务」/追溯展示)。
|
||
type StepSignVO struct {
|
||
ID int `json:"id"`
|
||
Sn string `json:"sn"`
|
||
OrderNo string `json:"orderNo"`
|
||
FlowId int `json:"flowId"`
|
||
StationNo string `json:"stationNo"`
|
||
StepId int `json:"stepId"`
|
||
StepName string `json:"stepName"`
|
||
SignRole string `json:"signRole"`
|
||
Result string `json:"result"`
|
||
SignedBy string `json:"signedBy"`
|
||
SignedAt string `json:"signedAt"`
|
||
Round int `json:"round"`
|
||
Source string `json:"source"`
|
||
Revoked bool `json:"revoked"`
|
||
// 报检呼叫时提交的步骤录入快照
|
||
StepValue string `json:"stepValue"`
|
||
StepText string `json:"stepText"`
|
||
StepChecked bool `json:"stepChecked"`
|
||
ProcessId int64 `json:"processId"`
|
||
CriterionName string `json:"criterionName"` // 考核标准名(如 扭矩)
|
||
CriterionLogic string `json:"criterionLogic"` // 判定规则 GE/LE/RANGE...
|
||
CriterionDetail string `json:"criterionDetail"` // 考核标准可读文本
|
||
HasInspectorSign bool `json:"hasInspectorSign"` // 是否已有检验员签字
|
||
Remark string `json:"remark"` // 签字意见(NG 回看时展示检验员结论理由)
|
||
InspectorRemark string `json:"inspectorRemark"` // 检验员意见(本轮)
|
||
InspectorSignedAt string `json:"inspectorSignedAt"`
|
||
Rehandled bool `json:"rehandled"` // NG 回看:工人是否已整改后重新报检(新一轮)
|
||
}
|
||
|
||
// CallSignReq 报检请求(工位终端:干完活后主动呼叫检验员签字)。
|
||
type CallSignReq struct {
|
||
Sn string `json:"sn"`
|
||
OrderNo string `json:"orderNo"`
|
||
FlowId int `json:"flowId"`
|
||
StationNo string `json:"stationNo"`
|
||
Operator string `json:"operator"`
|
||
Steps []StepDataReq `json:"steps"` // 当前步骤内容,算内容指纹 + 落快照
|
||
Binds []BindItemReq `json:"binds"` // 兼容旧载荷,不进指纹
|
||
}
|
||
|
||
// CallSignResult 报检结果。
|
||
type CallSignResult struct {
|
||
Round int `json:"round"`
|
||
State string `json:"state"`
|
||
NeedSign bool `json:"needSign"`
|
||
Message string `json:"message"`
|
||
}
|
||
|
||
// RevokeSignReq 撤回呼叫请求(整轮作废,回到作业中)。
|
||
type RevokeSignReq struct {
|
||
Sn string `json:"sn"`
|
||
OrderNo string `json:"orderNo"`
|
||
FlowId int `json:"flowId"`
|
||
StationNo string `json:"stationNo"`
|
||
Operator string `json:"operator"`
|
||
}
|
||
|
||
// SignStatusReq 签字状态查询请求。
|
||
type SignStatusReq struct {
|
||
Sn string `json:"sn"`
|
||
OrderNo string `json:"orderNo"`
|
||
FlowId int `json:"flowId"`
|
||
StationNo string `json:"stationNo"`
|
||
}
|
||
|
||
// StepSignState 单步签字状态(终端展示每步签了没)。
|
||
type StepSignState struct {
|
||
StepId int `json:"stepId"`
|
||
StepName string `json:"stepName"`
|
||
NeedInspectorSign bool `json:"needInspectorSign"`
|
||
InspectorResult string `json:"inspectorResult"` // 本轮检验员结论 OK/NG/空
|
||
InspectorSigner string `json:"inspectorSigner"`
|
||
InspectorRemark string `json:"inspectorRemark"` // NG 意见回显
|
||
InspectorSignedAt string `json:"inspectorSignedAt"` // 检验员签字时间
|
||
}
|
||
|
||
// SignStatusVO 三档签字状态(WORKING 未呼叫 / SIGNING 签字中 / RECTIFY 待整改 / READY 可报工)。
|
||
type SignStatusVO struct {
|
||
State string `json:"state"` // WORKING/SIGNING/RECTIFY/READY
|
||
Round int `json:"round"` // 当前有效轮次(0=未呼叫)
|
||
NeedSign bool `json:"needSign"` // 本工序是否配了需检验步骤
|
||
Message string `json:"message"` // 面向工人的中文提示
|
||
CanRevoke bool `json:"canRevoke"` // 当前是否有可撤回的签字
|
||
Steps []StepSignState `json:"steps"`
|
||
}
|
||
|
||
// InspectorSignReq 检验员签字确认请求(OK/NG,签在本轮)。
|
||
type InspectorSignReq struct {
|
||
Sn string `json:"sn"`
|
||
OrderNo string `json:"orderNo"`
|
||
StationNo string `json:"stationNo"`
|
||
StepId int `json:"stepId"`
|
||
Result string `json:"result"` // OK / NG
|
||
Remark string `json:"remark"`
|
||
}
|
||
|
||
// ============ 内容指纹:只覆盖本轮步骤录入内容(步骤值 + 检测勾选 + 拧紧结果)============
|
||
// P2-1 口径(2026-11-30 定稿):**装机绑定不进指纹**。理由:
|
||
//
|
||
// ① 装机绑定走独立 bindRecord / bindRemove 接口逐条落库、有自己的台账和齐套闸门,不随报工/呼叫载荷提交;
|
||
// ② 若要把绑定算进来,报检与报工两侧必须携带同一份绑定快照,否则每次报工都会指纹不一致;
|
||
// 当前终端两条路都不传 binds(报工代理亦已删 binds 载荷),所以指纹只对步骤内容负责。
|
||
// ③ 绑定变更本身会触发齐套重校验,不需要靠签字作废来兜底。
|
||
//
|
||
// 报检时算一次落库,报工时用同一函数重算比对:一致才放行,变了即"改数据作废本轮"。
|
||
// 规范化:按 stepId 排序(顺序变化不算改数据),浮点用 'f',-1 定长表示,
|
||
// 只纳入内容型字段(value/text/checked),不含签字人/备注/时间戳(改备注不算)。
|
||
// binds 参数保留仅因签名兼容(两侧均传 nil):函数内不再纳入指纹。
|
||
func calcContentFingerprint(steps []StepDataReq, binds []BindItemReq) string {
|
||
type stepKey struct {
|
||
id int
|
||
value string
|
||
text string
|
||
checked bool
|
||
}
|
||
ss := make([]stepKey, 0, len(steps))
|
||
for _, s := range steps {
|
||
ss = append(ss, stepKey{s.StepId, strconv.FormatFloat(s.Value, 'f', -1, 64), s.Text, s.Checked})
|
||
}
|
||
sort.Slice(ss, func(i, j int) bool { return ss[i].id < ss[j].id })
|
||
var b strings.Builder
|
||
for _, s := range ss {
|
||
ck := "0"
|
||
if s.checked {
|
||
ck = "1"
|
||
}
|
||
fmt.Fprintf(&b, "S|%d|%s|%s|%s\n", s.id, s.value, s.text, ck)
|
||
}
|
||
sum := sha256.Sum256([]byte(b.String()))
|
||
return hex.EncodeToString(sum[:])
|
||
}
|
||
|
||
// newestRound 取该 (sn, stationNo) 下未撤销签字的当前轮次;flowId>0 时限定工序。
|
||
// 轮次在「报检」时整工序统一 +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
|
||
}
|