fix(order-audit): 审核不再回查店管家,改为纯本地校验
按用户要求:审核(待审核 / 异常 → 待推送)只做本地校验(状态、明细、店铺、仓库)与库存锁定, 不再逐单请求外部打单平台确认「是否已发货」。那批外部请求会把 20 单的审核拖到 8~13 秒、 50 单约 25 秒,顶穿前端 axios 15 秒超时(nginx 大量 499)。 - orderStatus:移除 _auditOne 的平台守卫,以及 _precheckPlatformFinished / _guardPlatformFinished / _checkPlatformFinished / _applyPlatformGuard - externalPrintOrder:移除只为该守卫服务的 checkPlatformFinished / checkPlatformFinishedBatch / _resolvePlatformCheckTarget / _describePlatformCheck,以及配套常量与时间预算 - 删除对应测试;文档 6.4 改写为「审核不回查平台」,说明平台状态现在由拉单核对(6.3) 与推送取号链路暴露 - 保留 dgj traceId 进程级缓存(取号 / 重打 / 拉单链路仍受益) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
e7c838d5bf
commit
095891636e
@ -73,42 +73,6 @@ const MAX_VERIFY_ORDERS = 300;
|
||||
/** 每次回读携带的订单号个数(平台 Contract=in 支持逗号分隔多值) */
|
||||
const VERIFY_CHUNK_SIZE = 50;
|
||||
|
||||
/** 批量校验时接口没返回的订单,逐单兜底(时间窗回扫)的并发度 */
|
||||
const VERIFY_FALLBACK_CONCURRENCY = 4;
|
||||
|
||||
/**
|
||||
* 批量校验兜底阶段的时间预算(毫秒,DGJ_VERIFY_BUDGET_MS 可覆盖,0 表示不限)
|
||||
*
|
||||
* 平台查不到的订单每单要再打 1~3 次接口,单量大时会把审核拖到前端超时;
|
||||
* 超预算后剩余订单按「校验失败放行」处理(与原有口径一致),保证审核能按时返回。
|
||||
* @return {number} 预算毫秒
|
||||
*/
|
||||
function verifyBudgetMs() {
|
||||
const raw = process.env.DGJ_VERIFY_BUDGET_MS;
|
||||
if (raw == null || raw === '') return 5000;
|
||||
const value = Number(raw);
|
||||
return Number.isFinite(value) && value >= 0 ? value : 5000;
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台校验用的店管家系统编号(优先用索引行的系统单号,其次订单行)
|
||||
* @param {Object} order 订单明细(状态表行)
|
||||
* @param {Object} index 订单索引行
|
||||
* @return {String} 店管家系统编号
|
||||
*/
|
||||
function platformLogicalOrderId(order, index) {
|
||||
return String((index && (index.parent_order_no || index.order_no)) || order.parent_order_no || order.order_no || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台校验用的店管家订单编号(扩展字段快照优先,其次来源单号)
|
||||
* @param {Object} order 订单明细(状态表行)
|
||||
* @return {String} 店管家订单编号
|
||||
*/
|
||||
function platformOrderIdOf(order) {
|
||||
return String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 外部打单平台订单拉取服务
|
||||
*
|
||||
@ -467,229 +431,6 @@ class ExternalPrintOrderService extends Service {
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* 审核/推送前校验:平台侧是否已发货或已终结(只读)
|
||||
*
|
||||
* 场景:订单昨天已在店管家发货,OMS 今天才审核 → 不该再推仓库。
|
||||
* 平台查询失败按「放行」处理(只告警),避免平台抖动把审核全卡住。
|
||||
* @param {Object} order 订单明细(状态表行,需 shop_id / source_platform_code / extend_props)
|
||||
* @param {Object} index 订单索引行(order_no / parent_order_no)
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<{applicable: boolean, finished: boolean, status: string, reason: string, row: Object|null}>} 校验结果
|
||||
*/
|
||||
async checkPlatformFinished(order, index, principalId) {
|
||||
const result = { applicable: false, finished: false, status: '', reason: '', row: null };
|
||||
const target = await this._resolvePlatformCheckTarget(order, principalId);
|
||||
if (!target) return result;
|
||||
|
||||
result.applicable = true;
|
||||
const row = await target.service.fetchPlatformOrder({
|
||||
platformType: target.platformType,
|
||||
dbname: target.dbname,
|
||||
logicalOrderId: platformLogicalOrderId(order, index),
|
||||
platformOrderId: platformOrderIdOf(order),
|
||||
placeOrderTime: order.place_order_time || order.pay_time || order.created_at,
|
||||
});
|
||||
if (!row) return result;
|
||||
return this._describePlatformCheck(target, row);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量校验平台侧是否已发货/已终结(只读,审核/推送前守卫)
|
||||
*
|
||||
* 与 checkPlatformFinished 同口径,但同一个「账号 + 订单域名 + 分区库」的订单
|
||||
* 用一次 `LogicOrderId Contract=in` 接口查完,只有接口没返回的订单才逐单兜底
|
||||
* (时间窗回扫,与单条校验行为一致)。批量审核逐单发请求会随单量线性变慢,
|
||||
* 十几单就会超过前端 15 秒超时。兜底阶段有总时间预算,超时后剩余订单按放行处理。
|
||||
* @param {Array<{order: Object, index: Object}>} items 订单明细与索引行
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<Map<number, Object|null>>} 索引行 id → 校验结果(null 表示校验失败,按放行处理)
|
||||
*/
|
||||
async checkPlatformFinishedBatch(items, principalId) {
|
||||
const { ctx } = this;
|
||||
const results = new Map();
|
||||
const cache = new Map();
|
||||
const targets = [];
|
||||
|
||||
for (const item of items) {
|
||||
const id = Number(item.index.id);
|
||||
const target = await this._resolvePlatformCheckTarget(item.order, principalId, cache);
|
||||
if (!target) {
|
||||
results.set(id, { applicable: false, finished: false, status: '', reason: '', row: null });
|
||||
continue;
|
||||
}
|
||||
targets.push({
|
||||
id,
|
||||
order: item.order,
|
||||
target,
|
||||
logicalOrderId: platformLogicalOrderId(item.order, item.index),
|
||||
});
|
||||
}
|
||||
|
||||
// 同账号 + 域名 + 分区库一次查完(平台支持 LogicOrderId 多值精确过滤)
|
||||
const groups = new Map();
|
||||
for (const item of targets) {
|
||||
const key = `${item.target.accountId}|${item.target.host}|${item.target.dbname}`;
|
||||
if (!groups.has(key)) groups.set(key, []);
|
||||
groups.get(key).push(item);
|
||||
}
|
||||
|
||||
const missing = [];
|
||||
for (const group of groups.values()) {
|
||||
const { service, host, dbname } = group[0].target;
|
||||
for (let start = 0; start < group.length; start += VERIFY_CHUNK_SIZE) {
|
||||
const chunk = group.slice(start, start + VERIFY_CHUNK_SIZE);
|
||||
let rows = [];
|
||||
try {
|
||||
const traceId = await service.resolveTraceId();
|
||||
rows = await service.fetchOrdersByIds(host, {
|
||||
traceId,
|
||||
dbname,
|
||||
ids: chunk.map(item => item.logicalOrderId),
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[externalPrintOrder] 批量核对平台订单失败 host=%s dbname=%s:%s', host, dbname, err.message);
|
||||
missing.push(...chunk);
|
||||
continue;
|
||||
}
|
||||
const byId = new Map();
|
||||
for (const row of rows) {
|
||||
const id = String(row.LogicOrderId || '');
|
||||
if (id) byId.set(id, row);
|
||||
}
|
||||
for (const item of chunk) {
|
||||
const row = byId.get(item.logicalOrderId);
|
||||
if (row) results.set(item.id, this._describePlatformCheck(item.target, row));
|
||||
else missing.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 接口没返回的订单保持原有兜底(按时间窗回扫);并发执行,超预算后剩余订单按放行处理
|
||||
const budgetLeft = verifyBudgetMs();
|
||||
const deadline = budgetLeft > 0 ? Date.now() + budgetLeft : Infinity;
|
||||
let cursor = 0;
|
||||
let skipped = 0;
|
||||
const worker = async () => {
|
||||
while (cursor < missing.length) {
|
||||
if (Date.now() > deadline) {
|
||||
// 时间预算用尽:剩余订单不再校验(与「平台校验失败放行」同口径),避免审核被平台拖到超时
|
||||
const rest = missing.slice(cursor);
|
||||
cursor = missing.length;
|
||||
skipped += rest.length;
|
||||
for (const item of rest) results.set(item.id, null);
|
||||
break;
|
||||
}
|
||||
const item = missing[cursor];
|
||||
cursor += 1;
|
||||
try {
|
||||
const row = await item.target.service.fetchPlatformOrder({
|
||||
platformType: item.target.platformType,
|
||||
dbname: item.target.dbname,
|
||||
logicalOrderId: item.logicalOrderId,
|
||||
platformOrderId: platformOrderIdOf(item.order),
|
||||
placeOrderTime: item.order.place_order_time || item.order.pay_time || item.order.created_at,
|
||||
});
|
||||
results.set(item.id, row
|
||||
? this._describePlatformCheck(item.target, row)
|
||||
: { applicable: true, finished: false, status: '', reason: '', row: null });
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[externalPrintOrder] 核对平台订单失败 order=%s:%s', item.logicalOrderId, err.message);
|
||||
results.set(item.id, null);
|
||||
}
|
||||
}
|
||||
};
|
||||
const size = Math.min(VERIFY_FALLBACK_CONCURRENCY, missing.length);
|
||||
await Promise.all(Array.from({ length: size }, worker));
|
||||
if (skipped) {
|
||||
ctx.logger.warn('[externalPrintOrder] 平台批量校验超时(%sms),跳过 %s 单的兜底核对(放行)', budgetLeft, skipped);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析校验目标:店铺 → 打单账号 → 平台服务 / 订单域名 / 分区库 / 平台类型
|
||||
* @param {Object} order 订单明细(状态表行,需 shop_id / source_platform_code / extend_props)
|
||||
* @param {number} principalId 主体ID
|
||||
* @param {Map} [cache] 同一批次的解析缓存(key = 店铺 + 平台编码)
|
||||
* @return {Promise<Object|null>} 目标信息;不适用(非外部打单店铺等)返回 null
|
||||
*/
|
||||
async _resolvePlatformCheckTarget(order, principalId, cache) {
|
||||
const { ctx } = this;
|
||||
if (!order || !order.shop_id) return null;
|
||||
const platformCode = String(order.source_platform_code || '').trim();
|
||||
if (!platformCode) return null;
|
||||
|
||||
const key = `${order.shop_id}|${platformCode}`;
|
||||
if (cache && cache.has(key)) return cache.get(key);
|
||||
|
||||
const target = await (async () => {
|
||||
const shop = await ctx.model.Shop.findByPk(order.shop_id, {
|
||||
attributes: [ 'id', 'type', 'external_print_account_id' ],
|
||||
});
|
||||
if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) return null;
|
||||
|
||||
const account = await ctx.model.ExternalPrintAccount.findByPk(shop.external_print_account_id, {
|
||||
include: [{ model: ctx.model.ExternalPrintPlatform, as: 'platform' }],
|
||||
});
|
||||
if (!account || !account.platform) return null;
|
||||
|
||||
const service = this.createPlatformService(account);
|
||||
const resolvePlatformType = service.constructor && service.constructor.resolvePlatformType;
|
||||
const resolveOrderHost = service.constructor && service.constructor.resolveOrderHost;
|
||||
if (typeof resolvePlatformType !== 'function' || typeof service.fetchPlatformOrder !== 'function') return null;
|
||||
|
||||
// 平台类型 / 分区库优先取已同步的快递接口记录(无需额外接口)
|
||||
const template = await ctx.model.ExternalPrintExpressInterface.findOne({
|
||||
where: { principal_id: principalId, account_id: account.id, platform_code: platformCode, status: 1 },
|
||||
attributes: [ 'id', 'platform_type', 'dbname' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
});
|
||||
// 平台类型只用于选「订单域名」:1688 分销单被换算成抖音小店/淘宝后,订单行仍在 Alibaba 分区,
|
||||
// 必须按原始平台算,否则回读会查错域名 → 查不到订单 → 校验形同失效
|
||||
const raw = order.extend_props && typeof order.extend_props === 'object' ? order.extend_props : {};
|
||||
const originalCode = String(raw.original_platform_code || '').trim();
|
||||
const originalPlatformType = originalCode ? resolvePlatformType(originalCode) : '';
|
||||
const platformType = originalPlatformType || (template ? template.platform_type : resolvePlatformType(platformCode));
|
||||
if (!platformType) return null;
|
||||
|
||||
const describe = service.constructor.describeFinishedOrder;
|
||||
const host = typeof resolveOrderHost === 'function' ? resolveOrderHost(platformType) : '';
|
||||
if (!host) return null;
|
||||
return {
|
||||
service,
|
||||
accountId: Number(account.id),
|
||||
platformType,
|
||||
host,
|
||||
dbname: template ? template.dbname : '',
|
||||
describe: typeof describe === 'function' ? describe : null,
|
||||
};
|
||||
})();
|
||||
|
||||
if (cache) cache.set(key, target);
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台订单行 → 统一的校验结果结构
|
||||
* @param {Object} target 校验目标(含 describe)
|
||||
* @param {Object} row 平台订单行
|
||||
* @return {{applicable: boolean, finished: boolean, status: string, reason: string, row: Object|null}} 校验结果
|
||||
*/
|
||||
_describePlatformCheck(target, row) {
|
||||
const detail = target.describe ? target.describe(row) : { finished: false, reason: '' };
|
||||
const status = String(row.ErpState || '');
|
||||
return {
|
||||
applicable: true,
|
||||
finished: !!detail.finished,
|
||||
status,
|
||||
row,
|
||||
reason: detail.finished
|
||||
? `店管家侧已发货或已终结(${detail.reason || `ErpState=${status || '-'}`})`
|
||||
: '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 作废「本地仍是待审核、但平台侧不应再处理」的订单(已发货/已终结,或平台已查不到)。
|
||||
*
|
||||
|
||||
@ -1123,6 +1123,8 @@ class OrderStatusService extends Service {
|
||||
* - **审核即锁定库存**(按明细 plan_qty 占用可用,不足则失败),锁定与状态流转同事务
|
||||
* - 写入审核人(主体账号名称,推送为 operatorName)与审核时间,并清空上一轮推送痕迹
|
||||
* - 多选时逐单独立事务:库存不足等失败只跳过该单,失败明细见 failures
|
||||
* - **只做本地校验,不请求外部打单平台**(订单在平台侧是否已发货属于平台实时状态,
|
||||
* 审核不再逐单回查:一批 20 单就要几十次外部请求,会把审核拖到前端超时)
|
||||
* @param {Object} p { ids }
|
||||
* @return {Promise<Object>} { count, status, status_label, failed, failures }
|
||||
*/
|
||||
@ -1144,16 +1146,11 @@ class OrderStatusService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// 平台状态校验是外部请求(店管家):先整批查一次再逐单落库,避免批量审核被逐单请求拖到超时
|
||||
const platformChecks = await this._precheckPlatformFinished(idList, principalId);
|
||||
|
||||
const failures = [];
|
||||
const done = [];
|
||||
for (const id of idList) {
|
||||
try {
|
||||
done.push(await this._auditOne(id, principalId, operatorName, {
|
||||
platformCheck: platformChecks.has(id) ? platformChecks.get(id) : undefined,
|
||||
}));
|
||||
done.push(await this._auditOne(id, principalId, operatorName));
|
||||
} catch (err) {
|
||||
failures.push({ id, message: err.message });
|
||||
ctx.logger.warn(`[order-status] 批量审核跳过 id=${id}:${err.message}`);
|
||||
@ -1174,11 +1171,9 @@ class OrderStatusService extends Service {
|
||||
* @param {Number} id 订单 id
|
||||
* @param {Number} principalId 主体ID
|
||||
* @param {String} operatorName 审核人名称(推送 operatorName)
|
||||
* @param {Object} [options] 选项
|
||||
* @param {Object|null} [options.platformCheck] 批量审核时预先取到的平台校验结果(undefined 表示未校验)
|
||||
* @return {Promise<Object>} { id, order_no, stock_locked }
|
||||
*/
|
||||
async _auditOne(id, principalId, operatorName, { platformCheck } = {}) {
|
||||
async _auditOne(id, principalId, operatorName) {
|
||||
const { ctx } = this;
|
||||
const [ row ] = await this._loadIndexRows([ id ], principalId);
|
||||
if (![ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ].includes(row.current_status)) {
|
||||
@ -1188,11 +1183,6 @@ class OrderStatusService extends Service {
|
||||
}
|
||||
|
||||
const detail = await this._model(row.current_status).findByPk(id);
|
||||
if (platformCheck === undefined) {
|
||||
await this._guardPlatformFinished(row, detail, principalId);
|
||||
} else {
|
||||
await this._applyPlatformGuard(row, platformCheck, principalId);
|
||||
}
|
||||
const itemCount = await ctx.model.OrderStatusItem.count({ where: { order_id: id, principal_id: principalId } });
|
||||
if (!itemCount) {
|
||||
const err = new Error(`订单 ${row.order_no} 无商品明细,无法审核`);
|
||||
@ -1250,110 +1240,6 @@ class OrderStatusService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量审核前校验平台状态
|
||||
*
|
||||
* 校验是外部请求(店管家),逐单串行会随单量线性变慢(前端 15 秒超时),
|
||||
* 这里交给平台服务按「账号 + 域名 + 分区库」一次批量回读,只做只读校验、不改单据
|
||||
* (自动作废留给逐单流程,避免并发写同一批库存行)。
|
||||
* @param {Array<Number>} ids 订单 id
|
||||
* @param {Number} principalId 主体ID
|
||||
* @return {Promise<Map<Number, Object|null>>} 已校验过的订单 → 校验结果(null 表示校验失败已放行)
|
||||
*/
|
||||
async _precheckPlatformFinished(ids, principalId) {
|
||||
const { ctx } = this;
|
||||
const checks = new Map();
|
||||
if (String(process.env.DGJ_AUDIT_PLATFORM_CHECK || '1') === '0') return checks;
|
||||
|
||||
const items = [];
|
||||
for (const id of ids) {
|
||||
try {
|
||||
const [ row ] = await this._loadIndexRows([ id ], principalId);
|
||||
// 状态不符 / 明细缺失:交给逐单流程给出准确原因,这里不拦
|
||||
if (![ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ].includes(row.current_status)) continue;
|
||||
const detail = await this._model(row.current_status).findByPk(id);
|
||||
if (!detail) continue;
|
||||
items.push({ row, detail });
|
||||
} catch {
|
||||
// 索引缺失、无权限等同样交给逐单流程报错
|
||||
}
|
||||
}
|
||||
if (!items.length) return checks;
|
||||
|
||||
let results;
|
||||
try {
|
||||
results = await ctx.service.externalPrintOrder.checkPlatformFinishedBatch(
|
||||
items.map(item => ({ order: item.detail, index: item.row })),
|
||||
principalId
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[order-audit] 批量平台状态校验失败(放行审核):%s', err.message);
|
||||
return checks;
|
||||
}
|
||||
|
||||
for (const item of items) {
|
||||
const id = Number(item.row.id);
|
||||
checks.set(id, results.has(id) ? results.get(id) : null);
|
||||
}
|
||||
return checks;
|
||||
}
|
||||
|
||||
/**
|
||||
* 审核前守卫:外部打单订单若平台侧已发货/已终结,自动作废并拒绝审核
|
||||
*
|
||||
* 背景:订单可能在店管家先发货、OMS 隔天才审核;若照常审核会推送一张平台已完成、
|
||||
* 仓库无法再取号的脏单。平台查询失败按放行处理(只告警),避免平台抖动卡住审核。
|
||||
* @param {Object} row 订单索引行
|
||||
* @param {Object} detail 订单明细(状态表行)
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<void>} 无返回值(命中时抛 400)
|
||||
*/
|
||||
async _guardPlatformFinished(row, detail, principalId) {
|
||||
const check = await this._checkPlatformFinished(row, detail, principalId);
|
||||
await this._applyPlatformGuard(row, check, principalId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 只读校验平台订单是否已发货/已终结(不含作废动作)
|
||||
* @param {Object} row 订单索引行
|
||||
* @param {Object} detail 订单明细(状态表行)
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<Object|null>} 校验结果;未校验/校验失败返回 null(放行)
|
||||
*/
|
||||
async _checkPlatformFinished(row, detail, principalId) {
|
||||
const { ctx } = this;
|
||||
if (String(process.env.DGJ_AUDIT_PLATFORM_CHECK || '1') === '0') return null;
|
||||
try {
|
||||
return await ctx.service.externalPrintOrder.checkPlatformFinished(detail, row, principalId);
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[order-audit] %s 平台状态校验失败(放行审核):%s', row.order_no, err.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按校验结果拦截审核:平台侧已完成时自动作废并抛 400
|
||||
* @param {Object} row 订单索引行
|
||||
* @param {Object|null} check 校验结果(null / finished=false 直接放行)
|
||||
* @param {Number} principalId 主体ID
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async _applyPlatformGuard(row, check, principalId) {
|
||||
const { ctx } = this;
|
||||
if (!check || !check.finished) return;
|
||||
|
||||
const reason = `${check.reason},系统自动作废`;
|
||||
try {
|
||||
await this.voidOrder({ ids: [ Number(row.id) ], void_reason: reason, principalId });
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[order-audit] %s 自动作废失败:%s', row.order_no, err.message);
|
||||
}
|
||||
|
||||
const ex = new Error(`订单 ${row.order_no} ${check.reason},不能审核(已自动作废)`);
|
||||
ex.status = 400;
|
||||
throw ex;
|
||||
}
|
||||
|
||||
/**
|
||||
* 手工标记推送结果(待推送 → 委外中 / 异常):无外部仓库时的流转入口,也可用于修正外部实际结果
|
||||
* @param {Object} p { ids, outcome: 'success'|'failed', remark }
|
||||
|
||||
@ -1,168 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const { app, assert } = require('egg-mock/bootstrap');
|
||||
|
||||
/**
|
||||
* 审核/推送前的平台状态批量校验
|
||||
*
|
||||
* 要点:同一「账号 + 域名 + 分区库」的订单只发一次接口(LogicOrderId 多值过滤),
|
||||
* 只有接口没返回的订单才逐单兜底(时间窗回扫),与单条校验行为一致。
|
||||
*/
|
||||
describe('service/externalPrintOrder checkPlatformFinishedBatch', () => {
|
||||
const PRINCIPAL_ID = 3;
|
||||
const describeFinished = row => ({
|
||||
finished: row.ErpState !== 'waitsellersend',
|
||||
reason: row.ErpState === 'waitsellersend' ? '' : 'ErpState=sended',
|
||||
});
|
||||
|
||||
const order = (id, extra = {}) => ({ id, shop_id: 2, source_platform_code: 'DYXD', ...extra });
|
||||
const index = id => ({ id, order_no: `dgj-${id}`, parent_order_no: String(id) });
|
||||
|
||||
/**
|
||||
* 构造服务实例,并用桩替换目标解析(不连库)
|
||||
* @param {Object} [options] 桩配置
|
||||
* @param {Array<Object>} [options.rows] 批量接口返回的订单行
|
||||
* @param {Function} [options.fetchOrdersByIds] 批量接口桩
|
||||
* @param {Function} [options.fetchPlatformOrder] 单条兜底接口桩
|
||||
* @return {{service: Object, calls: Object}} 服务实例与调用记录
|
||||
*/
|
||||
function buildService(options = {}) {
|
||||
const rows = options.rows || [];
|
||||
const fetchOrdersByIds = options.fetchOrdersByIds;
|
||||
const fetchPlatformOrder = options.fetchPlatformOrder;
|
||||
const calls = { batch: [], single: [] };
|
||||
const platformService = {
|
||||
resolveTraceId: async () => 'trace-x',
|
||||
fetchOrdersByIds: async (host, options) => {
|
||||
calls.batch.push({ host, ...options });
|
||||
if (fetchOrdersByIds) return fetchOrdersByIds(host, options);
|
||||
return rows;
|
||||
},
|
||||
fetchPlatformOrder: async options => {
|
||||
calls.single.push(options);
|
||||
if (fetchPlatformOrder) return fetchPlatformOrder(options);
|
||||
return null;
|
||||
},
|
||||
};
|
||||
const service = app.mockContext().service.externalPrintOrder;
|
||||
service._resolvePlatformCheckTarget = async () => ({
|
||||
service: platformService,
|
||||
accountId: 1,
|
||||
platformType: 'TouTiao',
|
||||
host: 'fxdd.dgjapp.com',
|
||||
dbname: 'db-1',
|
||||
describe: describeFinished,
|
||||
});
|
||||
return { service, calls };
|
||||
}
|
||||
|
||||
it('同批订单只发一次批量接口,找到的按平台状态判定', async () => {
|
||||
const { service, calls } = buildService({
|
||||
rows: [
|
||||
{ LogicOrderId: '100', ErpState: 'waitsellersend' },
|
||||
{ LogicOrderId: '200', ErpState: 'sended' },
|
||||
],
|
||||
});
|
||||
|
||||
const results = await service.checkPlatformFinishedBatch([
|
||||
{ order: order(100), index: index(100) },
|
||||
{ order: order(200), index: index(200) },
|
||||
], PRINCIPAL_ID);
|
||||
|
||||
assert.strictEqual(calls.batch.length, 1);
|
||||
assert.deepStrictEqual(calls.batch[0].ids, [ '100', '200' ]);
|
||||
assert.strictEqual(calls.single.length, 0);
|
||||
assert.strictEqual(results.get(100).finished, false);
|
||||
assert.strictEqual(results.get(200).finished, true);
|
||||
assert.strictEqual(results.get(200).status, 'sended');
|
||||
});
|
||||
|
||||
it('接口没返回的订单才逐单兜底(行为与单条校验一致)', async () => {
|
||||
const { service, calls } = buildService({
|
||||
rows: [{ LogicOrderId: '100', ErpState: 'waitsellersend' }],
|
||||
fetchPlatformOrder: options => (options.logicalOrderId === '300'
|
||||
? { ErpState: 'sended' }
|
||||
: null),
|
||||
});
|
||||
|
||||
const results = await service.checkPlatformFinishedBatch([
|
||||
{ order: order(100), index: index(100) },
|
||||
{ order: order(200), index: index(200) },
|
||||
{ order: order(300), index: index(300) },
|
||||
], PRINCIPAL_ID);
|
||||
|
||||
assert.strictEqual(calls.batch.length, 1);
|
||||
assert.deepStrictEqual(calls.single.map(item => item.logicalOrderId).sort(), [ '200', '300' ]);
|
||||
assert.strictEqual(results.get(100).finished, false);
|
||||
assert.strictEqual(results.get(200).finished, false, '兜底也没查到时按未终结放行');
|
||||
assert.strictEqual(results.get(300).finished, true);
|
||||
});
|
||||
|
||||
it('批量接口失败时整批走兜底,不阻断审核', async () => {
|
||||
const { service, calls } = buildService({
|
||||
fetchOrdersByIds: () => {
|
||||
throw new Error('核对店管家订单失败');
|
||||
},
|
||||
fetchPlatformOrder: options => ({ LogicOrderId: options.logicalOrderId, ErpState: 'waitsellersend' }),
|
||||
});
|
||||
|
||||
const results = await service.checkPlatformFinishedBatch([
|
||||
{ order: order(100), index: index(100) },
|
||||
{ order: order(200), index: index(200) },
|
||||
], PRINCIPAL_ID);
|
||||
|
||||
assert.strictEqual(calls.single.length, 2);
|
||||
assert.strictEqual(results.get(100).finished, false);
|
||||
assert.strictEqual(results.get(200).finished, false);
|
||||
});
|
||||
|
||||
it('不适用平台校验的订单(非外部打单店铺等)直接放行', async () => {
|
||||
const service = app.mockContext().service.externalPrintOrder;
|
||||
service._resolvePlatformCheckTarget = async () => null;
|
||||
|
||||
const results = await service.checkPlatformFinishedBatch([
|
||||
{ order: order(100), index: index(100) },
|
||||
], PRINCIPAL_ID);
|
||||
|
||||
assert.deepStrictEqual(results.get(100), {
|
||||
applicable: false, finished: false, status: '', reason: '', row: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('兜底阶段预算用尽时剩余订单按放行处理(null)', async () => {
|
||||
const previous = process.env.DGJ_VERIFY_BUDGET_MS;
|
||||
process.env.DGJ_VERIFY_BUDGET_MS = '20';
|
||||
try {
|
||||
const { service, calls } = buildService({
|
||||
rows: [],
|
||||
fetchPlatformOrder: () => new Promise(resolve => {
|
||||
setTimeout(() => resolve({ ErpState: 'sended' }), 50);
|
||||
}),
|
||||
});
|
||||
const items = [ 1, 2, 3, 4, 5, 6 ].map(id => ({ order: order(id), index: index(id) }));
|
||||
|
||||
const results = await service.checkPlatformFinishedBatch(items, PRINCIPAL_ID);
|
||||
|
||||
assert.strictEqual(results.size, 6);
|
||||
// 并发 4 先起步,剩下的 2 单在预算用尽后直接放行、不再打接口
|
||||
assert.strictEqual(calls.single.length, 4);
|
||||
const nulls = [ ...results.values() ].filter(value => value === null);
|
||||
assert.strictEqual(nulls.length, 2);
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.DGJ_VERIFY_BUDGET_MS;
|
||||
else process.env.DGJ_VERIFY_BUDGET_MS = previous;
|
||||
}
|
||||
});
|
||||
|
||||
it('单条校验(checkPlatformFinished)仍按原口径返回', async () => {
|
||||
const { service } = buildService({
|
||||
fetchPlatformOrder: () => ({ ErpState: 'sended' }),
|
||||
});
|
||||
|
||||
const result = await service.checkPlatformFinished(order(100), index(100), PRINCIPAL_ID);
|
||||
|
||||
assert.strictEqual(result.applicable, true);
|
||||
assert.strictEqual(result.finished, true);
|
||||
assert.match(result.reason, /店管家侧已发货或已终结/);
|
||||
});
|
||||
});
|
||||
@ -1,109 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||
|
||||
/**
|
||||
* 批量审核的平台状态预校验
|
||||
*
|
||||
* 背景:校验是外部请求(店管家),逐单串行会把十几单的审核拖到前端 15 秒超时;
|
||||
* 所以批量审核先按批次校验一次,再逐单落库,且落库时不再重复请求平台。
|
||||
*/
|
||||
describe('service/orderStatus 批量审核平台预校验', () => {
|
||||
const PRINCIPAL_ID = 3;
|
||||
|
||||
/**
|
||||
* 构造一个只够跑预校验的服务实例
|
||||
* @param {Object} [options] 桩配置
|
||||
* @param {Function} [options.check] 批量平台状态校验桩
|
||||
* @return {Object} 服务实例
|
||||
*/
|
||||
function buildService(options = {}) {
|
||||
const ctx = app.mockContext({ state: { principalId: PRINCIPAL_ID } });
|
||||
ctx.userId = null;
|
||||
ctx.service.externalPrintOrder.checkPlatformFinishedBatch = options.check;
|
||||
const service = ctx.service.orderStatus;
|
||||
service._loadIndexRows = async ids => ids.map(id => ({ id, order_no: `NO-${id}`, current_status: 'pending' }));
|
||||
service._model = () => ({ findByPk: async id => ({ id, shop_id: 2 }) });
|
||||
return service;
|
||||
}
|
||||
|
||||
it('只送待审核/异常且有明细的订单,结果按订单 id 归档(未返回按放行)', async () => {
|
||||
const seen = [];
|
||||
const service = buildService({
|
||||
check: async items => {
|
||||
seen.push(...items.map(item => Number(item.index.id)));
|
||||
return new Map([[ 2, { finished: true, reason: '店管家侧已发货' }]]);
|
||||
},
|
||||
});
|
||||
service._model = () => ({ findByPk: async id => (id === 3 ? null : { id, shop_id: 2 }) });
|
||||
const loadIndex = service._loadIndexRows;
|
||||
service._loadIndexRows = async ids => (await loadIndex(ids)).map(row => ({
|
||||
...row,
|
||||
current_status: row.id === 4 ? 'queued' : 'pending',
|
||||
}));
|
||||
|
||||
const checks = await service._precheckPlatformFinished([ 1, 2, 3, 4 ], PRINCIPAL_ID);
|
||||
|
||||
assert.deepStrictEqual(seen, [ 1, 2 ]);
|
||||
assert.strictEqual(checks.get(2).finished, true);
|
||||
assert.strictEqual(checks.get(1), null);
|
||||
assert.ok(!checks.has(3), '明细缺失的订单不预校验');
|
||||
assert.ok(!checks.has(4), '状态不符的订单不预校验');
|
||||
});
|
||||
|
||||
it('批量校验整体失败时放行整批,不阻断审核', async () => {
|
||||
const service = buildService({
|
||||
check: async () => {
|
||||
throw new Error('平台超时');
|
||||
},
|
||||
});
|
||||
|
||||
const checks = await service._precheckPlatformFinished([ 1, 2 ], PRINCIPAL_ID);
|
||||
|
||||
assert.strictEqual(checks.size, 0);
|
||||
});
|
||||
|
||||
it('DGJ_AUDIT_PLATFORM_CHECK=0 时不请求平台', async () => {
|
||||
let called = false;
|
||||
const service = buildService({
|
||||
check: async () => {
|
||||
called = true;
|
||||
return new Map();
|
||||
},
|
||||
});
|
||||
const previous = process.env.DGJ_AUDIT_PLATFORM_CHECK;
|
||||
process.env.DGJ_AUDIT_PLATFORM_CHECK = '0';
|
||||
try {
|
||||
const checks = await service._precheckPlatformFinished([ 1 ], PRINCIPAL_ID);
|
||||
assert.strictEqual(checks.size, 0);
|
||||
assert.strictEqual(called, false);
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.DGJ_AUDIT_PLATFORM_CHECK;
|
||||
else process.env.DGJ_AUDIT_PLATFORM_CHECK = previous;
|
||||
}
|
||||
});
|
||||
|
||||
it('已预校验的单据落库时不再请求平台', async () => {
|
||||
const service = buildService();
|
||||
const applied = [];
|
||||
const guarded = [];
|
||||
service._applyPlatformGuard = async (row, check) => { applied.push([ row.id, check ]); };
|
||||
service._guardPlatformFinished = async row => { guarded.push(row.id); };
|
||||
mock(app.model.OrderStatusItem, 'count', async () => 0);
|
||||
|
||||
const check = { finished: false };
|
||||
await assert.rejects(
|
||||
() => service._auditOne(1, PRINCIPAL_ID, '审核人', { platformCheck: check }),
|
||||
/无商品明细/
|
||||
);
|
||||
assert.deepStrictEqual(applied, [[ 1, check ]]);
|
||||
assert.deepStrictEqual(guarded, []);
|
||||
|
||||
// 未预校验(单条审核)时才走完整守卫
|
||||
await assert.rejects(
|
||||
() => service._auditOne(1, PRINCIPAL_ID, '审核人'),
|
||||
/无商品明细/
|
||||
);
|
||||
assert.deepStrictEqual(guarded, [ 1 ]);
|
||||
});
|
||||
});
|
||||
@ -359,10 +359,14 @@ Filters[2] TableAlias=pfn FieldType=int TableName=PathFlowNode Name=UpFxUs
|
||||
⚠️ **域名口径(换算后必须按原始平台算)**:订单行始终留在店管家原始平台的分区(1688 → `Alibaba` → `fxali.dgjapp.com`),
|
||||
换算是为了「选对模板」,不能连带改域名。因此凡是「按订单读/写平台数据」的地方都用
|
||||
`extend_props.original_platform_code` 推导 PlatformType 与域名:取号回读订单行(`fetchWaybillNo` 的 `originalPlatformCode`)、
|
||||
拉单核对/作废(`fetchRowsForVerify`)、审核前已发货校验(`checkPlatformFinished`)、发货回传(`externalSendSync.resolveTarget`)。
|
||||
拉单核对/作废(`fetchRowsForVerify`)、发货回传(`externalSendSync.resolveTarget`)。
|
||||
实测同一条 1688 分销单:`fxali` 命中(`ErpState=waitsellersend`),`fxdd` 查不到——用错的域名会被判「平台已查不到」而误作废。
|
||||
模板查找仍按换算后的平台编码(`source_platform_code`),因为模板必须与下游渠道一致。
|
||||
|
||||
⚠️ **审核不回查平台**:审核(`orderStatus.audit`)只做本地校验(明细 / 店铺 / 仓库)与库存锁定,不请求店管家。
|
||||
历史上审核前曾逐单回查平台是否已发货(`checkPlatformFinished`),一批 20 单要几十次外部请求,
|
||||
会把审核拖到前端 15 秒超时,已按用户要求移除;平台侧是否已发货交由拉单核对(`fetchRowsForVerify`)与推送取号链路暴露。
|
||||
|
||||
#### 4.2.1.1 第二来源:我的店铺(国内电商,自营店)
|
||||
|
||||
店管家账号下有两类店铺,接口与归属键都不同,由 `PrintPlatformService.listShopSources()` 统一声明:
|
||||
@ -864,20 +868,18 @@ DGJ_WAYBILL_ENABLE=0 # 0/false/off/no 视为关闭;不设置或其他值均
|
||||
为避免误判,限制:窗口最长回看 **45 天**、本次必须成功命中至少一个分区、`AUTO_VOID_MISSING_ORDER=0` 可整体关闭。
|
||||
- 操作日志同步记录 `reason` 与 `platform_status`;店铺「最近同步结果」与拉单任务结果都会显示「其中平台已查不到 N 单」。
|
||||
|
||||
### 6.4 审核前平台状态守卫(防「平台已发货的单被审核推送」)
|
||||
### 6.4 审核不回查平台(2026-11-23 已移除审核前守卫)
|
||||
|
||||
订单可能昨天已在店管家发货,OMS 今天才审核。`orderStatus._auditOne` 在审核前会:
|
||||
审核(`orderStatus._auditOne`)**只做本地校验**:状态(待审核 / 异常)、有商品明细、已选店铺、已选仓库,
|
||||
然后锁定库存 + 流转状态,**不再请求店管家**。
|
||||
|
||||
1. 判断是否「外部打单订单」(店铺 `type=2` + `external_print_account_id`);
|
||||
2. 用已同步的快递接口记录拿 `platform_type/dbname`,实时回读店管家订单行(只读);
|
||||
3. `isOrderFinished(row)` 为真(`ErpState` 已发货/已终结、有 `OnlineSendTime`、包裹 `IsSended`、`LogisticStatus>0`)时:
|
||||
- **自动作废**该订单,作废备注写明命中的具体依据(如「店管家侧已发货或已终结(平台订单状态 ErpState=sended、平台已有发货时间 2026-11-03 17:35:24),系统自动作废」);
|
||||
- 抛 400:`订单 xxx 店管家侧已发货或已终结(…),不能审核(已自动作废)`。
|
||||
4. 平台查询失败**放行**(只告警),避免平台抖动卡住审核。
|
||||
曾有过一版「审核前平台状态守卫」:每单实时回读店管家订单行,`isOrderFinished(row)` 为真就自动作废并抛 400。
|
||||
它的问题是逐单串行打外部接口——命中单约 0.2s、查不到的单(还要按 `PlatformOrderId` 和时间窗再查)约 1.2s,
|
||||
一批 20 单要 8~13 秒、50 单约 25 秒,直接顶穿前端 15 秒超时(nginx 大量 499),因此按用户要求整体移除。
|
||||
|
||||
关闭开关:`DGJ_AUDIT_PLATFORM_CHECK=0`(默认开启)。
|
||||
|
||||
> 审核现在会为外部打单订单增加 1 次只读的平台查询;批量审核按单串行执行。
|
||||
现在「平台侧已发货」由这些链路暴露:
|
||||
- 拉单核对 / 自动作废(见 6.3,`fetchRowsForVerify` + `AUTO_VOID_MISSING_ORDER`);
|
||||
- 推送仓库取号(`fetchWaybillNo` 回读到已完成订单会直接报错,单据落「异常」交人工处理)。
|
||||
|
||||
### 6.5 取号时同样拦截
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user