Files
bj_power/bj_power_wms/internal/handler/call.go
T

323 lines
12 KiB
Go
Raw Normal View History

package handler
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"bj_power_wms/ent"
"bj_power_wms/ent/inventory"
"bj_power_wms/ent/outboundorder"
"bj_power_wms/internal/mesclient"
"bj_power_wms/internal/svc"
"bj_power_wms/internal/syncfailure"
"github.com/zeromicro/go-zero/core/logx"
)
// ============ B5 叫料队列(仓库端,2026-10-13 定稿) ============
// 入口:WMS「叫料队列」页(JWT + call:view/call:manage)。
// 完成备料 = WMS 本地 FIFO 选库存 → 通用出库(类别「叫料配送」)→ 通知 MES /call/complete;
// MES 不反向调 WMS 出库(主控裁定:库存动作归 WMS,减少环、降低失败面)。
// callPendingHandler GET /api/call/pending 叫料队列:待备料叫料单(代理 MES 内部列表)。
// 支持 stationNo / materialCode / requestNo 过滤(不区分大小写由 MES 侧处理)。
func callPendingHandler(ctx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if ctx.Mes == nil {
fail(w, http.StatusInternalServerError, "MES 未配置,无法拉取叫料队列")
return
}
list, err := ctx.Mes.ListMaterialRequests(r.Context(), "PENDING")
if err != nil {
fail(w, http.StatusBadGateway, "拉取 MES 叫料队列失败: "+err.Error())
return
}
stationNo := strings.TrimSpace(r.URL.Query().Get("stationNo"))
materialCode := strings.TrimSpace(r.URL.Query().Get("materialCode"))
requestNo := strings.TrimSpace(r.URL.Query().Get("requestNo"))
out := make([]mesclient.MaterialRequest, 0, len(list))
for _, m := range list {
if stationNo != "" && strconv.Itoa(m.StationNo) != stationNo {
continue
}
if materialCode != "" && !strings.Contains(strings.ToLower(m.MaterialCode), strings.ToLower(materialCode)) {
continue
}
if requestNo != "" && !strings.Contains(strings.ToLower(m.RequestNo), strings.ToLower(requestNo)) {
continue
}
out = append(out, m)
}
ok(w, map[string]any{"total": len(out), "list": out})
}
}
// callCompleteHandler POST /api/call/complete 仓库完成备料(点「完成」一键:选库存→出库→通知 MES→派车)。
// body: {requestNo}。实发量由 WMS 库存实况确定(缺多少发多少,差额 MES 自动释放)。
func callCompleteHandler(ctx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if ctx.Mes == nil {
fail(w, http.StatusInternalServerError, "MES 未配置,无法完成备料")
return
}
var req struct {
RequestNo string `json:"requestNo"`
}
if err := parseJSON(r, &req); err != nil || strings.TrimSpace(req.RequestNo) == "" {
fail(w, http.StatusBadRequest, "缺少叫料单号")
return
}
operator := r.Header.Get("X-Username")
if operator == "" {
operator = "warehouse"
}
// 幂等守卫(2026-11-08 Bug2):本单若已在 WMS 出过库,说明前一次「完成备料」的
// 出库已提交、只是通知 MES 失败。此处只重发通知,绝不重跑 doGeneralOutbound 造成重复出库。
// 判定完全基于 WMS 本地出库单 remark 精确等值,不依赖任何 MES 接口(MES 不可达时仍生效)。
prior, perr := ctx.EntClient.OutboundOrder.Query().
Where(outboundorder.RemarkEQ("叫料单 "+strings.TrimSpace(req.RequestNo)),
outboundorder.VoidedEQ(false)).All(r.Context())
if perr == nil && len(prior) > 0 {
priorSent := 0
priorNos := make([]string, 0, len(prior))
for _, ob := range prior {
priorSent += ob.Quantity
priorNos = append(priorNos, ob.OutboundNo)
}
priorJoined := strings.Join(priorNos, ",")
notify := map[string]any{
"requestNo": req.RequestNo, "sentQty": priorSent,
"outboundNo": priorJoined, "operator": operator,
}
if cerr := ctx.Mes.CallComplete(r.Context(), req.RequestNo, float64(priorSent), priorJoined, operator); cerr != nil {
syncfailure.Record(ctx.SQLDB, "WMS→MES", "call.complete", req.RequestNo,
"/api/internal/call/complete", notify, cerr.Error())
fail(w, http.StatusBadGateway, "已出库,通知MES失败,请在同步失败台账重试通知: "+cerr.Error())
return
}
ok(w, map[string]any{
"requestNo": req.RequestNo, "sentQty": priorSent, "reqQty": priorSent,
"outboundNos": priorJoined, "short": 0, "agvNote": "(已出库,仅重发通知)",
})
return
}
// 1. 取 MES 叫料单并校验状态
list, err := ctx.Mes.ListMaterialRequests(r.Context(), "PENDING")
if err != nil {
fail(w, http.StatusBadGateway, "拉取 MES 叫料单失败: "+err.Error())
return
}
var call *mesclient.MaterialRequest
for i := range list {
if list[i].RequestNo == req.RequestNo {
call = &list[i]
break
}
}
if call == nil {
fail(w, http.StatusNotFound, "叫料单不存在或已不是待备料状态(可能已被其他仓库处理)")
return
}
// 2026-11-09 用户拍板 A(案例.md:100/108/565):期望接驳台是叫料时的
// 「非必填意向」,可留空;实际接驳台由库管在「建配送单」时选定(只能空台)。
// 本层是「完成备料」(叫料层),故允许 TargetDock 为空,不再硬拒。
// 配送单创建 / 派车的 TargetDock 必填仍保留在 delivery.go:128-131 与 :371-373:
// 叫料层可空 ≠ 配送单层可空,两层不得混淆。
need := int(call.ReqQty + 0.5)
if need <= 0 {
fail(w, http.StatusBadRequest, "叫料单请求量异常")
return
}
// 借料来源透传(库房知情权):排除本工位自取项,仅保留真正借出的兄弟工位
borrowForWMS := map[string]int{}
for k, v := range call.BorrowFrom {
if k == strconv.Itoa(call.StationNo) {
continue
}
if v > 0 {
borrowForWMS[k] = v
}
}
// 2. FIFO 选库存(口径同 /api/internal/stock/batches:在库 + 合格 + 未锁定部分)
rows, err := ctx.EntClient.Inventory.Query().
Where(
inventory.MaterialCodeEQ(call.MaterialCode),
inventory.QuantityGT(0),
inventory.QualityStatusIn(QStatusPass),
inventory.StatusEQ("在库"),
).
Order(ent.Asc("batch_no"), ent.Asc("created_at")).
All(ctx0())
if err != nil {
fail(w, http.StatusInternalServerError, "查询库存失败: "+err.Error())
return
}
type pick struct {
batchNo string
sn string
take int
}
picks := make([]pick, 0, 4)
remain := need
2026-11-05 19:18:18 +08:00
totalAvail := 0
for _, inv := range rows {
if remain <= 0 {
break
}
avail := inv.Quantity - inv.LockedQty
if avail <= 0 {
continue
}
take := avail
if take > remain {
take = remain
}
if call.SnMode == 1 {
// 序列号=是:逐件(每行 quantity=1)
if inv.SnCode == "" {
continue
}
picks = append(picks, pick{sn: inv.SnCode, take: 1})
2026-11-05 19:18:18 +08:00
totalAvail++
remain--
continue
}
if inv.SnMode == snModeBatch {
picks = append(picks, pick{batchNo: inv.BatchNo, take: take})
2026-11-05 19:18:18 +08:00
totalAvail += avail
remain -= take
}
}
if len(picks) == 0 {
2026-11-05 19:18:18 +08:00
fail(w, http.StatusConflict, "缺料无法完成备料:物料「"+call.MaterialName+"("+call.MaterialCode+")」工位 "+strconv.Itoa(call.StationNo)+" 请求量 "+itoa(need)+",合格可用量 "+itoa(totalAvail)+",请先补入库或走补料审批")
return
}
// 3. 逐批通用出库(类别=叫料配送;目标接驳台=叫料单目标;进程内复用通用出库全链路)
outboundNos := make([]string, 0, len(picks))
sentTotal := 0
for _, p := range picks {
payload := generalOutboundRequest{
MaterialCode: call.MaterialCode,
Qty: p.take,
Operator: operator,
OutboundCategory: "call",
Remark: "叫料单 " + call.RequestNo,
TargetDock: call.TargetDock,
TargetStation: strconv.Itoa(call.StationNo),
NeedAgv: call.NeedAgv,
BorrowFrom: borrowForWMS,
}
if p.sn != "" {
payload.SnList = []string{p.sn}
} else {
payload.BatchNo = p.batchNo
}
obNo, obQty, gerr := doGeneralOutbound(ctx, payload)
if gerr != nil {
fail(w, http.StatusInternalServerError, "出库失败(物料 "+call.MaterialCode+"):"+gerr.Error())
return
}
outboundNos = append(outboundNos, obNo)
sentTotal += obQty
}
if sentTotal <= 0 {
fail(w, http.StatusInternalServerError, "出库结果异常:实发量为 0")
return
}
// 4. 通知 MES 完成备料(状态迁移 + 四数账;失败不阻断出库事实,返回出库单号供重试)
joined := strings.Join(outboundNos, ",")
if cerr := ctx.Mes.CallComplete(r.Context(), call.RequestNo, float64(sentTotal), joined, operator); cerr != nil {
logx.Errorf("call complete notify MES failed: requestNo=%s err=%v", call.RequestNo, cerr)
// 出库已提交,不回滚;落失败台账供人工重试(best-effort,写失败只打日志不阻断)
syncfailure.Record(ctx.SQLDB, "WMS→MES", "call.complete", call.RequestNo,
"/api/internal/call/complete", map[string]any{
"requestNo": call.RequestNo, "sentQty": sentTotal,
"outboundNo": joined, "operator": operator,
}, cerr.Error())
fail(w, http.StatusBadGateway, "已出库(单号 "+joined+"),通知MES失败,请在同步失败台账重试通知: "+cerr.Error())
return
}
// 5. AGV 自动派车已交由 MES 在「完成备料」内统一触发(best-effort),WMS 不再本地下发海康 RCS
agvNote := "(AGV 由 MES 自动派车)"
ok(w, map[string]any{
"requestNo": call.RequestNo, "sentQty": sentTotal, "reqQty": need,
"outboundNos": joined, "short": need - sentTotal, "agvNote": agvNote,
})
}
}
// callRejectHandler POST /api/call/reject 仓库驳回叫料单(仅待备料;理由必填,异常标记:非当日等)。
func callRejectHandler(ctx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if ctx.Mes == nil {
fail(w, http.StatusInternalServerError, "MES 未配置")
return
}
var req struct {
RequestNo string `json:"requestNo"`
Reason string `json:"reason"`
}
if err := parseJSON(r, &req); err != nil || strings.TrimSpace(req.RequestNo) == "" {
fail(w, http.StatusBadRequest, "缺少叫料单号")
return
}
if strings.TrimSpace(req.Reason) == "" {
fail(w, http.StatusBadRequest, "驳回必须填写理由")
return
}
operator := r.Header.Get("X-Username")
if operator == "" {
operator = "warehouse"
}
if err := ctx.Mes.CallReject(r.Context(), req.RequestNo, strings.TrimSpace(req.Reason), operator); err != nil {
fail(w, http.StatusBadGateway, "驳回失败: "+err.Error())
return
}
ok(w, map[string]any{"requestNo": req.RequestNo})
}
}
// doGeneralOutbound 进程内复用通用出库全链路(事务/扣减/单号/冻结守卫零重复实现)。
// 返回出库单号与实发量;HTTP 层错误以 error 返回(message 透出)。
func doGeneralOutbound(ctx *svc.ServiceContext, req generalOutboundRequest) (string, int, error) {
body, merr := json.Marshal(req)
if merr != nil {
return "", 0, merr
}
rec := httptest.NewRecorder()
httpReq := httptest.NewRequest(http.MethodPost, "/api/outbound/general", bytes.NewReader(body))
httpReq.Header.Set("Content-Type", "application/json")
makeOutboundHandler(ctx, "general")(rec, httpReq)
var env struct {
Code int `json:"code"`
Message string `json:"message"`
Data struct {
OutboundNo string `json:"outboundNo"`
Qty int `json:"qty"`
} `json:"data"`
}
if derr := json.Unmarshal(rec.Body.Bytes(), &env); derr != nil {
return "", 0, derr
}
if env.Code != 0 {
return "", 0, errors.New(env.Message)
}
return env.Data.OutboundNo, env.Data.Qty, nil
}
// dispatchAgv 已移除(2026-10-14 AGV 唯一真源迁 MES):WMS 完成备料后由 MES 在 /api/internal/call/complete
// 内部统一触发海康 RCS 派车,WMS 不再本地持有 RCS 客户端,避免双真源/双派车。