Files
bj_power/bj_power_mes/internal/logic/productprocess.go
T
SunYF 88875c1f13 feat(mes/wms/终端): 工位终端状态感知 + 全厂统一账号 + 单号短号规则 + 退料SN逐颗核对闭环(2026-11-26~28 现场整改)
【MES · 工位终端状态感知(11-28 第十三节拍板)】
- 新增 station_terminal_state / station_terminal_event 两表:当前状态镜像 + 状态变化流水
- 在线判定走既有 SSE 长连接存活:建连/断连/30s ping 心跳,90s 无心跳判离线,零 HTTP 轮询
- 登录/退出/暂停/恢复由终端事件驱动上报;新增「终端状态」管理页(produce.terminalstate,仅超级管理员):看在线/登录/操作人/接单/下班判定/心跳,抽屉看状态流水
- 库管代退料前置条件②「工人已下班」据此判定:未登录或终端离线任一即下班

【工位终端 · 全厂统一账号(11-28 拍板)】
- 删除本地账号表与 seed,登录直连 MES 用户表;本地 SQLite 只剩操作日志+登录态,断网不能换人
- SSE 客户端携带本机固定工位号,MES 据连接存活映射该工位在线状态

【单号短号规则(11-27 拍板)】
- 叫料单 MR / 叫料包 PK / 转产退库 TR / 配送单 DL:改「前缀+YYMMDD+3位当天序号」,每天从 001 归零、超 999 进 4 位
- MR 与 TR 同列不同前缀独立计数不撞号;进程内互斥分配 + DB 唯一索引兜底;历史时间戳号一律不动

【退料闭环(11-28)】
- 退库单新增 sn_list:工位提交的待退 SN 清单落库,收货逐颗扫码核对(不按批次分组、允许跨批次混合,所属批次系统按 SN 带出,库管不必填)
- 收货改大数量必须有实物依据:SN 件以精确扫描的最终清单为准(条数相等且不重复);批次件必须落到真实启用的四级库位,禁止凭空加库存
- 余量参考值口径定稿(N4):应剩余量 = 实际备料 − 已消耗 − 已退 − 已损耗
- 损耗台账取消「后审核批注」:删 status/comment/commenter/commented_at 字段,WMS 确认收货当场落账闭环,MES 台账只读

【日排产 · 两种 PENDING 区分(11-26 口径定稿)】
- daily_plan 新增 discarded 废弃标记:停用打标、新建不打标;额度只算 CONFIRMED + 未废弃 PENDING
- 工单管「要干几台」、日排产管「按天从哪个工位领多少料」,两张账不合并不互倒推;排产合计可小于工单数(缺口靠借料/补料审批摆出,不自动兜底)

【其他】
- SN 查询大小写脱敏(11-27):存储原样不强制大小写,匹配 LOWER(sn)=LOWER(?),扫 ABC-0001 与 abc-0001 命中同一件
- 拧紧枪人工跳过链路:设备未连接时人工跳过上报,「拧紧跳过(设备未连接)」前缀单独列示,不写 torque_record 绝不冒充设备结果
- 单据流转提示规则表全量 35 条(MES 18 + WMS 17):常驻提示条、单号可复制;单号字段逐条对后端响应实测,取不到不显示复制按钮
- PLC 快照缓存/对账、产线清线、绩效与拧紧枪配置页同步修正

【文档】
- 新增《临时结束.md》2026-11-26 日排产/叫料/完工口径大讨论定稿(含状态专项结论与被推翻旧说法留档);问题临时.md 全量更新
2026-11-28 13:44:51 +08:00

679 lines
27 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package logic
import (
"context"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
"bj_power_mes/ent"
"bj_power_mes/ent/productbom"
"bj_power_mes/ent/productprocess"
"bj_power_mes/ent/productprocessitem"
"bj_power_mes/ent/productprocessmaterial"
"bj_power_mes/ent/workorder"
"bj_power_mes/internal/verr"
)
// ---------- 产品工艺(2026-10-09 定稿) ----------
//
// 产品工艺 = 产品级的工艺定义:只选工艺+顺序(seq 严格递增=串行),不绑工位。
// 工位在建工单时按「工位绑定」(station.flow_id) 自动推导(同工艺的全部启用工位),
// 并复制为工单工艺组合 flow_combination 快照;产品工艺是模板,工单组合是实例快照。
// 校验口径(客户裁决):覆盖/顺序校验仅作保存时警告提示,不阻断保存(允许手改组合偏离)。
// ProductProcessItemReq 产品工艺明细项(flows 数组顺序即 seq 顺序)
type ProductProcessItemReq struct {
FlowId int `json:"flowId"`
}
// ProductProcessReq 产品工艺保存请求
type ProductProcessReq struct {
Id int `json:"id"`
ProductCode string `json:"productCode"`
ProductName string `json:"productName"`
Name string `json:"name"`
Status string `json:"status"`
Remark string `json:"remark"`
Flows []ProductProcessItemReq `json:"flows"`
// 2026-11-13 拍板「总分制」:随产品工艺一起提交的分账行(总账物料分配到各工艺)。
// 总账存在时不分配完 / Σ分账≠总账 → 保存被硬拒。
Allocations []BOMAllocation `json:"allocations"`
}
// ProductProcessItemVO 明细行(含实时反查的绑定工位号)
type ProductProcessItemVO struct {
Seq int `json:"seq"`
FlowId int `json:"flowId"`
FlowName string `json:"flowName"`
StationNos []int `json:"stationNos"` // 该工艺当前绑定的启用工位号(升序,实时反查)
}
// ProductProcessVO 列表/详情视图
type ProductProcessVO struct {
Id int `json:"id"`
ProductCode string `json:"productCode"`
ProductName string `json:"productName"`
Name string `json:"name"`
Status string `json:"status"`
Remark string `json:"remark"`
Flows []ProductProcessItemVO `json:"flows"`
// 只读:被工单引用次数(总引用,含历史;展示用)
UsedByWorkOrders int `json:"usedByWorkOrders"`
// 只读:未完成工单(CREATED/IN_PROGRESS/PAUSED,2026-11-05 起含 CREATED)引用数 —— >0 时编辑接口拒绝(规则1)
RunningByWorkOrders int `json:"runningByWorkOrders"`
// 只读:历史工单(已完成/已取消)引用数 —— 展示用(不锁定编辑)
CreatedByWorkOrders int `json:"createdByWorkOrders"`
// 只读:可执行状态(所有工艺都有启用工位绑定且顺序可满足)
Executable bool `json:"executable"`
NotReady string `json:"notReady"` // 不可执行原因(可执行时为空)
CreatedAt time.Time `json:"createdAt"`
}
// ListProductProcesses 产品工艺列表(分页;筛选:产品编码/状态/工艺反查/关键字)。
// page>0 真分页返回 map{total,list,page,pageSize};page=0 返回全量数组(工单页下拉用)。
func (s *Service) ListProductProcesses(ctx context.Context, productCode, status string, flowId int, keyword, name string, stepMin, stepMax int, page, pageSize int) (any, error) {
q := s.ctx.EntClient.ProductProcess.Query()
if productCode != "" {
q = q.Where(productprocess.ProductCodeContainsFold(productCode))
}
if status != "" {
q = q.Where(productprocess.Status(status))
}
if keyword != "" {
kw := productprocess.Or(
productprocess.NameContainsFold(keyword),
productprocess.ProductCodeContainsFold(keyword),
productprocess.ProductNameContainsFold(keyword),
)
q = q.Where(kw)
}
if name != "" {
q = q.Where(productprocess.NameContainsFold(name))
}
// 工艺反查:只要包含该工艺的产品工艺
if flowId > 0 {
items, err := s.ctx.EntClient.ProductProcessItem.Query().
Where(productprocessitem.FlowId(flowId)).All(ctx)
if err != nil {
return nil, err
}
ids := make([]int, 0, len(items))
for _, it := range items {
ids = append(ids, it.ProductProcessId)
}
if len(ids) == 0 {
ids = []int{-1} // 无命中:返回空集
}
q = q.Where(productprocess.IDIn(ids...))
}
pps, err := q.Order(ent.Desc(productprocess.FieldCreatedAt), ent.Desc(productprocess.FieldID)).All(ctx)
if err != nil {
return nil, err
}
// 名字映射(工艺/工位)
flows, _ := s.ctx.EntClient.ProcessFlow.Query().All(ctx)
flowName := map[int]string{}
for _, f := range flows {
flowName[f.ID] = f.Name
}
sts, _ := s.ctx.EntClient.Station.Query().All(ctx)
byFlow := map[int][]int{}
for _, st := range sts {
if st.Status == "ENABLED" && st.FlowId > 0 {
byFlow[st.FlowId] = append(byFlow[st.FlowId], st.StationNo)
}
}
for k := range byFlow {
sort.Ints(byFlow[k])
}
// 明细按产品工艺分组
items, _ := s.ctx.EntClient.ProductProcessItem.Query().
Order(ent.Asc(productprocessitem.FieldProductProcessId), ent.Asc(productprocessitem.FieldSeq)).All(ctx)
itemsOf := map[int][]*ent.ProductProcessItem{}
for _, it := range items {
itemsOf[it.ProductProcessId] = append(itemsOf[it.ProductProcessId], it)
}
// 工单引用计数(规则1,2026-10-20;2026-11-05 修订):未完成(锁定编辑)与历史(仅展示)分档
used := map[int]int{}
usedRunning := map[int]int{}
usedCreated := map[int]int{}
wos, _ := s.ctx.EntClient.WorkOrder.Query().Where(workorder.ProductProcessIdGT(0)).All(ctx)
for _, w := range wos {
used[w.ProductProcessId]++
switch w.Status {
case "IN_PROGRESS", "PAUSED", "CREATED", "PENDING", "RELEASED":
usedRunning[w.ProductProcessId]++
default:
usedCreated[w.ProductProcessId]++
}
}
out := make([]*ProductProcessVO, 0, len(pps))
for _, p := range pps {
vo := &ProductProcessVO{
Id: p.ID, ProductCode: p.ProductCode, ProductName: p.ProductName, Name: p.Name,
Status: p.Status, Remark: p.Remark,
UsedByWorkOrders: used[p.ID], RunningByWorkOrders: usedRunning[p.ID],
CreatedByWorkOrders: usedCreated[p.ID], CreatedAt: p.CreatedAt,
Flows: []ProductProcessItemVO{},
}
for _, it := range itemsOf[p.ID] {
vo.Flows = append(vo.Flows, ProductProcessItemVO{
Seq: it.Seq, FlowId: it.FlowId, FlowName: flowName[it.FlowId],
StationNos: byFlow[it.FlowId],
})
}
vo.Executable, vo.NotReady = ppExecutable(vo)
out = append(out, vo)
}
// 工艺数范围过滤:按产品工艺的工艺顺序/工艺条目数(vo.Flows 长度)
if stepMin > 0 || stepMax > 0 {
kept := make([]*ProductProcessVO, 0, len(out))
for _, vo := range out {
n := len(vo.Flows)
if stepMin > 0 && n < stepMin {
continue
}
if stepMax > 0 && n > stepMax {
continue
}
kept = append(kept, vo)
}
out = kept
}
if page > 0 {
total := len(out)
start := (page - 1) * pageSize
if start > total {
start = total
}
end := start + pageSize
if end > total {
end = total
}
return map[string]any{"total": total, "list": out[start:end], "page": page, "pageSize": pageSize}, nil
}
return out, nil
}
// ppExecutable 可执行判定:每道工艺都有启用的绑定工位,且按 seq 排列后工位号可满足递增
func ppExecutable(vo *ProductProcessVO) (bool, string) {
prev := 0
for _, it := range vo.Flows {
if len(it.StationNos) == 0 {
return false, fmt.Sprintf("第%d道工艺「%s」暂无启用的绑定工位", it.Seq, it.FlowName)
}
if prev > 0 && it.StationNos[0] <= prev {
return false, fmt.Sprintf("第%d道工艺「%s」(工位%d) 与上一道工位顺序冲突", it.Seq, it.FlowName, it.StationNos[0])
}
prev = it.StationNos[len(it.StationNos)-1]
}
return true, ""
}
// SaveProductProcess 保存产品工艺(新建或整表覆盖明细)。
// 约束:① 产品必填,明细非空;② 同一工艺不能在同一产品工艺内出现两次(客户裁决);
// ③ 一个产品对应一个产品工艺(新建时若该产品已存在 product_process,直接报错"该产品已有产品工艺,请直接编辑");
// ④ 规则1(2026-10-20 拍板,2026-11-05 修订):有未完成工单(CREATED/IN_PROGRESS/PAUSED)引用 →
//
// 定义与工艺明细(flows)一并禁改,保证工单路线前后一致;建议「复制工艺」后用新工艺建新单;
//
// ⑤ 名称未传时按"${物料编码} ${物料名称} 工艺"兜底。
func (s *Service) SaveProductProcess(ctx context.Context, req ProductProcessReq, operator string) (int, error) {
// 收集式校验(报错一次收全 + 每条带怎么办,2026-10-20):全部问题列出、一次性返回
ve := verr.New()
if strings.TrimSpace(req.ProductCode) == "" {
ve.Add("productCode", "请选择产品", "在「产品」下拉中选择产品(来自 WMS 物料档案,类型=成品)")
}
// 名称兜底(前端未传时按 物料编码 物料名称 工艺 生成)
if strings.TrimSpace(req.Name) == "" {
req.Name = strings.TrimSpace(req.ProductCode) + " " + strings.TrimSpace(req.ProductName) + " 工艺"
}
if len(req.Flows) == 0 {
ve.Add("flows", "请至少选择一道工艺", "在「工艺流程」中点「加入」加入至少一道工艺,再用上下移按钮排好执行顺序")
}
seen := map[int]bool{}
dupReported := map[int]bool{}
for _, f := range req.Flows {
if f.FlowId <= 0 {
ve.Add("flows", "工艺选择无效", "删除无效行后,从工艺下拉中重新选择")
continue
}
if seen[f.FlowId] {
if !dupReported[f.FlowId] {
ve.Add("flows", "同一工艺在同一产品工艺内出现两次", "重复工艺只保留一处(客户裁决:同一工艺在同一产品工艺内不能重复)")
dupReported[f.FlowId] = true
}
continue
}
seen[f.FlowId] = true
if _, err := s.ctx.EntClient.ProcessFlow.Get(ctx, f.FlowId); err != nil {
ve.Add("flows", fmt.Sprintf("所选工艺不存在(ID=%d)", f.FlowId), "删除该行后,从工艺下拉中重新选择")
}
}
status := req.Status
if status == "" {
status = "INACTIVE" // 新建默认停用:配齐工艺路线+总账+分账后再手动启用
}
if status != "ACTIVE" && status != "INACTIVE" {
ve.Add("status", "状态只能是启用或停用", "点「启用」开启这套产品工艺,或保持停用先完善配置")
}
if req.Id > 0 {
if _, err := s.ctx.EntClient.ProductProcess.Get(ctx, req.Id); err != nil {
ve.Add("id", "产品工艺不存在", "列表可能已被他人修改,请关闭弹窗刷新后重试")
} else if n, _ := s.ctx.EntClient.WorkOrder.Query().
Where(workorder.ProductProcessId(req.Id),
workorder.StatusIn("IN_PROGRESS", "RELEASED")).Count(ctx); n > 0 {
// 规则1(2026-10-20 拍板,2026-11-05 修订;2026-11-27 用户拍板修订占用名单):
// 有「执行中/已下发待开工」的工单引用 → 定义与明细(flows)一并禁改,保证在制工单路线快照一致。
// 2026-11-27 起 PAUSED(已暂停=已清线=让位)不再占用,允许改工艺去接其它工单;
// CREATED/PENDING(还没开工)同样不占用——它们还没进线,路线可随时重选。
ve.AddAction("productProcessId", "该产品工艺仍有执行中的工单引用,不能修改(定义与工艺明细均锁定)。",
"如需调整,请复制一份新工艺修改,新工单使用新工艺;暂停中的工单请先保持暂停状态再改。",
"复制工艺", "/product-process?copy="+strconv.Itoa(req.Id))
}
} else if strings.TrimSpace(req.ProductCode) != "" {
// 一个产品对应一个产品工艺:新建时若已存在启用的则报错(停用的允许并存:复制场景)
if n, _ := s.ctx.EntClient.ProductProcess.Query().
Where(productprocess.ProductCode(req.ProductCode), productprocess.Status("ACTIVE")).Count(ctx); n > 0 {
ve.Add("productCode", "该产品已有启用中的产品工艺,请直接编辑",
"在列表中找到该产品的工艺行点「编辑」;如需换版,先停用旧工艺再新建")
}
}
if err := ve.OrNil(); err != nil {
return 0, err
}
// 2026-11-13 拍板 P10:工艺配置与物料清单彻底分离、各自独立保存。
// 产品工艺的保存不再写入分账(保存物料清单不会再保存一遍工艺);
// 这里只校验「已有分账的工艺仍在本次工艺路线内」,避免改路线后分账指向消失的工艺。
if req.Id > 0 && len(req.Flows) > 0 {
flowSet := map[int]bool{}
for _, f := range req.Flows {
flowSet[f.FlowId] = true
}
allocRows, aErr := s.ctx.EntClient.ProductProcessMaterial.Query().
Where(productprocessmaterial.ProductProcessId(req.Id)).All(ctx)
if aErr != nil {
return 0, aErr
}
for _, a := range allocRows {
if !flowSet[a.FlowId] {
return 0, fmt.Errorf("工艺 %d 已从工艺路线移除,但物料清单里仍有该工艺的物料分配;请先在物料清单里重新分配", a.FlowId)
}
}
}
var ppID int
if req.Id > 0 {
if _, err := s.ctx.EntClient.ProductProcess.UpdateOneID(req.Id).
SetProductCode(req.ProductCode).SetProductName(req.ProductName).
SetName(req.Name).SetStatus(status).SetRemark(req.Remark).
Save(ctx); err != nil {
return 0, err
}
ppID = req.Id
} else {
p, err := s.ctx.EntClient.ProductProcess.Create().
SetProductCode(req.ProductCode).SetProductName(req.ProductName).
SetName(req.Name).SetStatus(status).SetRemark(req.Remark).
Save(ctx)
if err != nil {
return 0, err
}
ppID = p.ID
}
// 明细整表覆盖(seq = 数组顺序,从 1 严格递增)
_, _ = s.ctx.EntClient.ProductProcessItem.Delete().
Where(productprocessitem.ProductProcessId(ppID)).Exec(ctx)
for i, f := range req.Flows {
if err := s.ctx.EntClient.ProductProcessItem.Create().
SetProductProcessId(ppID).SetSeq(i + 1).SetFlowId(f.FlowId).
Exec(ctx); err != nil {
return 0, err
}
}
// 分账不再随产品工艺保存:由独立的「物料清单」页面/弹窗调 SaveProcessAllocations 写入
s.ctx.EventLog.Write(ctx, "product.process.save", "", operator, "product_process", fmt.Sprint(ppID),
"保存产品工艺", map[string]any{"id": ppID, "name": req.Name, "productCode": req.ProductCode, "flows": len(req.Flows)})
return ppID, nil
}
// DeleteProductProcess 删除产品工艺(被工单引用过禁止删除,只能停用)
func (s *Service) DeleteProductProcess(ctx context.Context, id int, operator string) error {
if id <= 0 {
return errors.New("缺少 id")
}
if n, _ := s.ctx.EntClient.WorkOrder.Query().Where(workorder.ProductProcessId(id)).Count(ctx); n > 0 {
return fmt.Errorf("该产品工艺已被 %d 张工单引用,不能删除(只能停用)", n)
}
p, err := s.ctx.EntClient.ProductProcess.Get(ctx, id)
if err != nil {
return errors.New("产品工艺不存在")
}
_, _ = s.ctx.EntClient.ProductProcessItem.Delete().Where(productprocessitem.ProductProcessId(id)).Exec(ctx)
// 2026-11-13 拍板堵后门:删除产品工艺必须同步删除它的物料分账,不留孤儿行
_, _ = s.ctx.EntClient.ProductProcessMaterial.Delete().
Where(productprocessmaterial.ProductProcessId(id)).Exec(ctx)
if err := s.ctx.EntClient.ProductProcess.DeleteOneID(id).Exec(ctx); err != nil {
return err
}
s.ctx.EventLog.Write(ctx, "product.process.delete", "", operator, "product_process", fmt.Sprint(id),
"删除产品工艺", map[string]any{"id": id, "name": p.Name})
return nil
}
// SetProductProcessStatus 启用/停用(停用不删:历史工单按 product_process_id 反查当时定义)
func (s *Service) SetProductProcessStatus(ctx context.Context, id int, status, operator string) error {
if id <= 0 {
return errors.New("缺少 id")
}
if status != "ACTIVE" && status != "INACTIVE" {
return errors.New("非法状态")
}
p, err := s.ctx.EntClient.ProductProcess.Get(ctx, id)
if err != nil {
return errors.New("产品工艺不存在")
}
if p.Status == status {
return nil
}
// 2026-11-23 启用强校验:工艺路线、总账、分账缺一不可,防止启用一套空工艺开工后出错。
if status == "ACTIVE" {
missing := make([]string, 0, 3)
routeN, e := s.ctx.EntClient.ProductProcessItem.Query().Where(productprocessitem.ProductProcessId(id)).Count(ctx)
if e != nil || routeN == 0 {
missing = append(missing, "工艺路线(没配工艺顺序)")
}
bomN, e := s.ctx.EntClient.ProductBOM.Query().Where(productbom.ProductCode(p.ProductCode)).Count(ctx)
if e != nil || bomN == 0 {
missing = append(missing, "物料清单总账(产品档案里没维护物料)")
}
allocN, e := s.ctx.EntClient.ProductProcessMaterial.Query().Where(productprocessmaterial.ProductProcessId(id)).Count(ctx)
if e != nil || allocN == 0 {
missing = append(missing, "工艺物料分账(总账里的物料还没分到各工艺)")
}
if len(missing) > 0 {
return errors.New("这套产品工艺还缺:" + strings.Join(missing, "、") + "。请先补齐再启用,缺这些配置开工后备料会算不出来")
}
}
if err := s.ctx.EntClient.ProductProcess.UpdateOneID(id).SetStatus(status).Exec(ctx); err != nil {
return err
}
action := "停用产品工艺"
if status == "ACTIVE" {
action = "启用产品工艺"
}
s.ctx.EventLog.Write(ctx, "product.process.status", "", operator, "product_process", fmt.Sprint(id),
action, map[string]any{"id": id, "name": p.Name, "status": status})
return nil
}
// CopyProductProcessReq 产品工艺复制请求
type CopyProductProcessReq struct {
SourceId int `json:"sourceId"`
NewName string `json:"newName"`
}
// CopyProductProcess 复制产品工艺(全量深拷贝):主表 + 所有明细步骤(ProductProcessItem 按 seq 顺序)。
// 数据模型仅主表+明细两表,无独立"步骤考核标准/物料绑定"子表,故深拷贝二者即覆盖全部内容。
// 默认名"源名-副本";按规则1精神,复制是新工艺,不受"一个产品一个产品工艺"约束(同一产品可有多版本)。
func (s *Service) CopyProductProcess(ctx context.Context, req CopyProductProcessReq, operator string) (int, error) {
if req.SourceId <= 0 {
return 0, errors.New("缺少源产品工艺ID")
}
src, err := s.ctx.EntClient.ProductProcess.Get(ctx, req.SourceId)
if err != nil {
return 0, errors.New("源产品工艺不存在")
}
items, _ := s.ctx.EntClient.ProductProcessItem.Query().
Where(productprocessitem.ProductProcessId(src.ID)).Order(ent.Asc(productprocessitem.FieldSeq)).All(ctx)
newName := strings.TrimSpace(req.NewName)
if newName == "" {
newName = src.Name + "-副本"
}
// 2026-11-17 拍板:复制是「换版草稿」,默认停用,人工确认后再启用,
// 杜绝复制启用中的工艺导致同一产品瞬间出现两套 ACTIVE。
np, err := s.ctx.EntClient.ProductProcess.Create().
SetProductCode(src.ProductCode).SetProductName(src.ProductName).
SetName(newName).SetStatus("INACTIVE").SetRemark(src.Remark).Save(ctx)
if err != nil {
return 0, err
}
for _, it := range items {
if err := s.ctx.EntClient.ProductProcessItem.Create().
SetProductProcessId(np.ID).SetSeq(it.Seq).SetFlowId(it.FlowId).Exec(ctx); err != nil {
return 0, err
}
}
// 2026-11-13 拍板堵后门:复制产品工艺必须同步复制物料分账(按工艺隔离)
allocRows, _ := s.ctx.EntClient.ProductProcessMaterial.Query().
Where(productprocessmaterial.ProductProcessId(src.ID)).All(ctx)
for _, a := range allocRows {
if err := s.ctx.EntClient.ProductProcessMaterial.Create().
SetProductProcessId(np.ID).SetSeq(a.Seq).SetFlowId(a.FlowId).
SetMaterialCode(a.MaterialCode).SetMaterialName(a.MaterialName).
SetUnit(a.Unit).SetUnitQty(a.UnitQty).Exec(ctx); err != nil {
return 0, err
}
}
s.ctx.EventLog.Write(ctx, "product.process.copy", "", operator, "product_process", fmt.Sprint(np.ID),
"复制产品工艺", map[string]any{"fromId": src.ID, "fromName": src.Name, "toId": np.ID, "toName": newName})
return np.ID, nil
}
// DeriveProductProcess 建单自动推导:按产品(或指定 id)取该产品的唯一产品工艺,
// 每道工艺带出其全部启用的绑定工位(升序),拼成工艺组合与实时警告。
// 返回 map{productProcessId,name,items,combination,warnings};无产品工艺时 combination 为空并给提示。
func (s *Service) DeriveProductProcess(ctx context.Context, productCode string, id int) (map[string]any, error) {
q := s.ctx.EntClient.ProductProcess.Query()
if id > 0 {
q = q.Where(productprocess.ID(id))
} else if productCode != "" {
q = q.Where(productprocess.ProductCode(productCode), productprocess.Status("ACTIVE"))
} else {
return nil, errors.New("缺少产品编码或产品工艺ID")
}
pps, err := q.Order(ent.Desc(productprocess.FieldID)).All(ctx)
if err != nil {
return nil, err
}
res := map[string]any{
"productProcessId": 0, "name": "", "productCode": productCode,
"items": []map[string]any{}, "combination": []map[string]int{}, "warnings": []string{},
}
if len(pps) == 0 {
res["warnings"] = []string{"该产品尚未配置产品工艺(可在「产品工艺」页创建)"}
return res, nil
}
pp := pps[0]
res["productProcessId"] = pp.ID
res["name"] = pp.Name
res["productCode"] = pp.ProductCode
items, _ := s.ctx.EntClient.ProductProcessItem.Query().
Where(productprocessitem.ProductProcessId(pp.ID)).
Order(ent.Asc(productprocessitem.FieldSeq)).All(ctx)
flows, _ := s.ctx.EntClient.ProcessFlow.Query().All(ctx)
flowName := map[int]string{}
for _, f := range flows {
flowName[f.ID] = f.Name
}
sts, _ := s.ctx.EntClient.Station.Query().All(ctx)
byFlow := map[int][]int{}
for _, st := range sts {
if st.Status == "ENABLED" && st.FlowId > 0 {
byFlow[st.FlowId] = append(byFlow[st.FlowId], st.StationNo)
}
}
for k := range byFlow {
sort.Ints(byFlow[k])
}
warns := []string{}
itemsVO := []map[string]any{}
combination := []map[string]int{}
for _, it := range items {
stsOfFlow := byFlow[it.FlowId]
itemsVO = append(itemsVO, map[string]any{
"seq": it.Seq, "flowId": it.FlowId, "flowName": flowName[it.FlowId], "stationNos": stsOfFlow,
})
if len(stsOfFlow) == 0 {
warns = append(warns, fmt.Sprintf("第%d道工艺「%s」暂无启用的绑定工位,请先在「工位绑定」中绑定", it.Seq, flowName[it.FlowId]))
continue
}
for _, no := range stsOfFlow {
combination = append(combination, map[string]int{"flowId": it.FlowId, "stationNo": no})
}
}
sort.Slice(combination, func(i, j int) bool { return combination[i]["stationNo"] < combination[j]["stationNo"] })
res["items"] = itemsVO
res["combination"] = combination
res["warnings"] = warns
return res, nil
}
// ComboDeviationWarnings 工单工艺组合与产品工艺的偏差柔性警告(仅提示,不阻断保存):
// 覆盖/个数——产品工艺的每道工艺都须出现在组合中,组合不得包含产品工艺之外的工艺。
// 顺序偏差已于 2026-10-20 客户裁定升级为硬拦截(见 ValidateWorkOrderComboStrict),此处不再重复提示。
func (s *Service) ComboDeviationWarnings(ctx context.Context, ppId int, combo []map[string]int) []string {
if ppId <= 0 {
return nil
}
pp, err := s.ctx.EntClient.ProductProcess.Get(ctx, ppId)
if err != nil {
return []string{"来源产品工艺已删除,无法比对"}
}
items, _ := s.ctx.EntClient.ProductProcessItem.Query().
Where(productprocessitem.ProductProcessId(ppId)).
Order(ent.Asc(productprocessitem.FieldSeq)).All(ctx)
if len(items) == 0 {
return nil
}
flows, _ := s.ctx.EntClient.ProcessFlow.Query().All(ctx)
flowName := map[int]string{}
for _, f := range flows {
flowName[f.ID] = f.Name
}
if len(combo) == 0 {
return []string{fmt.Sprintf("未选择工艺组合:产品工艺「%s」共 %d 道工艺均未包含", pp.Name, len(items))}
}
inCombo := map[int][]int{}
for _, c := range combo {
fid, no := c["flowId"], c["stationNo"]
if fid > 0 && no > 0 {
inCombo[fid] = append(inCombo[fid], no)
}
}
for k := range inCombo {
sort.Ints(inCombo[k])
}
ppFlowSet := map[int]bool{}
for _, it := range items {
ppFlowSet[it.FlowId] = true
}
// 个数汇总(客户裁决:顺序 或 个数 不符都要提示)——先给一条总数对不上的汇总,明细警告跟在后面
have, missingCnt, extraCnt := 0, 0, 0
for fid := range inCombo {
if ppFlowSet[fid] {
have++
} else {
extraCnt++
}
}
missingCnt = len(items) - have
warns := []string{}
if missingCnt > 0 || extraCnt > 0 {
warns = append(warns, fmt.Sprintf("工艺组合道数与产品工艺不符:产品工艺共 %d 道,组合包含 %d 道(缺 %d 道、多 %d 道)",
len(items), have, missingCnt, extraCnt))
}
for _, it := range items {
name := flowName[it.FlowId]
if len(inCombo[it.FlowId]) == 0 {
warns = append(warns, fmt.Sprintf("工艺组合缺少第%d道工艺「%s」", it.Seq, name))
}
}
for fid, sts := range inCombo {
if !ppFlowSet[fid] {
warns = append(warns, fmt.Sprintf("工艺组合包含产品工艺之外的工艺「%s」(%d 个工位)", flowName[fid], len(sts)))
}
}
return warns
}
// productProcessNamesByFlow 反查:工艺ID → 引用它的产品工艺名称列表(工位绑定/工艺列表只读展示用)
func (s *Service) productProcessNamesByFlow(ctx context.Context) map[int][]string {
items, _ := s.ctx.EntClient.ProductProcessItem.Query().All(ctx)
out := map[int][]string{}
if len(items) == 0 {
return out
}
pps, _ := s.ctx.EntClient.ProductProcess.Query().All(ctx)
name := map[int]string{}
for _, p := range pps {
name[p.ID] = p.Name
}
for _, it := range items {
if n := name[it.ProductProcessId]; n != "" {
out[it.FlowId] = append(out[it.FlowId], n)
}
}
return out
}
// ppContainsFold 大小写无关包含(工艺列表按产品工艺名筛选用)
func ppContainsFold(list []string, kw string) bool {
for _, v := range list {
if strings.Contains(strings.ToLower(v), strings.ToLower(kw)) {
return true
}
}
return false
}
// ProductProcessOverview 产品档案「工艺」抽屉用:按成品聚合出当前启用 + 历史版本 + 每套工艺关联的工单号。
// 复用 ListProductProcesses 的 VO(已含工艺顺序/工位/可执行/工单计数),额外补工单号明细。
// 返回 {productCode, active:*VO|null, history:[]VO, workOrders:{ppId:[{id,workOrderNo,status}]}}。
func (s *Service) ProductProcessOverview(ctx context.Context, productCode string) (map[string]any, error) {
res := map[string]any{
"productCode": productCode,
"active": nil,
"history": []*ProductProcessVO{},
"workOrders": map[int][]map[string]any{},
}
if strings.TrimSpace(productCode) == "" {
return res, nil
}
raw, err := s.ListProductProcesses(ctx, productCode, "", 0, "", "", 0, 0, 0, 0)
if err != nil {
return nil, err
}
list, _ := raw.([]*ProductProcessVO)
history := make([]*ProductProcessVO, 0)
woMap := map[int][]map[string]any{}
for _, vo := range list {
if vo.Status == "ACTIVE" && res["active"] == nil {
res["active"] = vo
} else {
history = append(history, vo)
}
}
res["history"] = history
// 本成品全部工艺 ID → 查关联工单号(含历史工单,供抽屉展示「这套工艺被哪些工单用过」)
ids := make([]int, 0, len(list))
for _, vo := range list {
ids = append(ids, vo.Id)
}
if len(ids) > 0 {
wos, _ := s.ctx.EntClient.WorkOrder.Query().Where(workorder.ProductProcessIdIn(ids...)).All(ctx)
for _, w := range wos {
woMap[w.ProductProcessId] = append(woMap[w.ProductProcessId], map[string]any{
"id": w.ID, "workOrderNo": w.WorkOrderNo, "status": w.Status,
})
}
}
res["workOrders"] = woMap
return res, nil
}