Files
bj_power/bj_power_mes/internal/logic/dashboard_front.go
T
SunYF f930a1325f feat(mes/wms): 接驳台编码统一为GW点位码 + 签字模型改报检呼叫 + 台账续流修复 + 末级库位强校验(2026-12-01 终版整改)
【全系统 · 接驳台编码终版统一(12-01 用户拍板)】
- 新增 dockcode 包作为唯一真源:工位接驳台 = GW{工位号}{Z|Y}(Z=左/Y=右,工位1~10同一规则,废除左右互换),库房 = JBT21 不变
- 编码即海康 RCS 地图点位码:落库/界面/下发 RCS/读 PLC 传感器全用同一套;旧 DOCK01~20 全量废弃,系统内无第二套编号、无换算层
- dock 表去 side 字段;agv_task.target_dock、line_point、看板点位态与中文名、dockLabel 工具全部改 GW 规则
- 产线布局说明.md 同步终版(图纸名 GxZ/GxY 与 AGV 码 GWxZ/GWxY 一一对应;注明 RCS 图与主线流向图相差 180°,读图一律以 GW 码为准)

【MES · 签字模型二次重构(11-30 实测后定稿)】
- _OPERATOR 签字整体废除:工艺步骤删 needOperatorSign / needAudit / auditRole 字段,签字角色改 CALL(工人报检呼叫)+ INSPECTOR(检验员审核签)
- 呼叫时落步骤录入快照(stepValue/stepText/stepChecked/processId),供检验员查看与指纹比对;「待签任务」只认检验员签名步骤
- 「签字复核」(AuditPending 页面 + produce.audit 菜单 + 路由)整套删除

【MES · 台账续流根因修复(11-30 对账发现)】
- 流转目标「G6」与 line_point.point_no「6」对不上导致到位落账查不到、却先释放源位→工件从调度消失;新增 ledgerPointByTarget 归一
- settleDirect/settleInTransit 改为先占目标位、成功才释放源位;目标被占原样保留,工件进缓存位排队(实测 C2 排队不再丢件)

【WMS · 末级库位强校验与上架移库】
- 新增 LocationCascade 四级联动选择器(区/架/层/号,只从启用 level=4 节点派生);手工入库、半成品/成品入库、隔离库位一律四级必填且命中启用节点
- 新增上架/移库 relocate:只改四级库位与 updated_at,不动质量状态/数量/锁定量;不合格与锁定行同样允许移库;支持 ids 逐行指定或 scope 按物料+原库位整组搬
- MES 新增 WMS 自动回流库位配置(半成品/成品各一组末级库位,默认值 1区/1架/1层/1号,存 sys_config 可改)

【MES · 统一口径与工程整改】
- 新增 workpiece_location:工单详情工件列表/WIP/追溯三处共用位置判定(SCRAPPED→DONE→SEMI_STORED→在 StationNo→在途→待流转)
- 新增 workorder_close_warn:工单完工/取消时汇总各工位实物余料出一条预警,不阻断关单
- 分页下沉:新增 pagination 工具,同步失败台账(两端)改 Count+LIMIT/OFFSET 真分页,列表不再全量切片
- 全网对账/孤儿扫描(问题临时.md 第25/26节):10 类关系边断言实测,给出 8 条可重复巡检项

【文档】
- 产线布局说明.md 按 GW 编码终版重写;问题临时.md 新增 24.7 闭环实测、25 全网对账、26 补料→配送→报工人库闭环
2026-12-01 22:15:28 +08:00

449 lines
17 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"
"math"
"strconv"
"strings"
"time"
"bj_power_mes/common/dockcode"
)
/*
看板前端契约层(MES 免登录看板页 /board,前端源码 frontend/src/board/)
MES 内部保留一套“富”聚合(DashboardSnapshot:质量/报警/绩效/AGV 等,供后续扩展),
而看板对外只暴露甲方约定的正面指标(见 MES /board 看板页口径):
- 不直接下发合格率/不良/报警等负面字段
- 当前订单卡片:合同 / 负责人 / 工期 / 完成度 / 可追溯
- 设备一律以“在线台数”等正面口径
此文件把富快照映射为前端 JSON,字段名与 MES /board 前端数据契约一一对应。
*/
// FrontToolState 单把工具(扫码枪 / 拧紧枪)
type FrontToolState struct {
Status string `json:"status"` // online / offline / busy / alarm
CurrentSn string `json:"currentSn,omitempty"`
ProcessedCount int `json:"processedCount"`
}
// FrontStation 工位(前端 Station)
type FrontStation struct {
ID int `json:"id"`
Name string `json:"name"`
Status string `json:"status"` // running / idle / alarm / offline
ScanGun FrontToolState `json:"scanGun"`
TighteningGun FrontToolState `json:"tighteningGun"`
CurrentSn string `json:"currentSn"`
CurrentOperator string `json:"currentOperator"`
CurrentProcess string `json:"currentProcess"` // 最近一道工艺名
DoneCount int `json:"doneCount"` // 今日完成数
PlanCount int `json:"planCount"` // 当日计划数(客户诉求4:工位完成率=完成/计划)
Paused bool `json:"paused"` // 当天已停单(前端仅图标提示)
PauseReason string `json:"pauseReason,omitempty"`
// 工位状态标签(客户诉求11):normal / shortage / leave / offline,前端据此渲染灰/正常/红呼吸灯
StationTag string `json:"stationTag"`
}
// FrontProduction 产能总览(前端 ProductionOverview)
type FrontProduction struct {
OutputToday int `json:"outputToday"`
TargetToday int `json:"targetToday"`
PassCount int `json:"passCount"` // 一次通过件数(替代合格率)
TorqueCount int `json:"torqueCount"`
InLine int `json:"inLine"`
DeviceOnline int `json:"deviceOnline"`
DeviceTotal int `json:"deviceTotal"`
CycleTimeMin float64 `json:"cycleTime"` // 实际生产节拍(分钟)
StationSummary StationSummary `json:"stationSummary"`
// 2026-11-10 新增可选 KPI 数据源(默认不下发负面口径,仅在勾选相应指标时使用)
QualifiedRate float64 `json:"qualifiedRate"` // 良率(%)
WipOrders int `json:"wipOrders"` // 在制(未完工)工单数
MaterialReadyPct float64 `json:"materialReadyPct"` // 物料齐套率(在库量覆盖今日计划量,封顶100)
DoneRate float64 `json:"doneRate"` // 当日完成率(%)
}
// FrontMovement 出入库动态(实时事件流)
type FrontMovement struct {
ID string `json:"id"`
Time string `json:"time"`
Type string `json:"type"` // in / out
Material string `json:"material"`
Qty int `json:"qty"`
Operator string `json:"operator"`
Batch string `json:"batch"` // 批次号
}
// FrontWarehouse 仓储动态(前端 WarehouseOverview,数据源 WMS 8890)
type FrontWarehouse struct {
TotalStock int `json:"totalStock"`
MaterialTypes int `json:"materialTypes"`
InboundToday int `json:"inboundToday"`
OutboundToday int `json:"outboundToday"`
LocationUsed int `json:"locationUsed"`
LocationTotal int `json:"locationTotal"`
PendingInbound int `json:"pendingInbound"`
PendingOutbound int `json:"pendingOutbound"`
Movements []FrontMovement `json:"movements"`
}
// FrontProgress 当前订单卡片(前端 ProductionProgress)
type FrontProgress struct {
OrderNo string `json:"orderNo"`
ContractNo string `json:"contractNo"`
ProductName string `json:"productName"`
Owner string `json:"owner"`
PlanStart string `json:"planStart"`
PlanEnd string `json:"planEnd"`
RemainDays int `json:"remainDays"`
TotalQty int `json:"totalQty"`
DoneQty int `json:"doneQty"`
Progress float64 `json:"progress"`
ProcessDone int `json:"processDone"`
ProcessTotal int `json:"processTotal"`
CurrentProcess string `json:"currentProcess"`
Status string `json:"status"`
TraceStepCount int `json:"traceStepCount"`
Traceable bool `json:"traceable"`
}
// FrontTrends 近 7 日产量趋势(前端 TrendData:{ production: [...] })
type FrontTrends struct {
Production []TrendPoint `json:"production"`
}
// FrontDashboard 前端全量快照(与 MES /board 前端数据契约对齐;isDemo 由前端标注,不回传)
type FrontDashboard struct {
UpdatedAt string `json:"updatedAt"`
Production FrontProduction `json:"production"`
Warehouse FrontWarehouse `json:"warehouse"`
Equipment []FrontStation `json:"equipment"`
// VirtualStations 虚拟工位(OFFLINE,不连PLC):地图"虚拟工位"滚动栏展示,不混入 equipment(12 工位映射口径不变)
VirtualStations []FrontStation `json:"virtualStations"`
Progress FrontProgress `json:"progress"`
// ProgressList 当前在产订单列表(多订单轮播):进行中的工单排前,最多 6 条;
// 首条与 Progress 一致(老消费方可继续只用 progress)。
ProgressList []FrontProgress `json:"progressList"`
Traces []TraceItem `json:"traces"`
Trends FrontTrends `json:"trends"`
// Points 产线点位态(主线 15 位 / 接驳台 21 位 / 在途路径指令),驱动 2D 地图真实亮灭与流光
Points FrontPoints `json:"points"`
// Agv AGV 实时搬运任务(真实备料任务驱动;无坐标,前端按状态+目标接驳台做过渡动画)
Agv []FrontAgvRobot `json:"agv"`
// Events 实时事件流(已过滤 NG 结果项:大屏报喜不报忧,负面事件只走语音播报)
Events []EventItem `json:"events"`
// Alarms 仅用于前端语音播报(D2),不渲染到屏幕(报喜不报忧)。
Alarms []AlarmItem `json:"alarms"`
// Manage 管理屏专属聚合:停机TOP/不良TOP/返修报废/节拍/缺料/低库存。
// 演示屏报喜不报忧——前端按 isManageScreen 决定是否渲染,本字段不下发负面数据到演示屏 UI。
Manage ManageStats `json:"manage"`
// RefreshSeconds 看板轮询兜底刷新间隔(秒,1~10),由 dashboard.refresh.seconds 配置驱动;
// 仅影响 SSE 实时通道不可用时的 HTTP 轮询周期,SSE 可用时不依赖此值。
RefreshSeconds int `json:"refreshSeconds"`
}
// DashboardFrontSnapshot 看板前端快照:富聚合 → 前端契约映射,走同一缓存(60s + 防击穿)。
func (s *Service) DashboardFrontSnapshot(ctx context.Context) (*FrontDashboard, error) {
return cachedTyped(ctx, s, "dashboard:front", dashboardTTL, func() (*FrontDashboard, error) {
rich, err := s.DashboardSnapshot(ctx)
if err != nil {
return nil, err
}
f := s.mapFrontDashboard(ctx, rich)
f.RefreshSeconds = s.CfgInt(ctx, CfgDashboardRefreshSeconds, 5)
return f, nil
})
}
// mapFrontDashboard 富快照 → 前端契约。
// 展示口径按甲方要求:负面字段(合格率/不良数/报警)一律不出现。
func (s *Service) mapFrontDashboard(ctx context.Context, r *DashboardSnapshot) *FrontDashboard {
f := &FrontDashboard{UpdatedAt: r.UpdatedAt}
// -------- production / equipment --------
onlineDevices := 0
summary := StationSummary{}
equipment := make([]FrontStation, 0, len(r.Equipment))
// 客户诉求4:工位当日计划数(daily_plan.stationPlanQty),按工位号映射
todayPlan := s.stationPlanQtyMap(ctx, time.Now())
stationTag := func(st StationState) string {
// 客户诉求11:工位状态标签——offline灰 / paused缺料或离开→红呼吸灯 / running正常 / idle空闲
if st.Status == "offline" {
return "offline"
}
if st.Paused {
return "shortage" // 停单(缺料/离开)→红呼吸灯
}
return "normal"
}
for _, st := range r.Equipment {
tool := "online"
switch st.Status {
case "running":
tool = "busy"
summary.Running++
case "alarm":
tool = "alarm"
summary.Alarm++
case "offline":
tool = "offline"
summary.Offline++
default:
summary.Idle++
}
if st.Status != "offline" {
onlineDevices += 2
}
equipment = append(equipment, FrontStation{
ID: st.StationNo,
Name: st.Name,
Status: st.Status,
ScanGun: FrontToolState{Status: tool, ProcessedCount: st.DoneToday},
TighteningGun: FrontToolState{Status: tool, CurrentSn: st.CurrentSn, ProcessedCount: st.DoneToday},
CurrentSn: st.CurrentSn,
CurrentOperator: st.CurrentOperator,
CurrentProcess: st.CurrentProcess,
DoneCount: st.DoneToday,
PlanCount: todayPlan[strconv.Itoa(st.StationNo)],
Paused: st.Paused,
PauseReason: st.PauseReason,
StationTag: stationTag(st),
})
}
f.Equipment = equipment
// -------- 虚拟工位(OFFLINE):同构映射,但不计入设备在线/总数口径 --------
f.VirtualStations = make([]FrontStation, 0, len(r.VirtualEquipment))
for _, st := range r.VirtualEquipment {
tool := "online"
switch st.Status {
case "running":
tool = "busy"
case "alarm":
tool = "alarm"
case "offline":
tool = "offline"
}
f.VirtualStations = append(f.VirtualStations, FrontStation{
ID: st.StationNo,
Name: st.Name,
Status: st.Status,
ScanGun: FrontToolState{Status: tool, ProcessedCount: st.DoneToday},
TighteningGun: FrontToolState{Status: tool, CurrentSn: st.CurrentSn, ProcessedCount: st.DoneToday},
CurrentSn: st.CurrentSn,
CurrentOperator: st.CurrentOperator,
CurrentProcess: st.CurrentProcess,
DoneCount: st.DoneToday,
PlanCount: todayPlan[strconv.Itoa(st.StationNo)],
Paused: st.Paused,
PauseReason: st.PauseReason,
StationTag: stationTag(st),
})
}
// 2026-11-10:为「良率 / 在制工单数 / 物料齐套率 / 当日完成率」四个可选 KPI 计算数据源
// (在富快照上算,不新增接口;仅当基础设置勾选相应指标时前端才展示)
wipOrders := 0
todayPlanQty := 0
todayDoneQty := 0
for _, wo := range r.Production.WorkOrders {
if wo.Status != "DONE" && wo.Status != "CANCELLED" {
wipOrders++
}
todayPlanQty += wo.DailyPlanQty
todayDoneQty += wo.DailyDoneQty
}
doneRate := 0.0
if todayPlanQty > 0 {
doneRate = math.Min(100, float64(todayDoneQty)/float64(todayPlanQty)*100)
} else if r.Production.TargetToday > 0 {
doneRate = math.Min(100, float64(r.Production.OutputToday)/float64(r.Production.TargetToday)*100)
}
materialReadyPct := 0.0
if todayPlanQty > 0 {
if r.Warehouse.TotalQty >= todayPlanQty {
materialReadyPct = 100
} else {
materialReadyPct = float64(r.Warehouse.TotalQty) / float64(todayPlanQty) * 100
}
}
f.Production = FrontProduction{
OutputToday: r.Production.OutputToday,
TargetToday: r.Production.TargetToday,
PassCount: r.Production.QualityOk,
TorqueCount: r.Production.TorqueTotal,
InLine: r.Production.InLine,
DeviceOnline: onlineDevices,
DeviceTotal: len(r.Equipment) * 2,
CycleTimeMin: r.Production.CycleTimeMin,
StationSummary: summary,
QualifiedRate: r.Production.QualifiedRate,
WipOrders: wipOrders,
MaterialReadyPct: materialReadyPct,
DoneRate: doneRate,
}
// -------- warehouse --------
movements := make([]FrontMovement, 0, len(r.Warehouse.Movements))
for _, m := range r.Warehouse.Movements {
movements = append(movements, FrontMovement{
ID: m.ID, Time: m.Time, Type: m.Type, Material: m.Material,
Qty: m.Qty, Operator: m.Operator, Batch: m.Batch,
})
}
f.Warehouse = FrontWarehouse{
TotalStock: r.Warehouse.TotalQty,
MaterialTypes: r.Warehouse.MaterialTypes,
InboundToday: r.Warehouse.InToday,
OutboundToday: r.Warehouse.OutToday,
LocationUsed: r.Warehouse.LocationUsed,
LocationTotal: r.Warehouse.LocationTotal,
PendingInbound: r.Warehouse.PendingInbound,
PendingOutbound: r.Warehouse.PendingOutbound,
Movements: movements,
}
// -------- 当前订单卡片 --------
pr := FrontProgress{ProcessTotal: 12, Status: "待排产"}
if c := r.Production.CurrentOrder; c != nil {
pr = FrontProgress{
OrderNo: c.OrderNo,
ProductName: c.ProductName,
TotalQty: c.TotalQty,
DoneQty: c.DoneQty,
Progress: c.Progress,
Status: c.Status,
CurrentProcess: c.CurrentProcess,
PlanStart: shortDate(c.PlanStart),
PlanEnd: shortDate(c.PlanEnd),
RemainDays: remainDays(c.PlanEnd),
ProcessTotal: 12,
}
}
// 追溯:取最近完工工件,汇总工艺实绩条数 → “全程可追溯”
stepCount := 0
allOk := true
for _, t := range r.Trace.Recent {
stepCount += t.StepCount
if t.NgCount > 0 {
allOk = false
}
}
pr.TraceStepCount = stepCount
pr.Traceable = stepCount > 0 && allOk
f.Progress = pr
// -------- 多订单列表(轮播):进行中工单排前,最多 6 条,首条与 progress 一致 --------
f.ProgressList = make([]FrontProgress, 0, len(r.Production.WorkOrders))
for i, wo := range r.Production.WorkOrders {
if i >= 6 {
break
}
f.ProgressList = append(f.ProgressList, FrontProgress{
OrderNo: wo.OrderNo,
ProductName: wo.ProductName,
TotalQty: wo.TotalQty,
DoneQty: wo.DoneQty,
Progress: wo.Progress,
Status: wo.Status,
CurrentProcess: wo.CurrentProcess,
PlanStart: shortDate(wo.PlanStart),
PlanEnd: shortDate(wo.PlanEnd),
RemainDays: remainDays(wo.PlanEnd),
ProcessTotal: 12,
TraceStepCount: stepCount,
Traceable: stepCount > 0 && allOk,
})
}
// -------- traces / trends / points / agv / events --------
f.Traces = r.Trace.Recent
if f.Traces == nil {
f.Traces = []TraceItem{}
}
f.Trends = FrontTrends{Production: r.Trends}
if f.Trends.Production == nil {
f.Trends.Production = []TrendPoint{}
}
// 点位态:PLC 读取失败时 buildPoints 已降级为 Mock 空态,前端角落标「模拟数据」
f.Points = s.buildPoints(ctx)
if f.Points.Transit == nil {
f.Points.Transit = []InTransit{}
}
// AGV:真实备料任务 → 点位码 + 中文显示名(GW{工位号}{Z|Y} / JBT21);无假坐标、无假进度
f.Agv = make([]FrontAgvRobot, 0, len(r.Agv.Robots))
for _, rb := range r.Agv.Robots {
f.Agv = append(f.Agv, FrontAgvRobot{
Code: rb.Code, Status: rb.Status,
StatusLabel: agvStatusLabel(rb.Status), // 客户诉求12:看板按状态映射颜色图标
From: dockcode.Label(rb.FromDock),
To: dockcode.Label(rb.ToDock),
Carrier: rb.Carrier, TaskNo: rb.TaskNo,
})
}
// 事件流:过滤 NG 结果项(大屏报喜不报忧;负面事件只进语音播报 alarms)
f.Events = make([]EventItem, 0, len(r.Events))
for _, e := range r.Events {
if strings.EqualFold(e.Level, "error") {
continue
}
f.Events = append(f.Events, e)
}
// 报警仅透传给前端做语音播报(D2),屏幕不渲染(报喜不报忧);管理屏告警条由 isManageScreen 控制渲染。
f.Alarms = r.Alarms
if f.Alarms == nil {
f.Alarms = []AlarmItem{}
}
// 管理屏专属聚合(客户 22 条):停机TOP/不良TOP/返修报废/节拍/缺料/低库存。
// 演示屏报喜不报忧——前端按 isManageScreen 决定是否渲染这些字段。
f.Manage = r.Manage
return f
}
// agvStatusLabel AGV 状态 → 中文显示名(客户诉求12:看板按空闲/运送/故障/充电映射颜色图标)
func agvStatusLabel(status string) string {
switch strings.ToLower(status) {
case "idle", "waiting", "done":
return "空闲"
case "moving", "delivering":
return "运送中"
case "loading", "locked":
return "装货中"
case "charging":
return "充电"
case "fault", "error":
return "故障"
default:
return "待命"
}
}
// shortDate "2006-01-02 15:04:05" → "2006-01-02"
func shortDate(s string) string {
if len(s) >= 10 {
return s[:10]
}
return strings.TrimSpace(s)
}
// remainDays 距交期剩余天数:按自然日差(负数 = 已超期)。
// 工期为空的订单返回 0,前端显示“—”即可。
func remainDays(planEnd string) int {
layout := dashboardTimeLayout
if len(planEnd) == 10 {
layout = "2006-01-02"
}
t, err := time.ParseInLocation(layout, strings.TrimSpace(planEnd), time.Local)
if err != nil {
return 0
}
// 取日期差(跨过当天 0 点即视为到期)
now := time.Now()
start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
end := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
return int(end.Sub(start).Hours() / 24)
}