1177 lines
50 KiB
Go
1177 lines
50 KiB
Go
package logic
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
"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"
|
||
"bj_power_mes/ent/workpieceprocess"
|
||
)
|
||
|
||
func itoa(n int) string { return strconv.Itoa(n) }
|
||
|
||
// joinIntsLocal 整数切片转逗号串(reonline 候选工位提示用,避免跨包依赖)。
|
||
func joinIntsLocal(ns []int) string {
|
||
p := make([]string, 0, len(ns))
|
||
for _, v := range ns {
|
||
p = append(p, itoa(v))
|
||
}
|
||
return strings.Join(p, ",")
|
||
}
|
||
|
||
// evalLogic 依据考核逻辑判定
|
||
func evalLogic(c *ent.StepCriterion, v float64) bool {
|
||
switch c.Logic {
|
||
case "GE":
|
||
return v >= c.Target
|
||
case "LE":
|
||
return v <= c.Target
|
||
case "GT":
|
||
return v > c.Target
|
||
case "LT":
|
||
return v < c.Target
|
||
case "RANGE":
|
||
l, r := true, true
|
||
if c.Min != nil {
|
||
l = v >= *c.Min
|
||
}
|
||
if c.Max != nil {
|
||
r = v <= *c.Max
|
||
}
|
||
return l && r
|
||
case "EQUAL":
|
||
return v == c.Target
|
||
default:
|
||
return true
|
||
}
|
||
}
|
||
|
||
type StepDataReq struct {
|
||
StepId int `json:"stepId"`
|
||
Name string `json:"name"`
|
||
Value float64 `json:"value"`
|
||
Text string `json:"text"`
|
||
// Checked:该步骤是否已完成「检测确认」。needCheck=true 的步骤必须为 true,服务端强校验,防止绕过前端。
|
||
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"`
|
||
WorkOrderId int `json:"workOrderId"`
|
||
StationNo int `json:"stationNo"` // 建档落点工位(必填;业务定稿·一.3/一.4/一.11)
|
||
PointNo string `json:"pointNo"` // 工件当前位置(产线点位台账编号:IN/C1/1-R1/工位号等);空=未选,不落账
|
||
}
|
||
|
||
// OnlineWorkpiece 工件进线登记(返回提示文案,供响应透出)。
|
||
// 执行路线 = 工单工艺组合(唯一路线源头),工件只需按组合逐工位报工推进。
|
||
// SN 口径按产品型号/物料档案 sn_mode 分流(2026-09-30 解耦定稿):
|
||
// - sn_mode=1 序列号=是:必须接收客户端扫入的来料 SN,校验其存在于 WMS SN 库存(已入库登记),
|
||
// 有效则工件 SN = 扫入SN(不再自动发号);
|
||
// - sn_mode=2 序列号=否:保持现状——终端自动发号后提交,MES 原样收号;
|
||
// - sn_mode=0 未选择:拒绝建档,报错提示先去产品型号/物料档案选择序列号=是。
|
||
//
|
||
// 重上线识别:workpiece 已存在且未完工 → 先调 SemiFlow(OUTBOUND)(WMS 半成品出库,
|
||
// 失败报错不继续、文案含 WMS 原文),再按工单工艺组合计算下一站并提示"继续执行:工位N·工艺名"。
|
||
// OnlineWorkpiece 工件进线登记(返回提示文案与 PLC↔MES 对账命中项,供响应透出)。
|
||
// 执行路线 = 工单工艺组合(唯一路线源头),工件只需按组合逐工位报工推进。
|
||
// SN 口径按产品型号/物料档案 sn_mode 分流(2026-09-30 解耦定稿):
|
||
// - sn_mode=1 序列号=是:必须接收客户端扫入的来料 SN,校验其存在于 WMS SN 库存(已入库登记),
|
||
// 有效则工件 SN = 扫入SN(不再自动发号);
|
||
// - sn_mode=2 序列号=否:保持现状——终端自动发号后提交,MES 原样收号;
|
||
// - sn_mode=0 未选择:拒绝建档,报错提示先去产品型号/物料档案选择序列号=是。
|
||
//
|
||
// PLC↔MES 对账(#8 T5 建档提交):建档成功后做单工位对账,命中则返回 mismatch(提示不拦),
|
||
// 供工位终端弹四选对话框(新件建档/绑定已知件/报异常/忽略)。
|
||
func (s *Service) OnlineWorkpiece(ctx context.Context, req OnlineReq, operator string) (string, *PlcMesMismatch, error) {
|
||
// 工件当前位置预检(建档前 fail-fast,点位不存在/被占用直接拒绝,不产生半量副作用)
|
||
if err := s.CheckPointFree(ctx, req.PointNo, req.Sn); err != nil {
|
||
return "", nil, err
|
||
}
|
||
// 重上线识别先于分流:重上线不涉及发号/SN 校验
|
||
if req.Sn != "" {
|
||
exist, err := s.ctx.EntClient.Workpiece.Query().Where(workpiece.Sn(req.Sn)).First(ctx)
|
||
if err != nil && !ent.IsNotFound(err) {
|
||
return "", nil, err
|
||
}
|
||
if exist != nil {
|
||
switch exist.Status {
|
||
case "DONE", "SCRAPPED":
|
||
return "", nil, errors.New("工件已完工/报废,不可重复上线登记")
|
||
case "NEW":
|
||
// 预生成 SN 首次上线建档:NEW→ONLINE,不涉及 WMS 出库;写物理位置+资格校验
|
||
return s.onlineNewWorkpiece(ctx, exist, req, operator)
|
||
default:
|
||
// ONLINE/PROCESSING/SEMI_STORED:重上线继续(半成品出库解锁一次上线资格)
|
||
return s.reonlineWorkpiece(ctx, exist, req, operator)
|
||
}
|
||
}
|
||
}
|
||
// 解析工单(sn_mode 挂在产品型号/物料档案上,必须先定位工单→产品)
|
||
if req.WorkOrderId == 0 && req.OrderNo != "" {
|
||
if wo, err := s.ctx.EntClient.WorkOrder.Query().Where(workorder.WorkOrderNo(req.OrderNo)).First(ctx); err == nil {
|
||
req.WorkOrderId = wo.ID
|
||
}
|
||
}
|
||
var wo *ent.WorkOrder
|
||
if req.WorkOrderId > 0 {
|
||
wo, _ = s.ctx.EntClient.WorkOrder.Get(ctx, req.WorkOrderId)
|
||
}
|
||
if wo == nil && req.OrderNo != "" {
|
||
wo, _ = s.ctx.EntClient.WorkOrder.Query().Where(workorder.WorkOrderNo(req.OrderNo)).First(ctx)
|
||
}
|
||
if wo == nil {
|
||
return "", nil, errors.New("工单不存在,无法确定序列号管理方式")
|
||
}
|
||
// SN 分流:读产品编码对应的物料档案 sn_mode(档案缺失视同未选择)
|
||
snMode := 0
|
||
if m, err := s.ctx.EntClient.Material.Query().Where(material.CodeEQ(wo.ProductCode)).First(ctx); err == nil {
|
||
snMode = m.SnMode
|
||
}
|
||
req.Sn = strings.TrimSpace(req.Sn)
|
||
switch snMode {
|
||
case 1: // 序列号=是:工件 SN = 扫入的来料 SN,须已在 WMS 入库登记
|
||
if req.Sn == "" {
|
||
return "", nil, errors.New("该物料按序列号管理:请扫描来料SN(已在WMS入库登记)")
|
||
}
|
||
_, sns, err := s.ctx.Wms.StockBatches(ctx, wo.ProductCode)
|
||
if err != nil {
|
||
return "", nil, fmt.Errorf("WMS SN 库存查询失败:%s", err.Error())
|
||
}
|
||
found := false
|
||
for _, sn := range sns {
|
||
if sn == req.Sn {
|
||
found = true
|
||
break
|
||
}
|
||
}
|
||
if !found {
|
||
return "", nil, fmt.Errorf("来料SN %s 不在 WMS 库存(请确认已在 WMS 入库登记)", req.Sn)
|
||
}
|
||
case 2: // 序列号=否:保持现状,终端自动发号后提交
|
||
if req.Sn == "" {
|
||
return "", nil, errors.New("sn 不能为空")
|
||
}
|
||
default: // 0=未选择(档案缺失/未配置)
|
||
return "", nil, errors.New("请先在产品型号/物料档案选择序列号管理方式(序列号=是/否)")
|
||
}
|
||
if err := s.ctx.EntClient.Workpiece.Create().
|
||
SetSn(req.Sn).SetOrderNo(req.OrderNo).SetWorkOrderId(req.WorkOrderId).
|
||
SetStatus("ONLINE").SetOnlineAt(time.Now()).SetAtStationNo(req.StationNo).Exec(ctx); err != nil {
|
||
return "", nil, err
|
||
}
|
||
// 二.2 物理位置:建档落点写入 at_station;三.2 状态流水 NEW→ONLINE
|
||
s.writeLifecycle(ctx, req.Sn, req.OrderNo, "NEW", "ONLINE", req.StationNo, 0, operator, "workstation", "上线建档")
|
||
s.ctx.EventLog.Write(ctx, "workpiece.online", req.OrderNo, operator, "workpiece", req.Sn,
|
||
"工件进线登记", map[string]any{"snMode": snMode, "stationNo": req.StationNo, "pointNo": req.PointNo,
|
||
"snSource": map[int]string{1: "SCANNED", 2: "AUTO"}[snMode]})
|
||
// 工件当前位置落账(点位台账:建档即占位;PointNo 空=未选,跳过)
|
||
if err := s.occupyStartPoint(ctx, req.PointNo, req.Sn, req.OrderNo, operator); err != nil {
|
||
return "", nil, err
|
||
}
|
||
s.notifyDashboard()
|
||
// PLC↔MES 对账(#8 T5 建档提交):提示不拦,仅透出 mismatch 供终端弹窗
|
||
mm, _ := s.detectAndRecord(ctx, req.StationNo, "terminal", req.OrderNo, operator)
|
||
return "进线登记成功", mm, nil
|
||
}
|
||
|
||
// reonlineWorkpiece 重上线(暂存退库后再次进线):
|
||
// ① 先校验:工单组合非空且存在下一站(stationNo > currentStationNo),无副作用不通过即拒绝;
|
||
// ② 再调 SemiFlow(OUTBOUND) 让 WMS 半成品出库,失败则报错不继续(文案含 WMS 原文)——
|
||
//
|
||
// 顺序保证:校验全部通过后才产生出库这一副作用,避免"已出库却登记失败"的悬挂状态;
|
||
//
|
||
// ③ 下一站工位当天停单时提示"工位N已停止接单"(复用 GetStationPaused 既有停单判定,不阻断登记)。
|
||
// onlineNewWorkpiece 预生成 SN 首次上线建档(NEW→ONLINE)。
|
||
// 二.4 资格校验:新件必须落点在工序1工位(工艺组合中工位号最小者),落点必填。
|
||
// 不涉及 WMS 出库(从未入半成品库);写物理位置 at_station=落点,记生命周期 NEW→ONLINE。
|
||
func (s *Service) onlineNewWorkpiece(ctx context.Context, wp *ent.Workpiece, req OnlineReq, operator string) (string, *PlcMesMismatch, error) {
|
||
wo := s.workpieceWorkOrder(ctx, wp)
|
||
items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, wo)
|
||
if len(items) == 0 {
|
||
return "", nil, errors.New("工单未配置工艺组合")
|
||
}
|
||
// 并行候选工位:新件建档可落在「首道工序」的任一候选工位(闲着的工位去哪个)
|
||
route := groupFlowRoute(items)
|
||
firstStations := route[0].Stations
|
||
if req.StationNo == 0 {
|
||
return "", nil, errors.New("建档落点工位必填")
|
||
}
|
||
if !intsContains(firstStations, req.StationNo) {
|
||
return "", nil, fmt.Errorf("新件建档必须落在第1道工序的候选工位(%s)之一,当前落点工位%d不符合资格",
|
||
joinIntsLocal(firstStations), req.StationNo)
|
||
}
|
||
station := req.StationNo
|
||
if _, e := s.ctx.EntClient.Workpiece.UpdateOneID(wp.ID).
|
||
SetStatus("ONLINE").SetOnlineAt(time.Now()).SetAtStationNo(station).Save(ctx); e != nil {
|
||
return "", nil, e
|
||
}
|
||
// 二.2 物理位置 + 三.2 状态流水 NEW→ONLINE
|
||
s.writeLifecycle(ctx, wp.Sn, wp.OrderNo, "NEW", "ONLINE", station, 0, operator, "workstation", "上线建档")
|
||
s.ctx.EventLog.Write(ctx, "workpiece.online", wp.OrderNo, operator, "workpiece", wp.Sn,
|
||
"预生成SN上线建档", map[string]any{"stationNo": station, "pointNo": req.PointNo})
|
||
// 工件当前位置落账(点位台账:建档即占位)
|
||
if err := s.occupyStartPoint(ctx, req.PointNo, wp.Sn, wp.OrderNo, operator); err != nil {
|
||
return "", nil, err
|
||
}
|
||
s.notifyDashboard()
|
||
// PLC↔MES 对账(#8 T5 建档提交):提示不拦,仅透出 mismatch 供终端弹窗
|
||
mm, _ := s.detectAndRecord(ctx, station, "terminal", wp.OrderNo, operator)
|
||
return "进线登记成功", mm, nil
|
||
}
|
||
|
||
// reonlineWorkpiece 重上线(暂存退库后再次进线):
|
||
// ① 先校验:工单组合非空且存在下一站(stationNo > currentStationNo),无副作用不通过即拒绝;
|
||
// ② 再调 SemiFlow(OUTBOUND) 让 WMS 半成品出库,失败则报错不继续(文案含 WMS 原文)——
|
||
// 顺序保证:校验全部通过后才产生出库这一副作用,避免"已出库却登记失败"的悬挂状态;
|
||
// ③ 下一站工位当天停单时提示"工位N已停止接单"(复用 GetStationPaused 既有停单判定,不阻断登记)。
|
||
// 出库一次解锁一次(业务定稿·一.5):置回 ONLINE 并写物理位置 at_station=下一站;记生命周期 SEMI_OUT。
|
||
func (s *Service) reonlineWorkpiece(ctx context.Context, wp *ent.Workpiece, req OnlineReq, operator string) (string, *PlcMesMismatch, error) {
|
||
items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, s.workpieceWorkOrder(ctx, wp))
|
||
if len(items) == 0 {
|
||
return "", nil, errors.New("工单未配置工艺组合")
|
||
}
|
||
route := groupFlowRoute(items)
|
||
nextSeq, doneAll := s.firstUndoneFlowSeq(ctx, s.ctx.EntClient, wp.Sn, route)
|
||
if doneAll {
|
||
return "", nil, fmt.Errorf("工件已报工至最后一道工序,工艺组合中无下一站")
|
||
}
|
||
var nextFlow *FlowRouteStep
|
||
for i := range route {
|
||
if route[i].Seq == nextSeq {
|
||
nextFlow = &route[i]
|
||
break
|
||
}
|
||
}
|
||
next := nextFlow.MinNo
|
||
// 二.4 资格校验:半成品(SEMI_STORED)重上线落点须为下一工序的候选工位之一;落点未传时按下一工序最小工位执行
|
||
if req.StationNo > 0 && !intsContains(nextFlow.Stations, req.StationNo) {
|
||
return "", nil, fmt.Errorf("半成品重上线须落在下一工序(候选工位%s)内,当前落点工位%d不符合资格",
|
||
joinIntsLocal(nextFlow.Stations), req.StationNo)
|
||
}
|
||
if err := s.SemiFlow(ctx, SemiReq{Sn: wp.Sn, OrderNo: wp.OrderNo, Action: "OUTBOUND"}, operator); err != nil {
|
||
return "", nil, fmt.Errorf("重上线失败:%s", err.Error())
|
||
}
|
||
// 出库一次解锁一次(问题.md 一.5):置回 ONLINE,写物理位置=所选落点(缺省下一工序最小工位),等待在所选工位重新上线建档。
|
||
land := req.StationNo
|
||
if land == 0 {
|
||
land = next
|
||
}
|
||
if _, e := s.ctx.EntClient.Workpiece.UpdateOneID(wp.ID).
|
||
SetStatus("ONLINE").SetAtStationNo(land).Save(ctx); e != nil {
|
||
return "", nil, fmt.Errorf("重上线解锁状态失败:%s", e.Error())
|
||
}
|
||
// 二.2 物理位置 + 三.2 状态流水 SEMI_STORED→ONLINE(出库 SEMI_OUT)
|
||
s.writeLifecycle(ctx, wp.Sn, wp.OrderNo, "SEMI_STORED", "ONLINE", land, 0, operator, "workstation", "半成品出库重上线")
|
||
msg := fmt.Sprintf("重上线成功,继续执行:工位%d·%s", land, s.flowNameById(ctx, nextFlow.FlowId))
|
||
if s.GetStationPaused(ctx, land) {
|
||
msg += "(注意:工位" + itoa(land) + "已停止接单)"
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "workpiece.reonline", wp.OrderNo, operator, "workpiece", wp.Sn,
|
||
"工件重上线(暂存退库后出库继续)", map[string]any{"nextStationNo": land, "nextFlowId": nextFlow.FlowId, "pointNo": req.PointNo})
|
||
// 工件当前位置落账(点位台账:重上线即占位)
|
||
if err := s.occupyStartPoint(ctx, req.PointNo, wp.Sn, wp.OrderNo, operator); err != nil {
|
||
return "", nil, err
|
||
}
|
||
s.notifyDashboard()
|
||
// PLC↔MES 对账(#8 T5 建档提交):提示不拦,仅透出 mismatch 供终端弹窗
|
||
mm, _ := s.detectAndRecord(ctx, land, "terminal", wp.OrderNo, operator)
|
||
return msg, mm, nil
|
||
}
|
||
|
||
// occupyStartPoint 建档落账:把工件当前位置(产线点位台账)记为占用。
|
||
// pointNo 空=终端未选位置(旧模型兼容),跳过不报错;调用前须已过 CheckPointFree 预检。
|
||
func (s *Service) occupyStartPoint(ctx context.Context, pointNo, sn, orderNo, operator string) error {
|
||
if strings.TrimSpace(pointNo) == "" {
|
||
return nil
|
||
}
|
||
return s.OccupyPoint(ctx, pointNo, sn, orderNo, operator, "IN")
|
||
}
|
||
|
||
// writeLifecycle 写工件生命周期状态流水(三.2 / P2 定稿:所有 status 变更点同事务写)。
|
||
// action 值域:NEW/ONLINE/REPORT/SEMI_IN/SEMI_OUT/DONE/SCRAPPED;from/to 为变更前后状态。
|
||
// 入库次数统一 count(action='SEMI_IN'),不再依赖 semiflow(CountSemiStored 已删)。
|
||
func (s *Service) writeLifecycle(ctx context.Context, sn, orderNo, from, to string, stationNo, flowSeq int, operator, source, remark string) {
|
||
if sn == "" {
|
||
return
|
||
}
|
||
_, _ = s.ctx.EntClient.WorkpieceLifecycleLog.Create().
|
||
SetSn(sn).SetWorkOrderNo(orderNo).SetAction(toAction(to, from)).
|
||
SetFromStatus(from).SetToStatus(to).SetStationNo(stationNo).SetFlowSeq(flowSeq).
|
||
SetOperator(operator).SetSource(source).SetRemark(remark).Save(ctx)
|
||
}
|
||
|
||
// toAction 由 状态变更 推导 lifecycle action(三.2 枚举)。
|
||
func toAction(to, from string) string {
|
||
switch to {
|
||
case "ONLINE":
|
||
return "ONLINE"
|
||
case "PROCESSING":
|
||
return "REPORT"
|
||
case "SEMI_STORED":
|
||
return "SEMI_IN"
|
||
case "DONE":
|
||
return "DONE"
|
||
case "SCRAPPED":
|
||
return "SCRAPPED"
|
||
case "NEW":
|
||
return "NEW"
|
||
}
|
||
if from == "SEMI_STORED" && to == "ONLINE" {
|
||
return "SEMI_OUT"
|
||
}
|
||
return to
|
||
}
|
||
|
||
// workpieceWorkOrder 取工件所属工单:优先 workOrderId,缺失按 orderNo 兜底解析
|
||
func (s *Service) workpieceWorkOrder(ctx context.Context, wp *ent.Workpiece) *ent.WorkOrder {
|
||
if wp.WorkOrderId > 0 {
|
||
if wo, err := s.ctx.EntClient.WorkOrder.Get(ctx, wp.WorkOrderId); err == nil {
|
||
return wo
|
||
}
|
||
}
|
||
if wp.OrderNo != "" {
|
||
if wo, err := s.ctx.EntClient.WorkOrder.Query().Where(workorder.WorkOrderNo(wp.OrderNo)).First(ctx); err == nil {
|
||
return wo
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
type ReportProcessReq struct {
|
||
Sn string `json:"sn"`
|
||
FlowId int `json:"flowId"` // 报工工艺(缺省回退工位当前绑定的工艺)
|
||
StationNo int `json:"stationNo"`
|
||
Operator string `json:"operator"` // 操作工(工位终端登录人注入;内部接口无 JWT 时作为操作人来源,杜绝「system」伪造留痕)
|
||
Steps []StepDataReq `json:"steps"`
|
||
// 签字确认(需求B):needOperatorSign 步骤须带操作工签字(签字确认弹框采集),服务端强校验并落库
|
||
Signs []StepSignInput `json:"signs"`
|
||
Binds []BindItemReq `json:"binds"` // 装机绑定(本工序装配物料:序列号=否填批次号/序列号=是填SN),随报工原子提交
|
||
// 作业时长采集(方案 M / P0-3):工位终端在「上料到本工位」时采 startedAt、点「报工」时采 endedAt,
|
||
// 两端时间戳同源于终端时钟(ISO8601),离线重传也不失真;缺失则回退服务端当前时刻(时长=0)。
|
||
StartedAt string `json:"startedAt"`
|
||
EndedAt string `json:"endedAt"`
|
||
}
|
||
|
||
// parseClientTime 解析工位终端上报的 ISO8601 时间戳(兼容带/不带毫秒、Z/时区偏移)。
|
||
func parseClientTime(s string) (time.Time, error) {
|
||
s = strings.TrimSpace(s)
|
||
if s == "" {
|
||
return time.Time{}, errors.New("empty time")
|
||
}
|
||
layouts := []string{time.RFC3339Nano, time.RFC3339, "2006-01-02T15:04:05", "2006-01-02 15:04:05"}
|
||
for _, l := range layouts {
|
||
if t, err := time.Parse(l, s); err == nil {
|
||
return t, nil
|
||
}
|
||
}
|
||
return time.Time{}, errors.New("unrecognized time format: " + s)
|
||
}
|
||
|
||
// ReportProcess 工位报工:先应用装机绑定并做强校验(齐套才放行),再写报工实绩 + 步骤考核。
|
||
// 绑料是"落到工艺"的强约束:工艺物料清单(flow_material)中要求装配的物料必须绑齐,
|
||
// 电气件按单台用量逐颗SN、结构件至少一个批次号;缺料直接拒绝报工并返回缺料清单。
|
||
// 顺序校验(工单工艺组合为唯一路线源头):报工工位必须在组合中、工艺匹配,且不可倒序(可跳过未选工位)。
|
||
func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, operator string, operatorId int) error {
|
||
if req.Sn == "" || req.StationNo == 0 {
|
||
return errors.New("sn 与 stationNo 必填")
|
||
}
|
||
// PLC↔MES 对账(#8 T4 报工提交):命中 mismatch 则阻断报工,提示先处理该工位托盘位异常
|
||
// (新件建档 / 绑定已知件),避免在无 MES 在制工件状态下误报工。
|
||
if m, _ := s.detectAndRecord(ctx, req.StationNo, "report", "", operator); m != nil {
|
||
return fmt.Errorf("PLC与MES对账不一致:%s。请先处理该工位托盘位异常(新件建档 / 绑定已知件)后再报工", m.Detail)
|
||
}
|
||
wp, err := s.ctx.EntClient.Workpiece.Query().Where(workpiece.Sn(req.Sn)).First(ctx)
|
||
if err != nil {
|
||
return errors.New("工件未进线登记")
|
||
}
|
||
// B6 拧紧闭环:NG 未处置件阻断报工(含当前工位本次报工)——须先质检/班组长确认放行(DisposeTorqueNg)。
|
||
if wp.TorqueNgPending {
|
||
return errors.New("该工件拧紧扭矩不合格,待人工处置(质检/班组长确认放行)后方可继续报工")
|
||
}
|
||
// 严格校验(业务口径已确认):仅“在制”工件可报工;DONE/SCRAPPED 一律拒绝(REPAIR 已退役)。
|
||
if wp.Status != "ONLINE" && wp.Status != "PROCESSING" {
|
||
return errors.New("工件当前状态为「" + wp.Status + "」,非在制,不允许报工")
|
||
}
|
||
// 工艺解析:优先取报工传入 flowId;缺省回退工位当前绑定的工艺
|
||
flowId := req.FlowId
|
||
if flowId <= 0 {
|
||
if st, e := s.ctx.EntClient.Station.Query().Where(station.StationNo(req.StationNo)).First(ctx); e == nil {
|
||
flowId = st.FlowId
|
||
}
|
||
}
|
||
if flowId <= 0 {
|
||
return errors.New("无法确定报工工艺:请传 flowId 或确认工位已绑定工艺")
|
||
}
|
||
// 组合校验:报工条目必须在工单工艺组合中且工艺匹配;不可倒序(工位号即顺序号)
|
||
wo, err := s.ctx.EntClient.WorkOrder.Get(ctx, wp.WorkOrderId)
|
||
if err != nil || wo == nil {
|
||
return errors.New("工件所属工单不存在")
|
||
}
|
||
// 并行候选工位模型(2026-11-02):同工序可配置多个候选工位,工件在任一候选工位报工一次即完成该工序;
|
||
// 不可跳工序(须按工序顺序),同工序已报工则不可重复报工。
|
||
route, _ := FlowRouteOfWO(ctx, s.ctx.EntClient, wo)
|
||
if len(route) == 0 {
|
||
return errors.New("工单未配置工艺组合")
|
||
}
|
||
var cur *FlowRouteStep
|
||
for i := range route {
|
||
if route[i].FlowId == flowId && intsContains(route[i].Stations, req.StationNo) {
|
||
cur = &route[i]
|
||
break
|
||
}
|
||
}
|
||
if cur == nil {
|
||
return fmt.Errorf("工位%d不在该工序「%s」的候选工位中,不可报工", req.StationNo, s.flowNameById(ctx, flowId))
|
||
}
|
||
// 不可跳工序 / 不可重复:本工序必须是第一个「尚未有 DONE 报工」的工序
|
||
nextSeq, doneAll := s.firstUndoneFlowSeq(ctx, s.ctx.EntClient, req.Sn, route)
|
||
if doneAll {
|
||
return errors.New("该工件所有工序已报工完成")
|
||
}
|
||
if cur.Seq != nextSeq {
|
||
if done, _ := s.ctx.EntClient.WorkpieceProcess.Query().
|
||
Where(workpieceprocess.Sn(req.Sn), workpieceprocess.FlowId(flowId), workpieceprocess.Status("DONE")).Exist(ctx); done {
|
||
return errors.New("该工序已报工完成,不可重复报工")
|
||
}
|
||
return errors.New("不可跳工序:请先完成上一道工序")
|
||
}
|
||
// 报工是"装机绑定→校验齐套→写实绩→写步骤考核→回写结果/工件状态"的多步写,必须整体事务化(方案 U3):
|
||
// 任一步失败全部回滚,杜绝"实绩已建但工件状态没推进/结果没落"的半成品脏数据;
|
||
// 校验(齐套/needCheck)也走同一 tx client,才能读到本事务内刚写入的绑定。
|
||
tx, err := s.ctx.EntClient.Tx(ctx)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
committed := false
|
||
defer func() {
|
||
if !committed {
|
||
_ = tx.Rollback()
|
||
}
|
||
}()
|
||
client := tx.Client()
|
||
// 阶段1:装机绑定(随报工提交)→ 落库后强校验齐套
|
||
stationNo := ""
|
||
if req.StationNo > 0 {
|
||
stationNo = itoa(req.StationNo)
|
||
}
|
||
if _, err := s.applyBinds(ctx, client, req.Sn, wp.OrderNo, flowId, stationNo, operator, req.Binds); err != nil {
|
||
return err
|
||
}
|
||
if miss, err := s.validateStationBinds(ctx, client, req.Sn, flowId); err != nil {
|
||
return err
|
||
} else if miss != "" {
|
||
return errors.New(miss)
|
||
}
|
||
// 阶段2:检测确认(needCheck)强校验——服务端为准,前端勾选只是辅助提示。
|
||
// 本工位在本工艺组合中的出现序号 k 对应步骤 seq=k,标记“需要检测确认”的步骤须带 checked=true。
|
||
// k 由组合派生(第 k 次出现 ↔ 步骤 seq=k),与签字校验同源,避免跨工位误拦。
|
||
// 并行候选工位:每道工序只报工一次(对应一次步骤序号),与历史「1工序1工位」语义一致,k 恒为 1
|
||
k := 1
|
||
if err := s.validateNeedCheck(ctx, client, req, flowId, k); err != nil {
|
||
return err
|
||
}
|
||
// 阶段2.5:签字机制(需求B)强校验 + 落操作工签字(needOperatorSign 步骤)。
|
||
// needInspectorSign 步骤要求检验员已在巡检终端「待签任务」页签签字,否则拒流转。
|
||
// 校验同时返回 k(同 stationSeqInFlow),供落签字时同范围使用。
|
||
k, err = s.validateNeedSign(ctx, client, req, flowId, k)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if err := s.writeOperatorSigns(ctx, client, req, flowId, k, wp.OrderNo, operator); err != nil {
|
||
return err
|
||
}
|
||
now := time.Now()
|
||
// 作业时长(方案 M / P0-3):startedAt=进工位(上料)时刻、endedAt=报工时刻,均由工位终端采集;
|
||
// 缺失或非法则回退到服务端当前时刻(durationSec=0),时钟回拨导致负数则时长归零。
|
||
startedAt, endedAt := now, now
|
||
if t, e := parseClientTime(req.StartedAt); e == nil {
|
||
startedAt = t
|
||
}
|
||
if t, e := parseClientTime(req.EndedAt); e == nil {
|
||
endedAt = t
|
||
}
|
||
durationSec := int(endedAt.Sub(startedAt).Seconds())
|
||
if durationSec < 0 {
|
||
durationSec = 0
|
||
endedAt = startedAt
|
||
}
|
||
proc, err := client.WorkpieceProcess.Create().
|
||
SetSn(req.Sn).SetFlowId(flowId).
|
||
SetStationNo(itoa(req.StationNo)).SetOrderNo(wp.OrderNo).
|
||
SetProcessName(s.flowNameById(ctx, flowId)).
|
||
SetStatus("DONE").SetOperator(operator).SetOperatorId(operatorId).SetResult("OK").
|
||
SetStartedAt(startedAt).SetEndedAt(endedAt).SetDurationSec(durationSec).Save(ctx)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
|
||
allOK := true
|
||
for _, st := range req.Steps {
|
||
ok, e := s.writeStepData(ctx, client, req.Sn, proc.ID, st, operator)
|
||
if e != nil {
|
||
return e
|
||
}
|
||
if !ok {
|
||
allOK = false
|
||
}
|
||
}
|
||
if bad, e := client.StepData.Query().
|
||
Where(stepdata.ProcessId(proc.ID), stepdata.IsOK(false)).Exist(ctx); e != nil {
|
||
return e
|
||
} else if bad {
|
||
allOK = false
|
||
}
|
||
result := "OK"
|
||
if !allOK {
|
||
result = "NG"
|
||
}
|
||
if _, err := client.WorkpieceProcess.UpdateOneID(proc.ID).SetResult(result).Save(ctx); err != nil {
|
||
return err
|
||
}
|
||
if _, err := client.Workpiece.UpdateOneID(wp.ID).
|
||
SetCurrentStationNo(req.StationNo).SetAtStationNo(req.StationNo).SetStatus("PROCESSING").Save(ctx); err != nil {
|
||
return err
|
||
}
|
||
// 二.2 物理位置随报工推进 + 三.2 状态流水 REPORT(同事务)
|
||
if _, err := client.WorkpieceLifecycleLog.Create().
|
||
SetSn(req.Sn).SetWorkOrderNo(wp.OrderNo).SetAction("REPORT").
|
||
SetFromStatus(wp.Status).SetToStatus("PROCESSING").SetStationNo(req.StationNo).
|
||
SetOperator(operator).SetSource("workstation").SetRemark("工位报工").Save(ctx); err != nil {
|
||
return err
|
||
}
|
||
if err := tx.Commit(); err != nil {
|
||
return err
|
||
}
|
||
committed = true
|
||
|
||
s.ctx.EventLog.Write(ctx, "workpiece.process.report", wp.OrderNo, operator, "workpiece", req.Sn,
|
||
"工位报工", map[string]any{"flowId": flowId, "stationNo": req.StationNo, "result": result})
|
||
s.notifyDashboard()
|
||
return nil
|
||
}
|
||
|
||
// validateNeedCheck 检测确认(needCheck)服务端强校验。
|
||
// 规则:本工位在本工艺组合中的出现序号 k 对应的步骤(seq=k),凡标记 needCheck=true,
|
||
// 报工请求里必须存在对应 stepId 且 checked=true 的步骤数据;缺失则拒绝报工。
|
||
// 与 validateNeedSign 同源:跨工位的检测确认步骤不应在本工位报工时被要求(2026-10-08 审核修正)。
|
||
// 工位不在组合中、或本步骤非 needCheck 时不拦截(与现场配置保持一致)。
|
||
func (s *Service) validateNeedCheck(ctx context.Context, client *ent.Client, req ReportProcessReq, flowId, k int) error {
|
||
if req.StationNo <= 0 || flowId <= 0 || k <= 0 {
|
||
return nil
|
||
}
|
||
steps, err := client.ProcessStep.Query().
|
||
Where(processstep.FlowId(flowId), processstep.NeedCheck(true), processstep.Seq(k)).All(ctx)
|
||
if err != nil || len(steps) == 0 {
|
||
return nil
|
||
}
|
||
checked := map[int]bool{}
|
||
for _, sd := range req.Steps {
|
||
if sd.Checked {
|
||
checked[sd.StepId] = true
|
||
}
|
||
}
|
||
missing := make([]string, 0, len(steps))
|
||
for _, ps := range steps {
|
||
if !checked[ps.ID] {
|
||
name := ps.Name
|
||
if name == "" {
|
||
name = "步骤" + itoa(ps.ID)
|
||
}
|
||
missing = append(missing, name)
|
||
}
|
||
}
|
||
if len(missing) > 0 {
|
||
return errors.New("以下步骤需先完成检测确认后方可报工:" + strings.Join(missing, "、"))
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// stationSeqInFlow 返回工位在指定工艺组合中的出现序号 k(按工位号升序的第 k 次出现,从 1 起)。
|
||
// 语义:组合条目 ↔ 工艺步骤 seq 一一对应(第 k 次出现 ↔ 步骤 seq=k)。不在组合中返回 0。
|
||
func stationSeqInFlow(items []FlowItem, flowId, stationNo int) int {
|
||
k, cur := 0, 0
|
||
for _, it := range items {
|
||
if it.FlowId != flowId {
|
||
continue
|
||
}
|
||
cur++
|
||
if it.StationNo == stationNo {
|
||
k = cur
|
||
break
|
||
}
|
||
}
|
||
return k
|
||
}
|
||
|
||
// firstUndoneFlowSeq 返回工件尚未完成(无 DONE 报工记录)的第一道工序序号(route.Seq);
|
||
// 全部完成返回 (0, true)。并行候选工位模型下,工序完成以「该工序任一候选工位已报工 DONE」判定。
|
||
func (s *Service) firstUndoneFlowSeq(ctx context.Context, client *ent.Client, sn string, route []FlowRouteStep) (int, bool) {
|
||
for _, f := range route {
|
||
done, _ := client.WorkpieceProcess.Query().
|
||
Where(workpieceprocess.Sn(sn), workpieceprocess.FlowId(f.FlowId), workpieceprocess.Status("DONE")).Exist(ctx)
|
||
if !done {
|
||
return f.Seq, false
|
||
}
|
||
}
|
||
return 0, true
|
||
}
|
||
|
||
// validateNeedSign 签字机制(需求B)服务端强校验,返回本工位在本工艺组合中的出现序号 k:
|
||
// 组合条目(按工位号升序)与工艺步骤 seq 一一对应——本工艺在组合中第 k 次出现 ↔ 步骤 seq=k。
|
||
// - needOperatorSign:仅校验「本次报工步骤」(seq=k),报工请求必须携带对应操作工签字;
|
||
// 随报工事务落 step_sign_record(signRole=OPERATOR)(writeOperatorSigns,同样限 seq=k)。
|
||
// - needInspectorSign:仅校验「历史步骤」(seq<k),检验员 OK 签字必须已存在方可流转到本工位——
|
||
// 本步骤的检验员签字发生在本工位报工之后(巡检终端待签任务),若在报工时校验本步骤
|
||
// 会与「检验员签字前置=操作工已签字」形成死锁(2026-10-08 闭环联调实测确认并修复)。
|
||
// k=0 表示工位不在组合中(不拦截);工位在组合中但流程内无签字步骤时原样返回 k 供调用方复用。
|
||
func (s *Service) validateNeedSign(ctx context.Context, client *ent.Client, req ReportProcessReq, flowId, k int) (int, error) {
|
||
if req.StationNo <= 0 || flowId <= 0 || k <= 0 {
|
||
return k, 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 k, 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 && ps.Seq == k {
|
||
// 当前报工步骤:必须有操作工签字(随报工落库)
|
||
sg, ok := signMap[ps.ID]
|
||
if !ok || strings.TrimSpace(sg.Signer) == "" {
|
||
name := ps.Name
|
||
if name == "" {
|
||
name = "步骤" + itoa(ps.ID)
|
||
}
|
||
return k, errors.New("以下步骤需操作工签字确认后才能报工:" + name)
|
||
}
|
||
}
|
||
if ps.NeedInspectorSign && ps.Seq < k {
|
||
// 历史步骤(已报工、待流转):检验员必须「签字确认」(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 k, e
|
||
}
|
||
if !has {
|
||
name := ps.Name
|
||
if name == "" {
|
||
name = "步骤" + itoa(ps.ID)
|
||
}
|
||
return k, errors.New("以下步骤需检验员签字确认(合格)后才能流转:" + name)
|
||
}
|
||
}
|
||
}
|
||
return k, nil
|
||
}
|
||
|
||
// writeOperatorSigns 在报工事务内落操作工签字(needOperatorSign 步骤,签字确认弹框采集);
|
||
// 仅落「本次报工步骤」(seq=k,与 validateNeedSign 校验范围一致),按唯一索引
|
||
// (sn, stationNo, stepId, signRole=OPERATOR, round) 去重,避免重报产生重复签字。
|
||
// orderNo 取自工件所属工单(wp.OrderNo),签字记录随单追溯。
|
||
func (s *Service) writeOperatorSigns(ctx context.Context, client *ent.Client, req ReportProcessReq, flowId, k int, orderNo, operator string) error {
|
||
steps, err := client.ProcessStep.Query().
|
||
Where(processstep.FlowId(flowId), processstep.NeedOperatorSign(true), processstep.Seq(k)).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
|
||
crits, err := client.StepCriterion.Query().Where(stepcriterion.StepId(st.StepId)).All(ctx)
|
||
if err != nil {
|
||
return false, err
|
||
}
|
||
for _, c := range crits {
|
||
if !evalLogic(c, st.Value) {
|
||
ok = false
|
||
}
|
||
}
|
||
var cname, clogic string
|
||
cid := 0
|
||
if len(crits) > 0 {
|
||
cname = crits[0].Name
|
||
clogic = crits[0].Logic
|
||
cid = crits[0].ID
|
||
}
|
||
_, err = client.StepData.Create().
|
||
SetSn(sn).SetProcessId(processId).SetStepId(st.StepId).
|
||
SetStepName(st.Name).SetCriterionId(cid).SetCriterionName(cname).
|
||
SetCriterionLogic(clogic).SetValue(st.Value).SetValueText(st.Text).
|
||
SetIsOK(ok).SetOperator(operator).Save(ctx)
|
||
return ok, err
|
||
}
|
||
|
||
// DoneReq 完工 + 成品关联追溯
|
||
type DoneReq struct {
|
||
Sn string `json:"sn"`
|
||
BatchItems []string `json:"batchItems"` // 序列号=否:批次号
|
||
SerialItems []string `json:"serialItems"` // 序列号=是:SN
|
||
PointNo string `json:"pointNo"` // 下料落点(产线点位台账编号:END-U 上排/END-D 下排);空=未选,不落账
|
||
}
|
||
|
||
// DoneWorkpiece 完工:先兜底校验全部工序装配物料齐套(工艺流程强校验),再登记成品并生成关联追溯
|
||
func (s *Service) DoneWorkpiece(ctx context.Context, req DoneReq, operator string) error {
|
||
// 下料落点预检(完工前 fail-fast:落点不存在/被占用直接拒绝,避免完工后无法落账)
|
||
if err := s.CheckPointFree(ctx, req.PointNo, req.Sn); err != nil {
|
||
return err
|
||
}
|
||
wp, err := s.ctx.EntClient.Workpiece.Query().Where(workpiece.Sn(req.Sn)).First(ctx)
|
||
if err != nil {
|
||
return errors.New("工件不存在")
|
||
}
|
||
// B6 拧紧闭环:NG 未处置件阻断下线完工(否则可从"下线"绕开报工拦截出线,闭环形同虚设)。
|
||
if wp.TorqueNgPending {
|
||
return errors.New("该工件拧紧扭矩不合格,待人工处置(质检/班组长确认放行)后方可下线完工")
|
||
}
|
||
// 兜底强校验:工单工艺组合中每个工艺的装配物料都须绑齐(工艺未配置物料清单时自动放行)
|
||
wo, err := s.ctx.EntClient.WorkOrder.Get(ctx, wp.WorkOrderId)
|
||
if err != nil || wo == nil {
|
||
return errors.New("工件所属工单不存在")
|
||
}
|
||
if miss, err := s.validateAllFlows(ctx, s.ctx.EntClient, req.Sn, wo); err != nil {
|
||
return err
|
||
} else if miss != "" {
|
||
return errors.New("完工前必须绑齐全部装配物料:" + miss)
|
||
}
|
||
// 下线完工分流(问题.md 二.2 + 一.7):不强制最后一道工序,任何工序均可下线;
|
||
// 成品工艺已全部报工→DONE(完工);未全部完成→SEMI_STORED(半成品入库)。
|
||
// 二.2 物理位置:完工/入库均清空 at_station(件已离产线/入半成品库)。
|
||
// 三.2 入库次数统一 count(action='SEMI_IN'),不再依赖 semiflow(CountSemiStored 已删)。
|
||
routeItems, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, wo)
|
||
routeCount := DistinctFlowCount(routeItems) // 并行候选工位:按工序数判定,而非工位数
|
||
reported := 0
|
||
if routeCount > 0 {
|
||
reported, _ = s.ctx.EntClient.WorkpieceProcess.Query().
|
||
Where(workpieceprocess.Sn(req.Sn), workpieceprocess.Status("DONE")).Count(ctx)
|
||
}
|
||
status := "DONE"
|
||
if routeCount > 0 && reported < routeCount {
|
||
status = "SEMI_STORED"
|
||
}
|
||
now := time.Now()
|
||
upd := s.ctx.EntClient.Workpiece.UpdateOneID(wp.ID).SetStatus(status).SetAtStationNo(0)
|
||
if status == "DONE" {
|
||
upd = upd.SetDoneAt(now)
|
||
}
|
||
if _, err := upd.Save(ctx); err != nil {
|
||
return err
|
||
}
|
||
// 三.2 状态流水:DONE→DONE;SEMI_STORED→补 INBOUND 缺口(SEMI_IN)
|
||
s.writeLifecycle(ctx, req.Sn, wp.OrderNo, wp.Status, status, 0, 0, operator, "workstation", "下线完工")
|
||
// 下料落点落账(点位台账:完工/半成品入库均登记末端下料检测位占用)
|
||
if err := s.occupyStartPoint(ctx, req.PointNo, req.Sn, wp.OrderNo, operator); err != nil {
|
||
return err
|
||
}
|
||
if status == "DONE" {
|
||
existID, _ := s.ctx.EntClient.AssociationTrace.Query().
|
||
Where(associationtrace.FinishedSn(req.Sn)).FirstID(ctx)
|
||
if existID > 0 {
|
||
_, _ = s.ctx.EntClient.AssociationTrace.UpdateOneID(existID).
|
||
SetBatchItems(req.BatchItems).SetSerialItems(req.SerialItems).SetOperator(operator).Save(ctx)
|
||
} else {
|
||
routeStr := ""
|
||
if items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, wo); len(items) > 0 {
|
||
routeStr = RouteStationsStrOfWO(items)
|
||
}
|
||
if _, cerr := s.ctx.EntClient.AssociationTrace.Create().
|
||
SetFinishedSn(req.Sn).SetOrderNo(wp.OrderNo).SetProcessCode(routeStr).
|
||
SetBatchItems(req.BatchItems).SetSerialItems(req.SerialItems).
|
||
SetOperator(operator).Save(ctx); cerr != nil {
|
||
return cerr
|
||
}
|
||
}
|
||
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, "pointNo": req.PointNo})
|
||
} else {
|
||
s.ctx.EventLog.Write(ctx, "workpiece.semi_stored", wp.OrderNo, operator, "workpiece", req.Sn, "下线完工(半成品入库)", map[string]any{"routeCount": routeCount, "reported": reported, "pointNo": req.PointNo})
|
||
}
|
||
s.notifyDashboard()
|
||
return nil
|
||
}
|
||
|
||
// Trace 追溯查询(SN 维度):工序时间线/操作人/步骤数据/物料批次SN/拧紧数据
|
||
func (s *Service) Trace(ctx context.Context, sn, operator string) (map[string]any, error) {
|
||
wp, err := s.ctx.EntClient.Workpiece.Query().Where(workpiece.Sn(sn)).First(ctx)
|
||
if err != nil {
|
||
return nil, errors.New("该SN无追溯数据")
|
||
}
|
||
procList, _ := s.ctx.EntClient.WorkpieceProcess.Query().
|
||
Where(workpieceprocess.Sn(sn)).Order(ent.Asc(workpieceprocess.FieldFlowId), ent.Asc(workpieceprocess.FieldID)).All(ctx)
|
||
steps, _ := s.ctx.EntClient.StepData.Query().
|
||
Where(stepdata.Sn(sn)).Order(ent.Desc(stepdata.FieldID)).All(ctx)
|
||
assoc, _ := s.ctx.EntClient.AssociationTrace.Query().
|
||
Where(associationtrace.FinishedSn(sn)).First(ctx)
|
||
tq := s.ctx.EntClient.TorqueRecord.Query().
|
||
Where(torquerecord.Sn(sn))
|
||
if operator != "" {
|
||
tq = tq.Where(torquerecord.OperatorEqualFold(operator))
|
||
}
|
||
torque, _ := tq.Order(ent.Desc(torquerecord.FieldTime)).Limit(200).All(ctx)
|
||
bindVO, _ := s.BuildBindTrace(ctx, sn)
|
||
// 半成品流转记录(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,
|
||
"torqueNgPending": wp.TorqueNgPending,
|
||
"torqueNgBy": wp.TorqueNgBy,
|
||
"torqueNgAt": wp.TorqueNgAt,
|
||
"processTimeline": procList,
|
||
"stepData": steps,
|
||
"associationTrace": assoc,
|
||
"torqueRecords": torque,
|
||
"bindTrace": bindVO,
|
||
"semiFlows": semiFlows,
|
||
"semiStoredCount": s.CountSemiIn(ctx, sn), // 半成品入库次数(三.3:count(action='SEMI_IN'),一.5 可追溯)
|
||
"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
|
||
}
|
||
|
||
// ListWorkpieces 查询工件(sn 模糊包含、orderNo 精确、status 精确)。
|
||
// page>0 走后端 SQL 分页:按 SN 升序(预生成 SN={工单号}-{3位序号},SN 升序=产品序号小号在前),
|
||
// 返回 rows+total;page=0 保持旧行为(limit 封顶 200、默认 500,按 ID 降序),兼容既有下拉/追溯调用方。
|
||
func (s *Service) ListWorkpieces(ctx context.Context, sn, orderNo, status string, limit, page, pageSize int) ([]*ent.Workpiece, int, error) {
|
||
q := s.ctx.EntClient.Workpiece.Query()
|
||
if sn != "" {
|
||
q = q.Where(workpiece.SnContains(sn))
|
||
}
|
||
if orderNo != "" {
|
||
q = q.Where(workpiece.OrderNo(orderNo))
|
||
}
|
||
if status != "" {
|
||
q = q.Where(workpiece.StatusEQ(status))
|
||
}
|
||
if page > 0 {
|
||
if pageSize <= 0 {
|
||
pageSize = 100
|
||
}
|
||
total, err := q.Count(ctx)
|
||
if err != nil {
|
||
return nil, 0, err
|
||
}
|
||
rows, err := q.Order(ent.Asc(workpiece.FieldSn)).
|
||
Offset((page - 1) * pageSize).Limit(pageSize).All(ctx)
|
||
return rows, total, err
|
||
}
|
||
if limit > 0 {
|
||
if limit > 200 {
|
||
limit = 200
|
||
}
|
||
q = q.Limit(limit)
|
||
} else {
|
||
q = q.Limit(500)
|
||
}
|
||
total, terr := q.Count(ctx)
|
||
if terr != nil {
|
||
return nil, 0, terr
|
||
}
|
||
rows, err := q.Order(ent.Desc(workpiece.FieldID)).All(ctx)
|
||
return rows, total, err
|
||
}
|
||
|
||
// InProcessItem 在制品(已进线未完工)视图项。跨天工件继续停留,日排产不重复排。
|
||
type InProcessItem struct {
|
||
Sn string `json:"sn"`
|
||
OrderNo string `json:"orderNo"`
|
||
ProductCode string `json:"productCode"`
|
||
ProductName string `json:"productName"`
|
||
CurrentStation int `json:"currentStation"` // 0=待流转(未分配工位), 13=末端待取件, 其余为物理工位
|
||
CurrentStationName string `json:"currentStationName"` // 工位显示名(待流转/末端待取件/装配X)
|
||
Status string `json:"status"`
|
||
OnlineAt string `json:"onlineAt"`
|
||
DwellSec int64 `json:"dwellSec"` // 停留时长(秒),自进线起算
|
||
DoneSteps int `json:"doneSteps"`
|
||
TotalSteps int `json:"totalSteps"`
|
||
}
|
||
|
||
// WorkpiecesInProcess 列出停在各工位、尚未完工的在制品(ONLINE/PROCESSING)。
|
||
// 位置口径(原虚拟位 0/13 魔法值已废除,业务定稿·一.10):
|
||
// - stationNo>0 :仅返回停在该工位的工件(currentStationNo 匹配)
|
||
// - scope=pending :待流转(ONLINE 未报工、未分配工位)
|
||
// - scope=end-pending :末端待取件(PROCESSING 且已报工至工艺路线末端工位)
|
||
// - 以上皆空 :返回全部
|
||
// orderNo 非空时按工单号模糊过滤(客户第12条「记录查看加一项看工单号查询」)。
|
||
// 已进线未完工的工件跨天继续,日排产仅排「未开工数量」,不会重复排产。
|
||
func (s *Service) WorkpiecesInProcess(ctx context.Context, stationNo int, orderNo, scope string) ([]InProcessItem, error) {
|
||
q := s.ctx.EntClient.Workpiece.Query().
|
||
Where(workpiece.Or(
|
||
workpiece.Status("ONLINE"),
|
||
workpiece.Status("PROCESSING"),
|
||
))
|
||
if orderNo != "" {
|
||
q = q.Where(workpiece.OrderNoContainsFold(orderNo))
|
||
}
|
||
list, err := q.Order(ent.Desc(workpiece.FieldOnlineAt)).All(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
out := make([]InProcessItem, 0, len(list))
|
||
woCache := map[int]*ent.WorkOrder{}
|
||
getWO := func(wp *ent.Workpiece) *ent.WorkOrder {
|
||
if wp.WorkOrderId <= 0 {
|
||
return nil
|
||
}
|
||
if wo, ok := woCache[wp.WorkOrderId]; ok {
|
||
return wo
|
||
}
|
||
wo, err := s.ctx.EntClient.WorkOrder.Get(ctx, wp.WorkOrderId)
|
||
if err != nil {
|
||
wo = nil
|
||
}
|
||
woCache[wp.WorkOrderId] = wo
|
||
return wo
|
||
}
|
||
for _, wp := range list {
|
||
// 路线 = 工单工艺组合(唯一路线源头);并行候选工位按工序级聚合
|
||
items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, getWO(wp))
|
||
route := groupFlowRoute(items)
|
||
total := DistinctFlowCount(items)
|
||
// 显示口径按 status 派生(原 0/13 魔法值已废除,业务定稿·一.10):
|
||
// 待流转 = ONLINE 未报工(未分配工位)
|
||
// 末端待取件 = PROCESSING 且所有工序已报工完成
|
||
// 其余 = 真实工位显示名
|
||
cur := wp.CurrentStationNo
|
||
_, doneAll := s.firstUndoneFlowSeq(ctx, s.ctx.EntClient, wp.Sn, route)
|
||
atEnd := wp.Status == "PROCESSING" && doneAll
|
||
switch scope {
|
||
case "pending":
|
||
if wp.Status != "ONLINE" || cur > 0 {
|
||
continue
|
||
}
|
||
case "end-pending":
|
||
if !atEnd {
|
||
continue
|
||
}
|
||
}
|
||
if stationNo > 0 && cur != stationNo {
|
||
continue
|
||
}
|
||
dwell := int64(0)
|
||
var onlineAt string
|
||
if wp.OnlineAt != nil {
|
||
dwell = int64(time.Since(*wp.OnlineAt).Seconds())
|
||
onlineAt = wp.OnlineAt.Format("2006-01-02 15:04:05")
|
||
}
|
||
done := 0
|
||
if procs, e := s.ctx.EntClient.WorkpieceProcess.Query().
|
||
Where(workpieceprocess.Sn(wp.Sn), workpieceprocess.Status("DONE")).Count(ctx); e == nil {
|
||
done = procs
|
||
}
|
||
code, name := "", ""
|
||
if wp.WorkOrderId > 0 {
|
||
if wo, e := s.ctx.EntClient.WorkOrder.Get(ctx, wp.WorkOrderId); e == nil {
|
||
code, name = wo.ProductCode, wo.ProductName
|
||
}
|
||
}
|
||
if code == "" && wp.OrderNo != "" {
|
||
if wo, e := s.ctx.EntClient.WorkOrder.Query().Where(workorder.WorkOrderNo(wp.OrderNo)).First(ctx); e == nil {
|
||
code, name = wo.ProductCode, wo.ProductName
|
||
}
|
||
}
|
||
stName := ""
|
||
switch {
|
||
case wp.Status == "ONLINE" && cur <= 0:
|
||
stName = "待流转"
|
||
case atEnd:
|
||
stName = "末端待取件"
|
||
default:
|
||
stName = stationDisplayName("", cur)
|
||
}
|
||
out = append(out, InProcessItem{
|
||
Sn: wp.Sn,
|
||
OrderNo: wp.OrderNo,
|
||
ProductCode: code,
|
||
ProductName: name,
|
||
CurrentStation: cur,
|
||
CurrentStationName: stName,
|
||
Status: wp.Status,
|
||
OnlineAt: onlineAt,
|
||
DwellSec: dwell,
|
||
DoneSteps: done,
|
||
TotalSteps: total,
|
||
})
|
||
}
|
||
return out, nil
|
||
}
|