- WMS 新增「检验处置项」实体(schema + ent 生成码),配套检验记录实体调整与复检接口,完善来料检/不良退货/入库检验前端 - MES 日排产:新增达成率统计与计划对比逻辑,调整日排产前端与流程卡/工序流 - 日志与传输:MES 新增 PLC 日志与 WMS 客户端传输日志,WMS 新增 MES 客户端传输日志 - MES 其他:扫码、工单/工件、AGV 客户端与告警、产品导入等逻辑完善及前端调整 - 工位终端:上线面板/作业面板、工件 handler 与 MES 客户端调整 - 配置与文档:更新 mes-api.yaml、三端构建产物与问题记录文档
1076 lines
42 KiB
Go
1076 lines
42 KiB
Go
package logic
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
"sort"
|
||
"strings"
|
||
"time"
|
||
|
||
"bj_power_mes/ent"
|
||
"bj_power_mes/ent/flowmaterial"
|
||
"bj_power_mes/ent/inspectionrecord"
|
||
"bj_power_mes/ent/lossledger"
|
||
"bj_power_mes/ent/processflow"
|
||
"bj_power_mes/ent/processstep"
|
||
"bj_power_mes/ent/plcsendlog"
|
||
"bj_power_mes/ent/station"
|
||
"bj_power_mes/ent/stepcriterion"
|
||
"bj_power_mes/ent/workorder"
|
||
"bj_power_mes/ent/workpieceprocess"
|
||
"bj_power_mes/internal/verr"
|
||
)
|
||
|
||
// ---------- 工艺流程(块3) ----------
|
||
|
||
// FlowReq 工艺流程保存请求(流程=菜谱,只描述"怎么干")
|
||
// Stations:绑定工位列表(可多选,一个流程可绑多个工位)。
|
||
type FlowReq struct {
|
||
Id int `json:"id"`
|
||
Name string `json:"name"`
|
||
Stations []int `json:"stations"`
|
||
PdfFile string `json:"pdfFile"`
|
||
Status string `json:"status"`
|
||
Remark string `json:"remark"`
|
||
Steps []StepItemReq `json:"steps"`
|
||
}
|
||
|
||
// FlowVO 工艺流程视图(含工序步骤 + 绑定该流程的工位号)
|
||
type FlowVO struct {
|
||
Id int `json:"id"`
|
||
Name string `json:"name"`
|
||
PdfFile string `json:"pdfFile"`
|
||
Status string `json:"status"`
|
||
Remark string `json:"remark"`
|
||
Stations []int `json:"stations"`
|
||
Steps []*ProcessStepTemplate `json:"steps"`
|
||
// 只读反查:引用本工艺的产品工艺名称列表(产品工艺明细实时反查)
|
||
ProductProcesses []string `json:"productProcesses"`
|
||
CreatedAt time.Time `json:"createdAt"`
|
||
}
|
||
|
||
// ListFlows 查询工艺流程(可按工位号过滤:只认「工位绑定」页的绑定关系 station.flow_id;
|
||
// pp 非空时按引用该工艺的产品工艺名称反查过滤)。page>0 时真分页返回 map{total,list,page,pageSize}(管理页用);page=0 全量数组(工位终端兼容)
|
||
func (s *Service) ListFlows(ctx context.Context, stationNo int, pp, name, status string, stepMin, page, pageSize int) (any, error) {
|
||
q := s.ctx.EntClient.ProcessFlow.Query().
|
||
Order(ent.Asc(processflow.FieldID))
|
||
flows, err := q.All(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
stations, _ := s.ctx.EntClient.Station.Query().All(ctx)
|
||
flowToStations := map[int][]int{}
|
||
for _, st := range stations {
|
||
if st.FlowId > 0 {
|
||
flowToStations[st.FlowId] = append(flowToStations[st.FlowId], st.StationNo)
|
||
}
|
||
}
|
||
ppNames := s.productProcessNamesByFlow(ctx)
|
||
out := make([]*FlowVO, 0, len(flows))
|
||
for _, f := range flows {
|
||
// 过滤:指定工位号时,只返回绑定了该工位的流程
|
||
if stationNo > 0 {
|
||
hit := false
|
||
for _, st := range flowToStations[f.ID] {
|
||
if st == stationNo {
|
||
hit = true
|
||
break
|
||
}
|
||
}
|
||
if !hit {
|
||
continue
|
||
}
|
||
}
|
||
// 名称模糊过滤(大小写无关)
|
||
if name != "" && !strings.Contains(strings.ToLower(f.Name), strings.ToLower(name)) {
|
||
continue
|
||
}
|
||
// 状态过滤(ACTIVE/INACTIVE,空=全部)
|
||
if status != "" && f.Status != status {
|
||
continue
|
||
}
|
||
vo := &FlowVO{
|
||
Id: f.ID, Name: f.Name,
|
||
PdfFile: f.PdfFile, Status: f.Status, Remark: f.Remark,
|
||
Stations: []int{}, Steps: s.flowSteps(ctx, f.ID), CreatedAt: f.CreatedAt,
|
||
}
|
||
if list, ok := flowToStations[f.ID]; ok {
|
||
vo.Stations = list
|
||
}
|
||
if vo.ProductProcesses = ppNames[f.ID]; vo.ProductProcesses == nil {
|
||
vo.ProductProcesses = []string{}
|
||
}
|
||
// 工序数下限过滤(stepMin>0 时只保留工序数≥阈值者)
|
||
if stepMin > 0 && len(vo.Steps) < stepMin {
|
||
continue
|
||
}
|
||
// 产品工艺反查过滤(模糊,大小写无关)
|
||
if pp != "" && !ppContainsFold(vo.ProductProcesses, pp) {
|
||
continue
|
||
}
|
||
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
|
||
}
|
||
|
||
// SaveFlow 保存工艺流程(可一次绑定多个工位)。
|
||
// 约束:① 绑定工位必须已存在(工位主数据由数据库维护,本接口不自动创建);
|
||
// ② 一个工位同时只能绑定一个流程(保存时直接覆盖旧绑定);
|
||
// ③ 停用流程不再自动解绑工位(绑定关系由本保存接口显式维护,启停只切流程状态)。
|
||
func (s *Service) SaveFlow(ctx context.Context, req FlowReq, operator string) error {
|
||
if req.Name == "" {
|
||
return errors.New("流程名称必填")
|
||
}
|
||
// 解析绑定工位列表
|
||
seen := map[int]bool{}
|
||
stations := []int{}
|
||
for _, no := range req.Stations {
|
||
if no < 1 || seen[no] {
|
||
continue
|
||
}
|
||
seen[no] = true
|
||
stations = append(stations, no)
|
||
}
|
||
status := req.Status
|
||
if status == "" {
|
||
status = "ACTIVE"
|
||
}
|
||
if status != "ACTIVE" && status != "INACTIVE" {
|
||
return errors.New("非法状态")
|
||
}
|
||
// 绑定语义(2026-09-08 定稿):直接更换——一个工位只有一条关联数据,
|
||
// 保存时所选工位一律改绑到本流程(覆盖旧绑定),不再报"已被启用流程绑定"冲突。
|
||
var flowID int
|
||
if req.Id > 0 {
|
||
// 条目12 守卫(2026-11-02):被执行中/已暂停工单引用的工艺禁止改内容(含启停)
|
||
if err := s.guardFlowEditable(ctx, req.Id); err != nil {
|
||
return err
|
||
}
|
||
upd := s.ctx.EntClient.ProcessFlow.UpdateOneID(req.Id).
|
||
SetName(req.Name).SetStatus(status).SetRemark(req.Remark)
|
||
if req.PdfFile != "" {
|
||
upd.SetPdfFile(req.PdfFile)
|
||
}
|
||
if _, err := upd.Save(ctx); err != nil {
|
||
return err
|
||
}
|
||
flowID = req.Id
|
||
} else {
|
||
f, err := s.ctx.EntClient.ProcessFlow.Create().
|
||
SetName(req.Name).SetPdfFile(req.PdfFile).
|
||
SetStatus(status).SetRemark(req.Remark).Save(ctx)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
flowID = f.ID
|
||
}
|
||
// 绑定同步:把绑定列表整体指向该流程(旧绑定该流程但不在列表内的工位解绑)
|
||
boundNow, _ := s.ctx.EntClient.Station.Query().Where(station.FlowId(flowID)).All(ctx)
|
||
for _, st := range boundNow {
|
||
if !seen[st.StationNo] {
|
||
_, _ = s.ctx.EntClient.Station.UpdateOneID(st.ID).SetFlowId(0).Save(ctx)
|
||
}
|
||
}
|
||
for _, no := range stations {
|
||
if err := s.syncStationFlow(ctx, no, flowID); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
// 覆盖式重建该流程的工序步骤及考核标准
|
||
_, _ = s.ctx.EntClient.ProcessStep.Delete().Where(processstep.FlowId(flowID)).Exec(ctx)
|
||
for _, st := range req.Steps {
|
||
if st.Name == "" {
|
||
continue
|
||
}
|
||
rec, err := s.ctx.EntClient.ProcessStep.Create().
|
||
SetFlowId(flowID).SetSeq(st.Seq).SetName(st.Name).
|
||
SetCollectType(st.CollectType).SetNeedCheck(st.NeedCheck).
|
||
SetNeedOperatorSign(st.NeedOperatorSign).SetNeedInspectorSign(st.NeedInspectorSign).
|
||
SetRemark(st.Remark).SetAttachment(st.Attachment).Save(ctx)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
_, _ = s.ctx.EntClient.StepCriterion.Delete().Where(stepcriterion.StepId(rec.ID)).Exec(ctx)
|
||
for _, c := range st.Criteria {
|
||
if c.Name == "" || c.Logic == "" || c.Logic == "NONE" {
|
||
continue
|
||
}
|
||
b := s.ctx.EntClient.StepCriterion.Create().
|
||
SetStepId(rec.ID).SetName(c.Name).SetUnit(c.Unit).SetLogic(c.Logic).SetTarget(c.Target)
|
||
if c.Min != nil {
|
||
b = b.SetMin(*c.Min)
|
||
}
|
||
if c.Max != nil {
|
||
b = b.SetMax(*c.Max)
|
||
}
|
||
if err := b.Exec(ctx); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "process.flow.save", "", operator, "process_flow", "", "维护工艺流程",
|
||
map[string]any{"flowId": flowID, "stations": stations, "steps": len(req.Steps)})
|
||
return nil
|
||
}
|
||
|
||
// syncStationFlow 同步工位绑定:工位 stationNo 绑定到 flowID(工位不存在时报错,不自动创建)
|
||
func (s *Service) syncStationFlow(ctx context.Context, stationNo, flowID int) error {
|
||
st, err := s.ctx.EntClient.Station.Query().Where(station.StationNo(stationNo)).First(ctx)
|
||
if err != nil {
|
||
return fmt.Errorf("工位 %d 不存在,请先在工位主数据中维护", stationNo)
|
||
}
|
||
_, err = s.ctx.EntClient.Station.UpdateOneID(st.ID).SetFlowId(flowID).Save(ctx)
|
||
return err
|
||
}
|
||
|
||
func (s *Service) DeleteFlow(ctx context.Context, id int, operator string) error {
|
||
// 条目12 守卫(2026-11-02):被执行中/已暂停工单引用的工艺禁止删除
|
||
if err := s.guardFlowEditable(ctx, id); err != nil {
|
||
return err
|
||
}
|
||
// 删除前先解除所有工位绑定,再清步骤与流程本身
|
||
_, _ = s.ctx.EntClient.Station.Update().
|
||
Where(station.FlowId(id)).
|
||
SetFlowId(0).Save(ctx)
|
||
_, _ = s.ctx.EntClient.ProcessStep.Delete().Where(processstep.FlowId(id)).Exec(ctx)
|
||
s.ctx.EventLog.Write(ctx, "process.flow.delete", "", operator, "process_flow", "", "删除工艺流程", map[string]any{"flowId": id})
|
||
return s.ctx.EntClient.ProcessFlow.DeleteOneID(id).Exec(ctx)
|
||
}
|
||
|
||
// flowSteps 查询某流程的工序步骤(含考核标准)
|
||
func (s *Service) flowSteps(ctx context.Context, flowId int) []*ProcessStepTemplate {
|
||
steps, _ := s.ctx.EntClient.ProcessStep.Query().
|
||
Where(processstep.FlowId(flowId)).Order(ent.Asc(processstep.FieldSeq)).All(ctx)
|
||
out := make([]*ProcessStepTemplate, 0, len(steps))
|
||
for _, st := range steps {
|
||
t := &ProcessStepTemplate{
|
||
ID: st.ID, Seq: st.Seq,
|
||
Name: st.Name, CollectType: st.CollectType, NeedCheck: st.NeedCheck,
|
||
NeedOperatorSign: st.NeedOperatorSign, NeedInspectorSign: st.NeedInspectorSign,
|
||
Remark: st.Remark, Attachment: st.Attachment, Criteria: []CriterionVO{},
|
||
}
|
||
crits, _ := s.ctx.EntClient.StepCriterion.Query().
|
||
Where(stepcriterion.StepId(st.ID)).All(ctx)
|
||
for _, c := range crits {
|
||
t.Criteria = append(t.Criteria, CriterionVO{
|
||
ID: c.ID, Name: c.Name, Unit: c.Unit, Logic: c.Logic,
|
||
Target: c.Target, Min: c.Min, Max: c.Max,
|
||
})
|
||
}
|
||
out = append(out, t)
|
||
}
|
||
return out
|
||
}
|
||
|
||
// ---------- 工位主数据(块3) ----------
|
||
|
||
type StationReq struct {
|
||
Id int `json:"id"`
|
||
StationNo int `json:"stationNo"`
|
||
Name string `json:"name"`
|
||
StationType *string `json:"stationType"`
|
||
FlowId *int `json:"flowId"`
|
||
VisibleTabs []string `json:"visibleTabs"` // 终端可见页签(空=全部显示)
|
||
// 规则3 fail-open:PLC 读取失败/离线时,前端弹「已现场确认,继续」二次确认后带此标记重发,后端放行并留痕
|
||
PlcOfflineConfirmed bool `json:"plcOfflineConfirmed"`
|
||
// 2026-11-13 拍板:应用「工位绑定变更」是清线门禁的触发点之一。
|
||
// 用户逐项打勾确认后带 confirmed 重发,确认结果写 event_log 形成可审计的「清线确认单」。
|
||
ClearanceConfirmed []string `json:"clearanceConfirmed"`
|
||
// 内部调用(应用工位模板)已在入口做过门禁,避免逐工位重复检查
|
||
SkipClearanceCheck bool `json:"skipClearanceCheck"`
|
||
}
|
||
|
||
type StationVO struct {
|
||
Id int `json:"id"`
|
||
StationNo int `json:"stationNo"`
|
||
Name string `json:"name"`
|
||
FlowId int `json:"flowId"`
|
||
FlowName string `json:"flowName"`
|
||
StationType string `json:"stationType"`
|
||
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) {
|
||
stas, err := s.ctx.EntClient.Station.Query().Order(ent.Asc(station.FieldStationNo)).All(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
flows, _ := s.ctx.EntClient.ProcessFlow.Query().All(ctx)
|
||
flowMap := map[int]*ent.ProcessFlow{}
|
||
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
|
||
}
|
||
|
||
// SaveStation 维护工位:
|
||
// - 工位号已存在 → 只改名称/类型/绑定流程(不增删工位)
|
||
// - 工位号不存在 → 新增工位;新增的工位号由用户自定义,允许扩展 14、15…(虚拟/物理均可)
|
||
//
|
||
// 工位数量以数据库为准,前端下拉随 station 表自动增减;虚拟工位(负数/13/14...)不连 PLC、仅记录;0=未指定不可作工位号。
|
||
// 内置工位(种子/初始化数据,is_builtin=true)需连 PLC 并必须按工位号顺序流转,
|
||
// 不允许手动更改工位类型;页面新增的工位一律为非内置,可改类型、可删除。
|
||
// 接驳台为独立主数据(MES dock 表),一个工位可绑定多个接驳台,关系以 dock.station_no 为准,页面不维护。
|
||
// stationHasActiveWorkOrder 工位是否正被"进行中"工单的生产路线引用(flow_combination 含该 stationNo)。
|
||
// 进行中 = IN_PROGRESS(执行中) / PAUSED(已暂停) / RELEASED(残量已下发待开工):这些状态下路线已固定,禁止改绑定。
|
||
func (s *Service) stationHasActiveWorkOrder(ctx context.Context, stationNo int) (bool, error) {
|
||
active := []string{"IN_PROGRESS", "PAUSED", "RELEASED"}
|
||
orders, err := s.ctx.EntClient.WorkOrder.Query().Where(workorder.StatusIn(active...)).All(ctx)
|
||
if err != nil {
|
||
return false, err
|
||
}
|
||
for _, o := range orders {
|
||
for _, item := range o.FlowCombination {
|
||
if item["stationNo"] == stationNo {
|
||
return true, nil
|
||
}
|
||
}
|
||
}
|
||
return false, nil
|
||
}
|
||
|
||
// 校验为收集式(报错一次收全 + 每条带怎么办,2026-10-20):类型/流程/托盘/在途指令全部列出、一次性返回。
|
||
func (s *Service) SaveStation(ctx context.Context, req StationReq, operator string) error {
|
||
// 工位号规则(2026-11-02 产线布局业务调整;2026-11-05 拍板:0=未指定,禁止作为工位号):
|
||
// 1~12 内置物理工位(硬件锁定,不可新增/占用);负数(-1、-2…)= 产线前段虚拟工位(排在工位1之前);
|
||
// ≥13 扩展工位;0 一律拒绝(Go 零值语义=未指定,不可作为合法工位号)。
|
||
// 负数工位号仅允许线下位(虚拟工位,不连 PLC、仅记录)。
|
||
if req.StationNo == 0 {
|
||
return errors.New("工位号不能为 0(0 表示未指定;产线前段虚拟工位请用负数号 -1、-2…,扩展工位用 ≥13)")
|
||
}
|
||
st, err := s.ctx.EntClient.Station.Query().Where(station.StationNo(req.StationNo)).First(ctx)
|
||
if err != nil {
|
||
// 新增工位:工位号不存在即创建(字段错误收集式列出)
|
||
// 物理产线工位(1~12)为内置硬件锁定(G1~G12 各连 PLC、须按工位号顺序流转),
|
||
// 禁止通过本接口新增或占用,避免与内置物理工位冲突、或绕过前端改物理工位号。
|
||
// 物理工位号只能由种子/初始化数据产生;页面新增请使用负数虚拟工位(-1、-2…)或扩展工位号(≥13),0 不可用。
|
||
if req.StationNo >= 1 && req.StationNo <= 12 {
|
||
return errors.New("工位号 1~12 为内置物理产线工位(硬件锁定),不可通过本接口新增或占用;产线前段虚拟工位请用负数号(-1、-2…),12 之后扩展用 ≥13")
|
||
}
|
||
ve := verr.New()
|
||
if req.Name == "" {
|
||
ve.Add("name", "请填写工位名称", "在「工位名称」输入框填写名称后保存")
|
||
}
|
||
// 工位类型:尊重请求(修复:此前新增一律落 LINE,前端建"线下位"实际存成线上位,
|
||
// 导致看板虚拟工位列表为空——2026-11-02 条目14根因)
|
||
stype := "LINE"
|
||
if req.StationType != nil && *req.StationType == "OFFLINE" {
|
||
stype = "OFFLINE"
|
||
}
|
||
if req.StationNo <= 0 && stype != "OFFLINE" {
|
||
ve.Add("stationNo", "工位号 ≤ 0 仅允许线下位(虚拟工位)", "类型选「线下位」后再保存")
|
||
}
|
||
if req.FlowId != nil && *req.FlowId > 0 {
|
||
flow, fErr := s.ctx.EntClient.ProcessFlow.Get(ctx, *req.FlowId)
|
||
if fErr != nil {
|
||
ve.Add("flowId", "所选工艺流程不存在", "从绑定流程下拉中重新选择")
|
||
} else if flow.Status != "ACTIVE" {
|
||
ve.AddAction("flowId", "该工艺流程已停用", "到「工艺」页启用后再绑定,或换选其他流程", "去工艺页", "/process-flow")
|
||
}
|
||
}
|
||
if err := ve.OrNil(); err != nil {
|
||
return err
|
||
}
|
||
cr := s.ctx.EntClient.Station.Create().
|
||
SetStationNo(req.StationNo).SetName(req.Name).SetStationType(stype).SetStatus("ENABLED").
|
||
// 页面「新增工位」创建的是非内置工位(可改类型、可删除);内置工位只能由种子/初始化数据产生。
|
||
SetIsBuiltin(false)
|
||
if len(req.VisibleTabs) > 0 {
|
||
cr.SetVisibleTabs(req.VisibleTabs)
|
||
}
|
||
if req.FlowId != nil && *req.FlowId > 0 {
|
||
cr.SetFlowId(*req.FlowId)
|
||
}
|
||
created, cErr := cr.Save(ctx)
|
||
if cErr != nil {
|
||
return cErr
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "station.create", "", operator, "station", "",
|
||
"新增工位", map[string]any{"stationNo": created.StationNo, "name": created.Name})
|
||
return nil
|
||
}
|
||
// 更新分支:字段错误 + 规则3守卫(托盘在位/在途指令)全部收集,一次性返回
|
||
// 2026-11-13 拍板:改「工位绑定」= 应用工位绑定变更,必须过清线门禁五项
|
||
//(在制品 / 余料 / 托盘 / PLC 未完成任务 / AGV 在途);逐项确认放行会落 event_log 留痕。
|
||
if req.FlowId != nil && *req.FlowId != st.FlowId && !req.SkipClearanceCheck {
|
||
if err := s.GuardLineClearanceWithConfirm(ctx, "", req.ClearanceConfirmed, operator); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
ve := verr.New()
|
||
// 仅改名称:flowId 不传(nil)保留原绑定;0=解绑;>0=绑定指定启用流程。
|
||
// 规则3(2026-10-20 拍板,2026-10-20 下午改 fail-closed→fail-open):改绑定关系(含解绑)前,
|
||
// 过「在途指令/托盘在位」双检(两条同时收集,不串行)。
|
||
// PLC 读取失败/超时/断连:不再是硬拒绝——未二次确认前返回 ErrPlcOfflineConfirmRequired
|
||
//(前端弹「已现场确认,继续」二次确认后带 plcOfflineConfirmed=true 重发→放行并留痕);
|
||
// 托盘在位/在途指令仍按原规则硬拒绝。
|
||
// 接驳台关系在 dock 表维护、本页不编辑,守卫仅覆盖绑定关系变更。
|
||
plcOffline := false
|
||
bindFlow := 0
|
||
if req.FlowId != nil {
|
||
bindFlow = *req.FlowId
|
||
// 进行中工单守卫(2026-11-02 工位管理需求):工位正被进行中工单的生产路线引用时,禁止修改/解除绑定工艺。
|
||
// 仅当绑定关系真的发生变化(含解绑/换绑)时才拦截;重复保存原绑定不误伤。
|
||
if *req.FlowId != st.FlowId {
|
||
if busy, bErr := s.stationHasActiveWorkOrder(ctx, st.StationNo); bErr == nil && busy {
|
||
ve.Add("flowId", fmt.Sprintf("工位%d 存在正在进行的工单(生产路线包含此工位),禁止修改绑定工艺", st.StationNo),
|
||
"请先将该工位的进行中工单完工或取消,再修改绑定工艺")
|
||
}
|
||
}
|
||
if n, _ := s.ctx.EntClient.PlcSendLog.Query().
|
||
Where(plcsendlog.Status("SENT"), plcsendlog.StationNo(st.StationNo)).Count(ctx); n > 0 {
|
||
ve.AddAction("flowId", fmt.Sprintf("工位%d 有正在执行的指令,不能修改配置", st.StationNo),
|
||
"等指令完成,或到 PLC 手动监控页强制清零后再改配置", "去 PLC 监控", "/plc-monitor")
|
||
}
|
||
if st.StationType == "LINE" {
|
||
// 托盘在位读 PLC G{工位号} 位;mock 模式同样走 QueryStationPallet 内存态,逻辑一致。
|
||
has, perr := s.ctx.PLC.QueryStationPallet(ctx, st.StationNo)
|
||
if perr != nil {
|
||
if req.PlcOfflineConfirmed {
|
||
// fail-open:PLC 离线已现场确认 → 放行,置 plcOffline 由下方留痕
|
||
plcOffline = true
|
||
} else {
|
||
// 未确认:短路返回哨兵错误,handler 映射为 3021 触发前端二次确认
|
||
return ErrPlcOfflineConfirmRequired
|
||
}
|
||
} else if has {
|
||
ve.Add("flowId", fmt.Sprintf("工位%d 上还有工件,不能修改配置", st.StationNo),
|
||
"先完成/移走该工位上的工件(下线完工或流转到下一位),再修改配置")
|
||
}
|
||
}
|
||
if bindFlow > 0 {
|
||
flow, fErr := s.ctx.EntClient.ProcessFlow.Get(ctx, bindFlow)
|
||
if fErr != nil {
|
||
ve.Add("flowId", "所选工艺流程不存在", "从绑定流程下拉中重新选择")
|
||
} else if flow.Status != "ACTIVE" {
|
||
ve.AddAction("flowId", "该工艺流程已停用", "到「工艺」页启用后再绑定,或换选其他流程", "去工艺页", "/process-flow")
|
||
}
|
||
}
|
||
}
|
||
if err := ve.OrNil(); err != nil {
|
||
return err
|
||
}
|
||
upd := s.ctx.EntClient.Station.UpdateOneID(st.ID).SetName(req.Name)
|
||
// 类型调整:仅非内置工位允许 LINE↔OFFLINE(2026-11-02:修复存量虚拟工位被存成 LINE 后
|
||
// 看板"暂无虚拟工位"无法自愈的问题);内置工位类型锁定不变。
|
||
if req.StationType != nil && !st.IsBuiltin {
|
||
if nt := *req.StationType; (nt == "LINE" || nt == "OFFLINE") && nt != st.StationType {
|
||
upd.SetStationType(nt)
|
||
s.ctx.EventLog.Write(ctx, "station.type_change", "", operator, "station", "",
|
||
fmt.Sprintf("工位%d 类型变更:%s → %s", st.StationNo, st.StationType, nt),
|
||
map[string]any{"stationNo": st.StationNo, "before": st.StationType, "after": nt})
|
||
}
|
||
}
|
||
if req.FlowId != nil {
|
||
upd.SetFlowId(bindFlow) // 0=解绑
|
||
}
|
||
// 终端可见页签:传 nil=不改;传空数组=清空(全部显示);传列表=按配置显示
|
||
if req.VisibleTabs != nil {
|
||
upd.SetVisibleTabs(req.VisibleTabs)
|
||
}
|
||
if _, err := upd.Save(ctx); err != nil {
|
||
return err
|
||
}
|
||
if plcOffline {
|
||
// 留痕:PLC 离线放行(工位配置变更,安全相关,须可审计)
|
||
s.ctx.EventLog.Write(ctx, "station.config.offline_change", "", operator, "station", "",
|
||
fmt.Sprintf("PLC 离线放行工位配置变更(工位%d:改前工艺%d → 改后工艺%d)", st.StationNo, st.FlowId, bindFlow),
|
||
map[string]any{"stationNo": st.StationNo, "beforeFlowId": st.FlowId, "afterFlowId": bindFlow, "operator": operator, "plcOffline": true})
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "station.save", "", operator, "station", "", "维护工位",
|
||
map[string]any{"stationNo": req.StationNo})
|
||
return nil
|
||
}
|
||
|
||
// ErrPlcOfflineConfirmRequired 哨兵错误:工位 PLC 读取失败/超时/断连且未二次确认时返回;
|
||
// handler 映射为 code=3021,前端弹「已现场确认,继续」二次确认后带 plcOfflineConfirmed=true 重发。
|
||
var ErrPlcOfflineConfirmRequired = errors.New("PLC离线确认:无法确认工位托盘状态(PLC 读取失败),请到现场确认后重试")
|
||
// DeleteStation 删除工位:内置工位不允许删除(对应实体产线位置,需连 PLC 且必须按顺序流转);
|
||
// 非内置工位(页面新增的)允许删除。
|
||
func (s *Service) DeleteStation(ctx context.Context, id int, operator string) error {
|
||
if id <= 0 {
|
||
return errors.New("缺少 id")
|
||
}
|
||
st, err := s.ctx.EntClient.Station.Get(ctx, id)
|
||
if err != nil {
|
||
return errors.New("工位不存在")
|
||
}
|
||
if st.IsBuiltin {
|
||
return errors.New("内置工位不允许删除")
|
||
}
|
||
if err := s.ctx.EntClient.Station.DeleteOneID(st.ID).Exec(ctx); err != nil {
|
||
return err
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "station.delete", "", operator, "station", "", "删除工位",
|
||
map[string]any{"stationNo": st.StationNo, "name": st.Name})
|
||
return nil
|
||
}
|
||
|
||
// SetStationStatus 工位启用/停用(切换 station status:ENABLED/DISABLED)。
|
||
// 内置/非内置均可切换;停用不影响历史引用(行保留),仅影响该工位能否被流程选用与终端拉取。
|
||
func (s *Service) SetStationStatus(ctx context.Context, id int, status, operator string) error {
|
||
if id <= 0 {
|
||
return errors.New("缺少 id")
|
||
}
|
||
if status != "ENABLED" && status != "DISABLED" {
|
||
return errors.New("非法状态")
|
||
}
|
||
st, err := s.ctx.EntClient.Station.Get(ctx, id)
|
||
if err != nil {
|
||
return errors.New("工位不存在")
|
||
}
|
||
if st.Status == status {
|
||
return nil
|
||
}
|
||
if err := s.ctx.EntClient.Station.UpdateOneID(id).SetStatus(status).Exec(ctx); err != nil {
|
||
return err
|
||
}
|
||
action := "停用工位"
|
||
if status == "ENABLED" {
|
||
action = "启用工位"
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "station.status", "", operator, "station", fmt.Sprint(id), action,
|
||
map[string]any{"id": id, "stationNo": st.StationNo, "status": status})
|
||
return nil
|
||
}
|
||
|
||
// SetFlowStatus 工艺流程启用/停用。
|
||
// 新语义:绑定关系由「保存流程」显式维护(一个流程可绑多工位),启停只切换流程状态,
|
||
// 不再自动解绑/绑定工位;停用流程对已绑定工位不可用(工位取步骤时按 ACTIVE 过滤)。
|
||
func (s *Service) SetFlowStatus(ctx context.Context, id int, status, operator string) error {
|
||
if id <= 0 {
|
||
return errors.New("缺少 id")
|
||
}
|
||
if status != "ACTIVE" && status != "INACTIVE" {
|
||
return errors.New("非法状态")
|
||
}
|
||
flow, err := s.ctx.EntClient.ProcessFlow.Get(ctx, id)
|
||
if err != nil {
|
||
return errors.New("工艺流程不存在")
|
||
}
|
||
if flow.Status == status {
|
||
return nil
|
||
}
|
||
// 启用无需额外动作:绑定由保存流程时校验(一个工位不会被两个启用流程占用)
|
||
if err := s.ctx.EntClient.ProcessFlow.UpdateOneID(id).SetStatus(status).Exec(ctx); err != nil {
|
||
return err
|
||
}
|
||
action := "停用工艺流程"
|
||
if status == "ACTIVE" {
|
||
action = "启用工艺流程"
|
||
}
|
||
s.ctx.EventLog.Write(ctx, "process.flow.status", "", operator, "process_flow", "", action, map[string]any{"flowId": id, "status": status, "name": flow.Name})
|
||
return nil
|
||
}
|
||
|
||
// ---------- 工位任务(块4/5:工位终端拉取) ----------
|
||
|
||
func (s *Service) StationTask(ctx context.Context, stationNo int) (map[string]any, error) {
|
||
st, err := s.ctx.EntClient.Station.Query().Where(station.StationNo(stationNo)).First(ctx)
|
||
if err != nil {
|
||
return nil, errors.New("工位不存在或未配置")
|
||
}
|
||
// 工位终端可见工单(2026-11-16 死结7 定案):不限排产日期,所有进行中(IN_PROGRESS)工单,
|
||
// 且工艺组合必须包含本工位——干不了的单不给选(此前整线单都可见,选了报工才被拒)。
|
||
// 「昨天没干完的、想提前干明天的」都能选;PAUSED 暂停单不显示(恢复后可见)。
|
||
orderNos := []string{}
|
||
wos, _ := s.ctx.EntClient.WorkOrder.Query().
|
||
Where(workorder.StatusIn("IN_PROGRESS")).
|
||
Order(ent.Asc(workorder.FieldID)).All(ctx)
|
||
for _, w := range wos {
|
||
for _, item := range w.FlowCombination {
|
||
if item["stationNo"] == stationNo {
|
||
orderNos = append(orderNos, w.WorkOrderNo)
|
||
break
|
||
}
|
||
}
|
||
}
|
||
// M4:工位终端按「本工位绑定的工艺流程」驱动。
|
||
// 产线定义 = 工位绑定(station.flow_id)+ 工位号 1→12 顺序,已无独立"工艺路线/路线段"对象。
|
||
// 本工位要干哪些步骤,完全取决于 station.flow_id 指向的流程图,工单的 processSeq 只决定走哪些工位。
|
||
activeFlowId := st.FlowId
|
||
var flow *ent.ProcessFlow
|
||
if activeFlowId > 0 {
|
||
flow, _ = s.ctx.EntClient.ProcessFlow.Get(ctx, activeFlowId)
|
||
}
|
||
steps := []*ProcessStepTemplate{}
|
||
if flow != nil && flow.Status == "ACTIVE" {
|
||
steps = s.flowSteps(ctx, flow.ID)
|
||
}
|
||
return map[string]any{
|
||
"stationNo": st.StationNo,
|
||
"stationName": st.Name,
|
||
"flowId": activeFlowId,
|
||
"flow": flow,
|
||
"flowActive": flow != nil && flow.Status == "ACTIVE",
|
||
"steps": steps,
|
||
"orderNos": orderNos,
|
||
// 终端可见页签(按工位配置;空=全部显示)
|
||
"tabs": st.VisibleTabs,
|
||
}, nil
|
||
}
|
||
|
||
// WorkloadRow 绩效/工作量聚合行(按人/按工位/明细三视图共用)
|
||
// 前端按 camelCase 读取,必须显式标注 json tag(否则 Go 默认序列化为 PascalCase 导致列空白)
|
||
type WorkloadRow struct {
|
||
Operator string `json:"operator"`
|
||
StationNo string `json:"stationNo"`
|
||
Date string `json:"date"`
|
||
OrderNo string `json:"orderNo"`
|
||
FlowId int `json:"flowId"`
|
||
ProcessName string `json:"processName"`
|
||
DoneCount int `json:"doneCount"`
|
||
OkCount int `json:"okCount"`
|
||
NgCount int `json:"ngCount"`
|
||
// Item M 绩效效率:作业时长取自 workpiece_process.duration_sec
|
||
TotalDurationSec int `json:"totalDurationSec"` // 累计作业时长(秒)
|
||
AvgDurationSec int `json:"avgDurationSec"` // 平均作业时长(秒)=累计/完成数
|
||
Efficiency float64 `json:"efficiency"` // 效率(件/小时)=完成数/(累计时长/3600)
|
||
}
|
||
|
||
// finalizeWorkloadRow 由累计作业时长与完成数派生平均作业时长与效率
|
||
func finalizeWorkloadRow(r *WorkloadRow) {
|
||
if r.DoneCount > 0 {
|
||
r.AvgDurationSec = r.TotalDurationSec / r.DoneCount
|
||
}
|
||
if r.TotalDurationSec > 0 {
|
||
r.Efficiency = float64(r.DoneCount) / (float64(r.TotalDurationSec) / 3600.0)
|
||
}
|
||
}
|
||
|
||
// StationSessionRow 上机记录行(由现有数据推导,零新表):
|
||
// 上机时间=开工签到(CHECKIN)时刻;下机时间=签到后该人该工位最后一条活动
|
||
// (报工 endedAt / 巡检记录 createdAt 取较大者,以同工位同人的下一次签到为界);
|
||
// 加工件数=窗口内报工实绩计数。口径说明:下机为「最后活动」推断,未签到则无记录。
|
||
type StationSessionRow struct {
|
||
Operator string `json:"operator"`
|
||
StationNo string `json:"stationNo"`
|
||
Date string `json:"date"` // 归属日期(签到那天)
|
||
CheckinAt string `json:"checkinAt"` // 上机时间(开工签到)
|
||
LastActiveAt string `json:"lastActiveAt"` // 下机时间(最后活动)
|
||
DurationSec int `json:"durationSec"` // 在机时长(秒)=下机-上机
|
||
DoneCount int `json:"doneCount"` // 加工件数
|
||
Efficiency float64 `json:"efficiency"` // 效率(件/小时)
|
||
}
|
||
|
||
const fmtSessionTime = "2006-01-02 15:04:05"
|
||
|
||
// buildStationSessions 由开工签到 + 报工实绩推导上机记录(按签到倒序)。
|
||
// rows 为已按 操作人/工位/日期 过滤的报工实绩(工单号筛选不影响本视图)。
|
||
func (s *Service) buildStationSessions(ctx context.Context, operator, stationNo, from, to string, rows []*ent.WorkpieceProcess) []StationSessionRow {
|
||
// 巡检记录:同筛选(不含工单号),既提供签到点也提供活动点
|
||
q := s.ctx.EntClient.InspectionRecord.Query()
|
||
if operator != "" {
|
||
q = q.Where(inspectionrecord.Operator(operator))
|
||
}
|
||
if stationNo != "" {
|
||
q = q.Where(inspectionrecord.StationNo(stationNo))
|
||
}
|
||
if from != "" {
|
||
if f, err := time.Parse("2006-01-02", from); err == nil {
|
||
q = q.Where(inspectionrecord.CreatedAtGTE(f))
|
||
}
|
||
}
|
||
if to != "" {
|
||
if t, err := time.Parse("2006-01-02", to); err == nil {
|
||
q = q.Where(inspectionrecord.CreatedAtLT(t.Add(24 * time.Hour)))
|
||
}
|
||
}
|
||
insps, err := q.All(ctx)
|
||
if err != nil {
|
||
return nil
|
||
}
|
||
|
||
// 活动时间轴:key=操作人|工位 → 有序活动时刻列表(报工 + 巡检)
|
||
type key struct{ op, st string }
|
||
act := map[key][]time.Time{}
|
||
addAct := func(op, st string, t time.Time) {
|
||
if op == "" || t.IsZero() {
|
||
return
|
||
}
|
||
k := key{op, st}
|
||
act[k] = append(act[k], t)
|
||
}
|
||
for _, r := range rows {
|
||
t := r.CreatedAt
|
||
if r.EndedAt != nil {
|
||
t = *r.EndedAt
|
||
}
|
||
addAct(r.Operator, r.StationNo, t)
|
||
}
|
||
for _, in := range insps {
|
||
addAct(in.Operator, in.StationNo, in.CreatedAt)
|
||
}
|
||
for k := range act {
|
||
times := act[k]
|
||
sort.Slice(times, func(i, j int) bool { return times[i].Before(times[j]) })
|
||
act[k] = times
|
||
}
|
||
|
||
// 签到 → 会话:结束=窗口内最后活动(下一次签到为界),无活动则时长 0
|
||
type ck struct {
|
||
k key
|
||
at time.Time
|
||
}
|
||
checkins := make([]ck, 0, len(insps))
|
||
for _, in := range insps {
|
||
if in.Category == "CHECKIN" {
|
||
checkins = append(checkins, ck{key{in.Operator, in.StationNo}, in.CreatedAt})
|
||
}
|
||
}
|
||
sort.Slice(checkins, func(i, j int) bool {
|
||
if checkins[i].k.op != checkins[j].k.op {
|
||
return checkins[i].k.op < checkins[j].k.op
|
||
}
|
||
if checkins[i].k.st != checkins[j].k.st {
|
||
return checkins[i].k.st < checkins[j].k.st
|
||
}
|
||
return checkins[i].at.Before(checkins[j].at)
|
||
})
|
||
|
||
out := make([]StationSessionRow, 0, len(checkins))
|
||
for i, c := range checkins {
|
||
// 窗口终点:同人同工位的下一次签到;无下一次则+24h 兜底
|
||
endBound := c.at.Add(24 * time.Hour)
|
||
if i+1 < len(checkins) && checkins[i+1].k == c.k {
|
||
endBound = checkins[i+1].at
|
||
}
|
||
row := StationSessionRow{
|
||
Operator: c.k.op,
|
||
StationNo: c.k.st,
|
||
Date: c.at.Format("2006-01-02"),
|
||
CheckinAt: c.at.Format(fmtSessionTime),
|
||
}
|
||
var last time.Time
|
||
for _, t := range act[c.k] {
|
||
if t.After(c.at) && t.Before(endBound) && t.After(last) {
|
||
last = t
|
||
} else if t.After(endBound) {
|
||
break
|
||
}
|
||
}
|
||
if !last.IsZero() {
|
||
row.LastActiveAt = last.Format(fmtSessionTime)
|
||
row.DurationSec = int(last.Sub(c.at).Seconds())
|
||
} else {
|
||
row.LastActiveAt = row.CheckinAt
|
||
}
|
||
for _, r := range rows {
|
||
if r.Operator != c.k.op || r.StationNo != c.k.st {
|
||
continue
|
||
}
|
||
t := r.CreatedAt
|
||
if r.EndedAt != nil {
|
||
t = *r.EndedAt
|
||
}
|
||
if t.After(c.at) && !t.After(last) {
|
||
row.DoneCount++
|
||
}
|
||
}
|
||
if row.DurationSec > 0 {
|
||
row.Efficiency = float64(row.DoneCount) / (float64(row.DurationSec) / 3600.0)
|
||
}
|
||
out = append(out, row)
|
||
}
|
||
// 倒序:最新签到在前(与全项目增量展示口径一致)
|
||
sort.Slice(out, func(i, j int) bool { return out[i].CheckinAt > out[j].CheckinAt })
|
||
return out
|
||
}
|
||
|
||
// Workload 绩效统计(按人/按工位/明细三视图,各自真分页)。
|
||
// orderNo 非空时按工单号模糊过滤(客户第12条「记录查看加一项看工单号查询」)。
|
||
func (s *Service) Workload(ctx context.Context, operator, stationNo, orderNo, from, to string,
|
||
opPage, opSize, stPage, stSize, detPage, detSize int) (map[string]any, error) {
|
||
q := s.ctx.EntClient.WorkpieceProcess.Query()
|
||
if operator != "" {
|
||
q = q.Where(workpieceprocess.Operator(operator))
|
||
}
|
||
if stationNo != "" {
|
||
q = q.Where(workpieceprocess.StationNo(stationNo))
|
||
}
|
||
if orderNo != "" {
|
||
q = q.Where(workpieceprocess.OrderNoContainsFold(orderNo))
|
||
}
|
||
if from != "" {
|
||
if f, err := time.Parse("2006-01-02", from); err == nil {
|
||
q = q.Where(workpieceprocess.CreatedAtGTE(f))
|
||
}
|
||
}
|
||
if to != "" {
|
||
if t, err := time.Parse("2006-01-02", to); err == nil {
|
||
q = q.Where(workpieceprocess.CreatedAtLT(t.Add(24 * time.Hour)))
|
||
}
|
||
}
|
||
rows, err := q.All(ctx)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
type key struct {
|
||
op, station, date string
|
||
code int
|
||
order string
|
||
}
|
||
agg := map[key]*WorkloadRow{}
|
||
for _, r := range rows {
|
||
// 明细聚合粒度含工单号:按工单号筛选后行内可见归属(客户追问点)
|
||
k := key{r.Operator, r.StationNo, r.CreatedAt.Format("2006-01-02"), r.FlowId, r.OrderNo}
|
||
row, ok := agg[k]
|
||
if !ok {
|
||
row = &WorkloadRow{Operator: r.Operator, StationNo: r.StationNo, Date: k.date, OrderNo: r.OrderNo, FlowId: r.FlowId, ProcessName: r.ProcessName}
|
||
agg[k] = row
|
||
}
|
||
row.DoneCount++
|
||
row.TotalDurationSec += r.DurationSec
|
||
if r.Result == "OK" {
|
||
row.OkCount++
|
||
} else {
|
||
row.NgCount++
|
||
}
|
||
}
|
||
list := make([]*WorkloadRow, 0, len(agg))
|
||
for _, v := range agg {
|
||
list = append(list, v)
|
||
}
|
||
sort.Slice(list, func(i, j int) bool {
|
||
if list[i].Operator != list[j].Operator {
|
||
return list[i].Operator < list[j].Operator
|
||
}
|
||
if list[i].StationNo != list[j].StationNo {
|
||
return list[i].StationNo < list[j].StationNo
|
||
}
|
||
if list[i].Date != list[j].Date {
|
||
return list[i].Date < list[j].Date
|
||
}
|
||
if list[i].FlowId != list[j].FlowId {
|
||
return list[i].FlowId < list[j].FlowId
|
||
}
|
||
return list[i].OrderNo < list[j].OrderNo
|
||
})
|
||
|
||
// 三个视图分别聚合(2026-09-08 绩效报表改造:按人/按工位/明细,各自真分页)
|
||
byOpAgg := map[string]*WorkloadRow{}
|
||
byStAgg := map[string]*WorkloadRow{}
|
||
for _, v := range list {
|
||
opKey := v.Operator
|
||
if o, ok := byOpAgg[opKey]; ok {
|
||
o.DoneCount += v.DoneCount
|
||
o.OkCount += v.OkCount
|
||
o.NgCount += v.NgCount
|
||
o.TotalDurationSec += v.TotalDurationSec
|
||
} else {
|
||
byOpAgg[opKey] = &WorkloadRow{Operator: v.Operator, DoneCount: v.DoneCount, OkCount: v.OkCount, NgCount: v.NgCount, TotalDurationSec: v.TotalDurationSec}
|
||
}
|
||
stKey := v.StationNo
|
||
if o, ok := byStAgg[stKey]; ok {
|
||
o.DoneCount += v.DoneCount
|
||
o.OkCount += v.OkCount
|
||
o.NgCount += v.NgCount
|
||
o.TotalDurationSec += v.TotalDurationSec
|
||
} else {
|
||
byStAgg[stKey] = &WorkloadRow{StationNo: v.StationNo, DoneCount: v.DoneCount, OkCount: v.OkCount, NgCount: v.NgCount, TotalDurationSec: v.TotalDurationSec}
|
||
}
|
||
}
|
||
paginate := func(all []*WorkloadRow, page, size int) (int, []*WorkloadRow) {
|
||
total := len(all)
|
||
start := (page - 1) * size
|
||
if start > total {
|
||
start = total
|
||
}
|
||
end := start + size
|
||
if end > total {
|
||
end = total
|
||
}
|
||
return total, all[start:end]
|
||
}
|
||
|
||
byOpList := make([]*WorkloadRow, 0, len(byOpAgg))
|
||
for _, v := range byOpAgg {
|
||
finalizeWorkloadRow(v)
|
||
byOpList = append(byOpList, v)
|
||
}
|
||
sort.Slice(byOpList, func(i, j int) bool { return byOpList[i].Operator < byOpList[j].Operator })
|
||
byStList := make([]*WorkloadRow, 0, len(byStAgg))
|
||
for _, v := range byStAgg {
|
||
finalizeWorkloadRow(v)
|
||
byStList = append(byStList, v)
|
||
}
|
||
sort.Slice(byStList, func(i, j int) bool { return byStList[i].StationNo < byStList[j].StationNo })
|
||
|
||
// 明细视图:按 (操作人,工位,日期,工艺,工单号) 聚合,与前端明细表列(orderNo/date/doneCount/okCount/ngCount)对齐
|
||
for _, v := range list {
|
||
finalizeWorkloadRow(v)
|
||
}
|
||
opTotal, byOpPage := paginate(byOpList, opPage, opSize)
|
||
stTotal, byStPage := paginate(byStList, stPage, stSize)
|
||
detTotal, detList := paginate(list, detPage, detSize)
|
||
|
||
// 上机记录:由开工签到+报工实绩推导(不受工单号筛选影响,前端在该页签禁用工单号)
|
||
sessions := s.buildStationSessions(ctx, operator, stationNo, from, to, rows)
|
||
|
||
// R8(2026-11-03 拍板):绩效报表读工单损耗——按工单号聚合损耗台账(数据源=工单退料产生的损耗记录)。
|
||
// 台账「主管批注」只写 comment/commenter,不改 lossQty,故改批注不影响工单损耗数(验收点)。
|
||
lossQ := s.ctx.EntClient.LossLedger.Query()
|
||
if from != "" {
|
||
if f, perr := time.Parse("2006-01-02", from); perr == nil {
|
||
lossQ = lossQ.Where(lossledger.CreatedAtGTE(f))
|
||
}
|
||
}
|
||
if to != "" {
|
||
if t, perr := time.Parse("2006-01-02", to); perr == nil {
|
||
lossQ = lossQ.Where(lossledger.CreatedAtLT(t.Add(24 * time.Hour)))
|
||
}
|
||
}
|
||
if orderNo != "" {
|
||
lossQ = lossQ.Where(lossledger.WorkOrderNoContainsFold(orderNo))
|
||
}
|
||
lossByOrderMap := map[string]float64{}
|
||
lossTotal := 0.0
|
||
if lossRows, lerr := lossQ.All(ctx); lerr == nil {
|
||
for _, l := range lossRows {
|
||
if l.WorkOrderNo == "" {
|
||
continue // 无工单归属的损耗(如普通退料整单退无差额)不进工单维度
|
||
}
|
||
lossByOrderMap[l.WorkOrderNo] += l.LossQty
|
||
lossTotal += l.LossQty
|
||
}
|
||
}
|
||
type lossRow struct {
|
||
OrderNo string `json:"orderNo"`
|
||
LossQty float64 `json:"lossQty"`
|
||
}
|
||
lossList := make([]lossRow, 0, len(lossByOrderMap))
|
||
for k, v := range lossByOrderMap {
|
||
lossList = append(lossList, lossRow{OrderNo: k, LossQty: v})
|
||
}
|
||
sort.Slice(lossList, func(i, j int) bool { return lossList[i].OrderNo < lossList[j].OrderNo })
|
||
|
||
return map[string]any{
|
||
"byOperator": map[string]any{"total": opTotal, "list": byOpPage},
|
||
"byStation": map[string]any{"total": stTotal, "list": byStPage},
|
||
"detail": map[string]any{"total": detTotal, "list": detList},
|
||
"sessions": map[string]any{"total": len(sessions), "list": sessions},
|
||
// R8 工单损耗(绩效读工单损耗):lossTotal 总损耗 + lossList 按工单聚合
|
||
"lossTotal": lossTotal,
|
||
"lossByOrder": map[string]any{"total": len(lossList), "list": lossList},
|
||
}, nil
|
||
}
|
||
|
||
// ---------- 工艺物料清单(flow_material) ----------
|
||
|
||
// FlowMaterialReq 工艺物料清单条目(保存为整表覆盖)
|
||
type FlowMaterialReq struct {
|
||
MaterialCode string `json:"materialCode"`
|
||
MaterialName string `json:"materialName"`
|
||
Spec string `json:"spec"`
|
||
Unit string `json:"unit"`
|
||
SnMode int `json:"snMode"` // 是否逐件SN管理 1序列号=是(录SN)/2序列号=否(冗余自物料档案)
|
||
UnitQty float64 `json:"unitQty"` // 单台用量
|
||
LossRate float64 `json:"lossRate"` // 损耗率(%)
|
||
}
|
||
|
||
// ListFlowMaterials 查某工艺的物料清单(按 ID 升序)
|
||
func (s *Service) ListFlowMaterials(ctx context.Context, flowId int) ([]*ent.FlowMaterial, error) {
|
||
return s.ctx.EntClient.FlowMaterial.Query().
|
||
Where(flowmaterial.FlowId(flowId)).
|
||
Order(ent.Asc(flowmaterial.FieldID)).All(ctx)
|
||
}
|
||
|
||
// SaveFlowMaterials 保存工艺物料清单(整表覆盖:先删后插)。
|
||
// 物料编码须在 WMS 物料档案存在;WMS 不可达/异常时降级放行并记日志,避免阻塞工艺配置。
|
||
func (s *Service) SaveFlowMaterials(ctx context.Context, flowId int, items []FlowMaterialReq, operator string) error {
|
||
if flowId <= 0 {
|
||
return errors.New("flowId 必填")
|
||
}
|
||
if _, err := s.ctx.EntClient.ProcessFlow.Get(ctx, flowId); err != nil {
|
||
return errors.New("工艺不存在")
|
||
}
|
||
// 条目12 守卫(2026-11-02):被执行中/已暂停工单引用的工艺,物料清单禁止整表覆盖
|
||
//(叫料池/单台用料均实时读本清单,改了会改变在产工单的备料口径)
|
||
if err := s.guardFlowEditable(ctx, flowId); err != nil {
|
||
return err
|
||
}
|
||
// WMS 物料存在性校验(缺失拒绝;不可达降级放行)
|
||
codes := make([]string, 0, len(items))
|
||
seen := map[string]bool{}
|
||
for _, it := range items {
|
||
if it.MaterialCode == "" {
|
||
return errors.New("物料编码不能为空")
|
||
}
|
||
if seen[it.MaterialCode] {
|
||
return errors.New("物料 " + it.MaterialCode + " 重复")
|
||
}
|
||
seen[it.MaterialCode] = true
|
||
codes = append(codes, it.MaterialCode)
|
||
}
|
||
if len(codes) > 0 && s.ctx.Wms != nil {
|
||
if missing, err := s.ctx.Wms.MaterialExists(ctx, codes); err != nil {
|
||
s.ctx.EventLog.Write(ctx, "flow.material.wms_skip", "", operator, "process_flow", itoa(flowId),
|
||
"WMS 物料校验不可达,已降级放行", map[string]any{"error": err.Error()})
|
||
} else if len(missing) > 0 {
|
||
return errors.New("以下物料在 WMS 物料档案中不存在:" + strings.Join(missing, "、"))
|
||
}
|
||
}
|
||
tx, err := s.ctx.EntClient.Tx(ctx)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
committed := false
|
||
defer func() {
|
||
if !committed {
|
||
_ = tx.Rollback()
|
||
}
|
||
}()
|
||
client := tx.Client()
|
||
if _, err := client.FlowMaterial.Delete().Where(flowmaterial.FlowId(flowId)).Exec(ctx); err != nil {
|
||
return err
|
||
}
|
||
for _, it := range items {
|
||
if err := client.FlowMaterial.Create().
|
||
SetFlowId(flowId).
|
||
SetMaterialCode(it.MaterialCode).SetMaterialName(it.MaterialName).
|
||
SetSpec(it.Spec).SetUnit(it.Unit).SetSnMode(it.SnMode).
|
||
SetUnitQty(it.UnitQty).SetLossRate(it.LossRate).
|
||
Exec(ctx); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
if err := tx.Commit(); err != nil {
|
||
return err
|
||
}
|
||
committed = true
|
||
s.ctx.EventLog.Write(ctx, "flow.material.save", "", operator, "process_flow", itoa(flowId),
|
||
"保存工艺物料清单(整表覆盖)", map[string]any{"flowId": flowId, "count": len(items)})
|
||
// 叫料池重算(B5:物料清单是用量来源,变更立即对齐)
|
||
_, _ = s.RecomputePoolAll(ctx)
|
||
return nil
|
||
}
|