867 lines
34 KiB
Go
867 lines
34 KiB
Go
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"
|
||
)
|
||
|
||
// 层级常量:区域(level1) → 货架(level2) → 层(level3) → 位置号(level4)
|
||
const (
|
||
zoneLevelRegion = 1
|
||
zoneLevelShelf = 2
|
||
zoneLevelLayer = 3
|
||
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:
|
||
return "区域"
|
||
case 2:
|
||
return "货架"
|
||
case 3:
|
||
return "层"
|
||
case 4:
|
||
return "位置号"
|
||
}
|
||
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"`
|
||
Level int `json:"level"`
|
||
Code string `json:"code"`
|
||
Name string `json:"name"`
|
||
ParentCode string `json:"parentCode"`
|
||
ZoneCode string `json:"zoneCode"`
|
||
ZoneName string `json:"zoneName"`
|
||
ShelfNo string `json:"shelfNo"`
|
||
LayerNo string `json:"layerNo"`
|
||
PositionNo string `json:"positionNo"`
|
||
Status string `json:"status"`
|
||
Description string `json:"description"`
|
||
CreatedAt int64 `json:"createdAt"`
|
||
// StockQty 本级实时库存总量(需求E/需求7):每次查询实时聚合 inventories(quantity>0 且 status∈{在库,锁定} 且非半成品),不缓存。
|
||
// level1=区域合计、level2=货架合计、level3=层合计、level4=该位置合计。
|
||
StockQty int `json:"stockQty"`
|
||
// UnshelvedQty 区域级「未分配货架」库存合计(货位为空但已填区域的合法状态,见库存口径说明);仅 level1 有意义。
|
||
UnshelvedQty int `json:"unshelvedQty"`
|
||
// IsSynthetic 是否为合成行(如「(未分配货架)」虚拟货架);合成行不可编辑/删除,仅用于展示未上架库存。
|
||
IsSynthetic bool `json:"isSynthetic"`
|
||
}
|
||
|
||
func toZoneNodeVO(z *ent.Zone) zoneNodeVO {
|
||
return zoneNodeVO{
|
||
ID: z.ID, Level: z.Level, Code: z.Code, Name: z.Name, ParentCode: z.ParentCode,
|
||
ZoneCode: z.ZoneCode, ZoneName: z.ZoneName, ShelfNo: z.ShelfNo, LayerNo: z.LayerNo,
|
||
PositionNo: z.PositionNo, Status: z.Status, Description: z.Description, CreatedAt: z.CreatedAt,
|
||
}
|
||
}
|
||
|
||
// listZonesHandler 按层级列出节点(4 个 Tab 各自独立分页 + 按上级筛选)
|
||
// 参数:level(必填1~4)、parentCode、zoneCode、shelfNo、layerNo、code、name、status、page、pageSize
|
||
func listZonesHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
level := atoi(r.URL.Query().Get("level"), 0)
|
||
if level < 1 || level > 4 {
|
||
fail(w, http.StatusBadRequest, "level 必须为 1~4")
|
||
return
|
||
}
|
||
page := atoi(r.URL.Query().Get("page"), 1)
|
||
pageSize := atoi(r.URL.Query().Get("pageSize"), 20)
|
||
if page <= 0 {
|
||
page = 1
|
||
}
|
||
if pageSize <= 0 {
|
||
pageSize = 20
|
||
}
|
||
if pageSize > 200 {
|
||
pageSize = 200
|
||
}
|
||
|
||
q := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(level))
|
||
if pc := strings.TrimSpace(r.URL.Query().Get("parentCode")); pc != "" {
|
||
q = q.Where(zone.ParentCodeEQ(pc))
|
||
}
|
||
if zc := strings.TrimSpace(r.URL.Query().Get("zoneCode")); zc != "" {
|
||
q = q.Where(zone.ZoneCodeEQ(strings.ToUpper(zc)))
|
||
}
|
||
if sh := strings.TrimSpace(r.URL.Query().Get("shelfNo")); sh != "" {
|
||
q = q.Where(zone.ShelfNoEQ(sh))
|
||
}
|
||
if ly := strings.TrimSpace(r.URL.Query().Get("layerNo")); ly != "" {
|
||
q = q.Where(zone.LayerNoEQ(ly))
|
||
}
|
||
// 列表页禁止关键字混搜:本节点编码、名称各自独立模糊筛选(需求N)
|
||
if code := strings.TrimSpace(r.URL.Query().Get("code")); code != "" {
|
||
q = q.Where(zone.CodeContainsFold(code))
|
||
}
|
||
if name := strings.TrimSpace(r.URL.Query().Get("name")); name != "" {
|
||
q = q.Where(zone.NameContainsFold(name))
|
||
}
|
||
if st := strings.TrimSpace(r.URL.Query().Get("status")); st != "" {
|
||
q = q.Where(zone.StatusEQ(st))
|
||
}
|
||
|
||
total, err := q.Count(ctx0())
|
||
if err != nil {
|
||
fail(w, http.StatusInternalServerError, err.Error())
|
||
return
|
||
}
|
||
rows, err := q.Order(ent.Asc("code"), ent.Asc("id")).
|
||
Offset((page - 1) * pageSize).Limit(pageSize).All(ctx0())
|
||
if err != nil {
|
||
fail(w, http.StatusInternalServerError, err.Error())
|
||
return
|
||
}
|
||
list := make([]zoneNodeVO, 0, len(rows))
|
||
byZone, byShelf, byLayer, byPos, byUnshelved := zoneStockMaps(ctx)
|
||
// 区域名称回填:zone_name 冗余字段仅 level1 区域行有值;子层级(货架/层/位置号)按 zone_code 反查所属区域名称。
|
||
zoneNameByCode := map[string]string{}
|
||
zcKeys := make([]string, 0)
|
||
for _, z := range rows {
|
||
if z.Level != zoneLevelRegion && z.ZoneCode != "" {
|
||
k := strings.ToUpper(strings.TrimSpace(z.ZoneCode))
|
||
if _, ok := zoneNameByCode[k]; !ok {
|
||
zcKeys = append(zcKeys, k)
|
||
}
|
||
}
|
||
}
|
||
if len(zcKeys) > 0 {
|
||
if regs, err := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(zoneLevelRegion), zone.CodeIn(zcKeys...)).All(ctx0()); err == nil {
|
||
for _, rg := range regs {
|
||
zoneNameByCode[strings.ToUpper(strings.TrimSpace(rg.Code))] = rg.Name
|
||
}
|
||
}
|
||
}
|
||
for _, z := range rows {
|
||
vo := toZoneNodeVO(z)
|
||
if z.Level != zoneLevelRegion {
|
||
vo.ZoneName = zoneNameByCode[strings.ToUpper(strings.TrimSpace(z.ZoneCode))]
|
||
}
|
||
zc := strings.ToLower(strings.TrimSpace(z.ZoneCode))
|
||
sh := strings.ToLower(strings.TrimSpace(z.ShelfNo))
|
||
ly := strings.TrimSpace(z.LayerNo)
|
||
switch z.Level {
|
||
case zoneLevelRegion:
|
||
vo.StockQty = byZone[zc]
|
||
vo.UnshelvedQty = byUnshelved[zc]
|
||
case zoneLevelShelf:
|
||
vo.StockQty = byShelf[zc+"|"+sh]
|
||
case zoneLevelLayer:
|
||
vo.StockQty = byLayer[zc+"|"+sh+"|"+ly]
|
||
case zoneLevelPos:
|
||
vo.StockQty = byPos[locKey(z.ZoneCode, z.ShelfNo, z.LayerNo, z.PositionNo)]
|
||
}
|
||
list = append(list, vo)
|
||
}
|
||
// 货架(level2)列表置顶固定合成行「(未分配货架)」:汇总本页所属区域的未上架库存,
|
||
// 灰显不可编辑,不参与分页计数(见库存口径说明:缺货位为合法状态)。
|
||
if level == zoneLevelShelf {
|
||
unshelvedTotal := 0
|
||
seenZc := map[string]bool{}
|
||
for _, z2 := range rows {
|
||
zc2 := strings.ToLower(strings.TrimSpace(z2.ZoneCode))
|
||
if !seenZc[zc2] {
|
||
seenZc[zc2] = true
|
||
unshelvedTotal += byUnshelved[zc2]
|
||
}
|
||
}
|
||
if unshelvedTotal > 0 && len(rows) > 0 {
|
||
synth := zoneNodeVO{
|
||
Level: zoneLevelShelf,
|
||
Code: "",
|
||
Name: "(未分配货架)",
|
||
ZoneCode: rows[0].ZoneCode,
|
||
ZoneName: rows[0].ZoneName,
|
||
Status: "启用",
|
||
StockQty: unshelvedTotal,
|
||
IsSynthetic: true,
|
||
}
|
||
list = append([]zoneNodeVO{synth}, list...)
|
||
}
|
||
}
|
||
// 区域(level1)列表置顶固定合成行「(未分区)」:zone_code 为空的库存合计(入库不强制货位的合法状态),
|
||
// 与货架级「(未分配货架)」同款处理:灰显不可编辑,不参与分页计数;使区域维护页与区域汇总/库位明细的「未分区」行对账一致。
|
||
if level == zoneLevelRegion {
|
||
if unpartitioned := byZone[""]; unpartitioned > 0 {
|
||
synth := zoneNodeVO{
|
||
Level: zoneLevelRegion,
|
||
Code: "",
|
||
Name: "(未分区)",
|
||
Status: "启用",
|
||
StockQty: unpartitioned,
|
||
UnshelvedQty: byUnshelved[""],
|
||
IsSynthetic: true,
|
||
}
|
||
list = append([]zoneNodeVO{synth}, list...)
|
||
}
|
||
}
|
||
ok(w, map[string]any{"total": total, "list": list, "page": page, "pageSize": pageSize})
|
||
}
|
||
}
|
||
|
||
// zoneStockMaps 实时聚合各级库存总量(需求E):一次扫描在库 inventories(quantity>0 且 status∈{在库,锁定} 且非半成品),
|
||
// 分别按 区域 / 区域+货架 / 区域+货架+层 / 完整四级货位 累加,供四级列表展示实时库存。
|
||
// byUnshelved 为区域级「未分配货架」库存合计(货位为空但已填区域的合法状态),供未上架标识与合成行使用。
|
||
// 键归一与 locKey 一致:区域/货架小写,层/位置原样 trim。
|
||
func zoneStockMaps(ctx *svc.ServiceContext) (byZone, byShelf, byLayer, byPos, byUnshelved map[string]int) {
|
||
byZone, byShelf, byLayer, byPos, byUnshelved = map[string]int{}, map[string]int{}, map[string]int{}, map[string]int{}, map[string]int{}
|
||
invs, err := ctx.EntClient.Inventory.Query().
|
||
Where(inventory.QuantityGT(0), inventory.StatusIn("在库", "锁定"), inventory.CategoryNEQ(invCatSemi)).All(ctx0())
|
||
if err != nil {
|
||
return
|
||
}
|
||
for _, iv := range invs {
|
||
zc := strings.ToLower(strings.TrimSpace(iv.ZoneCode))
|
||
sh := strings.ToLower(strings.TrimSpace(iv.ShelfNo))
|
||
ly := strings.TrimSpace(iv.LayerNo)
|
||
byZone[zc] += iv.Quantity
|
||
byShelf[zc+"|"+sh] += iv.Quantity
|
||
byLayer[zc+"|"+sh+"|"+ly] += iv.Quantity
|
||
byPos[locKey(iv.ZoneCode, iv.ShelfNo, iv.LayerNo, iv.PositionNo)] += iv.Quantity
|
||
if sh == "" {
|
||
byUnshelved[zc] += iv.Quantity
|
||
}
|
||
}
|
||
return
|
||
}
|
||
|
||
// zoneNodeReq 新建层级节点请求。
|
||
// 父级以完整路径给出(区域→货架→层),后端据此精确定位父级,避免仅凭 code 跨父级歧义。
|
||
type zoneNodeReq struct {
|
||
Level int `json:"level"`
|
||
Code string `json:"code"`
|
||
Name string `json:"name"`
|
||
ZoneCode string `json:"zoneCode"` // 所属区域编码(level>=2 必填)
|
||
ShelfNo string `json:"shelfNo"` // 所属货架号(level>=3 必填)
|
||
LayerNo string `json:"layerNo"` // 所属层号(level=4 必填)
|
||
Remark string `json:"remark"`
|
||
}
|
||
|
||
// createZoneNodeHandler 新建层级节点(按完整路径 区域→货架→层 精确定位父级并写冗余路径)。
|
||
// 父级必须存在且不能为空;位置号(level4)必须挂在已存在的层下(不再有“无层默认位置”)。
|
||
func createZoneNodeHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
var req zoneNodeReq
|
||
if err := parseJSON(r, &req); err != nil {
|
||
fail(w, http.StatusBadRequest, "参数错误")
|
||
return
|
||
}
|
||
req.Code = strings.TrimSpace(req.Code)
|
||
req.Name = strings.TrimSpace(req.Name)
|
||
req.ZoneCode = strings.ToUpper(strings.TrimSpace(req.ZoneCode))
|
||
req.ShelfNo = strings.TrimSpace(req.ShelfNo)
|
||
req.LayerNo = strings.TrimSpace(req.LayerNo)
|
||
req.Remark = strings.TrimSpace(req.Remark)
|
||
if req.Level < 1 || req.Level > 4 {
|
||
fail(w, http.StatusBadRequest, "level 必须为 1~4")
|
||
return
|
||
}
|
||
// 层/位置号只能通过「批量生成」创建,禁止单条手填(规则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 == "" {
|
||
req.Name = zoneDefaultName(req.Level, req.Code, req.ZoneCode, req.ShelfNo, req.LayerNo)
|
||
}
|
||
|
||
// 逐级解析父级:父级必须已存在,路径(区域+货架+层)唯一确定,避免仅凭 code 跨父级歧义。
|
||
var zoneCode, shelfNo, layerNo, parentCode string
|
||
switch req.Level {
|
||
case 1:
|
||
zoneCode = req.Code
|
||
parentCode = ""
|
||
case 2:
|
||
if req.ZoneCode == "" {
|
||
fail(w, http.StatusBadRequest, "请选择所属区域")
|
||
return
|
||
}
|
||
reg, err := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(1), zone.CodeEQ(req.ZoneCode)).Only(ctx0())
|
||
if err != nil {
|
||
fail(w, http.StatusBadRequest, "所属区域不存在:"+req.ZoneCode)
|
||
return
|
||
}
|
||
zoneCode = reg.ZoneCode
|
||
shelfNo = req.Code
|
||
parentCode = reg.Code
|
||
case 3:
|
||
if req.ZoneCode == "" || req.ShelfNo == "" {
|
||
fail(w, http.StatusBadRequest, "请选择所属区域与货架")
|
||
return
|
||
}
|
||
sh, err := ctx.EntClient.Zone.Query().
|
||
Where(zone.LevelEQ(2), zone.ZoneCodeEQ(req.ZoneCode), zone.CodeEQ(req.ShelfNo)).Only(ctx0())
|
||
if err != nil {
|
||
fail(w, http.StatusBadRequest, "所属货架不存在:"+req.ZoneCode+"/"+req.ShelfNo)
|
||
return
|
||
}
|
||
zoneCode = sh.ZoneCode
|
||
shelfNo = sh.ShelfNo
|
||
layerNo = req.Code
|
||
parentCode = sh.Code
|
||
case 4:
|
||
if req.ZoneCode == "" || req.ShelfNo == "" || req.LayerNo == "" {
|
||
fail(w, http.StatusBadRequest, "请选择所属层")
|
||
return
|
||
}
|
||
ly, err := ctx.EntClient.Zone.Query().
|
||
Where(zone.LevelEQ(3), zone.ZoneCodeEQ(req.ZoneCode), zone.ShelfNoEQ(req.ShelfNo), zone.CodeEQ(req.LayerNo)).Only(ctx0())
|
||
if err != nil {
|
||
fail(w, http.StatusBadRequest, "所属层不存在:"+req.ZoneCode+"/"+req.ShelfNo+"/"+req.LayerNo)
|
||
return
|
||
}
|
||
zoneCode = ly.ZoneCode
|
||
shelfNo = ly.ShelfNo
|
||
layerNo = ly.Code
|
||
parentCode = ly.Code
|
||
}
|
||
|
||
// 唯一性:同层级 + 同区域 + 同货架 + 同层 + 同编码 不可重复
|
||
dup, _ := ctx.EntClient.Zone.Query().
|
||
Where(zone.LevelEQ(req.Level), zone.ZoneCodeEQ(zoneCode),
|
||
zone.ShelfNoEQ(shelfNo), zone.LayerNoEQ(layerNo), zone.CodeEQ(req.Code)).
|
||
Exist(ctx0())
|
||
if dup {
|
||
fail(w, http.StatusConflict, "该编码已存在:"+req.Code)
|
||
return
|
||
}
|
||
|
||
create := ctx.EntClient.Zone.Create().
|
||
SetLevel(req.Level).SetCode(req.Code).SetParentCode(parentCode).
|
||
SetZoneCode(zoneCode).SetNillableShelfNo(strPtr(shelfNo)).
|
||
SetNillableLayerNo(strPtr(layerNo)).SetNillablePositionNo(strPtr(req.Code)).
|
||
SetStatus("启用").SetNillableDescription(strPtr(req.Remark)).
|
||
SetName(req.Name) // 四级均可有名称(需求E)
|
||
if req.Level == 1 {
|
||
create.SetZoneName(req.Name) // 区域名称冗余,兼容 stock.go 区域名映射
|
||
}
|
||
z, err := create.Save(ctx0())
|
||
if err != nil {
|
||
fail(w, http.StatusInternalServerError, err.Error())
|
||
return
|
||
}
|
||
|
||
ctx.EventLog.Write(ctx0(), "zone.create", r.Header.Get("X-Username"), "zone", req.Code,
|
||
"新建"+zoneLevelName(req.Level)+" "+req.Code, nil)
|
||
ok(w, toZoneNodeVO(z))
|
||
}
|
||
}
|
||
|
||
type zoneNodeUpdateReq struct {
|
||
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 冗余)。
|
||
// 需求E:不删只停用,无删除入口;名称与备注全级可维护。
|
||
func updateZoneNodeHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
var req zoneNodeUpdateReq
|
||
if err := parseJSON(r, &req); err != nil {
|
||
fail(w, http.StatusBadRequest, "参数错误")
|
||
return
|
||
}
|
||
if req.ID <= 0 {
|
||
fail(w, http.StatusBadRequest, "id 必填")
|
||
return
|
||
}
|
||
z, err := ctx.EntClient.Zone.Get(ctx0(), req.ID)
|
||
if err != nil {
|
||
fail(w, http.StatusNotFound, "节点不存在")
|
||
return
|
||
}
|
||
status := req.Status
|
||
if status == "" {
|
||
status = z.Status
|
||
}
|
||
if status != "启用" && status != "停用" {
|
||
fail(w, http.StatusBadRequest, "状态取值非法")
|
||
return
|
||
}
|
||
// 层/位置号:编码仍锁定(只能批量生成管理),但名称/备注/状态放开编辑(2026-11-02 修复"名称修改不了")
|
||
// 名称变更同步:层/位置号无冗余字段,仅 zone.name;货架/区域逻辑不变。
|
||
// 货架(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
|
||
}
|
||
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 z.Level == 1 {
|
||
upd.SetZoneName(strings.TrimSpace(req.Name)) // 区域名称冗余同步
|
||
}
|
||
if _, err := upd.Save(ctx0()); err != nil {
|
||
fail(w, http.StatusInternalServerError, err.Error())
|
||
return
|
||
}
|
||
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})
|
||
}
|
||
}
|
||
|
||
// listZonesForPicker 库位下拉(兼容 + 层级两用):
|
||
// - 不带 level:返回所有启用位置号(level4)扁平结构(兼容 Outbound/Stocktake/Inventory 旧调用)
|
||
// - 带 level:返回该层级节点(用于入库页区域→货架→层→位置 级联下拉)
|
||
//
|
||
// locKey 四级货位比较键:区域/货架忽略大小写(存量数据存在 z01/Z01 混用),层/位置原样。
|
||
func locKey(zoneCode, shelfNo, layerNo, positionNo string) string {
|
||
return strings.ToLower(strings.TrimSpace(zoneCode)) + "|" +
|
||
strings.ToLower(strings.TrimSpace(shelfNo)) + "|" +
|
||
strings.TrimSpace(layerNo) + "|" + strings.TrimSpace(positionNo)
|
||
}
|
||
|
||
// vacantZoneHandler 同区空位推荐:返回指定区域(不传 zoneCode 则不限区域)内「未被库存占用」的位置节点(level=4)。
|
||
// 用途:入库选中物料后,若该物料无历史库位(新物料),自动推荐同区空位,替代人工逐个挑选货架/层/位置。
|
||
// 占用判定:inventories 中 quantity>0 且 status 非「出库/报废」的记录,其四级货位视为已占用。
|
||
func vacantZoneHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
wantZone := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("zoneCode")))
|
||
limit := atoi(r.URL.Query().Get("limit"), 20)
|
||
if limit <= 0 || limit > 200 {
|
||
limit = 20
|
||
}
|
||
rows, err := ctx.EntClient.Zone.Query().
|
||
Where(zone.LevelEQ(zoneLevelPos), zone.StatusEQ("启用")).
|
||
Order(ent.Asc("zone_code"), ent.Asc("shelf_no"), ent.Asc("layer_no"), ent.Asc("code")).
|
||
All(ctx0())
|
||
if err != nil {
|
||
fail(w, http.StatusInternalServerError, err.Error())
|
||
return
|
||
}
|
||
occupied := map[string]bool{}
|
||
if invs, ierr := ctx.EntClient.Inventory.Query().
|
||
Where(inventory.QuantityGT(0), inventory.StatusNotIn("出库", "报废")).
|
||
All(ctx0()); ierr == nil {
|
||
for _, iv := range invs {
|
||
occupied[locKey(iv.ZoneCode, iv.ShelfNo, iv.LayerNo, iv.PositionNo)] = true
|
||
}
|
||
}
|
||
list := make([]map[string]any, 0, limit)
|
||
for _, z := range rows {
|
||
if wantZone != "" && strings.ToLower(z.ZoneCode) != wantZone {
|
||
continue
|
||
}
|
||
if occupied[locKey(z.ZoneCode, z.ShelfNo, z.LayerNo, z.PositionNo)] {
|
||
continue
|
||
}
|
||
list = append(list, map[string]any{
|
||
"zoneCode": z.ZoneCode, "zoneName": z.ZoneName, "shelfNo": z.ShelfNo,
|
||
"layerNo": z.LayerNo, "positionNo": z.PositionNo, "name": z.Name, "code": z.Code,
|
||
})
|
||
if len(list) >= limit {
|
||
break
|
||
}
|
||
}
|
||
ok(w, list)
|
||
}
|
||
}
|
||
|
||
func listZonesForPicker(ctx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
level := atoi(r.URL.Query().Get("level"), 0)
|
||
status := strings.TrimSpace(r.URL.Query().Get("status"))
|
||
if level == 0 {
|
||
q := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(4))
|
||
if status == "" {
|
||
q = q.Where(zone.StatusEQ("启用"))
|
||
} else {
|
||
q = q.Where(zone.StatusEQ(status))
|
||
}
|
||
rows, err := q.Order(ent.Asc("code")).All(ctx0())
|
||
if err != nil {
|
||
fail(w, http.StatusInternalServerError, err.Error())
|
||
return
|
||
}
|
||
list := make([]map[string]any, 0, len(rows))
|
||
for _, z := range rows {
|
||
list = append(list, map[string]any{
|
||
"zoneCode": z.ZoneCode, "zoneName": z.ZoneName, "shelfNo": z.ShelfNo,
|
||
"layerNo": z.LayerNo, "positionNo": z.PositionNo, "name": z.Name, "code": z.Code,
|
||
})
|
||
}
|
||
ok(w, list)
|
||
return
|
||
}
|
||
q := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(level))
|
||
if pc := strings.TrimSpace(r.URL.Query().Get("parentCode")); pc != "" {
|
||
q = q.Where(zone.ParentCodeEQ(pc))
|
||
}
|
||
if zc := strings.TrimSpace(r.URL.Query().Get("zoneCode")); zc != "" {
|
||
q = q.Where(zone.ZoneCodeEQ(strings.ToUpper(zc)))
|
||
}
|
||
if sh := strings.TrimSpace(r.URL.Query().Get("shelfNo")); sh != "" {
|
||
q = q.Where(zone.ShelfNoEQ(sh))
|
||
}
|
||
if ly := strings.TrimSpace(r.URL.Query().Get("layerNo")); ly != "" {
|
||
q = q.Where(zone.LayerNoEQ(ly))
|
||
}
|
||
if status == "" {
|
||
q = q.Where(zone.StatusEQ("启用"))
|
||
} else {
|
||
q = q.Where(zone.StatusEQ(status))
|
||
}
|
||
rows, err := q.Order(ent.Asc("code")).All(ctx0())
|
||
if err != nil {
|
||
fail(w, http.StatusInternalServerError, err.Error())
|
||
return
|
||
}
|
||
list := make([]map[string]any, 0, len(rows))
|
||
for _, z := range rows {
|
||
list = append(list, map[string]any{
|
||
"id": z.ID, "level": z.Level, "code": z.Code, "name": z.Name,
|
||
"parentCode": z.ParentCode, "zoneCode": z.ZoneCode, "shelfNo": z.ShelfNo, "layerNo": z.LayerNo,
|
||
})
|
||
}
|
||
ok(w, list)
|
||
}
|
||
}
|
||
|
||
type zoneBatchGenReq struct {
|
||
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)
|
||
type zoneBatchLayerName struct {
|
||
LayerNo string `json:"layerNo"`
|
||
LayerName string `json:"layerName"`
|
||
}
|
||
|
||
// zoneBatchPosName 批量生成位置号:前端预览后手改的位置名称(positionNo→positionName)
|
||
type zoneBatchPosName struct {
|
||
PositionNo string `json:"positionNo"`
|
||
PositionName string `json:"positionName"`
|
||
}
|
||
|
||
// batchGenerateHandler 批量生成库位节点:选区域→货架→范围,先预览后提交。
|
||
// level=3:只生成「层」节点(按层范围);level=4(默认):在「已存在的具体层」下生成「位置号」节点。
|
||
// 批量生成只生成自己这一级,绝不自动创建父级;已存在的节点跳过不重复建。
|
||
func batchGenerateHandler(ctx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
var req zoneBatchGenReq
|
||
if err := parseJSON(r, &req); err != nil {
|
||
fail(w, http.StatusBadRequest, "参数错误")
|
||
return
|
||
}
|
||
req.ZoneCode = strings.ToUpper(strings.TrimSpace(req.ZoneCode))
|
||
req.ShelfNo = strings.TrimSpace(req.ShelfNo)
|
||
if req.ZoneCode == "" || req.ShelfNo == "" {
|
||
fail(w, http.StatusBadRequest, "请选择区域与货架")
|
||
return
|
||
}
|
||
level := req.Level
|
||
if level != 3 {
|
||
level = 4
|
||
}
|
||
sh, err := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(2), zone.ZoneCodeEQ(req.ZoneCode), zone.CodeEQ(req.ShelfNo)).Only(ctx0())
|
||
if err != nil {
|
||
fail(w, http.StatusBadRequest, "货架不存在:"+req.ZoneCode+"/"+req.ShelfNo)
|
||
return
|
||
}
|
||
zoneCode := sh.ZoneCode
|
||
|
||
// ---------- level=3:批量生成层节点(父级货架必须已存在,按「数量」从 max+1 连续生成) ----------
|
||
if level == 3 {
|
||
if req.Count <= 0 {
|
||
fail(w, http.StatusBadRequest, "请填写生成数量(≥1)")
|
||
return
|
||
}
|
||
if req.Count > 2000 {
|
||
fail(w, http.StatusBadRequest, "一次最多生成 2000 个层,请缩小数量")
|
||
return
|
||
}
|
||
type genLayer struct {
|
||
LayerNo string `json:"layerNo"`
|
||
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 {
|
||
no := strings.TrimSpace(ly.LayerNo)
|
||
nm := strings.TrimSpace(ly.LayerName)
|
||
if no != "" && nm != "" {
|
||
nameByNo[no] = nm
|
||
}
|
||
}
|
||
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 := zoneDefaultName(3, ls, zoneCode, req.ShelfNo, ls)
|
||
if v, ok := nameByNo[ls]; ok {
|
||
name = v
|
||
}
|
||
layerList = append(layerList, genLayer{LayerNo: ls, LayerName: name, Exists: exists})
|
||
}
|
||
if req.Preview {
|
||
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 {
|
||
skippedL++
|
||
continue
|
||
}
|
||
if _, err := ctx.EntClient.Zone.Create().
|
||
SetLevel(3).SetCode(it.LayerNo).SetParentCode(req.ShelfNo).
|
||
SetZoneCode(zoneCode).SetShelfNo(req.ShelfNo).SetLayerNo(it.LayerNo).
|
||
SetName(it.LayerName).SetStatus("启用").Save(ctx0()); err != nil {
|
||
fail(w, http.StatusInternalServerError, "创建层失败: "+err.Error())
|
||
return
|
||
}
|
||
createdL++
|
||
}
|
||
ctx.EventLog.Write(ctx0(), "zone.batch", r.Header.Get("X-Username"), "zone", req.ShelfNo,
|
||
"批量生成层 "+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
|
||
}
|
||
|
||
// ---------- level=4:批量生成位置号(必须选已存在的层,按最近编码序号+1 生成 N 个) ----------
|
||
layerNo := strings.ToUpper(strings.TrimSpace(req.LayerNo))
|
||
if layerNo == "" {
|
||
fail(w, http.StatusBadRequest, "请选择具体的层")
|
||
return
|
||
}
|
||
if req.Count <= 0 {
|
||
fail(w, http.StatusBadRequest, "请填写生成数量(≥1)")
|
||
return
|
||
}
|
||
if req.Count > 2000 {
|
||
fail(w, http.StatusBadRequest, "一次最多生成 2000 个位置,请缩小数量")
|
||
return
|
||
}
|
||
// 层级字段用下拉选择,层必须已存在;不存在则报错,不自动创建
|
||
if exist, _ := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(3), zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(req.ShelfNo), zone.CodeEQ(layerNo)).Exist(ctx0()); !exist {
|
||
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 v := zoneTrailingNum(p.Code); v > maxNo {
|
||
maxNo = v
|
||
}
|
||
}
|
||
// 预览:从 maxNo+1 起连续生成 N 个,标注是否已存在(按层号+位置号去重跳过)
|
||
type genItem struct {
|
||
LayerNo string `json:"layerNo"`
|
||
PositionNo string `json:"positionNo"`
|
||
PositionName string `json:"positionName"`
|
||
Exists bool `json:"exists"`
|
||
}
|
||
preview := make([]genItem, 0, req.Count)
|
||
for i := 1; i <= req.Count; 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: 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 {
|
||
no := strings.TrimSpace(pn.PositionNo)
|
||
nm := strings.TrimSpace(pn.PositionName)
|
||
if no != "" && nm != "" {
|
||
nameByPos[no] = nm
|
||
}
|
||
}
|
||
created, skipped := 0, 0
|
||
for i := 1; i <= req.Count; 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 := zoneDefaultName(4, ps, zoneCode, req.ShelfNo, layerNo)
|
||
if v, ok := nameByPos[ps]; ok {
|
||
name = v
|
||
}
|
||
if _, err := ctx.EntClient.Zone.Create().SetLevel(4).SetCode(ps).SetParentCode(layerNo).SetZoneCode(zoneCode).SetShelfNo(req.ShelfNo).SetLayerNo(layerNo).SetPositionNo(ps).SetName(name).SetStatus("启用").Save(ctx0()); err != nil {
|
||
fail(w, http.StatusInternalServerError, "创建位置失败: "+err.Error())
|
||
return
|
||
}
|
||
created++
|
||
}
|
||
ctx.EventLog.Write(ctx0(), "zone.batch", r.Header.Get("X-Username"), "zone", req.ShelfNo,
|
||
"批量生成位置 "+req.ZoneCode+"/"+req.ShelfNo+" 层"+layerNo+
|
||
" 从"+(strconv.Itoa(maxNo+1))+"起生成"+strconv.Itoa(req.Count)+"个:新建"+strconv.Itoa(created)+" 跳过"+strconv.Itoa(skipped), nil)
|
||
ok(w, map[string]any{"preview": false, "created": created, "skipped": skipped, "total": req.Count})
|
||
|
||
}
|
||
}
|