package logic import ( "context" "errors" "fmt" "math" "sort" "strconv" "strings" "time" "bj_power_mes/ent" "bj_power_mes/ent/callpool" "bj_power_mes/ent/dock" "bj_power_mes/ent/materialrequest" "bj_power_mes/ent/workpiece" "bj_power_mes/ent/workpiecebind" "bj_power_mes/ent/workpieceprocess" ) // adjustInstalledQty 调整工位叫料池「已装量」(2026-11-26 用户铁律「总账=分账之和」)。 // delta>0=装配占用(追溯件绑定/非追溯件报工),delta<0=撤销回补。 // 只改 installed_qty 一列,用 ent 原子增减(AddInstalledQty)避免并发丢更新; // 工位号来自绑定记录的 stationNo(字符串),无效或池子无对应行时静默跳过—— // 记账是追溯的附属,不能因池子缺行卡死装配主流程(无行场景:虚拟位/未启用排产)。 func (s *Service) adjustInstalledQty(ctx context.Context, client *ent.Client, stationNo, materialCode string, delta int) { if delta == 0 || stationNo == "" || materialCode == "" { return } stNo, err := strconv.Atoi(stationNo) if err != nil || stNo <= 0 { return } _, err = client.CallPool.Update(). Where(callpool.StationNo(stNo), callpool.MaterialCode(materialCode)). AddInstalledQty(delta).Save(ctx) if err != nil { s.ctx.EventLog.Write(ctx, "workpiece.bind.installed_fail", "", "system", "call_pool", stationNo, "已装量记账失败", map[string]any{"stationNo": stationNo, "materialCode": materialCode, "delta": delta, "err": err.Error()}) } } // installedPerBind 每条绑定分账对应的已装量(2026-11-26 用户拍板:按实际数量): // SN 件逐颗绑定,每颗计 1(一台绑 ceil(单台用量) 颗合计正好=单台用量); // 批次件只扫 1 个批次号,已装按单台用量整包计(数量自动带出,工人不用管)。 func installedPerBind(snMode int, unitQty float64) int { if snMode == 1 { return 1 } n := int(math.Ceil(unitQty)) if n < 1 { n = 1 } return n } // RemoveBind 撤销一条绑定(仅允许未报工前的误扫纠正;报工后不可撤销) func (s *Service) RemoveBind(ctx context.Context, sn string, flowId int, materialCode, bindValue, operator string) error { if sn == "" || materialCode == "" || bindValue == "" { return errors.New("sn/materialCode/bindValue 必填") } // 该工艺已报工(存在实绩)则不允许撤销 done, err := s.ctx.EntClient.WorkpieceProcess.Query(). Where(workpieceprocess.Sn(sn), workpieceprocess.FlowId(flowId)).Exist(ctx) if err != nil { return err } if done { return errors.New("该工艺已报工,不能撤销装配绑定") } // 先取回待删绑定(拿工位号用于已装量回补) row, err := s.ctx.EntClient.WorkpieceBind.Query(). Where(workpiecebind.Sn(sn), workpiecebind.FlowId(flowId), workpiecebind.MaterialCode(materialCode), workpiecebind.BindValue(bindValue)).Only(ctx) if err != nil { return errors.New("未找到该绑定记录") } n, err := s.ctx.EntClient.WorkpieceBind.Delete(). Where(workpiecebind.Sn(sn), workpiecebind.FlowId(flowId), workpiecebind.MaterialCode(materialCode), workpiecebind.BindValue(bindValue)).Exec(ctx) if err != nil { return err } if n == 0 { return errors.New("未找到该绑定记录") } // 回补已装量(与绑定扣账同口径 installedPerBind:SN颗=1、批次件按单台用量整包回补) unitQty := 1.0 if _, wo, werr := s.workpieceProduct(ctx, s.ctx.EntClient, sn); werr == nil && wo != nil { if dm, derr := s.MaterialsByFlowForWO(ctx, s.ctx.EntClient, wo, []int{flowId}); derr == nil { for _, d := range dm[flowId] { if d != nil && d.MaterialCode == materialCode { unitQty = d.UnitQty break } } } } s.adjustInstalledQty(ctx, s.ctx.EntClient, row.StationNo, materialCode, -installedPerBind(row.SnMode, unitQty)) s.ctx.EventLog.Write(ctx, "workpiece.bind.remove", "", operator, "workpiece_bind", sn, "撤销装配绑定", map[string]any{"flowId": flowId, "materialCode": materialCode, "bindValue": bindValue, "stationNo": row.StationNo}) return nil } // BindWorkpiece 独立绑定接口:工人在工位扫一件绑一件(报工前的逐条扫码/防错), // 与报工携带 binds 等价,落库后立即返回结果供前端即时反馈(SN 重复/料不匹配当场报错)。 func (s *Service) BindWorkpiece(ctx context.Context, sn, orderNo string, flowId int, stationNo string, operator string, items []BindItemReq) (map[string]any, error) { bound, err := s.applyBinds(ctx, s.ctx.EntClient, sn, orderNo, flowId, stationNo, operator, items) if err != nil { return nil, err } if bound > 0 { s.ctx.EventLog.Write(ctx, "workpiece.bind", orderNo, operator, "workpiece_bind", sn, "装机绑定物料", map[string]any{"flowId": flowId, "count": bound}) s.notifyDashboard() } // 返回最新面板,前端据此刷新齐套状态 panel, err := s.StationBindPanelData(ctx, sn, flowId) if err != nil { return map[string]any{"bound": bound}, nil } return map[string]any{"bound": bound, "panel": panel}, nil } // ---------- 装机绑定(工位装配物料追溯 + 工艺物料清单强校验) ---------- // 业务口径(2026-11-06 拍板):物料本身不绑工单——物料/批次是工位共享的,装到 SN 工件上 // 才通过工件关联到工单;绑定记录一律挂 sn,不挂工位账。 // BindItemReq 单条装机绑定请求(报工时随 steps 一并提交) type BindItemReq struct { MaterialCode string `json:"materialCode"` BindValue string `json:"bindValue"` // 序列号=否=批次号;序列号=是=SN } // bindTarget 某工艺要求装配的物料定义(源自来源产品工艺分账) type bindTarget struct { MaterialCode string MaterialName string Spec string Unit string SnMode int // 是否逐件SN管理:1 序列号=是(录SN) / 2 序列号=否 UnitQty float64 } // workpieceProduct 解析工件所属产品编码与工单(sn → workpiece → workOrder) func (s *Service) workpieceProduct(ctx context.Context, client *ent.Client, sn string) (*ent.Workpiece, *ent.WorkOrder, error) { wp, err := client.Workpiece.Query().Where(workpiece.Sn(sn)).First(ctx) if err != nil { return nil, nil, errors.New("工件未进线登记") } if wp.WorkOrderId <= 0 { return wp, nil, errors.New("工件未关联工单") } wo, err := client.WorkOrder.Get(ctx, wp.WorkOrderId) if err != nil || wo == nil { return wp, nil, errors.New("工件所属工单不存在") } return wp, wo, nil } // stationBindTargets 取某工艺(flowId)要求装配的物料清单(2026-11-13 总分制; // 2026-11-18 起纯分账口径:按工件所属工单来源产品工艺分账取数,无分账则无绑定目标)。 func (s *Service) stationBindTargets(ctx context.Context, client *ent.Client, sn string, flowId int) ([]bindTarget, error) { _, wo, err := s.workpieceProduct(ctx, client, sn) if err != nil { return nil, err } fmByFlow, err := s.MaterialsByFlowForWO(ctx, client, wo, []int{flowId}) if err != nil { return nil, err } out := make([]bindTarget, 0, len(fmByFlow[flowId])) for _, it := range fmByFlow[flowId] { // 追溯绑定开关(2026-11-26 拍板):产品总账未勾选「追溯绑定」的物料(C类标准件)不进 // 绑定清单/齐套校验——绑定是关键件的追溯动作,不是全物料的记账负担。绑定方式由 // 物料档案 sn_mode 自动判定(序列号=是逐件扫SN / 序列号=否记批次),无需再选档位。 if !it.TraceBind { continue } out = append(out, bindTarget{ MaterialCode: it.MaterialCode, MaterialName: it.MaterialName, Spec: it.Spec, Unit: it.Unit, SnMode: it.SnMode, UnitQty: it.UnitQty, }) } return out, nil } // deliveredOutboundNos 本工位「已签收叫料单」对应的 WMS 出库单号集合(SN 绑定的合法来源范围)。 // 签收=PREPARED→DONE,代表料确实送到本工位;叫料单 outboundNo 可能多个逗号分隔。 func (s *Service) deliveredOutboundNos(ctx context.Context, client *ent.Client, stationNo string) []string { n, err := strconv.Atoi(strings.TrimSpace(stationNo)) if err != nil || n <= 0 { return nil } rows, err := client.MaterialRequest.Query(). Where(materialrequest.StationNo(n), materialrequest.StatusEQ("DONE")).All(ctx) if err != nil { return nil } set := map[string]bool{} out := make([]string, 0) for _, mr := range rows { for _, no := range strings.Split(mr.OutboundNo, ",") { no = strings.TrimSpace(no) if no != "" && !set[no] { set[no] = true out = append(out, no) } } } return out } // bindNeed 单个物料在本工件上允许绑定的最大数量(与齐套判定同口径): // 序列号=是 按单台用量向上取整(至少1颗);序列号=否 只认1个批次号。 func bindNeed(snMode int, unitQty float64) int { if snMode == 1 { n := int(math.Ceil(unitQty)) if n < 1 { n = 1 } return n } return 1 } // applyBinds 报工时应用装机绑定(落库 + 防错校验): // ① 料必须在该工件来源产品工艺的分账中; // ② 电气件 SN 全局防重:已被其他工件绑定则拒绝(防错拿/防重复装机); // ③ 同一工件同一料同一绑定值幂等(重复扫码不报错,静默去重); // ④ 绑定数量卡死:本工件该物料已绑数达到需要量后再绑直接拒绝(2026-11-26 用户拍板)。 // 返回绑定成功条数。 func (s *Service) applyBinds(ctx context.Context, client *ent.Client, sn, orderNo string, flowId int, stationNo string, operator string, items []BindItemReq) (int, error) { if len(items) == 0 { return 0, nil } wp, _, err := s.workpieceProduct(ctx, client, sn) if err != nil { return 0, err } if wp.Status == "DONE" || wp.Status == "SCRAPPED" { return 0, errors.New("已完工/报废工件不能再绑定物料") } // 本工艺物料清单全集:materialCode → 定义(校验料合法性 + 取物料快照) fmMap := map[string]*MaterialDemand{} targets, err := s.stationBindTargets(ctx, client, sn, flowId) if err != nil { return 0, err } for i := range targets { fmMap[targets[i].MaterialCode] = &MaterialDemand{ MaterialCode: targets[i].MaterialCode, MaterialName: targets[i].MaterialName, Spec: targets[i].Spec, Unit: targets[i].Unit, SnMode: targets[i].SnMode, UnitQty: targets[i].UnitQty, } } // 绑定值校验(2026-11-26 用户定案): // 序列号=是 → SN 必须是「发到本工位」的料:本工位已签收叫料单对应出库明细里的 SN; // 序列号=否 → 批次件放开,信任现场实物标签,不校验。 // 按物料分组一次校验;WMS 不可达 → 放行并写 event_log 留痕(不因 WMS 故障卡产线装配)。 outNos := s.deliveredOutboundNos(ctx, client, stationNo) chk := map[string][]string{} // materialCode → SN 列表(只有序列号=是的进这里) for _, it := range items { mc := strings.TrimSpace(it.MaterialCode) bv := strings.TrimSpace(it.BindValue) fm, ok := fmMap[mc] if !ok || bv == "" { continue // 留给下方逐条校验报错 } if fm.SnMode == 1 { chk[mc] = append(chk[mc], bv) } } for mc, vals := range chk { missing, err := s.ctx.Wms.BindValuesMissing(ctx, mc, 1, vals, outNos) if err != nil { // WMS 不可达:fail-open + 留痕。校验能力依赖 WMS,但装配不能被 WMS 故障卡死。 s.ctx.EventLog.Write(ctx, "workpiece.bind.check_skip", sn, operator, "workpiece_bind", sn, fmt.Sprintf("SN 到料校验跳过(WMS 不可达):%s %v", mc, vals), map[string]any{"sn": sn, "materialCode": mc, "err": err.Error()}) continue } if len(missing) > 0 { return 0, fmt.Errorf("SN 校验不通过:%s 不是发到本工位的物料,不能用在本工件上;请核对实物是否本工位叫料,错拿请退回库房", strings.Join(missing, "、")) } } // 本工件各物料已绑数(数量卡死用,一次查全,循环内增量维护) have := map[string]int{} existingRows, _ := client.WorkpieceBind.Query(). Where(workpiecebind.Sn(sn)).All(ctx) for _, rb := range existingRows { have[rb.MaterialCode]++ } bound := 0 for _, it := range items { mc := strings.TrimSpace(it.MaterialCode) bv := strings.TrimSpace(it.BindValue) if mc == "" || bv == "" { return bound, errors.New("物料编码与绑定值不能为空") } fm, ok := fmMap[mc] if !ok { return bound, fmt.Errorf("物料 %s 不在本工艺的追溯绑定清单(总账未勾选「追溯绑定」或未分配到该工艺),不能绑定", mc) } snMode := fm.SnMode if snMode != 1 { snMode = 2 } // 同工件同料同值幂等 exists, _ := client.WorkpieceBind.Query(). Where(workpiecebind.Sn(sn), workpiecebind.MaterialCode(mc), workpiecebind.BindValue(bv)).Exist(ctx) if exists { continue } // 数量卡死:已达需要量仍未绑过这个新值 → 拒绝(防超装多算追溯) need := bindNeed(snMode, fm.UnitQty) if have[mc] >= need { kind := "批次号" if snMode == 1 { kind = fmt.Sprintf("%d颗SN", need) } return bound, fmt.Errorf("物料 %s(%s)本工件只需绑定 %s,已绑满 %d 个,不能再绑;如装错请先在追溯明细移除后再绑", mc, fm.MaterialName, kind, have[mc]) } have[mc]++ // 序列号=是 SN 全局防重 if snMode == 1 { other, _ := client.WorkpieceBind.Query(). Where(workpiecebind.BindValue(bv), workpiecebind.BindType("SN"), workpiecebind.SnNEQ(sn)).First(ctx) if other != nil { return bound, fmt.Errorf("序列号=是SN %s 已绑定到工件 %s(工艺「%s」),不能重复装机", bv, other.Sn, s.flowNameById(ctx, other.FlowId)) } } bindType := "BATCH" if snMode == 1 { bindType = "SN" } if err := client.WorkpieceBind.Create(). SetSn(sn).SetOrderNo(orderNo).SetFlowId(flowId). SetStationNo(stationNo).SetMaterialCode(mc).SetMaterialName(fm.MaterialName). SetSpec(fm.Spec).SetUnit(fm.Unit).SetSnMode(snMode). SetBindValue(bv).SetBindType(bindType).SetOperator(operator). Exec(ctx); err != nil { return bound, err } // 已装量扣账(总账=分账之和,按实际数量):SN件每颗+1;批次件扫1个批次号按单台用量整包+。 // 失败不卡装配,仅留痕。 s.adjustInstalledQty(ctx, client, stationNo, mc, installedPerBind(snMode, fm.UnitQty)) bound++ } return bound, nil } // stationHasEnabledLineDock 判断工位是否为「实体工位」:存在启用的 line 类型接驳台。 // 虚拟/线下位(如末端下料检测位 11/12)无接驳台、不承载 AGV 物料物流, // 因此不采集装配物料绑定,报工/完工/追溯/终端面板一律放行(2026-11-08 B2 拍板)。 func (s *Service) stationHasEnabledLineDock(ctx context.Context, client *ent.Client, stationNo int) bool { if stationNo <= 0 { return false } n, err := client.Dock.Query().Where( dock.StationNo(stationNo), dock.DockTypeEQ("line"), dock.StatusEQ("ENABLED")).Count(ctx) return err == nil && n > 0 } const bindSkipReason = "该工艺未采集绑定(工位无接驳台)" // BindNotCollected 追溯页:因候选工位无接驳台而未采集装配绑定的工艺。 type BindNotCollected struct { FlowId int `json:"flowId"` FlowName string `json:"flowName"` StationNo int `json:"stationNo"` Reason string `json:"reason"` } // flowBindGate 按工单工艺组合判定每道工艺是否需采集装配绑定: // 多工位同工艺=并行候选工位,任一候选工位有启用 line 接驳台即需采集; // 该工艺全部候选均无接驳台(虚拟/线下位)时不采集,并返回追溯用未采集清单。 func (s *Service) flowBindGate(ctx context.Context, client *ent.Client, wo *ent.WorkOrder) (map[int]bool, []BindNotCollected) { items, _ := RouteStationsFromWO(ctx, client, wo) required := map[int]bool{} seen := map[int]bool{} skipped := []BindNotCollected{} for _, it := range items { if s.stationHasEnabledLineDock(ctx, client, it.StationNo) { required[it.FlowId] = true } } for _, it := range items { if seen[it.FlowId] || required[it.FlowId] { continue } seen[it.FlowId] = true skipped = append(skipped, BindNotCollected{ FlowId: it.FlowId, FlowName: s.flowNameById(ctx, it.FlowId), StationNo: it.StationNo, Reason: bindSkipReason, }) } return required, skipped } // validateStationBinds 校验某工件在某工艺的装配物料是否绑齐(齐套强校验核心): // 返回缺料明细(空串=齐套)。判定:电气件(SN) 绑定的不同SN数 ≥ 单台用量;结构件(批次) 至少绑定1个批次号。 // 该工艺未配置物料清单,或报工工位无启用产线接驳台(不采集绑定)时放行。 func (s *Service) validateStationBinds(ctx context.Context, client *ent.Client, sn string, flowId int, requireBinds bool) (string, error) { if _, _, err := s.workpieceProduct(ctx, client, sn); err != nil { return "", err } if !requireBinds { return "", nil // 工位无启用产线接驳台(虚拟/线下位)→ 不采集绑定,放行 } targets, err := s.stationBindTargets(ctx, client, sn, flowId) if err != nil { return "", err } if len(targets) == 0 { return "", nil // 该工艺未配置装配物料 → 不校验 } // 已绑定明细:按 物料编码 → 绑定值集合 binds, _ := client.WorkpieceBind.Query(). Where(workpiecebind.Sn(sn), workpiecebind.FlowId(flowId)).All(ctx) boundMap := map[string]map[string]bool{} for _, b := range binds { if boundMap[b.MaterialCode] == nil { boundMap[b.MaterialCode] = map[string]bool{} } boundMap[b.MaterialCode][b.BindValue] = true } missing := []string{} for _, t := range targets { set := boundMap[t.MaterialCode] boundCount := len(set) // 需绑量与 applyBinds 数量卡死同口径(bindNeed):SN件=ceil(单台用量)、批次件=1个批次号。 // 2026-11-26 审计修正:原 ceil(UnitQty) 不分模式,批次件用量>1 时与卡死上限矛盾 → 死锁绑不齐。 need := bindNeed(t.SnMode, t.UnitQty) if t.SnMode == 1 { // 序列号=是 SN:需绑满单台用量 if boundCount < need { missing = append(missing, fmt.Sprintf("%s(%s):需绑定%d颗SN,已绑%d颗", t.MaterialCode, t.MaterialName, need, boundCount)) } } else { // 序列号=否:至少绑定1个批次号 if boundCount < 1 { missing = append(missing, fmt.Sprintf("%s(%s):未绑定批次号", t.MaterialCode, t.MaterialName)) } } } if len(missing) == 0 { return "", nil } return "装配物料未绑齐:" + strings.Join(missing, ";"), nil } // validateAllFlows 完工兜底:按工单工艺组合(唯一路线源头)逐工艺校验装配物料齐套。 // 同一工艺绑多工位时只校验一次(按 FlowId 去重);该工艺候选工位全无启用 line 接驳台 // (虚拟/线下位,未采集绑定)时跳过,不再把「没绑」误判成缺料。 func (s *Service) validateAllFlows(ctx context.Context, client *ent.Client, sn string, wo *ent.WorkOrder) (string, error) { if _, _, err := s.workpieceProduct(ctx, client, sn); err != nil { return "", err } items, _ := RouteStationsFromWO(ctx, client, wo) required, _ := s.flowBindGate(ctx, client, wo) missing := []string{} seen := map[int]bool{} for _, it := range items { if seen[it.FlowId] { continue } seen[it.FlowId] = true if !required[it.FlowId] { continue // 该工艺全部候选工位无接驳台 → 未采集绑定,不参与齐套 } msg, err := s.validateStationBinds(ctx, client, sn, it.FlowId, true) if err != nil { return "", err } if msg != "" { missing = append(missing, fmt.Sprintf("工艺「%s」:%s", s.flowNameById(ctx, it.FlowId), msg)) } } if len(missing) == 0 { return "", nil } return strings.Join(missing, ";"), nil } // InspectionBindItem 检验记录/检验单附带的装配物料绑定明细条目 // (客户需求:每个工位对精密器件扫码录入,记录在检验单上) type InspectionBindItem struct { Sn string `json:"sn"` FlowName string `json:"flowName"` // 装配工艺名 StationNo string `json:"stationNo"` // 绑定工位 MaterialCode string `json:"materialCode"` MaterialName string `json:"materialName"` Spec string `json:"spec"` BindValue string `json:"bindValue"` // 序列号=是=SN / 序列号=否=批次号 BindMode string `json:"bindMode"` // 序列号=是 / 序列号=否 Operator string `json:"operator"` CreatedAt time.Time `json:"createdAt"` } // inspectionBindItems 按 SN 查跨工艺全部装配绑定明细(供检验记录详情/检验单附明细区;无绑定返回空不报错) func (s *Service) inspectionBindItems(ctx context.Context, sn string) []InspectionBindItem { if sn == "" { return nil } binds, err := s.ctx.EntClient.WorkpieceBind.Query(). Where(workpiecebind.Sn(sn)). Order(ent.Asc(workpiecebind.FieldFlowId), ent.Asc(workpiecebind.FieldID)). All(ctx) if err != nil || len(binds) == 0 { return nil } out := make([]InspectionBindItem, 0, len(binds)) for _, b := range binds { mode := "序列号=否" if b.SnMode == 1 { mode = "序列号=是" } out = append(out, InspectionBindItem{ Sn: b.Sn, FlowName: s.flowNameById(ctx, b.FlowId), StationNo: b.StationNo, MaterialCode: b.MaterialCode, MaterialName: b.MaterialName, Spec: b.Spec, BindValue: b.BindValue, BindMode: mode, Operator: b.Operator, CreatedAt: b.CreatedAt, }) } return out } // InspectionBinds 检验记录详情:按 SN 返回装配物料绑定明细(跨工艺,标注工艺/工位) func (s *Service) InspectionBinds(ctx context.Context, sn string) []InspectionBindItem { return s.inspectionBindItems(ctx, sn) } // ListWorkpieceBinds 查询工件的装机绑定明细 func (s *Service) ListWorkpieceBinds(ctx context.Context, sn string) ([]*ent.WorkpieceBind, error) { q := s.ctx.EntClient.WorkpieceBind.Query() if sn != "" { q = q.Where(workpiecebind.Sn(sn)) } return q.Order(ent.Asc(workpiecebind.FieldFlowId), ent.Asc(workpiecebind.FieldID)).Limit(2000).All(ctx) } // BindTraceVO 追溯页:装机绑定明细 + 每工艺齐套状态 + 装机物料明细 type BindTraceVO struct { Binds []*ent.WorkpieceBind `json:"binds"` Complete bool `json:"complete"` Missing string `json:"missing"` Materials []BindNode `json:"materials"` // 装机物料明细(按工单工艺组合×工艺物料清单平铺一层,无多级树;2026-11-24 由兼容名 bomTree 改名) NotCollected []BindNotCollected `json:"notCollected"` // 无接驳台工艺:未采集绑定原因 } // BindNode 追溯用的装机物料明细节点(平铺一层;多级 BOM 已于 2026-09-23 退役,无下级展开) type BindNode struct { MaterialCode string `json:"materialCode"` MaterialName string `json:"materialName"` Spec string `json:"spec"` Unit string `json:"unit"` SnMode int `json:"snMode"` // 1 序列号=是 / 2 序列号=否 Qty float64 `json:"qty"` // 折算到单台成品的用量 } // BuildBindTrace 组装某工件装机绑定追溯(含全工艺齐套状态 + 物料组成树,供产品档案/追溯页展示) func (s *Service) BuildBindTrace(ctx context.Context, sn string) (*BindTraceVO, error) { binds, err := s.ListWorkpieceBinds(ctx, sn) if err != nil { return nil, err } _, wo, err := s.workpieceProduct(ctx, s.ctx.EntClient, sn) if err != nil { return nil, err } missing, err := s.validateAllFlows(ctx, s.ctx.EntClient, sn, wo) if err != nil { return nil, err } // 无接驳台工艺未采集绑定:追溯页显式给出原因,避免与「已绑齐」的空列表混淆 _, skipped := s.flowBindGate(ctx, s.ctx.EntClient, wo) // 物料组成:按工单工艺组合×工艺物料清单平铺一层(物料清单已删除,无多级树) var tree []BindNode for _, it := range s.WorkOrderUnitUsage(ctx, wo) { tree = append(tree, BindNode{ MaterialCode: it.MaterialCode, MaterialName: it.MaterialName, Spec: it.Spec, Unit: it.Unit, SnMode: it.SnMode, Qty: it.UnitQty, }) } return &BindTraceVO{Binds: binds, Complete: missing == "", Missing: missing, Materials: tree, NotCollected: skipped}, nil } // BindRequiredItem 应绑清单条目(工位终端展示引导 + 前端齐套计算) type BindRequiredItem struct { MaterialCode string `json:"materialCode"` MaterialName string `json:"materialName"` Spec string `json:"spec"` Unit string `json:"unit"` SnMode int `json:"snMode"` // 1 序列号=是(录SN) / 2 序列号=否 UnitQty float64 `json:"unitQty"` Need int `json:"need"` // 需绑数量 Bound []string `json:"bound"` // 已绑定的批次号/SN 列表 BoundCount int `json:"boundCount"` Complete bool `json:"complete"` } // StationBindPanel 某工件在某工艺的装配绑定面板数据(应绑清单 + 已绑情况) type StationBindPanel struct { Enabled bool `json:"enabled"` // 本工艺是否启用装配物料绑定 Required []BindRequiredItem `json:"required"` Complete bool `json:"complete"` Missing string `json:"missing"` StationNo int `json:"stationNo"` // 工位号(从工单工艺组合该 flow 条目派生) FlowId int `json:"flowId"` LastBinds []*ent.WorkpieceBind `json:"lastBinds"` // 最近10条绑定记录 StationNames map[int]string `json:"-"` HasLineDock bool `json:"hasLineDock"` // 候选工位是否有启用 line 接驳台 SkipReason string `json:"skipReason"` // 无需采集绑定的原因 } // StationBindPanelData 供工位终端在报工前拉取:本工件本工艺该装什么、已装什么 // 业务口径(2026-11-06 拍板):装配物料绑定是「当前工件齐套视图」,不是工位账—— // 与工位账(叫料池四数/物料明细)并存、互不替代;齐套看的是这一台 SN 绑没绑齐。 func (s *Service) StationBindPanelData(ctx context.Context, sn string, flowId int) (*StationBindPanel, error) { _, wo, err := s.workpieceProduct(ctx, s.ctx.EntClient, sn) if err != nil { return nil, err } targets, err := s.stationBindTargets(ctx, s.ctx.EntClient, sn, flowId) if err != nil { return nil, err } // 工位号从工单工艺组合该 flow 的条目派生(组合是唯一路线源头) stationNo := 0 if items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, wo); len(items) > 0 { for _, it := range items { if it.FlowId == flowId { stationNo = it.StationNo break } } } // B2(2026-11-08):候选工位无启用 line 接驳台 → 该工艺不采集装配绑定, // 面板不展示「需绑批次/需绑SN」,齐套恒为 true,前端不会拦截报工。 hasDock := s.stationHasEnabledLineDock(ctx, s.ctx.EntClient, stationNo) panel := &StationBindPanel{ Enabled: len(targets) > 0 && hasDock, FlowId: flowId, StationNo: stationNo, HasLineDock: hasDock, Required: []BindRequiredItem{}, } if !hasDock { panel.SkipReason = bindSkipReason } // 全量绑定(齐套判定必须按全量统计,不能用 limit 截断,否则多料/多SN会误判缺料) allBinds, _ := s.ctx.EntClient.WorkpieceBind.Query(). Where(workpiecebind.Sn(sn), workpiecebind.FlowId(flowId)).All(ctx) boundMap := map[string]map[string]bool{} for _, b := range allBinds { if boundMap[b.MaterialCode] == nil { boundMap[b.MaterialCode] = map[string]bool{} } boundMap[b.MaterialCode][b.BindValue] = true } for _, t := range targets { if !hasDock { break // 无接驳台工位不展示「需绑批次 / 需绑SN」应绑清单 } // 需绑量与卡死/报工齐套同口径(bindNeed):批次件=1,避免面板显示"需绑2"实际绑1就齐的误导 need := bindNeed(t.SnMode, t.UnitQty) bound := make([]string, 0, len(boundMap[t.MaterialCode])) for v := range boundMap[t.MaterialCode] { bound = append(bound, v) } sort.Strings(bound) item := BindRequiredItem{ MaterialCode: t.MaterialCode, MaterialName: t.MaterialName, Spec: t.Spec, Unit: t.Unit, SnMode: t.SnMode, UnitQty: t.UnitQty, Need: need, Bound: bound, BoundCount: len(bound), } if t.SnMode == 1 { item.Complete = len(bound) >= need } else { item.Complete = len(bound) >= 1 } panel.Required = append(panel.Required, item) } allComplete := true for _, r := range panel.Required { if !r.Complete { allComplete = false break } } panel.Complete = allComplete if !allComplete && hasDock { panel.Missing, _ = s.validateStationBinds(ctx, s.ctx.EntClient, sn, flowId, true) } // 最近绑定(仅展示用) sort.Slice(allBinds, func(i, j int) bool { return allBinds[i].ID > allBinds[j].ID }) if len(allBinds) > 10 { allBinds = allBinds[:10] } panel.LastBinds = allBinds return panel, nil }