- MES 新增损耗台账 loss_ledger,差异确认损耗接口 ConfirmReceiveLoss(按工单归集) - 备料清单 preparation:MES 按 日计划×工单×工位×物料 实时计算,WMS 只读展示 PreparationList - 退料闭环:N5 工位托盘守卫(未完成禁止退料)、退料 AGV 自动派车(JBT21 空位判定 + 托盘回收链路)、退料参考剩余量接口(应剩余=实备-已耗-已退-已损) - 新增 AGV 车辆状态表 agv_vehicle_state 及查询 - 整合接驳台/叫料池/库存锁既有闭环,清理 sql 目录注释生成脚本与 catalog,更新文档
814 lines
29 KiB
Go
814 lines
29 KiB
Go
package wmsclient
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"net/url"
|
||
"strconv"
|
||
"strings"
|
||
"sync/atomic"
|
||
"time"
|
||
)
|
||
|
||
// Client WMS 内部接口客户端(半成品流转等)
|
||
// baseURL 支持运行时热切换(系统管理员「基础设置」页保存 WMS 地址后 SetBaseURL 即生效),
|
||
// 因此用 atomic.Value 存储,读侧无需加锁。
|
||
type Client struct {
|
||
baseURL atomic.Value // string
|
||
token string
|
||
hc *http.Client
|
||
}
|
||
|
||
// defaultBaseURL 未配置 WMS 地址时的兜底值
|
||
const defaultBaseURL = "http://127.0.0.1:9091"
|
||
|
||
func New(baseURL, token string) *Client {
|
||
c := &Client{
|
||
token: token,
|
||
hc: &http.Client{Timeout: 5 * time.Second},
|
||
}
|
||
c.SetBaseURL(baseURL)
|
||
return c
|
||
}
|
||
|
||
// SetBaseURL 热切换 WMS 地址;空串回退默认地址。
|
||
// 注意:所有请求路径都以 "/api/..." 开头,这里必须去掉尾斜杠,否则拼出 "//api" 404。
|
||
func (c *Client) SetBaseURL(u string) {
|
||
u = strings.TrimSpace(u)
|
||
if u == "" {
|
||
u = defaultBaseURL
|
||
}
|
||
u = strings.TrimRight(u, "/")
|
||
c.baseURL.Store(u)
|
||
}
|
||
|
||
// BaseURL 当前生效的 WMS 地址(不带尾斜杠,请求路径以 /api/... 开头直接拼接)
|
||
func (c *Client) BaseURL() string {
|
||
return c.baseURL.Load().(string)
|
||
}
|
||
|
||
// SemiPayload MES→WMS 半成品入库/出库载荷。
|
||
// 归属三字段(2026-09-30):半成品归属自动继承其产品工号的工单归属——
|
||
// ownershipType/ownershipNo 取自工单归属(workorder=合同号/project=科技项目号/other=其他),
|
||
// productWorkNo=产品工号(即工单号),均由 MES 从工单带出后传入,不做人工手选。
|
||
type SemiPayload struct {
|
||
Sn string
|
||
OrderNo string
|
||
CompletedText string
|
||
Operator string
|
||
OwnershipType string // 归属类型:workorder=合同号/project=科技项目号/other=其他
|
||
OwnershipNo string // 归属编号(合同号或科技项目号)
|
||
ProductWorkNo string // 产品工号(=所属工单号)
|
||
}
|
||
|
||
// SemiInbound 调 WMS /api/internal/semi/inbound 半成品入库。
|
||
// 统一契约:payload={sn,orderNo,completedText,operator,ownershipType,ownershipNo,productWorkNo},
|
||
// completedText 由 MES 生成("已完成至工位N",N=workpiece.currentStationNo;0/无记录传空串),
|
||
// 旧 doneProcessCodes 已废除。
|
||
func (c *Client) SemiInbound(ctx context.Context, p SemiPayload) error {
|
||
return c.postSemi(ctx, "/api/internal/semi/inbound", map[string]any{
|
||
"sn": p.Sn, "orderNo": p.OrderNo, "completedText": p.CompletedText, "operator": p.Operator,
|
||
"ownershipType": p.OwnershipType, "ownershipNo": p.OwnershipNo, "productWorkNo": p.ProductWorkNo,
|
||
})
|
||
}
|
||
|
||
// SemiOutbound 调 WMS /api/internal/semi/outbound 半成品出库(重上线),契约同 SemiInbound。
|
||
func (c *Client) SemiOutbound(ctx context.Context, p SemiPayload) error {
|
||
return c.postSemi(ctx, "/api/internal/semi/outbound", map[string]any{
|
||
"sn": p.Sn, "orderNo": p.OrderNo, "completedText": p.CompletedText, "operator": p.Operator,
|
||
"ownershipType": p.OwnershipType, "ownershipNo": p.OwnershipNo, "productWorkNo": p.ProductWorkNo,
|
||
})
|
||
}
|
||
|
||
// postSemi 调 WMS 半成品接口并解析业务响应 {code,message}:
|
||
// 网络/超时、非2xx、业务码非0 均返回 error,且优先携带 WMS 原文 message,
|
||
// 供上线登记重上线路径直接透出(WMS 出库失败必须阻断并让操作工看到原因)。
|
||
func (c *Client) postSemi(ctx context.Context, path string, body any) error {
|
||
b, err := json.Marshal(body)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+path, bytes.NewReader(b))
|
||
if err != nil {
|
||
return err
|
||
}
|
||
req.Header.Set("Content-Type", "application/json")
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
defer resp.Body.Close()
|
||
raw, _ := io.ReadAll(resp.Body)
|
||
var br struct {
|
||
Code int `json:"code"`
|
||
Message string `json:"message"`
|
||
}
|
||
_ = json.Unmarshal(raw, &br)
|
||
if resp.StatusCode >= 300 || br.Code != 0 {
|
||
if br.Message != "" {
|
||
return errors.New(br.Message)
|
||
}
|
||
return &RespError{Status: resp.StatusCode}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// DisposeInventoryReq MES → WMS 在库不合格处置请求(调 /api/internal/inventory/dispose)
|
||
// 定位口径与 WMS 一致:sn 非空按 SN 料(material_code+序列号)精确定位;
|
||
// 否则按批次料(material_code+batch_no)定位(同批次多行全部置状态)。
|
||
// DisposalType 仅支持 RETURN/REWORK/SCRAP;RETURN 必填 ReturnTrackingNo。
|
||
type DisposeInventoryReq struct {
|
||
MaterialCode string `json:"materialCode"`
|
||
Sn string `json:"sn"`
|
||
BatchNo string `json:"batchNo"`
|
||
DisposalType string `json:"disposalType"`
|
||
ReturnTrackingNo string `json:"returnTrackingNo"`
|
||
Remark string `json:"remark"`
|
||
Operator string `json:"operator"`
|
||
}
|
||
|
||
// DisposeInventory 调 WMS /api/internal/inventory/dispose 执行在库处置(退货/返修/报废)。
|
||
// 网络/超时、非2xx、业务码非0 均返回 error 且优先携带 WMS 原文 message,
|
||
// 供质量检验保存链路透出「库存联动失败」原因(不阻断检验记录落库)。
|
||
func (c *Client) DisposeInventory(ctx context.Context, req DisposeInventoryReq) error {
|
||
b, err := json.Marshal(req)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/inventory/dispose", bytes.NewReader(b))
|
||
if err != nil {
|
||
return err
|
||
}
|
||
httpReq.Header.Set("Content-Type", "application/json")
|
||
httpReq.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(httpReq)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
defer resp.Body.Close()
|
||
raw, _ := io.ReadAll(resp.Body)
|
||
var br struct {
|
||
Code int `json:"code"`
|
||
Message string `json:"message"`
|
||
}
|
||
_ = json.Unmarshal(raw, &br)
|
||
if resp.StatusCode >= 300 || br.Code != 0 {
|
||
if br.Message != "" {
|
||
return errors.New(br.Message)
|
||
}
|
||
return &RespError{Status: resp.StatusCode}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// FinishedPayload MES→WMS 成品回流入库载荷(完工检合格触发,调 /api/internal/finished/inbound)。
|
||
// 归属三字段照 semi.go 半成品归属继承模式取自工单:ownershipType/ownershipNo 取工单归属,
|
||
// productWorkNo=产品工号(即工单号),由 MES 自动带出,不做人工手选。
|
||
// productStatus=完工检结论(已通过/部分通过,WMS 侧映射 qualityStatus 合格);
|
||
// relatedStandard=相关标准、testRecordNo=试验记录单号(MES 完工检记录暂无专用字段时传空)。
|
||
type FinishedPayload struct {
|
||
ProductCode string
|
||
ProductName string
|
||
Sn string
|
||
OrderNo string
|
||
Operator string
|
||
ProductStatus string // 完工检结论:已通过 / 部分通过(不合格不触发本接口)
|
||
QualityStatus string // 质量状态:合格(默认)/不合格/未检/待退
|
||
RelatedStandard string // 相关标准(无则传空)
|
||
TestRecordNo string // 试验记录单号(无则传空)
|
||
OwnershipType string // 归属类型:workorder=合同号/project=科技项目号/other=其他
|
||
OwnershipNo string // 归属编号(合同号或科技项目号)
|
||
ProductWorkNo string // 产品工号(=所属工单号)
|
||
}
|
||
|
||
// FinishedInbound 成品回流入库:调 WMS /api/internal/finished/inbound,统一库存主表 category=3。
|
||
// WMS 对重复 SN 返回 HTTP 409 防重,此处转成 *RespError{Status:409} 供调用方
|
||
// 提示「已入库勿重复」(返修后复检再录合格的重复入库场景)。
|
||
func (c *Client) FinishedInbound(ctx context.Context, p FinishedPayload) error {
|
||
b, err := json.Marshal(map[string]any{
|
||
"productCode": p.ProductCode, "productName": p.ProductName, "sn": p.Sn,
|
||
"orderNo": p.OrderNo, "snSource": "AUTO", "operator": p.Operator,
|
||
"productStatus": p.ProductStatus, "qualityStatus": p.QualityStatus, "relatedStandard": p.RelatedStandard,
|
||
"testRecordNo": p.TestRecordNo, "ownershipType": p.OwnershipType,
|
||
"ownershipNo": p.OwnershipNo, "productWorkNo": p.ProductWorkNo,
|
||
})
|
||
if err != nil {
|
||
return err
|
||
}
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/finished/inbound", bytes.NewReader(b))
|
||
if err != nil {
|
||
return err
|
||
}
|
||
req.Header.Set("Content-Type", "application/json")
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
defer resp.Body.Close()
|
||
raw, _ := io.ReadAll(resp.Body)
|
||
var br struct {
|
||
Code int `json:"code"`
|
||
Message string `json:"message"`
|
||
}
|
||
_ = json.Unmarshal(raw, &br)
|
||
if resp.StatusCode >= 300 || br.Code != 0 {
|
||
if resp.StatusCode == http.StatusConflict {
|
||
return &RespError{Status: resp.StatusCode, Message: br.Message}
|
||
}
|
||
if br.Message != "" {
|
||
return errors.New(br.Message)
|
||
}
|
||
return &RespError{Status: resp.StatusCode}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// MaterialExists 批量校验物料编码是否存在于 WMS 物料档案。
|
||
// 返回 WMS 中不存在的编码列表(全部存在则为空)。WMS 响应 {code,message,data:{missing:[]}}。
|
||
// 失败(网络/超时/非0响应)返回 err,由调用方决定降级策略。
|
||
func (c *Client) MaterialExists(ctx context.Context, codes []string) ([]string, error) {
|
||
b, err := json.Marshal(map[string]any{"codes": codes})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/material/exists", bytes.NewReader(b))
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req.Header.Set("Content-Type", "application/json")
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
var body struct {
|
||
Code int `json:"code"`
|
||
Data struct {
|
||
Missing []string `json:"missing"`
|
||
} `json:"data"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||
return nil, err
|
||
}
|
||
if resp.StatusCode >= 300 || body.Code != 0 {
|
||
return nil, &RespError{Status: resp.StatusCode}
|
||
}
|
||
return body.Data.Missing, nil
|
||
}
|
||
|
||
// ProductTypeRow 产品型号档案行(WMS materials item_type=3)
|
||
// 注:原「备注」随 WMS 物料档案「简称」一并删除(2026-09-19),
|
||
// 改为与 WMS 必填口径一致的「规格 / 单位」。
|
||
type ProductTypeRow struct {
|
||
ID int `json:"id"`
|
||
Code string `json:"code"`
|
||
Name string `json:"name"`
|
||
Spec string `json:"spec"`
|
||
Unit string `json:"unit"`
|
||
Category string `json:"category"`
|
||
ManageMode int `json:"manageMode"` // 类型 1结构件/2电气件/3其他
|
||
SnMode int `json:"snMode"` // 是否逐件SN管理 0未选择/1序列号=是(录SN)/2序列号=否(不录SN)
|
||
IsActive bool `json:"isActive"`
|
||
// SyncPending 推送 WMS 失败标记(两库对等 M3):true=本地已落、WMS 待重推
|
||
SyncPending bool `json:"syncPending"`
|
||
CreatedAt int64 `json:"createdAt"`
|
||
UpdatedAt int64 `json:"updatedAt"`
|
||
}
|
||
|
||
// get 调 WMS GET 接口并解出 {code,data}
|
||
func (c *Client) get(ctx context.Context, path string, out any) error {
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL()+path, nil)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
defer resp.Body.Close()
|
||
if resp.StatusCode >= 300 {
|
||
return &RespError{Status: resp.StatusCode}
|
||
}
|
||
var body struct {
|
||
Code int `json:"code"`
|
||
Data any `json:"data"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||
return err
|
||
}
|
||
if body.Code != 0 {
|
||
return &RespError{Status: resp.StatusCode}
|
||
}
|
||
if out != nil && body.Data != nil {
|
||
b, _ := json.Marshal(body.Data)
|
||
return json.Unmarshal(b, out)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// ExportProductTypes 拉取产品型号导出 xlsx 字节流(WMS 端执行统一导出时间规则)。
|
||
// 编码/名称各自独立模糊筛选(禁止关键字混搜)。
|
||
func (c *Client) ExportProductTypes(ctx context.Context, code, name, spec, isActive, startDate, endDate string) ([]byte, error) {
|
||
q := "/api/internal/product-types/export?"
|
||
if code != "" {
|
||
q += "code=" + url.QueryEscape(code) + "&"
|
||
}
|
||
if name != "" {
|
||
q += "name=" + url.QueryEscape(name) + "&"
|
||
}
|
||
if spec != "" {
|
||
q += "spec=" + url.QueryEscape(spec) + "&"
|
||
}
|
||
if isActive != "" {
|
||
q += "isActive=" + isActive + "&"
|
||
}
|
||
q += "startDate=" + startDate + "&endDate=" + endDate
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL()+q, nil)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
if resp.StatusCode >= 300 {
|
||
return nil, &RespError{Status: resp.StatusCode}
|
||
}
|
||
buf := new(bytes.Buffer)
|
||
if _, err := buf.ReadFrom(resp.Body); err != nil {
|
||
return nil, err
|
||
}
|
||
return buf.Bytes(), nil
|
||
}
|
||
|
||
// CreateReturnOrder 调 WMS /api/internal/return-order 预建退库单(工位退料/叫料单退库,待 WMS 确认收货)。
|
||
// refNo 非空 = 叫料单退库(B5):携带叫料单号,WMS 确认收回后凭此回调 MES /call/return-confirm。
|
||
// returnDock(2026-11-03 拍板):退料必须指定接驳台(退料托盘放置位置),WMS 退库单展示。
|
||
// lossReason(2026-11-04 拍板):损耗原因(巡检退料一律必填;转产退料实际<理论时必填),WMS 退库单落 loss_reason 可查。
|
||
// transportMode(2026-11-04 定稿):运输方式 agv/manual——agv=传感器检测到接驳台有托盘且库房有空位自动派车;manual=无 AGV。
|
||
func (c *Client) CreateReturnOrder(ctx context.Context, orderNo, sn, materialCode, materialName, spec, reason, operator string, stationNo, qty int, unit, refNo, returnDock, lossReason, transportMode string) error {
|
||
return c.post(ctx, "/api/internal/return-order", map[string]any{
|
||
"orderNo": orderNo, "sn": sn, "materialCode": materialCode, "materialName": materialName,
|
||
"spec": spec, "qty": qty, "unit": unit, "reason": reason, "operator": operator, "stationNo": stationNo,
|
||
"refNo": refNo, "returnDock": returnDock, "lossReason": lossReason, "transportMode": transportMode,
|
||
})
|
||
}
|
||
|
||
// StationReturnList 工位终端「我的退料单」列表(WMS internal 转发)。
|
||
func (c *Client) StationReturnList(ctx context.Context, stationNo int) ([]map[string]any, error) {
|
||
u := fmt.Sprintf("%s/api/internal/return-order/station-list?stationNo=%d", c.BaseURL(), stationNo)
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
var env struct {
|
||
Code int `json:"code"`
|
||
Data []map[string]any `json:"data"`
|
||
Msg string `json:"message"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&env); err != nil {
|
||
return nil, err
|
||
}
|
||
if env.Code != 0 {
|
||
return nil, fmt.Errorf("WMS 返回错误: %s", env.Msg)
|
||
}
|
||
if env.Data == nil {
|
||
return []map[string]any{}, nil
|
||
}
|
||
return env.Data, nil
|
||
}
|
||
|
||
// ---------- 退料 AGV 自动派车 / 工位取消退料 / 余量参考值(2026-11-04 口径定稿) ----------
|
||
|
||
// PendingReturnRow 待派车退料单行(WMS /api/internal/return-order/pending-agv 返回)。
|
||
type PendingReturnRow struct {
|
||
ReturnNo string `json:"returnNo"`
|
||
ReturnDock string `json:"returnDock"`
|
||
StationNo int `json:"stationNo"`
|
||
OrderNo string `json:"orderNo"`
|
||
}
|
||
|
||
// PendingAgvReturns 拉取待自动派车退料单(PENDING + 运输方式=AGV + 未派车)。
|
||
func (c *Client) PendingAgvReturns(ctx context.Context) ([]PendingReturnRow, error) {
|
||
u := c.BaseURL() + "/api/internal/return-order/pending-agv"
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
var env struct {
|
||
Code int `json:"code"`
|
||
Data []PendingReturnRow `json:"data"`
|
||
Msg string `json:"message"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&env); err != nil {
|
||
return nil, err
|
||
}
|
||
if env.Code != 0 {
|
||
return nil, fmt.Errorf("WMS 返回错误: %s", env.Msg)
|
||
}
|
||
if env.Data == nil {
|
||
return []PendingReturnRow{}, nil
|
||
}
|
||
return env.Data, nil
|
||
}
|
||
|
||
// MarkReturnDispatched 回写退料单「已派车」标记(自动派车成功后调用,防重复派车)。
|
||
func (c *Client) MarkReturnDispatched(ctx context.Context, returnNo string) error {
|
||
return c.post(ctx, "/api/internal/return-order/mark-dispatched", map[string]any{"returnNo": returnNo})
|
||
}
|
||
|
||
// CancelReturnOrder 工位取消自己发起的 PENDING 退料单(工位终端 → MES 转发 WMS)。
|
||
func (c *Client) CancelReturnOrder(ctx context.Context, returnNo string, stationNo int, operator, reason string) error {
|
||
return c.post(ctx, "/api/internal/return-order/cancel", map[string]any{
|
||
"returnNo": returnNo, "stationNo": stationNo, "operator": operator, "reason": reason,
|
||
})
|
||
}
|
||
|
||
// ReturnedSummaryRow 已退余量汇总行(WMS /api/internal/return-order/returned-summary 返回)。
|
||
type ReturnedSummaryRow struct {
|
||
OrderNo string `json:"orderNo"`
|
||
MaterialCode string `json:"materialCode"`
|
||
ReturnedQty float64 `json:"returnedQty"` // PENDING+RECEIVED 退料数量合计(已取消不计)
|
||
}
|
||
|
||
// FetchReturnedSummary 拉取某工位已退余量汇总(余量参考值=应剩余量−已退−损耗)。
|
||
func (c *Client) FetchReturnedSummary(ctx context.Context, stationNo int) ([]ReturnedSummaryRow, error) {
|
||
u := fmt.Sprintf("%s/api/internal/return-order/returned-summary?stationNo=%d", c.BaseURL(), stationNo)
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
var env struct {
|
||
Code int `json:"code"`
|
||
Data []ReturnedSummaryRow `json:"data"`
|
||
Msg string `json:"message"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&env); err != nil {
|
||
return nil, err
|
||
}
|
||
if env.Code != 0 {
|
||
return nil, fmt.Errorf("WMS 返回错误: %s", env.Msg)
|
||
}
|
||
if env.Data == nil {
|
||
return []ReturnedSummaryRow{}, nil
|
||
}
|
||
return env.Data, nil
|
||
}
|
||
|
||
// DisplayOverview 拉取 WMS 免登录看板总览 /api/display/overview。
|
||
// 用于看板「仓储动态」屏。WMS 不可达时返回 err,由调用方降级为空对象(看板其余屏不受影响)。
|
||
func (c *Client) DisplayOverview(ctx context.Context) (map[string]any, error) {
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL()+"/api/display/overview", nil)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
if resp.StatusCode >= 300 {
|
||
return nil, &RespError{Status: resp.StatusCode}
|
||
}
|
||
var body struct {
|
||
Code int `json:"code"`
|
||
Data map[string]any `json:"data"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||
return nil, err
|
||
}
|
||
if body.Data == nil {
|
||
return map[string]any{}, nil
|
||
}
|
||
return body.Data, nil
|
||
}
|
||
|
||
// MaterialQuery 查询 WMS 物料档案 + 库存(看板物料追溯入口复用)。
|
||
// code 必填,batch 可选。返回 found(档案是否存在) + material(档案) + inventory(在库行)。
|
||
func (c *Client) MaterialQuery(ctx context.Context, code, batch string) (map[string]any, error) {
|
||
if code == "" {
|
||
return map[string]any{}, nil
|
||
}
|
||
u := c.BaseURL() + "/api/internal/material/query?code=" + url.QueryEscape(code)
|
||
if batch != "" {
|
||
u += "&batch=" + url.QueryEscape(batch)
|
||
}
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
if resp.StatusCode >= 300 {
|
||
return nil, &RespError{Status: resp.StatusCode}
|
||
}
|
||
var body struct {
|
||
Code int `json:"code"`
|
||
Data map[string]any `json:"data"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||
return nil, err
|
||
}
|
||
if body.Data == nil {
|
||
return map[string]any{}, nil
|
||
}
|
||
return body.Data, nil
|
||
}
|
||
|
||
// StockAvailable 批量查询物料可用量(调 WMS /api/internal/stock/check,qty 传 0 只取可用量)。
|
||
// 返回 materialCode → availQty。用于 MES 侧计算可生产数量(物料清单单台用量在 MES、库存可用量在 WMS)。
|
||
func (c *Client) StockAvailable(ctx context.Context, codes []string) (map[string]int, error) {
|
||
items := make([]map[string]any, 0, len(codes))
|
||
for _, code := range codes {
|
||
items = append(items, map[string]any{"materialCode": code, "qty": 0})
|
||
}
|
||
b, err := json.Marshal(map[string]any{"items": items})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/stock/check", bytes.NewReader(b))
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req.Header.Set("Content-Type", "application/json")
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
var body struct {
|
||
Code int `json:"code"`
|
||
Data struct {
|
||
Items []struct {
|
||
MaterialCode string `json:"materialCode"`
|
||
AvailQty int `json:"availQty"`
|
||
} `json:"items"`
|
||
} `json:"data"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||
return nil, err
|
||
}
|
||
if resp.StatusCode >= 300 || body.Code != 0 {
|
||
return nil, &RespError{Status: resp.StatusCode}
|
||
}
|
||
out := make(map[string]int, len(body.Data.Items))
|
||
for _, it := range body.Data.Items {
|
||
out[it.MaterialCode] = it.AvailQty
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// ProducibleItem 可生产数量行(按工单维度,MES 实时计算;原定时推送/快照已下线)
|
||
type ProducibleItem struct {
|
||
OrderNo string `json:"orderNo"`
|
||
ProductCode string `json:"productCode"`
|
||
ProductName string `json:"productName"`
|
||
ProducibleQty int `json:"producibleQty"`
|
||
ShortText string `json:"shortText"`
|
||
ComputedAt int64 `json:"computedAt"`
|
||
}
|
||
|
||
// ProducibleDemand 未来5天物料需求行(推送 WMS,供备料四态「预警」判定)
|
||
type ProducibleDemand struct {
|
||
MaterialCode string `json:"materialCode"`
|
||
Future5Qty int `json:"future5Qty"`
|
||
}
|
||
|
||
// MaterialManageModes 批量查询物料在 WMS 的「类型」(manage_mode: 1结构件/2电气件/3其他)。
|
||
// 物料类别(item_type=成品/组件类)与「类型」(结构件/电气件/其他)是两个独立维度,本接口只查后者。
|
||
// WMS 不可达返回 err,由调用方降级(不阻塞产线)。
|
||
func (c *Client) MaterialManageModes(ctx context.Context, codes []string) (map[string]int, error) {
|
||
b, err := json.Marshal(map[string]any{"codes": codes})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/material/manage-modes", bytes.NewReader(b))
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req.Header.Set("Content-Type", "application/json")
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
var body struct {
|
||
Code int `json:"code"`
|
||
Data struct {
|
||
ManageModes map[string]int `json:"manageModes"`
|
||
} `json:"data"`
|
||
Msg string `json:"message"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||
return nil, err
|
||
}
|
||
if body.Code != 0 {
|
||
if body.Msg != "" {
|
||
return nil, errors.New(body.Msg)
|
||
}
|
||
return nil, errors.New("WMS 查询物料类型失败")
|
||
}
|
||
if body.Data.ManageModes == nil {
|
||
return map[string]int{}, nil
|
||
}
|
||
return body.Data.ManageModes, nil
|
||
}
|
||
|
||
// StockBatch WMS 可用批次(结构件)
|
||
type StockBatch struct {
|
||
BatchNo string `json:"batchNo"`
|
||
Quantity int `json:"quantity"`
|
||
LockedQty int `json:"lockedQty"`
|
||
Avail int `json:"avail"`
|
||
ZoneCode string `json:"zoneCode"`
|
||
QualityStatus string `json:"qualityStatus"`
|
||
}
|
||
|
||
// StockBatches 调 WMS /api/internal/stock/batches 取该物料可出库的批次(FIFO 升序)与可用 SN 列表。
|
||
// 供「工单备料自动出库」分配用;WMS 只返回「合格」且在库的库存。
|
||
func (c *Client) StockBatches(ctx context.Context, materialCode string) ([]StockBatch, []string, error) {
|
||
u := c.BaseURL() + "/api/internal/stock/batches?materialCode=" + url.QueryEscape(materialCode)
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||
if err != nil {
|
||
return nil, nil, err
|
||
}
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return nil, nil, err
|
||
}
|
||
defer resp.Body.Close()
|
||
var body struct {
|
||
Code int `json:"code"`
|
||
Message string `json:"message"`
|
||
Data struct {
|
||
Batches []StockBatch `json:"batches"`
|
||
SnList []string `json:"snList"`
|
||
} `json:"data"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||
return nil, nil, err
|
||
}
|
||
if resp.StatusCode >= 300 || body.Code != 0 {
|
||
return nil, nil, errors.New("查询 WMS 可用库存失败: " + body.Message)
|
||
}
|
||
return body.Data.Batches, body.Data.SnList, nil
|
||
}
|
||
|
||
func (c *Client) post(ctx context.Context, path string, body any) error {
|
||
b, err := json.Marshal(body)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+path, bytes.NewReader(b))
|
||
if err != nil {
|
||
return err
|
||
}
|
||
req.Header.Set("Content-Type", "application/json")
|
||
req.Header.Set("X-API-TOKEN", c.token)
|
||
resp, err := c.hc.Do(req)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
defer resp.Body.Close()
|
||
raw, _ := io.ReadAll(resp.Body)
|
||
if resp.StatusCode >= 300 {
|
||
// 优先透出 WMS 业务错误原文(fail() 返回 {code:-1,message}),不吞真实失败原因
|
||
var br struct {
|
||
Code int `json:"code"`
|
||
Message string `json:"message"`
|
||
}
|
||
_ = json.Unmarshal(raw, &br)
|
||
if br.Message != "" {
|
||
return errors.New(br.Message)
|
||
}
|
||
return &RespError{Status: resp.StatusCode}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
type RespError struct {
|
||
Status int
|
||
Message string // WMS 业务错误原文(可选;409 防重等场景透出,空则仅报状态码)
|
||
}
|
||
|
||
// DeliveredOutbound 调 WMS /api/internal/outbound/delivered:AGV 到位(任务结束)后
|
||
// 把关联出库单从「已出库」置「已送达」(幂等,已作废/已送达的跳过)。调用方 best-effort,失败仅记日志。
|
||
func (c *Client) DeliveredOutbound(ctx context.Context, outboundNos []string) error {
|
||
return c.post(ctx, "/api/internal/outbound/delivered", map[string]any{"outboundNos": outboundNos})
|
||
}
|
||
|
||
func (e *RespError) Error() string {
|
||
if e.Message != "" {
|
||
return "wms call failed with status " + strconv.Itoa(e.Status) + ": " + e.Message
|
||
}
|
||
return "wms call failed with status " + strconv.Itoa(e.Status)
|
||
}
|
||
|
||
// MaterialRow WMS 物料档案行(代理 WMS materials 表)
|
||
type MaterialRow struct {
|
||
ID int `json:"id"`
|
||
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"` // 类型 1结构件/2电气件/3其他
|
||
SnMode int `json:"snMode"` // 是否逐件SN管理 0未选择/1序列号=是/2序列号=否(WMS 侧未改造时缺省 0)
|
||
TemplateCode string `json:"templateCode"`
|
||
SafetyStock int `json:"safetyStock"`
|
||
IsActive bool `json:"isActive"`
|
||
CreatedAt int64 `json:"createdAt"`
|
||
UpdatedAt int64 `json:"updatedAt"`
|
||
}
|
||
|
||
// MaterialPage 分页查询 WMS 物料(GET /api/internal/materials)
|
||
func (c *Client) MaterialPage(ctx context.Context, code, name, spec string, itemType, manageMode, page, pageSize int) (int64, []MaterialRow, error) {
|
||
q := "/api/internal/materials?page=" + strconv.Itoa(page) + "&pageSize=" + strconv.Itoa(pageSize)
|
||
if code != "" {
|
||
q += "&materialCode=" + url.QueryEscape(code)
|
||
}
|
||
if name != "" {
|
||
q += "&name=" + url.QueryEscape(name)
|
||
}
|
||
if spec != "" {
|
||
q += "&spec=" + url.QueryEscape(spec)
|
||
}
|
||
if itemType > 0 {
|
||
q += "&itemType=" + strconv.Itoa(itemType)
|
||
}
|
||
if manageMode > 0 {
|
||
q += "&manageMode=" + strconv.Itoa(manageMode)
|
||
}
|
||
var out struct {
|
||
Total int64 `json:"total"`
|
||
List []MaterialRow `json:"list"`
|
||
}
|
||
if err := c.get(ctx, q, &out); err != nil {
|
||
return 0, nil, err
|
||
}
|
||
return out.Total, out.List, nil
|
||
}
|
||
|
||
// MaterialUpsert MES→WMS 物料推送载荷(POST WMS /api/internal/materials/upsert,按 code 幂等)。
|
||
type MaterialUpsert 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"` // 类型 1结构件/2电气件/3其他
|
||
SnMode int `json:"snMode"` // 是否逐件SN管理 1序列号=是/2序列号=否(与 WMS 并行改造,字段契约一致)
|
||
TemplateCode string `json:"templateCode"`
|
||
SafetyStock int `json:"safetyStock"`
|
||
IsActive *bool `json:"isActive"`
|
||
}
|
||
|
||
// UpsertMaterialToWMS 推送物料到 WMS(需求一 M3/M5:MES 本地写入后同步推送;按 code 幂等 upsert)。
|
||
func (c *Client) UpsertMaterialToWMS(ctx context.Context, m MaterialUpsert) error {
|
||
return c.post(ctx, "/api/internal/materials/upsert", map[string]any{
|
||
"code": m.Code, "name": m.Name, "spec": m.Spec, "unit": m.Unit, "description": m.Description,
|
||
"itemType": m.ItemType, "manageMode": m.ManageMode, "snMode": m.SnMode,
|
||
"templateCode": m.TemplateCode,
|
||
"safetyStock": m.SafetyStock, "isActive": m.IsActive,
|
||
})
|
||
}
|