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

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

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

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

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

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

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

394 lines
15 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"
"fmt"
"sort"
"strconv"
"strings"
"time"
"bj_power_mes/ent"
"bj_power_mes/ent/productprocessitem"
"bj_power_mes/ent/station"
"bj_power_mes/ent/workorder"
"bj_power_mes/internal/verr"
)
// ---------- 工单工艺组合(work_order.flow_combination)路线派生 ----------
// TodayStr 当天日期 yyyy-MM-dd(工位停单只认当天)
func TodayStr() string { return time.Now().Format("2006-01-02") }
// FlowItem 工单工艺组合条目:工艺 + 工位(工位号即顺序号,按工位号升序执行)
type FlowItem struct {
FlowId int `json:"flowId"`
StationNo int `json:"stationNo"`
}
// RouteStationsFromWO 解析工单 flow_combination → 组合条目(按工位号升序;空组合返回空切片)
func RouteStationsFromWO(ctx context.Context, client *ent.Client, wo *ent.WorkOrder) ([]FlowItem, error) {
if wo == nil {
return nil, nil
}
items := flowMapsToItems(wo.FlowCombination)
sort.SliceStable(items, func(i, j int) bool { return items[i].StationNo < items[j].StationNo })
return items, nil
}
// flowIdsOf 组合条目去重后的 flowId 列表(升序,供按工单取物料清单)
func flowIdsOf(items []FlowItem) []int {
seen := map[int]bool{}
out := make([]int, 0, len(items))
for _, it := range items {
if it.FlowId > 0 && !seen[it.FlowId] {
seen[it.FlowId] = true
out = append(out, it.FlowId)
}
}
sort.Ints(out)
return out
}
// flowMapsToItems jsonb 原始值 → 组合条目(过滤 flowId 非正 / stationNo 为 0 的脏条目;
// stationNo 允许负数:负数=产线前段虚拟工位,2026-11-02)
func flowMapsToItems(raw []map[string]int) []FlowItem {
items := make([]FlowItem, 0, len(raw))
for _, m := range raw {
flowId, no := m["flowId"], m["stationNo"]
if flowId > 0 && no != 0 {
items = append(items, FlowItem{FlowId: flowId, StationNo: no})
}
}
return items
}
// flowItemsToMaps 组合条目 → jsonb 存储结构
func flowItemsToMaps(items []FlowItem) []map[string]int {
out := make([]map[string]int, 0, len(items))
for _, it := range items {
out = append(out, map[string]int{"flowId": it.FlowId, "stationNo": it.StationNo})
}
return out
}
// flowCombinationEqual 两份工艺组合是否相同(按 {flowId,stationNo} 条目多重集比较,忽略顺序与脏条目)。
// 2026-11-05 拍板:未完成工单禁改工艺路线,工单编辑保存时用于判定「是否真的改了路线」(未变不拦截)。
func flowCombinationEqual(a, b []map[string]int) bool {
ia, ib := flowMapsToItems(a), flowMapsToItems(b)
if len(ia) != len(ib) {
return false
}
count := make(map[FlowItem]int, len(ia))
for _, it := range ia {
count[it]++
}
for _, it := range ib {
if count[it] == 0 {
return false
}
count[it]--
}
return true
}
// RouteStationsOfWO 组合条目 → 工位号列表(升序;未选工位即跳过)
func RouteStationsOfWO(items []FlowItem) []int {
out := make([]int, 0, len(items))
for _, it := range items {
out = append(out, it.StationNo)
}
return out
}
// RouteStationsStrOfWO 组合条目 → 路线串 "2,5,6,8"
func RouteStationsStrOfWO(items []FlowItem) string {
parts := make([]string, 0, len(items))
for _, it := range items {
parts = append(parts, strconv.Itoa(it.StationNo))
}
return strings.Join(parts, ",")
}
// StationFlowMapOfWO 组合条目 → 工位号→工艺ID
func StationFlowMapOfWO(items []FlowItem) map[int]int {
m := make(map[int]int, len(items))
for _, it := range items {
m[it.StationNo] = it.FlowId
}
return m
}
// ---------- 并行候选工位:工艺级路线(一道工艺可配置多个候选工位) ----------
// FlowRouteStep 工艺级路线步骤:一道工艺(工艺) + 其全部候选工位。
// 并行模型(2026-11-02):工件在任一候选工位报工一次即完成该工艺,候选工位间为「可任选」关系而非串行顺序。
type FlowRouteStep struct {
FlowId int // 工艺ID
Stations []int // 候选工位号(升序)
MinNo int // 候选最小工位号(用于工艺顺序)
MaxNo int // 候选最大工位号(用于进度推进)
Seq int // 工艺顺序(按 MinNo 升序,从1起)
}
// groupFlowRoute 扁平组合条目 → 工艺级路线(同 flowId 归并为一道工艺,多工位为其候选集)。
// 工艺顺序按各工艺候选最小工位号升序(产线单向不回头)。
func groupFlowRoute(items []FlowItem) []FlowRouteStep {
byFlow := map[int][]int{}
for _, it := range items {
byFlow[it.FlowId] = append(byFlow[it.FlowId], it.StationNo)
}
steps := make([]FlowRouteStep, 0, len(byFlow))
for fid, sts := range byFlow {
sort.Ints(sts)
steps = append(steps, FlowRouteStep{FlowId: fid, Stations: sts, MinNo: sts[0], MaxNo: sts[len(sts)-1]})
}
sort.SliceStable(steps, func(i, j int) bool { return steps[i].MinNo < steps[j].MinNo })
for i := range steps {
steps[i].Seq = i + 1
}
return steps
}
// FlowRouteOfWO 工单 flow_combination → 工艺级路线(含候选工位)。
func FlowRouteOfWO(ctx context.Context, client *ent.Client, wo *ent.WorkOrder) ([]FlowRouteStep, error) {
if wo == nil {
return nil, nil
}
return groupFlowRoute(flowMapsToItems(wo.FlowCombination)), nil
}
// GroupFlowRoute 导出版:扁平组合条目 → 工艺级路线(handler 包渲染流程卡用)。
func GroupFlowRoute(items []FlowItem) []FlowRouteStep {
return groupFlowRoute(items)
}
// DistinctFlowCount 路线中工艺(工艺)去重计数:并行模型下完工/进度按「工艺数」而非「工位数」判定。
func DistinctFlowCount(items []FlowItem) int {
m := map[int]bool{}
for _, it := range items {
m[it.FlowId] = true
}
return len(m)
}
// intsContains 整数切片包含判断(候选工位校验用)。
func intsContains(ns []int, v int) bool {
for _, n := range ns {
if n == v {
return true
}
}
return false
}
// FlowUsedByActiveOrders 工艺是否被「执行中/已暂停」工单的工艺组合引用(2026-11-02 条目12 守卫)。
// 背景:工单 flow_combination 是建单快照,但生产流程卡的定义层(工艺清单/步骤门禁)每次
// 请求实时渲染 ProcessFlow/ProcessStep——改基础工艺会改掉在产工单的流程卡展示。
// 与产品工艺规则1同口径:执行中禁改,建议复制新工艺给新工单用。命中返回工单号列表。
func (s *Service) FlowUsedByActiveOrders(ctx context.Context, flowId int) ([]string, error) {
wos, err := s.ctx.EntClient.WorkOrder.Query().
Where(workorder.StatusIn("IN_PROGRESS", "PAUSED")).All(ctx)
if err != nil {
return nil, err
}
var hit []string
for _, w := range wos {
for _, m := range w.FlowCombination {
if m["flowId"] == flowId {
hit = append(hit, w.WorkOrderNo)
break
}
}
}
return hit, nil
}
// guardFlowEditable 基础工艺内容(名称/步骤/绑定/物料清单/删除)变更守卫:
// 被执行中/已暂停工单引用 → 拒绝并给出「怎么办」。
func (s *Service) guardFlowEditable(ctx context.Context, flowId int) error {
hits, err := s.FlowUsedByActiveOrders(ctx, flowId)
if err != nil {
return err
}
if len(hits) > 0 {
return fmt.Errorf("该工艺被执行中/已暂停的工单引用(%s),不能修改或删除;如需调整请复制一份新工艺,新工单使用新工艺",
strings.Join(hits, "、"))
}
return nil
}
// ValidateFlowCombination 保存工单时校验工艺组合(收集式实现,见 ValidateFlowCombinationCollect;
// 保留原签名供既有调用方使用,错误为收集式 ValidationError,handler 经 FailErr 输出结构化清单)。
func (s *Service) ValidateFlowCombination(ctx context.Context, raw []map[string]int) ([]FlowItem, error) {
items, ve := s.ValidateFlowCombinationCollect(ctx, raw)
return items, ve.OrNil()
}
// ValidateFlowCombinationCollect 收集式组合校验(报错一次收全,2026-10-20):
// 逐条检查每个组合项,重复/停用/不存在/绑定不匹配等问题全部列出、不串行 return;
// 每条错误带「怎么办」,能跳转解决的给 action(去工艺页/去工位管理)。
func (s *Service) ValidateFlowCombinationCollect(ctx context.Context, raw []map[string]int) ([]FlowItem, *verr.ValidationError) {
items := flowMapsToItems(raw)
ve := verr.New()
if len(items) == 0 {
ve.Add("flowCombination", "请先选择工艺组合", "至少选择一条「工艺+工位」:从产品工艺带出,或在工单编辑中手动勾选")
return nil, ve
}
sort.SliceStable(items, func(i, j int) bool { return items[i].StationNo < items[j].StationNo })
seen := map[int]bool{}
for _, it := range items {
if seen[it.StationNo] {
ve.Add("flowCombination", fmt.Sprintf("工位 %d 在工艺组合中重复", it.StationNo),
fmt.Sprintf("同一工位只能出现一次,删除工位 %d 的重复行", it.StationNo))
continue
}
seen[it.StationNo] = true
flow, err := s.ctx.EntClient.ProcessFlow.Get(ctx, it.FlowId)
if err != nil {
ve.Add("flowCombination", fmt.Sprintf("工艺不存在(ID=%d)", it.FlowId),
"删除该组合行后,从工艺下拉中重新选择")
continue
}
if flow.Status != "ACTIVE" {
ve.AddAction("flowCombination", fmt.Sprintf("工艺「%s」已停用", flow.Name),
"到「工艺」页启用该工艺,或在组合中移除该工艺行", "去工艺页", "/process-flow")
continue
}
exist, err := s.ctx.EntClient.Station.Query().Where(station.StationNo(it.StationNo)).First(ctx)
if err != nil {
ve.Add("flowCombination", fmt.Sprintf("工位 %d 不存在", it.StationNo),
"在组合中移除该工位行,或到「工位管理」新增该工位")
continue
}
// 工位当前绑定工艺必须与工单一致且工位启用(与排产校验 ValidateWOCombinationForSchedule 同口径),
// 否则工单下发后工位被改绑/停用会导致路线漂移
if exist.Status != "ENABLED" {
ve.AddAction("flowCombination", fmt.Sprintf("工位%d 已停用", it.StationNo),
"到「工位管理」启用该工位,或在组合中移除该工位行", "去工位管理", "/station")
} else if exist.FlowId != it.FlowId {
ve.AddAction("flowCombination", fmt.Sprintf("工位%d 当前绑定工艺与工单不一致", it.StationNo),
fmt.Sprintf("到「工位管理」把工位%d 绑回「%s」,或在组合中改选该工位当前绑定的工艺", it.StationNo, flow.Name),
"去工位管理", "/station")
}
}
return items, ve
}
// ValidateWorkOrderComboStrict 工单工艺组合「工艺工位」严格校验(2026-10-20 定稿;2026-11-27 修订规则①)。
// 仅在带产品工艺(productProcessId>0)时生效;无产品工艺则交由既有逻辑(组合可选)。
// 三条规则,收集式一次列全(与 ValidateFlowCombinationCollect 合并返回):
//
// ① 每道工艺都选了工位 —— 2026-11-27 用户拍板改为「选填」:建单/编辑时工位还没定、某道工艺可能还没绑工位,
// 允许留空(requireAllFlows=false 时跳过本规则);真正的「每道工艺都有工位」核对压到下发并开工时的
// ValidateFlowCombinationCollect + 路线非空校验(那时必须确定哪台工位干哪道工艺)。
// ② 工位号按工艺顺序严格递增(产线单向不回头,不允许倒序流转)—— 只要选了就仍要守这条;
// ③ 每个工位确实绑定对应工艺 —— 由 ValidateFlowCombinationCollect 同口径兜底(含停用/改绑/不存在,消息带「怎么办」)。
func (s *Service) ValidateWorkOrderComboStrict(ctx context.Context, ppId int, combo []map[string]int, requireAllFlows bool) *verr.ValidationError {
ve := verr.New()
if ppId <= 0 {
return ve
}
if _, err := s.ctx.EntClient.ProductProcess.Get(ctx, ppId); err != nil {
return ve // 产品工艺不存在时交给来源工艺存在性校验,避免重复
}
items, err := s.ctx.EntClient.ProductProcessItem.Query().
Where(productprocessitem.ProductProcessId(ppId)).
Order(ent.Asc(productprocessitem.FieldSeq)).All(ctx)
if err != nil || len(items) == 0 {
return ve
}
flows, _ := s.ctx.EntClient.ProcessFlow.Query().All(ctx)
flowName := map[int]string{}
for _, f := range flows {
flowName[f.ID] = f.Name
}
// 组合按 flowId 归并(一道工艺可配置多个有序工位:基于「产线单向不回头」,
// 本道工艺的全部工位必须都在上一道工艺的全部工位之后,即各工艺的工位区间互不交叉、整体严格递增)。
byFlow := map[int][]int{}
for _, c := range combo {
fid, no := c["flowId"], c["stationNo"]
if fid <= 0 {
continue // 无工艺的组合项交由其他校验
}
if no == 0 {
// 工位号 0 = 未指定(Go 零值语义),不可作为工位落点(2026-11-05 拍板)
ve.Add("flowCombination",
"工位号不能为 0(0 表示未指定)",
"请为每道工艺选择工位号:正整数或负数虚拟工位(-1、-2…),0 不可作为落点")
continue
}
byFlow[fid] = append(byFlow[fid], no)
}
for k := range byFlow {
sort.Ints(byFlow[k])
}
prevName, prevMax := "", 0
for _, it := range items {
name := flowName[it.FlowId]
if name == "" {
name = "工艺" + strconv.Itoa(it.FlowId)
}
sts := byFlow[it.FlowId]
if len(sts) == 0 {
// 规则①(2026-11-27 选填):建单/编辑允许该道工艺暂未选工位(requireAllFlows=false),
// 留空不拦;开工时再核对。requireAllFlows=true 的调用方才硬拦。
if requireAllFlows {
ve.Add("flowCombination",
fmt.Sprintf("第%d道工艺「%s」未选工位", it.Seq, name),
fmt.Sprintf("请为第%d道工艺「%s」选择至少一个绑定了该工艺的工位", it.Seq, name))
}
continue
}
// 同工艺内重复工位(脏数据)拦截
seen := map[int]bool{}
dup := false
for _, n := range sts {
if seen[n] {
dup = true
break
}
seen[n] = true
}
if dup {
ve.Add("flowCombination",
fmt.Sprintf("第%d道工艺「%s」的工位列表存在重复(工位%d)", it.Seq, name, sts[0]),
fmt.Sprintf("请在第%d道工艺「%s」中去重工位", it.Seq, name))
continue
}
minS, maxS := sts[0], sts[len(sts)-1]
if prevMax > 0 && minS <= prevMax {
// 规则②:本道工艺工位区间未整体在上一道之后(产线单向不能回头 / 工艺工位不可交叉)
ve.Add("flowCombination",
fmt.Sprintf("第%d道工艺「%s」的工位(%s)未整体排在上一道工艺「%s」(工位%d)之后",
it.Seq, name, strings.Join(intsToStrs(sts), ","), prevName, prevMax),
fmt.Sprintf("产线单向不能回头:请把工艺「%s」的工位都改到工位%d 之后,或调整工艺顺序",
name, prevMax))
}
prevName, prevMax = name, maxS
}
return ve
}
// intsToStrs 整数切片转字符串切片(校验消息用)
func intsToStrs(ns []int) []string {
out := make([]string, 0, len(ns))
for _, n := range ns {
out = append(out, "工位"+strconv.Itoa(n))
}
return out
}
// 说明:原 ValidateWOCombinationForSchedule「工单必须先选工艺组合才能排产」校验已移除(2026-11-23)——
// 工艺路线现以工位绑定为准,工单 flowCombination 是历史快照,排产不再依赖它。
// flowNameById 工艺名称(查不到回退「工艺{id}」)
func (s *Service) flowNameById(ctx context.Context, id int) string {
if id > 0 {
if f, err := s.ctx.EntClient.ProcessFlow.Get(ctx, id); err == nil && f.Name != "" {
return f.Name
}
}
return "工艺" + strconv.Itoa(id)
}