oms/backend/app/service/orderDeliveryPush.js
liufumingren 11e7b26ced feat(backend): 发货单模块与 WMS 定时推送队列
- 发货单主表/明细表(order_deliveries / order_delivery_items)控制器与模型
- 表头金额与明细派生字段重算(utils/recalcOrderDelivery.js)
- 状态流转:审核/驳回/取消/恢复/作废、批量审核、批量切换仓库
- 审核入队 + 定时推送:service/orderDeliveryPush.js(乐观锁 CAS 防重、失败重试上限 3 次、业务失败退回待审核)+ schedule/orderDeliveryPush.js
- 收件人 AI 智能识别(service/ai.js,DeepSeek)
- 相关迁移:建表、站内字段、明细表、订单类型默认值、快递字典、菜单种子、历史数据搬迁
2026-09-13 02:23:47 +08:00

349 lines
13 KiB
JavaScript
Raw 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').Service;
const QimenWmsClient = require('../lib/wms/qimenClient');
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
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_deliveries.status):
* - 审核(1→2):仅入队,不推送
* - 推送成功(2→3):写 pushed_at / wms_push_result
* - 对方服务明确响应失败:判定推送失败,退回「待审核(1)」并记录原因
* - 无响应/超时/网络异常:保留「已审核(2)」等待下次重试,最多 3 次;达到 3 次仍失败同样退回「待审核(1)」
*
* 并发防重:用 pushed_at 做乐观锁(CAS)抢占单据,多 worker 下同一单只会被一个进程推送一次
*/
class OrderDeliveryPushService 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<{byProduct: Object, byItemCode: Object}>} 两种键的映射(未推送到该仓库的商品不会出现)
*/
async resolveWmsItemIds(order, items) {
const Op = this.app.Sequelize.Op;
const codes = [ ...new Set((items || []).map(i => i.item_code).filter(Boolean)) ];
if (!codes.length) return { byProduct: {}, byItemCode: {} };
const products = await this.ctx.model.Product.findAll({
where: { principal_id: order.principal_id, item_code: { [Op.in]: codes } },
attributes: [ 'id', 'item_code' ],
});
if (!products.length) return { byProduct: {}, byItemCode: {} };
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 = {};
for (const p of products) {
const wmsItemId = byProduct[Number(p.id)];
if (wmsItemId != null) byItemCode[p.item_code] = wmsItemId;
}
return { byProduct, byItemCode };
}
/**
* 冲正外部发货单(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 };
}
}
/**
* 取上次推送记录(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 : {};
}
/**
* 加载待推送单据(含仓库)
* @param {number|string} id 发货单ID
* @return {Promise<Object|null>} 发货单实例
*/
async loadOrder(id) {
return this.ctx.model.OrderDelivery.findByPk(id, {
include: [{ model: this.ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] }],
});
}
/**
* 推送单条发货单(一次尝试)
*
* 返回 ok=false 时:
* - retry=true :无响应/超时,单据保留「已审核(2)」,等下次定时任务重试
* - retry=false:对方明确失败或已达重试上限,单据已退回「待审核(1)」
* @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, message: '发货单不存在' };
if (Number(order.status) !== 2) {
return { ok: false, skipped: true, message: `当前状态不可推送(status=${order.status})` };
}
if (!(Number(order.warehouse_id) > 0)) {
return { ok: false, skipped: true, message: '单据未指定仓库,无法推送' };
}
const api = await this.findWarehouseApi(order);
if (!api) {
return {
ok: false,
skipped: true,
message: `仓库「${order.warehouse ? `${order.warehouse.name}(${order.warehouse.code})` : `#${order.warehouse_id}`}」未配置启用中的类奇门接口`,
};
}
// 乐观锁抢占:多 worker / 并发请求下同一单只推一次(同时把本次尝试时间写入 pushed_at)
const now = new Date();
const throttleBefore = new Date(now.getTime() - PUSH_THROTTLE_MS);
const [ claimed ] = await ctx.model.OrderDelivery.update(
{ pushed_at: now },
{
where: {
id: order.id,
status: 2,
[Op.or]: [
{ pushed_at: null },
{ pushed_at: { [Op.lt]: throttleBefore } },
],
},
}
);
if (!claimed) {
return { ok: false, skipped: true, message: '该单据正在推送或处于重试间隔内,已跳过' };
}
const prev = this._prevResult(order);
const attempts = Number(prev.attempts || 0) + 1;
const base = {
deliveryOrderCode: order.delivery_order_code,
warehouseApiId: api.id,
apiType: api.type,
attempts,
maxAttempts: PUSH_MAX_ATTEMPTS,
source,
attemptedAt: now.toISOString(),
};
const items = await ctx.model.OrderDeliveryItem.findAll({
where: { order_delivery_id: order.id },
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
});
if (!items.length) {
await order.update({
wms_push_result: { ...base, success: false, failureKind: 'empty_items', message: '单据无明细,无法推送' },
});
return { ok: false, retry: false, message: '单据无明细,无法推送', attempts };
}
const client = new QimenWmsClient(api, this.app);
const wmsItemIds = await this.resolveWmsItemIds(order, items);
let resp;
try {
resp = await client.createDeliveryOrder(order, items, {
warehouse: order.warehouse,
wmsItemIdByProduct: wmsItemIds.byProduct,
wmsItemIdByItemCode: wmsItemIds.byItemCode,
});
} 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(`[delivery-push] ${order.delivery_order_code} 第 ${attempts}/${PUSH_MAX_ATTEMPTS} 次推送异常(将重试):${err.message}`);
return { ok: false, retry: true, message: err.message, attempts };
}
// 达到上限:冲正外部单据后退回「待审核(1)」
const cancelResult = await this.cancelRemote(client, order);
await order.update({
status: 1,
audit_by: null,
audit_time: null,
wms_push_result: {
...base,
success: false,
failureKind: 'timeout',
retryable: false,
error: err.message,
cancelResult,
},
});
ctx.logger.error(`[delivery-push] ${order.delivery_order_code} 连续 ${attempts} 次推送异常,已退回待审核:${err.message}`);
return { ok: false, retry: false, message: `连续 ${attempts} 次无响应/超时,已退回待审核:${err.message}`, attempts };
}
if (client.isSuccess(resp)) {
await order.update({
status: 3,
pushed_at: now,
operate_time: now,
wms_push_result: { ...base, success: true, response: resp },
});
ctx.logger.info(`[delivery-push] ${order.delivery_order_code} 推送成功(第 ${attempts} 次)`);
return { ok: true, message: '已推送仓库', response: resp, attempts };
}
// 对方明确响应失败:不重试,冲正后退回「待审核(1)」
const cancelResult = await this.cancelRemote(client, order);
const message = resp && (resp.message || resp.code);
await order.update({
status: 1,
audit_by: null,
audit_time: null,
wms_push_result: {
...base,
success: false,
failureKind: 'business',
retryable: false,
code: resp && resp.code,
message,
response: resp,
cancelResult,
},
});
ctx.logger.warn(`[delivery-push] ${order.delivery_order_code} 推送失败(对方明确拒绝),已退回待审核:${message}`);
return { ok: false, retry: false, message: `WMS 返回失败:${message}`, response: resp, attempts };
}
/**
* 扫描「已审核(2)」的单据并推送(定时任务入口)
* @param {Object} [options] { limit }
* @return {Promise<{scanned: number, pushed: number, failed: number, retry: number, skipped: number}>}
*/
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.OrderDelivery.findAll({
where: {
status: 2,
warehouse_id: { [Op.ne]: null },
[Op.or]: [
{ pushed_at: null },
{ pushed_at: { [Op.lt]: throttleBefore } },
],
},
attributes: [ 'id' ],
// pushed_at 为 NULL(从未尝试)优先,其次按尝试时间升序
order: [[ 'pushed_at', 'ASC' ], [ 'id', 'ASC' ]],
limit,
});
const stat = { scanned: orders.length, pushed: 0, failed: 0, retry: 0, skipped: 0 };
for (const row of orders) {
const res = await this.pushOne(row.id, { source: 'schedule' });
if (res.ok) stat.pushed++;
else if (res.skipped) stat.skipped++;
else if (res.retry) stat.retry++;
else stat.failed++;
}
return stat;
}
/**
* 批量推送指定ID列表(限流顺序执行)
* @param {number[]} ids 发货单ID列表
* @param {Object} [options] { limit, gap }
* @return {Promise<{requested: number, processed: number, pendingRest: number, pushed: number, failed: number, retry: number, skipped: number, details: Array}>}
*/
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,
details: [],
};
for (let i = 0; i < targets.length; i++) {
const id = targets[i];
const res = await this.pushOne(id, { source: 'batch' });
if (res.ok) result.pushed++;
else if (res.skipped) result.skipped++;
else if (res.retry) result.retry++;
else result.failed++;
result.details.push({
id: Number(id),
ok: res.ok,
skipped: !!res.skipped,
retry: !!res.retry,
message: res.message,
});
if (gap > 0 && i < targets.length - 1) {
await new Promise(resolve => setTimeout(resolve, gap));
}
}
return result;
}
}
module.exports = OrderDeliveryPushService;