Files
bj_power/bj_power_mes/internal/logic/station_template.go
T

399 lines
15 KiB
Go
Raw Normal View History

package logic
import (
"context"
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"bj_power_mes/ent/plcsendlog"
"bj_power_mes/ent/station"
"bj_power_mes/ent/sysconfig"
)
// 工位绑定模板:一模板一键存 sys_config(key = station.bind.template.N,N=1..20)。
// sys_config.value 上限 512 字节,故单键只存单条模板 JSON,不用一个键存整个数组。
const (
stationTemplateKeyPrefix = "station.bind.template."
stationTemplateMaxCount = 20
stationTemplateMaxBytes = 512
)
// StationTemplateStation 模板内的单条「工位号 → 工艺流程图ID」绑定
type StationTemplateStation struct {
StationNo int `json:"stationNo"`
FlowId int `json:"flowId"`
}
// StationTemplate 工位绑定模板(保存/查看均带 processNames=符合的产品工艺名称)
// 2026-11-10:新增 ProductCode 作为产品范围标签。ProcessNames 只作展示,不再当产品标识用
// (名称可改、可重复,套用校验一律以 productCode 为准,与 schema/product_process.go 的 productCode 对齐)。
type StationTemplate struct {
Name string `json:"name"`
ProductCode string `json:"productCode,omitempty"`
Stations []StationTemplateStation `json:"stations"`
ProcessNames []string `json:"processNames"`
}
// stationTemplateKey 第 n 个模板槽位的配置键
func stationTemplateKey(n int) string {
return stationTemplateKeyPrefix + strconv.Itoa(n)
}
type stationTemplateRow struct {
Slot int
StationTemplate
}
// loadStationTemplates 读取全部模板槽位(KeyHasPrefix),只保留 1..20 的合法槽位,按槽位升序。
func (s *Service) loadStationTemplates(ctx context.Context) ([]stationTemplateRow, error) {
rows, err := s.ctx.EntClient.SysConfig.Query().
Where(sysconfig.KeyHasPrefix(stationTemplateKeyPrefix)).All(ctx)
if err != nil {
return nil, err
}
out := make([]stationTemplateRow, 0, len(rows))
for _, r := range rows {
n, e := strconv.Atoi(strings.TrimPrefix(r.Key, stationTemplateKeyPrefix))
if e != nil || n < 1 || n > stationTemplateMaxCount {
continue
}
var t StationTemplate
if json.Unmarshal([]byte(r.Value), &t) != nil {
continue // 坏数据跳过,不阻断其余模板
}
if t.Stations == nil {
t.Stations = []StationTemplateStation{}
}
if t.ProcessNames == nil {
t.ProcessNames = []string{}
}
out = append(out, stationTemplateRow{Slot: n, StationTemplate: t})
}
sort.Slice(out, func(i, j int) bool { return out[i].Slot < out[j].Slot })
return out, nil
}
// ListStationTemplates 全部模板(按槽位升序)
func (s *Service) ListStationTemplates(ctx context.Context) ([]StationTemplate, error) {
rows, err := s.loadStationTemplates(ctx)
if err != nil {
return nil, err
}
out := make([]StationTemplate, 0, len(rows))
for _, r := range rows {
out = append(out, r.StationTemplate)
}
return out, nil
}
// SaveStationTemplate 保存模板:同名覆盖,否则取最小空位序号;上限 20 条;单条 value ≤512 字节。
func (s *Service) SaveStationTemplate(ctx context.Context, t StationTemplate, operator string) error {
t.Name = strings.TrimSpace(t.Name)
if t.Name == "" {
return errors.New("模板名称不能为空")
}
t.ProductCode = strings.TrimSpace(t.ProductCode)
if t.Stations == nil {
t.Stations = []StationTemplateStation{}
}
if t.ProcessNames == nil {
t.ProcessNames = []string{}
}
// 模板内工位唯一:同一工位只能出现一次(station.flow_id 是单值,一个工位只绑一个工艺)。
seen := map[int]bool{}
for _, it := range t.Stations {
if it.StationNo <= 0 {
return errors.New("模板内含无效工位号,请检查后重试")
}
if seen[it.StationNo] {
return errors.New("工位 " + strconv.Itoa(it.StationNo) + " 在模板中重复,一个工位只能绑定一道工艺")
}
seen[it.StationNo] = true
if it.FlowId <= 0 {
return errors.New("工位 " + strconv.Itoa(it.StationNo) + " 未选择绑定工艺")
}
}
b, err := json.Marshal(t)
if err != nil {
return err
}
if len(b) > stationTemplateMaxBytes {
return errors.New("模板内容过长,请减少工位或缩短名称")
}
value := string(b)
rows, err := s.loadStationTemplates(ctx)
if err != nil {
return err
}
for _, r := range rows {
if r.Name == t.Name {
return s.upsertConfig(ctx, stationTemplateKey(r.Slot), value, "工位绑定模板:"+t.Name)
}
}
if len(rows) >= stationTemplateMaxCount {
return errors.New("模板数量已达上限 20 条")
}
used := make(map[int]bool, len(rows))
for _, r := range rows {
used[r.Slot] = true
}
slot := 0
for n := 1; n <= stationTemplateMaxCount; n++ {
if !used[n] {
slot = n
break
}
}
if slot == 0 {
return errors.New("模板数量已达上限 20 条")
}
if err := s.upsertConfig(ctx, stationTemplateKey(slot), value, "工位绑定模板:"+t.Name); err != nil {
return err
}
s.ctx.EventLog.Write(ctx, "station.template.save", "", operator, "sys_config", stationTemplateKey(slot),
"保存工位绑定模板:"+t.Name, map[string]any{"name": t.Name, "stations": len(t.Stations)})
return nil
}
// DeleteStationTemplate 按名称删除模板(不存在=幂等成功)。
func (s *Service) DeleteStationTemplate(ctx context.Context, name, operator string) error {
name = strings.TrimSpace(name)
if name == "" {
return errors.New("模板名称不能为空")
}
rows, err := s.loadStationTemplates(ctx)
if err != nil {
return err
}
for _, r := range rows {
if r.Name != name {
continue
}
key := stationTemplateKey(r.Slot)
row, e := s.ctx.EntClient.SysConfig.Query().Where(sysconfig.Key(key)).Only(ctx)
if e != nil || row == nil {
return nil
}
if e := s.ctx.EntClient.SysConfig.DeleteOneID(row.ID).Exec(ctx); e != nil {
return e
}
s.ctx.EventLog.Write(ctx, "station.template.delete", "", operator, "sys_config", key,
"删除工位绑定模板:"+name, map[string]any{"name": name})
return nil
}
return nil
}
// StationTemplateSkipRow 应用模板时被跳过的工位(收集式,不中断其它工位)
type StationTemplateSkipRow struct {
StationNo int `json:"stationNo"`
Reason string `json:"reason"`
}
// TemplatePrecheckRow 单个工位的套用预检结果(只读,不写库)
// 2026-11-13 拍板:必须带真实产品维度与工序维度——「当前工位绑定的工序」+
// 「该模板支持的成品」,不允许前端只显示横杠。
type TemplatePrecheckRow struct {
StationNo int `json:"stationNo"`
FlowId int `json:"flowId"`
FlowName string `json:"flowName"` // 模板要给该工位绑定的基础工序名
CurrentFlowId int `json:"currentFlowId"` // 该工位当前绑定的基础工序 ID
CurrentFlowName string `json:"currentFlowName"` // 该工位当前绑定的基础工序名
Products []string `json:"products"` // 当前混产模板支持的成品
Blocked bool `json:"blocked"`
Reasons []string `json:"reasons"`
}
// TemplatePrecheckResult 套用前的冲突清单:前端先展示、用户确认后再提交真正的套用。
type TemplatePrecheckResult struct {
Name string `json:"name"`
ProductCode string `json:"productCode"`
TemplateName string `json:"templateName"` // 当前产线在用的混产模板
Products []string `json:"products"` // 该模板支持的成品
Matched []string `json:"matched"`
Rows []TemplatePrecheckRow `json:"rows"`
}
// findStationTemplate 按名称取模板,供套用与预检共用。
func (s *Service) findStationTemplate(ctx context.Context, name string) (*StationTemplate, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, errors.New("模板名称不能为空")
}
rows, err := s.loadStationTemplates(ctx)
if err != nil {
return nil, err
}
for i := range rows {
if rows[i].Name == name {
t := rows[i].StationTemplate
return &t, nil
}
}
return nil, errors.New("工位模板不存在:" + name)
}
// checkTemplateProduct 产品范围校验:模板带 productCode 时目标产品必须一致。
func checkTemplateProduct(tpl *StationTemplate, targetProductCode string) error {
target := strings.TrimSpace(targetProductCode)
if tpl.ProductCode != "" && target != "" && tpl.ProductCode != target {
return fmt.Errorf("该模板适用于产品 %s,当前产品 %s 不适用;请改用对应产品的模板,或在「产品工艺」页为该产品重新生成模板",
tpl.ProductCode, target)
}
return nil
}
// PrecheckStationTemplate 只读预检:逐工位列出「有进行中工单 / 在途指令 / 托盘在位 /
// 工艺流程停用 / 工位不存在」等会被跳过的原因,供前端弹窗逐条展示后再由用户确认提交。
func (s *Service) PrecheckStationTemplate(ctx context.Context, name, targetProductCode string) (*TemplatePrecheckResult, error) {
tpl, err := s.findStationTemplate(ctx, name)
if err != nil {
return nil, err
}
if err := checkTemplateProduct(tpl, targetProductCode); err != nil {
return nil, err
}
// 产品维度:当前在用混产模板圈定的成品(用户要求预检里能看到「该模板支持的成品」)
activeName, products, aErr := s.ActiveMixProducts(ctx)
if aErr != nil {
return nil, aErr
}
res := &TemplatePrecheckResult{
Name: tpl.Name,
ProductCode: tpl.ProductCode,
TemplateName: activeName,
Products: products,
Matched: append([]string{}, tpl.ProcessNames...),
Rows: []TemplatePrecheckRow{},
}
if res.Matched == nil {
res.Matched = []string{}
}
if res.Products == nil {
res.Products = []string{}
}
for _, item := range tpl.Stations {
row := TemplatePrecheckRow{
StationNo: item.StationNo, FlowId: item.FlowId, Reasons: []string{},
Products: products,
}
// 模板要绑定的基础工序名
if item.FlowId > 0 {
flow, fErr := s.ctx.EntClient.ProcessFlow.Get(ctx, item.FlowId)
if fErr != nil {
row.Reasons = append(row.Reasons, "所选工艺流程不存在")
} else {
row.FlowName = flow.Name
if flow.Status != "ACTIVE" {
row.Reasons = append(row.Reasons, "所选工艺流程已停用")
}
}
}
st, e := s.ctx.EntClient.Station.Query().Where(station.StationNo(item.StationNo)).First(ctx)
if e != nil {
row.Reasons = append(row.Reasons, "工位不存在,不会套用")
} else {
// 当前工位绑定的基础工序(能力声明:工位×工序,不是工位×成品)
row.CurrentFlowId = st.FlowId
if st.FlowId > 0 {
if cur, cErr := s.ctx.EntClient.ProcessFlow.Get(ctx, st.FlowId); cErr == nil {
row.CurrentFlowName = cur.Name
} else {
row.CurrentFlowName = "已绑定工序不存在"
}
} else {
row.CurrentFlowName = "未绑定"
}
if item.FlowId != st.FlowId {
if busy, bErr := s.stationHasActiveWorkOrder(ctx, item.StationNo); bErr == nil && busy {
row.Reasons = append(row.Reasons, "有正在进行的工单引用此工位,禁止改绑定")
}
}
if n, _ := s.ctx.EntClient.PlcSendLog.Query().
Where(plcsendlog.Status("SENT"), plcsendlog.StationNo(item.StationNo)).Count(ctx); n > 0 {
row.Reasons = append(row.Reasons, "有在途下发指令,不能改配置")
}
if st.StationType == "LINE" {
if has, pErr := s.ctx.PLC.QueryStationPallet(ctx, item.StationNo); pErr == nil && has {
row.Reasons = append(row.Reasons, "托盘/工件还在工位上,不能改配置")
}
}
}
row.Blocked = len(row.Reasons) > 0
res.Rows = append(res.Rows, row)
}
return res, nil
}
// ApplyStationTemplateResult 应用模板结果
type ApplyStationTemplateResult struct {
Applied []int `json:"applied"`
Skipped []StationTemplateSkipRow `json:"skipped"`
Matched []string `json:"matched"`
ProductCode string `json:"productCode"`
}
// ApplyStationTemplate 逐工位套用模板绑定:复用 SaveStation 的全部守卫(进行中工单 / 在途指令 /
// PLC 托盘在位 / 工艺流程启用),冲突逐条收集到 skipped 并跳过,不中断其它工位。
// matched = 模板承载的产品工艺名称(保存时显示符合哪个产品工艺 / 查看时能看到)。
// 2026-11-10:加产品范围校验——模板带 productCode 时,必须与目标产品工艺一致才允许套用,
// 避免「给 A 产品配的产线」被误套到 B 产品上。老模板(无 productCode)与不传目标产品时兼容放行。
func (s *Service) ApplyStationTemplate(ctx context.Context, name, targetProductCode, operator string) (*ApplyStationTemplateResult, error) {
return s.ApplyStationTemplateWithConfirm(ctx, name, targetProductCode, operator, nil)
}
// ApplyStationTemplateWithConfirm 带「清线确认单」逐项确认的应用入口。
// confirmed 为用户逐项打勾/人工确认放行的 key(见 CheckLineClearance),放行结果写 event_log 留痕。
func (s *Service) ApplyStationTemplateWithConfirm(ctx context.Context, name, targetProductCode, operator string, confirmed []string) (*ApplyStationTemplateResult, error) {
tpl, err := s.findStationTemplate(ctx, name)
if err != nil {
return nil, err
}
if err := checkTemplateProduct(tpl, targetProductCode); err != nil {
return nil, err
}
// 2026-11-13 拍板:同模板内多成品混产切换靠扫码防错,不强制停机清线;
// 引入模板外的新产品必须先过清线门禁(在制品 / 余料 / 托盘 / PLC 未完成任务 / AGV 在途 五项)。
if err := s.GuardLineClearanceWithConfirm(ctx, targetProductCode, confirmed, operator); err != nil {
return nil, err
}
res := &ApplyStationTemplateResult{
Applied: []int{},
Skipped: []StationTemplateSkipRow{},
Matched: append([]string{}, tpl.ProcessNames...),
ProductCode: tpl.ProductCode,
}
if res.Matched == nil {
res.Matched = []string{}
}
for _, item := range tpl.Stations {
// 模板只套用既有工位的绑定关系,不新增工位(与 /stations 的字段口径一致)
st, e := s.ctx.EntClient.Station.Query().Where(station.StationNo(item.StationNo)).First(ctx)
if e != nil {
res.Skipped = append(res.Skipped, StationTemplateSkipRow{
StationNo: item.StationNo, Reason: "工位不存在,未套用绑定",
})
continue
}
flowId := item.FlowId
// 清线门禁已在 ApplyStationTemplate 入口统一执行,逐工位保存时跳过,避免重复检查
if e := s.SaveStation(ctx, StationReq{
StationNo: item.StationNo,
Name: st.Name,
FlowId: &flowId,
SkipClearanceCheck: true,
}, operator); e != nil {
res.Skipped = append(res.Skipped, StationTemplateSkipRow{
StationNo: item.StationNo, Reason: e.Error(),
})
continue
}
res.Applied = append(res.Applied, item.StationNo)
}
return res, nil
}