Files
bj_power/bj_power_mes/internal/logic/productprocess.go
T
SunYF 20e061c969 feat(mes/wms/终端): 三端统一对时JWT验签 + 盘点按库位拆快照 + 档案删除口径 + 退库单数量修正(2026-11-24 全场整改)
【全系统 · 时间权威与鉴权(核心)】
- 新增 clock 包(三端各一份):谁签发 JWT 就以谁的时间验 exp——验签方向签发方取 /api/server-time(30s 缓存,取不到降级本机 + 10min 容差兜底),本端签发用本机时间
- 三端均注册 GET /api/server-time;MES/WMS/终端配同一份「签发方→取时间地址」映射
- 密钥 SHA256 前 8 位指纹日志([鉴权诊断]),现场比对两端指纹秒定位密钥不一致导致的 401「登录已失效」
- token 由 localStorage 改 sessionStorage;登录响应带服务器时间,偏差只提示「时间已自动校正」不拦截
- 现场人工 w32tm 对时操作卡作废(随文档留存,正常部署无需执行)

【WMS · 库存盘点重构】
- 快照粒度改「物料 × 库位」:同物料 A/B 区拆两条各盘各的;扫码命中多行弹库位清单逐库位录入、写回精确定位,行不存在报错不静默跳过
- GET /api/stocktake/active 返回全部进行中单(旧 .First() 只返一条导致历史多单看不见、库存长期冻结);前端加单号下拉切换,刷新保持当前单
- 历史卡死单只走「完成/取消」事务解冻,严禁删库;写回任何一行失败都强提示,不吞错
- 去「全库」,按区域筛选支持选到区/货架/层/号任意层级;「本次盘点范围」同步加筛选、物料按区域过滤;去多余「(可选)」字样

【WMS/MES · 档案删除与停用口径】
- 产品档案新建默认停用(product_process.status ACTIVE→INACTIVE),配齐工艺路线+总账+分账才允许启用
- 产品/物料档案删除按钮统一为一个(按 WMS 做法),仅「无任何引用」可物理删;引用检查覆盖两库、查库报错一律拒绝删除(fail-close,不再误删)
- 产品编码自动生成,重复则自增保证唯一;权限对齐:停用走「编辑」、删除走独立「删除」码
- WMS 删物料同步核查 MES 引用,MES 不可达/删除失败则拒绝并落同步失败台账,无兼容补录行

【业务整改】
- MES 工单整体完工自动结算遗留 PENDING 叫料单(释放占用额度);已发货 SHIPPED 不动,仅落日志提示人工签收
- WMS 已收货退库单支持直接修正数量(问题14):原单不动、留痕(修正人/时间/原因/前后值),库存差额补扣,SN 件按最终 SN 集合增删行
- 日排产:「排产日期范围」→「排产日期」;平铺补产品编码/名称;「产品型号」→「产品」去产品编号/名称;平均分摊与每日固定互算;删除写操作日志
- 齐套测算:逐日消耗模拟按实际排产日期;工单详情增「总物料清单」(照搬产品档案总账,实时)
- PLC 对账:虚拟/离线工位(OFFLINE,如 15)跳过 PLC 托盘位读取,不再为特例扔给 PLC
- AGV 点位锁与回调细节按 11-20 现场整改继续修正(agv.go / agv_point_lock.go)

【文档】
- 新增《全系统业务深坑审计报告》《全系统串联审计报告》《现场对时操作卡》;更新产线API.md、案例.md、问题临时.md(记录甲方逐条原话与验收口径)
2026-11-24 22:11:12 +08:00

677 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("CREATED", "IN_PROGRESS", "PAUSED", "RELEASED", "PENDING")).Count(ctx); n > 0 {
// 规则1(2026-10-20 拍板,2026-11-05 修订):有未完成的工单(未开工 CREATED/执行中/已暂停)
// 引用 → 定义与明细(flows)一并禁改,保证已建工单的路线快照前后一致;给「复制工艺」一键跳转
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
}