Files
bj_power/bj_power_mes/internal/logic/torque.go
T
2026-10-26 16:32:35 +08:00

284 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package logic
import (
"context"
"errors"
"log"
"strconv"
"strings"
"time"
"bj_power_mes/ent"
"bj_power_mes/ent/alert"
"bj_power_mes/ent/processstep"
"bj_power_mes/ent/station"
"bj_power_mes/ent/stepcriterion"
"bj_power_mes/ent/torquerecord"
"bj_power_mes/ent/workpiece"
)
type TorqueReq struct {
Sn string `json:"sn"`
WorkOrder string `json:"workOrder"`
WorkOrderNo string `json:"workOrderNo"`
StationNo string `json:"stationNo"`
ScrewNo string `json:"screwNo"`
Strain float64 `json:"strain"` // 扭矩
Torque float64 `json:"torque"`
Angle float64 `json:"angle"`
Result string `json:"result"`
Operator string `json:"operator"`
Time time.Time `json:"time"`
}
// ReportTorque 接收拧紧数据(工位终端/内部接口上报),入库并做扭矩 RANGE 判定写 step_data。
// operatorId:落库操作人用户ID,由 MES 从当前登录态 JWT 解析,即「本次发送所用的登录人」。
func (s *Service) ReportTorque(ctx context.Context, req TorqueReq, operator string, operatorId int) error {
if req.Sn == "" {
return errors.New("sn 不能为空")
}
if req.Strain == 0 {
req.Strain = req.Torque
}
result := req.Result
if result == "" {
result = "OK"
}
workOrderNo := req.WorkOrder
if workOrderNo == "" {
workOrderNo = req.WorkOrderNo
}
if req.Time.IsZero() {
req.Time = time.Now()
}
_, err := s.ctx.EntClient.TorqueRecord.Create().
SetWorkOrderNo(workOrderNo).SetSn(req.Sn).SetScrewNo(req.ScrewNo).
SetStrain(req.Strain).SetTorque(req.Strain).SetAngle(req.Angle).
SetResult(result).SetOperator(operator).SetOperatorId(operatorId).SetStationNo(req.StationNo).
SetTime(req.Time).Save(ctx)
if err != nil {
return err
}
s.ctx.EventLog.Write(ctx, "torque.report", workOrderNo, operator, "torque_record", req.Sn, "接收拧紧数据上报", map[string]any{"strain": req.Strain, "angle": req.Angle, "result": result})
s.evaluateTorqueCriterion(ctx, req.Sn, req.StationNo, req.Strain, req.Angle, operator)
s.notifyDashboard()
return nil
}
// evaluateTorqueCriterion 依据「采集方式=拧紧枪自动(AUTO)步骤 + RANGE 考核标准」自动判定 OK/NG 写入 step_data。
// 判定完全依据步骤采集方式与区间逻辑,不再依赖指标名(如「扭矩」),
// 避免误命名(如「时间」)导致整段判定静默失效;与 dashboard.loadTorqueCriterion 共用
// torqueRangeCriteria,口径统一。仅取上报工位所绑定工艺流程内的扭矩标准,跨流程/无关步骤不会误判。
func (s *Service) evaluateTorqueCriterion(ctx context.Context, sn, stationNo string, strain, angle float64, operator string) {
crits, _ := s.torqueRangeCriteria(ctx, s.stationFlowId(ctx, stationNo))
ng := false
for _, c := range crits {
ok := true
if c.Min != nil && strain < *c.Min {
ok = false
}
if c.Max != nil && strain > *c.Max {
ok = false
}
_, _ = s.ctx.EntClient.StepData.Create().
SetSn(sn).SetStepId(c.StepId).SetCriterionId(c.ID).
SetCriterionName(c.Name).SetCriterionLogic(c.Logic).
SetValue(strain).SetIsOK(ok).SetOperator(operator).Save(ctx)
if !ok {
ng = true
}
}
if ng {
// 反查该 SN 所属工单号一并写入预警,供预警中心按工单号检索(客户第12条)
orderNo := ""
if wp, e := s.ctx.EntClient.Workpiece.Query().Where(workpiece.Sn(sn)).First(ctx); e == nil {
orderNo = wp.OrderNo
}
// B6 拧紧闭环:NG 立即标记该件「待人工处置」,阻断后续报工(ReportProcess)/下线完工(DoneWorkpiece)。
// 注意:本函数仅在 NG 分支写标记,返工重拧合格不自动清标记——唯一清除入口=质检/班组长确认放行
// (DisposeTorqueNg),避免"重拧即放行"绕过人工处置。标记失败仅记日志不阻断拧紧落库。
if _, e := s.ctx.EntClient.Workpiece.Update().
Where(workpiece.Sn(sn)).
SetTorqueNgPending(true).SetTorqueNgAt(time.Now()).SetTorqueNgBy(operator).Save(ctx); e != nil {
log.Printf("[torque] 置拧紧不合格标记失败 sn=%s: %v", sn, e)
}
// 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)
}
}
}
}
// stationFlowId 由工位号取绑定工艺流程 ID;未绑定/非法工位返回 0。
func (s *Service) stationFlowId(ctx context.Context, stationNo string) int {
no, err := strconv.Atoi(strings.TrimSpace(stationNo))
if err != nil || no <= 0 {
return 0
}
st, err := s.ctx.EntClient.Station.Query().Where(station.StationNo(no)).First(ctx)
if err != nil || st.FlowId <= 0 {
return 0
}
return st.FlowId
}
// torqueRangeCriteria 取「采集方式=拧紧枪自动(AUTO)步骤 + RANGE 逻辑」的考核标准(即扭矩规格)。
// flowId>0 限定某个工艺流程;flowId<=0 取全部流程(供看板全局控制图使用)。
// 判定完全依据步骤采集方式与区间逻辑,不依赖指标名,杜绝「时间」等误命名导致漏判。
// 2026-10-19:is_torque 字段已删(与 collectType=AUTO 完全重复),统一按采集方式过滤。
func (s *Service) torqueRangeCriteria(ctx context.Context, flowId int) ([]*ent.StepCriterion, error) {
stepQ := s.ctx.EntClient.ProcessStep.Query().Where(processstep.CollectType("AUTO"))
if flowId > 0 {
stepQ = stepQ.Where(processstep.FlowId(flowId))
}
steps, err := stepQ.All(ctx)
if err != nil {
return nil, err
}
if len(steps) == 0 {
return nil, nil
}
ids := make([]int, 0, len(steps))
for _, st := range steps {
ids = append(ids, st.ID)
}
return s.ctx.EntClient.StepCriterion.Query().
Where(stepcriterion.StepIdIn(ids...), stepcriterion.Logic("RANGE")).
All(ctx)
}
// ListTorqueRecords 查询拧紧数据(五条件复合取交集:工单号/SN/日期区间/工位/操作人)
func (s *Service) ListTorqueRecords(ctx context.Context, sn, workOrderNo, stationNo, operator string, from, to time.Time) ([]*ent.TorqueRecord, error) {
q := s.ctx.EntClient.TorqueRecord.Query()
if sn != "" {
// 大小写不敏感(2026-09-08 全项目搜索规范)
q = q.Where(torquerecord.SnEqualFold(sn))
}
if workOrderNo != "" {
q = q.Where(torquerecord.WorkOrderNoEqualFold(workOrderNo))
}
if stationNo != "" {
q = q.Where(torquerecord.StationNoEqualFold(stationNo))
}
if operator != "" {
q = q.Where(torquerecord.OperatorEqualFold(operator))
}
if !from.IsZero() {
q = q.Where(torquerecord.TimeGTE(from))
}
if !to.IsZero() {
q = q.Where(torquerecord.TimeLTE(to))
}
return q.Order(ent.Desc(torquerecord.FieldTime)).Limit(500).All(ctx)
}
// TorqueDisposeReq 拧紧不合格人工处置请求(质检/班组长确认放行)
type TorqueDisposeReq struct {
Sn string `json:"sn"`
Reason string `json:"reason"`
}
// DisposeTorqueNg 拧紧不合格人工处置(B6 最小闭环):质检/班组长确认放行。
// 校验该件确有待处置项后:清标记 + 写 event_log(谁/何时/原因) + 置对应 torque_ng 预警 resolved(READ)。
// 不实现返修工单流程(线下处理);处置仅放行,NG 数据永久保留于 step_data/torque_record 供追溯。
func (s *Service) DisposeTorqueNg(ctx context.Context, req TorqueDisposeReq, operator string) error {
if req.Sn == "" {
return errors.New("sn 必填")
}
wp, err := s.ctx.EntClient.Workpiece.Query().Where(workpiece.Sn(req.Sn)).First(ctx)
if err != nil {
return errors.New("工件不存在")
}
if !wp.TorqueNgPending {
return errors.New("该工件无待处置的拧紧不合格项")
}
now := time.Now()
if _, err := s.ctx.EntClient.Workpiece.UpdateOneID(wp.ID).
SetTorqueNgPending(false).ClearTorqueNgAt().ClearTorqueNgBy().Save(ctx); err != nil {
return err
}
// 留痕:谁/何时/原因
s.ctx.EventLog.Write(ctx, "torque.disposition", wp.OrderNo, operator, "workpiece", req.Sn,
"拧紧不合格人工处置-确认放行", map[string]any{"reason": req.Reason, "disposedBy": operator, "disposedAt": now.Format(time.RFC3339)})
// 置对应 torque_ng 预警 resolved(状态变更 READ,不删行);幂等(已处置直接成功)。
alerts, _ := s.ctx.EntClient.Alert.Query().
Where(alert.Type("torque_ng"), alert.RefId(req.Sn), alert.Status("UNREAD")).All(ctx)
for _, a := range alerts {
_ = s.ResolveAlert(ctx, a.ID, operator)
}
return nil
}
// ProcessStepTemplate 下发给前端渲染的参数采集模板
type ProcessStepTemplate struct {
ID int `json:"id"`
Seq int `json:"seq"`
Name string `json:"name"`
CollectType string `json:"collectType"` // AUTO(拧紧枪自动)/MANUAL(手填)/SCAN(扫码,与手填等价)/NONE
NeedCheck bool `json:"needCheck"`
// 签字机制(需求B):操作工报工前须签字确认 / 检验员待签任务须签字确认方可流转
NeedOperatorSign bool `json:"needOperatorSign"`
NeedInspectorSign bool `json:"needInspectorSign"`
Remark string `json:"remark"`
Attachment []map[string]string `json:"attachment"` // 本步骤图纸/附件 [{name,url}],按工序分发到工位终端
Criteria []CriterionVO `json:"criteria"`
}
// CriterionVO 考核标准视图
type CriterionVO struct {
ID int `json:"id"`
Name string `json:"name"`
Unit string `json:"unit"`
Logic string `json:"logic"` // GE/LE/GT/LT/RANGE/EQUAL/NONE
Target float64 `json:"target"`
Min *float64 `json:"min"`
Max *float64 `json:"max"`
}
// ListStationSteps 按工位号加载该工位绑定且「启用」的工艺流程的工序步骤(含考核标准)。
// 链路:工位号 → station.flow_id → 工艺流程(绑定关系在「工位绑定」页维护,流程可绑任意工位)。
// 选工位 → 自动带出该工位的工序步骤(供巡检终端等按工位渲染)。
func (s *Service) ListStationSteps(ctx context.Context, stationNo int) ([]*ProcessStepTemplate, error) {
if stationNo < 1 {
return []*ProcessStepTemplate{}, nil
}
st, err := s.ctx.EntClient.Station.Query().Where(station.StationNo(stationNo)).First(ctx)
if err != nil || st.FlowId <= 0 {
// 该工位未绑定工艺流程:返回空模板(前端提示)
return []*ProcessStepTemplate{}, nil
}
flow, err := s.ctx.EntClient.ProcessFlow.Get(ctx, st.FlowId)
if err != nil || flow.Status != "ACTIVE" {
return []*ProcessStepTemplate{}, nil
}
return s.flowSteps(ctx, flow.ID), nil
}
// StepItemReq 一次保存的一个步骤(含其考核标准)
type StepItemReq struct {
ID int `json:"id"`
Seq int `json:"seq"`
Name string `json:"name"`
CollectType string `json:"collectType"`
NeedCheck bool `json:"needCheck"`
// 签字机制(需求B):保存工艺步骤时携带,落库到 process_step 表
NeedOperatorSign bool `json:"needOperatorSign"`
NeedInspectorSign bool `json:"needInspectorSign"`
Remark string `json:"remark"`
Attachment []map[string]string `json:"attachment"` // 本步骤图纸/附件 [{name,url}]
Criteria []CriterionVO `json:"criteria"`
}