- principalCheck 中间件加载主体状态:停用主体只放行读请求(GET/HEAD/OPTIONS)与导出任务提交, 其余写操作(新建/编辑/推送/删除)一律 403「主体已停用,仅可查看与导出」 - 可选主体列表包含停用主体并按「启用优先」排序;/api/auth/profile 返回 status/disabled - 顶栏主体下拉显示「xxx(已停用)」且不可选择;当前主体停用时在顶栏下方显示只读提示条 - 定时任务跳过停用主体:自动拉单、订单推送 WMS、发货推送、出库推送、发货结果回传平台、一键拉单任务 - 主体自身的 GET/PUT 未加主体状态校验,运维仍可通过接口重新启用 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
390 lines
15 KiB
JavaScript
390 lines
15 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
const QimenWmsClient = require('../lib/wms/qimenClient');
|
||
const { releaseDeliveryStock } = require('../utils/deliveryStock');
|
||
|
||
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
|
||
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 };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 释放发货单已锁定的库存(best-effort)
|
||
* 失败只记日志不抛出:既不阻塞「退回待审核」状态流转,`stock_locked` 也保持 1,
|
||
* 便于后续驳回/取消/作废时再次尝试释放,不会出现“锁定了但无人认领”的丢失
|
||
* @param {Object} order 发货单实例(需含 id / principal_id / warehouse_id / delivery_order_code / stock_locked)
|
||
* @param {String} remark 备注(写入出入库记录)
|
||
* @return {Promise<void>}
|
||
*/
|
||
async releaseStock(order, remark) {
|
||
try {
|
||
const result = await releaseDeliveryStock(this.ctx, order, { remark });
|
||
if (!result.skipped) {
|
||
this.ctx.logger.info(`[delivery-push] ${order.delivery_order_code} 已释放锁定库存(${result.affected} 行):${remark}`);
|
||
}
|
||
} catch (err) {
|
||
this.ctx.logger.error(`[delivery-push] ${order.delivery_order_code} 释放锁定库存失败:${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: '单据未指定仓库,无法推送' };
|
||
}
|
||
// 手工单必须选店铺:无店铺时不下推(否则报文中没有 shopNick,WMS 匹配不到快递策略)
|
||
if (!(Number(order.shop_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(),
|
||
};
|
||
|
||
// 店铺名称兜底:shopNick 取所选店铺名称(WMS 侧靠它匹配快递策略),
|
||
// 历史数据可能只存了 shop_id 而没写快照,这里补一次并回写
|
||
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(`[delivery-push] ${order.delivery_order_code} 补齐店铺名称快照:${shop.name}`);
|
||
}
|
||
}
|
||
if (!order.shop_nick) {
|
||
ctx.logger.warn(`[delivery-push] ${order.delivery_order_code} 未取到店铺名称(shop_nick 为空),推送报文中不会有 shopNick,WMS 侧可能匹配不到快递策略`);
|
||
}
|
||
|
||
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 this.releaseStock(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 this.releaseStock(order, '推送失败退回待审核,释放锁定库存');
|
||
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 },
|
||
principal_id: { [Op.in]: await ctx.service.cache.getEnabledPrincipalIds() },
|
||
[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;
|