- principalCheck 中间件加载主体状态:停用主体只放行读请求(GET/HEAD/OPTIONS)与导出任务提交, 其余写操作(新建/编辑/推送/删除)一律 403「主体已停用,仅可查看与导出」 - 可选主体列表包含停用主体并按「启用优先」排序;/api/auth/profile 返回 status/disabled - 顶栏主体下拉显示「xxx(已停用)」且不可选择;当前主体停用时在顶栏下方显示只读提示条 - 定时任务跳过停用主体:自动拉单、订单推送 WMS、发货推送、出库推送、发货结果回传平台、一键拉单任务 - 主体自身的 GET/PUT 未加主体状态校验,运维仍可通过接口重新启用 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
518 lines
20 KiB
JavaScript
518 lines
20 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
const QimenWmsClient = require('../lib/wms/qimenClient');
|
||
const { applyStockChange } = require('../utils/stockRecord');
|
||
|
||
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
|
||
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;
|
||
|
||
/**
|
||
* 出库单推送服务(审核入队 → 定时任务/手动推送)
|
||
*
|
||
* 状态机约定(outbound_orders.status):
|
||
* - 审核(1→2):仅入队,不推送(清空上一轮推送记录,重试计数归零)
|
||
* - 推送成功(2→3):锁定库存(占用可用,防超卖)、写 operate_time/pushed_at/wms_push_result
|
||
* - 对方服务明确响应失败 / 库存锁定失败:判定失败,释放锁定库存 + best-effort 冲正外部单据,退回「待出库(1)」
|
||
* - 无响应/超时/网络异常:保留「已审核(2)」等下次重试(此时库存保持锁定,不重复锁定),最多 3 次;
|
||
* 达到 3 次仍失败同样退回「待出库(1)」并释放锁定
|
||
*
|
||
* 并发防重:用 pushed_at 做乐观锁(CAS)抢占单据,多 worker 下同一单只会被一个进程推送一次
|
||
* 库存标记:outbound_orders.stock_locked(1=当前占用着锁定库存),释放/扣减后置 0
|
||
*/
|
||
class OutboundOrderPushService 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_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.OutboundOrder.findByPk(id, {
|
||
include: [
|
||
{ model: this.ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
|
||
{ model: this.ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
|
||
],
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 取参与推送的明细(仅已关联商品的明细:无商品的行既不锁定库存也无法下发 itemId)
|
||
* @param {number|string} orderId 出库单ID
|
||
* @return {Promise<Array>} stock_items 明细
|
||
*/
|
||
async loadItems(orderId) {
|
||
const Op = this.app.Sequelize.Op;
|
||
return this.ctx.model.StockItem.findAll({
|
||
where: { bill_type: 2, bill_id: orderId, product_id: { [Op.ne]: null } },
|
||
attributes: [ 'id', 'product_id', 'code', 'name', 'quantity', 'inventory_type' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 取明细对应商品档案(写库存流水需要编码/名称快照)
|
||
* @param {Array} items 明细
|
||
* @return {Promise<Map>} productId -> product
|
||
*/
|
||
async loadProductMap(items) {
|
||
const Op = this.app.Sequelize.Op;
|
||
const ids = [ ...new Set(items.map(i => Number(i.product_id)).filter(Boolean)) ];
|
||
if (!ids.length) return new Map();
|
||
const rows = await this.ctx.model.Product.findAll({
|
||
where: { id: { [Op.in]: ids } },
|
||
attributes: [ 'id', 'item_code', 'item_name' ],
|
||
});
|
||
return new Map(rows.map(p => [ Number(p.id), p ]));
|
||
}
|
||
|
||
/**
|
||
* 按商品回查该仓库的 WMS 内部商品ID(warehouse_products.wms_item_id,stockout.create 的 itemId 必填)
|
||
* @param {Object} order 出库单
|
||
* @param {Array} items 明细
|
||
* @return {Promise<Object>} productId -> wms_item_id
|
||
*/
|
||
async resolveWmsItemIds(order, items) {
|
||
const Op = this.app.Sequelize.Op;
|
||
const productIds = [ ...new Set(items.map(i => Number(i.product_id)).filter(Boolean)) ];
|
||
if (!productIds.length) return {};
|
||
|
||
const links = await this.ctx.model.WarehouseProduct.findAll({
|
||
where: {
|
||
principal_id: order.principal_id,
|
||
warehouse_id: order.warehouse_id,
|
||
product_id: { [Op.in]: productIds },
|
||
},
|
||
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);
|
||
}
|
||
return byProduct;
|
||
}
|
||
|
||
/**
|
||
* 冲正外部出库单(best-effort,失败只记录不抛出)
|
||
* @param {Object} client QimenWmsClient
|
||
* @param {Object} order 出库单
|
||
* @return {Promise<Object>} 冲正返回或异常信息
|
||
*/
|
||
async cancelRemote(client, order) {
|
||
try {
|
||
return await client.cancelOrder(order);
|
||
} catch (err) {
|
||
return { code: 'EXCEPTION', message: err.message };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 锁定库存(推送前占用可用,防超卖)并记 outbound_lock 流水,与 stock_locked 标记同事务
|
||
*
|
||
* 已锁定(stock_locked=1)时直接跳过:推送无响应重试时库存保持锁定,不能重复占用
|
||
* @param {Object} order 出库单实例
|
||
* @param {Array} items 明细
|
||
* @param {Map} pmap productId -> product(流水快照)
|
||
* @param {Object} [options] { remark }
|
||
* @return {Promise<{skipped: boolean, affected: number}>}
|
||
* @throws {Error} 库存不足时抛 INSUFFICIENT_STOCK(message 已带商品名/可用/需求)
|
||
*/
|
||
async lockStock(order, items, pmap, options = {}) {
|
||
const { ctx } = this;
|
||
if (Number(order.stock_locked) === 1) return { skipped: true, affected: 0 };
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
let affected = 0;
|
||
try {
|
||
for (const it of items) {
|
||
const pid = Number(it.product_id);
|
||
try {
|
||
// 行级库存类型:CC=残次 -> 锁定残次库存,其余(ZP等)归为正品 ZC
|
||
await applyStockChange(ctx, {
|
||
bizType: 'outbound_lock',
|
||
principalId: order.principal_id,
|
||
warehouseId: order.warehouse_id,
|
||
productId: pid,
|
||
itemCode: it.code || (pmap.get(pid) && pmap.get(pid).item_code),
|
||
itemName: it.name || (pmap.get(pid) && pmap.get(pid).item_name),
|
||
itemType: it.inventory_type === 'CC' ? 'CC' : 'ZC',
|
||
quantity: Number(it.quantity) || 0,
|
||
billId: order.id,
|
||
billNo: order.bill_no,
|
||
createdBy: ctx.userId,
|
||
remark: options.remark || '出库单推送仓库锁定库存',
|
||
transaction,
|
||
});
|
||
} catch (err) {
|
||
if (err.code === 'INSUFFICIENT_STOCK') {
|
||
const p = pmap.get(pid);
|
||
err.message = `库存不足:${p ? `${p.item_name}(${p.item_code})` : '商品#' + pid},可用 ${err.available},需 ${err.require}`;
|
||
}
|
||
throw err;
|
||
}
|
||
affected += 1;
|
||
}
|
||
await order.update({ stock_locked: 1 }, { transaction });
|
||
await transaction.commit();
|
||
order.stock_locked = 1;
|
||
return { skipped: false, affected };
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 解锁库存(记 outbound_unlock 流水,并把 stock_locked 置 0)
|
||
*
|
||
* 失败时抛错:调用方(取消/作废/驳回)据此阻断状态流转,避免「锁定了但单据已终结」
|
||
* @param {Object} order 出库单实例
|
||
* @param {Array} [items] 明细(缺省按单据现查)
|
||
* @param {String} remark 备注(写入出入库记录)
|
||
* @return {Promise<{skipped: boolean, affected: number}>}
|
||
*/
|
||
async unlockStock(order, items, remark) {
|
||
const { ctx } = this;
|
||
const rows = items && items.length ? items : await this.loadItems(order.id);
|
||
if (!rows.length) return { skipped: true, affected: 0 };
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
let affected = 0;
|
||
try {
|
||
for (const it of rows) {
|
||
await applyStockChange(ctx, {
|
||
bizType: 'outbound_unlock',
|
||
principalId: order.principal_id,
|
||
warehouseId: order.warehouse_id,
|
||
productId: Number(it.product_id),
|
||
itemCode: it.code,
|
||
itemName: it.name,
|
||
itemType: it.inventory_type === 'CC' ? 'CC' : 'ZC',
|
||
quantity: Number(it.quantity) || 0,
|
||
billId: order.id,
|
||
billNo: order.bill_no,
|
||
createdBy: ctx.userId,
|
||
remark: remark || '出库单释放锁定库存',
|
||
transaction,
|
||
});
|
||
affected += 1;
|
||
}
|
||
await order.update({ stock_locked: 0 }, { transaction });
|
||
await transaction.commit();
|
||
order.stock_locked = 0;
|
||
return { skipped: false, affected };
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 释放锁定库存(best-effort,仅记录日志不抛出)
|
||
* 用于推送失败退回场景:退货状态流转优先,stock_locked 保持 1 便于后续驳回/取消/作废再释放
|
||
* @param {Object} order 出库单实例
|
||
* @param {Array} items 明细
|
||
* @param {String} remark 备注
|
||
* @return {Promise<void>}
|
||
*/
|
||
async releaseStock(order, items, remark) {
|
||
const { ctx } = this;
|
||
try {
|
||
const result = await this.unlockStock(order, items, remark);
|
||
if (!result.skipped) {
|
||
ctx.logger.info(`[outbound-push] ${order.bill_no} 已释放锁定库存(${result.affected} 行):${remark}`);
|
||
}
|
||
} catch (err) {
|
||
ctx.logger.error(`[outbound-push] ${order.bill_no} 释放锁定库存失败:${err.message}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 推送单条出库单(一次尝试)
|
||
*
|
||
* 返回 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.OutboundOrder.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.bill_no,
|
||
warehouseApiId: api.id,
|
||
apiType: api.type,
|
||
attempts,
|
||
maxAttempts: PUSH_MAX_ATTEMPTS,
|
||
source,
|
||
attemptedAt: now.toISOString(),
|
||
};
|
||
|
||
const items = await this.loadItems(order.id);
|
||
if (!items.length) {
|
||
// 审核要求有明细,正常不会走到这里;真出现则退回「待出库」,让用户补明细后重新审核
|
||
await ctx.model.OutboundOrder.update({
|
||
status: 1,
|
||
pushed_at: null,
|
||
wms_push_result: { ...base, success: false, failureKind: 'empty_items', retryable: false, message: '单据无明细,无法推送' },
|
||
}, { where: { id: order.id } });
|
||
ctx.logger.warn(`[outbound-push] ${order.bill_no} 无明细,已退回待出库`);
|
||
return { ok: false, retry: false, message: '单据无明细,无法推送', attempts };
|
||
}
|
||
|
||
const pmap = await this.loadProductMap(items);
|
||
const client = new QimenWmsClient(api, this.app);
|
||
|
||
// 先锁定库存(占用可用,防止超卖)——不向 WMS 提交前先占用,避免外部建单而本地无占用
|
||
try {
|
||
await this.lockStock(order, items, pmap);
|
||
} catch (err) {
|
||
const insufficient = err.code === 'INSUFFICIENT_STOCK';
|
||
const message = insufficient ? err.message : `库存锁定失败:${err.message}`;
|
||
// 用批量 update:CAS 已把 pushed_at 写入库而实例内存值仍为 null,实例 update 不会真正把 null 落库
|
||
await ctx.model.OutboundOrder.update({
|
||
status: 1,
|
||
pushed_at: null,
|
||
wms_push_result: {
|
||
...base,
|
||
success: false,
|
||
failureKind: insufficient ? 'insufficient_stock' : 'lock_failed',
|
||
retryable: false,
|
||
message,
|
||
},
|
||
}, { where: { id: order.id } });
|
||
ctx.logger.warn(`[outbound-push] ${order.bill_no} 推送前锁定库存失败,已退回待出库:${message}`);
|
||
return { ok: false, retry: false, message, attempts };
|
||
}
|
||
|
||
let resp;
|
||
try {
|
||
resp = await client.createStockout(order, items, {
|
||
warehouse: order.warehouse,
|
||
wmsItemIdByProduct: await this.resolveWmsItemIds(order, items),
|
||
});
|
||
} 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(`[outbound-push] ${order.bill_no} 第 ${attempts}/${PUSH_MAX_ATTEMPTS} 次推送异常(将重试):${err.message}`);
|
||
return { ok: false, retry: true, message: err.message, attempts };
|
||
}
|
||
// 达到上限:冲正外部单据后退回「待出库」,并释放锁定库存
|
||
const cancelResult = await this.cancelRemote(client, order);
|
||
await this.releaseStock(order, items, '推送超时退回待出库,释放锁定库存');
|
||
await ctx.model.OutboundOrder.update({
|
||
status: 1,
|
||
pushed_at: null,
|
||
wms_push_result: {
|
||
...base,
|
||
success: false,
|
||
failureKind: 'timeout',
|
||
retryable: false,
|
||
error: err.message,
|
||
cancelResult,
|
||
},
|
||
}, { where: { id: order.id } });
|
||
ctx.logger.error(`[outbound-push] ${order.bill_no} 连续 ${attempts} 次推送异常,已退回待出库:${err.message}`);
|
||
return { ok: false, retry: false, message: `连续 ${attempts} 次无响应/超时,已退回待出库:${err.message}`, attempts };
|
||
}
|
||
|
||
if (client.isSuccess(resp)) {
|
||
await order.update({
|
||
status: 3,
|
||
operate_time: now,
|
||
pushed_at: now,
|
||
wms_push_result: { ...base, success: true, response: resp },
|
||
});
|
||
ctx.logger.info(`[outbound-push] ${order.bill_no} 推送成功(第 ${attempts} 次)`);
|
||
return { ok: true, message: '已推送仓库', response: resp, attempts };
|
||
}
|
||
|
||
// 对方明确响应失败:不重试,冲正后退回「待出库」,并释放锁定库存
|
||
const cancelResult = await this.cancelRemote(client, order);
|
||
const message = resp && (resp.message || resp.code);
|
||
await this.releaseStock(order, items, '推送失败退回待出库,释放锁定库存');
|
||
await ctx.model.OutboundOrder.update({
|
||
status: 1,
|
||
pushed_at: null,
|
||
wms_push_result: {
|
||
...base,
|
||
success: false,
|
||
failureKind: 'business',
|
||
retryable: false,
|
||
code: resp && resp.code,
|
||
message,
|
||
response: resp,
|
||
cancelResult,
|
||
},
|
||
}, { where: { id: order.id } });
|
||
ctx.logger.warn(`[outbound-push] ${order.bill_no} 推送失败(对方明确拒绝),已退回待出库:${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.OutboundOrder.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<Object>} 统计与明细
|
||
*/
|
||
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 = OutboundOrderPushService;
|