- 移除实体:MES 删除 FlowMaterial(工艺物料)与 MixProductionTemplate(混产模板)全套(schema/ent 生成码/handler/logic),清理关联路由与种子 - 新增功能:产线清线(line_clearance handler + logic)、PLC 监控 WebSocket 实时推送(ws/plc_monitor_hub + handler) - 看板增强:新增管理屏与 KPI 组件(BoardManage/BoardKpi),调整演示屏 Mock 与各看板面板 - MES 完善:PLC 匹配/扭矩扫描/签收、工艺卡 PDF 与工单、AGV 链路、叫料/备料/在制品/短料预测等逻辑与前端调整 - 工位终端:删除离线面板 OfflinePanel,调整主界面/物料面板与 api/store/handler/路由 - WMS:AGV 托盘、物料与 MES 客户端调整及前端帮助/基础数据/叫料/托盘页 - 文档:更新产线API/客户问题/案例/部署手册/问题记录
1351 lines
60 KiB
Go
1351 lines
60 KiB
Go
package logic
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
"net/url"
|
||
"sort"
|
||
"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/linepoint"
|
||
"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/workpiecebind"
|
||
"bj_power_mes/ent/workpieceprocess"
|
||
|
||
"bj_power_mes/internal/plc"
|
||
|
||
"github.com/zeromicro/go-zero/core/logx"
|
||
)
|
||
|
||
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, ",")
|
||
}
|
||
|
||
// preferFreeStation 候选工位空闲优先(2026-11-06 条18 拍板):多候选优先空闲工位(传感器无托盘),
|
||
// 都闲取最小工位号,都忙取最小工位号并提示(由调用方在返回文案中追加)。
|
||
// 空闲判定 = 产线点位台账 STATION 点位无占用工件(occupied=false,由 PLC/记账维护);
|
||
// 台账无该工位行(如负数虚拟工位未落台账)时视为信息不足,不参与空闲判定、按最小工位号兜底。
|
||
func (s *Service) preferFreeStation(ctx context.Context, stations []int) (int, bool) {
|
||
if len(stations) == 0 {
|
||
return 0, false
|
||
}
|
||
sorted := append([]int(nil), stations...)
|
||
sort.Ints(sorted)
|
||
pts, err := s.ctx.EntClient.LinePoint.Query().Where(linepoint.PointTypeEQ("STATION")).All(ctx)
|
||
if err != nil || len(pts) == 0 {
|
||
return sorted[0], false
|
||
}
|
||
busy := map[int]bool{}
|
||
for _, p := range pts {
|
||
if p.Occupied {
|
||
busy[p.StationNo] = true
|
||
}
|
||
}
|
||
for _, no := range sorted {
|
||
if !busy[no] {
|
||
return no, false
|
||
}
|
||
}
|
||
return sorted[0], true
|
||
}
|
||
|
||
// 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"` // 工件当前位置(产线点位台账编号:C1~C15/工位号等;接驳台是AGV点位不作落点);空=未选,不落账
|
||
}
|
||
|
||
// 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(提示不拦),
|
||
// 供工位终端弹四选对话框(新件建档/绑定已知件/报异常/忽略)。
|
||
// 业务口径(2026-11-06 拍板):上线建档只对工件——生成在制工件+落点占位,不挂物料清单;
|
||
// 终端的领料核对是前端核对动作不落库。物料需求走叫料池(排产维度),工件维度与排产维度不能混。
|
||
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("工单未配置工艺组合")
|
||
}
|
||
// 并行候选工位:新件建档可落在「首道工艺」的任一候选工位。
|
||
// 业务口径(2026-11-06 条18 拍板):新件落点工位=工位登录态工位(E2,X-Station-No 注入),
|
||
// 候选资格由下方校验保证;「多候选优先空闲」在终端选点层天然满足——终端「工件位置」下拉
|
||
// 只列空闲点位(占用不显示),且工位分组仅显示本工单工艺组合候选工位。
|
||
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)
|
||
}
|
||
// 工位物理互斥(2026-11-16):滚筒线单件流,落点工位台面被其他工单在制件占用 → 拒绝建档,
|
||
// 该件须等占用件流转走(或改落其他空闲候选工位)。
|
||
busy, otherOrder, err := s.flowStationBusyBy(ctx, req.StationNo, wp.OrderNo)
|
||
if err == nil && busy && otherOrder != "" {
|
||
return "", nil, fmt.Errorf("建档落点工位%d正在加工工单%s的工件(工位互斥,一次只干一个工单),请等其流转走或改落其他空闲候选工位",
|
||
req.StationNo, otherOrder)
|
||
}
|
||
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
|
||
}
|
||
}
|
||
// 业务口径(2026-11-06 条18 拍板):在制品缺省落点多候选优先空闲工位——都闲取最小工位号,
|
||
// 都忙取最小工位号并提示(见下方 msg 追加)。
|
||
next, candidatesAllBusy := s.preferFreeStation(ctx, nextFlow.Stations)
|
||
// 二.4 资格校验:在制品(SEMI_STORED)重上线落点须为下一工艺的候选工位之一;
|
||
// 落点 0=未指定(缺省按下一工艺最小工位执行);负数虚拟工位同为合法工位号,同样参与资格校验
|
||
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) + "已停止接单)"
|
||
}
|
||
if candidatesAllBusy {
|
||
msg += "(提示:下一工艺候选工位均被占用,已按最小工位号落点,请人工协调清台)"
|
||
}
|
||
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
|
||
}
|
||
|
||
// releaseEndPointTolerant 完工即释放:末端点位台账当前登记者就是本工件(或本来就空)时清掉;
|
||
// 登记的是别的工件时不碰(异常场景走「工件位置纠正」),不报错、不影响完工。
|
||
func (s *Service) releaseEndPointTolerant(ctx context.Context, pointNo, sn, orderNo, operator string) {
|
||
pointNo = strings.TrimSpace(pointNo)
|
||
if pointNo == "" {
|
||
return
|
||
}
|
||
pt, err := s.ctx.EntClient.LinePoint.Query().Where(linepoint.PointNo(pointNo)).First(ctx)
|
||
if err != nil || pt.CurrentSn == "" {
|
||
return
|
||
}
|
||
if pt.CurrentSn != sn {
|
||
return
|
||
}
|
||
if _, err := s.ctx.EntClient.LinePoint.UpdateOneID(pt.ID).
|
||
SetCurrentSn("").SetOrderNo("").SetOccupied(false).Save(ctx); err != nil {
|
||
return
|
||
}
|
||
if operator == "" {
|
||
operator = "SYSTEM"
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "line.point.release", orderNo, operator, "line_point", pointNo,
|
||
"完工即释放末端点位:"+sn, 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"`
|
||
// OrderNo 终端当前作业工单(2026-11-16 错单强拦截):与扫码件归属工单不一致直接拒绝,
|
||
// 禁止把工单B的件静默记到工单A(工位互斥配套防呆)。
|
||
OrderNo string `json:"orderNo"`
|
||
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 工位报工:先应用装机绑定并做强校验(齐套才放行),再写报工实绩 + 步骤考核。
|
||
// 绑料是"落到工艺"的强约束:工件来源产品工艺分账中要求装配的物料必须绑齐,
|
||
// 电气件按单台用量逐颗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-16 错单强拦截(工位物理互斥配套):终端当前作业工单必须与扫码件归属工单一致,
|
||
// 不一致直接拒绝,杜绝"扫到工单B的件静默记到工单A"的错账。
|
||
if req.OrderNo != "" && req.OrderNo != wo.WorkOrderNo {
|
||
return fmt.Errorf("扫码件 %s 属于工单 %s,与当前作业工单 %s 不一致,已拒绝报工;请先在作业页切换到工单 %s,或核对手中工件",
|
||
req.Sn, wo.WorkOrderNo, req.OrderNo, wo.WorkOrderNo)
|
||
}
|
||
// 并行候选工位模型(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,
|
||
s.stationHasEnabledLineDock(ctx, client, req.StationNo)); 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
|
||
}
|
||
// 阶段3(同一事务,2026-11-18 用户拍板):末道工艺报工 → 自动完工同步落库,不再异步——
|
||
// 全部工艺已有 DONE 报工(firstUndoneFlowSeq 以本事务 client 判定,能读到刚写入的本工艺报工实绩)
|
||
// → 置 DONE + 生命周期 + 关联追溯 + 工单进度/日排产,全部随报工一个事务提交,要么全成要么全回滚。
|
||
// PLC 物理下发等外部副作用在事务提交后执行(不进事务)。
|
||
autoDone := false
|
||
blocked := ""
|
||
if _, allDone := s.firstUndoneFlowSeq(ctx, client, req.Sn, route); allDone {
|
||
autoDone = true
|
||
// 齐套兜底校验(validateAllFlows:工单工艺组合中每个工艺的装配物料都须绑齐;工艺未配物料清单自动放行):
|
||
// 日常由各工位报工的绑定强校验覆盖,此处只兜配置变动/历史数据的底。
|
||
// 不过 → 报工照常提交(不回滚工人劳动),工件保持 PROCESSING(全部工艺已报),落预警等人工;
|
||
// 补偿出路 = 管理后台「在制品追踪」强行完工(PROCESSING/SEMI_STORED 均可,留痕)。
|
||
if m, verr := s.validateAllFlows(ctx, client, req.Sn, wo); verr == nil && m != "" {
|
||
autoDone = false
|
||
blocked = m
|
||
}
|
||
}
|
||
if autoDone {
|
||
if _, err := client.Workpiece.UpdateOneID(wp.ID).
|
||
SetStatus("DONE").SetDoneAt(now).SetAtStationNo(0).Save(ctx); err != nil {
|
||
return err
|
||
}
|
||
if _, err := client.WorkpieceLifecycleLog.Create().
|
||
SetSn(req.Sn).SetWorkOrderNo(wp.OrderNo).SetAction("DONE").
|
||
SetFromStatus("PROCESSING").SetToStatus("DONE").SetStationNo(req.StationNo).
|
||
SetOperator(operator).SetSource("workstation").SetRemark("末道工艺报工自动完工(与报工同事务)").Save(ctx); err != nil {
|
||
return err
|
||
}
|
||
if err := s.upsertAssociationTrace(ctx, client, wp, operator); err != nil {
|
||
return err
|
||
}
|
||
s.bumpWorkOrderProgress(ctx, client, wp.OrderNo, req.Sn)
|
||
s.bumpDailyPlanCompleted(ctx, client, wp.OrderNo, now)
|
||
}
|
||
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})
|
||
// 断料预警(2026-11-14 用户拍板铁律 1):报工成功即以「本次报工实际耗时」为节拍推算
|
||
// 本工位剩余物料可支撑台数/时长,低于阈值落预警(工位终端实时弹播;推算失败静默不阻断);单台用量按工单来源产品工艺的工艺分账取(无分账回退旧口径)。
|
||
s.evaluateShortageAfterReport(ctx, req.StationNo, flowId, durationSec, wo)
|
||
if blocked != "" {
|
||
// 自动完工被拦(齐套兜底校验不过):报工已提交,工件保持 PROCESSING,落预警;
|
||
// 人工出路 = 管理后台「在制品追踪」强行完工(补偿入口)。
|
||
logx.Errorf("自动完工被拦(齐套缺失):sn=%s missing=%s", req.Sn, blocked)
|
||
s.ctx.EventLog.Write(ctx, "workpiece.auto_done_blocked", wp.OrderNo, operator, "workpiece", req.Sn,
|
||
"自动完工被拦:装配物料齐套校验未过,待人工处置(管理后台在制品追踪可强行完工)",
|
||
map[string]any{"missing": blocked, "stationNo": req.StationNo})
|
||
}
|
||
if autoDone {
|
||
// 完工件自动流转末端下料位(PLC 下发 + 释放源点位台账,末端不落台账=完工即离场)
|
||
s.moveDoneToEnd(ctx, wp, req.Sn, operator)
|
||
s.notifyDashboard()
|
||
} else {
|
||
// 未完工(还有后续工艺 / 齐套被拦):走原自动流转连锁推进物理位置
|
||
go func() {
|
||
defer func() { _ = recover() }()
|
||
s.TriggerFlowChainForSn(context.Background(), req.Sn, operator)
|
||
}()
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// upsertAssociationTrace 成品关联追溯落库/更新(bind_type=BATCH → 批次清单、bind_type=SN → 序列号清单),
|
||
// 清单从装机绑定台账自动汇总,不再人工重录。
|
||
// client 传调用方事务 client(自动完工与报工同事务)时,追溯落库随事务一起提交/回滚。
|
||
func (s *Service) upsertAssociationTrace(ctx context.Context, client *ent.Client, wp *ent.Workpiece, operator string) error {
|
||
binds, _ := client.WorkpieceBind.Query().Where(workpiecebind.Sn(wp.Sn)).All(ctx)
|
||
batchItems, serialItems := []string{}, []string{}
|
||
for _, b := range binds {
|
||
if b.BindType == "SN" {
|
||
serialItems = append(serialItems, b.BindValue)
|
||
} else {
|
||
batchItems = append(batchItems, b.BindValue)
|
||
}
|
||
}
|
||
routeStr := ""
|
||
if wo, e := client.WorkOrder.Get(ctx, wp.WorkOrderId); e == nil && wo != nil {
|
||
if items, _ := RouteStationsFromWO(ctx, client, wo); len(items) > 0 {
|
||
routeStr = RouteStationsStrOfWO(items)
|
||
}
|
||
}
|
||
existID, _ := client.AssociationTrace.Query().Where(associationtrace.FinishedSn(wp.Sn)).FirstID(ctx)
|
||
if existID > 0 {
|
||
if _, uerr := client.AssociationTrace.UpdateOneID(existID).
|
||
SetBatchItems(batchItems).SetSerialItems(serialItems).SetOperator(operator).Save(ctx); uerr != nil {
|
||
return uerr
|
||
}
|
||
return nil
|
||
}
|
||
if _, cerr := client.AssociationTrace.Create().
|
||
SetFinishedSn(wp.Sn).SetOrderNo(wp.OrderNo).SetProcessCode(routeStr).
|
||
SetBatchItems(batchItems).SetSerialItems(serialItems).
|
||
SetOperator(operator).Save(ctx); cerr != nil {
|
||
return cerr
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// moveDoneToEnd 完工件自动流转末端下料位(2026-11-18 定稿):只下发 PLC 流转 + 释放源点位台账,
|
||
// 末端不落台账(完工=离场)。源无台账行(虚拟/线下位)、源已是末端或路由不可达时,
|
||
// 只释放台账、不下发流转,不报错(完工本身已成功)。
|
||
func (s *Service) moveDoneToEnd(ctx context.Context, wp *ent.Workpiece, sn string, operator string) {
|
||
src, err := s.ctx.EntClient.LinePoint.Query().
|
||
Where(linepoint.Occupied(true), linepoint.CurrentSnEQ(sn)).First(ctx)
|
||
if ent.IsNotFound(err) {
|
||
s.ctx.EventLog.Write(ctx, "workpiece.auto_done_move", wp.OrderNo, operator, "workpiece", sn,
|
||
"完工件流转末端:源无点位台账(虚拟/线下位),不流转", nil)
|
||
return
|
||
}
|
||
if err != nil {
|
||
logx.Errorf("完工件流转末端失败(查源点位):sn=%s err=%v", sn, err)
|
||
return
|
||
}
|
||
// 末端终点:END-U(G11)台账空闲优先,否则 END-D(G12)
|
||
tgtNo := 11
|
||
if pt, e := s.ctx.EntClient.LinePoint.Query().
|
||
Where(linepoint.PointType("END"), linepoint.PointNoEQ("END-U"), linepoint.Occupied(true)).
|
||
First(ctx); e == nil && pt != nil {
|
||
tgtNo = 12
|
||
}
|
||
if (src.PointType == "STATION" || src.PointType == "END") && src.StationNo >= 1 && src.StationNo <= 10 {
|
||
if _, _, _, ok := s.flowSend(ctx, plc.SrcStation, src.StationNo, tgtNo, plc.SrcStation); !ok {
|
||
logx.Errorf("完工件流转末端:路由不可达 G%d→G%d,仅释放台账", src.StationNo, tgtNo)
|
||
}
|
||
}
|
||
if err := s.OccupyPoint(ctx, src.PointNo, sn, wp.OrderNo, operator, "OUT"); err != nil {
|
||
logx.Errorf("完工件流转末端失败(释放源点位):sn=%s err=%v", sn, err)
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "workpiece.auto_done_move", wp.OrderNo, operator, "workpiece", sn,
|
||
fmt.Sprintf("完工件自动流转末端下料位(G%d),末端不落台账(完工=离场)", tgtNo),
|
||
map[string]any{"from": src.PointNo, "to": tgtNo})
|
||
}
|
||
|
||
// 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
|
||
}
|
||
|
||
// ForceCompleteReq 强行完工请求(管理后台「在制品追踪」异常补偿入口)。
|
||
type ForceCompleteReq struct {
|
||
Sn string `json:"sn"`
|
||
}
|
||
|
||
// ForceCompleteWorkpiece 强行完工:异常件的人工补偿出口,接受 SEMI_STORED(已暂存退库)
|
||
// 与 PROCESSING(在制,含"全部工艺已报但自动完工被齐套校验拦下"的滞留件)两种状态。
|
||
// 拧紧 NG / 齐套缺失等被拦下的件经本入口人工收口;属管理员显式动作,写操作日志留痕
|
||
// (含拧紧 NG 未处置状态)。在制件若仍占点位台账,完工时按 SN 容忍释放(登记是本件才清)。
|
||
// 正常件报完最后一道工艺即随报工同事务自动完工,无需任何人工完工步骤。
|
||
func (s *Service) ForceCompleteWorkpiece(ctx context.Context, req ForceCompleteReq, operator string) error {
|
||
sn := strings.TrimSpace(req.Sn)
|
||
if sn == "" {
|
||
return errors.New("请填写工件 SN")
|
||
}
|
||
wp, err := s.ctx.EntClient.Workpiece.Query().Where(workpiece.Sn(sn)).First(ctx)
|
||
if err != nil {
|
||
return errors.New("工件不存在")
|
||
}
|
||
if wp.Status != "SEMI_STORED" && wp.Status != "PROCESSING" {
|
||
return fmt.Errorf("工件当前状态为「%s」,仅半成品或在制件可强行完工;正常件报完最后一道工艺即自动完工", wp.Status)
|
||
}
|
||
now := time.Now()
|
||
if _, err := s.ctx.EntClient.Workpiece.UpdateOneID(wp.ID).
|
||
SetStatus("DONE").SetDoneAt(now).SetAtStationNo(0).Save(ctx); err != nil {
|
||
return err
|
||
}
|
||
// 在制件若仍占点位台账(齐套被拦滞留/滞留件),完工即离场:按 SN 容忍释放(登记是本件才清)
|
||
if wp.Status == "PROCESSING" {
|
||
if pt, perr := s.ctx.EntClient.LinePoint.Query().
|
||
Where(linepoint.Occupied(true), linepoint.CurrentSnEQ(sn)).First(ctx); perr == nil && pt != nil {
|
||
s.releaseEndPointTolerant(ctx, pt.PointNo, sn, wp.OrderNo, operator)
|
||
}
|
||
}
|
||
// 状态流水 SEMI_STORED/PROCESSING→DONE(完工收口)
|
||
s.writeLifecycle(ctx, sn, wp.OrderNo, wp.Status, "DONE", 0, 0, operator, "admin", "强行完工(人工补偿收口)")
|
||
if err := s.upsertAssociationTrace(ctx, s.ctx.EntClient, wp, operator); err != nil {
|
||
return err
|
||
}
|
||
s.bumpWorkOrderProgress(ctx, s.ctx.EntClient, wp.OrderNo, sn)
|
||
s.bumpDailyPlanCompleted(ctx, s.ctx.EntClient, wp.OrderNo, now)
|
||
note := ""
|
||
if wp.TorqueNgPending {
|
||
note = "(拧紧扭矩不合格未处置,人工强行放行)"
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "workpiece.force_done", wp.OrderNo, operator, "workpiece", sn,
|
||
"强行完工"+note, map[string]any{"torqueNgPending": wp.TorqueNgPending, "fromStatus": wp.Status})
|
||
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=待流转(未分配工位)/半成品(已退库),其余为物理工位
|
||
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)或半成品(SEMI_STORED)。
|
||
// 位置口径(原虚拟位 0/13 魔法值已废除,业务定稿·一.10):
|
||
// - stationNo>0 :仅返回停在该工位的工件(currentStationNo 匹配)
|
||
// - scope=pending:待流转(ONLINE 未报工、未分配工位)
|
||
// - status=SEMI_STORED:半成品视图(2026-11-18 定稿:已暂存退库件不占产线,
|
||
// 仅供「强行完工」人工收口;原「末端待取件」scope 已随自动完工整体退役)
|
||
// - 以上皆空 :返回全部在制
|
||
// orderNo 非空时按工单号模糊过滤(客户第12条「记录查看加一项看工单号查询」)。
|
||
// 已进线未完工的工件跨天继续,日排产仅排「未开工数量」,不会重复排产。
|
||
func (s *Service) WorkpiecesInProcess(ctx context.Context, stationNo int, orderNo, scope, status string) ([]InProcessItem, error) {
|
||
q := s.ctx.EntClient.Workpiece.Query()
|
||
if status == "SEMI_STORED" {
|
||
q = q.Where(workpiece.Status("SEMI_STORED"))
|
||
} else {
|
||
q = q.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))
|
||
total := DistinctFlowCount(items)
|
||
// 显示口径按 status 派生(原 0/13 魔法值已废除,业务定稿·一.10):
|
||
// 待流转 = ONLINE 未报工(未分配工位)
|
||
// 半成品 = SEMI_STORED(已暂存退库,不占产线,可强行完工)
|
||
// 其余 = 真实工位显示名
|
||
cur := wp.CurrentStationNo
|
||
switch scope {
|
||
case "pending":
|
||
if wp.Status != "ONLINE" || cur > 0 {
|
||
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 == "SEMI_STORED":
|
||
stName = "半成品(已退库)"
|
||
case wp.Status == "ONLINE" && cur <= 0:
|
||
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
|
||
}
|