oms/backend/app/service/orderWms.js
liufumingren d4128c4eee fix(order): 修正手工单推送仓库的「未绑定系统商品」误判
- 推送前校验改为「能否解析到系统商品」: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>
2026-11-13 23:17:21 +08:00

551 lines
24 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Service } = require('egg');
const QimenWmsClient = require('../lib/wms/qimenClient');
const { ORDER_STATUS } = require('../lib/orderStatus');
const { releaseOrderStock } = require('../utils/orderStock');
const { getShopBasic, getAccountWithPlatform } = require('../lib/externalPrintConfig');
const { findUnconvertibleItems, unconvertibleMessage } = require('../lib/orderPushItems');
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
const PUSH_MAX_ATTEMPTS = 3;
/** 同一单据两次尝试的最小间隔(毫秒):避免失败单在定时任务里被连续猛推 */
const PUSH_THROTTLE_MS = 20000;
/** 定时任务每次最多处理的单据数 */
const PUSH_PENDING_LIMIT = 10;
/** 手动批量推送每次最多处理的单据数(其余交给定时任务,避免一次请求打爆对方服务) */
const PUSH_BATCH_LIMIT = 50;
/** 手动批量推送时两条之间的间隔(毫秒),用于限流 */
const PUSH_BATCH_GAP_MS = 150;
/**
* 订单推送服务(新表口径:order_index + order_status_queued → order_status_outsourcing)
*
* 与老发货单推送(app/service/orderDeliveryPush.js)口径一致,只是不再把「已审核待推送」与
* 「已推送成功」混在同一状态:
* - 审核后订单进入「待推送」(= 老「已审核(2)」),由定时任务 / 手动推送递交 WMS
* - 推送成功:流转「委外中」,写 pushed_at(乐观锁)、wms_status=已推送、wms_order_no(外部单据ID)、
* wms_synced_at 与 wms_push_result;**等 WMS 回传 deliveryorder.confirm 才流转「配送」**
* - 对方明确响应失败 / 连续超时:流转「异常」并释放审核锁定的库存(老口径为退回待审核)
*
* 并发防重:用 pushed_at 做乐观锁(CAS)抢占单据,多 worker 下同一单只会被一个进程推送一次
*/
class OrderWmsService extends Service {
/**
* 查该仓库启用的类奇门接口配置
* @param {Object} order 订单(需含 principal_id / warehouse_id)
* @return {Promise<Object|null>} warehouse_apis 记录
*/
async findWarehouseApi(order) {
return this.ctx.model.WarehouseApi.findOne({
where: {
warehouse_id: order.warehouse_id,
principal_id: order.principal_id,
type: 'qimen',
status: 1,
},
order: [[ 'id', 'ASC' ]],
});
}
/**
* 按商品编码回查该仓库的 WMS 内部商品ID(warehouse_products.wms_item_id)
* @param {Object} order 订单
* @param {Array} items 订单明细
* @return {Promise<Object>} { byProduct, byItemCode }
*/
async resolveWmsItemIds(order, items) {
const Op = this.app.Sequelize.Op;
const productIds = [ ...new Set((items || []).map(i => Number(i.product_id)).filter(id => Number.isInteger(id) && id > 0)) ];
const codes = [ ...new Set((items || []).map(i => i.item_code).filter(Boolean)) ];
if (!productIds.length && !codes.length) return { byProduct: {}, byItemCode: {}, productById: {} };
const where = { principal_id: order.principal_id };
if (productIds.length && codes.length) {
where[Op.or] = [{ id: { [Op.in]: productIds } }, { item_code: { [Op.in]: codes } }];
} else if (productIds.length) {
where.id = { [Op.in]: productIds };
} else {
where.item_code = { [Op.in]: codes };
}
const products = await this.ctx.model.Product.findAll({
where,
attributes: [ 'id', 'item_code', 'item_name' ],
});
if (!products.length) return { byProduct: {}, byItemCode: {}, productById: {} };
const links = await this.ctx.model.WarehouseProduct.findAll({
where: {
principal_id: order.principal_id,
warehouse_id: order.warehouse_id,
product_id: { [Op.in]: products.map(p => Number(p.id)) },
},
attributes: [ 'product_id', 'wms_item_id' ],
});
const byProduct = {};
for (const l of links) {
if (l.wms_item_id != null) byProduct[Number(l.product_id)] = Number(l.wms_item_id);
}
const byItemCode = {};
// 明细上的商品编码 → 系统商品(推送报文优先用系统商品的编码/名称,避免平台原值下发)
const productById = {};
for (const p of products) {
const wmsItemId = byProduct[Number(p.id)];
if (wmsItemId != null) byItemCode[p.item_code] = wmsItemId;
productById[Number(p.id)] = { item_code: p.item_code, item_name: p.item_name };
}
return { byProduct, byItemCode, productById };
}
/**
* 推送前校验明细是否已落到「系统商品」
*
* 判据不是「有没有 product_id」而是「能否解析到系统商品」(见 app/lib/orderPushItems.js):
* - 平台拉单的明细必须完成「店铺商品 → 系统商品」绑定,否则推给仓库的会是平台编码;
* - 手工单 / 接口建单的明细则直接选系统商品(历史数据把系统商品ID 存在 item_id),
* 按主体商品库核对 ID / 编码即可,不能因为缺少店铺商品绑定而拦下。
* @param {Object} order 订单(需含 principal_id)
* @param {Array} items 明细(order_status_items,已展开为最小单位)
* @return {Promise<{ok: Boolean, message: String}>} 校验结果(不通过时 message 为原因)
*/
async validateConvertedItems(order, items) {
const list = Array.isArray(items) ? items : [];
if (!list.length) return { ok: true, message: '' };
const Op = this.app.Sequelize.Op;
const ids = [ ...new Set(
[ ...list.map(item => Number(item.product_id)), ...list.map(item => Number(item.item_id)) ]
.filter(id => Number.isInteger(id) && id > 0)
) ];
const codes = [ ...new Set(list.map(item => String(item.item_code == null ? '' : item.item_code).trim()).filter(Boolean)) ];
const or = [];
if (ids.length) or.push({ id: { [Op.in]: ids } });
if (codes.length) or.push({ item_code: { [Op.in]: codes } });
const products = or.length
? await this.ctx.model.Product.findAll({
where: { principal_id: order.principal_id, [Op.or]: or },
attributes: [ 'id', 'item_code' ],
raw: true,
})
: [];
const invalid = findUnconvertibleItems(list, products);
return invalid.length ? { ok: false, message: unconvertibleMessage(invalid) } : { ok: true, message: '' };
}
/**
* 冲正外部单据(best-effort,失败只记录不抛出)
* @param {Object} client QimenWmsClient
* @param {Object} order 订单(适配后的视图对象)
* @return {Promise<Object>} 冲正返回或异常信息
*/
async cancelRemote(client, order) {
try {
return await client.cancelDeliveryOrder(order);
} catch (err) {
return { code: 'EXCEPTION', message: err.message };
}
}
/**
* 释放订单已锁定的库存(best-effort;失败只记日志,`stock_locked` 保持 1 便于后续再释放)
* @param {Object} order 状态表行实例
* @param {String} remark 备注(写库存流水)
* @param {Object} [transaction] 事务
* @return {Promise<void>} 无
*/
async releaseStock(order, remark, transaction) {
try {
const result = await releaseOrderStock(this.ctx, order, { remark, transaction });
if (!result.skipped) {
this.ctx.logger.info(`[order-wms] ${order.order_no} 已释放锁定库存(${result.affected} 行):${remark}`);
}
} catch (err) {
this.ctx.logger.error(`[order-wms] ${order.order_no} 释放锁定库存失败:${err.message}`);
}
}
/**
* 取上次推送记录(wms_push_result JSON)
* @param {Object} order 状态表行实例
* @return {Object} 上次记录(无则空对象)
*/
_prevResult(order) {
const raw = order.wms_push_result;
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
}
/**
* 状态表行 → 奇门客户端可用的发货单视图
* 新表字段沿用老表列名,只需把 order_no/receiver 映射成 delivery_order_code/name
* @param {Object} row 状态表行实例
* @param {Object} warehouse 仓库(含 code)
* @return {Object} 视图对象
*/
adaptOrder(row, warehouse) {
const plain = row.get ? row.get({ plain: true }) : { ...row };
return {
...plain,
delivery_order_code: plain.order_no,
name: plain.receiver,
warehouse_code: plain.warehouse_code || (warehouse && warehouse.code) || null,
warehouse: warehouse ? (warehouse.get ? warehouse.get({ plain: true }) : warehouse) : null,
};
}
/**
* 判断外部打单平台订单是否需要回 OMS 取号
*
* 以订单店铺绑定的打单账号所属平台配置 `fetch_waybill_no` 为准(1=需要回取号);
* 手工店铺 / 非外部打单平台订单恒为 0。
* 店铺与账号平台配置均走缓存(CACHE_TTL_SHOP / CACHE_TTL_PLATFORM),避免批量推送时逐单查库。
* @param {Object} order 订单
* @param {Object|null} shop 店铺(含 type / external_print_account_id)
* @return {Promise<number>} 1 需要回 OMS 取号,0 否
*/
async resolveNeedOmsWaybill(order, shop) {
if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) return 0;
const account = await getAccountWithPlatform(this.ctx, shop.external_print_account_id, order.principal_id);
return account && account.platform && Number(account.platform.fetch_waybill_no) === 1 ? 1 : 0;
}
/**
* 加载待推送订单(含仓库),仅返回「待推送」的单据
* @param {Number|String} id 订单ID
* @return {Promise<Object|null>} 状态表行实例
*/
async loadOrder(id) {
return this.ctx.model.OrderStatusQueued.findByPk(id);
}
/**
* 推送单条订单(一次尝试)
*
* 返回 ok=false 时:
* - retry=true :无响应/超时,单据保留「待推送」,等下次定时任务重试
* - retry=false:对方明确失败或已达重试上限,单据已流转「异常」并释放锁定库存
* @param {Number|String} id 订单ID
* @param {Object} [options] { source: 'schedule' | 'manual' | 'batch' }
* @return {Promise<{ok: Boolean, skipped?: Boolean, retry?: Boolean, message: String, response?: Object, attempts?: Number}>} 推送结果
*/
async pushOne(id, options = {}) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const source = options.source || 'manual';
const order = await this.loadOrder(id);
if (!order) return { ok: false, skipped: true, message: '订单不存在或不在「待推送」' };
// 以下三项属「永久性前置缺失」:标 fatal,由调用方(定时任务)转「异常」并写明原因,避免单据卡在待推送
if (!(Number(order.warehouse_id) > 0)) {
return { ok: false, skipped: true, fatal: true, message: '订单未设置仓库,无法推送:请补全仓库后重新审核' };
}
if (!(Number(order.shop_id) > 0)) {
return { ok: false, skipped: true, fatal: true, message: '订单未设置店铺,无法推送:请先设置店铺(批量操作 → 设置所属店铺)' };
}
const api = await this.findWarehouseApi(order);
if (!api) {
return {
ok: false,
skipped: true,
fatal: true,
message: `仓库#${order.warehouse_id} 未配置启用中的类奇门接口,无法推送:请到「外部仓库」补全接口配置`,
};
}
const warehouse = await ctx.model.Warehouse.findByPk(order.warehouse_id, { attributes: [ 'id', 'code', 'name' ] });
// 乐观锁抢占:多 worker / 并发请求下同一单只推一次(同时把本次尝试时间写入 pushed_at)
const now = new Date();
const throttleBefore = new Date(now.getTime() - PUSH_THROTTLE_MS);
const [ claimed ] = await ctx.model.OrderStatusQueued.update(
{ pushed_at: now },
{
where: {
id: order.id,
principal_id: order.principal_id,
status: ORDER_STATUS.QUEUED,
[Op.or]: [
{ pushed_at: null },
{ pushed_at: { [Op.lt]: throttleBefore } },
],
},
}
);
if (!claimed) {
return { ok: false, skipped: true, message: '该订单正在推送或处于重试间隔内,已跳过' };
}
order.pushed_at = now;
const prev = this._prevResult(order);
const attempts = Number(prev.attempts || 0) + 1;
const base = {
orderId: Number(order.id),
deliveryOrderCode: order.order_no,
warehouseApiId: api.id,
apiType: api.type,
attempts,
maxAttempts: PUSH_MAX_ATTEMPTS,
source,
attemptedAt: now.toISOString(),
};
// 店铺信息:补齐店铺名称快照,并判断外部打单平台订单是否需要回 OMS 取号(店铺资料走缓存)
const shop = order.shop_id ? await getShopBasic(ctx, order.shop_id, order.principal_id) : null;
if (!order.shop_nick && shop && shop.name) {
order.shop_nick = shop.name;
await order.update({ shop_nick: shop.name });
ctx.logger.info(`[order-wms] ${order.order_no} 补齐店铺名称快照:${shop.name}`);
}
if (!order.shop_nick) {
ctx.logger.warn(`[order-wms] ${order.order_no} 未取到店铺名称(shop_nick 为空),推送报文中不会有 shopNick`);
}
// 回 OMS 取号开关:外部打单平台订单按平台配置实时判定(配置变更后未推送的订单也能生效)
const needOmsWaybill = await this.resolveNeedOmsWaybill(order, shop);
if (Number(order.need_oms_waybill) !== needOmsWaybill) {
// 平台配置可能在建单后调整,推送前把实际下发值回写,保证单据记录与报文一致
order.need_oms_waybill = needOmsWaybill;
await order.update({ need_oms_waybill: needOmsWaybill });
}
if (needOmsWaybill) {
ctx.logger.info(`[order-wms] ${order.order_no} 外部打单平台要求回 OMS 取号,推送 need_oms_waybill=1`);
}
const itemRows = await ctx.model.OrderStatusItem.findAll({
where: { order_id: order.id, principal_id: order.principal_id },
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
});
if (!itemRows.length) {
await order.update({
wms_push_result: { ...base, success: false, failureKind: 'empty_items', message: '订单无明细,无法推送' },
});
return { ok: false, retry: false, fatal: true, message: '订单无明细,无法推送', attempts };
}
const client = new QimenWmsClient(api, this.app);
const items = itemRows.map(item => item.get({ plain: true }));
// 明细必须能落到系统商品(平台订单需先绑定店铺商品;手工单按商品库核对),否则推给仓库的会是平台编码
const itemCheck = await this.validateConvertedItems(order, items);
if (!itemCheck.ok) {
await order.update({
wms_push_result: { ...base, success: false, failureKind: 'unbound_items', message: itemCheck.message },
});
ctx.logger.warn(`[order-wms] ${order.order_no} 推送中止:${itemCheck.message}`);
return { ok: false, retry: false, fatal: true, message: itemCheck.message, attempts };
}
const wmsItemIds = await this.resolveWmsItemIds(order, items);
const view = this.adaptOrder(order, warehouse);
// 请求根节点参数:外部打单平台订单按平台配置决定是否回 OMS 取号
view.need_oms_waybill = needOmsWaybill;
let resp;
try {
resp = await client.createDeliveryOrder(view, items, {
warehouse: view.warehouse,
wmsItemIdByProduct: wmsItemIds.byProduct,
wmsItemIdByItemCode: wmsItemIds.byItemCode,
// 报文里的商品编码/名称以系统商品为准(明细可能是拉单时的平台原值)
productById: wmsItemIds.productById,
});
} catch (err) {
// 超时 / 网络异常 / 非法响应:可重试
const canRetry = attempts < PUSH_MAX_ATTEMPTS;
if (canRetry) {
await order.update({
wms_push_result: { ...base, success: false, failureKind: 'timeout', retryable: true, error: err.message },
});
ctx.logger.warn(`[order-wms] ${order.order_no} 第 ${attempts}/${PUSH_MAX_ATTEMPTS} 次推送异常(将重试):${err.message}`);
return { ok: false, retry: true, message: err.message, attempts };
}
const cancelResult = await this.cancelRemote(client, view);
await order.update({
wms_push_result: {
...base,
success: false,
failureKind: 'timeout',
retryable: false,
error: err.message,
cancelResult,
},
});
await this.toException(order, `连续 ${attempts} 次推送无响应/超时:${err.message}`);
ctx.logger.error(`[order-wms] ${order.order_no} 连续 ${attempts} 次推送异常,已转异常:${err.message}`);
return { ok: false, retry: false, message: `连续 ${attempts} 次无响应/超时,已转异常:${err.message}`, attempts };
}
if (client.isSuccess(resp)) {
const externalNo = resp && (resp.deliveryOrderId || resp.outBizCode || null);
// 推送成功才进「委外中」:外部单据号 + 推送痕迹与状态流转同事务写入(字段随流转一并搬表)
await ctx.service.orderStatus.markPushed({
ids: [ Number(order.id) ],
principalId: Number(order.principal_id),
overrides: {
pushed_at: now,
operate_time: now,
wms_status: 'pushed',
wms_order_no: externalNo == null ? order.wms_order_no : String(externalNo),
wms_synced_at: now,
wms_push_result: { ...base, success: true, response: resp },
},
});
ctx.logger.info(`[order-wms] ${order.order_no} 推送成功(第 ${attempts} 次),已转「委外中」`);
return { ok: true, message: '已推送仓库', response: resp, attempts };
}
// 对方明确响应失败:不重试,转「异常」并释放审核锁定的库存
const cancelResult = await this.cancelRemote(client, view);
const message = resp && (resp.message || resp.code);
await order.update({
wms_push_result: {
...base,
success: false,
failureKind: 'business',
retryable: false,
code: resp && resp.code,
message,
response: resp,
cancelResult,
},
});
await this.toException(order, `推送仓库失败:${message}`);
ctx.logger.warn(`[order-wms] ${order.order_no} 推送失败(对方明确拒绝),已转异常:${message}`);
return { ok: false, retry: false, message: `WMS 返回失败:${message}`, response: resp, attempts };
}
/**
* 推送失败转「异常」(释放锁定库存 + 状态流转,同一事务)
* @param {Object} order 状态表行实例(委外中)
* @param {String} reason 异常原因(写入备注)
* @return {Promise<void>} 无
*/
async toException(order, reason) {
await this.ctx.service.orderStatus.markPushFailed({
ids: [ Number(order.id) ],
principalId: Number(order.principal_id),
reason,
});
}
/**
* 扫描「待推送」的订单并推送(定时任务入口)
*
* 扫描范围:全部待推送订单(**不过滤仓库**,否则无仓库/无接口配置的单据会永远卡在队列里);
* ① 可推送 → 递交 WMS:成功转「委外中」、失败转「异常」
* ② 永久性前置缺失(无仓库 / 无店铺 / 仓库无启用接口 / 无明细)→ 转「异常」并写明原因
* ③ 瞬时跳过(另一 worker 正在推送 / 重试间隔内)→ 保留待推送,下轮再试
* @param {Object} [options] { limit }
* @return {Promise<Object>} { scanned, pushed, failed, retry, skipped, aborted }
*/
async processPending(options = {}) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const limit = Number(options.limit) > 0 ? Number(options.limit) : PUSH_PENDING_LIMIT;
const throttleBefore = new Date(Date.now() - PUSH_THROTTLE_MS);
const orders = await ctx.model.OrderStatusQueued.findAll({
where: {
status: ORDER_STATUS.QUEUED,
principal_id: { [Op.in]: await ctx.service.cache.getEnabledPrincipalIds() },
[Op.or]: [
{ pushed_at: null },
{ pushed_at: { [Op.lt]: throttleBefore } },
],
},
attributes: [ 'id', 'principal_id' ],
order: [[ 'pushed_at', 'ASC' ], [ 'id', 'ASC' ]],
limit,
});
const stat = { scanned: orders.length, pushed: 0, failed: 0, retry: 0, skipped: 0, aborted: 0 };
for (const row of orders) {
const res = await this.pushOne(row.id, { source: 'schedule' });
if (res.ok) {
stat.pushed++;
} else if (res.fatal) {
// 永久性前置缺失:转异常(释放锁定库存 + 写明原因),队列不再残留
stat.aborted++;
try {
await ctx.service.orderStatus.markPushFailed({
ids: [ Number(row.id) ],
principalId: Number(row.principal_id),
reason: res.message,
});
} catch (err) {
ctx.logger.error(`[order-wms] id=${row.id} 转异常失败:${err.message}`);
}
} else if (res.skipped) {
stat.skipped++;
} else if (res.retry) {
stat.retry++;
} else {
stat.failed++;
}
}
return stat;
}
/**
* 批量推送指定ID列表(限流顺序执行)
* @param {Array} ids 订单ID列表
* @param {Object} [options] { limit, gap }
* @return {Promise<Object>} { requested, processed, pendingRest, pushed, failed, retry, skipped, details }
*/
async pushMany(ids, options = {}) {
const limit = Number(options.limit) > 0 ? Number(options.limit) : PUSH_BATCH_LIMIT;
const gap = options.gap === undefined ? PUSH_BATCH_GAP_MS : Number(options.gap);
const targets = ids.slice(0, limit);
const result = {
requested: ids.length,
processed: targets.length,
pendingRest: Math.max(ids.length - targets.length, 0),
pushed: 0,
failed: 0,
retry: 0,
skipped: 0,
aborted: 0,
details: [],
};
for (let i = 0; i < targets.length; i++) {
const res = await this.pushOne(targets[i], { source: 'batch' });
if (res.ok) result.pushed++;
else if (res.fatal) result.aborted++;
else if (res.skipped) result.skipped++;
else if (res.retry) result.retry++;
else result.failed++;
result.details.push({ id: targets[i], ok: res.ok, fatal: Boolean(res.fatal), message: res.message });
if (gap > 0 && i < targets.length - 1) await new Promise(resolve => setTimeout(resolve, gap));
}
return result;
}
/**
* 取消外部单据(已推送成功、处于委外中的订单取消前调用)
* @param {Object} order 状态表行实例
* @return {Promise<Object>} { ok: Boolean, message: String, response?: Object }
*/
async cancelRemoteOrder(order) {
const api = await this.findWarehouseApi(order);
if (!api) return { ok: false, message: '该仓库未配置启用的类奇门接口,无法取消已推送的外部单据' };
const warehouse = await this.ctx.model.Warehouse.findByPk(order.warehouse_id, { attributes: [ 'id', 'code' ] });
const client = new QimenWmsClient(api, this.app);
const view = this.adaptOrder(order, warehouse);
let resp;
try {
resp = await client.cancelDeliveryOrder(view);
} catch (err) {
return { ok: false, message: `取消仓库单据失败:${err.message}` };
}
if (!client.isSuccess(resp)) {
return { ok: false, message: `取消仓库单据失败:${resp && (resp.message || resp.code)}`, response: resp };
}
return { ok: true, message: '已取消外部单据', response: resp };
}
}
module.exports = OrderWmsService;