feat: 两库对等物料管理及产品工号贯通全流程
- 新增 MES 本地物料表及双向同步接口,WMS 物料变更自动同步 - 全流程新增产品工号字段,贯通入库/库存/出库/检验环节 - 工单管理支持多工单混产,移除单工单互斥限制 - 新增批次号/SN 字段支持质量检验联动 WMS 库存处置 - 修复权限规则,仅内置管理员账号不允许修改删除 - 工位终端新增 SN 扫码自动切换所属工单功能
This commit is contained in:
@@ -350,14 +350,12 @@ func (s *Service) CreateUser(ctx context.Context, req UserReq) error {
|
||||
}
|
||||
|
||||
func (s *Service) UpdateUser(ctx context.Context, req UserReq) error {
|
||||
// 内置管理员账号(SUPER_ADMIN)不允许通过管理接口修改(含禁用/改角色/改密码等)
|
||||
// 仅内置管理员账号(username=admin)不允许通过管理接口修改;其余账号(含 SUPER_ADMIN 角色的用户)均可修改。
|
||||
// 2026-09-28 修正:原按角色码 SUPER_ADMIN 锁定的规则过宽,导致普通新建账号被误锁、无法编辑/删除/改状态。
|
||||
if usr, e := s.ctx.EntClient.User.Get(ctx, req.Id); e == nil {
|
||||
if usr.Username == "admin" {
|
||||
return errors.New("系统内置管理员账号不允许修改")
|
||||
}
|
||||
if rl, e2 := s.ctx.EntClient.Role.Get(ctx, usr.RoleId); e2 == nil && rl.Code == "SUPER_ADMIN" {
|
||||
return errors.New("系统内置管理员账号不允许修改")
|
||||
}
|
||||
}
|
||||
u := s.ctx.EntClient.User.UpdateOneID(req.Id).SetRoleId(req.RoleId).SetName(req.Name).
|
||||
SetCanLoginWorkstation(req.CanLoginWorkstation)
|
||||
@@ -421,13 +419,11 @@ func (s *Service) DeleteUser(ctx context.Context, id int) error {
|
||||
if err != nil {
|
||||
return errors.New("用户不存在")
|
||||
}
|
||||
// 内置管理员账号(SUPER_ADMIN)不允许删除
|
||||
// 仅内置管理员账号(username=admin)不允许删除;其余账号(含 SUPER_ADMIN 角色的用户)均可删除。
|
||||
// 2026-09-28 修正:原按角色码 SUPER_ADMIN 锁定的规则过宽,导致普通新建账号被误锁、无法删除。
|
||||
if usr.Username == "admin" {
|
||||
return errors.New("系统内置管理员账号不允许删除")
|
||||
}
|
||||
if rl, e2 := s.ctx.EntClient.Role.Get(ctx, usr.RoleId); e2 == nil && rl.Code == "SUPER_ADMIN" {
|
||||
return errors.New("系统内置管理员账号不允许删除")
|
||||
}
|
||||
return s.ctx.EntClient.User.DeleteOneID(id).Exec(ctx)
|
||||
}
|
||||
|
||||
@@ -444,7 +440,7 @@ type UserVO struct {
|
||||
}
|
||||
|
||||
func (s *Service) ListUsers(ctx context.Context) ([]UserVO, error) {
|
||||
usrs, err := s.ctx.EntClient.User.Query().Order(ent.Asc(user.FieldID)).All(ctx)
|
||||
usrs, err := s.ctx.EntClient.User.Query().Order(ent.Desc(user.FieldCreatedAt)).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -367,7 +367,7 @@ func (s *Service) SetDailyPlanStatus(ctx context.Context, id int, target, operat
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------- 自动排产(引导式) ----------
|
||||
// ---------- 排产预览/确认(引导式,M9 定稿 2026-09-29:预览逐日可调、总数据必须对上) ----------
|
||||
|
||||
// DateSegment 日期区间 [start, end](含两端),yyyy-MM-dd
|
||||
type DateSegment struct {
|
||||
@@ -453,101 +453,189 @@ func distributeQty(total, days int, mode string, dailyQty int) []int {
|
||||
return out
|
||||
}
|
||||
|
||||
// AutoSchedule 引导式自动排产:生成多条 daily_plan(status=PENDING,未启用),供人工确认后启用。
|
||||
// 排产合计(含已有排产)≤ 未开工数量;已进线未完工工件跨天继续、不被重排冲掉。
|
||||
func (s *Service) AutoSchedule(ctx context.Context, req AutoScheduleReq, operator string) error {
|
||||
if req.OrderNo == "" {
|
||||
return errors.New("工单号必填")
|
||||
}
|
||||
if req.Mode != "AVG" && req.Mode != "FIXED" {
|
||||
return errors.New("排产模式仅支持 AVG(平均分摊) / FIXED(固定日产)")
|
||||
}
|
||||
dates, err := expandDates(req.Segments)
|
||||
// autoScheduleGuard 排产公共校验:工单存在/状态/工艺组合一致;
|
||||
// 返回工单、应排总数(quota=未开工数量−既有排产合计)、既有排产按日期索引。
|
||||
func (s *Service) autoScheduleGuard(ctx context.Context, orderNo string) (*ent.WorkOrder, int, map[string]*ent.DailyPlan, error) {
|
||||
wo, err := s.ctx.EntClient.WorkOrder.Query().Where(workorder.WorkOrderNo(orderNo)).First(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(dates) == 0 {
|
||||
return errors.New("请至少选择一个日期区间")
|
||||
}
|
||||
wo, err := s.ctx.EntClient.WorkOrder.Query().Where(workorder.WorkOrderNo(req.OrderNo)).First(ctx)
|
||||
if err != nil {
|
||||
return errors.New("工单不存在")
|
||||
return nil, 0, nil, errors.New("工单不存在")
|
||||
}
|
||||
if wo.Status == "DONE" || wo.Status == "CANCELLED" {
|
||||
return errors.New("该工单已完成或已取消,不能排产")
|
||||
return nil, 0, nil, errors.New("该工单已完成或已取消,不能排产")
|
||||
}
|
||||
if wo.Status == "PAUSED" {
|
||||
return errors.New("该工单已暂停,恢复执行前不能排产")
|
||||
return nil, 0, nil, errors.New("该工单已暂停,恢复执行前不能排产")
|
||||
}
|
||||
// 自动排产继承工单工艺组合(唯一路线源头,不可改):先校验组合与工位绑定一致
|
||||
// 排产继承工单工艺组合(唯一路线源头,不可改):先校验组合与工位绑定一致
|
||||
if err := s.ValidateWOCombinationForSchedule(ctx, wo); err != nil {
|
||||
return err
|
||||
return nil, 0, nil, err
|
||||
}
|
||||
remain, err := s.unscheduledQty(ctx, wo)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, 0, nil, err
|
||||
}
|
||||
// 已有排产(非本次区间内的)已占用部分未开工数量,本次可排上限 = remain − 既有排产合计
|
||||
exist, _ := s.ctx.EntClient.DailyPlan.Query().Where(dailyplan.OrderNo(req.OrderNo)).All(ctx)
|
||||
exist, _ := s.ctx.EntClient.DailyPlan.Query().Where(dailyplan.OrderNo(orderNo)).All(ctx)
|
||||
byDate := make(map[string]*ent.DailyPlan, len(exist))
|
||||
existTotal := 0
|
||||
for _, p := range exist {
|
||||
byDate[p.PlanDate] = p
|
||||
existTotal += p.PlanQty
|
||||
}
|
||||
quota := remain - existTotal
|
||||
if quota < 0 {
|
||||
quota = 0
|
||||
}
|
||||
return wo, quota, byDate, nil
|
||||
}
|
||||
|
||||
days := len(dates)
|
||||
var planQty []int
|
||||
switch req.Mode {
|
||||
case "FIXED":
|
||||
if req.DailyQty <= 0 {
|
||||
return errors.New("固定日产模式需填写每日产量(>0)")
|
||||
}
|
||||
if quota > req.DailyQty*days {
|
||||
return errors.New("固定日产×天数超过未开工数量,无法排产")
|
||||
}
|
||||
planQty = distributeQty(quota, days, "FIXED", req.DailyQty)
|
||||
case "AVG", "":
|
||||
planQty = distributeQty(quota, days, "AVG", 0)
|
||||
}
|
||||
sum := 0
|
||||
for _, q := range planQty {
|
||||
sum += q
|
||||
}
|
||||
if sum == 0 {
|
||||
return errors.New("未开工数量为 0,无需排产(已在产/已完工)")
|
||||
}
|
||||
// AutoSchedulePreviewRow 排产预览行:Editable=false 的日已执行中/已完成,数量锁定不可调
|
||||
type AutoSchedulePreviewRow struct {
|
||||
Date string `json:"date"`
|
||||
Qty int `json:"qty"`
|
||||
Editable bool `json:"editable"`
|
||||
ExistStatus string `json:"existStatus"` // 该日既有排产状态;""=无既有排产
|
||||
}
|
||||
|
||||
// 生成/更新排产(本次区间内的日期覆盖式写入,status=PENDING 待人工启用;执行中/已完工的日计划受保护不被覆盖)
|
||||
for i, ds := range dates {
|
||||
q := planQty[i]
|
||||
if q <= 0 {
|
||||
// AutoSchedulePreview 排产预览结果:可调行(Editable=true)数量合计 == Quota,确认时原样提交
|
||||
type AutoSchedulePreview struct {
|
||||
OrderNo string `json:"orderNo"`
|
||||
Quota int `json:"quota"` // 应排总数 = 未开工数量 − 既有排产合计
|
||||
Rows []AutoSchedulePreviewRow `json:"rows"`
|
||||
}
|
||||
|
||||
// AutoSchedulePreview 排产预览(不落库,M9 定稿 2026-09-29):按模式给出初始逐日数量,
|
||||
// 用户在预览中逐日自行调节(前松/中紧/后松等任意节奏),确认走 AutoScheduleApply。
|
||||
// 已执行中/已完成的日期原样展示并锁定(其数量已计入既有排产、不占本次 quota)。
|
||||
func (s *Service) AutoSchedulePreview(ctx context.Context, req AutoScheduleReq) (*AutoSchedulePreview, error) {
|
||||
if req.OrderNo == "" {
|
||||
return nil, errors.New("工单号必填")
|
||||
}
|
||||
if req.Mode != "AVG" && req.Mode != "FIXED" {
|
||||
return nil, errors.New("排产模式仅支持 AVG(平均分摊) / FIXED(固定日产)")
|
||||
}
|
||||
if req.Mode == "FIXED" && req.DailyQty <= 0 {
|
||||
return nil, errors.New("固定日产模式需填写每日产量(>0)")
|
||||
}
|
||||
dates, err := expandDates(req.Segments)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(dates) == 0 {
|
||||
return nil, errors.New("请至少选择一个日期区间")
|
||||
}
|
||||
_, quota, byDate, err := s.autoScheduleGuard(ctx, req.OrderNo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if quota == 0 {
|
||||
return nil, errors.New("未开工数量为 0,无需排产(已在产/已完工/已排满)")
|
||||
}
|
||||
rows := make([]AutoSchedulePreviewRow, 0, len(dates))
|
||||
editDates := make([]string, 0, len(dates))
|
||||
for _, ds := range dates {
|
||||
if p := byDate[ds]; p != nil && (p.Status == "PROCESSING" || p.Status == "DONE") {
|
||||
rows = append(rows, AutoSchedulePreviewRow{Date: ds, Qty: p.PlanQty, Editable: false, ExistStatus: p.Status})
|
||||
continue
|
||||
}
|
||||
existOne, _ := s.ctx.EntClient.DailyPlan.Query().
|
||||
Where(dailyplan.OrderNo(req.OrderNo), dailyplan.PlanDate(ds)).First(ctx)
|
||||
if existOne != nil {
|
||||
// 保护执行中/已完成的排产(方案 K / P2-3):不打回 PENDING、不覆盖数量,
|
||||
// 避免自动排产把正在产线执行(PROCESSING)或已完工(DONE)的日计划冲掉;
|
||||
// 这些计划的既有数量已在 existTotal 中计入、quota 已相应扣减,跳过不会超排。
|
||||
if existOne.Status == "PROCESSING" || existOne.Status == "DONE" {
|
||||
continue
|
||||
}
|
||||
_, err = s.ctx.EntClient.DailyPlan.UpdateOneID(existOne.ID).
|
||||
SetPlanQty(q).SetStatus("PENDING").SetOperator(operator).Save(ctx)
|
||||
} else {
|
||||
_, err = s.ctx.EntClient.DailyPlan.Create().
|
||||
SetOrderNo(req.OrderNo).SetPlanDate(ds).SetPlanQty(q).
|
||||
SetStatus("PENDING").SetOperator(operator).Save(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
editDates = append(editDates, ds)
|
||||
rows = append(rows, AutoSchedulePreviewRow{Date: ds, Qty: 0, Editable: true})
|
||||
}
|
||||
if len(editDates) == 0 {
|
||||
return nil, errors.New("所选日期均已有执行中/已完成的排产,无可调日期")
|
||||
}
|
||||
if req.Mode == "FIXED" && quota > req.DailyQty*len(editDates) {
|
||||
return nil, errors.New("固定日产×可调天数不足应排总数,请增加日期或提高每日产量")
|
||||
}
|
||||
mode := "AVG"
|
||||
if req.Mode == "FIXED" {
|
||||
mode = "FIXED"
|
||||
}
|
||||
initial := distributeQty(quota, len(editDates), mode, req.DailyQty)
|
||||
k := 0
|
||||
for i := range rows {
|
||||
if rows[i].Editable {
|
||||
rows[i].Qty = initial[k]
|
||||
k++
|
||||
}
|
||||
}
|
||||
s.ctx.EventLog.Write(ctx, "daily.plan.auto", req.OrderNo, operator, "daily_plan", req.OrderNo,
|
||||
"自动排产(模式="+req.Mode+")", map[string]any{"days": days, "total": sum, "quota": quota})
|
||||
return &AutoSchedulePreview{OrderNo: req.OrderNo, Quota: quota, Rows: rows}, nil
|
||||
}
|
||||
|
||||
// AutoScheduleApplyItem 确认排产的逐日数量(预览中用户自行调节后的结果)
|
||||
type AutoScheduleApplyItem struct {
|
||||
Date string `json:"date"`
|
||||
Qty int `json:"qty"`
|
||||
}
|
||||
|
||||
// AutoScheduleApplyReq 确认排产请求:Σ逐日数量必须等于应排总数(总数据要对的上)
|
||||
type AutoScheduleApplyReq struct {
|
||||
OrderNo string `json:"orderNo"`
|
||||
Items []AutoScheduleApplyItem `json:"items"`
|
||||
}
|
||||
|
||||
// AutoScheduleApply 确认排产(预览手调后提交):
|
||||
// 校验 Σ逐日数量 == 应排总数(quota)、逐日 ≥0、不触碰执行中/已完成日期;
|
||||
// 数量为 0 的日删除既有待执行行(不新建 0 行),其余覆盖式写入 status=PENDING 待人工启用。
|
||||
func (s *Service) AutoScheduleApply(ctx context.Context, req AutoScheduleApplyReq, operator string) error {
|
||||
if req.OrderNo == "" {
|
||||
return errors.New("工单号必填")
|
||||
}
|
||||
if len(req.Items) == 0 {
|
||||
return errors.New("排产明细为空,请先生成预览")
|
||||
}
|
||||
_, quota, byDate, err := s.autoScheduleGuard(ctx, req.OrderNo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if quota == 0 {
|
||||
return errors.New("未开工数量为 0,无需排产(已在产/已完工/已排满)")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
sum := 0
|
||||
for _, it := range req.Items {
|
||||
if _, err := parseDate(it.Date); err != nil {
|
||||
return errors.New("日期格式错误(应为 yyyy-MM-dd):" + it.Date)
|
||||
}
|
||||
if seen[it.Date] {
|
||||
return errors.New("日期重复:" + it.Date)
|
||||
}
|
||||
seen[it.Date] = true
|
||||
if it.Qty < 0 {
|
||||
return errors.New("每日数量不能为负数:" + it.Date)
|
||||
}
|
||||
if p := byDate[it.Date]; p != nil && (p.Status == "PROCESSING" || p.Status == "DONE") {
|
||||
return errors.New("日期 " + it.Date + " 的排产已执行中/已完成,不能修改")
|
||||
}
|
||||
sum += it.Qty
|
||||
}
|
||||
if sum != quota {
|
||||
return errors.New("各日合计 " + itoa(sum) + " 件 ≠ 应排总数 " + itoa(quota) + " 件(总数据必须对上),请调整后重试")
|
||||
}
|
||||
for _, it := range req.Items {
|
||||
existOne := byDate[it.Date]
|
||||
switch {
|
||||
case it.Qty == 0:
|
||||
if existOne != nil {
|
||||
if err := s.ctx.EntClient.DailyPlan.DeleteOneID(existOne.ID).Exec(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case existOne != nil:
|
||||
// 覆盖式更新;原 CONFIRMED 回退 PENDING,需重新人工启用(与原自动排产口径一致)
|
||||
if _, err := s.ctx.EntClient.DailyPlan.UpdateOneID(existOne.ID).
|
||||
SetPlanQty(it.Qty).SetStatus("PENDING").SetOperator(operator).Save(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
if _, err := s.ctx.EntClient.DailyPlan.Create().
|
||||
SetOrderNo(req.OrderNo).SetPlanDate(it.Date).SetPlanQty(it.Qty).
|
||||
SetStatus("PENDING").SetOperator(operator).Save(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
s.ctx.EventLog.Write(ctx, "daily.plan.apply", req.OrderNo, operator, "daily_plan", req.OrderNo,
|
||||
"确认排产(预览逐日调节)", map[string]any{"days": len(req.Items), "total": sum, "quota": quota})
|
||||
s.notifyDashboard()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -111,19 +111,6 @@ func (s *Service) buildWorkOrderProgress(ctx context.Context, today time.Time) [
|
||||
return []WorkOrderProgress{}
|
||||
}
|
||||
date := today.Format("2006-01-02")
|
||||
// 当前产线工艺组合(唯一路线源头 = 工单 flow_combination):取执行中工单,无则取最新已下发工单
|
||||
routeStr := ""
|
||||
if cur, err := s.ctx.EntClient.WorkOrder.Query().
|
||||
Where(workorder.Status("IN_PROGRESS")).Order(ent.Desc(workorder.FieldID)).First(ctx); err == nil {
|
||||
if items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, cur); len(items) > 0 {
|
||||
routeStr = RouteStationsStrOfWO(items)
|
||||
}
|
||||
} else if rel, err := s.ctx.EntClient.WorkOrder.Query().
|
||||
Where(workorder.Status("RELEASED")).Order(ent.Desc(workorder.FieldID)).First(ctx); err == nil {
|
||||
if items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, rel); len(items) > 0 {
|
||||
routeStr = RouteStationsStrOfWO(items)
|
||||
}
|
||||
}
|
||||
list := make([]WorkOrderProgress, 0, len(wos))
|
||||
for _, w := range wos {
|
||||
item := WorkOrderProgress{
|
||||
@@ -139,7 +126,12 @@ func (s *Service) buildWorkOrderProgress(ctx context.Context, today time.Time) [
|
||||
DailyPlanQty: s.sumDailyPlanQtyByOrder(ctx, date, w.WorkOrderNo),
|
||||
DailyDoneQty: s.countWorkpieceDoneByOrder(ctx, today, w.WorkOrderNo),
|
||||
}
|
||||
item.CurrentProcess = "工艺组合 " + routeStr
|
||||
// 多工单混生产:每单显示自己的工艺组合路线(唯一路线源头=本工单 flow_combination),不再共用单一在产工单路线
|
||||
if items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, w); len(items) > 0 {
|
||||
item.CurrentProcess = "工艺组合 " + RouteStationsStrOfWO(items)
|
||||
} else {
|
||||
item.CurrentProcess = "工艺组合 未配置"
|
||||
}
|
||||
list = append(list, item)
|
||||
}
|
||||
// 进行中的工单排前面,同状态按 ID 倒序
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"bj_power_mes/ent"
|
||||
"bj_power_mes/ent/inspectionrecord"
|
||||
"bj_power_mes/internal/wmsclient"
|
||||
)
|
||||
|
||||
// FlexStr 兼容客户端把数字字段传成 number 或 string(前端 stationNo 用数字,
|
||||
@@ -49,20 +50,42 @@ type InspectionReq struct {
|
||||
Manufacturer string `json:"manufacturer"` // 生产厂家
|
||||
InspectionNo string `json:"inspectionNo"` // 检验单号
|
||||
AttachmentIds string `json:"attachmentIds"` // 附件ID,逗号分隔
|
||||
DisposalType string `json:"disposalType"` // 处置类型 退货/返修/退换
|
||||
DisposalType string `json:"disposalType"` // 处置类型 退货/返修/退换/报废
|
||||
DisposalRemark string `json:"disposalRemark"` // 处置说明
|
||||
// 判不合格联动 WMS 在库处置的定位字段(可空=不联动):
|
||||
// 电气件(manage_mode=2)填 SN、结构件(manage_mode=1)填批次号;
|
||||
// BatchSnMode 指示 BatchSn 的口径(SN=按序列号定位 / BATCH=按批次定位,默认 BATCH)
|
||||
BatchSn string `json:"batchSn"`
|
||||
BatchSnMode string `json:"batchSnMode"`
|
||||
ReturnTrackingNo string `json:"returnTrackingNo"` // 退货运单号(退货/退换处置必填)
|
||||
}
|
||||
|
||||
// CreateInspection 提交巡检记录;ALARM 类型同时触发看板报警(SSE + 清缓存)
|
||||
func (s *Service) CreateInspection(ctx context.Context, req InspectionReq, operator string) error {
|
||||
// wmsDisposalType MES 中文处置方式 → WMS 内部处置枚举(RETURN/REWORK/SCRAP);
|
||||
// 无法映射返回空串(不联动 WMS,仅留痕)。
|
||||
func wmsDisposalType(v string) string {
|
||||
switch v {
|
||||
case "退货", "退换":
|
||||
return "RETURN"
|
||||
case "返修":
|
||||
return "REWORK"
|
||||
case "报废":
|
||||
return "SCRAP"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// CreateInspection 提交巡检记录;ALARM 类型同时触发看板报警(SSE + 清缓存)。
|
||||
// 质量检验(过程检/完工检)判不合格且填了批次号/SN 时,联动 WMS 在库处置:
|
||||
// 检验留痕优先——WMS 调用失败不阻断保存,仅在返回信息中提示「库存联动失败: 原因」。
|
||||
func (s *Service) CreateInspection(ctx context.Context, req InspectionReq, operator string) (string, error) {
|
||||
if req.Category == "" {
|
||||
return errors.New("记录类型必填")
|
||||
return "", errors.New("记录类型必填")
|
||||
}
|
||||
category := req.Category
|
||||
// PROCESS 为 PAD 巡检终端「过程巡检」专用;MES 车间质检「过程检」用 QC_PROCESS 隔离,
|
||||
// 避免同枚举导致两个列表互混、统计口径乱(P1-8)。
|
||||
if !oneOf(category, "CHECKIN", "POINT", "PROCESS", "DONE", "ALARM", "INCOMING", "FINAL", "QC_PROCESS") {
|
||||
return errors.New("记录类型不合法")
|
||||
return "", errors.New("记录类型不合法")
|
||||
}
|
||||
result := req.Result
|
||||
if result == "" {
|
||||
@@ -110,13 +133,50 @@ func (s *Service) CreateInspection(ctx context.Context, req InspectionReq, opera
|
||||
if req.DisposalRemark != "" {
|
||||
create.SetDisposalRemark(req.DisposalRemark)
|
||||
}
|
||||
if req.BatchSn != "" {
|
||||
create.SetBatchSn(req.BatchSn)
|
||||
}
|
||||
_, err := create.Save(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
s.ctx.EventLog.Write(ctx, "inspection."+category, req.OrderNo, req.Operator, "inspection_record",
|
||||
req.Sn, "巡检终端提交", map[string]any{"category": category, "stationNo": string(req.StationNo), "result": result})
|
||||
|
||||
// 判不合格 → 联动 WMS 在库处置(缺口 B):
|
||||
// 前提:结论 NG + 已选可映射的处置方式 + 物料编码与批次号/SN 齐全;
|
||||
// 定位口径:电气件按 SN(material_code+序列号)、结构件按批次(material_code+批次号)。
|
||||
// WMS 调用失败不阻断检验留痕,返回信息提示「库存联动失败」,并写事件日志便于追溯。
|
||||
msg := "巡检记录已提交"
|
||||
if result == "NG" && req.MaterialCode != "" && req.BatchSn != "" {
|
||||
if dt := wmsDisposalType(req.DisposalType); dt != "" {
|
||||
wreq := wmsclient.DisposeInventoryReq{
|
||||
MaterialCode: req.MaterialCode,
|
||||
DisposalType: dt,
|
||||
ReturnTrackingNo: req.ReturnTrackingNo,
|
||||
Remark: req.DisposalRemark,
|
||||
Operator: req.Operator,
|
||||
}
|
||||
if req.BatchSnMode == "SN" {
|
||||
wreq.Sn = req.BatchSn
|
||||
} else {
|
||||
wreq.BatchNo = req.BatchSn
|
||||
}
|
||||
if err := s.ctx.Wms.DisposeInventory(ctx, wreq); err != nil {
|
||||
msg = "检验记录已保存;库存联动失败: " + err.Error()
|
||||
s.ctx.EventLog.Write(ctx, "inspection.wms_dispose_failed", req.OrderNo, req.Operator,
|
||||
"inspection_record", req.Sn, "库存联动失败 "+err.Error(),
|
||||
map[string]any{"materialCode": req.MaterialCode, "batchSn": req.BatchSn,
|
||||
"disposalType": dt, "batchSnMode": req.BatchSnMode})
|
||||
} else {
|
||||
msg = "检验记录已保存,已联动 WMS 在库处置(" + req.DisposalType + ")"
|
||||
s.ctx.EventLog.Write(ctx, "inspection.wms_disposed", req.OrderNo, req.Operator,
|
||||
"inspection_record", req.Sn, "已联动 WMS 在库处置 "+dt,
|
||||
map[string]any{"materialCode": req.MaterialCode, "batchSn": req.BatchSn, "disposalType": dt})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if category == "ALARM" {
|
||||
// 触发看板报警:SSE 推送 + 使 Redis 看板报警缓存失效
|
||||
alarmJSON, _ := json.Marshal(map[string]any{
|
||||
@@ -134,7 +194,7 @@ func (s *Service) CreateInspection(ctx context.Context, req InspectionReq, opera
|
||||
}
|
||||
}
|
||||
s.notifyDashboard()
|
||||
return nil
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// ListInspections 查询巡检记录(不分页,供内部/导出用,封顶 1000)
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"bj_power_mes/ent"
|
||||
"bj_power_mes/ent/material"
|
||||
"bj_power_mes/internal/wmsclient"
|
||||
)
|
||||
|
||||
// 物料两库对等双向同步(需求一 M1-M8,2026-09-29 定稿):
|
||||
// · MES 本地 materials 表 = 与 WMS materials 对等的副本,code(图号)为两库同步唯一业务键,
|
||||
// 两库均不物理删除(只停用,M5);
|
||||
// · MES 侧写入(M3):先落本地,再推 WMS /api/internal/materials/upsert,推失败置 sync_pending
|
||||
// 待重推(不回滚本地);列表请求顺带异步重推 pending 行;
|
||||
// · WMS 侧写入(M2/M4):经内部接口按 code 幂等 upsert 到本地(本包 UpsertLocalMaterial),
|
||||
// 只落本地、不回推 WMS(防同步环);
|
||||
// · 本地为空(冷启动)异步从 WMS 全量拉取补齐(M7);失败静默记日志,不阻塞用户;
|
||||
// · 型号/物料查询全部读本地(M6):WMS 宕机时 MES 建单/排产/下拉照常可用;
|
||||
// · 备料"物料在 WMS 档案存在"校验仍直查 WMS(M8)——备料要出库,库存真源在 WMS。
|
||||
|
||||
// MaterialUpsertReq 两库物料 upsert 载荷(WMS→MES 推送 / MES 拉 WMS 补齐共用),code 为同步唯一业务键。
|
||||
type MaterialUpsertReq struct {
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
Spec string `json:"spec"`
|
||||
Unit string `json:"unit"`
|
||||
Description string `json:"description"`
|
||||
ItemType int `json:"itemType"`
|
||||
ManageMode int `json:"manageMode"`
|
||||
TemplateCode string `json:"templateCode"`
|
||||
SafetyStock int `json:"safetyStock"`
|
||||
IsActive *bool `json:"isActive"`
|
||||
}
|
||||
|
||||
// UpsertLocalMaterial 按 code 幂等 upsert MES 本地物料副本。
|
||||
// WMS→MES 推送落点(M2):WMS 是该行内容的写入方,落库成功即视为两库一致,清 sync_pending。
|
||||
// 返回 true=新建 / false=更新;code 为必填业务键,不可通过本接口修改。
|
||||
func (s *Service) UpsertLocalMaterial(ctx context.Context, req MaterialUpsertReq) (bool, error) {
|
||||
if req.Code == "" {
|
||||
return false, errors.New("code(图号)为必填项")
|
||||
}
|
||||
active := true
|
||||
if req.IsActive != nil {
|
||||
active = *req.IsActive
|
||||
}
|
||||
existing, err := s.ctx.EntClient.Material.Query().Where(material.CodeEQ(req.Code)).Only(ctx)
|
||||
if err == nil {
|
||||
_, err = s.ctx.EntClient.Material.UpdateOneID(existing.ID).
|
||||
SetName(req.Name).
|
||||
SetSpec(req.Spec).
|
||||
SetUnit(req.Unit).
|
||||
SetDescription(req.Description).
|
||||
SetItemType(req.ItemType).
|
||||
SetManageMode(req.ManageMode).
|
||||
SetTemplateCode(req.TemplateCode).
|
||||
SetSafetyStock(req.SafetyStock).
|
||||
SetIsActive(active).
|
||||
SetSyncPending(false).
|
||||
Save(ctx)
|
||||
return false, err
|
||||
}
|
||||
if !ent.IsNotFound(err) {
|
||||
return false, err
|
||||
}
|
||||
_, err = s.ctx.EntClient.Material.Create().
|
||||
SetCode(req.Code).
|
||||
SetName(req.Name).
|
||||
SetSpec(req.Spec).
|
||||
SetUnit(req.Unit).
|
||||
SetDescription(req.Description).
|
||||
SetItemType(req.ItemType).
|
||||
SetManageMode(req.ManageMode).
|
||||
SetTemplateCode(req.TemplateCode).
|
||||
SetSafetyStock(req.SafetyStock).
|
||||
SetIsActive(active).
|
||||
SetSyncPending(false).
|
||||
Save(ctx)
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
// materialUpsertOf 本地物料行 → 推 WMS 载荷。
|
||||
func materialUpsertOf(m *ent.Material) wmsclient.MaterialUpsert {
|
||||
active := m.IsActive
|
||||
return wmsclient.MaterialUpsert{
|
||||
Code: m.Code,
|
||||
Name: m.Name,
|
||||
Spec: m.Spec,
|
||||
Unit: m.Unit,
|
||||
Description: m.Description,
|
||||
ItemType: m.ItemType,
|
||||
ManageMode: m.ManageMode,
|
||||
TemplateCode: m.TemplateCode,
|
||||
SafetyStock: m.SafetyStock,
|
||||
IsActive: &active,
|
||||
}
|
||||
}
|
||||
|
||||
// pushMaterialToWMS 推单行到 WMS(同步调用):成功清 sync_pending,失败置位等待重推(不 panic)。
|
||||
func (s *Service) pushMaterialToWMS(ctx context.Context, m *ent.Material) error {
|
||||
if err := s.ctx.Wms.UpsertMaterialToWMS(ctx, materialUpsertOf(m)); err != nil {
|
||||
_ = s.ctx.EntClient.Material.UpdateOneID(m.ID).SetSyncPending(true).Exec(ctx)
|
||||
return err
|
||||
}
|
||||
_ = s.ctx.EntClient.Material.UpdateOneID(m.ID).SetSyncPending(false).Exec(ctx)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RetryPendingMaterialPushes 重推全部 sync_pending 行(M3),返回重推成功的行数。
|
||||
func (s *Service) RetryPendingMaterialPushes(ctx context.Context) int {
|
||||
pending, err := s.ctx.EntClient.Material.Query().Where(material.SyncPendingEQ(true)).All(ctx)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
okCnt := 0
|
||||
for i := range pending {
|
||||
c, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
if s.pushMaterialToWMS(c, pending[i]) == nil {
|
||||
okCnt++
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
return okCnt
|
||||
}
|
||||
|
||||
// RetryPendingMaterialPushesAsync 异步重推(列表请求顺带触发,不阻塞响应,失败静默)。
|
||||
func (s *Service) RetryPendingMaterialPushesAsync() {
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if n := s.RetryPendingMaterialPushes(ctx); n > 0 {
|
||||
log.Printf("[material-sync] 重推 WMS 成功 %d 行", n)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// PullMaterialsFromWMSAsync 从 WMS 全量分页拉取物料 upsert 到本地(M7 冷启动补齐)。
|
||||
// 仅在本地为空时调用——若本地已有 pending 行,说明本地存在未推 WMS 的改动,禁止被 WMS 旧值覆盖。
|
||||
// 失败静默记日志,不阻塞用户。
|
||||
func (s *Service) PullMaterialsFromWMSAsync() {
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
total := 0
|
||||
for page := 1; page <= 100; page++ {
|
||||
_, rows, err := s.ctx.Wms.MaterialPage(ctx, "", "", "", 0, 0, page, 200)
|
||||
if err != nil {
|
||||
log.Printf("[material-sync] 拉取 WMS 物料失败(第 %d 页): %v", page, err)
|
||||
return
|
||||
}
|
||||
for _, r := range rows {
|
||||
active := r.IsActive
|
||||
if _, err := s.UpsertLocalMaterial(ctx, MaterialUpsertReq{
|
||||
Code: r.Code, Name: r.Name, Spec: r.Spec, Unit: r.Unit, Description: r.Description,
|
||||
ItemType: r.ItemType, ManageMode: r.ManageMode, TemplateCode: r.TemplateCode,
|
||||
SafetyStock: r.SafetyStock, IsActive: &active,
|
||||
}); err != nil {
|
||||
log.Printf("[material-sync] 物料 %s 落库失败: %v", r.Code, err)
|
||||
continue
|
||||
}
|
||||
total++
|
||||
}
|
||||
if len(rows) < 200 {
|
||||
break
|
||||
}
|
||||
}
|
||||
log.Printf("[material-sync] 自 WMS 全量同步物料 %d 行", total)
|
||||
}()
|
||||
}
|
||||
|
||||
// EnsureMaterialCacheAsync 列表请求顺带的缓存维护(M3/M7):本地为空才异步全量拉取;重推 pending 行。
|
||||
// 均为异步,不阻塞响应。
|
||||
func (s *Service) EnsureMaterialCacheAsync() {
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
n, err := s.ctx.EntClient.Material.Query().Count(ctx)
|
||||
cancel()
|
||||
if err == nil && n == 0 {
|
||||
s.PullMaterialsFromWMSAsync()
|
||||
}
|
||||
}()
|
||||
s.RetryPendingMaterialPushesAsync()
|
||||
}
|
||||
@@ -142,9 +142,9 @@ func (s *Service) ComputeProducible(ctx context.Context) (*ProducibleResult, err
|
||||
return nil, errors.New("拉取 WMS 可用量失败: " + err.Error())
|
||||
}
|
||||
|
||||
// 产品名称映射(product_type 优先,工单快照兜底)
|
||||
// 产品名称映射(本地成品档案优先=M6,工单快照兜底)
|
||||
nameMap := map[string]string{}
|
||||
if rows, e := s.ctx.Wms.ProductTypes(ctx, ""); e == nil {
|
||||
if rows, _, e := s.ListProductTypes(ctx, ""); e == nil {
|
||||
for _, p := range rows {
|
||||
nameMap[p.Code] = p.Name
|
||||
}
|
||||
|
||||
@@ -4,15 +4,22 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bj_power_mes/ent/workorder"
|
||||
"bj_power_mes/ent"
|
||||
"bj_power_mes/ent/material"
|
||||
"bj_power_mes/internal/wmsclient"
|
||||
)
|
||||
|
||||
// 产品型号(成品档案):编码主数据单一来源 = WMS(materials item_type=3)。
|
||||
// MES 本页实时代理 WMS;不再保留本地 product_types 缓存/双写(方案 A:WMS 不可达即报错,
|
||||
// 不降级读本地缓存,避免给界面喂空/陈旧数据)。
|
||||
// 产品型号(成品档案 item_type=3):两库对等双向同步(需求一 M3/M5/M6,2026-09-29 定稿)。
|
||||
// MES 侧维护改为「本地优先」:先写 MES 本地 materials 表,再推 WMS /api/internal/materials/upsert,
|
||||
// 推失败置 sync_pending 由列表请求异步重推,不回滚本地(M3)。
|
||||
// 查询全部读本地——WMS 宕机时 MES 建单/排产/型号下拉照常可用(M6)。
|
||||
// 与 WMS product-types 接口同口径:品类固定 3(成品)、管理粒度固定 2(序列号)、
|
||||
// 编码留空自动生成 PROD-YYYYMMDD-当日流水、Category 列取说明列(历史迁移约定)。
|
||||
// 备料"物料在 WMS 档案存在"校验仍直查 WMS(M8,库存真源在 WMS,见 logic/material.go)。
|
||||
|
||||
type ProductTypeReq struct {
|
||||
Id int `json:"id"`
|
||||
@@ -20,11 +27,50 @@ type ProductTypeReq struct {
|
||||
Code string `json:"code"`
|
||||
Spec string `json:"spec"`
|
||||
Unit string `json:"unit"`
|
||||
Category string `json:"category"`
|
||||
ManageMode int `json:"manageMode"` // 1结构件(批次)/2电气件(SN);MES 成品只列这两个
|
||||
ManageMode int `json:"manageMode"` // 兼容前端传参;成品固定按序列号(2)管理,与 WMS 同口径
|
||||
IsActive bool `json:"isActive"`
|
||||
}
|
||||
|
||||
// productTypeCodePrefix 与 WMS 编码规则同源:PROD-YYYYMMDD-流水
|
||||
const productTypeCodePrefix = "PROD"
|
||||
|
||||
// genProductTypeCode 本地生成型号编码:PROD-YYYYMMDD-流水(当日序号递增,与 WMS 规则一致)
|
||||
func (s *Service) genProductTypeCode(ctx context.Context) (string, error) {
|
||||
date := time.Now().Format("20060102")
|
||||
prefix := fmt.Sprintf("%s-%s-", productTypeCodePrefix, date)
|
||||
all, err := s.ctx.EntClient.Material.Query().Where(material.CodeHasPrefix(prefix)).All(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
maxSeq := 0
|
||||
for _, m := range all {
|
||||
var seq int
|
||||
if _, err := fmt.Sscanf(m.Code, prefix+"%d", &seq); err == nil && seq > maxSeq {
|
||||
maxSeq = seq
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%s%03d", prefix, maxSeq+1), nil
|
||||
}
|
||||
|
||||
// productTypeRowOf 本地物料行 → 前端型号 DTO(与 WMS productTypeRow 同形;Category 取说明列)。
|
||||
func productTypeRowOf(m *ent.Material) wmsclient.ProductTypeRow {
|
||||
return wmsclient.ProductTypeRow{
|
||||
ID: m.ID,
|
||||
Code: m.Code,
|
||||
Name: m.Name,
|
||||
Spec: m.Spec,
|
||||
Unit: m.Unit,
|
||||
Category: m.Description,
|
||||
ManageMode: m.ManageMode,
|
||||
IsActive: m.IsActive,
|
||||
CreatedAt: m.CreatedAt.Unix(),
|
||||
UpdatedAt: m.UpdatedAt.Unix(),
|
||||
SyncPending: m.SyncPending,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateProductType 新建型号:本地优先落库 → 推 WMS(M3)。
|
||||
// 推送失败不报错、不回滚本地(sync_pending 已置位,列表请求自动重推)。
|
||||
func (s *Service) CreateProductType(ctx context.Context, req ProductTypeReq) error {
|
||||
active := req.IsActive
|
||||
if !req.IsActive {
|
||||
@@ -39,12 +85,35 @@ func (s *Service) CreateProductType(ctx context.Context, req ProductTypeReq) err
|
||||
if strings.TrimSpace(req.Unit) == "" {
|
||||
return errors.New("单位为必填项")
|
||||
}
|
||||
if err := s.ctx.Wms.CreateProductType(ctx, req.Code, req.Name, req.Spec, req.Unit, req.Category, active, req.ManageMode); err != nil {
|
||||
return errors.New("WMS 不可达或拒绝写入(编码主数据以 WMS 为单一来源):" + err.Error())
|
||||
code := strings.TrimSpace(req.Code)
|
||||
if code == "" {
|
||||
var err error
|
||||
if code, err = s.genProductTypeCode(ctx); err != nil {
|
||||
return errors.New("生成编码失败:" + err.Error())
|
||||
}
|
||||
}
|
||||
if exists, _ := s.ctx.EntClient.Material.Query().Where(material.CodeEQ(code)).Exist(ctx); exists {
|
||||
return errors.New("编码已存在: " + code)
|
||||
}
|
||||
m, err := s.ctx.EntClient.Material.Create().
|
||||
SetCode(code).
|
||||
SetName(req.Name).
|
||||
SetSpec(req.Spec).
|
||||
SetUnit(req.Unit).
|
||||
SetItemType(3).
|
||||
SetManageMode(2). // 成品按 SN 管理,与 WMS product-types 同口径
|
||||
SetIsActive(active).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return errors.New("保存物料档案失败:" + err.Error())
|
||||
}
|
||||
if err := s.pushMaterialToWMS(ctx, m); err != nil {
|
||||
log.Printf("[material-sync] 新建 %s 已落本地,推送 WMS 失败(待重推): %v", code, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateProductType 编辑型号(编码不可改):本地优先 → 推 WMS(M3)。
|
||||
func (s *Service) UpdateProductType(ctx context.Context, req ProductTypeReq) error {
|
||||
if req.Id == 0 {
|
||||
return errors.New("缺少 id")
|
||||
@@ -58,74 +127,119 @@ func (s *Service) UpdateProductType(ctx context.Context, req ProductTypeReq) err
|
||||
if strings.TrimSpace(req.Unit) == "" {
|
||||
return errors.New("单位为必填项")
|
||||
}
|
||||
if err := s.ctx.Wms.UpdateProductType(ctx, req.Id, req.Name, req.Spec, req.Unit, req.Category, req.IsActive, req.ManageMode); err != nil {
|
||||
return errors.New("WMS 不可达或拒绝写入:" + err.Error())
|
||||
cur, err := s.ctx.EntClient.Material.Get(ctx, req.Id)
|
||||
if err != nil || cur.ItemType != 3 {
|
||||
return errors.New("物料档案不存在")
|
||||
}
|
||||
m, err := s.ctx.EntClient.Material.UpdateOneID(cur.ID).
|
||||
SetName(req.Name).
|
||||
SetSpec(req.Spec).
|
||||
SetUnit(req.Unit).
|
||||
SetIsActive(req.IsActive).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return errors.New("更新物料档案失败:" + err.Error())
|
||||
}
|
||||
if err := s.pushMaterialToWMS(ctx, m); err != nil {
|
||||
log.Printf("[material-sync] 编辑 %s 已落本地,推送 WMS 失败(待重推): %v", cur.Code, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteProductType 删除保护:被工单/BOM 引用过的型号禁删(MES 侧引用校验,
|
||||
// WMS 侧库存引用由 WMS 内部接口再校验一层)
|
||||
// DeleteProductType 「删除」=停用(客户裁决"都不可删除",M5 两库一致):
|
||||
// 本地置 isActive=false → 推 WMS 同步停用。停用不影响历史工单/库存引用(行保留)。
|
||||
func (s *Service) DeleteProductType(ctx context.Context, id int) error {
|
||||
row, err := s.ProductTypeByID(ctx, id)
|
||||
cur, err := s.ctx.EntClient.Material.Get(ctx, id)
|
||||
if err != nil || cur.ItemType != 3 {
|
||||
return errors.New("物料档案不存在")
|
||||
}
|
||||
if !cur.IsActive {
|
||||
return nil // 已停用,幂等
|
||||
}
|
||||
m, err := s.ctx.EntClient.Material.UpdateOneID(id).SetIsActive(false).Save(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
return errors.New("停用物料档案失败:" + err.Error())
|
||||
}
|
||||
woCnt, _ := s.ctx.EntClient.WorkOrder.Query().Where(workorder.ProductCode(row.Code)).Count(ctx)
|
||||
if woCnt > 0 {
|
||||
return fmt.Errorf("该物料档案已被 %d 张工单引用,不可删除;建议停用(下架)", woCnt)
|
||||
}
|
||||
if err := s.ctx.Wms.DeleteProductType(ctx, id); err != nil {
|
||||
return errors.New("WMS 不可达或拒绝删除:" + err.Error())
|
||||
if err := s.pushMaterialToWMS(ctx, m); err != nil {
|
||||
log.Printf("[material-sync] 停用 %s 已落本地,推送 WMS 失败(待重推): %v", cur.Code, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListProductTypes 全量列表(下拉/兼容形态,id asc 新建在底部)。
|
||||
// 纯 WMS 代理:WMS 不可达直接报错(不再降级本地缓存)。degraded 恒为 true(仅兼容前端字段)。
|
||||
// ListProductTypes 全量列表(下拉/兼容形态,id asc 新建在底部)。读 MES 本地(M6)。
|
||||
// degraded 恒为 true(仅兼容前端字段)。
|
||||
func (s *Service) ListProductTypes(ctx context.Context, isActive string) ([]wmsclient.ProductTypeRow, bool, error) {
|
||||
list, err := s.ctx.Wms.ProductTypes(ctx, isActive)
|
||||
if err != nil {
|
||||
return nil, false, errors.New("WMS 不可达,无法读取成品档案:" + err.Error())
|
||||
q := s.ctx.EntClient.Material.Query().Where(material.ItemTypeEQ(3))
|
||||
switch isActive {
|
||||
case "true":
|
||||
q = q.Where(material.IsActiveEQ(true))
|
||||
case "false":
|
||||
q = q.Where(material.IsActiveEQ(false))
|
||||
}
|
||||
return list, true, nil
|
||||
list, err := q.Order(ent.Asc("id")).All(ctx)
|
||||
if err != nil {
|
||||
return nil, false, errors.New("查询成品档案失败:" + err.Error())
|
||||
}
|
||||
rows := make([]wmsclient.ProductTypeRow, 0, len(list))
|
||||
for i := range list {
|
||||
rows = append(rows, productTypeRowOf(list[i]))
|
||||
}
|
||||
return rows, true, nil
|
||||
}
|
||||
|
||||
// ListProductTypesPage 分页+搜索(管理页真分页)。
|
||||
// 2026-09-08 禁止关键字混搜:编码/名称/类别各自独立模糊。
|
||||
// 纯 WMS 代理:WMS 不可达直接报错。wmsOnline 恒为 true(仅兼容前端字段)。
|
||||
func (s *Service) ListProductTypesPage(ctx context.Context, code, name, category, isActive string, page, pageSize int) (int64, []wmsclient.ProductTypeRow, bool, error) {
|
||||
total, list, err := s.ctx.Wms.ProductTypePage(ctx, code, name, category, isActive, page, pageSize)
|
||||
if err != nil {
|
||||
return 0, nil, false, errors.New("WMS 不可达,无法读取成品档案:" + err.Error())
|
||||
// ListProductTypesPage 分页+搜索(管理页真分页,真源=本地)。
|
||||
// 2026-09-08 禁止关键字混搜:编码/名称各自独立模糊。wmsOnline 恒为 true(仅兼容前端字段)。
|
||||
// 本地副本为空时异步自 WMS 全量拉取补齐(M7),并顺带重推 pending 行(M3)。
|
||||
func (s *Service) ListProductTypesPage(ctx context.Context, code, name, isActive string, page, pageSize int) (int64, []wmsclient.ProductTypeRow, bool, error) {
|
||||
s.EnsureMaterialCacheAsync()
|
||||
q := s.ctx.EntClient.Material.Query().Where(material.ItemTypeEQ(3))
|
||||
if code != "" {
|
||||
q = q.Where(material.CodeContainsFold(code))
|
||||
}
|
||||
return total, list, true, nil
|
||||
if name != "" {
|
||||
q = q.Where(material.NameContainsFold(name))
|
||||
}
|
||||
switch isActive {
|
||||
case "true":
|
||||
q = q.Where(material.IsActiveEQ(true))
|
||||
case "false":
|
||||
q = q.Where(material.IsActiveEQ(false))
|
||||
}
|
||||
total, err := q.Count(ctx)
|
||||
if err != nil {
|
||||
return 0, nil, false, errors.New("查询成品档案失败:" + err.Error())
|
||||
}
|
||||
list, err := q.Order(ent.Asc("id")).
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).All(ctx)
|
||||
if err != nil {
|
||||
return 0, nil, false, errors.New("查询成品档案失败:" + err.Error())
|
||||
}
|
||||
rows := make([]wmsclient.ProductTypeRow, 0, len(list))
|
||||
for i := range list {
|
||||
rows = append(rows, productTypeRowOf(list[i]))
|
||||
}
|
||||
return int64(total), rows, true, nil
|
||||
}
|
||||
|
||||
// ProductTypeByID 从 WMS 取成品档案(item_type=3)按 id;WMS 不可达即报错。
|
||||
// ProductTypeByID 按本地 id 取成品档案(item_type=3)。
|
||||
func (s *Service) ProductTypeByID(ctx context.Context, id int) (*wmsclient.ProductTypeRow, error) {
|
||||
list, err := s.ctx.Wms.ProductTypes(ctx, "")
|
||||
if err != nil {
|
||||
return nil, errors.New("WMS 不可达,无法读取成品档案:" + err.Error())
|
||||
m, err := s.ctx.EntClient.Material.Get(ctx, id)
|
||||
if err != nil || m.ItemType != 3 {
|
||||
return nil, errors.New("物料档案不存在")
|
||||
}
|
||||
for i := range list {
|
||||
if list[i].ID == id {
|
||||
return &list[i], nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("物料档案不存在")
|
||||
row := productTypeRowOf(m)
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// ProductTypeByCode 从 WMS 取成品档案按 code。
|
||||
// ProductTypeByCode 按编码取成品档案(item_type=3)。
|
||||
func (s *Service) ProductTypeByCode(ctx context.Context, code string) (*wmsclient.ProductTypeRow, error) {
|
||||
list, err := s.ctx.Wms.ProductTypes(ctx, "")
|
||||
if err != nil {
|
||||
return nil, errors.New("WMS 不可达,无法读取成品档案:" + err.Error())
|
||||
m, err := s.ctx.EntClient.Material.Query().Where(material.CodeEQ(code)).Only(ctx)
|
||||
if err != nil || m.ItemType != 3 {
|
||||
return nil, errors.New("物料档案不存在")
|
||||
}
|
||||
for i := range list {
|
||||
if list[i].Code == code {
|
||||
return &list[i], nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("物料档案不存在")
|
||||
row := productTypeRowOf(m)
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// 引用保护说明:原「被工单引用禁删」检查随删除→停用语义取消(M5)——
|
||||
// 停用仅令该型号退出新建下拉,历史工单/库存行原样保留,不存在悬挂引用。
|
||||
|
||||
@@ -139,7 +139,11 @@ func (s *Service) resolveUniqueWorkOrderNo(ctx context.Context, want string) (st
|
||||
return "", errors.New("工单号自动编号失败(序号已用尽),请手动指定工单号")
|
||||
}
|
||||
|
||||
// UpdateWorkOrder 编辑工单。仅「已创建」状态允许编辑(已下发/执行中/已暂停只能流转,已完成/已取消只读)。
|
||||
// UpdateWorkOrder 编辑工单。
|
||||
// - 「已创建」(含存量 PENDING):全字段可编辑
|
||||
// - 「已暂停」(PAUSED):仅允许调整工艺组合(其余字段锁定),且须无在制工件——
|
||||
// 在制工件按当前组合走完,防止运行中路线突变;变更写 eventlog 留痕
|
||||
// - 其余状态只读(已下发/执行中只能做状态流转,已完成/已取消只读)
|
||||
func (s *Service) UpdateWorkOrder(ctx context.Context, req WorkOrderReq, operator string) error {
|
||||
if req.Id == 0 {
|
||||
return errors.New("缺少 id")
|
||||
@@ -148,6 +152,34 @@ func (s *Service) UpdateWorkOrder(ctx context.Context, req WorkOrderReq, operato
|
||||
if err != nil {
|
||||
return errors.New("工单不存在")
|
||||
}
|
||||
pausedEdit := old.Status == "PAUSED"
|
||||
if old.Status != "CREATED" && old.Status != "PENDING" && !pausedEdit {
|
||||
return errors.New("仅「已创建」可编辑全部字段;「已暂停」仅允许调整工艺组合;其余状态只能做状态流转")
|
||||
}
|
||||
// 已暂停:仅工艺组合可改(在制守卫 + 留痕),其余字段一律拒绝
|
||||
if pausedEdit {
|
||||
if req.FlowCombination == nil {
|
||||
return errors.New("已暂停的工单仅允许调整工艺组合")
|
||||
}
|
||||
inflight, _ := s.ctx.EntClient.Workpiece.Query().
|
||||
Where(workpiece.OrderNo(old.WorkOrderNo), workpiece.StatusNEQ("DONE")).
|
||||
Count(ctx)
|
||||
if inflight > 0 {
|
||||
return fmt.Errorf("该工单还有 %d 个在制/未完工工件,请先完成或撤回后再调整工艺组合", inflight)
|
||||
}
|
||||
items, err := s.ValidateFlowCombination(ctx, req.FlowCombination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.ctx.EntClient.WorkOrder.UpdateOneID(req.Id).
|
||||
SetFlowCombination(flowItemsToMaps(items)).Exec(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
s.ctx.EventLog.Write(ctx, "work.order.flow_change", old.WorkOrderNo, operator, "work_order", old.WorkOrderNo,
|
||||
"已暂停工单调整工艺组合", map[string]any{"old": old.FlowCombination, "new": flowItemsToMaps(items)})
|
||||
s.notifyDashboard()
|
||||
return nil
|
||||
}
|
||||
if old.Status != "CREATED" && old.Status != "PENDING" {
|
||||
return errors.New("仅「已创建」状态的工单可编辑;生产中或已结束的工单只能做状态流转")
|
||||
}
|
||||
@@ -278,15 +310,12 @@ func (s *Service) SetWorkOrderStatus(ctx context.Context, id int, status, reason
|
||||
if !workOrderTransitions[wo.Status][status] {
|
||||
return fmt.Errorf("不允许从「%s」变更为「%s」", statusTextCN(wo.Status), statusTextCN(status))
|
||||
}
|
||||
// 单工单互斥:一条产线同时只能有一个在产工单(下发/开工前校验)
|
||||
// 工艺组合守卫:下发/开工必须有工艺组合(建单允许空组合,组合是"怎么生产"的前提)
|
||||
// 多工单混生产:移除原"单工单互斥"(一条产线允许同时执行多个工单;
|
||||
// 工位级天然串行=一个工位一次装一个工件,备料/报工/追溯全按工单挂账互不干扰)
|
||||
if status == "RELEASED" || status == "IN_PROGRESS" {
|
||||
others, _ := s.ctx.EntClient.WorkOrder.Query().
|
||||
Where(workorder.StatusIn("IN_PROGRESS", "PAUSED")).
|
||||
All(ctx)
|
||||
for _, o := range others {
|
||||
if o.ID != id {
|
||||
return fmt.Errorf("产线上已有在产工单「%s」(%s),完成或暂停后方可下发/开工新工单", o.WorkOrderNo, statusTextCN(o.Status))
|
||||
}
|
||||
if len(wo.FlowCombination) == 0 {
|
||||
return errors.New("该工单未配置工艺组合,请先在工单编辑中勾选工艺组合后再下发/开工")
|
||||
}
|
||||
}
|
||||
upd := s.ctx.EntClient.WorkOrder.UpdateOneID(id).SetStatus(status)
|
||||
|
||||
Reference in New Issue
Block a user