- 推送前校验改为「能否解析到系统商品」:product_id / combo_product_id / 历史手工单 item_id(与商品编码一致)/ 无平台溯源时编码命中商品库 - 平台未绑定明细(带店铺商品 / 平台快照 / 平台商品ID)仍然拦截并提示先在「店铺商品」绑定 - 建单 / 改单写库时把历史手工单误存在 item_id 里的系统商品ID 迁到 product_id,并补 item_type / parse_status - 推送报文 itemId 优先用仓库映射(warehouse_products.wms_item_id),避免把系统商品ID 当 WMS 商品ID 下发 - 手工单表单改用 product_id 记录所选系统商品(item_id 仅沿用历史数据) - 新增 orderPushItems 与推送报文 itemId 单测 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
809 lines
36 KiB
JavaScript
809 lines
36 KiB
JavaScript
'use strict';
|
||
|
||
const { qimenSign } = require('./sign');
|
||
const {
|
||
DEFAULT_INBOUND_ORDER_TYPE,
|
||
normalizeInboundOrderType,
|
||
DEFAULT_OUTBOUND_ORDER_TYPE,
|
||
normalizeOutboundOrderType,
|
||
DEFAULT_DELIVERY_ORDER_TYPE,
|
||
normalizeDeliveryOrderType,
|
||
} = require('./orderTypes');
|
||
|
||
/** 单次请求超时(毫秒) */
|
||
const DEFAULT_TIMEOUT_MS = 10000;
|
||
/** 业务成功码集合(index.ping 备注:成功通常为 200 或 1;singleitem 文档:1=成功 0=失败) */
|
||
const SUCCESS_CODES = new Set([ 1, 200, '1', '200' ]);
|
||
/** 对外请求日志中单条报文/URL 最大存储长度(字符) */
|
||
const MAX_LOG_BODY = 4000;
|
||
/** 出站报文/URL 需脱敏的字段 */
|
||
const SENSITIVE_FIELDS = [ 'app_secret', 'password', 'token', 'sign', 'salt' ];
|
||
|
||
/**
|
||
* 对 URL 中的敏感 query 参数脱敏(sign / app_secret),避免凭据落库
|
||
* @param {string} rawUrl
|
||
* @return {string}
|
||
*/
|
||
function maskSignInUrl(rawUrl) {
|
||
try {
|
||
const u = new URL(rawUrl);
|
||
for (const key of [ 'sign', 'app_secret' ]) {
|
||
if (u.searchParams.has(key)) u.searchParams.set(key, '***');
|
||
}
|
||
return u.toString();
|
||
} catch {
|
||
return rawUrl;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 对报文对象中的敏感字段脱敏(递归)
|
||
* @param {*} value
|
||
* @return {*}
|
||
*/
|
||
function maskObject(value) {
|
||
if (!value || typeof value !== 'object') return value;
|
||
const result = Array.isArray(value) ? [ ...value ] : { ...value };
|
||
for (const key of Object.keys(result)) {
|
||
if (SENSITIVE_FIELDS.includes(key.toLowerCase())) {
|
||
result[key] = '***';
|
||
} else if (result[key] && typeof result[key] === 'object') {
|
||
result[key] = maskObject(result[key]);
|
||
}
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 序列化并限制长度
|
||
* @param {*} value
|
||
* @param {number} max
|
||
* @return {string}
|
||
*/
|
||
function safeStringify(value, max) {
|
||
let text;
|
||
try {
|
||
text = typeof value === 'string' ? value : JSON.stringify(value);
|
||
} catch {
|
||
text = '[unserializable]';
|
||
}
|
||
if (!text) return '';
|
||
return text.length > max ? `${text.slice(0, max)}...[truncated]` : text;
|
||
}
|
||
|
||
/**
|
||
* 类奇门JSON接口客户端(OMS → WMS)
|
||
*
|
||
* 封装对 WMS openapi(POST {base_url})的调用与签名。当前聚焦「商品资料推送(singleitem.synchronize)」,
|
||
* 后续可在此扩展 deliveryorder / entryorder / inventory 等模块,复用同一套鉴权与报文结构。
|
||
*
|
||
* 约定(基于 D:/wms/methods/openapi.json + warehouse_notify.json):
|
||
* - 鉴权参数 method / app_key / timestamp / sign 通过 query 传递(与 qimen.json 一致)
|
||
* - 业务参数通过 JSON body 传递(如 { item: {...} })
|
||
* - 签名 sign = MD5(app_secret + timestamp + body_json),与 WMS 出站通知规则一致
|
||
* - 时间戳为 Unix 秒,±10 分钟有效
|
||
*
|
||
* 说明:openapi.json 未显式给出签名算法,此处与同系统出站通知(MD5(secret+timestamp+body))保持一致;
|
||
* 若实际 WMS 使用其它签名,仅需替换 _sign 实现。
|
||
*
|
||
* 每次请求都会异步落库到 api_outbound_logs(前提是构造时传入了 app 实例),用于排查。
|
||
*/
|
||
class QimenWmsClient {
|
||
/**
|
||
* @param {Object} warehouseApi 仓库接口配置模型实例(需含 base_url / app_key / app_secret / getFieldValues)
|
||
* @param {Egg.Application} [app] egg 应用实例,传入后才会记录对外请求日志
|
||
*/
|
||
constructor(warehouseApi, app) {
|
||
if (!warehouseApi) throw new Error('warehouseApi 不能为空');
|
||
this.baseUrl = (warehouseApi.base_url || '').replace(/\/+$/, '');
|
||
this.appKey = warehouseApi.app_key || '';
|
||
this.appSecret = warehouseApi.app_secret || '';
|
||
this.fields = typeof warehouseApi.getFieldValues === 'function'
|
||
? warehouseApi.getFieldValues()
|
||
: (warehouseApi.extra && typeof warehouseApi.extra === 'object' ? warehouseApi.extra : {});
|
||
this.timeoutMs = DEFAULT_TIMEOUT_MS;
|
||
// 归属与落库依赖(app 可选,单测/脚本未注入时跳过记录)
|
||
this.app = app || null;
|
||
this.principalId = warehouseApi.principal_id || null;
|
||
this.warehouseId = warehouseApi.warehouse_id || null;
|
||
this.warehouseApiId = warehouseApi.id || null;
|
||
this.apiType = warehouseApi.type || 'qimen';
|
||
}
|
||
|
||
/**
|
||
* 计算签名(与 WMS app/lib/api_sign.js 对齐)
|
||
* 参与签名的 query 为 method/app_key/v/timestamp(不含 sign),
|
||
* body 用请求体对象(解析后的结构)做稳定序列化后 MD5。
|
||
* @param {string} method WMS 方法名
|
||
* @param {number} timestamp Unix 秒
|
||
* @param {Object} params 请求体对象
|
||
*/
|
||
_sign(method, timestamp, params) {
|
||
const queryForSign = {
|
||
method,
|
||
app_key: this.appKey,
|
||
v: this._apiVersion(),
|
||
timestamp: String(timestamp),
|
||
};
|
||
return qimenSign({ query: queryForSign, body: params, secret: this.appSecret });
|
||
}
|
||
|
||
/**
|
||
* 取接口版本号(v 参数),源自配置项 api_version,缺省 V2.0
|
||
* @return {string}
|
||
*/
|
||
_apiVersion() {
|
||
return (this.fields && this.fields.api_version) || 'V2.0';
|
||
}
|
||
|
||
/**
|
||
* 调用 WMS openapi 方法
|
||
* @param {string} method 方法名,如 singleitem.synchronize / index.ping
|
||
* @param {Object} params 业务参数(作为 JSON body 发送)
|
||
* @return {Promise<{code:number|string,message:string,data:any}>} WMS 返回
|
||
*/
|
||
async call(method, params = {}) {
|
||
if (!this.baseUrl) throw new Error('仓库接口未配置 base_url(WMS openapi 地址)');
|
||
if (!this.appKey || !this.appSecret) throw new Error('仓库接口未配置 app_key / app_secret');
|
||
|
||
const timestamp = Math.floor(Date.now() / 1000);
|
||
const bodyJson = JSON.stringify(params);
|
||
const sign = this._sign(method, timestamp, params);
|
||
|
||
const url = new URL(this.baseUrl);
|
||
url.searchParams.set('method', method);
|
||
url.searchParams.set('app_key', this.appKey);
|
||
// v 为 WMS 要求的接口版本号(本地配置项 api_version,默认 V2.0),随系统参数一并传入
|
||
url.searchParams.set('v', this._apiVersion());
|
||
url.searchParams.set('timestamp', String(timestamp));
|
||
url.searchParams.set('sign', sign);
|
||
const finalUrl = url.toString();
|
||
|
||
const start = Date.now();
|
||
let responseStatus = null;
|
||
let responseText = '';
|
||
let isSuccess = false;
|
||
let businessCode = null;
|
||
let businessMessage = null;
|
||
let errorMsg = null;
|
||
let result = null;
|
||
|
||
const controller = new AbortController();
|
||
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
||
try {
|
||
const resp = await fetch(finalUrl, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: bodyJson,
|
||
signal: controller.signal,
|
||
});
|
||
responseStatus = resp.status;
|
||
responseText = await resp.text();
|
||
if (!resp.ok) {
|
||
errorMsg = `WMS 返回 HTTP ${resp.status}: ${responseText.slice(0, 200)}`;
|
||
throw new Error(errorMsg);
|
||
}
|
||
try {
|
||
result = JSON.parse(responseText);
|
||
isSuccess = true;
|
||
} catch {
|
||
errorMsg = `WMS 返回非法 JSON: ${responseText.slice(0, 200)}`;
|
||
throw new Error(errorMsg);
|
||
}
|
||
} catch (err) {
|
||
if (!errorMsg) errorMsg = err.message;
|
||
throw err;
|
||
} finally {
|
||
clearTimeout(timer);
|
||
if (result) {
|
||
businessCode = result.code != null ? String(result.code) : null;
|
||
businessMessage = typeof result.message === 'string' ? result.message.slice(0, 255) : null;
|
||
}
|
||
this._log({
|
||
method,
|
||
url: finalUrl,
|
||
params,
|
||
responseStatus,
|
||
responseText,
|
||
isSuccess,
|
||
businessCode,
|
||
businessMessage,
|
||
error: errorMsg,
|
||
durationMs: Date.now() - start,
|
||
});
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 异步落库对外请求日志(不阻塞主流程,写入失败仅记录到错误日志)
|
||
* @param {Object} entry
|
||
*/
|
||
_log(entry) {
|
||
if (!this.app || !this.app.model || !this.app.model.ApiOutboundLog) return;
|
||
const payload = {
|
||
principal_id: this.principalId,
|
||
warehouse_id: this.warehouseId,
|
||
warehouse_api_id: this.warehouseApiId,
|
||
api_type: this.apiType,
|
||
method: entry.method,
|
||
url: maskSignInUrl(entry.url),
|
||
request_headers: JSON.stringify({ 'Content-Type': 'application/json' }),
|
||
request_body: safeStringify(maskObject(entry.params), MAX_LOG_BODY),
|
||
response_status: entry.responseStatus,
|
||
response_body: safeStringify(entry.responseText, MAX_LOG_BODY),
|
||
is_success: entry.isSuccess ? 1 : 0,
|
||
business_code: entry.businessCode,
|
||
business_message: entry.businessMessage,
|
||
error: entry.error ? entry.error.slice(0, 2000) : null,
|
||
duration: entry.durationMs,
|
||
};
|
||
this.app.model.ApiOutboundLog.create(payload).catch(err => {
|
||
this.app.logger.error(`[api-outbound-log] 写入失败:${err.message}`);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 业务码是否表示成功
|
||
* @param result
|
||
*/
|
||
isSuccess(result) {
|
||
if (!result) return false;
|
||
if (SUCCESS_CODES.has(result.code)) return true;
|
||
// 部分 WMS 用 flag 字段标识成功(如 {"flag":"success","code":1,...})
|
||
return result.flag === 'success' || result.flag === 'SUCCESS';
|
||
}
|
||
|
||
/**
|
||
* 从 singleitem.synchronize 响应中提取 WMS 内部商品ID(itemId)
|
||
* 兼容多种返回形态:
|
||
* - { data: { itemId } } / { data: { id } } / { data: <itemId 数字或字符串> }
|
||
* - 实测部分 WMS 直接把 itemId 放在响应顶层:{"flag":"success","code":1,"itemId":1001163,...}
|
||
* @param {Object} resp WMS 响应
|
||
* @return {number|null}
|
||
*/
|
||
static extractItemId(resp) {
|
||
if (!resp) return null;
|
||
// 1) data 字段内
|
||
if (resp.data != null) {
|
||
const d = resp.data;
|
||
if (typeof d === 'object') {
|
||
if (d.itemId != null) return Number(d.itemId);
|
||
if (d.id != null) return Number(d.id);
|
||
} else {
|
||
return Number(d);
|
||
}
|
||
}
|
||
// 2) 响应顶层(实测结构)
|
||
if (resp.itemId != null) return Number(resp.itemId);
|
||
if (resp.id != null) return Number(resp.id);
|
||
return null;
|
||
}
|
||
|
||
/** 心跳探测 */
|
||
async ping() {
|
||
return this.call('index.ping', {});
|
||
}
|
||
|
||
/**
|
||
* 商品资料推送:将 OMS 商品字段映射为 WMS singleitem.synchronize 的 item 结构并推送
|
||
* @param {Object} product OMS 商品(model 实例或 plain 对象)
|
||
* @return {Promise<{code,message,data}>}
|
||
*/
|
||
async pushItem(product) {
|
||
return this.call('singleitem.synchronize', { item: this._buildItem(product) });
|
||
}
|
||
|
||
/**
|
||
* 取入库单类型编码:入库单本身已按 WMS 编码落库(inbound_orders.inbound_type),
|
||
* 这里只做 trim/大写与合法性兜底,不再做语义映射(见 lib/wms/orderTypes.js)
|
||
* @param {string} inboundType 入库单类型编码,如 'CGRK'
|
||
* @return {string}
|
||
*/
|
||
_inboundOrderType(inboundType) {
|
||
return normalizeInboundOrderType(inboundType) || DEFAULT_INBOUND_ORDER_TYPE;
|
||
}
|
||
|
||
/**
|
||
* OMS 库存类型(inventory_type) → WMS orderLine.inventoryType
|
||
* WMS 规范:ZP=正品 CC=残次 JS=机损 XS=箱损 FP=废品,默认 ZP
|
||
* @param {string} inventoryType
|
||
* @return {string}
|
||
*/
|
||
_mapInventoryType(inventoryType) {
|
||
const allowed = [ 'ZP', 'CC', 'JS', 'XS', 'FP' ];
|
||
const code = String(inventoryType || 'ZP').toUpperCase();
|
||
return allowed.includes(code) ? code : 'ZP';
|
||
}
|
||
|
||
/** 日期格式化为 WMS 要求的 YYYY-MM-DD HH:MM:SS,失败返回空串 */
|
||
_fmtDateTime(value) {
|
||
if (!value) return '';
|
||
const d = value instanceof Date ? value : new Date(value);
|
||
if (isNaN(d.getTime())) return '';
|
||
const p = n => String(n).padStart(2, '0');
|
||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||
}
|
||
|
||
/**
|
||
* 构建 entryorder.create 请求体(对齐 WMS `entryorder.create` 标准报文)
|
||
*
|
||
* 实际下发字段(见 `D:/wms/methods/openapi.json` 的 params:openapi 渠道除 entryOrderCode 外均为选填):
|
||
* entryOrder:entryOrderCode / entryOrderType / warehouseCode / orderCreateTime /
|
||
* expectedArriveTime / expectEndTime / totalOrderLines / supplierCode / supplierName /
|
||
* logisticsCode / logisticsName / expressCode / remark / operateTime / operatorName /
|
||
* relatedOrders.relatedOrder.orderCode(关联采购单号)
|
||
* orderLines.orderLine:orderLineNo / itemCode / itemId / itemName / planQty / inventoryType
|
||
* 已不再下发:entryOrder 的 ownerCode(openapi 不要求,不传 WMS 落空串;见 warehouseApiFields.js 说明)、
|
||
* purchaseOrderCode(改用 relatedOrders)、operatorCode、senderInfo、receiverInfo、extendProps;
|
||
* 行级 outBizCode / ownerCode / skuProperty / purchasePrice / retailPrice(WMS 不识别)。
|
||
* @param {Object} order OMS 入库单(model 实例或 plain,已 include warehouse/creator)
|
||
* @param {Array} items 入库明细(stock_items,已 include product)
|
||
* @param {Object} [opts] { warehouse, creator, wmsItemIdByProduct }
|
||
* @return {Object} { entryOrder, orderLines: { orderLine: [...] } }
|
||
*/
|
||
_buildEntryOrder(order, items, opts = {}) {
|
||
const o = order.get ? order.get({ plain: true }) : order;
|
||
const warehouse = opts.warehouse && opts.warehouse.get ? opts.warehouse.get({ plain: true }) : (opts.warehouse || {});
|
||
const creator = opts.creator && opts.creator.get ? opts.creator.get({ plain: true }) : (opts.creator || {});
|
||
const wmsItemIdByProduct = opts.wmsItemIdByProduct || {};
|
||
|
||
const orderLineList = (items || []).map((it, idx) => {
|
||
const i = it.get ? it.get({ plain: true }) : it;
|
||
const product = i.product && i.product.get ? i.product.get({ plain: true }) : (i.product || {});
|
||
const productId = i.product_id != null ? Number(i.product_id) : null;
|
||
const wmsItemId = productId != null ? wmsItemIdByProduct[productId] : undefined;
|
||
return {
|
||
orderLineNo: String(idx + 1),
|
||
itemCode: i.code || product.item_code || '',
|
||
// 仓库商品主键:WMS 侧优先按 itemId 直查商品,未推送到该仓库的商品不带该字段(降级按 itemCode 匹配)
|
||
...(wmsItemId != null ? { itemId: wmsItemId } : {}),
|
||
itemName: i.name || product.item_name || '',
|
||
planQty: Number(i.quantity) || 0,
|
||
inventoryType: this._mapInventoryType(i.inventory_type),
|
||
};
|
||
});
|
||
|
||
const entryOrder = {
|
||
entryOrderCode: o.bill_no || '',
|
||
warehouseCode: warehouse.code || 'OTHER',
|
||
orderCreateTime: this._fmtDateTime(o.created_at),
|
||
// openapi 渠道的入库单类型字段是 entryOrderType(默认 SCRK),不是 orderType
|
||
entryOrderType: this._inboundOrderType(o.inbound_type),
|
||
totalOrderLines: orderLineList.length,
|
||
remark: o.remark || '',
|
||
};
|
||
// 预计到货时间:标准字段名为 expectedArriveTime(落库 expect_start_time)
|
||
if (o.expect_start_time) entryOrder.expectedArriveTime = this._fmtDateTime(o.expect_start_time);
|
||
if (o.expect_end_time) entryOrder.expectEndTime = this._fmtDateTime(o.expect_end_time);
|
||
// 关联采购单号:标准报文用 relatedOrders.relatedOrder.orderCode 表达
|
||
if (o.purchase_order_code) {
|
||
entryOrder.relatedOrders = { relatedOrder: { orderCode: o.purchase_order_code } };
|
||
}
|
||
if (o.logistics_code) entryOrder.logisticsCode = o.logistics_code;
|
||
if (o.logistics_name) entryOrder.logisticsName = o.logistics_name;
|
||
if (o.express_code) entryOrder.expressCode = o.express_code;
|
||
if (o.supplier_code) entryOrder.supplierCode = o.supplier_code;
|
||
if (o.supplier) entryOrder.supplierName = o.supplier;
|
||
const operatorName = o.operator || creator.nickname || creator.username || '';
|
||
if (operatorName) entryOrder.operatorName = operatorName;
|
||
entryOrder.operateTime = this._fmtDateTime(o.operate_time || o.updated_at || new Date());
|
||
|
||
return {
|
||
entryOrder,
|
||
orderLines: { orderLine: orderLineList },
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 入库单推送:将 OMS 入库单映射为 WMS entryorder.create 并推送
|
||
* @param {Object} order OMS 入库单(已 include warehouse/creator)
|
||
* @param {Array} items 入库明细(已 include product)
|
||
* @param {Object} [opts] { warehouse, creator, wmsItemIdByProduct }
|
||
* @return {Promise<{code,message,data}>}
|
||
*/
|
||
async createEntryOrder(order, items, opts = {}) {
|
||
return this.call('entryorder.create', this._buildEntryOrder(order, items, opts));
|
||
}
|
||
|
||
/**
|
||
* 取出库单类型编码:出库单本身已按 WMS 编码落库(outbound_orders.outbound_type),
|
||
* 这里只做 trim/大写与合法性兜底,不再做语义映射(见 lib/wms/orderTypes.js)
|
||
* 注:stockout.create 与 order.cancel 必须传同一个值,否则取消时定位不到单据
|
||
* @param {string} outboundType 出库单类型编码,如 'QTCK'
|
||
* @return {string}
|
||
*/
|
||
_outboundOrderType(outboundType) {
|
||
return normalizeOutboundOrderType(outboundType) || DEFAULT_OUTBOUND_ORDER_TYPE;
|
||
}
|
||
|
||
/**
|
||
* 构建 stockout.create(非订单出库单)请求体(对齐 WMS 出库单规范)
|
||
* 字段来源:单据头 + 明细(含商品快照);仓库编码取 warehouse.code;
|
||
* 明细行 itemId 为 WMS 必填项,取 warehouse_products.wms_item_id(由调用方查好后传入)
|
||
* 快递公司与收件人:`deliveryOrder.logisticsCode` ← outbound_orders.express_code;
|
||
* `deliveryOrder.receiverInfo`(13 字段:name/company/zipCode/tel/mobile/email/countryCode/
|
||
* province/city/area/town/detailAddress/id)← outbound_orders.receiver_*,全空则整块不下发
|
||
* @param {Object} order OMS 出库单(model 实例或 plain,已 include warehouse)
|
||
* @param {Array} items 出库明细(stock_items,已 include product)
|
||
* @param {Object} [opts] { warehouse, wmsItemIdByProduct }
|
||
* @return {Object} { deliveryOrder, orderLines: { orderLine: [...] } }
|
||
*/
|
||
_buildStockout(order, items, opts = {}) {
|
||
const o = order.get ? order.get({ plain: true }) : order;
|
||
const warehouse = opts.warehouse && opts.warehouse.get ? opts.warehouse.get({ plain: true }) : (opts.warehouse || {});
|
||
const wmsItemIdByProduct = opts.wmsItemIdByProduct || {};
|
||
|
||
const orderLineList = (items || []).map((it, idx) => {
|
||
const i = it.get ? it.get({ plain: true }) : it;
|
||
const product = i.product && i.product.get ? i.product.get({ plain: true }) : (i.product || {});
|
||
const wmsItemId = i.product_id != null ? wmsItemIdByProduct[Number(i.product_id)] : undefined;
|
||
const line = {
|
||
orderLineNo: String(idx + 1),
|
||
itemCode: i.code || product.item_code || '',
|
||
itemName: i.name || product.item_name || '',
|
||
planQty: Number(i.quantity) || 0,
|
||
inventoryType: this._mapInventoryType(i.inventory_type),
|
||
};
|
||
// itemId 为 WMS 必填项:仅已推送到该仓库的商品才有 wms_item_id,缺失时不传
|
||
if (wmsItemId != null) line.itemId = wmsItemId;
|
||
return line;
|
||
});
|
||
|
||
const deliveryOrder = {
|
||
deliveryOrderCode: o.bill_no || '',
|
||
orderType: this._outboundOrderType(o.outbound_type),
|
||
warehouseCode: warehouse.code || 'OTHER',
|
||
createTime: this._fmtDateTime(o.created_at),
|
||
totalOrderLines: orderLineList.length,
|
||
remark: o.remark || '',
|
||
};
|
||
|
||
// 快递公司:deliveryOrder.logisticsCode(货主开启 enable_external_express_code 时按快递设置匹配,
|
||
// 匹配不到用出库单兜底快递编码,默认 ZT 自提);无值时不带,保持与历史报文一致
|
||
if (o.express_code) deliveryOrder.logisticsCode = o.express_code;
|
||
|
||
// 收件人:deliveryOrder.receiverInfo(13 个标准字段,WMS 侧落 wms_order_stockout.receiver_* 列,
|
||
// 供转订单与确认回传使用);任一字段有值才下发,全空则整块不传
|
||
const receiverInfo = {
|
||
name: o.receiver_name || '',
|
||
company: o.receiver_company || '',
|
||
zipCode: o.receiver_zip_code || '',
|
||
tel: o.receiver_tel || '',
|
||
mobile: o.receiver_mobile || '',
|
||
email: o.receiver_email || '',
|
||
countryCode: o.receiver_country_code || '',
|
||
province: o.receiver_province || '',
|
||
city: o.receiver_city || '',
|
||
area: o.receiver_area || '',
|
||
town: o.receiver_town || '',
|
||
detailAddress: o.receiver_detail_address || '',
|
||
id: o.receiver_id || '',
|
||
};
|
||
if (Object.values(receiverInfo).some(v => v)) deliveryOrder.receiverInfo = receiverInfo;
|
||
|
||
return {
|
||
deliveryOrder,
|
||
orderLines: { orderLine: orderLineList },
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 出库单推送:将 OMS 出库单映射为 WMS stockout.create(非订单出库单)并推送
|
||
* @param {Object} order OMS 出库单(已 include warehouse)
|
||
* @param {Array} items 出库明细(已 include product)
|
||
* @param {Object} [opts] { warehouse, wmsItemIdByProduct }
|
||
* @return {Promise<{code,message,data}>}
|
||
*/
|
||
async createStockout(order, items, opts = {}) {
|
||
return this.call('stockout.create', this._buildStockout(order, items, opts));
|
||
}
|
||
|
||
/**
|
||
* 出库单取消:调用 order.cancel 取消已推送的外部出库单(stockout)
|
||
* 文档/源码依据:`order.cancel`,参数 orderCode(要取消的出库单号)+ orderType;
|
||
* openapiMethods/order.js 的 CK_TYPES = PTCK/DBCK/B2BCK/QTCK/CGTH 会按 stockout_order_code
|
||
* 定位 wms_order_stockout 并取消(释放锁定、状态置 CANCELLED);ORDER 组(JYCK/HHCK/BFCK)
|
||
* 走的是发货单表,与 stockout 不是同一张表,故此处必须传落库的 CK 编码。
|
||
* @param {Object} order OMS 出库单(model 实例或 plain)
|
||
* @return {Promise<{code,message,data}>} WMS 返回
|
||
*/
|
||
async cancelOrder(order) {
|
||
const o = order.get ? order.get({ plain: true }) : order;
|
||
return this.call('order.cancel', {
|
||
orderCode: o.bill_no || '',
|
||
orderType: this._outboundOrderType(o.outbound_type),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 取发货单订单类型编码:OMS 落库已按 WMS 编码(order_deliveries.order_type),
|
||
* 这里只做 trim/大写与合法性兜底;ORDER 组 = JYCK / HHCK / BFCK
|
||
* 注:deliveryorder.create 与 order.cancel 必须传同一个值,否则取消时定位不到单据
|
||
* @param {string} orderType 订单类型编码,如 'JYCK'
|
||
* @return {string}
|
||
*/
|
||
_deliveryOrderType(orderType) {
|
||
return normalizeDeliveryOrderType(orderType) || DEFAULT_DELIVERY_ORDER_TYPE;
|
||
}
|
||
|
||
/**
|
||
* 发货单明细库存类型:OMS 落 ZP 正品 / CC 残次,WMS orderLine.inventoryType 同口径直接透传
|
||
* @param {string} inventoryType
|
||
* @return {string}
|
||
*/
|
||
_mapDeliveryLineInventoryType(inventoryType) {
|
||
const code = String(inventoryType || 'ZP').trim().toUpperCase();
|
||
return [ 'ZP', 'CC', 'JS', 'XS', 'FP' ].includes(code) ? code : 'ZP';
|
||
}
|
||
|
||
/**
|
||
* 构建 deliveryorder.create(订单出库单/发货单)请求体(对齐 WMS 发货单规范)
|
||
*
|
||
* 字段口径来源:D:/wms/methods/openapi.json `deliveryorder.create`
|
||
* - 必填:deliveryOrder.deliveryOrderCode、orderLines.orderLine(非空,每行 planQty > 0)
|
||
* - 收件人:receiverInfo.name/mobile/province/city/area/detailAddress 必填(OMS 侧已按同名口径校验)
|
||
* - need_oms_waybill 在请求根节点(不在 deliveryOrder 内):外部打单平台订单按平台配置
|
||
* fetch_waybill_no 决定(1=回 OMS 取号),手工单恒为 0
|
||
* - 明细:itemId 与 itemCode 二选一,优先传 itemId(warehouse_products.wms_item_id 回写值),缺失时用 itemCode
|
||
* @param {Object} order OMS 发货单(model 实例或 plain,已 include warehouse)
|
||
* @param {Array} items 发货单明细(order_delivery_items,已 include product 时优先取商品快照)
|
||
* @param {Object} [opts] { warehouse, wmsItemIdByItemCode, wmsItemIdByProduct }
|
||
* @return {Object} { deliveryOrder, orderLines: { orderLine: [...] }, need_oms_waybill }
|
||
*/
|
||
_buildDeliveryOrder(order, items, opts = {}) {
|
||
const o = order.get ? order.get({ plain: true }) : order;
|
||
const warehouse = opts.warehouse && opts.warehouse.get ? opts.warehouse.get({ plain: true }) : (opts.warehouse || {});
|
||
const wmsItemIdByProduct = opts.wmsItemIdByProduct || {};
|
||
const wmsItemIdByItemCode = opts.wmsItemIdByItemCode || {};
|
||
// OMS 商品信息(product_id → { item_code, item_name }):明细上的 item_code/name 可能是
|
||
// 拉单时的平台原值(绑定系统商品后未回写),推送必须以系统商品为准
|
||
const productById = opts.productById || {};
|
||
|
||
const deliveryOrder = {
|
||
deliveryOrderCode: o.delivery_order_code || '',
|
||
orderType: this._deliveryOrderType(o.order_type),
|
||
warehouseCode: warehouse.code || o.warehouse_code || 'OTHER',
|
||
createTime: this._fmtDateTime(o.created_at),
|
||
totalOrderLines: (items || []).length,
|
||
isUrgency: this._yn(o.is_urgency),
|
||
invoiceFlag: this._yn(o.invoice_flag),
|
||
};
|
||
|
||
// 订单标记 / 来源订单号集合 / OAID 来源编码 / 来源平台(未填写时不传,由 WMS 按货主默认兜底)
|
||
if (o.order_flag) deliveryOrder.orderFlag = o.order_flag;
|
||
if (o.source_platform_code) deliveryOrder.sourcePlatformCode = o.source_platform_code;
|
||
if (o.source_platform_name) deliveryOrder.sourcePlatformName = o.source_platform_name;
|
||
if (o.pre_delivery_order_code) deliveryOrder.preDeliveryOrderCode = o.pre_delivery_order_code;
|
||
if (o.pre_delivery_order_id) deliveryOrder.preDeliveryOrderId = String(o.pre_delivery_order_id);
|
||
if (o.place_order_time) deliveryOrder.placeOrderTime = this._fmtDateTime(o.place_order_time);
|
||
if (o.pay_time) deliveryOrder.payTime = this._fmtDateTime(o.pay_time);
|
||
if (o.pay_no) deliveryOrder.payNo = o.pay_no;
|
||
if (o.shop_nick) deliveryOrder.shopNick = o.shop_nick;
|
||
if (o.seller_nick) deliveryOrder.sellerNick = o.seller_nick;
|
||
if (o.buyer_nick) deliveryOrder.buyerNick = o.buyer_nick;
|
||
if (o.seller_message) deliveryOrder.sellerMessage = o.seller_message;
|
||
if (o.buyer_message) deliveryOrder.buyerMessage = o.buyer_message;
|
||
if (o.source_order_codes) deliveryOrder.sourceOrderCodes = o.source_order_codes;
|
||
if (o.oaid_order_source_code) deliveryOrder.oaidOrderSourceCode = o.oaid_order_source_code;
|
||
|
||
const operatorName = o.operator_name || '';
|
||
if (operatorName) deliveryOrder.operatorName = operatorName;
|
||
deliveryOrder.operateTime = this._fmtDateTime(o.operate_time || o.updated_at || new Date());
|
||
|
||
// 金额:金额为空的项不下发(避免把货主默认金额覆盖成 0)
|
||
const amountFields = {
|
||
totalAmount: o.total_amount,
|
||
itemAmount: o.item_amount,
|
||
discountAmount: o.discount_amount,
|
||
freight: o.freight,
|
||
arAmount: o.ar_amount,
|
||
gotAmount: o.got_amount,
|
||
};
|
||
for (const [ key, value ] of Object.entries(amountFields)) {
|
||
if (value != null && value !== '') deliveryOrder[key] = Number(value);
|
||
}
|
||
|
||
// 物流:logisticsCode 用于匹配快递设置,expressCode/logisticsAreaCode 为取号回写值
|
||
if (o.logistics_code || o.logistics_name) {
|
||
deliveryOrder.logisticsCode = o.logistics_code || '';
|
||
deliveryOrder.logisticsName = o.logistics_name || '';
|
||
}
|
||
if (o.express_code) deliveryOrder.expressCode = o.express_code;
|
||
if (o.logistics_area_code) deliveryOrder.logisticsAreaCode = o.logistics_area_code;
|
||
|
||
deliveryOrder.receiverInfo = {
|
||
name: o.name || '',
|
||
tel: o.tel || '',
|
||
mobile: o.mobile || '',
|
||
email: o.email || '',
|
||
countryCode: o.country_code || '',
|
||
province: o.province || '',
|
||
city: o.city || '',
|
||
area: o.area || '',
|
||
town: o.town || '',
|
||
detailAddress: o.detail_address || '',
|
||
zipCode: o.zip_code || '',
|
||
};
|
||
if (o.oaid) deliveryOrder.receiverInfo.oaid = o.oaid;
|
||
|
||
// 扩展属性:{ key: value } 对象(手工单固定写 labels: "手工单")
|
||
if (o.extend_props && typeof o.extend_props === 'object' && !Array.isArray(o.extend_props)) {
|
||
deliveryOrder.extendProps = o.extend_props;
|
||
}
|
||
|
||
// 上游平台单号(店管家「订单编号」PlatformOrderId):WMS 用它做上游订单关联/展示;
|
||
// 明细行上的 sourceOrderCode 必须是平台单号,不能是 OMS / 店管家的内部系统编号
|
||
const upstreamOrderCode = o.oaid_order_source_code
|
||
|| (o.extend_props && typeof o.extend_props === 'object' ? o.extend_props.platform_order_no : '')
|
||
|| '';
|
||
|
||
const orderLineList = (items || []).map((it, idx) => {
|
||
const i = it.get ? it.get({ plain: true }) : it;
|
||
const product = i.product && i.product.get ? i.product.get({ plain: true }) : (i.product || {});
|
||
const productId = i.product_id != null ? Number(i.product_id) : (product.id != null ? Number(product.id) : null);
|
||
// 绑定系统商品的明细:编码/名称一律用系统商品,避免把平台编码(如 10000202451115)推给仓库
|
||
const bound = productId != null ? productById[productId] : null;
|
||
// itemId 优先取明细自带的 WMS 商品ID,其次按商品编码/OMS 商品ID 回查 warehouse_products.wms_item_id
|
||
const mappedItemId = (i.item_code && wmsItemIdByItemCode[i.item_code])
|
||
|| (productId != null ? wmsItemIdByProduct[productId] : undefined);
|
||
// itemId 优先用仓库映射(warehouse_products.wms_item_id),再看明细自带值;
|
||
// 历史手工单曾把「系统商品ID」误存进 item_id,若该 ID 能在系统商品表里查到(productById),
|
||
// 就不能当 WMS 商品ID 下发,否则 WMS 可能按 itemId 命中其它商品(仍会下发 itemCode 供降级匹配)
|
||
const storedItemId = i.item_id != null && i.item_id !== '' ? Number(i.item_id) : null;
|
||
const storedIsProductId = storedItemId != null && productById[storedItemId] != null;
|
||
const itemId = mappedItemId != null ? Number(mappedItemId) : (storedIsProductId ? null : storedItemId);
|
||
|
||
const line = {
|
||
orderLineNo: String(i.order_line_no == null || i.order_line_no === '' ? idx + 1 : i.order_line_no),
|
||
itemCode: (bound && bound.item_code) || product.item_code || i.item_code || '',
|
||
itemName: (bound && bound.item_name) || product.item_name || i.item_name || '',
|
||
planQty: Number(i.plan_qty) || 0,
|
||
actualPrice: i.actual_price != null && i.actual_price !== '' ? Number(i.actual_price) : 0,
|
||
retailPrice: i.retail_price != null && i.retail_price !== '' ? Number(i.retail_price) : 0,
|
||
inventoryType: this._mapDeliveryLineInventoryType(i.inventory_type),
|
||
};
|
||
// itemId 与 itemCode 二选一:有 WMS 内部商品ID 时一并下发,命中率更高
|
||
if (itemId != null && !isNaN(itemId)) line.itemId = itemId;
|
||
if (i.ext_code) line.extCode = i.ext_code;
|
||
// 平台单号优先(明细上的 source_order_code 存的是店管家系统编号,不能当作平台单号下发)
|
||
const lineSourceOrderCode = upstreamOrderCode || i.source_order_code || '';
|
||
if (lineSourceOrderCode) line.sourceOrderCode = lineSourceOrderCode;
|
||
if (i.sub_source_order_code) line.subSourceOrderCode = i.sub_source_order_code;
|
||
if (i.stock_id) line.stockId = Number(i.stock_id);
|
||
if (i.extend_props && typeof i.extend_props === 'object' && !Array.isArray(i.extend_props)) {
|
||
line.extendProps = JSON.stringify(i.extend_props);
|
||
}
|
||
return line;
|
||
});
|
||
|
||
return {
|
||
deliveryOrder,
|
||
orderLines: { orderLine: orderLineList },
|
||
// 外部打单平台订单按平台配置回 OMS 取号,手工单默认 0;该参数在请求根节点
|
||
need_oms_waybill: o.need_oms_waybill == null ? 0 : Number(o.need_oms_waybill),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 发货单推送:将 OMS 发货单映射为 WMS deliveryorder.create(ORDER 组,落 wms_order_delivery)并推送
|
||
* @param {Object} order OMS 发货单(已 include warehouse)
|
||
* @param {Array} items 发货单明细
|
||
* @param {Object} [opts] { warehouse, wmsItemIdByItemCode, wmsItemIdByProduct }
|
||
* @return {Promise<{code,message,data}>} WMS 返回(成功时 data.deliveryOrderId 为 WMS 内部订单ID)
|
||
*/
|
||
async createDeliveryOrder(order, items, opts = {}) {
|
||
return this.call('deliveryorder.create', this._buildDeliveryOrder(order, items, opts));
|
||
}
|
||
|
||
/**
|
||
* 发货单取消:调用 order.cancel 取消已推送的外部发货单(ORDER 组:JYCK/HHCK/BFCK)
|
||
* 文档/源码依据:openapiMethods/order.js 的 ORDER_TYPES 按 delivery_order_code 定位 wms_order_delivery,
|
||
* 取消后释放库存锁定、状态置 CANCELLED,并向开放平台回调 `deliveryorder.cancel` 事件。
|
||
* @param {Object} order OMS 发货单(model 实例或 plain)
|
||
* @return {Promise<{code,message,data}>} WMS 返回
|
||
*/
|
||
async cancelDeliveryOrder(order) {
|
||
const o = order.get ? order.get({ plain: true }) : order;
|
||
return this.call('order.cancel', {
|
||
orderCode: o.delivery_order_code || '',
|
||
orderType: this._deliveryOrderType(o.order_type),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 入库单取消:调用 order.cancel 取消已推送的外部入库单
|
||
* 文档/源码依据(D:\wms\methods/qimen.json + app/service/qimenMethods/order.js):
|
||
* `order.cancel` 入参 request.orderCode + request.orderType,RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)
|
||
* 会把入库单 order_status 置 CANCELLED;openapi 渠道(openapiMethods/order.js)只实现了 ORDER/CK 组,
|
||
* 收到 RK 类型会返回业务失败「暂不支持该订单类型的取消操作」——由调用方按「渠道不支持」降级处理。
|
||
* @param {Object} order OMS 入库单(model 实例或 plain)
|
||
* @return {Promise<{code,message,data}>} WMS 返回
|
||
*/
|
||
async cancelInboundOrder(order) {
|
||
const o = order.get ? order.get({ plain: true }) : order;
|
||
return this.call('order.cancel', {
|
||
orderCode: o.bill_no || '',
|
||
orderType: this._inboundOrderType(o.inbound_type),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 库存查询:按 WMS 内部商品ID批量查询库存量(inventory.query)
|
||
* @param {number[]} itemIds WMS 内部商品ID列表
|
||
* @return {Promise<Array<{itemId:number,itemCode:string,quantity:number,lockQuantity:number}>>}
|
||
* 返回 data.items 中的库存明细数组(仅含命中库存记录的商品)
|
||
*/
|
||
async queryInventory(itemIds = []) {
|
||
if (!Array.isArray(itemIds) || itemIds.length === 0) return [];
|
||
const resp = await this.call('inventory.query', { itemIds: itemIds.map(Number) });
|
||
if (!this.isSuccess(resp)) {
|
||
const err = new Error(`WMS 查询库存失败: ${resp && (resp.message || resp.code)}`);
|
||
err.wmsResponse = resp;
|
||
throw err;
|
||
}
|
||
// 兼容 data.items 与顶层 items 两种结构
|
||
if (resp && resp.data && Array.isArray(resp.data.items)) return resp.data.items;
|
||
if (resp && Array.isArray(resp.items)) return resp.items;
|
||
return [];
|
||
}
|
||
|
||
_yn(value) {
|
||
return value === 'Y' || value === 'y' || value === 1 || value === true ? 'Y' : 'N';
|
||
}
|
||
|
||
/**
|
||
* OMS 商品类型 → WMS singleitem.synchronize 的 itemType 英文编码
|
||
* 按 WMS 规范仅使用 ZC(正常商品) / CC(残次品) 两种:
|
||
* - 本系统商品均为正常品,残次品以 product_stocks 的 item_type=CC 库存行表示;
|
||
* - 故推送统一为 ZC(若显式为 'CC' 则直接采用,便于后续为残次单独建 SKU 推送)。
|
||
* @param {number|string} itemType OMS 数值类型或直接给定的编码
|
||
* @return {string} WMS 英文编码(仅 ZC / CC)
|
||
*/
|
||
_mapItemType(itemType) {
|
||
const code = String(itemType == null ? '' : itemType).toUpperCase();
|
||
if (code === 'CC') return 'CC';
|
||
return 'ZC';
|
||
}
|
||
|
||
/**
|
||
* OMS 商品 → WMS item 字段映射(参数名对齐 openapi.json singleitem.synchronize)
|
||
* @param product
|
||
*/
|
||
_buildItem(product) {
|
||
const f = this.fields || {};
|
||
const p = product.get ? product.get({ plain: true }) : product;
|
||
|
||
const nameParts = [ p.item_name ];
|
||
if (f.item_name_with_spec && p.sku_property) nameParts.push(p.sku_property);
|
||
|
||
return {
|
||
itemCode: p.item_code,
|
||
goodsCode: p.goods_code || '',
|
||
itemName: nameParts.join(' ').trim(),
|
||
barCode: p.barcode || '',
|
||
unit: p.stock_unit || '',
|
||
categoryId: p.category_id || 0,
|
||
categoryName: p.category_name || '',
|
||
itemType: this._mapItemType(p.item_type),
|
||
tagPrice: Number(p.tag_price) || 0,
|
||
retailPrice: Number(p.retail_price) || 0,
|
||
brandName: p.brand_name || '',
|
||
isSNMgmt: this._yn(p.is_sn_mgmt),
|
||
isShelfLifeMgmt: this._yn(p.is_shelf_life_mgmt),
|
||
isBatchMgmt: this._yn(p.is_batch_mgmt),
|
||
isAreaSale: this._yn(p.is_area_sale),
|
||
length: Number(p.length) || 0,
|
||
width: Number(p.width) || 0,
|
||
height: Number(p.height) || 0,
|
||
volume: Number(p.volume) || 0,
|
||
grossWeight: Number(p.gross_weight) || 0,
|
||
netWeight: Number(p.net_weight) || 0,
|
||
isValid: 'Y',
|
||
createTime: p.created_at ? new Date(p.created_at).toISOString() : '',
|
||
};
|
||
}
|
||
}
|
||
|
||
module.exports = QimenWmsClient;
|