Files
bj_power/bj_power_mes/internal/logic/productprocess.go
T
SunYF 8be6e03a15 docs: 统一修正全项目“SN管理”相关术语为“序列号”
本次 commit 统一修正了全项目范围内关于 SN 管理的术语表述,将原“SN管理”、“序列号件”、“批次件”等表述调整为“序列号”、“序列号=是”、“序列号=否”,同时同步更新了相关文档、代码注释、前端提示文本、数据库 schema 注释、API 文档等,确保全链路术语统一,消除理解歧义。
2026-10-10 15:58:59 +08:00

486 lines
18 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"
"strings"
"time"
"bj_power_mes/ent"
"bj_power_mes/ent/productprocess"
"bj_power_mes/ent/productprocessitem"
"bj_power_mes/ent/workorder"
)
// ---------- 产品工艺(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"`
// 只读:被工单引用次数(>0 时只读:禁编辑禁删,只能停用+新建)
UsedByWorkOrders int `json:"usedByWorkOrders"`
// 只读:可执行状态(所有工艺都有启用工位绑定且顺序可满足)
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 string, 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 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)
}
// 工单引用计数
used := map[int]int{}
wos, _ := s.ctx.EntClient.WorkOrder.Query().Where(workorder.ProductProcessIdGT(0)).All(ctx)
for _, w := range wos {
used[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], 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)
}
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,直接报错"该产品已有产品工艺,请直接编辑");
// ④ 被工单引用过的只读,禁编辑;⑤ 名称未传时按"${物料编码} ${物料名称} 工艺"兜底。
func (s *Service) SaveProductProcess(ctx context.Context, req ProductProcessReq, operator string) error {
if strings.TrimSpace(req.ProductCode) == "" {
return errors.New("请选择产品")
}
// 名称兜底(前端未传时按 物料编码 物料名称 工艺 生成)
if strings.TrimSpace(req.Name) == "" {
req.Name = strings.TrimSpace(req.ProductCode) + " " + strings.TrimSpace(req.ProductName) + " 工艺"
}
if len(req.Flows) == 0 {
return errors.New("请至少选择一道工艺")
}
seen := map[int]bool{}
for _, f := range req.Flows {
if f.FlowId <= 0 {
return errors.New("工艺选择无效")
}
if seen[f.FlowId] {
return errors.New("同一工艺不能在同一产品工艺内出现两次")
}
seen[f.FlowId] = true
if _, err := s.ctx.EntClient.ProcessFlow.Get(ctx, f.FlowId); err != nil {
return errors.New("所选工艺不存在(ID=" + fmt.Sprint(f.FlowId) + ")")
}
}
status := req.Status
if status == "" {
status = "ACTIVE"
}
if status != "ACTIVE" && status != "INACTIVE" {
return errors.New("非法状态")
}
var ppID int
if req.Id > 0 {
if _, err := s.ctx.EntClient.ProductProcess.Get(ctx, req.Id); err != nil {
return errors.New("产品工艺不存在")
}
if n, _ := s.ctx.EntClient.WorkOrder.Query().Where(workorder.ProductProcessId(req.Id)).Count(ctx); n > 0 {
return errors.New(fmt.Sprintf("该产品工艺已被 %d 张工单引用,只读不可编辑(如需调整请停用后新建)", n))
}
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 {
// 一个产品对应一个产品工艺:新建时若已存在则直接报错
if n, _ := s.ctx.EntClient.ProductProcess.Query().Where(productprocess.ProductCode(req.ProductCode)).Count(ctx); n > 0 {
return errors.New("该产品已有产品工艺,请直接编辑")
}
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
}
// 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{}
prevMax := 0
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
}
if prevMax > 0 && stsOfFlow[0] <= prevMax {
warns = append(warns, fmt.Sprintf("第%d道工艺「%s」(工位%d) 与上一道工位顺序冲突(工位号需按顺序递增)", it.Seq, flowName[it.FlowId], stsOfFlow[0]))
}
if stsOfFlow[len(stsOfFlow)-1] > prevMax {
prevMax = stsOfFlow[len(stsOfFlow)-1]
}
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 工单工艺组合与产品工艺的偏差警告(仅提示,不阻断保存):
// ① 覆盖/个数——产品工艺的每道工艺都须出现在组合中,组合不得包含产品工艺之外的工艺;
// ② 顺序——各道工艺在组合中的首个工位号须按 seq 递增。
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))
}
prevFirst := 0
for _, it := range items {
name := flowName[it.FlowId]
sts := inCombo[it.FlowId]
if len(sts) == 0 {
warns = append(warns, fmt.Sprintf("工艺组合缺少第%d道工艺「%s」", it.Seq, name))
continue
}
if prevFirst > 0 && sts[0] <= prevFirst {
warns = append(warns, fmt.Sprintf("工艺组合顺序与产品工艺不一致:第%d道「%s」(工位%d) 不在上一道工艺之后", it.Seq, name, sts[0]))
}
prevFirst = sts[0]
}
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
}