Files
bj_power/bj_power_mes/internal/logic/productprocess.go
T

565 lines
22 KiB
Go
Raw Normal View History

package logic
import (
"context"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
"bj_power_mes/ent"
"bj_power_mes/ent/productprocess"
"bj_power_mes/ent/productprocessitem"
"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"`
}
// 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"`
// 只读:运行中工单(IN_PROGRESS/PAUSED)引用数 —— >0 时编辑接口拒绝(规则1,2026-10-20)
RunningByWorkOrders int `json:"runningByWorkOrders"`
// 只读:未开工工单(CREATED)引用数 —— >0 时允许编辑,前端保存前警告确认(规则1)
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 返回全量数组(工单页下拉用)。
2026-10-26 16:32:35 +08:00
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)
}
2026-10-26 16:32:35 +08:00
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):总数 + 运行中(IN_PROGRESS/PAUSED)+ 未开工(CREATED)分档
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":
usedRunning[w.ProductProcessId]++
case "CREATED", "PENDING":
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)
}
2026-10-26 16:32:35 +08:00
// 工序数范围过滤:按产品工艺的工艺顺序/工序条目数(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):运行中工单(IN_PROGRESS/PAUSED)引用 → 禁编辑;仅未开工(CREATED)引用 → 允许(前端警告确认);
// ⑤ 名称未传时按"${物料编码} ${物料名称} 工艺"兜底。
func (s *Service) SaveProductProcess(ctx context.Context, req ProductProcessReq, operator string) 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 = "ACTIVE"
}
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", "PAUSED")).Count(ctx); n > 0 {
// 规则1(2026-10-20):运行中工单引用 → 拒绝编辑,给「复制工艺」一键跳转
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 err
}
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 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 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 err
}
}
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 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)
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
}
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 + "-副本"
}
np, err := s.ctx.EntClient.ProductProcess.Create().
SetProductCode(src.ProductCode).SetProductName(src.ProductName).
SetName(newName).SetStatus(src.Status).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
}
}
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
}