feat: 新增预警定时扫描器,移除附件归档字段并为角色表补充更新时间
This commit is contained in:
@@ -0,0 +1,405 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"bj_power_wms/ent/alert"
|
||||
"bj_power_wms/ent/alertrule"
|
||||
"bj_power_wms/ent/inventory"
|
||||
"bj_power_wms/ent/inspectionrecord"
|
||||
"bj_power_wms/ent/material"
|
||||
"bj_power_wms/internal/svc"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/zeromicro/go-zero/rest/pathvar"
|
||||
)
|
||||
|
||||
// 五类预警的固定 rule_code(与 alert_rules.code 一一对应)。
|
||||
const (
|
||||
ruleInventoryLow = "inventory_low"
|
||||
ruleInspectionOver = "inspection_overdue"
|
||||
ruleBackupOverdue = "backup_overdue"
|
||||
ruleSyncFailed = "sync_failed"
|
||||
ruleInventoryAge = "inventory_age"
|
||||
)
|
||||
|
||||
// 扫描默认阈值(仅在规则未配置时使用)。
|
||||
const (
|
||||
defaultInspectionOverdueHours = 48 // 来料检超期小时
|
||||
defaultInventoryAgeDays = 180 // 库龄超档天
|
||||
alertDedupHours = 24 // 同一 rule_code+target 防刷窗口(小时)
|
||||
)
|
||||
|
||||
// alertRuleDef 默认规则定义(扫描器启动时确保存在)。
|
||||
var alertRuleDefs = []struct {
|
||||
code string
|
||||
name string
|
||||
threshold int
|
||||
}{
|
||||
{ruleInventoryLow, "库存阈值/缺货预警", 0},
|
||||
{ruleInspectionOver, "来料检超期未检预警", defaultInspectionOverdueHours},
|
||||
{ruleBackupOverdue, "备份超期预警", 0},
|
||||
{ruleSyncFailed, "物料同步失败预警", 0},
|
||||
{ruleInventoryAge, "库龄超档预警", defaultInventoryAgeDays},
|
||||
}
|
||||
|
||||
// ensureAlertRules 确保五类规则存在(缺则插入,已存在不覆盖用户修改)。
|
||||
func ensureAlertRules(ctx *svc.ServiceContext) {
|
||||
for _, d := range alertRuleDefs {
|
||||
exist, err := ctx.EntClient.AlertRule.Query().Where(alertrule.CodeEQ(d.code)).Exist(ctx0())
|
||||
if err != nil || exist {
|
||||
continue
|
||||
}
|
||||
_, _ = ctx.EntClient.AlertRule.Create().
|
||||
SetCode(d.code).
|
||||
SetName(d.name).
|
||||
SetEnabled(true).
|
||||
SetThreshold(d.threshold).
|
||||
Save(ctx0())
|
||||
}
|
||||
}
|
||||
|
||||
// getAlertRule 读取规则启用状态与阈值。
|
||||
func getAlertRule(ctx *svc.ServiceContext, code string) (enabled bool, threshold int) {
|
||||
r, err := ctx.EntClient.AlertRule.Query().Where(alertrule.CodeEQ(code)).Only(ctx0())
|
||||
if err != nil {
|
||||
return false, 0
|
||||
}
|
||||
return r.Enabled, r.Threshold
|
||||
}
|
||||
|
||||
// alertExistsRecent 同一 rule_code+target 是否已有「未读」且较新(窗口内)的预警(防刷)。
|
||||
func alertExistsRecent(ctx *svc.ServiceContext, ruleCode, target string) (bool, error) {
|
||||
cutoff := time.Now().Unix() - int64(alertDedupHours)*3600
|
||||
return ctx.EntClient.Alert.Query().
|
||||
Where(
|
||||
alert.And(
|
||||
alert.RuleCodeEQ(ruleCode),
|
||||
alert.TargetEQ(target),
|
||||
alert.StatusEQ("unread"),
|
||||
alert.CreatedAtGT(cutoff),
|
||||
),
|
||||
).
|
||||
Exist(ctx0())
|
||||
}
|
||||
|
||||
// upsertAlert 防刷写入预警:窗口内已存在相同未读预警则跳过。
|
||||
func upsertAlert(ctx *svc.ServiceContext, ruleCode, level, title, content, target string) {
|
||||
exists, err := alertExistsRecent(ctx, ruleCode, target)
|
||||
if err != nil || exists {
|
||||
return
|
||||
}
|
||||
_, _ = ctx.EntClient.Alert.Create().
|
||||
SetRuleCode(ruleCode).
|
||||
SetLevel(level).
|
||||
SetTitle(title).
|
||||
SetContent(content).
|
||||
SetTarget(target).
|
||||
Save(ctx0())
|
||||
}
|
||||
|
||||
// scanInventoryLow 库存阈值/缺货:materials.safety_stock>0 的物料,合格可用量低于安全库存则预警。
|
||||
func scanInventoryLow(ctx *svc.ServiceContext) {
|
||||
enabled, _ := getAlertRule(ctx, ruleInventoryLow)
|
||||
if !enabled {
|
||||
return
|
||||
}
|
||||
mats, err := ctx.EntClient.Material.Query().Where(material.SafetyStockGT(0)).All(ctx0())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, m := range mats {
|
||||
rows, e := ctx.EntClient.Inventory.Query().
|
||||
Where(
|
||||
inventory.And(
|
||||
inventory.MaterialCodeEQ(m.Code),
|
||||
inventory.QualityStatusEQ("合格"),
|
||||
),
|
||||
).
|
||||
All(ctx0())
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
avail := 0
|
||||
for _, inv := range rows {
|
||||
q := inv.Quantity - inv.LockedQty
|
||||
if q < 0 {
|
||||
q = 0
|
||||
}
|
||||
avail += q
|
||||
}
|
||||
if avail < m.SafetyStock {
|
||||
upsertAlert(ctx, ruleInventoryLow, "warning",
|
||||
"库存偏低:"+m.Name,
|
||||
fmt.Sprintf("物料 %s(%s) 合格可用量 %d 低于安全库存 %d,请及时补货", m.Code, m.Name, avail, m.SafetyStock),
|
||||
m.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// scanInspectionOverdue 来料检超期未检:inspection_records 仍「未检」且创建距今超阈值小时。
|
||||
func scanInspectionOverdue(ctx *svc.ServiceContext) {
|
||||
enabled, threshold := getAlertRule(ctx, ruleInspectionOver)
|
||||
if !enabled {
|
||||
return
|
||||
}
|
||||
if threshold <= 0 {
|
||||
threshold = defaultInspectionOverdueHours
|
||||
}
|
||||
cutoff := time.Now().Unix() - int64(threshold)*3600
|
||||
recs, err := ctx.EntClient.InspectionRecord.Query().
|
||||
Where(
|
||||
inspectionrecord.And(
|
||||
inspectionrecord.StatusEQ("未检"),
|
||||
inspectionrecord.CreatedAtLT(cutoff),
|
||||
),
|
||||
).
|
||||
All(ctx0())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, r := range recs {
|
||||
name := r.MaterialName
|
||||
if name == "" {
|
||||
name = r.MaterialCode
|
||||
}
|
||||
upsertAlert(ctx, ruleInspectionOver, "warning",
|
||||
"来料检超期未检:"+name,
|
||||
fmt.Sprintf("物料 %s(%s) 检验记录 %s 已超 %d 小时未检,请尽快安排检验", r.MaterialCode, name, r.TargetID, threshold),
|
||||
r.TargetID)
|
||||
}
|
||||
}
|
||||
|
||||
// scanBackupOverdue 备份超期:复用 backup 服务的 Reminder 计算,超期则产生一条预警。
|
||||
func scanBackupOverdue(ctx *svc.ServiceContext) {
|
||||
enabled, _ := getAlertRule(ctx, ruleBackupOverdue)
|
||||
if !enabled {
|
||||
return
|
||||
}
|
||||
days := CfgIntFromSysConfig(ctx, CfgArchiveRemindDays, 7)
|
||||
res, err := ctx.Backup.Reminder(days)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if res.Overdue {
|
||||
upsertAlert(ctx, ruleBackupOverdue, "warning",
|
||||
"备份超期提醒",
|
||||
fmt.Sprintf("距上次成功备份已超 %d 天,请及时进行数据归档备份", days),
|
||||
"backup")
|
||||
}
|
||||
}
|
||||
|
||||
// scanSyncFailed 物料同步失败:materials.sync_pending=true。
|
||||
func scanSyncFailed(ctx *svc.ServiceContext) {
|
||||
enabled, _ := getAlertRule(ctx, ruleSyncFailed)
|
||||
if !enabled {
|
||||
return
|
||||
}
|
||||
mats, err := ctx.EntClient.Material.Query().Where(material.SyncPendingEQ(true)).All(ctx0())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, m := range mats {
|
||||
upsertAlert(ctx, ruleSyncFailed, "error",
|
||||
"物料同步失败:"+m.Name,
|
||||
fmt.Sprintf("物料 %s(%s) 推送 MES 失败,请手动重试同步", m.Code, m.Name),
|
||||
m.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// scanInventoryAge 库龄超档:inventories qty>0 且创建距今超阈值天的库存行。
|
||||
func scanInventoryAge(ctx *svc.ServiceContext) {
|
||||
enabled, threshold := getAlertRule(ctx, ruleInventoryAge)
|
||||
if !enabled {
|
||||
return
|
||||
}
|
||||
if threshold <= 0 {
|
||||
threshold = defaultInventoryAgeDays
|
||||
}
|
||||
cutoff := time.Now().Unix() - int64(threshold)*86400
|
||||
rows, err := ctx.EntClient.Inventory.Query().
|
||||
Where(
|
||||
inventory.And(
|
||||
inventory.QuantityGT(0),
|
||||
inventory.CreatedAtLT(cutoff),
|
||||
),
|
||||
).
|
||||
All(ctx0())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, inv := range rows {
|
||||
target := "inv:" + strconv.Itoa(inv.ID)
|
||||
name := inv.MaterialName
|
||||
if name == "" {
|
||||
name = inv.MaterialCode
|
||||
}
|
||||
upsertAlert(ctx, ruleInventoryAge, "info",
|
||||
"库龄超档:"+name,
|
||||
fmt.Sprintf("物料 %s(%s) 库存行入库已超 %d 天,库龄超档请关注", inv.MaterialCode, name, threshold),
|
||||
target)
|
||||
}
|
||||
}
|
||||
|
||||
// runAlertScan 执行一轮全量扫描(先确保规则存在)。
|
||||
func runAlertScan(ctx *svc.ServiceContext) {
|
||||
ensureAlertRules(ctx)
|
||||
scanInventoryLow(ctx)
|
||||
scanInspectionOverdue(ctx)
|
||||
scanBackupOverdue(ctx)
|
||||
scanSyncFailed(ctx)
|
||||
scanInventoryAge(ctx)
|
||||
}
|
||||
|
||||
// StartAlertScanner 启动后台扫描协程:立即跑一次,之后每 5 分钟一轮。
|
||||
// 仅在服务启动期调用一次(见 bj_power_wms.go)。
|
||||
func StartAlertScanner(ctx *svc.ServiceContext) {
|
||||
go func() {
|
||||
runAlertScan(ctx)
|
||||
ticker := time.NewTicker(5 * time.Minute)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
runAlertScan(ctx)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// ===== API =====
|
||||
|
||||
// listAlertsHandler GET /api/alerts 列表(可按 status / rule_code 过滤)+ 未读总数。
|
||||
func listAlertsHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
status := q.Get("status")
|
||||
ruleCode := q.Get("rule_code")
|
||||
page := atoi(q.Get("page"), 1)
|
||||
pageSize := atoi(q.Get("pageSize"), 20)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 200 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
builder := ctx.EntClient.Alert.Query()
|
||||
if status != "" {
|
||||
builder = builder.Where(alert.StatusEQ(status))
|
||||
}
|
||||
if ruleCode != "" {
|
||||
builder = builder.Where(alert.RuleCodeEQ(ruleCode))
|
||||
}
|
||||
|
||||
total, err := builder.Count(ctx0())
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
list, err := builder.
|
||||
Order(alert.ByCreatedAt(sql.OrderDesc())).
|
||||
Offset((page - 1) * pageSize).
|
||||
Limit(pageSize).
|
||||
All(ctx0())
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
unread, err := ctx.EntClient.Alert.Query().Where(alert.StatusEQ("unread")).Count(ctx0())
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ok(w, map[string]any{
|
||||
"list": list,
|
||||
"total": total,
|
||||
"unreadCount": unread,
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// readAlertHandler POST /api/alerts/:id/read 标记单条已读。
|
||||
func readAlertHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.Atoi(pathvar.Vars(r)["id"])
|
||||
if err != nil {
|
||||
fail(w, http.StatusBadRequest, "无效的预警ID")
|
||||
return
|
||||
}
|
||||
_, err = ctx.EntClient.Alert.UpdateOneID(id).SetStatus("read").Save(ctx0())
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
ok(w, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// readAllAlertsHandler POST /api/alerts/read-all 全部已读。
|
||||
func readAllAlertsHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := ctx.EntClient.Alert.Update().
|
||||
Where(alert.StatusEQ("unread")).
|
||||
SetStatus("read").
|
||||
Save(ctx0())
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
ok(w, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// listAlertRulesHandler GET /api/alert-rules 列出规则(含启用/阈值)。
|
||||
func listAlertRulesHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
rules, err := ctx.EntClient.AlertRule.Query().Order(alertrule.ByCode()).All(ctx0())
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
ok(w, rules)
|
||||
}
|
||||
}
|
||||
|
||||
// updateAlertRuleHandler POST /api/alert-rules/update 按 code 更新 enabled/threshold/remark。
|
||||
func updateAlertRuleHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Code string `json:"code"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
Threshold *int `json:"threshold"`
|
||||
Remark *string `json:"remark"`
|
||||
}
|
||||
if err := parseJSON(r, &req); err != nil {
|
||||
fail(w, http.StatusBadRequest, "请求体解析失败:"+err.Error())
|
||||
return
|
||||
}
|
||||
if req.Code == "" {
|
||||
fail(w, http.StatusBadRequest, "规则编码不能为空")
|
||||
return
|
||||
}
|
||||
upd := ctx.EntClient.AlertRule.Update().Where(alertrule.CodeEQ(req.Code))
|
||||
if req.Enabled != nil {
|
||||
upd = upd.SetEnabled(*req.Enabled)
|
||||
}
|
||||
if req.Threshold != nil {
|
||||
upd = upd.SetThreshold(*req.Threshold)
|
||||
}
|
||||
if req.Remark != nil {
|
||||
upd = upd.SetRemark(*req.Remark)
|
||||
}
|
||||
upd = upd.SetUpdatedAt(time.Now().Unix())
|
||||
if _, err := upd.Save(ctx0()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
ok(w, nil)
|
||||
}
|
||||
}
|
||||
@@ -251,7 +251,6 @@ type attachmentViewRow struct {
|
||||
MimeType string `json:"mimeType"`
|
||||
UploadedBy string `json:"uploadedBy"`
|
||||
CreatedAt int64 `json:"createdAt"`
|
||||
Archived bool `json:"archived"`
|
||||
Deleted bool `json:"deleted"`
|
||||
DeletedAt int64 `json:"deletedAt"`
|
||||
DeletedBy string `json:"deletedBy"`
|
||||
@@ -265,7 +264,7 @@ func attachmentView(ctx *svc.ServiceContext, rec *ent.Attachment) *attachmentVie
|
||||
return &attachmentViewRow{
|
||||
ID: int64(rec.ID), BizType: rec.BizType, BizID: rec.BizID, FileType: rec.FileType,
|
||||
FileName: rec.FileName, FileSize: rec.FileSize, FileExt: rec.FileExt, MimeType: rec.MimeType,
|
||||
UploadedBy: rec.UploadedBy, CreatedAt: rec.CreatedAt, Archived: rec.Archived, Deleted: rec.Deleted,
|
||||
UploadedBy: rec.UploadedBy, CreatedAt: rec.CreatedAt, Deleted: rec.Deleted,
|
||||
DeletedAt: rec.DeletedAt, DeletedBy: rec.DeletedBy, DeletedReason: rec.DeletedReason,
|
||||
PurgedAt: rec.PurgedAt, PurgedBy: rec.PurgedBy,
|
||||
// 公开预览 URL 用磁盘 UUID 文件名(不可枚举),杜绝顺序 ID 越权遍历(安全审计 #8)
|
||||
|
||||
@@ -243,7 +243,7 @@ func doGeneralOutbound(ctx *svc.ServiceContext, req generalOutboundRequest) (str
|
||||
rec := httptest.NewRecorder()
|
||||
httpReq := httptest.NewRequest(http.MethodPost, "/api/outbound/general", bytes.NewReader(body))
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
generalOutboundHandler(ctx)(rec, httpReq)
|
||||
makeOutboundHandler(ctx, "general")(rec, httpReq)
|
||||
var env struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
|
||||
@@ -602,48 +602,8 @@ func getMaterialHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// materialTypesHandler 内部接口:批量查询物料类别(item_type)。
|
||||
// body: {"codes":["A","B"]} → data: {"types":{"A":1,"B":3}}(1原材料/3成品/4其他)。
|
||||
// 供 MES 递归展开产品物料清单使用:成品子项(item_type=3)需继续展开到原材料。
|
||||
func materialTypesHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Codes []string `json:"codes"`
|
||||
}
|
||||
if err := parseJSON(r, &req); err != nil {
|
||||
fail(w, http.StatusBadRequest, "参数错误")
|
||||
return
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
codes := []string{}
|
||||
for _, c := range req.Codes {
|
||||
c = strings.TrimSpace(c)
|
||||
if c == "" || seen[c] {
|
||||
continue
|
||||
}
|
||||
seen[c] = true
|
||||
codes = append(codes, c)
|
||||
}
|
||||
types := map[string]int{}
|
||||
if len(codes) > 0 {
|
||||
list, err := ctx.EntClient.Material.Query().
|
||||
Where(material.CodeIn(codes...)).
|
||||
Select(material.FieldCode, material.FieldItemType).
|
||||
All(ctx0())
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "查询物料类别失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
for _, m := range list {
|
||||
types[m.Code] = m.ItemType
|
||||
}
|
||||
}
|
||||
ok(w, map[string]any{"types": types})
|
||||
}
|
||||
}
|
||||
|
||||
// materialManageModesHandler 内部接口:批量查询物料「类型」(manage_mode: 1结构件/2电气件/3其他)。
|
||||
// 与 materialTypesHandler(物料类别 item_type)相互独立:物料类别=成品/组件类,类型=结构件/电气件/其他。
|
||||
// 注意:物料类别(item_type=1原材料/2半成品/3成品/4其他,成品/组件类维度)与「类型」(结构件/电气件/其他)是两个独立维度,本接口只查后者。
|
||||
// body: {"codes":["A","B"]} → data: {"manageModes": {"A":1}}(不存在的编码不返回)。
|
||||
func materialManageModesHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -144,19 +144,27 @@ type generalOutboundRequest struct {
|
||||
NeedAgv bool `json:"needAgv"` // 是否叫AGV配送到接驳台(可选)
|
||||
}
|
||||
|
||||
// generalOutboundHandler 通用出库(手动出库,不依赖工单)
|
||||
// 适用:退料 / 样品 / 报废 / 发货 等不挂靠 MES 工单的场景。
|
||||
// makeOutboundHandler 通用出库 / 科技项目出库 共用工厂(B1/B2 逻辑拆分)。
|
||||
// 两者底层完全一致(出库单 + 库存扣减 + 出库明细 原子提交;库存用条件原子更新避免负库存),
|
||||
// 仅 outboundType(单据类型)与归属(ownership) 不同:
|
||||
// - outboundType="general" → 通用出库(归属可选 合同号/其他,拒绝科技项目号)
|
||||
// - outboundType="project" → 科技项目出库(强锁归属=科技项目号)
|
||||
// 支持序列号=否(数量)与序列号=是(SN),序列号方式按物料档案 sn_mode 分叉(2026-09-30 解耦);
|
||||
// 填箱号时一并把装箱信息(箱号/SN清单/合同号)
|
||||
// 落到统一的出库主表,不再另建装箱表。
|
||||
// 事务保证:出库单 + 库存扣减 + 出库明细 原子提交;库存用条件原子更新避免负库存。
|
||||
func generalOutboundHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
// 填箱号时一并把装箱信息(箱号/SN清单/合同号)落到统一的出库主表,不再另建装箱表。
|
||||
func makeOutboundHandler(ctx *svc.ServiceContext, outboundType string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req generalOutboundRequest
|
||||
if err := parseJSON(r, &req); err != nil {
|
||||
fail(w, http.StatusBadRequest, "参数错误: "+err.Error())
|
||||
return
|
||||
}
|
||||
// B1/B2 逻辑拆分:科技项目出库(project) 与 通用出库(general) 共用本流程,仅单据类型与归属不同。
|
||||
if outboundType == "project" {
|
||||
req.OwnershipType = "project" // 科技项目出库强锁归属=科技项目号
|
||||
} else if req.OwnershipType == "project" {
|
||||
fail(w, http.StatusBadRequest, "通用出库不支持「科技项目号」归属,请使用「科技项目出库」入口")
|
||||
return
|
||||
}
|
||||
if req.MaterialCode == "" {
|
||||
fail(w, http.StatusBadRequest, "materialCode 必填")
|
||||
return
|
||||
@@ -247,7 +255,7 @@ func generalOutboundHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
pw := "" // 产品工号:从源库存取,出库单创建后回填(五页带出)
|
||||
ob, err := tx.OutboundOrder.Create().
|
||||
SetOutboundNo(outboundNo).
|
||||
SetOutboundType("general").
|
||||
SetOutboundType(outboundType).
|
||||
SetStatus("已出库").
|
||||
SetNeedAgv(req.NeedAgv).
|
||||
SetNillableTargetDock(strPtr(req.TargetDock)).
|
||||
@@ -426,15 +434,19 @@ func generalOutboundHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
}
|
||||
committed = true
|
||||
|
||||
ctx.EventLog.Write(ctx0(), "outbound.general", r.Header.Get("X-Username"), "outbound", outboundNo,
|
||||
"通用出库 "+req.MaterialCode+" ×"+itoa(actualQty),
|
||||
typeLabel := "通用出库"
|
||||
if outboundType == "project" {
|
||||
typeLabel = "科技项目出库"
|
||||
}
|
||||
ctx.EventLog.Write(ctx0(), "outbound."+outboundType, r.Header.Get("X-Username"), "outbound", outboundNo,
|
||||
typeLabel+" "+req.MaterialCode+" ×"+itoa(actualQty),
|
||||
map[string]any{"qty": actualQty, "boxNo": req.BoxNo, "snCount": len(req.SnList)})
|
||||
logx.Infof("general outbound: material=%s qty=%d box=%s", req.MaterialCode, actualQty, req.BoxNo)
|
||||
logx.Infof("%s outbound: material=%s qty=%d box=%s", outboundType, req.MaterialCode, actualQty, req.BoxNo)
|
||||
ok(w, map[string]any{
|
||||
"outboundNo": outboundNo,
|
||||
"qty": actualQty,
|
||||
"boxNo": req.BoxNo,
|
||||
"type": "general",
|
||||
"type": outboundType,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -645,6 +657,8 @@ func outboundTypeLabel(v string) string {
|
||||
return "补料出库"
|
||||
case "general":
|
||||
return "通用出库"
|
||||
case "project":
|
||||
return "科技项目出库"
|
||||
default:
|
||||
return "通用出库"
|
||||
}
|
||||
|
||||
@@ -161,6 +161,7 @@ func userDTO(u *ent.User) map[string]any {
|
||||
"isActive": u.IsActive,
|
||||
"lastLoginAt": u.LastLoginAt,
|
||||
"createdAt": u.CreatedAt,
|
||||
"updatedAt": u.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -87,7 +87,8 @@ func RegisterHandlers(server *rest.Server, ctx *svc.ServiceContext) {
|
||||
// 出库(统一主表:备料出库 workorder / 通用出库 general,装箱信息落在同一张表)
|
||||
server.AddRoutes(
|
||||
[]rest.Route{
|
||||
{Method: http.MethodPost, Path: "/api/outbound/general", Handler: generalOutboundHandler(ctx)},
|
||||
{Method: http.MethodPost, Path: "/api/outbound/general", Handler: makeOutboundHandler(ctx, "general")},
|
||||
{Method: http.MethodPost, Path: "/api/outbound/project", Handler: makeOutboundHandler(ctx, "project")},
|
||||
{Method: http.MethodGet, Path: "/api/outbound/query", Handler: queryOutboundHandler(ctx)},
|
||||
{Method: http.MethodGet, Path: "/api/outbound/export", Handler: exportOutboundHandler(ctx)},
|
||||
// 出库库位联动:优先批次在库库位,其次该物料最近一次入库库位(客户诉求 一.9「出库相同」)
|
||||
@@ -265,13 +266,31 @@ func RegisterHandlers(server *rest.Server, ctx *svc.ServiceContext) {
|
||||
},
|
||||
)
|
||||
|
||||
// 系统基础设置(admin-only):保存即生效,无需重启。
|
||||
server.AddRoutes(
|
||||
[]rest.Route{
|
||||
{Method: http.MethodGet, Path: "/api/settings", Handler: requireAdmin(SettingsHandler(ctx))},
|
||||
{Method: http.MethodPut, Path: "/api/settings", Handler: requireAdmin(SaveSettingsHandler(ctx))},
|
||||
},
|
||||
)
|
||||
// 预警中心(顶栏铃铛 + 预警列表):JWT 鉴权后注册
|
||||
server.AddRoutes(
|
||||
[]rest.Route{
|
||||
{Method: http.MethodGet, Path: "/api/alerts", Handler: listAlertsHandler(ctx)},
|
||||
{Method: http.MethodPost, Path: "/api/alerts/:id/read", Handler: readAlertHandler(ctx)},
|
||||
{Method: http.MethodPost, Path: "/api/alerts/read-all", Handler: readAllAlertsHandler(ctx)},
|
||||
{Method: http.MethodGet, Path: "/api/alert-rules", Handler: listAlertRulesHandler(ctx)},
|
||||
{Method: http.MethodPost, Path: "/api/alert-rules/update", Handler: updateAlertRuleHandler(ctx)},
|
||||
},
|
||||
)
|
||||
|
||||
// 系统基础设置(admin-only):保存即生效,无需重启。
|
||||
server.AddRoutes(
|
||||
[]rest.Route{
|
||||
{Method: http.MethodGet, Path: "/api/settings", Handler: requireAdmin(SettingsHandler(ctx))},
|
||||
{Method: http.MethodPut, Path: "/api/settings", Handler: requireAdmin(SaveSettingsHandler(ctx))},
|
||||
},
|
||||
)
|
||||
|
||||
// 本机只读信息(OS / 主机名 / Go 版本 / 端口 / 启动时间 / MES 地址):登录即可查看,修改 MES 地址需改配置文件并重启。
|
||||
server.AddRoutes(
|
||||
[]rest.Route{
|
||||
{Method: http.MethodGet, Path: "/api/system/info", Handler: SystemInfoHandler(ctx)},
|
||||
},
|
||||
)
|
||||
|
||||
// 项目间内部 API(X-API-TOKEN 写死 token 保护)
|
||||
// 与 JWT 侧业务接口同实现,仅供 MES(B)/工位终端(D) 等服务间调用
|
||||
@@ -291,7 +310,6 @@ server.AddRoutes(
|
||||
// 物料两库对等(需求一 M3/M5):MES→WMS 推送落点,按 code 幂等 upsert(删除=停用 isActive=false)
|
||||
{Method: http.MethodPost, Path: "/api/internal/materials/upsert", Handler: wrapInternal(ctx)(upsertMaterialInternalHandler(ctx))},
|
||||
{Method: http.MethodPost, Path: "/api/internal/material/exists", Handler: wrapInternal(ctx)(materialExistsHandler(ctx))},
|
||||
{Method: http.MethodPost, Path: "/api/internal/material/types", Handler: wrapInternal(ctx)(materialTypesHandler(ctx))},
|
||||
// 看板物料追溯入口复用:物料档案 + 库存查询(按编码/批次)
|
||||
{Method: http.MethodGet, Path: "/api/internal/material/query", Handler: wrapInternal(ctx)(materialQueryInternalHandler(ctx))},
|
||||
{Method: http.MethodPost, Path: "/api/internal/material/manage-modes", Handler: wrapInternal(ctx)(materialManageModesHandler(ctx))},
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"bj_power_wms/internal/svc"
|
||||
)
|
||||
|
||||
// processStartTime 进程启动时刻(包加载即服务启动,用于计算运行时长)。
|
||||
var processStartTime = time.Now()
|
||||
|
||||
// SystemInfoHandler GET /api/system/info 只读本机信息面板数据。
|
||||
// 含 OS / 主机名 / Go 版本 / 监听端口 / 启动时间 / MES 地址(MES 地址只读,修改需改配置文件并重启)。
|
||||
func SystemInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
host, _ := os.Hostname()
|
||||
c := svcCtx.Config
|
||||
ok(w, map[string]any{
|
||||
"os": runtime.GOOS,
|
||||
"hostname": host,
|
||||
"goVersion": runtime.Version(),
|
||||
"port": c.Port,
|
||||
"startTime": processStartTime.Unix(),
|
||||
"uptimeSeconds": int64(time.Since(processStartTime).Seconds()),
|
||||
"mesAddress": c.Mes.BaseURL,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,17 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"bj_power_wms/ent"
|
||||
"bj_power_wms/ent/inboundorder"
|
||||
"bj_power_wms/ent/inventory"
|
||||
"bj_power_wms/ent/outboundorder"
|
||||
"bj_power_wms/ent/stocktakeitem"
|
||||
"bj_power_wms/ent/zone"
|
||||
"bj_power_wms/internal/svc"
|
||||
)
|
||||
@@ -19,6 +24,18 @@ const (
|
||||
zoneLevelPos = 4
|
||||
)
|
||||
|
||||
// zoneGenLocks 进程内互斥表:按父级键串行化「查重+创建」,弥补「不建唯一索引」下的并发重复编码(规则5)。
|
||||
// WMS 为单进程部署,进程内锁即可;若未来多实例需改为 pg_advisory_xact_lock。
|
||||
var zoneGenLocks sync.Map
|
||||
|
||||
// zoneGenLock 对给定父级键加锁,返回解锁函数(配合 defer 使用)。
|
||||
func zoneGenLock(key string) func() {
|
||||
v, _ := zoneGenLocks.LoadOrStore(key, &sync.Mutex{})
|
||||
mu := v.(*sync.Mutex)
|
||||
mu.Lock()
|
||||
return func() { mu.Unlock() }
|
||||
}
|
||||
|
||||
func zoneLevelName(l int) string {
|
||||
switch l {
|
||||
case 1:
|
||||
@@ -33,6 +50,77 @@ func zoneLevelName(l int) string {
|
||||
return "节点"
|
||||
}
|
||||
|
||||
// zoneSuffix 各级编码后缀(规则3):区域=N区 / 货架=N架 / 层=N层 / 位置号=N号
|
||||
func zoneSuffix(level int) string {
|
||||
switch level {
|
||||
case 1:
|
||||
return "区"
|
||||
case 2:
|
||||
return "架"
|
||||
case 3:
|
||||
return "层"
|
||||
case 4:
|
||||
return "号"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// zoneTrailingNum 提取编码尾部连续数字("1区"->1、"12架"->12、"7"->7);无数字返回 0。
|
||||
// 自增引擎据此在同父级下找最大尾部数字 +1,兼容纯数字与「N+后缀」两种历史格式。
|
||||
func zoneTrailingNum(code string) int {
|
||||
code = strings.TrimSpace(code)
|
||||
i := len(code) - 1
|
||||
for i >= 0 && code[i] >= '0' && code[i] <= '9' {
|
||||
i--
|
||||
}
|
||||
if i == len(code)-1 {
|
||||
return 0
|
||||
}
|
||||
n, err := strconv.Atoi(code[i+1:])
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// nextZoneCode 计算某父级下下一个编码:取同父级现有节点尾部数字最大值 +1,拼后缀。
|
||||
// 父级约束:level1 无父;level2 按 zoneCode(区域);level3 按 zoneCode+shelfNo;level4 按 zoneCode+shelfNo+layerNo。
|
||||
func nextZoneCode(ctx *svc.ServiceContext, level int, zoneCode, shelfNo, layerNo string) (string, error) {
|
||||
q := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(level))
|
||||
switch level {
|
||||
case 2:
|
||||
q = q.Where(zone.ZoneCodeEQ(zoneCode))
|
||||
case 3:
|
||||
q = q.Where(zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(shelfNo))
|
||||
case 4:
|
||||
q = q.Where(zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(shelfNo), zone.LayerNoEQ(layerNo))
|
||||
}
|
||||
nodes, err := q.All(ctx0())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
max := 0
|
||||
for _, n := range nodes {
|
||||
if v := zoneTrailingNum(n.Code); v > max {
|
||||
max = v
|
||||
}
|
||||
}
|
||||
return strconv.Itoa(max+1) + zoneSuffix(level), nil
|
||||
}
|
||||
|
||||
// zoneDefaultName 默认名称(规则4):区域/货架=编码本身;层=区域-货架-层;位置号=区域-货架-层-位置号
|
||||
func zoneDefaultName(level int, code, zoneCode, shelfNo, layerNo string) string {
|
||||
switch level {
|
||||
case 1, 2:
|
||||
return code
|
||||
case 3:
|
||||
return zoneCode + "-" + shelfNo + "-" + code
|
||||
case 4:
|
||||
return zoneCode + "-" + shelfNo + "-" + layerNo + "-" + code
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
// zoneNodeVO 层级节点视图对象(列表/下拉共用)
|
||||
type zoneNodeVO struct {
|
||||
ID int `json:"id"`
|
||||
@@ -265,16 +353,28 @@ func createZoneNodeHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
fail(w, http.StatusBadRequest, "level 必须为 1~4")
|
||||
return
|
||||
}
|
||||
if req.Code == "" {
|
||||
fail(w, http.StatusBadRequest, "编码必填")
|
||||
// 层/位置号只能通过「批量生成」创建,禁止单条手填(规则2)
|
||||
if req.Level == 3 || req.Level == 4 {
|
||||
fail(w, http.StatusBadRequest, "层级/位置号只能通过“批量生成”创建,不可单条新增")
|
||||
return
|
||||
}
|
||||
// 并发防重(规则5):同父级「查重+创建」加进程内互斥,弥补无唯一索引
|
||||
unlock := zoneGenLock(fmt.Sprintf("z:%d:%s:%s:%s", req.Level, req.ZoneCode, req.ShelfNo, req.LayerNo))
|
||||
defer unlock()
|
||||
// 编码自增引擎(规则3):区域/货架新建时若未填编码,自动取同父级最大尾部数字+1 拼后缀
|
||||
if req.Code == "" {
|
||||
nc, err := nextZoneCode(ctx, req.Level, req.ZoneCode, req.ShelfNo, req.LayerNo)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
req.Code = nc
|
||||
}
|
||||
if req.Level == 1 {
|
||||
req.Code = strings.ToUpper(req.Code)
|
||||
if req.Name == "" {
|
||||
fail(w, http.StatusBadRequest, "区域名称必填")
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.Name == "" {
|
||||
req.Name = zoneDefaultName(req.Level, req.Code, req.ZoneCode, req.ShelfNo, req.LayerNo)
|
||||
}
|
||||
|
||||
// 逐级解析父级:父级必须已存在,路径(区域+货架+层)唯一确定,避免仅凭 code 跨父级歧义。
|
||||
@@ -360,11 +460,12 @@ func createZoneNodeHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
}
|
||||
|
||||
type zoneNodeUpdateReq struct {
|
||||
ID int `json:"id"`
|
||||
Code string `json:"code"` // 仅 level=4 位置号允许改编码;货架/层/区域忽略(避免级联子节点与库存的破坏性重命名)
|
||||
Name string `json:"name"`
|
||||
Remark string `json:"remark"`
|
||||
Status string `json:"status"`
|
||||
ID int `json:"id"`
|
||||
Code string `json:"code"` // 已不再用于编辑编码(编码锁定,见规则2)
|
||||
Name string `json:"name"`
|
||||
Remark string `json:"remark"`
|
||||
Status string `json:"status"`
|
||||
ZoneCode string `json:"zoneCode"` // 仅 level=2 货架允许改所属区域(整体搬家),级联子孙层/位置与库存
|
||||
}
|
||||
|
||||
// updateZoneNodeHandler 编辑节点(四级均可改名称/备注/启用停用;区域额外同步 zone_name 冗余)。
|
||||
@@ -393,59 +494,57 @@ func updateZoneNodeHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
fail(w, http.StatusBadRequest, "状态取值非法")
|
||||
return
|
||||
}
|
||||
// 位置号(level4)放开编辑:允许改编码(支持字符串,如 P-01);同步冗余 position_no 并级联库存,避免库存挂空。
|
||||
// 货架/层/区域编码维持不可改(重命名会级联全部子节点+库存,破坏性,需单独裁决)。
|
||||
renamedCode := ""
|
||||
if z.Level == zoneLevelPos {
|
||||
newCode := strings.ToUpper(strings.TrimSpace(req.Code))
|
||||
if newCode == "" {
|
||||
fail(w, http.StatusBadRequest, "位置号必填")
|
||||
// 层/位置号不可编辑(规则2):只允许区域/货架编辑名称/备注/状态
|
||||
if z.Level == zoneLevelLayer || z.Level == zoneLevelPos {
|
||||
fail(w, http.StatusBadRequest, "层级/位置号不支持编辑,只能通过批量生成管理")
|
||||
return
|
||||
}
|
||||
// 货架(level2)改所属区域(整体搬家):级联子孙层/位置 zone_code 与库存 zone_code(规则:所属货架/层不可改,但货架可整体换区)
|
||||
newZone := strings.ToUpper(strings.TrimSpace(req.ZoneCode))
|
||||
if z.Level == zoneLevelShelf && newZone != "" && newZone != z.ZoneCode {
|
||||
reg, rerr := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(zoneLevelRegion), zone.CodeEQ(newZone)).Only(ctx0())
|
||||
if rerr != nil {
|
||||
fail(w, http.StatusBadRequest, "目标区域不存在:"+newZone)
|
||||
return
|
||||
}
|
||||
if newCode != z.Code {
|
||||
dup, _ := ctx.EntClient.Zone.Query().
|
||||
Where(zone.LevelEQ(zoneLevelPos), zone.ZoneCodeEQ(z.ZoneCode),
|
||||
zone.ShelfNoEQ(z.ShelfNo), zone.LayerNoEQ(z.LayerNo),
|
||||
zone.CodeEQ(newCode), zone.Not(zone.IDEQ(z.ID))).Exist(ctx0())
|
||||
if dup {
|
||||
fail(w, http.StatusConflict, "该位置号已存在:"+newCode)
|
||||
return
|
||||
}
|
||||
renamedCode = newCode
|
||||
shelfNo := z.ShelfNo
|
||||
if _, err := ctx.EntClient.Zone.Update().Where(zone.IDEQ(z.ID)).SetZoneCode(newZone).SetParentCode(reg.Code).Save(ctx0()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "货架改区域失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := ctx.EntClient.Zone.Update().Where(zone.ShelfNoEQ(shelfNo)).SetZoneCode(newZone).Save(ctx0()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "级联层/位置失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := ctx.EntClient.Inventory.Update().Where(inventory.ShelfNoEQ(shelfNo), inventory.ZoneCodeEQ(z.ZoneCode)).SetZoneCode(newZone).Save(ctx0()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "级联库存失败(inventories): "+err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := ctx.EntClient.InboundOrder.Update().Where(inboundorder.ShelfNoEQ(shelfNo), inboundorder.ZoneCodeEQ(z.ZoneCode)).SetZoneCode(newZone).Save(ctx0()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "级联库存失败(inbound_orders): "+err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := ctx.EntClient.OutboundOrder.Update().Where(outboundorder.ShelfNoEQ(shelfNo), outboundorder.ZoneCodeEQ(z.ZoneCode)).SetZoneCode(newZone).Save(ctx0()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "级联库存失败(outbound_orders): "+err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := ctx.EntClient.StocktakeItem.Update().Where(stocktakeitem.ShelfNoEQ(shelfNo), stocktakeitem.ZoneCodeEQ(z.ZoneCode)).SetZoneCode(newZone).Save(ctx0()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "级联库存失败(stocktake_items): "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
upd := ctx.EntClient.Zone.UpdateOneID(req.ID).SetStatus(status).
|
||||
SetName(strings.TrimSpace(req.Name)).
|
||||
SetNillableDescription(strPtr(strings.TrimSpace(req.Remark)))
|
||||
if renamedCode != "" {
|
||||
upd.SetCode(renamedCode).SetNillablePositionNo(strPtr(renamedCode))
|
||||
}
|
||||
if z.Level == 1 {
|
||||
upd.SetZoneName(strings.TrimSpace(req.Name)) // 区域名称冗余同步
|
||||
}
|
||||
// 位置号重命名:先级联库存 position_no(用旧码定位→新码),再落库 zone,保证库存不挂空。
|
||||
if renamedCode != "" {
|
||||
if _, err := ctx.EntClient.Inventory.Update().
|
||||
Where(inventory.ZoneCodeEQ(z.ZoneCode), inventory.ShelfNoEQ(z.ShelfNo),
|
||||
inventory.LayerNoEQ(z.LayerNo), inventory.PositionNoEQ(z.Code)).
|
||||
SetPositionNo(renamedCode).Save(ctx0()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "级联更新库存位置号失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if _, err := upd.Save(ctx0()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
finalCode := z.Code
|
||||
if renamedCode != "" {
|
||||
finalCode = renamedCode
|
||||
}
|
||||
logMsg := "编辑" + zoneLevelName(z.Level) + " " + finalCode
|
||||
if renamedCode != "" {
|
||||
logMsg = "位置号更名 " + z.Code + " → " + renamedCode + "(已级联库存 position_no)"
|
||||
}
|
||||
ctx.EventLog.Write(ctx0(), "zone.update", r.Header.Get("X-Username"), "zone", finalCode, logMsg, nil)
|
||||
logMsg := "编辑" + zoneLevelName(z.Level) + " " + z.Code
|
||||
ctx.EventLog.Write(ctx0(), "zone.update", r.Header.Get("X-Username"), "zone", z.Code, logMsg, nil)
|
||||
ok(w, map[string]any{"id": req.ID})
|
||||
}
|
||||
}
|
||||
@@ -568,18 +667,14 @@ func listZonesForPicker(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
}
|
||||
|
||||
type zoneBatchGenReq struct {
|
||||
ZoneCode string `json:"zoneCode"`
|
||||
ShelfNo string `json:"shelfNo"`
|
||||
LayerStart int `json:"layerStart"` // level=3 批量生成层:层范围起
|
||||
LayerEnd int `json:"layerEnd"` // level=3 批量生成层:层范围止
|
||||
LayerNo string `json:"layerNo"` // level=4 批量生成位置号:层号(必须为已存在的层)
|
||||
PosStart int `json:"posStart"`
|
||||
PosEnd int `json:"posEnd"`
|
||||
Count int `json:"count"` // level=4 批量生成位置号:生成数量(从「该层最大位置号+1」起连续生成)
|
||||
Level int `json:"level"` // 3=批量生成层(level3) 4=批量生成位置号(level4,默认,需指定已存在的层)
|
||||
Preview bool `json:"preview"`
|
||||
Layers []zoneBatchLayerName `json:"layers"` // level=3 提交时携带预览表中(可能手改过的)层名称,非空则优先采用
|
||||
Positions []zoneBatchPosName `json:"positions"` // level=4 提交时携带预览表中(可能手改过的)位置名称,非空则优先采用
|
||||
ZoneCode string `json:"zoneCode"`
|
||||
ShelfNo string `json:"shelfNo"`
|
||||
LayerNo string `json:"layerNo"` // level=4 批量生成位置号:层号(必须为已存在的层)
|
||||
Count int `json:"count"` // level=3 生成层 / level=4 生成位置号:均从「该父级最大尾部数字+1」起连续生成
|
||||
Level int `json:"level"` // 3=批量生成层(level3) 4=批量生成位置号(level4,默认,需指定已存在的层)
|
||||
Preview bool `json:"preview"`
|
||||
Layers []zoneBatchLayerName `json:"layers"` // level=3 提交时携带预览表中(可能手改过的)层名称,非空则优先采用
|
||||
Positions []zoneBatchPosName `json:"positions"` // level=4 提交时携带预览表中(可能手改过的)位置名称,非空则优先采用
|
||||
}
|
||||
|
||||
// zoneBatchLayerName 批量生成层:前端预览后手改的层名称(layerNo→layerName)
|
||||
@@ -621,18 +716,14 @@ func batchGenerateHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
}
|
||||
zoneCode := sh.ZoneCode
|
||||
|
||||
// ---------- level=3:批量生成层节点(父级货架必须已存在,只生成层自己) ----------
|
||||
// ---------- level=3:批量生成层节点(父级货架必须已存在,按「数量」从 max+1 连续生成) ----------
|
||||
if level == 3 {
|
||||
if req.LayerStart < 0 || req.LayerEnd < req.LayerStart {
|
||||
fail(w, http.StatusBadRequest, "层起止不合法(起始需 ≤ 结束,且 ≥ 0)")
|
||||
if req.Count <= 0 {
|
||||
fail(w, http.StatusBadRequest, "请填写生成数量(≥1)")
|
||||
return
|
||||
}
|
||||
layers := make([]int, 0)
|
||||
for l := req.LayerStart; l <= req.LayerEnd; l++ {
|
||||
layers = append(layers, l)
|
||||
}
|
||||
if len(layers) > 2000 {
|
||||
fail(w, http.StatusBadRequest, "一次最多生成 2000 个层,请缩小范围")
|
||||
if req.Count > 2000 {
|
||||
fail(w, http.StatusBadRequest, "一次最多生成 2000 个层,请缩小数量")
|
||||
return
|
||||
}
|
||||
type genLayer struct {
|
||||
@@ -640,6 +731,14 @@ func batchGenerateHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
LayerName string `json:"layerName"`
|
||||
Exists bool `json:"exists"`
|
||||
}
|
||||
// 现有层最大尾部数字(兼容纯数字与 N层 两种历史格式)
|
||||
maxNo := 0
|
||||
cur, _ := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(3), zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(req.ShelfNo)).All(ctx0())
|
||||
for _, p := range cur {
|
||||
if v := zoneTrailingNum(p.Code); v > maxNo {
|
||||
maxNo = v
|
||||
}
|
||||
}
|
||||
// 手改层名称优先:前端预览后可点击层名称修改,提交时按 layerNo 带回
|
||||
nameByNo := make(map[string]string, len(req.Layers))
|
||||
for _, ly := range req.Layers {
|
||||
@@ -649,12 +748,12 @@ func batchGenerateHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
nameByNo[no] = nm
|
||||
}
|
||||
}
|
||||
layerList := make([]genLayer, 0, len(layers))
|
||||
for _, l := range layers {
|
||||
ls := strconv.Itoa(l)
|
||||
layerList := make([]genLayer, 0, req.Count)
|
||||
for i := 1; i <= req.Count; i++ {
|
||||
ls := strconv.Itoa(maxNo+i) + "层"
|
||||
exists, _ := ctx.EntClient.Zone.Query().
|
||||
Where(zone.LevelEQ(3), zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(req.ShelfNo), zone.CodeEQ(ls)).Exist(ctx0())
|
||||
name := req.ShelfNo + "架" + ls + "层"
|
||||
name := zoneDefaultName(3, ls, zoneCode, req.ShelfNo, ls)
|
||||
if v, ok := nameByNo[ls]; ok {
|
||||
name = v
|
||||
}
|
||||
@@ -664,6 +763,9 @@ func batchGenerateHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
ok(w, map[string]any{"preview": true, "level": 3, "list": layerList, "total": len(layerList)})
|
||||
return
|
||||
}
|
||||
// 并发防重(规则5):同货架下的「查重+创建」加进程内互斥
|
||||
unlock := zoneGenLock(fmt.Sprintf("z:3:%s:%s:", zoneCode, req.ShelfNo))
|
||||
defer unlock()
|
||||
createdL, skippedL := 0, 0
|
||||
for _, it := range layerList {
|
||||
if it.Exists {
|
||||
@@ -680,9 +782,8 @@ func batchGenerateHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
createdL++
|
||||
}
|
||||
ctx.EventLog.Write(ctx0(), "zone.batch", r.Header.Get("X-Username"), "zone", req.ShelfNo,
|
||||
"批量生成层 "+req.ZoneCode+"/"+req.ShelfNo+" 层"+strconv.Itoa(req.LayerStart)+"-"+strconv.Itoa(req.LayerEnd)+
|
||||
":新建"+strconv.Itoa(createdL)+" 跳过"+strconv.Itoa(skippedL), nil)
|
||||
ok(w, map[string]any{"preview": false, "level": 3, "created": createdL, "skipped": skippedL, "total": len(layers)})
|
||||
"批量生成层 "+req.ZoneCode+"/"+req.ShelfNo+" 从"+(strconv.Itoa(maxNo+1))+"起生成"+strconv.Itoa(req.Count)+"个:新建"+strconv.Itoa(createdL)+" 跳过"+strconv.Itoa(skippedL), nil)
|
||||
ok(w, map[string]any{"preview": false, "level": 3, "created": createdL, "skipped": skippedL, "total": req.Count})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -705,12 +806,12 @@ func batchGenerateHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
fail(w, http.StatusBadRequest, "层不存在,请先在层管理里创建")
|
||||
return
|
||||
}
|
||||
// 最近编码序号:该层下已存在的最大位置号(按整数解析,非整数忽略)
|
||||
// 最近编码序号:该层下已存在的最大位置号(取编码尾部数字,兼容纯数字与 N号 两种格式)
|
||||
maxNo := 0
|
||||
cur, _ := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(4), zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(req.ShelfNo), zone.LayerNoEQ(layerNo)).All(ctx0())
|
||||
for _, p := range cur {
|
||||
if n, err := strconv.Atoi(p.Code); err == nil && n > maxNo {
|
||||
maxNo = n
|
||||
if v := zoneTrailingNum(p.Code); v > maxNo {
|
||||
maxNo = v
|
||||
}
|
||||
}
|
||||
// 预览:从 maxNo+1 起连续生成 N 个,标注是否已存在(按层号+位置号去重跳过)
|
||||
@@ -722,14 +823,17 @@ func batchGenerateHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
}
|
||||
preview := make([]genItem, 0, req.Count)
|
||||
for i := 1; i <= req.Count; i++ {
|
||||
ps := strconv.Itoa(maxNo + i)
|
||||
ps := strconv.Itoa(maxNo+i) + "号"
|
||||
exists, _ := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(4), zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(req.ShelfNo), zone.LayerNoEQ(layerNo), zone.CodeEQ(ps)).Exist(ctx0())
|
||||
preview = append(preview, genItem{LayerNo: layerNo, PositionNo: ps, PositionName: req.ShelfNo + "架" + layerNo + "层" + ps + "位", Exists: exists})
|
||||
preview = append(preview, genItem{LayerNo: layerNo, PositionNo: ps, PositionName: zoneDefaultName(4, ps, zoneCode, req.ShelfNo, layerNo), Exists: exists})
|
||||
}
|
||||
if req.Preview {
|
||||
ok(w, map[string]any{"preview": true, "list": preview, "total": len(preview)})
|
||||
return
|
||||
}
|
||||
// 并发防重(规则5):同层下的「查重+创建」加进程内互斥
|
||||
unlock := zoneGenLock(fmt.Sprintf("z:4:%s:%s:%s", zoneCode, req.ShelfNo, layerNo))
|
||||
defer unlock()
|
||||
// 提交:创建不存在的位置号(按层号+位置号去重跳过);手改位置名称优先采用
|
||||
nameByPos := make(map[string]string, len(req.Positions))
|
||||
for _, pn := range req.Positions {
|
||||
@@ -741,12 +845,12 @@ func batchGenerateHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||||
}
|
||||
created, skipped := 0, 0
|
||||
for i := 1; i <= req.Count; i++ {
|
||||
ps := strconv.Itoa(maxNo + i)
|
||||
ps := strconv.Itoa(maxNo+i) + "号"
|
||||
if exist, _ := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(4), zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(req.ShelfNo), zone.LayerNoEQ(layerNo), zone.CodeEQ(ps)).Exist(ctx0()); exist {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
name := req.ShelfNo + "架" + layerNo + "层" + ps + "位"
|
||||
name := zoneDefaultName(4, ps, zoneCode, req.ShelfNo, layerNo)
|
||||
if v, ok := nameByPos[ps]; ok {
|
||||
name = v
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user