- getWaveStrategyFetchCandidateOrders 增加可选 createdBefore 上限过滤(不传时行为不变) - autoPopulateWaveStrategyFetchSelections 先抓今日前订单池,清空后回落第二池;日志补充池阶段信息 - 新增 normalizeWaveStrategyFetchCreatedBefore / buildWaveStrategyFetchTodayStart - 附带:resolveWaveScopeByWaveMeta 单品单件 wave_scope=4 映射与 pickMode 传递 - 新增边拣边分联调脚本与订单池完整验证脚本
528 lines
22 KiB
JavaScript
528 lines
22 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 边拣边分(batch_mode=3)策略 HTTP 联调脚本(含货主配置 OTHER 场景)。
|
||
*
|
||
* 通过 /system 入口按顺序完成:
|
||
* 1. user.login 登录获取 token(请使用仓库账号,策略配置仅仓库主体可维护);
|
||
* 2. 探测签约关系 id(优先环境变量 WMS_TEST_CONTRACT_ID,否则从签约列表自动查找);
|
||
* 3. storeWarehouse.store.getPolicyConfig 读取当前货主配置;
|
||
* 4. storeWarehouse.store.savePolicyConfig 修改货主配置:
|
||
* 默认平台 default_platform_code = OTHER(其他平台)、默认快递 default_express_code = OTHER(其他快递);
|
||
* 5. order.wave.waveStrategyCreate 创建散单-边拣边分策略;
|
||
* 6. order.pendingOrder.createOrder 创建 N 条同商品结构订单(显式 OTHER 平台 + OTHER 快递,items_hash 相同);
|
||
* 7. order.reviewOrder.reviewOrder 审核(仅当订单创建后 step=0);
|
||
* 8. order.pendingOrder.allocateExpressCode 分配快递并轮询进度(OTHER+OTHER 应成功);
|
||
* 9. order.pendingOrder.allocateStorage 分配储位并轮询进度;
|
||
* 10. order.wave.waveStrategyQuickScan 触发策略快速扫描并轮询进度;
|
||
* 11. order.wave.waveStrategyFetchPda 提交按策略抓取任务(存在未完成任务时自动取消本人任务后重试);
|
||
* 12. 负向验证:临时把货主默认快递改为非 OTHER 快递(默认 STO)→ 创建订单并分配快递,
|
||
* 预期分配不了运单号(该仓库仅有 QT+OTHER 接口配置);验证后还原货主默认快递为 OTHER。
|
||
*
|
||
* 用法(PowerShell 示例):
|
||
* $env:WMS_TEST_USERNAME='仓库账号'; $env:WMS_TEST_PASSWORD='密码';
|
||
* $env:WMS_TEST_STORE_ID='货主ID'; $env:WMS_TEST_ITEM_ID='商品库存ID';
|
||
* node .\script\tmp-wave-edge-pick-http-test.cjs
|
||
*
|
||
* 可选环境变量:
|
||
* WMS_BASE_URL 服务地址(默认 http://127.0.0.1:6060)
|
||
* WMS_TEST_CONTRACT_ID 签约关系 ID(不传则自动从签约列表探测)
|
||
* WMS_TEST_PLATFORM_CODE 货主默认平台编码(默认 OTHER)
|
||
* WMS_TEST_EXPRESS_CODE 货主默认快递编码(默认 OTHER)
|
||
* WMS_TEST_ORDER_COUNT 同结构订单数量(默认 2)
|
||
* WMS_TEST_PLAN_QTY 每条明细计划数量(默认 1)
|
||
* WMS_TEST_MIN_SAME_STRUCTURE 策略最小同结构订单数(默认 2,需 <= 订单数量)
|
||
* WMS_TEST_NEGATIVE_EXPRESS 负向验证快递编码(默认 STO)
|
||
*/
|
||
|
||
const BASE_URL = process.env.WMS_BASE_URL || 'http://127.0.0.1:6060';
|
||
const USERNAME = process.env.WMS_TEST_USERNAME || '';
|
||
const PASSWORD = process.env.WMS_TEST_PASSWORD || '';
|
||
const STORE_ID = Number(process.env.WMS_TEST_STORE_ID || 0);
|
||
const ITEM_ID = Number(process.env.WMS_TEST_ITEM_ID || 0);
|
||
const CONTRACT_ID = Number(process.env.WMS_TEST_CONTRACT_ID || 0);
|
||
const PLATFORM_CODE = String(process.env.WMS_TEST_PLATFORM_CODE || 'OTHER').trim() || 'OTHER';
|
||
const EXPRESS_CODE = String(process.env.WMS_TEST_EXPRESS_CODE || 'OTHER').trim() || 'OTHER';
|
||
const NEGATIVE_EXPRESS = String(process.env.WMS_TEST_NEGATIVE_EXPRESS || 'STO').trim() || 'STO';
|
||
const PLAN_QTY = Number(process.env.WMS_TEST_PLAN_QTY || 1);
|
||
const ORDER_COUNT = Number(process.env.WMS_TEST_ORDER_COUNT || 2);
|
||
const MIN_SAME_STRUCTURE = Number(process.env.WMS_TEST_MIN_SAME_STRUCTURE || 2);
|
||
const POLL_TIMEOUT_MS = 90 * 1000;
|
||
const POLL_INTERVAL_MS = 1500;
|
||
|
||
/**
|
||
* 发送 /system POST 请求。
|
||
*
|
||
* @param {string} method 方法名(如 order.wave.waveStrategyCreate)。
|
||
* @param {Object} [data={}] 请求体参数。
|
||
* @param {string|null} [token=null] 登录令牌。
|
||
* @return {Promise<Object>} { httpStatus, json } 响应结果。
|
||
*/
|
||
async function callSystem(method, data = {}, token = null) {
|
||
const url = `${BASE_URL}/system?method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`;
|
||
const headers = {
|
||
'Content-Type': 'application/json',
|
||
};
|
||
if (token) {
|
||
headers.Authorization = `Bearer ${token}`;
|
||
}
|
||
|
||
const controller = new AbortController();
|
||
const timer = setTimeout(() => controller.abort(), 30 * 1000);
|
||
try {
|
||
const response = await fetch(url, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
platform: 'web',
|
||
project: 'wms',
|
||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||
},
|
||
body: JSON.stringify(data),
|
||
signal: controller.signal,
|
||
});
|
||
const text = await response.text();
|
||
let json = null;
|
||
try {
|
||
json = JSON.parse(text);
|
||
} catch (error) {
|
||
json = { raw: text };
|
||
}
|
||
return { httpStatus: response.status, json };
|
||
} finally {
|
||
clearTimeout(timer);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 深度优先查找对象中第一个匹配 key 的非空值。
|
||
*
|
||
* @param {*} target 待查找对象。
|
||
* @param {string} key 目标字段名。
|
||
* @return {*} 匹配值或 undefined。
|
||
*/
|
||
function deepFind(target, key) {
|
||
if (target === null || target === undefined) {
|
||
return undefined;
|
||
}
|
||
if (Array.isArray(target)) {
|
||
for (const item of target) {
|
||
const found = deepFind(item, key);
|
||
if (found !== undefined) {
|
||
return found;
|
||
}
|
||
}
|
||
return undefined;
|
||
}
|
||
if (typeof target === 'object') {
|
||
for (const [ currentKey, value ] of Object.entries(target)) {
|
||
if (currentKey === key && value !== null && value !== undefined && value !== '') {
|
||
return value;
|
||
}
|
||
}
|
||
for (const value of Object.values(target)) {
|
||
const found = deepFind(value, key);
|
||
if (found !== undefined) {
|
||
return found;
|
||
}
|
||
}
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
/**
|
||
* 从列表响应中按匹配函数查找首个满足条件的记录。
|
||
*
|
||
* @param {Object} json 响应 JSON。
|
||
* @param {Function} matcher 匹配函数,接收 list 项返回 boolean。
|
||
* @return {Object|null} 命中的记录或 null。
|
||
*/
|
||
function findListRecord(json, matcher) {
|
||
const list = deepFind(json, 'list');
|
||
if (!Array.isArray(list)) {
|
||
return null;
|
||
}
|
||
return list.find(item => typeof matcher === 'function' && matcher(item)) || null;
|
||
}
|
||
|
||
/**
|
||
* 按条件轮询异步任务直到完成或超时。
|
||
*
|
||
* @param {Function} pollFn 轮询函数,返回 { done:boolean, payload:* }。
|
||
* @param {number} timeoutMs 超时毫秒数。
|
||
* @param {number} intervalMs 轮询间隔毫秒数。
|
||
* @return {Promise<Object>} { ok, payload } 最终结果。
|
||
*/
|
||
async function pollUntilDone(pollFn, timeoutMs = POLL_TIMEOUT_MS, intervalMs = POLL_INTERVAL_MS) {
|
||
const startedAt = Date.now();
|
||
let lastPayload = null;
|
||
while (Date.now() - startedAt < timeoutMs) {
|
||
const result = await pollFn();
|
||
lastPayload = result.payload;
|
||
if (result.done) {
|
||
return { ok: true, payload: lastPayload };
|
||
}
|
||
await new Promise(resolve => setTimeout(resolve, intervalMs));
|
||
}
|
||
return { ok: false, payload: lastPayload };
|
||
}
|
||
|
||
/**
|
||
* 校验脚本运行所需环境变量。
|
||
*
|
||
* @return {void}
|
||
*/
|
||
function ensureEnv() {
|
||
const missingList = [];
|
||
if (!USERNAME) {
|
||
missingList.push('WMS_TEST_USERNAME');
|
||
}
|
||
if (!PASSWORD) {
|
||
missingList.push('WMS_TEST_PASSWORD');
|
||
}
|
||
if (!Number.isInteger(STORE_ID) || STORE_ID <= 0) {
|
||
missingList.push('WMS_TEST_STORE_ID');
|
||
}
|
||
if (!Number.isInteger(ITEM_ID) || ITEM_ID <= 0) {
|
||
missingList.push('WMS_TEST_ITEM_ID');
|
||
}
|
||
if (missingList.length > 0) {
|
||
throw new Error(`缺少环境变量: ${missingList.join(', ')}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 探测货主在当前仓库下的签约关系 ID。
|
||
*
|
||
* 优先使用 WMS_TEST_CONTRACT_ID;否则依次从仓库侧签约列表与货主侧签约列表查找。
|
||
*
|
||
* @param {string} token 登录令牌。
|
||
* @return {Promise<number>} 签约关系 ID。
|
||
*/
|
||
async function resolveContractId(token) {
|
||
if (Number.isInteger(CONTRACT_ID) && CONTRACT_ID > 0) {
|
||
return CONTRACT_ID;
|
||
}
|
||
|
||
const warehouseListRes = await callSystem('storeWarehouse.warehouse.list', {
|
||
page: 1,
|
||
page_size: 100,
|
||
}, token);
|
||
const warehouseSide = findListRecord(warehouseListRes.json, item => Number(item && item.store_id) === STORE_ID);
|
||
if (warehouseSide && Number(warehouseSide.id) > 0) {
|
||
return Number(warehouseSide.id);
|
||
}
|
||
|
||
const storeListRes = await callSystem('storeWarehouse.store.list', {
|
||
page: 1,
|
||
page_size: 100,
|
||
}, token);
|
||
const storeSide = findListRecord(storeListRes.json, item => Number(item && item.warehouse_id) > 0);
|
||
if (storeSide && Number(storeSide.id) > 0) {
|
||
return Number(storeSide.id);
|
||
}
|
||
|
||
throw new Error(`未能从签约列表自动探测货主 ${STORE_ID} 的签约关系,请设置 WMS_TEST_CONTRACT_ID`);
|
||
}
|
||
|
||
/**
|
||
* 创建一条测试订单。
|
||
*
|
||
* @param {string} token 登录令牌。
|
||
* @param {Object} [options={}] 订单参数。
|
||
* @param {string} [options.platformCode] 系统平台编码(默认取 PLATFORM_CODE)。
|
||
* @param {string} [options.logisticsCode] 快递编码(默认取 EXPRESS_CODE)。
|
||
* @param {number} [options.suffix=0] 收件人手机与地址后缀。
|
||
* @return {Promise<number>} 订单 ID。
|
||
*/
|
||
async function createTestOrder(token, options = {}) {
|
||
const platformCode = String(options.platformCode || PLATFORM_CODE).trim();
|
||
const hasLogisticsCode = options.logisticsCode !== undefined && options.logisticsCode !== null;
|
||
const logisticsCode = hasLogisticsCode ? String(options.logisticsCode).trim() : '';
|
||
const suffix = Number(options.suffix || 0);
|
||
const items = [{ item_id: ITEM_ID, plan_qty: PLAN_QTY }];
|
||
|
||
const body = {
|
||
store_id: STORE_ID,
|
||
name: '联调测试收件人',
|
||
mobile: `1380000${String(suffix).padStart(4, '0')}`,
|
||
detail_address: `联调测试地址${suffix + 1}号`,
|
||
province: '广东省',
|
||
city: '广州市',
|
||
area: '天河区',
|
||
sys_platform_code: platformCode,
|
||
items,
|
||
};
|
||
if (hasLogisticsCode) {
|
||
body.logistics_code = logisticsCode;
|
||
}
|
||
|
||
const orderRes = await callSystem('order.pendingOrder.createOrder', body, token);
|
||
const orderId = Number(deepFind(orderRes.json, 'order_id') || 0);
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
throw new Error(`订单创建失败,响应: ${JSON.stringify(orderRes.json)}`);
|
||
}
|
||
return orderId;
|
||
}
|
||
|
||
/**
|
||
* 主流程入口。
|
||
*
|
||
* @return {Promise<void>}
|
||
*/
|
||
async function main() {
|
||
ensureEnv();
|
||
console.log(`[联调] 目标服务: ${BASE_URL}`);
|
||
console.log(`[联调] 货主ID: ${STORE_ID},商品ID: ${ITEM_ID},订单数: ${ORDER_COUNT}`);
|
||
console.log(`[联调] 目标平台: ${PLATFORM_CODE},目标快递: ${EXPRESS_CODE},负向快递: ${NEGATIVE_EXPRESS}`);
|
||
|
||
// 1. 登录
|
||
const loginRes = await callSystem('user.login', {
|
||
username: USERNAME,
|
||
password: PASSWORD,
|
||
});
|
||
const token = deepFind(loginRes.json, 'token');
|
||
if (!token) {
|
||
throw new Error(`登录失败,响应: ${JSON.stringify(loginRes.json)}`);
|
||
}
|
||
console.log('[1/12] 登录成功,已获取 token');
|
||
|
||
// 2. 探测签约关系 ID
|
||
const contractId = await resolveContractId(token);
|
||
console.log(`[2/12] 签约关系 ID: ${contractId}`);
|
||
|
||
// 3. 读取当前货主配置
|
||
const configRes = await callSystem('storeWarehouse.store.getPolicyConfig', { id: contractId }, token);
|
||
const currentPolicy = deepFind(configRes.json, 'policy_config');
|
||
const currentPolicyObject = currentPolicy && typeof currentPolicy === 'object' && !Array.isArray(currentPolicy)
|
||
? currentPolicy
|
||
: {};
|
||
console.log(`[3/12] 当前货主配置: ${JSON.stringify(currentPolicyObject).slice(0, 300)}`);
|
||
|
||
// 4. 修改货主配置:默认平台/默认快递改为 OTHER(其他平台/其他快递)
|
||
const updatedPolicy = {
|
||
...currentPolicyObject,
|
||
default_platform_code: PLATFORM_CODE,
|
||
default_express_code: EXPRESS_CODE,
|
||
};
|
||
const saveConfigRes = await callSystem('storeWarehouse.store.savePolicyConfig', {
|
||
id: contractId,
|
||
policy_config: updatedPolicy,
|
||
}, token);
|
||
const savedPolicy = deepFind(saveConfigRes.json, 'policy_config');
|
||
const savedDefaultPlatform = String(savedPolicy && savedPolicy.default_platform_code || '').trim();
|
||
const savedDefaultExpress = String(savedPolicy && savedPolicy.default_express_code || '').trim();
|
||
console.log(`[4/12] 货主配置已更新: 默认平台=${savedDefaultPlatform}, 默认快递=${savedDefaultExpress}`);
|
||
if (savedDefaultPlatform !== PLATFORM_CODE || savedDefaultExpress !== EXPRESS_CODE) {
|
||
console.warn(`[4/12] 警告: 保存结果与预期不一致,响应: ${JSON.stringify(saveConfigRes.json)}`);
|
||
}
|
||
|
||
// 5. 创建边拣边分策略
|
||
const strategyName = `HTTP联调-边拣边分-${Date.now()}`;
|
||
const strategyRes = await callSystem('order.wave.waveStrategyCreate', {
|
||
strategy_name: strategyName,
|
||
strategy_type: 1,
|
||
batch_mode: 3,
|
||
status: 1,
|
||
min_same_structure: MIN_SAME_STRUCTURE,
|
||
require_same_express: false,
|
||
batch_max_orders: 20,
|
||
batch_max_skus: 50,
|
||
description: 'HTTP 联调用边拣边分策略',
|
||
}, token);
|
||
const strategyId = Number(deepFind(strategyRes.json, 'id') || 0);
|
||
if (!Number.isInteger(strategyId) || strategyId <= 0) {
|
||
throw new Error(`策略创建失败,响应: ${JSON.stringify(strategyRes.json)}`);
|
||
}
|
||
console.log(`[5/12] 策略创建成功: id=${strategyId}, name=${strategyName}`);
|
||
|
||
// 6. 创建同结构订单(显式 OTHER 平台 + OTHER 快递)
|
||
const orderIds = [];
|
||
for (let index = 0; index < ORDER_COUNT; index += 1) {
|
||
const orderId = await createTestOrder(token, {
|
||
platformCode: PLATFORM_CODE,
|
||
logisticsCode: EXPRESS_CODE,
|
||
suffix: index,
|
||
});
|
||
orderIds.push(orderId);
|
||
}
|
||
console.log(`[6/12] 同结构订单创建成功: order_ids=[${orderIds.join(', ')}]`);
|
||
|
||
// 7. 若存在待审核订单则审核
|
||
let needReview = false;
|
||
for (const orderId of orderIds) {
|
||
const detailRes = await callSystem('order.pendingOrder.detail', { id: orderId }, token);
|
||
const step = Number(deepFind(detailRes.json, 'step') || 0);
|
||
if (step === 0) {
|
||
needReview = true;
|
||
break;
|
||
}
|
||
}
|
||
if (needReview) {
|
||
const reviewRes = await callSystem('order.reviewOrder.reviewOrder', { ids: orderIds }, token);
|
||
console.log(`[7/12] 订单审核完成: ${JSON.stringify(reviewRes.json)}`);
|
||
} else {
|
||
console.log('[7/12] 订单无需审核(step 已非 0),跳过');
|
||
}
|
||
|
||
// 8. 分配快递并轮询(OTHER 平台 + OTHER 快递应成功)
|
||
const expressRes = await callSystem('order.pendingOrder.allocateExpressCode', { ids: orderIds }, token);
|
||
const expressTaskId = deepFind(expressRes.json, 'task_id');
|
||
if (!expressTaskId) {
|
||
throw new Error(`快递分配提交失败,响应: ${JSON.stringify(expressRes.json)}`);
|
||
}
|
||
const expressPoll = await pollUntilDone(async () => {
|
||
const progressRes = await callSystem('order.pendingOrder.allocateExpressCodeTaskProgress', { task_id: expressTaskId }, token);
|
||
const status = String(deepFind(progressRes.json, 'status') || '');
|
||
const progress = Number(deepFind(progressRes.json, 'progress') || 0);
|
||
return {
|
||
done: [ 'success', 'failed', 'error', 'finish' ].includes(status) || progress >= 100,
|
||
payload: progressRes.json,
|
||
};
|
||
});
|
||
if (!expressPoll.ok) {
|
||
console.warn('[8/12] 快递分配轮询超时,可能仍在中途,请稍后复查');
|
||
} else {
|
||
console.log(`[8/12] 快递分配任务结束: ${JSON.stringify(expressPoll.payload).slice(0, 300)}`);
|
||
}
|
||
|
||
// 9. 分配储位并轮询
|
||
const storageRes = await callSystem('order.pendingOrder.allocateStorage', { order_ids: orderIds }, token);
|
||
const requestId = deepFind(storageRes.json, 'request_id');
|
||
if (!requestId) {
|
||
throw new Error(`储位分配提交失败,响应: ${JSON.stringify(storageRes.json)}`);
|
||
}
|
||
const storagePoll = await pollUntilDone(async () => {
|
||
const progressRes = await callSystem('order.pendingOrder.allocateStorageProgress', { request_id: requestId }, token);
|
||
const status = String(deepFind(progressRes.json, 'status') || '');
|
||
const progress = Number(deepFind(progressRes.json, 'progress') || 0);
|
||
return {
|
||
done: [ 'success', 'failed', 'error', 'finish' ].includes(status) || progress >= 100,
|
||
payload: progressRes.json,
|
||
};
|
||
});
|
||
if (!storagePoll.ok) {
|
||
console.warn('[9/12] 储位分配轮询超时,可能仍在中途,请稍后复查');
|
||
} else {
|
||
console.log(`[9/12] 储位分配任务结束: ${JSON.stringify(storagePoll.payload).slice(0, 300)}`);
|
||
}
|
||
|
||
// 10. 快速扫描并轮询
|
||
const scanRes = await callSystem('order.wave.waveStrategyQuickScan', {}, token);
|
||
const scanTaskId = deepFind(scanRes.json, 'task_id');
|
||
if (!scanTaskId) {
|
||
throw new Error(`快速扫描提交失败,响应: ${JSON.stringify(scanRes.json)}`);
|
||
}
|
||
const scanPoll = await pollUntilDone(async () => {
|
||
const progressRes = await callSystem('order.wave.waveStrategyQuickScanTaskProgress', { task_id: scanTaskId }, token);
|
||
const state = String(deepFind(progressRes.json, 'state') || '');
|
||
return {
|
||
done: [ 'success', 'failed' ].includes(state),
|
||
payload: progressRes.json,
|
||
};
|
||
});
|
||
if (!scanPoll.ok) {
|
||
throw new Error(`快速扫描超时: ${JSON.stringify(scanPoll.payload)}`);
|
||
}
|
||
const matchedCount = Number(deepFind(scanPoll.payload, 'matched_order_count') || 0);
|
||
const unmatchedCount = Number(deepFind(scanPoll.payload, 'unmatched_order_count') || 0);
|
||
console.log(`[10/12] 快速扫描完成: matched=${matchedCount}, unmatched=${unmatchedCount}`);
|
||
if (matchedCount <= 0) {
|
||
console.warn('[10/12] 提示: matched=0。订单可能已被自动扫描(wave_strategy_version 与当前一致,不在扫描范围),以 PDA 抓取结果为准');
|
||
}
|
||
|
||
// 11. PDA 按策略抓取(存在未完成任务时先取消本人任务再重试)
|
||
let fetchRes = await callSystem('order.wave.waveStrategyFetchPda', { strategy_id: strategyId }, token);
|
||
let flag = String(deepFind(fetchRes.json, 'flag') || '');
|
||
let fetchState = Number(deepFind(fetchRes.json, 'fetch_state') || 0);
|
||
let taskId = deepFind(fetchRes.json, 'task_id');
|
||
let taskNo = deepFind(fetchRes.json, 'task_no');
|
||
if (fetchState === 3 && Number(taskId) > 0) {
|
||
console.log(`[11/12] 检测到未完成任务 ${taskId}(${taskNo || ''}),先取消本人任务后重试`);
|
||
const cancelRes = await callSystem('order.wave.wavePickTaskCancelSelf', { task_id: Number(taskId) }, token);
|
||
console.log(`[11/12] 取消任务响应: ${JSON.stringify(cancelRes.json).slice(0, 300)}`);
|
||
fetchRes = await callSystem('order.wave.waveStrategyFetchPda', { strategy_id: strategyId }, token);
|
||
flag = String(deepFind(fetchRes.json, 'flag') || '');
|
||
fetchState = Number(deepFind(fetchRes.json, 'fetch_state') || 0);
|
||
taskId = deepFind(fetchRes.json, 'task_id');
|
||
taskNo = deepFind(fetchRes.json, 'task_no');
|
||
}
|
||
console.log(`[11/12] PDA 抓取响应: ${JSON.stringify(fetchRes.json)}`);
|
||
|
||
// 12. 负向验证:临时把货主默认快递改为非 OTHER 快递,预期分配不了运单号
|
||
let negativeAllocated = null;
|
||
try {
|
||
console.log(`[12/12] 负向验证开始: 临时改货主默认快递为 ${NEGATIVE_EXPRESS}`);
|
||
const negativeConfigRes = await callSystem('storeWarehouse.store.savePolicyConfig', {
|
||
id: contractId,
|
||
policy_config: {
|
||
...currentPolicyObject,
|
||
default_platform_code: PLATFORM_CODE,
|
||
default_express_code: NEGATIVE_EXPRESS,
|
||
},
|
||
}, token);
|
||
const negativeDefaultExpress = String(deepFind(negativeConfigRes.json, 'default_express_code') || '').trim();
|
||
if (negativeDefaultExpress !== NEGATIVE_EXPRESS) {
|
||
throw new Error(`负向配置切换失败: ${JSON.stringify(negativeConfigRes.json)}`);
|
||
}
|
||
|
||
const negativeOrderId = await createTestOrder(token, {
|
||
platformCode: PLATFORM_CODE,
|
||
logisticsCode: null,
|
||
suffix: ORDER_COUNT + 99,
|
||
});
|
||
const negativeDetailRes = await callSystem('order.pendingOrder.detail', { id: negativeOrderId }, token);
|
||
const negativeStep = Number(deepFind(negativeDetailRes.json, 'step') || 0);
|
||
if (negativeStep === 0) {
|
||
await callSystem('order.reviewOrder.reviewOrder', { ids: [ negativeOrderId ] }, token);
|
||
}
|
||
const negativeExpressRes = await callSystem('order.pendingOrder.allocateExpressCode', { ids: [ negativeOrderId ] }, token);
|
||
const negativeTaskId = deepFind(negativeExpressRes.json, 'task_id');
|
||
if (!negativeTaskId) {
|
||
throw new Error(`负向订单快递分配提交失败: ${JSON.stringify(negativeExpressRes.json)}`);
|
||
}
|
||
const negativePoll = await pollUntilDone(async () => {
|
||
const progressRes = await callSystem('order.pendingOrder.allocateExpressCodeTaskProgress', { task_id: negativeTaskId }, token);
|
||
const status = String(deepFind(progressRes.json, 'status') || '');
|
||
const progress = Number(deepFind(progressRes.json, 'progress') || 0);
|
||
return {
|
||
done: [ 'success', 'failed', 'error', 'finish' ].includes(status) || progress >= 100,
|
||
payload: progressRes.json,
|
||
};
|
||
});
|
||
const negativeStatus = String(deepFind(negativePoll.payload, 'status') || '');
|
||
negativeAllocated = negativePoll.ok && negativeStatus === 'success';
|
||
console.log(`[12/12] 负向订单(${PLATFORM_CODE}+${NEGATIVE_EXPRESS})分配结果: ${JSON.stringify(negativePoll.payload).slice(0, 300)}`);
|
||
} catch (error) {
|
||
console.warn(`[12/12] 负向验证执行异常(不影响主流程): ${error.message}`);
|
||
} finally {
|
||
await callSystem('storeWarehouse.store.savePolicyConfig', {
|
||
id: contractId,
|
||
policy_config: {
|
||
...currentPolicyObject,
|
||
default_platform_code: PLATFORM_CODE,
|
||
default_express_code: EXPRESS_CODE,
|
||
},
|
||
}, token).catch(error => {
|
||
console.warn(`[12/12] 还原货主配置失败: ${error.message}`);
|
||
});
|
||
console.log(`[12/12] 货主配置已还原: 默认平台=${PLATFORM_CODE}, 默认快递=${EXPRESS_CODE}`);
|
||
}
|
||
|
||
console.log('==================== 联调总结 ====================');
|
||
console.log(`策略ID: ${strategyId}(batch_mode=3 边拣边分)`);
|
||
console.log(`订单: [${orderIds.join(', ')}]`);
|
||
console.log(`快速扫描命中订单数: ${matchedCount}`);
|
||
console.log(`PDA 抓取: flag=${flag}, fetch_state=${fetchState}, task_id=${taskId || '无'}, task_no=${taskNo || '无'}`);
|
||
const passed = flag === 'success' && (fetchState === 1 || fetchState === 3);
|
||
console.log(`结论: ${passed ? '策略命中,抓取任务创建成功 ✅' : '未达成预期,请根据上述响应排查 ❌'}`);
|
||
if (negativeAllocated !== null) {
|
||
console.log(`负向验证: ${PLATFORM_CODE}+${NEGATIVE_EXPRESS} ${negativeAllocated ? '居然分配成功(与预期不符,需排查)❌' : '分配不了运单号(符合预期)✅'}`);
|
||
}
|
||
}
|
||
|
||
main().catch(error => {
|
||
console.error(`[联调] 执行失败: ${error.message}`);
|
||
process.exit(1);
|
||
});
|