feat: 新增产品工艺管理与工序审核功能

- 新增产品工艺(product_process)及明细(product_process_item)数据模型
- 新增工序审核开关(need_audit)与审核角色(audit_role)字段
- 新增待审核签字页面与路由
- 优化 WMS/MES 接口交互,增加业务错误处理与友好提示
- 补充库存过滤逻辑,避免返回已出库 SN 数据
- 调整默认查询时间范围为近一个月,优化用户体验
This commit is contained in:
SunYF
2026-10-09 13:46:33 +08:00
parent e2f1dacf76
commit b032f47fc7
95 changed files with 10546 additions and 1457 deletions
+55 -25
View File
@@ -98,6 +98,14 @@ func (s *Service) GenerateMaterialRequest(ctx context.Context, planDate string,
return 0, missing, nil
}
// 阶段2:全部存在 → 按 组合条目 × flow_material × 分产量 拆料生成
// 幂等查重(AITEST 闭环实测缺陷):同 工单+排产日+物料+工位+工艺 已有备料单则跳过,
// 否则每次调用 generate 都翻倍生成重复单据(重复出库/重复备料,生产级事故源)。
existing, _ := s.ctx.EntClient.MaterialRequest.Query().
Where(materialrequest.PlanDateEQ(planDate)).All(ctx)
existKey := make(map[string]bool, len(existing))
for _, mr := range existing {
existKey[mr.OrderNo+"|"+mr.MaterialCode+"|"+strconv.Itoa(mr.StationNo)+"|"+strconv.Itoa(mr.FlowId)] = true
}
created := 0
tsBase := time.Now().Format("20060102150405")
seq := 1
@@ -137,16 +145,23 @@ func (s *Service) GenerateMaterialRequest(ctx context.Context, planDate string,
if fm.MaterialCode == "" {
continue
}
for i, stNo := range stations {
q := qtys[i]
if q <= 0 {
continue
}
reqQty := float64(q) * fm.UnitQty * (1 + fm.LossRate/100)
if reqQty <= 0 {
continue
}
reqNo := fmt.Sprintf("MR%s%03d", tsBase, seq)
for i, stNo := range stations {
q := qtys[i]
if q <= 0 {
continue
}
// 损耗向上取整:备料单需求数量必须为整数(接料/出库按整数收发),
// 小数 reqQty 会使接料接口(int)永远无法收满、备料单永远无法完结(AITEST 闭环实测缺陷)
reqQty := math.Ceil(float64(q) * fm.UnitQty * (1 + fm.LossRate/100))
if reqQty <= 0 {
continue
}
// 幂等:该 工单+物料+工位+工艺 当日已有单则跳过(重复调用不翻倍)
dedupKey := g.plan.OrderNo + "|" + fm.MaterialCode + "|" + strconv.Itoa(stNo) + "|" + strconv.Itoa(flowId)
if existKey[dedupKey] {
continue
}
reqNo := fmt.Sprintf("MR%s%03d", tsBase, seq)
seq++
_ = s.ctx.EntClient.MaterialRequest.Create().
SetRequestNo(reqNo).SetOrderNo(g.plan.OrderNo).SetPlanDate(g.plan.PlanDate).
@@ -184,30 +199,41 @@ func (s *Service) GenerateMaterialRequest(ctx context.Context, planDate string,
// SyncOrderLedger 计算并向 WMS 下发某工单的「工单级物料需求总量」(需求10)。
//
// 需求量口径(临时.md §四 工单域):需求量 = 工单数量 × 单台含损耗用量,向上取整。
// 工单级而非日级——用日级会误卡跨天生产(临时.md L283-285)。
// 用料唯一来源 = 工单工艺组合×工艺物料清单(BOM 已删除),同物料合并,一个物料一行下发。
// WMS 侧按 orderNo+materialCode 幂等 upsert total_qty,可重复调用。
// 需求量口径(AITEST 闭环实测修正):= 该工单全部备料单 reqQty 之和(损耗按工位拆单逐单向上取整)。
// 原按「工单数量×单台用量」整体取整的算法与工位级拆单逐单取整必然不一致(拆单合计 ≥ 整体取整),
// 会导致自动出库合计触发 WMS 台账超量拦截、备料单永远无法出齐(如 拆单合计 8 > 整体取整 7)。
// 改为聚合备料单:total 与单据精确自洽,generate 幂等生成新单后重复调用自动增长,WMS 侧按
// orderNo+materialCode 幂等 upsert total_qty。
// 工单尚无备料单时不下发(保持 WMS 既有 total 不变,避免误清零)。
func (s *Service) SyncOrderLedger(ctx context.Context, orderNo, operator string) error {
wo, err := s.ctx.EntClient.WorkOrder.Query().
Where(workorder.WorkOrderNo(orderNo)).Only(ctx)
if err != nil {
return err
}
usage := s.WorkOrderUnitUsage(ctx, wo)
if len(usage) == 0 {
mrs, err := s.ctx.EntClient.MaterialRequest.Query().
Where(materialrequest.OrderNoEQ(orderNo)).All(ctx)
if err != nil {
return err
}
if len(mrs) == 0 {
return nil
}
items := make([]wmsclient.LedgerSyncItem, 0, len(usage))
for _, it := range usage {
need := float64(wo.Quantity) * it.EffQty
if need <= 0 {
agg := map[string]int{} // materialCode → ΣreqQty(逐单向上取整后求和)
names := map[string]string{}
for _, mr := range mrs {
agg[mr.MaterialCode] += int(math.Ceil(mr.ReqQty))
names[mr.MaterialCode] = mr.MaterialName
}
items := make([]wmsclient.LedgerSyncItem, 0, len(agg))
for code, total := range agg {
if total <= 0 {
continue
}
items = append(items, wmsclient.LedgerSyncItem{
MaterialCode: it.MaterialCode,
MaterialName: it.MaterialName,
TotalQty: int(math.Ceil(need - 1e-9)),
MaterialCode: code,
MaterialName: names[code],
TotalQty: total,
})
}
if len(items) == 0 {
@@ -275,7 +301,10 @@ func (s *Service) AutoOutboundRequests(ctx context.Context, planDate, orderNo, o
opts.SnList = []string{sn}
opts.BatchNo = ""
opts.Qty = 1
opts.IdempotencyKey = fmt.Sprintf("IDEM-%s-%s-%s-%d", mr.OrderNo, mr.MaterialCode, sn, round)
// 幂等键必须含备料单号:同工单+同物料会按工位拆成多张备料单,
// 若只用 orderNo+物料做键,各单 round=1 必然撞键——WMS 幂等复用吞掉
// 第二张单的扣减,MES 却虚增 sent_qty 并置 LOCKED(账实不符,AITEST 闭环实测)。
opts.IdempotencyKey = fmt.Sprintf("IDEM-%s-%s-%d", mr.RequestNo, sn, round)
no, _, _, e := s.ctx.Wms.StockDeduct(ctx, mr.OrderNo, mr.MaterialCode, opts)
if e != nil {
break
@@ -300,7 +329,8 @@ func (s *Service) AutoOutboundRequests(ctx context.Context, planDate, orderNo, o
opts.BatchNo = b.BatchNo
opts.Qty = take
opts.ZoneCode = b.ZoneCode
opts.IdempotencyKey = fmt.Sprintf("IDEM-%s-%s-%s-%d", mr.OrderNo, mr.MaterialCode, b.BatchNo, round)
// 同上:幂等键含备料单号,杜绝工位级拆单跨单撞键(AITEST 闭环实测缺陷)
opts.IdempotencyKey = fmt.Sprintf("IDEM-%s-%s-%d", mr.RequestNo, b.BatchNo, round)
no, _, _, e := s.ctx.Wms.StockDeduct(ctx, mr.OrderNo, mr.MaterialCode, opts)
if e != nil {
break
+20 -4
View File
@@ -43,12 +43,14 @@ type FlowVO struct {
Remark string `json:"remark"`
Stations []int `json:"stations"`
Steps []*ProcessStepTemplate `json:"steps"`
CreatedAt time.Time `json:"createdAt"`
// 只读反查:引用本工艺的产品工艺名称列表(产品工艺明细实时反查)
ProductProcesses []string `json:"productProcesses"`
CreatedAt time.Time `json:"createdAt"`
}
// ListFlows 查询工艺流程(可按工位号过滤:只认「关联工位」页的绑定关系 station.flow_id)
// page>0 时真分页返回 map{total,list,page,pageSize}(管理页用);page=0 全量数组(工位终端兼容)
func (s *Service) ListFlows(ctx context.Context, stationNo, page, pageSize int) (any, error) {
// ListFlows 查询工艺流程(可按工位号过滤:只认「关联工位」页的绑定关系 station.flow_id;
// pp 非空时按引用该工艺的产品工艺名称反查过滤)。page>0 时真分页返回 map{total,list,page,pageSize}(管理页用);page=0 全量数组(工位终端兼容)
func (s *Service) ListFlows(ctx context.Context, stationNo int, pp string, page, pageSize int) (any, error) {
q := s.ctx.EntClient.ProcessFlow.Query().
Order(ent.Asc(processflow.FieldID))
flows, err := q.All(ctx)
@@ -62,6 +64,7 @@ func (s *Service) ListFlows(ctx context.Context, stationNo, page, pageSize int)
flowToStations[st.FlowId] = append(flowToStations[st.FlowId], st.StationNo)
}
}
ppNames := s.productProcessNamesByFlow(ctx)
out := make([]*FlowVO, 0, len(flows))
for _, f := range flows {
// 过滤:指定工位号时,只返回绑定了该工位的流程
@@ -85,6 +88,13 @@ func (s *Service) ListFlows(ctx context.Context, stationNo, page, pageSize int)
if list, ok := flowToStations[f.ID]; ok {
vo.Stations = list
}
if vo.ProductProcesses = ppNames[f.ID]; vo.ProductProcesses == nil {
vo.ProductProcesses = []string{}
}
// 产品工艺反查过滤(模糊,大小写无关)
if pp != "" && !ppContainsFold(vo.ProductProcesses, pp) {
continue
}
out = append(out, vo)
}
if page > 0 {
@@ -264,6 +274,8 @@ type StationVO struct {
Status string `json:"status"`
IsBuiltin bool `json:"isBuiltin"`
VisibleTabs []string `json:"visibleTabs"`
// 只读反查:本工位绑定工艺被哪些产品工艺引用(名称列表)
ProductProcesses []string `json:"productProcesses"`
}
func (s *Service) ListStations(ctx context.Context) ([]*StationVO, error) {
@@ -276,12 +288,16 @@ func (s *Service) ListStations(ctx context.Context) ([]*StationVO, error) {
for _, f := range flows {
flowMap[f.ID] = f
}
ppNames := s.productProcessNamesByFlow(ctx)
out := make([]*StationVO, 0, len(stas))
for _, st := range stas {
vo := &StationVO{Id: st.ID, StationNo: st.StationNo, Name: st.Name, FlowId: st.FlowId, StationType: st.StationType, Status: st.Status, IsBuiltin: st.IsBuiltin, VisibleTabs: st.VisibleTabs}
if f, ok := flowMap[st.FlowId]; ok {
vo.FlowName = f.Name
}
if vo.ProductProcesses = ppNames[st.FlowId]; vo.ProductProcesses == nil {
vo.ProductProcesses = []string{}
}
out = append(out, vo)
}
return out, nil
+3 -2
View File
@@ -105,7 +105,7 @@ func (s *Service) loadOrderUsage(ctx context.Context, orderNos []string) map[str
// 两系统独立运行约束:未配置 WMS 或不可达时返回错误,由调用方(WMS)提示,绝不阻塞 MES。
func (s *Service) ComputeProducible(ctx context.Context) (*ProducibleResult, error) {
if s.ctx.Wms == nil || s.ctx.EntClient == nil {
return nil, errors.New("未配置 WMS 地址,无法计算可生产数量")
return nil, errors.New("未配置 WMS 服务地址,无法计算可生产数量;请在系统设置中填写 WMS 地址后重试")
}
today := time.Now().Format("2006-01-02")
planQty, err := s.planOrdersBetween(ctx, today, addDays(today, 59))
@@ -139,7 +139,8 @@ func (s *Service) ComputeProducible(ctx context.Context) (*ProducibleResult, err
sort.Strings(codes)
avail, err := s.ctx.Wms.StockAvailable(ctx, codes)
if err != nil {
return nil, errors.New("拉取 WMS 可用量失败: " + err.Error())
// 业务友好提示:不把底层网络/连接技术细节返回给前端;详细错误由 EventLog 与框架日志捕获
return nil, errors.New("无法获取 WMS 库存可用量(WMS 服务未启动或网络不可达),排产支撑暂不可用;请检查 WMS 服务状态或稍后重试")
}
// 产品名称映射(本地成品档案优先=M6,工单快照兜底)
@@ -0,0 +1,497 @@
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"`
IsDefault bool `json:"isDefault"`
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"`
IsDefault bool `json:"isDefault"`
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.ProductCodeContains(productCode))
}
if status != "" {
q = q.Where(productprocess.Status(status))
}
if keyword != "" {
kw := productprocess.Or(
productprocess.NameContains(keyword),
productprocess.ProductCodeContains(keyword),
productprocess.ProductNameContains(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,
IsDefault: p.IsDefault, 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 保存产品工艺(新建或整表覆盖明细)。
// 约束:① 名称/产品必填,明细非空;② 同一工艺不能在同一产品工艺内出现两次(客户裁决);
// ③ is_default 每产品至多一条(设新自动取消旧);④ 被工单引用过的只读,禁编辑。
func (s *Service) SaveProductProcess(ctx context.Context, req ProductProcessReq, operator string) error {
if strings.TrimSpace(req.Name) == "" {
return errors.New("请填写产品工艺名称")
}
if strings.TrimSpace(req.ProductCode) == "" {
return errors.New("请选择产品")
}
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("非法状态")
}
// is_default 唯一性:设为默认时取消同产品旧默认
clearDefault := func(code string) {
_, _ = s.ctx.EntClient.ProductProcess.Update().
Where(productprocess.ProductCode(code), productprocess.IsDefault(true)).
SetIsDefault(false).Save(ctx)
}
var ppID int
if req.Id > 0 {
old, err := s.ctx.EntClient.ProductProcess.Get(ctx, req.Id)
if 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).SetIsDefault(req.IsDefault).SetStatus(status).SetRemark(req.Remark).
Save(ctx); err != nil {
return err
}
ppID = req.Id
// 产品编码可能被改:新旧两个编码下的默认都要校正
clearDefault(old.ProductCode)
if old.ProductCode != req.ProductCode {
clearDefault(req.ProductCode)
}
} else {
p, err := s.ctx.EntClient.ProductProcess.Create().
SetProductCode(req.ProductCode).SetProductName(req.ProductName).
SetName(req.Name).SetIsDefault(req.IsDefault).SetStatus(status).SetRemark(req.Remark).
Save(ctx)
if err != nil {
return err
}
ppID = p.ID
}
if req.IsDefault {
clearDefault(req.ProductCode)
_, _ = s.ctx.EntClient.ProductProcess.UpdateOneID(ppID).SetIsDefault(true).Save(ctx)
}
// 明细整表覆盖(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 建单自动推导:按产品取默认(或指定)产品工艺,
// 每道工艺带出其全部启用的绑定工位(升序),拼成工艺组合与实时警告。
// 返回 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.FieldIsDefault), 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
}
+8
View File
@@ -27,12 +27,15 @@ func (s *Service) Seed(ctx context.Context) error {
"produce.workorder", "produce.dailyplan", "produce.material", "produce.producible",
"produce.trace", "produce.wip", "produce.plc", "produce.product",
"produce.processflow", "produce.station", "produce.performance", "produce.processcard",
// 产品工艺(产品级工艺定义,2026-10-09)+ 待审核签字
"produce.productprocess", "produce.audit",
// 按钮级权限(块2)
"produce.workorder:add", "produce.workorder:edit", "produce.workorder:delete",
"produce.workorder:dailyplan", "produce.material:generate", "produce.material:outbound",
"produce.plc:send", "produce.product:add", "produce.product:edit", "produce.product:delete",
"produce.processflow:add", "produce.processflow:edit", "produce.processflow:delete",
"produce.processflow:upload", "produce.station:edit", "produce.station:add", "produce.station:delete",
"produce.productprocess:add", "produce.productprocess:edit", "produce.productprocess:delete",
// 预警中心 / 附件中心(含归档清理按钮)
"sys.alert", "sys.attachment", "sys.attachment:manage",
// 数量不符处理(上报在工位终端,处理在本页)
@@ -85,6 +88,7 @@ func (s *Service) Seed(ctx context.Context) error {
{"produce.qty", "数量不符处理", "MENU", "/qty-report"},
{"produce.plc", "工位组合下发", "MENU", "/plc-send"},
{"produce.processflow", "工艺流程", "MENU", "/process-flow"},
{"produce.productprocess", "产品工艺", "MENU", "/product-process"},
{"produce.station", "关联工位", "MENU", "/station"}, {"produce.performance", "绩效报表", "MENU", "/performance"},
{"produce.dock", "接驳台维护", "MENU", "/dock"},
{"produce.trace", "工件追溯", "MENU", "/trace"},
@@ -93,6 +97,7 @@ func (s *Service) Seed(ctx context.Context) error {
{"produce.virtualstation", "虚拟工位作业", "MENU", "/virtual-station"},
{"produce.wip", "在制品", "MENU", "/wip"},
{"produce.processcard", "生产流程卡", "MENU", "/process-card"},
{"produce.audit", "待审核签字", "MENU", "/audit-pending"},
{"produce.product", "物料档案", "MENU", "/product-type"},
{"produce.quality", "质量检验", "MENU", "/quality"},
{"sys.inspect", "巡检终端", "MENU", "/inspect"},
@@ -139,6 +144,9 @@ func (s *Service) Seed(ctx context.Context) error {
{"produce.processflow:edit", "工艺流程-编辑", "BUTTON", "", "produce.processflow"},
{"produce.processflow:delete", "工艺流程-删除", "BUTTON", "", "produce.processflow"},
{"produce.processflow:upload", "工艺流程-上传图纸", "BUTTON", "", "produce.processflow"},
{"produce.productprocess:add", "产品工艺-新增", "BUTTON", "", "produce.productprocess"},
{"produce.productprocess:edit", "产品工艺-编辑", "BUTTON", "", "produce.productprocess"},
{"produce.productprocess:delete", "产品工艺-删除", "BUTTON", "", "produce.productprocess"},
{"produce.station:edit", "工位-绑定与改名", "BUTTON", "", "produce.station"},
{"produce.station:add", "工位-新增", "BUTTON", "", "produce.station"},
{"produce.station:delete", "工位-删除", "BUTTON", "", "produce.station"},
+189
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"strings"
"time"
"bj_power_mes/ent"
"bj_power_mes/ent/stepsignrecord"
@@ -105,6 +106,102 @@ func (s *Service) InspectorSign(ctx context.Context, req InspectorSignReq, opera
return nil
}
// AuditorSignReq 审核人复核签字请求(工序级审核 gate,工艺配置 needAudit 决定)。
type AuditorSignReq struct {
Sn string `json:"sn"`
OrderNo string `json:"orderNo"`
StationNo string `json:"stationNo"`
StepId int `json:"stepId"`
Result string `json:"result"` // OK / NG(NG=审核不通过,退回操作工重做)
Remark string `json:"remark"`
}
// AuditorSign 落审核人复核签字(signRole=AUDITOR);前置:步骤须 needAudit=true,且前置签字
// (若 needInspectorSign 则检验员须 OK,否则操作工已签)已存在。
// result=NG 表示审核不通过,撤销该步骤已有的操作工/检验员签字,退回操作工重做(新一轮轮次)。
func (s *Service) AuditorSign(ctx context.Context, req AuditorSignReq, operator string) error {
req.Sn = strings.TrimSpace(req.Sn)
req.StationNo = strings.TrimSpace(req.StationNo)
req.OrderNo = strings.TrimSpace(req.OrderNo)
if req.Sn == "" || req.StationNo == "" || req.StepId <= 0 {
return errors.New("审核参数不完整:缺少 SN / 工位号 / 步骤")
}
if operator == "" {
return errors.New("未获取到审核人身份,请重新登录")
}
client := s.ctx.EntClient
ps, err := client.ProcessStep.Get(ctx, req.StepId)
if err != nil {
return errors.New("工艺步骤不存在:" + itoa(req.StepId))
}
if !ps.NeedAudit {
return errors.New("该步骤未配置「需审核人复核」,无需审核")
}
result := strings.ToUpper(strings.TrimSpace(req.Result))
if result != "OK" && result != "NG" {
result = "OK"
}
// 前置签字校验(审核在签字链末端)
if ps.NeedInspectorSign {
inspOK, e := client.StepSignRecord.Query().
Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo),
stepsignrecord.StepId(req.StepId), stepsignrecord.SignRole("INSPECTOR"),
stepsignrecord.Revoked(false), stepsignrecord.Result("OK"), stepsignrecord.SignedByNEQ("")).Exist(ctx)
if e != nil {
return e
}
if !inspOK {
return errors.New("检验员尚未 OK 签字,审核人不能先于检验员复核")
}
} else {
opSigned, e := client.StepSignRecord.Query().
Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo),
stepsignrecord.StepId(req.StepId), stepsignrecord.SignRole("OPERATOR"),
stepsignrecord.Revoked(false), stepsignrecord.SignedByNEQ("")).Exist(ctx)
if e != nil {
return e
}
if !opSigned {
return errors.New("操作工尚未签字,审核人不能复核")
}
}
// 计算轮次(每轮审核递增)
recs, e := client.StepSignRecord.Query().
Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo),
stepsignrecord.StepId(req.StepId), stepsignrecord.SignRole("AUDITOR")).All(ctx)
if e != nil {
return e
}
round := 1
for _, r := range recs {
if r.Round >= round {
round = r.Round + 1
}
}
if result == "NG" {
// 退回操作工重做:撤销该步骤已有的操作工/检验员签字
_, _ = client.StepSignRecord.Update().
Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo),
stepsignrecord.StepId(req.StepId),
stepsignrecord.SignRoleIn("OPERATOR", "INSPECTOR"), stepsignrecord.Revoked(false)).
SetRevoked(true).SetRevokedBy(operator).
SetRevokedAt(time.Now()).SetRevokeReason("审核不通过,退回重做").Save(ctx)
}
_, err = client.StepSignRecord.Create().
SetSn(req.Sn).SetOrderNo(req.OrderNo).SetFlowId(ps.FlowId).
SetStationNo(req.StationNo).SetStepId(req.StepId).SetStepName(ps.Name).
SetSignRole("AUDITOR").SetResult(result).
SetSignedBy(operator).SetRound(round).
SetSource("audit").SetRemark(req.Remark).Save(ctx)
if err != nil {
if isUniqueSignViolation(err) {
return errors.New("该步骤已审核,请勿重复提交")
}
return err
}
return nil
}
// isUniqueSignViolation 判定是否为签字唯一索引冲突(并发签字竞态)
func isUniqueSignViolation(err error) bool {
if err == nil {
@@ -204,3 +301,95 @@ func (s *Service) PendingSigns(ctx context.Context, f PendingSignFilter) ([]Step
}
return list[start:end], total, nil
}
// PendingAuditFilter 待审核查询过滤(审核人「待审任务」数据源)。
type PendingAuditFilter struct {
Sn string `json:"sn"`
OrderNo string `json:"orderNo"`
StationNo string `json:"stationNo"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
}
// PendingAudits 聚合「前置签字已满足、待审核人复核」的工艺步骤。
// 基数=操作工已签字(未撤销)的步骤;排除:已有审核 OK 的步骤;以及检验未通过(存在检验员签字记录但未 OK)的步骤。
func (s *Service) PendingAudits(ctx context.Context, f PendingAuditFilter) ([]StepSignVO, int, error) {
client := s.ctx.EntClient
q := client.StepSignRecord.Query().
Where(stepsignrecord.SignRole("OPERATOR"), stepsignrecord.Revoked(false), stepsignrecord.SignedByNEQ(""))
if f.Sn != "" {
q = q.Where(stepsignrecord.Sn(f.Sn))
}
if f.OrderNo != "" {
q = q.Where(stepsignrecord.OrderNo(f.OrderNo))
}
if f.StationNo != "" {
q = q.Where(stepsignrecord.StationNo(f.StationNo))
}
ops, err := q.Order(ent.Desc(stepsignrecord.FieldID)).All(ctx)
if err != nil {
return nil, 0, err
}
type signKey struct {
sn, stationNo string
stepId int
}
inspectorAny := map[signKey]bool{}
inspectorOK := map[signKey]bool{}
auditOK := map[signKey]bool{}
insp, e := client.StepSignRecord.Query().
Where(stepsignrecord.SignRoleIn("INSPECTOR", "AUDITOR"), stepsignrecord.Revoked(false),
stepsignrecord.SignedByNEQ("")).All(ctx)
if e != nil {
return nil, 0, e
}
for _, r := range insp {
k := signKey{r.Sn, r.StationNo, r.StepId}
if r.SignRole == "INSPECTOR" {
inspectorAny[k] = true
if r.Result == "OK" {
inspectorOK[k] = true
}
}
if r.SignRole == "AUDITOR" && r.Result == "OK" {
auditOK[k] = true
}
}
list := make([]StepSignVO, 0, len(ops))
for _, r := range ops {
k := signKey{r.Sn, r.StationNo, r.StepId}
if auditOK[k] {
continue
}
if inspectorAny[k] && !inspectorOK[k] {
// 检验环节未通过,未到审核阶段
continue
}
signedAt := r.SignedAt.Format("2006-01-02 15:04:05")
list = append(list, StepSignVO{
ID: r.ID, Sn: r.Sn, OrderNo: r.OrderNo, FlowId: r.FlowId,
StationNo: r.StationNo, StepId: r.StepId, StepName: r.StepName,
SignRole: r.SignRole, Result: r.Result, SignedBy: r.SignedBy,
SignedAt: signedAt, Round: r.Round, Source: r.Source,
OperatorSigner: r.SignedBy, OperatorSignedAt: signedAt,
})
}
total := len(list)
ps := f.PageSize
if ps <= 0 {
ps = 50
}
pg := f.Page
if pg <= 0 {
pg = 1
}
start := (pg - 1) * ps
if start >= total {
return []StepSignVO{}, total, nil
}
end := start + ps
if end > total {
end = total
}
return list[start:end], total, nil
}
+38 -2
View File
@@ -34,6 +34,9 @@ type WorkOrderReq struct {
DueDate string `json:"dueDate"`
// 工艺组合(唯一路线源头):[{flowId,stationNo}],工位号即顺序号,按工位号升序执行、可跳过未选工位
FlowCombination []map[string]int `json:"flowCombination"`
// 来源产品工艺(2026-10-09):建单选产品时带出默认产品工艺并自动填组合;
// 组合是快照可手改,本字段恒保留=来源定义(0=无来源,历史工单),供追溯与偏差提示。
ProductProcessId int `json:"productProcessId"`
}
// CreateWorkOrder 创建工单(状态恒 CREATED,后续用状态流转按钮推进)
@@ -102,6 +105,13 @@ func (s *Service) CreateWorkOrder(ctx context.Context, req WorkOrderReq, operato
}
b.SetFlowCombination(flowItemsToMaps(items))
}
// 来源产品工艺:传了必须存在( ACTIVE/停用均可落——前端只列启用的,此处宽松校验存在性)
if req.ProductProcessId > 0 {
if _, err := s.ctx.EntClient.ProductProcess.Get(ctx, req.ProductProcessId); err != nil {
return errors.New("所选产品工艺不存在")
}
b.SetProductProcessId(req.ProductProcessId)
}
// 创建人(Item M):取当前登录用户
b.SetCreatedBy(operator)
if _, err := b.Save(ctx); err != nil {
@@ -227,6 +237,13 @@ func (s *Service) UpdateWorkOrder(ctx context.Context, req WorkOrderReq, operato
}
u.SetFlowCombination(flowItemsToMaps(items))
}
// 来源产品工艺:传了必须存在(恒保留=来源定义,不随组合手改清空)
if req.ProductProcessId > 0 {
if _, err := s.ctx.EntClient.ProductProcess.Get(ctx, req.ProductProcessId); err != nil {
return errors.New("所选产品工艺不存在")
}
u.SetProductProcessId(req.ProductProcessId)
}
if req.Quantity > 0 {
u.SetQuantity(req.Quantity)
}
@@ -263,8 +280,10 @@ func (s *Service) UpdateWorkOrder(ctx context.Context, req WorkOrderReq, operato
}
// ListWorkOrders 查询工单(支持工单号/状态/产品编码/产品名称/归属类型/归属编号 过滤;
// 工程编号查询已随编号体系改造移除,字段保留仅防历史迁移)
func (s *Service) ListWorkOrders(ctx context.Context, orderNo, status, productCode, productName, contractNo, ownershipType, dueFrom, dueTo string) ([]*ent.WorkOrder, error) {
// 工程编号查询已随编号体系改造移除,字段保留仅防历史迁移)。
// keyword:跨字段模糊(工单号/产品编码/产品名称/合同号 任一命中),供下拉远程搜索用;
// limit:>0 时启用截断(封顶 200),仅下拉搜索场景传参,列表页不传=全量,行为向后兼容。
func (s *Service) ListWorkOrders(ctx context.Context, orderNo, status, productCode, productName, contractNo, ownershipType, dueFrom, dueTo, keyword string, limit int) ([]*ent.WorkOrder, error) {
q := s.ctx.EntClient.WorkOrder.Query()
if orderNo != "" {
q = q.Where(workorder.WorkOrderNoContains(orderNo))
@@ -295,6 +314,23 @@ func (s *Service) ListWorkOrders(ctx context.Context, orderNo, status, productCo
q = q.Where(workorder.DueDateLTE(t))
}
}
// keyword 跨字段模糊(下拉远程搜索):工单号/产品编码/产品名称/合同号 任一命中
if keyword != "" {
kw := workorder.Or(
workorder.WorkOrderNoContains(keyword),
workorder.ProductCodeContains(keyword),
workorder.ProductNameContains(keyword),
workorder.ContractNoContains(keyword),
)
q = q.Where(kw)
}
// limit 截断(封顶 200):仅下拉搜索场景启用,防数据炸弹
if limit > 0 {
if limit > 200 {
limit = 200
}
q = q.Limit(limit)
}
return q.Order(ent.Desc(workorder.FieldCreatedAt), ent.Desc(workorder.FieldID)).All(ctx)
}
+67 -34
View File
@@ -322,16 +322,20 @@ func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, opera
return errors.New(miss)
}
// 阶段2:检测确认(needCheck)强校验——服务端为准,前端勾选只是辅助提示。
// 本工位绑定工艺流程中标记“需要检测确认”的步骤,报工数据里必须逐条带 checked=true,否则拒绝报工。
if err := s.validateNeedCheck(ctx, client, req); err != nil {
// 本工位在本工艺组合中的出现序号 k 对应步骤 seq=k,标记“需要检测确认”的步骤须带 checked=true。
// k 由组合派生(第 k 次出现 ↔ 步骤 seq=k),与签字校验同源,避免跨工位误拦。
k := stationSeqInFlow(items, flowId, req.StationNo)
if err := s.validateNeedCheck(ctx, client, req, flowId, k); err != nil {
return err
}
// 阶段2.5:签字机制(需求B)强校验 + 落操作工签字(needOperatorSign 步骤)。
// needInspectorSign 步骤要求检验员已在巡检终端「待签任务」页签签字,否则拒流转。
if err := s.validateNeedSign(ctx, client, req, flowId); err != nil {
// 校验同时返回 k(同 stationSeqInFlow),供落签字时同范围使用。
k, err = s.validateNeedSign(ctx, client, req, flowId, k)
if err != nil {
return err
}
if err := s.writeOperatorSigns(ctx, client, req, flowId, wp.OrderNo, operator); err != nil {
if err := s.writeOperatorSigns(ctx, client, req, flowId, k, wp.OrderNo, operator); err != nil {
return err
}
now := time.Now()
@@ -398,19 +402,16 @@ func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, opera
}
// validateNeedCheck 检测确认(needCheck)服务端强校验。
// 规则:本工位绑定的工艺流程中,凡标记 needCheck=true 的工艺步骤,
// 规则:本工位在本工艺组合中的出现序号 k 对应的步骤(seq=k),凡标记 needCheck=true,
// 报工请求里必须存在对应 stepId 且 checked=true 的步骤数据;缺失则拒绝报工。
// 工位未绑定流程、或流程内没有 needCheck 步骤时不拦截(与现场配置保持一致)。
func (s *Service) validateNeedCheck(ctx context.Context, client *ent.Client, req ReportProcessReq) error {
if req.StationNo <= 0 {
return nil
}
st, err := client.Station.Query().Where(station.StationNo(req.StationNo)).First(ctx)
if err != nil || st.FlowId <= 0 {
// 与 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(st.FlowId), processstep.NeedCheck(true)).All(ctx)
Where(processstep.FlowId(flowId), processstep.NeedCheck(true), processstep.Seq(k)).All(ctx)
if err != nil || len(steps) == 0 {
return nil
}
@@ -436,19 +437,39 @@ func (s *Service) validateNeedCheck(ctx context.Context, client *ent.Client, req
return nil
}
// validateNeedSign 签字机制(需求B)服务端强校验,镜像 validateNeedCheck:
// 本工位绑定工艺流程中,凡标记 needOperatorSign=true 的工艺步骤,报工请求必须携带对应签字
// (Signs 中存在 stepId 匹配且 signer 非空);凡标记 needInspectorSign=true 的步骤,必须已存在
// 检验员签字记录(step_sign_record, signRole=INSPECTOR, 未撤销, signedBy 非空)方可流转。
// 工位未绑定流程、或流程内无签字步骤时不拦截(与现场配置保持一致)。
func (s *Service) validateNeedSign(ctx context.Context, client *ent.Client, req ReportProcessReq, flowId int) error {
if req.StationNo <= 0 || flowId <= 0 {
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
}
// 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 err
return k, err
}
stationNo := itoa(req.StationNo)
signMap := map[int]StepSignInput{}
@@ -458,44 +479,47 @@ func (s *Service) validateNeedSign(ctx context.Context, client *ent.Client, req
}
}
for _, ps := range steps {
if ps.NeedOperatorSign {
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 errors.New("以下步骤需操作工签字确认后才能报工:" + name)
return k, errors.New("以下步骤需操作工签字确认后才能报工:" + name)
}
}
if ps.NeedInspectorSign {
// 检验员必须「签字确认」(result=OK、未撤销、有签字人) 才能流转;NG 结论视为未通过、不放行。
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 e
return k, e
}
if !has {
name := ps.Name
if name == "" {
name = "步骤" + itoa(ps.ID)
}
return errors.New("以下步骤需检验员签字确认(合格)后才能流转:" + name)
return k, errors.New("以下步骤需检验员签字确认(合格)后才能流转:" + name)
}
}
}
return nil
return k, nil
}
// writeOperatorSigns 在报工事务内落操作工签字(needOperatorSign 步骤,签字确认弹框采集);
// 按唯一索引(sn, stationNo, stepId, signRole=OPERATOR, round) 去重,避免重报产生重复签字。
// 仅落「本次报工步骤」(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 int, orderNo, operator string) error {
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)).All(ctx)
Where(processstep.FlowId(flowId), processstep.NeedOperatorSign(true), processstep.Seq(k)).All(ctx)
if err != nil {
return err
}
@@ -790,7 +814,8 @@ func (s *Service) inspectionRecordAttachments(ctx context.Context, rec *ent.Insp
return out
}
func (s *Service) ListWorkpieces(ctx context.Context, sn, orderNo string) ([]*ent.Workpiece, error) {
// ListWorkpieces 查询工件(sn 模糊包含、orderNo 精确;limit>0 时截断封顶 200,默认 500)
func (s *Service) ListWorkpieces(ctx context.Context, sn, orderNo string, limit int) ([]*ent.Workpiece, error) {
q := s.ctx.EntClient.Workpiece.Query()
if sn != "" {
q = q.Where(workpiece.SnContains(sn))
@@ -798,7 +823,15 @@ func (s *Service) ListWorkpieces(ctx context.Context, sn, orderNo string) ([]*en
if orderNo != "" {
q = q.Where(workpiece.OrderNo(orderNo))
}
return q.Order(ent.Desc(workpiece.FieldID)).Limit(500).All(ctx)
if limit > 0 {
if limit > 200 {
limit = 200
}
q = q.Limit(limit)
} else {
q = q.Limit(500)
}
return q.Order(ent.Desc(workpiece.FieldID)).All(ctx)
}
// InProcessItem 在制品(已进线未完工)视图项。跨天工件继续停留,日排产不重复排。