oms/backend/app/service/orderWms.js
liufumingren 6c03a20364 feat(backend): 订单状态分表、WMS 推送与归档
- 新增 order_index 索引表 + 6 张同构状态表(待审核/异常/委外中/配送/已作废/已取消)与历史表,
  订单 ID 全局唯一,状态由业务事务推动:审核、驳回、取消、作废、恢复、归档
- 明细表 order_status_items、收件人文本智能解析、批量切换仓库/店铺并刷新快照
- WMS deliveryorder.create 推送(单条/批量)、推送失败定时重试、订单归档定时任务
- 迁移:建表、旧发货单数据迁入新表、菜单合并与迁移记录清理
- routes / swagger contract 补充订单状态接口

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-30 23:06:18 +08:00

458 lines
18 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');
const QimenWmsClient = require('../lib/wms/qimenClient');
const { ORDER_STATUS } = require('../lib/orderStatus');
const { releaseOrderStock } = require('../utils/orderStock');
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
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 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 };
}
}
/**
* 释放订单已锁定的库存(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,
};
}
/**
* 加载待推送订单(含仓库),仅返回「待推送」的单据
* @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(),
};
// 店铺名称兜底:shopNick 取所选店铺名称(WMS 侧靠它匹配快递策略)
if (!order.shop_nick && order.shop_id) {
const shop = await ctx.model.Shop.findByPk(order.shop_id, { attributes: [ 'id', 'name' ] });
if (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`);
}
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 wmsItemIds = await this.resolveWmsItemIds(order, items);
const view = this.adaptOrder(order, warehouse);
let resp;
try {
resp = await client.createDeliveryOrder(view, items, {
warehouse: view.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(`[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,
[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;