feat: 新增工序签字功能,移除移料指令模块

新增操作工/检验员工序签字功能,支持工艺步骤配置签字要求;删除移料指令相关代码,将移料页签重命名为产线点位(上料/下料);新增成品入库功能及相关权限;优化备料单状态、质量状态逻辑,新增批次序号字段;修复AGV取消后备料单回退状态问题。
This commit is contained in:
SunYF
2026-10-05 20:15:38 +08:00
parent c33acab9c8
commit f1cf57e9b2
181 changed files with 9785 additions and 9699 deletions
+231 -24
View File
@@ -5,18 +5,22 @@ import (
"errors"
"fmt"
"math"
"net/url"
"strconv"
"strings"
"time"
"bj_power_mes/ent"
"bj_power_mes/ent/associationtrace"
"bj_power_mes/ent/attachment"
"bj_power_mes/ent/inspectionrecord"
"bj_power_mes/ent/material"
"bj_power_mes/ent/processstep"
"bj_power_mes/ent/semiflow"
"bj_power_mes/ent/station"
"bj_power_mes/ent/stepcriterion"
"bj_power_mes/ent/stepdata"
"bj_power_mes/ent/stepsignrecord"
"bj_power_mes/ent/torquerecord"
"bj_power_mes/ent/workorder"
"bj_power_mes/ent/workpiece"
@@ -62,6 +66,16 @@ type StepDataReq struct {
Checked bool `json:"checked"`
}
// StepSignInput 报工携带的步骤签字:操作工在工位终端/虚拟工位「签字确认」弹框中录入,
// 与 needOperatorSign 步骤一一对应;服务端强校验(validateNeedSign)后落 step_sign_record(signRole=OPERATOR)。
// 检验员签字(needInspectorSign)不走报工,由巡检终端「待签任务」页签单独签字(需求B)。
type StepSignInput struct {
StepId int `json:"stepId"`
SignRole string `json:"signRole"` // OPERATOR
Signer string `json:"signer"` // 签字人(操作工登录账号/姓名)
Remark string `json:"remark"`
}
type OnlineReq struct {
Sn string `json:"sn"`
OrderNo string `json:"orderNo"`
@@ -206,7 +220,9 @@ type ReportProcessReq struct {
FlowId int `json:"flowId"` // 报工工艺(缺省回退工位当前绑定的工艺)
StationNo int `json:"stationNo"`
Steps []StepDataReq `json:"steps"`
Binds []BindItemReq `json:"binds"` // 装机绑定(本工序装配物料:批次件批次号/序列号件SN),随报工原子提交
// 签字确认(需求B):needOperatorSign 步骤须带操作工签字(签字确认弹框采集),服务端强校验并落库
Signs []StepSignInput `json:"signs"`
Binds []BindItemReq `json:"binds"` // 装机绑定(本工序装配物料:批次件批次号/序列号件SN),随报工原子提交
// 作业时长采集(方案 M / P0-3):工位终端在「上料到本工位」时采 startedAt、点「报工」时采 endedAt,
// 两端时间戳同源于终端时钟(ISO8601),离线重传也不失真;缺失则回退服务端当前时刻(时长=0)。
StartedAt string `json:"startedAt"`
@@ -309,6 +325,14 @@ func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, opera
if err := s.validateNeedCheck(ctx, client, req); err != nil {
return err
}
// 阶段2.5:签字机制(需求B)强校验 + 落操作工签字(needOperatorSign 步骤)。
// needInspectorSign 步骤要求检验员已在巡检终端「待签任务」页签签字,否则拒流转。
if err := s.validateNeedSign(ctx, client, req, flowId); err != nil {
return err
}
if err := s.writeOperatorSigns(ctx, client, req, flowId, wp.OrderNo, operator); err != nil {
return err
}
now := time.Now()
// 作业时长(方案 M / P0-3):startedAt=进工位(上料)时刻、endedAt=报工时刻,均由工位终端采集;
// 缺失或非法则回退到服务端当前时刻(durationSec=0),时钟回拨导致负数则时长归零。
@@ -411,6 +435,104 @@ func (s *Service) validateNeedCheck(ctx context.Context, client *ent.Client, req
return nil
}
// validateNeedSign 签字机制(需求B)服务端强校验,镜像 validateNeedCheck:
// 本工位绑定工艺流程中,凡标记 needOperatorSign=true 的工艺步骤,报工请求必须携带对应签字
// (Signs 中存在 stepId 匹配且 signer 非空);凡标记 needInspectorSign=true 的步骤,必须已存在
// 检验员签字记录(step_sign_record, signRole=INSPECTOR, 未撤销, signedBy 非空)方可流转。
// 工位未绑定流程、或流程内无签字步骤时不拦截(与现场配置保持一致)。
func (s *Service) validateNeedSign(ctx context.Context, client *ent.Client, req ReportProcessReq, flowId int) error {
if req.StationNo <= 0 || flowId <= 0 {
return nil
}
steps, err := client.ProcessStep.Query().
Where(processstep.FlowId(flowId), processstep.Or(processstep.NeedOperatorSign(true), processstep.NeedInspectorSign(true))).All(ctx)
if err != nil || len(steps) == 0 {
return err
}
stationNo := itoa(req.StationNo)
signMap := map[int]StepSignInput{}
for _, sg := range req.Signs {
if sg.SignRole == "OPERATOR" {
signMap[sg.StepId] = sg
}
}
for _, ps := range steps {
if ps.NeedOperatorSign {
sg, ok := signMap[ps.ID]
if !ok || strings.TrimSpace(sg.Signer) == "" {
name := ps.Name
if name == "" {
name = "步骤" + itoa(ps.ID)
}
return errors.New("以下步骤需操作工签字确认后才能报工:" + name)
}
}
if ps.NeedInspectorSign {
// 检验员必须「签字确认」(result=OK、未撤销、有签字人) 才能流转;NG 结论视为未通过、不放行。
has, e := client.StepSignRecord.Query().
Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(stationNo),
stepsignrecord.StepId(ps.ID), stepsignrecord.SignRole("INSPECTOR"),
stepsignrecord.Revoked(false), stepsignrecord.SignedByNEQ(""),
stepsignrecord.Result("OK")).Exist(ctx)
if e != nil {
return e
}
if !has {
name := ps.Name
if name == "" {
name = "步骤" + itoa(ps.ID)
}
return errors.New("以下步骤需检验员签字确认(合格)后才能流转:" + name)
}
}
}
return nil
}
// writeOperatorSigns 在报工事务内落操作工签字(needOperatorSign 步骤,签字确认弹框采集);
// 按唯一索引(sn, stationNo, stepId, signRole=OPERATOR, round) 去重,避免重报产生重复签字。
// orderNo 取自工件所属工单(wp.OrderNo),签字记录随单追溯。
func (s *Service) writeOperatorSigns(ctx context.Context, client *ent.Client, req ReportProcessReq, flowId int, orderNo, operator string) error {
steps, err := client.ProcessStep.Query().
Where(processstep.FlowId(flowId), processstep.NeedOperatorSign(true)).All(ctx)
if err != nil {
return err
}
if len(steps) == 0 {
return nil
}
stationNo := itoa(req.StationNo)
signMap := map[int]StepSignInput{}
for _, sg := range req.Signs {
if sg.SignRole == "OPERATOR" {
signMap[sg.StepId] = sg
}
}
for _, ps := range steps {
sg, ok := signMap[ps.ID]
if !ok || strings.TrimSpace(sg.Signer) == "" {
continue // 已在 validateNeedSign 拦截,这里兜底跳过
}
exist, _ := client.StepSignRecord.Query().
Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(stationNo),
stepsignrecord.StepId(ps.ID), stepsignrecord.SignRole("OPERATOR"),
stepsignrecord.Round(1)).First(ctx)
if exist != nil {
continue
}
_, err = client.StepSignRecord.Create().
SetSn(req.Sn).SetOrderNo(orderNo).SetFlowId(flowId).
SetStationNo(stationNo).SetStepId(ps.ID).SetStepName(ps.Name).
SetSignRole("OPERATOR").SetResult("OK").
SetSignedBy(strings.TrimSpace(sg.Signer)).SetRound(1).
SetSource("station").SetRemark(sg.Remark).Save(ctx)
if err != nil {
return err
}
}
return nil
}
// writeStepData 写一条步骤考核数据,按标准自动判定是否合格
func (s *Service) writeStepData(ctx context.Context, client *ent.Client, sn string, processId int, st StepDataReq, operator string) (bool, error) {
ok := true
@@ -486,12 +608,10 @@ func (s *Service) DoneWorkpiece(ctx context.Context, req DoneReq, operator strin
s.bumpWorkOrderProgress(ctx, wp.OrderNo, req.Sn)
s.bumpDailyPlanCompleted(ctx, wp.OrderNo, now)
s.ctx.EventLog.Write(ctx, "workpiece.done", wp.OrderNo, operator, "workpiece", req.Sn, "完工+关联追溯", map[string]any{"batchItems": req.BatchItems, "serialItems": req.SerialItems})
// 成品完工自动回流 WMS(统一库存主表 category=3):
// 成品 SN = 工件 SN(进线登记时确定:序列号件=扫入的来料SN / 批次件=系统发号,全程唯一可追溯)。
// WMS 不可达/校验失败时降级:记 eventlog 不阻塞完工,与备料 WMS 校验降级策略同模式。
s.retainFinishedToWms(ctx, wp, operator)
// 完工确认 = 生产完成(方案A定稿):此处不再回流 WMS 入库,成品改由「完工检」结论触发——
// 完工检合格(已通过/部分通过)才回流入库,见 inspection.go finishedInspectionInbound。
// 反冲扣账:物料在当道工序被消耗,完工即按整份 BOM 反冲扣 WMS 库存。
// 失败仅记 eventlog 不阻塞完工(与成品回流同降级策略)。
// 失败仅记 eventlog 不阻塞完工。
s.backflushWorkpiece(ctx, wp, operator)
s.notifyDashboard()
return nil
@@ -534,24 +654,6 @@ func (s *Service) backflushWorkpiece(ctx context.Context, wp *ent.Workpiece, ope
"反冲扣账已下发WMS", map[string]any{"orderNo": wp.OrderNo, "items": len(items)})
}
// retainFinishedToWms 完工品回流 WMS 库存。失败仅记日志(wms.finished.retain_failed),
// 不回滚完工状态——仓管可在 WMS 侧人工补录,避免 WMS 抖动卡死产线。
func (s *Service) retainFinishedToWms(ctx context.Context, wp *ent.Workpiece, operator string) {
wo, err := s.ctx.EntClient.WorkOrder.Get(ctx, wp.WorkOrderId)
if err != nil || wo == nil {
s.ctx.EventLog.Write(ctx, "wms.finished.retain_failed", wp.OrderNo, operator, "workpiece", wp.Sn,
"成品回流WMS失败:工单不存在", map[string]any{"error": "work order not found"})
return
}
if wmsErr := s.ctx.Wms.FinishedInbound(ctx, wo.ProductCode, wo.ProductName, wp.Sn, wp.OrderNo, operator); wmsErr != nil {
s.ctx.EventLog.Write(ctx, "wms.finished.retain_failed", wp.OrderNo, operator, "workpiece", wp.Sn,
"成品回流WMS失败(库存未入,请人工补录)", map[string]any{"error": wmsErr.Error(), "productCode": wo.ProductCode})
return
}
s.ctx.EventLog.Write(ctx, "wms.finished.retain", wp.OrderNo, operator, "workpiece", wp.Sn,
"成品完工已回流WMS库存", map[string]any{"productCode": wo.ProductCode})
}
// Trace 追溯查询(SN 维度):工序时间线/操作人/步骤数据/物料批次SN/拧紧数据
func (s *Service) Trace(ctx context.Context, sn string) (map[string]any, error) {
wp, err := s.ctx.EntClient.Workpiece.Query().Where(workpiece.Sn(sn)).First(ctx)
@@ -570,6 +672,12 @@ func (s *Service) Trace(ctx context.Context, sn string) (map[string]any, error)
// 半成品流转记录(IN=暂存退库 / OUT=重上线),追溯页展示完成至工位快照
semiFlows, _ := s.ctx.EntClient.SemiFlow.Query().
Where(semiflow.Sn(sn)).Order(ent.Desc(semiflow.FieldID)).All(ctx)
// 检验记录(过程检/完工检,只读展示;PAD 巡检动作不纳入)
inspections := s.traceInspections(ctx, sn)
// 签字记录(需求B):操作工/检验员对工艺步骤的签字确认,只读展示
signs, _ := s.ctx.EntClient.StepSignRecord.Query().
Where(stepsignrecord.Sn(sn), stepsignrecord.Revoked(false)).
Order(ent.Desc(stepsignrecord.FieldID)).All(ctx)
return map[string]any{
"workpiece": wp,
@@ -579,9 +687,108 @@ func (s *Service) Trace(ctx context.Context, sn string) (map[string]any, error)
"torqueRecords": torque,
"bindTrace": bindVO,
"semiFlows": semiFlows,
"inspections": inspections,
"signs": signs,
}, nil
}
// TraceAttachmentVO 追溯页检验附件条目(预览走公开直链,下载走带鉴权 id 路由,前端点击打开)
type TraceAttachmentVO struct {
ID int `json:"id"`
FileName string `json:"fileName"`
URL string `json:"url"` // /api/v1/attachment/file/:id?dl=1(带 JWT 下载)
PreviewURL string `json:"previewUrl"` // 免鉴权公开直链 /api/v1/files?name=
}
// TraceInspectionVO 追溯页检验记录条目(过程检/完工检,只读展示)
type TraceInspectionVO struct {
ID int `json:"id"`
Category string `json:"category"` // QC_PROCESS=过程检 / FINAL=完工检
Result string `json:"result"` // OK/NG/PARTIAL
DisposalType string `json:"disposalType"` // 退货/返修/退换/报废(空=无处置)
DisposalRemark string `json:"disposalRemark"` // 处置说明
RelatedStandard string `json:"relatedStandard"`
TestRecordNo string `json:"testRecordNo"`
Operator string `json:"operator"`
CreatedAt time.Time `json:"createdAt"`
Attachments []TraceAttachmentVO `json:"attachments"`
}
// traceInspections 追溯页检验记录:该 SN 的过程检(QC_PROCESS)/完工检(FINAL)记录,时间倒序。
// MES 质检过程检落 QC_PROCESS(与 PAD 过程巡检 PROCESS 隔离,P1-8),
// CHECKIN/POINT/PROCESS/DONE/ALARM 为巡检动作不纳入;无记录返回空不报错。
func (s *Service) traceInspections(ctx context.Context, sn string) []TraceInspectionVO {
recs, err := s.ctx.EntClient.InspectionRecord.Query().
Where(inspectionrecord.SnEQ(sn), inspectionrecord.CategoryIn("QC_PROCESS", "FINAL")).
Order(ent.Desc(inspectionrecord.FieldCreatedAt), ent.Desc(inspectionrecord.FieldID)).
Limit(200).All(ctx)
if err != nil || len(recs) == 0 {
return nil
}
out := make([]TraceInspectionVO, 0, len(recs))
for _, rec := range recs {
out = append(out, TraceInspectionVO{
ID: rec.ID,
Category: rec.Category,
Result: rec.Result,
DisposalType: rec.DisposalType,
DisposalRemark: rec.DisposalRemark,
RelatedStandard: rec.RelatedStandard,
TestRecordNo: rec.TestRecordNo,
Operator: rec.Operator,
CreatedAt: rec.CreatedAt,
Attachments: s.inspectionRecordAttachments(ctx, rec),
})
}
return out
}
// inspectionRecordAttachments 某检验记录的附件列表,合并两条现有关联口径并按 ID 去重:
// ① 记录上的 attachmentIds(逗号分隔,关联 attachment 表);
// ② 附件表按 bizType=quality & bizId=报检单号(质检页上传/查看的既有模式)。
func (s *Service) inspectionRecordAttachments(ctx context.Context, rec *ent.InspectionRecord) []TraceAttachmentVO {
seen := map[int]bool{}
var atts []*ent.Attachment
if rec.AttachmentIds != "" {
for _, p := range strings.Split(rec.AttachmentIds, ",") {
id, e := strconv.Atoi(strings.TrimSpace(p))
if e != nil || id <= 0 || seen[id] {
continue
}
seen[id] = true
if a, ge := s.ctx.EntClient.Attachment.Get(ctx, id); ge == nil && !a.Deleted {
atts = append(atts, a)
}
}
}
if rec.ReportNo != "" {
byBiz, qe := s.ctx.EntClient.Attachment.Query().
Where(attachment.BizTypeEQ("quality"), attachment.BizIdEQ(rec.ReportNo), attachment.DeletedEQ(false)).
Order(ent.Asc(attachment.FieldID)).All(ctx)
if qe == nil {
for _, a := range byBiz {
if !seen[a.ID] {
seen[a.ID] = true
atts = append(atts, a)
}
}
}
}
out := make([]TraceAttachmentVO, 0, len(atts))
for _, a := range atts {
vo := TraceAttachmentVO{
ID: a.ID,
FileName: a.FileName,
URL: "/api/v1/attachment/file/" + strconv.Itoa(a.ID) + "?dl=1",
}
if a.FilePath != "" {
vo.PreviewURL = "/api/v1/files?name=" + url.QueryEscape(a.FilePath)
}
out = append(out, vo)
}
return out
}
func (s *Service) ListWorkpieces(ctx context.Context, sn, orderNo string) ([]*ent.Workpiece, error) {
q := s.ctx.EntClient.Workpiece.Query()
if sn != "" {