feat: 波次复核开始时间回写与统计/防覆盖修复

- 波次策略列表 order.wave.waveStrategyList 成功响应新增 info.order_count(当前查询条件下全部策略命中订单去重总数,新增 getWaveStrategyMatchedOrderCountTotal,与行级统计同口径,统计失败安全降级为 0)

- 拣货任务 wms_wave_pick_task.finish_time 防覆盖:两处写入改为 CASE WHEN finish_time IS NULL,只记第一次

- 波次复核开始时间:新增迁移 20260908120000(wms_wave_batch 新增 recheck_start_time 字段,已在开发/生产执行)、模型字段同步、scanOrder 各成功分支首次回写(新增 markWaveRecheckStart,仅 IS NULL 时写入,回写失败不影响扫描主流程)

- 同步 methods/system.json 与 methods/changes/system.json 接口文档及变更记录(docMeta.version 更新至 0.3.101)

- 新增 recheckOrder-scanOrder-recheckStartTime HTTP 行为验证脚本与验证报告
This commit is contained in:
liufumingren 2026-09-08 16:36:57 +08:00
parent b1000fd0e8
commit 68dbf65c77
9 changed files with 787 additions and 7 deletions

View File

@ -97,6 +97,11 @@ module.exports = app => {
allowNull: true,
comment: '校验结果',
},
recheck_start_time: {
type: DATE,
allowNull: true,
comment: '复核开始时间',
},
priority: {
type: TINYINT,
allowNull: true,

View File

@ -30,6 +30,8 @@ class RecheckOrderService extends OrderBaseService {
* - 运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs、
* items_weight、suggested_package_material)
* - 所有模式的 list[] 每项均附带 items_weight(订单商品总重量)与 suggested_package_material(推荐包材信息,无推荐时为 null)
* - 任一模式首次成功加载波次复核视图时,回写该波次的复核开始时间(recheck_start_time),
* 仅首次写入(按 IS NULL 条件更新),回写失败仅告警、不影响扫描主流程
* @param {Object} data 请求体。
* @param {string} [data.keyword] 通用扫描关键词。
* @param {string} [data.value] 通用扫描关键词别名。
@ -75,6 +77,10 @@ class RecheckOrderService extends OrderBaseService {
this.buildGroupWaveList(groupTaskId, warehouseId),
this.getPickerInfoByTaskId(groupTaskId, warehouseId),
]);
await this.markWaveRecheckStart(
groupWaveList.map(item => Number(item.wave_id || 0)),
warehouseId
);
return {
match_type: matchType,
list_type: 'group',
@ -113,6 +119,7 @@ class RecheckOrderService extends OrderBaseService {
const scanView = await this.buildSingleWaveScanView(orderWaveId, orderWaveNo, warehouseId);
if (scanView) {
await this.markWaveRecheckStart([ orderWaveId ], warehouseId);
return {
match_type: matchType,
list_type: 'single',
@ -168,6 +175,10 @@ class RecheckOrderService extends OrderBaseService {
this.buildGroupWaveList(groupTaskId, warehouseId),
this.getPickerInfoByTaskId(groupTaskId, warehouseId),
]);
await this.markWaveRecheckStart(
groupWaveList.map(item => Number(item.wave_id || 0)),
warehouseId
);
return {
match_type: matchType,
list_type: 'group',
@ -182,6 +193,7 @@ class RecheckOrderService extends OrderBaseService {
const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId);
if (scanView) {
await this.markWaveRecheckStart([ waveId ], warehouseId);
return {
match_type: matchType,
list_type: 'single',
@ -212,6 +224,10 @@ class RecheckOrderService extends OrderBaseService {
this.buildGroupWaveList(taskId, warehouseId),
this.getPickerInfoByTaskId(taskId, warehouseId),
]);
await this.markWaveRecheckStart(
groupWaveList.map(item => Number(item.wave_id || 0)),
warehouseId
);
return {
match_type: 'cart',
list_type: 'group',
@ -239,6 +255,7 @@ class RecheckOrderService extends OrderBaseService {
const taskWaves = Array.isArray(taskWaveRows) ? taskWaveRows : [];
const scanViews = [];
const scannedWaveIds = [];
for (const tw of taskWaves) {
const waveId = Number(tw.wave_id || 0);
@ -249,10 +266,14 @@ class RecheckOrderService extends OrderBaseService {
if (scanView) {
scanViews.push(scanView);
scannedWaveIds.push(waveId);
}
}
}
// 扫描视图构建成功后回写波次复核开始时间(仅首次写入,失败不影响主流程)
await this.markWaveRecheckStart(scannedWaveIds, warehouseId);
if (scanViews.length === 0) {
return {
match_type: 'cart',
@ -324,6 +345,49 @@ class RecheckOrderService extends OrderBaseService {
throw new Error('未找到对应订单');
}
/**
* 回写波次复核开始时间(仅首次扫描写入)。
* 对每个有效波次执行条件更新:仅当 recheck_start_time 为空时写入 NOW(),并同步刷新 update_time,
* 与拣货任务开始时间补写惯例(app/service/systems/pick.js)保持一致;
* 多波次场景每个波次各自按 IS NULL 条件判断,已写过复核开始时间的波次不会被覆盖。
* 回写失败仅记录告警日志,不阻断扫描主流程(如迁移未执行导致字段缺失等场景)。
* @param {number|Array<number>} waveIds 波次ID或波次ID数组。
* @param {number} warehouseId 仓库ID。
* @return {Promise<void>} 无返回值。
*/
async markWaveRecheckStart(waveIds, warehouseId) {
const { ctx } = this;
const normalizedWarehouseId = Number(warehouseId || 0);
const sourceWaveIds = Array.isArray(waveIds) ? waveIds : [ waveIds ];
const normalizedWaveIds = [ ...new Set(sourceWaveIds
.map(id => Number(id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
if (normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) {
return;
}
try {
await ctx.model.query(
`
UPDATE wms_wave_batch
SET recheck_start_time = NOW(),
update_time = NOW()
WHERE wave_id IN (:waveIds)
AND warehouse_id = :warehouseId
AND recheck_start_time IS NULL
`,
{
replacements: { waveIds: normalizedWaveIds, warehouseId: normalizedWarehouseId },
}
);
} catch (error) {
ctx.logger.warn(
`[recheckOrder.markWaveRecheckStart] 回写波次复核开始时间失败,不影响扫描主流程, waveIds=${normalizedWaveIds.join(',')}, error=${error.message}`
);
}
}
/**
* 通过拣货任务ID刷新复核扫描视图。
* 根据任务的 pick_mode 区分散单/团单模式,返回与 scanOrder 一致的数据结构,用于前端刷新数据。

View File

@ -2931,6 +2931,25 @@ class WaveService extends OrderBaseService {
const total = Number(queryResult && queryResult.count || 0);
const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0;
// 统计本次查询条件下全部策略命中的去重订单总数(info.order_count);
// 与行级 matched_order_count_filtered 同口径,仅在该仓库存在策略时执行,
// 统计失败时安全降级为 0,不影响列表主流程。
let matchedOrderCountTotal = 0;
if (total > 0) {
try {
matchedOrderCountTotal = await this.getWaveStrategyMatchedOrderCountTotal(
contextWarehouseId,
{ strategyType: normalizedStrategyType }
);
} catch (error) {
this.ctx.logger.warn('[wave.waveStrategyList] 统计全部命中订单总数失败,降级为 0', {
warehouse_id: contextWarehouseId,
strategy_type: normalizedStrategyType,
error: error && error.message ? error.message : `${error}`,
});
}
}
return this.success('ok', {
list: mergedList,
pagination: {
@ -2941,6 +2960,9 @@ class WaveService extends OrderBaseService {
hasPrevious: page > 1,
hasNext: page < totalPages,
},
info: {
order_count: matchedOrderCountTotal,
},
});
}
@ -3340,6 +3362,103 @@ class WaveService extends OrderBaseService {
return matchedMap;
}
/**
* 统计仓库内全部策略命中的去重订单总数。
*
* 口径与 getWaveStrategyMatchedOrderCountFilteredMap 完全一致(订单池过滤、同结构
* 数量区间、require_same_express 分组方式),但不再按策略分组统计,而是汇总
* 查询条件下(仓库 + 可选策略类型)全部策略命中的订单并去重:
* 同一订单命中多个策略仅计一次。
*
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [options={}] 统计选项。
* @param {number|string|null} [options.strategyType=null] 策略类型过滤(1 散单 / 2 团购),为 null 时不限制。
* @return {Promise<number>} 全部策略命中的去重订单总数。
*/
async getWaveStrategyMatchedOrderCountTotal(warehouseId, options = {}) {
const normalizedWarehouseId = Number(warehouseId || 0);
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
throw new Error('未识别到当前仓库上下文');
}
const normalizedOptions = this.isPlainObject(options) ? options : {};
const strategyTypeRaw = Number(normalizedOptions.strategyType);
const strategyType = Number.isInteger(strategyTypeRaw) && [ 1, 2 ].includes(strategyTypeRaw)
? strategyTypeRaw
: null;
const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId);
const orderTableName = this.getModelTableSqlName(orderModel);
const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`;
const buildMatchedOrderIdSql = requireSameExpress => {
const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')} AS express_key` : '';
const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : '';
return `
SELECT m.order_id AS order_id
FROM wms_order_wave_strategy_match m
INNER JOIN ${orderTableName} o
ON o.id = m.order_id
AND o.warehouse_id = :warehouseId
AND o.wave_id = 0
AND o.step != 0
AND o.post_status = 'fin'
AND o.storage_status = 'fin'
AND o.print_status != 'fin'
AND o.status != 'cancel'
AND o.outbound_status != 'padding'
AND o.intercept_status = 'none'
AND o.lock_status = 'none'
INNER JOIN (
SELECT
src.items_hash AS structure_key${groupKeyExtra},
COUNT(1) AS same_structure_count
FROM ${orderTableName} src
WHERE src.warehouse_id = :warehouseId
AND src.wave_id = 0
AND src.step != 0
AND src.post_status = 'fin'
AND src.storage_status = 'fin'
AND src.print_status != 'fin'
AND src.status != 'cancel'
AND src.outbound_status != 'padding'
AND src.intercept_status = 'none'
AND src.lock_status = 'none'
GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''}
) same_structure
ON same_structure.structure_key = o.items_hash${joinKeyExtra}
INNER JOIN wms_wave_strategy s
ON s.id = m.strategy_id
AND s.warehouse_id = :warehouseId
AND COALESCE(s.require_same_express, 0) = ${requireSameExpress ? 1 : 0}
AND (:strategyType IS NULL OR s.strategy_type = :strategyType)
WHERE m.warehouse_id = :warehouseId
AND same_structure.same_structure_count >= COALESCE(NULLIF(s.min_same_structure, 0), 0)
AND (s.max_same_structure IS NULL OR s.max_same_structure <= 0 OR same_structure.same_structure_count <= s.max_same_structure)
`;
};
const countRows = await this.ctx.model.query(`
SELECT COUNT(DISTINCT matched.order_id) AS order_count
FROM (
${buildMatchedOrderIdSql(true)}
UNION ALL
${buildMatchedOrderIdSql(false)}
) matched
`, {
replacements: {
warehouseId: normalizedWarehouseId,
strategyType,
},
type: this.ctx.model.QueryTypes.SELECT,
});
const totalCount = Number(
(Array.isArray(countRows) && countRows[0] && countRows[0].order_count) || 0
);
return Number.isInteger(totalCount) && totalCount >= 0 ? totalCount : 0;
}
/**
* 新增波次策略。
*

View File

@ -2170,7 +2170,7 @@ class PickSystemService extends Service {
await this.ctx.model.query(`
UPDATE wms_wave_pick_task
SET status = 2,
finish_time = NOW(),
finish_time = CASE WHEN finish_time IS NULL THEN NOW() ELSE finish_time END,
start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END,
update_time = NOW()
WHERE id = :taskId
@ -2453,7 +2453,7 @@ class PickSystemService extends Service {
await ctx.model.query(`
UPDATE wms_wave_pick_task
SET status = 2,
finish_time = NOW(),
finish_time = CASE WHEN finish_time IS NULL THEN NOW() ELSE finish_time END,
start_time = CASE WHEN start_time IS NULL THEN NOW() ELSE start_time END,
update_time = NOW()
WHERE id = :taskId

View File

@ -0,0 +1,71 @@
'use strict';
/**
* 为波次表 wms_wave_batch 增加复核开始时间字段。
*
* 背景:
* 复核扫描接口 order.recheckOrder.scanOrder 首次成功加载某波次的复核视图时,
* 需要记录该波次的复核开始时间用于统计与审计;此前波次表仅有复核完成时间
* (check_time,校验时间),缺少复核开始时间,二者语义不同不可复用。
*
* 变更:
* 1. wms_wave_batch 新增 recheck_start_time:DATETIME,可空、无默认值,复核开始时间。
* 2. 不回填任何历史数据(对既有数据零影响,仅后续首次扫描时写入)。
* 3. 模型定义同步更新(app/model/wave_batch.js)。
*
* 幂等:字段已存在则跳过;回滚时字段不存在则跳过。
*/
const TABLE_NAME = 'wms_wave_batch';
const COLUMN_NAME = 'recheck_start_time';
const FILE_TAG = '[20260908120000-add-recheck-start-time-to-wms-wave-batch]';
/**
* 获取表字段定义。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Object>} 字段定义对象。
*/
const getTableColumns = async (queryInterface, tableName) => {
return queryInterface.describeTable(tableName);
};
module.exports = {
/**
* 正向迁移:为波次表补充复核开始时间字段(字段已存在则跳过)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME);
if (!columnsBefore[COLUMN_NAME]) {
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
type: Sequelize.DATE,
allowNull: true,
comment: '复核开始时间',
after: 'check_result',
});
console.log(`${FILE_TAG} up: added column ${COLUMN_NAME} on ${TABLE_NAME}`);
} else {
console.log(`${FILE_TAG} up: skip, column ${COLUMN_NAME} already exists on ${TABLE_NAME}`);
}
},
/**
* 回滚迁移:若复核开始时间字段存在则删除。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME);
if (columnsBefore[COLUMN_NAME]) {
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
console.log(`${FILE_TAG} down: removed column ${COLUMN_NAME} on ${TABLE_NAME}`);
} else {
console.log(`${FILE_TAG} down: skip, column ${COLUMN_NAME} not exists on ${TABLE_NAME}`);
}
},
};

View File

@ -1,4 +1,21 @@
[
{
"version": "2026.09.08-wave-strategy-list-info-order-count",
"date": "2026-09-08",
"type": "changed",
"summary": "order.wave.waveStrategyList 成功响应新增 info 子对象(info.order_count):返回当前查询条件下(当前仓库 + strategy_type 过滤)全部波次策略命中的订单总数,按订单去重、不受分页影响,统计失败时安全降级为 0;错误/失败路径响应结构不变,成功路径 info 恒存在。",
"methods": [
"order.wave.waveStrategyList"
],
"module": "order.wave",
"notes": [
"app/service/systemMethods/order/wave.js:waveStrategyList 成功响应新增 info 对象;当 total>0(当前仓库存在波次策略)时调用 getWaveStrategyMatchedOrderCountTotal(contextWarehouseId,{strategyType}) 统计全部命中订单去重总数,异常时捕获并记录 warn 日志(含 warehouse_id/strategy_type/error)后降级为 0,不影响列表主流程",
"app/service/systemMethods/order/wave.js:新增 getWaveStrategyMatchedOrderCountTotal(warehouseId,{strategyType}):基于 wms_order_wave_strategy_match 关联订单表与 wms_wave_strategy,require_same_express=1(结构+快递分组)与 =0(仅结构分组)两类候选口径 UNION ALL 后 COUNT(DISTINCT order_id);strategy_type 非法或未传时为 null(不过滤);仅统计未入波次且满足同结构 min/max 上下限的候选订单",
"methods/system.json:order.wave 分组 order.wave.waveStrategyList 条目 response 数组末尾新增 info 子对象及 order_count 字段说明(全部命中订单去重总数、不受分页影响、异常降级为 0),params/headers/description 保持原样;errors 条目键名由 description 规范化为 message(文案不变,满足更新脚本 schema,与 order.manualOutboundOrder 等先例一致);docMeta.version 0.3.100 -> 0.3.101,updatedAt 保持 2026-09-08;本变更记录写入 methods/changes/system.json 数组首位",
"README.md / AI_TOOLBOX.md 无需同步:检索确认无 waveStrategyList 响应结构描述;AI_METHOD_ROUTING.md 第 6 节为自动扫描函数清单(本次新增 getWaveStrategyMatchedOrderCountTotal 已纳入代码),如需刷新清单可另行执行扫描脚本",
"本次仅同步文档,未修改任何业务代码,未执行数据库/Redis 写操作"
]
},
{
"version": "2026.09.07-ai-method-routing-service-inventory-refresh",
"date": "2026-09-07",

View File

@ -1,8 +1,8 @@
{
"module": "system",
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
"version": "0.3.97",
"updatedAt": "2026-09-07",
"version": "0.3.101",
"updatedAt": "2026-09-08",
"headers": [
{
"name": "platform",
@ -7775,20 +7775,33 @@
"type": "object",
"required": true,
"description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)"
},
{
"name": "info",
"type": "object",
"required": true,
"description": "查询汇总信息对象(成功路径恒存在;错误/失败路径响应结构不变,不含本字段)。包含当前查询条件下全部波次策略命中的去重订单总数。",
"children": [
{
"name": "order_count",
"type": "number",
"description": "当前查询条件下(当前仓库 + strategy_type 过滤)所有策略命中的订单总数,按订单去重(COUNT DISTINCT order_id)统计,不受分页影响;口径与 list[*].matched_order_count_filtered 的抓取候选一致(require_same_express=1 与 =0 两类候选口径合并去重);仅当当前仓库存在波次策略时执行统计,统计失败时安全降级为 0,不影响列表主流程。"
}
]
}
],
"errors": [
{
"code": "400",
"description": "缺少仓库上下文或分页参数不合法"
"message": "缺少仓库上下文或分页参数不合法"
},
{
"code": "400",
"description": "strategy_type 非法(仅支持 1/2)"
"message": "strategy_type 非法(仅支持 1/2)"
},
{
"code": "500",
"description": "查询失败"
"message": "查询失败"
}
]
},

View File

@ -0,0 +1,405 @@
'use strict';
/**
* recheck_start_time(wms_wave_batch 复核开始时间)HTTP 链路验证。
*
* 验证目标:
* 1. 首次扫描写入: 通过 HTTP 调用 order.recheckOrder.scanOrder 扫描有订单的波次,
* 验证对应波次 wms_wave_batch.recheck_start_time 被写入且非 NULL;
* 2. 重复扫描不覆盖: 等待 >=2 秒后再次用同一方式扫描同一波次,
* 验证 recheck_start_time 保持不变(只记第一次);
* 3. 多波次/其他路径(加分项): 车号匹配(散单 cart)写入另一波次;
* 团购任务路径(pick_mode=1, cart=car0008)写入任务下多波次,逐一验证。
*
* 数据约定(固定测试参数):
* - 测试仓库 warehouse_id = 100000(用户切换角色 roleId=4 后 ctx.user.store_id)
* - 主波次: wave_no=B2026081500099, wave_id=1777970280349948(无拣货任务关联→pick_mode=0 散单视图, 500 单已拣货未复核, recheck_start_time 原为 NULL)
* - 运单号: YT000000000276(订单 70125, 属于主波次)
* - 车号(散单): 1919810 → task 273 → wave A2026090600014(8 单已拣货, 首写或已写)
* - 车号(团购): car0008 → task 160(pick_mode=1)→ 20 个团购波次(首写或已写)
*
* 约束: 库验证一律 SELECT 只读,业务写入仅由 HTTP 接口产生;不触碰生产环境。
*
* 运行方式: node test/app/service/systemMethods/order/recheckOrder-scanOrder-recheckStartTime-http.integration.test.js
* 前置: 本地 dev 服务已启动(http://127.0.0.1:6060),迁移 20260908120000 已执行。
*/
const path = require('node:path');
const fs = require('node:fs');
const {
invokeSystemMethod,
getAuthToken,
BASE_URL,
} = require('../../../../support/system_method_client');
const { createTestDb } = require('../../../../support/test_db_client');
const TEST_WAREHOUSE_ID = 100000;
const MAIN_WAVE_NO = 'B2026081500099';
const MAIN_WAVE_ID = 1777970280349948;
const WAYBILL_NO = 'YT000000000276';
const CART_CODE_SINGLE = '1919810';
const CART_WAVE_NO = 'A2026090600014';
const CART_WAVE_ID = 1777970280350088;
const GROUP_CART_CODE = 'car0008';
const GROUP_TASK_ID = 160;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const results = [];
let db = null;
function record(testName, passed, detail = '') {
results.push({ testName, passed, detail });
const status = passed ? '✓ PASS' : '✗ FAIL';
console.log(` ${status}: ${testName}${detail ? ' — ' + detail : ''}`);
}
function fmtDbTime(value) {
if (!value) return 'NULL';
return value instanceof Date ? value.toISOString() : String(value);
}
/**
* 只读查询波次的复核开始时间与更新时间(DATE_FORMAT 输出库端时区字符串)。
* @param {number} waveId 波次ID。
* @return {Promise<Object|null>} 波次行(recheck_start_time/update_time/create_time),不存在时返回 null。
*/
async function readWaveRecheck(waveId) {
const [ rows ] = await db.query(
`SELECT wave_id, wave_no,
DATE_FORMAT(recheck_start_time, '%Y-%m-%d %H:%i:%s.%f') AS recheck_start_time,
DATE_FORMAT(update_time, '%Y-%m-%d %H:%i:%s.%f') AS update_time,
DATE_FORMAT(create_time, '%Y-%m-%d %H:%i:%s.%f') AS create_time
FROM wms_wave_batch
WHERE wave_id = ? AND warehouse_id = ?`,
[ waveId, TEST_WAREHOUSE_ID ]
);
return rows.length > 0 ? rows[0] : null;
}
/**
* 发起一次 scanOrder HTTP 调用并记录报文关键信息。
* @param {string} label 扫描步骤标签。
* @param {Object} params 扫描请求体参数。
* @param {string} token 用户 token。
* @return {Promise<Object>} 扫描报文摘要。
*/
async function scanOnce(label, params, token) {
const before = new Date();
const res = await invokeSystemMethod('order.recheckOrder.scanOrder', params, token);
const after = new Date();
const data = res.body && res.body.data ? res.body.data : null;
return {
label,
params,
httpStatus: res.status,
flag: res.body && res.body.flag,
message: res.body && (res.body.message || res.body.msg) || '',
matchType: data && data.match_type,
listType: data && data.list_type,
taskId: data && data.task_id,
pickerId: data && data.picker_id,
listLen: data && Array.isArray(data.list) ? data.list.length : null,
beforeIso: before.toISOString(),
afterIso: after.toISOString(),
};
}
async function runTests() {
console.log('========================================');
console.log('recheck_start_time 写入行为 HTTP 链路验证');
console.log('目标服务: ' + BASE_URL);
console.log('测试仓库: ' + TEST_WAREHOUSE_ID);
console.log('测试时间: ' + new Date().toISOString());
console.log('========================================\n');
db = await createTestDb();
// ============ 认证与角色切换 ============
let token;
try {
const auth = await getAuthToken();
const changed = await invokeSystemMethod('user.changeRole', { roleId: 4 }, auth.token);
if (changed.body.flag !== 'success') {
throw new Error('changeRole 失败: ' + (changed.body.message || changed.body.msg));
}
token = changed.body.data && changed.body.data.token;
if (!token) throw new Error('changeRole 未返回 token');
const info = await invokeSystemMethod('user.info', {}, token);
const storeId = info.body && info.body.data && info.body.data.store_id;
console.log(`[INFO] 认证成功, 角色切换后 store_id=${storeId}, store_name=${info.body.data.store_name}`);
if (String(storeId) !== String(TEST_WAREHOUSE_ID)) {
throw new Error(`角色切换后 store_id=${storeId} 不等于测试仓库 ${TEST_WAREHOUSE_ID}`);
}
record('auth-1: 登录并切换角色后 store_id=100000', true, `store_id=${storeId}`);
} catch (err) {
console.error('[FATAL] 认证/角色切换失败: ' + err.message);
process.exit(1);
}
// ============ 前置: 运单号归属校验 ============
const [ waybillRows ] = await db.query(
'SELECT order_id, warehouse_id FROM wms_order_express WHERE waybill_code = ? ORDER BY id LIMIT 5',
[ WAYBILL_NO ]
);
const waybillOk = waybillRows.some(r => Number(r.warehouse_id) === TEST_WAREHOUSE_ID);
record('pre-1: 运单号 ' + WAYBILL_NO + ' 归属仓库 100000', waybillOk,
waybillRows.map(r => `order_id=${r.order_id},warehouse_id=${r.warehouse_id}`).join(' | '));
// ============ 扫描前基线 ============
const mainWaveBefore = await readWaveRecheck(MAIN_WAVE_ID);
console.log('\n[基线] 主波次 ' + MAIN_WAVE_NO + ': recheck_start_time=' + fmtDbTime(mainWaveBefore && mainWaveBefore.recheck_start_time));
record('base-1: 主波次扫描前 recheck_start_time 为 NULL',
mainWaveBefore && mainWaveBefore.recheck_start_time === null,
'wave_id=' + MAIN_WAVE_ID);
// ============ 用例 1: 首次扫描写入(波次号路径) ============
console.log('\n--- 用例1: 首次扫描(波次号) → 写入 recheck_start_time ---');
const scan1 = await scanOnce('S1-波次号扫描', { wave_no: MAIN_WAVE_NO }, token);
console.log(' [报文]', JSON.stringify(scan1, null, 2));
await sleep(300);
const mainWaveAfter1 = await readWaveRecheck(MAIN_WAVE_ID);
console.log(' [库] recheck_start_time=' + fmtDbTime(mainWaveAfter1 && mainWaveAfter1.recheck_start_time));
{
const flagOk = scan1.flag === 'success';
const wrote = mainWaveAfter1 && mainWaveAfter1.recheck_start_time !== null;
record('case1: 波次号扫描成功且 recheck_start_time 已写入非 NULL',
flagOk && wrote,
`flag=${scan1.flag}, match_type=${scan1.matchType}, list_type=${scan1.listType}, recheck_start_time=${fmtDbTime(mainWaveAfter1 && mainWaveAfter1.recheck_start_time)}`);
record('case1-附带: 扫描返回波次视图非空',
scan1.listLen !== null && scan1.listLen > 0,
`list_len=${scan1.listLen}`);
}
// ============ 用例 2: 重复扫描不覆盖 ============
console.log('\n--- 用例2: 等待 >=2s 后重复扫描 → 值保持不变 ---');
await sleep(2500);
const scan2 = await scanOnce('S2-波次号重复扫描', { wave_no: MAIN_WAVE_NO }, token);
console.log(' [报文]', JSON.stringify(scan2, null, 2));
await sleep(300);
const mainWaveAfter2 = await readWaveRecheck(MAIN_WAVE_ID);
console.log(' [库] recheck_start_time=' + fmtDbTime(mainWaveAfter2 && mainWaveAfter2.recheck_start_time));
{
const first = mainWaveAfter1 && mainWaveAfter1.recheck_start_time;
const second = mainWaveAfter2 && mainWaveAfter2.recheck_start_time;
const unchanged = first !== null && second !== null && String(first) === String(second);
record('case2: 重复扫描后 recheck_start_time 保持不变(只记第一次)',
scan2.flag === 'success' && unchanged,
`first=${fmtDbTime(first)} second=${fmtDbTime(second)}`);
record('case2-附带: update_time 未被重复扫描刷新',
String(mainWaveAfter1.update_time) === String(mainWaveAfter2.update_time),
`after1=${mainWaveAfter1.update_time} after2=${mainWaveAfter2.update_time}`);
}
// ============ 用例 3(加分): 运单号路径扫同一波次 → 不覆盖 ============
let scan3 = null;
let mainWaveAfter3 = null;
if (waybillOk) {
console.log('\n--- 用例3(加分): 运单号扫描同一波次 → 不覆盖 ---');
scan3 = await scanOnce('S3-运单号扫描', { waybill_no: WAYBILL_NO }, token);
console.log(' [报文]', JSON.stringify(scan3, null, 2));
await sleep(300);
mainWaveAfter3 = await readWaveRecheck(MAIN_WAVE_ID);
const first = mainWaveAfter2 && mainWaveAfter2.recheck_start_time;
const third = mainWaveAfter3 && mainWaveAfter3.recheck_start_time;
const unchanged = first !== null && third !== null && String(first) === String(third);
record('case3: 运单号路径扫描后 recheck_start_time 仍保持不变',
scan3.flag === 'success' && unchanged,
`match_type=${scan3.matchType}, value=${fmtDbTime(third)}`);
} else {
record('case3: 运单号路径扫描', false, '运单号未归属测试仓库,跳过');
}
// ============ 用例 4(加分): 车号路径(散单)写入另一波次 ============
console.log('\n--- 用例4(加分): 车号扫描(散单 pick_mode=4) → 写入任务波次 ---');
const cartWaveBefore = await readWaveRecheck(CART_WAVE_ID);
console.log(' [基线] 车号波次 ' + CART_WAVE_NO + ' 扫描前 recheck_start_time=' + fmtDbTime(cartWaveBefore && cartWaveBefore.recheck_start_time));
const scan4 = await scanOnce('S4-车号扫描(散单)', { cart_code: CART_CODE_SINGLE }, token);
console.log(' [报文]', JSON.stringify(scan4, null, 2));
await sleep(300);
const cartWaveAfter = await readWaveRecheck(CART_WAVE_ID);
{
const beforeVal = cartWaveBefore && cartWaveBefore.recheck_start_time;
const afterVal = cartWaveAfter && cartWaveAfter.recheck_start_time;
const ok = scan4.flag === 'success' && afterVal !== null
&& (beforeVal === null || String(beforeVal) === String(afterVal));
const mode = beforeVal === null ? '首次扫描写入' : '重复扫描不覆盖';
record('case4: 车号(散单)扫描后任务波次 recheck_start_time 写入非 NULL(' + mode + ')',
ok,
`match_type=${scan4.matchType}, task_id=${scan4.taskId}, before=${fmtDbTime(beforeVal)}, after=${fmtDbTime(afterVal)}`);
}
// ============ 用例 5(加分): 团购任务路径(多波次各自写入) ============
console.log('\n--- 用例5(加分): 团购任务路径(车号 car0008, pick_mode=1) → 多波次各自写入 ---');
{
const [ groupWavesBefore ] = await db.query(
`SELECT tw.wave_id, tw.wave_no,
DATE_FORMAT(wb.recheck_start_time, '%Y-%m-%d %H:%i:%s.%f') AS recheck_start_time
FROM wms_wave_pick_task_wave tw
LEFT JOIN wms_wave_batch wb ON wb.wave_id = tw.wave_id AND wb.warehouse_id = tw.warehouse_id
WHERE tw.task_id = ? AND tw.warehouse_id = ?
ORDER BY tw.wave_id ASC`,
[ GROUP_TASK_ID, TEST_WAREHOUSE_ID ]
);
const allNullBefore = groupWavesBefore.every(w => w.recheck_start_time === null);
console.log(' [基线] 团购任务 ' + GROUP_TASK_ID + ' 下 ' + groupWavesBefore.length + ' 个波次扫描前均为 NULL: ' + allNullBefore);
const scan5 = await scanOnce('S5-团购车号扫描', { cart_code: GROUP_CART_CODE }, token);
console.log(' [报文]', JSON.stringify(scan5, null, 2));
await sleep(300);
const [ groupWavesAfter ] = await db.query(
`SELECT tw.wave_id, tw.wave_no,
DATE_FORMAT(wb.recheck_start_time, '%Y-%m-%d %H:%i:%s.%f') AS recheck_start_time
FROM wms_wave_pick_task_wave tw
LEFT JOIN wms_wave_batch wb ON wb.wave_id = tw.wave_id AND wb.warehouse_id = tw.warehouse_id
WHERE tw.task_id = ? AND tw.warehouse_id = ?
ORDER BY tw.wave_id ASC`,
[ GROUP_TASK_ID, TEST_WAREHOUSE_ID ]
);
const allWrote = groupWavesAfter.length > 0
&& groupWavesAfter.every(w => w.recheck_start_time !== null);
const unchangedVsBefore = allWrote && !allNullBefore
? groupWavesAfter.every(after => {
const before = groupWavesBefore.find(b => String(b.wave_id) === String(after.wave_id));
return before && String(before.recheck_start_time) === String(after.recheck_start_time);
})
: true;
const mode = allNullBefore ? '首次扫描各自写入' : '重复扫描不覆盖';
record('case5: 团购任务路径下所有波次 recheck_start_time 非 NULL(' + mode + ')',
scan5.flag === 'success' && allWrote && unchangedVsBefore,
`match_type=${scan5.matchType}, list_type=${scan5.listType}, wave_count=${groupWavesAfter.length}`);
const sample = groupWavesAfter.slice(0, 3).map(w => `wave_id=${w.wave_id}=${fmtDbTime(w.recheck_start_time)}`);
console.log(' [库样本] ' + sample.join(' | '));
}
// ============ 汇总 ============
console.log('\n========================================');
console.log('测试汇总');
console.log('========================================');
const passed = results.filter(r => r.passed).length;
const failed = results.filter(r => !r.passed).length;
console.log(' 通过: ' + passed);
console.log(' 失败: ' + failed);
console.log(' 总计: ' + results.length);
if (failed > 0) {
console.log('\n失败用例:');
for (const r of results.filter(r => !r.passed)) {
console.log(' - ' + r.testName + ': ' + r.detail);
}
}
// 最终库值快照(写入报告)
const finalMain = await readWaveRecheck(MAIN_WAVE_ID);
const finalCart = await readWaveRecheck(CART_WAVE_ID);
const reportDir = path.resolve(__dirname, '../../../../../test_reports', failed > 0 ? 'fail' : 'pass');
fs.mkdirSync(reportDir, { recursive: true });
const nowLocal = new Date();
const pad2 = n => String(n).padStart(2, '0');
const stamp = `${nowLocal.getFullYear()}${pad2(nowLocal.getMonth() + 1)}${pad2(nowLocal.getDate())}`
+ `-${pad2(nowLocal.getHours())}${pad2(nowLocal.getMinutes())}`;
const reportPath = path.join(reportDir, `${stamp}-recheck-start-time-复核开始时间HTTP验证报告.md`);
const lines = [];
lines.push('# recheck_start_time 写入行为 HTTP 验证报告');
lines.push('');
lines.push('- 测试类型: 接口验证(HTTP 真实链路)+ 只读数据库校验');
lines.push(`- 测试时间: ${new Date().toISOString()}`);
lines.push(`- 目标服务: ${BASE_URL}`);
lines.push(`- 测试仓库: ${TEST_WAREHOUSE_ID}(roleId=4 角色切换后 store_id)`);
lines.push('- 被测代码: `app/service/systemMethods/order/recheckOrder.js` — `scanOrder` / `markWaveRecheckStart`');
lines.push('');
lines.push('## 测试目标');
lines.push('');
lines.push('1. 首次扫描写入:HTTP 调用 `order.recheckOrder.scanOrder` 扫描有订单波次,验证 `wms_wave_batch.recheck_start_time` 写入非 NULL;');
lines.push('2. 重复扫描不覆盖:等待 ≥2 秒后重复扫描同一波次,验证值保持不变(只记第一次);');
lines.push('3. 多波次/其他路径(加分):车号(散单)与团购任务路径验证各波次各自写入。');
lines.push('');
lines.push('## 测试范围');
lines.push('');
lines.push('| 步骤 | 扫描方式 | 参数 | 目标波次 |');
lines.push('|------|---------|------|---------|');
lines.push(`| S1 | 波次号 | wave_no=${MAIN_WAVE_NO} | ${MAIN_WAVE_ID} (${MAIN_WAVE_NO}) |`);
lines.push(`| S2 | 波次号(重复) | wave_no=${MAIN_WAVE_NO} | 同上 |`);
lines.push(`| S3 | 运单号 | waybill_no=${WAYBILL_NO} | 同上 |`);
lines.push(`| S4 | 车号(散单) | cart_code=${CART_CODE_SINGLE} | ${CART_WAVE_ID} (${CART_WAVE_NO}) |`);
lines.push(`| S5 | 车号(团购) | cart_code=${GROUP_CART_CODE} | task ${GROUP_TASK_ID} 下全部团购波次 |`);
lines.push('');
lines.push('## 每次扫描 HTTP 报文与库值对比');
lines.push('');
lines.push('| 步骤 | 请求时间(本地) | HTTP 状态 | flag | match_type | list_type | 库 recheck_start_time | 说明 |');
lines.push('|------|---------------|----------|------|-----------|-----------|----------------------|------|');
const dumpRow = (s, waveRow, note) => {
lines.push(`| ${s.label} | ${s.beforeIso} | ${s.httpStatus} | ${s.flag} | ${s.matchType} | ${s.listType} | ${fmtDbTime(waveRow && waveRow.recheck_start_time)} | ${note} |`);
};
dumpRow(scan1, mainWaveAfter1, '首次扫描后写入');
dumpRow(scan2, mainWaveAfter2, '重复扫描后应不变');
if (waybillOk) dumpRow(scan3, mainWaveAfter3, '运单号路径应不变');
if (scan4.flag) dumpRow(scan4, cartWaveAfter, '车号散单路径写入另一波次');
lines.push('');
lines.push('### 关键库值快照');
lines.push('');
lines.push('```text');
lines.push(`主波次 ${MAIN_WAVE_NO} (${MAIN_WAVE_ID}):`);
lines.push(` 扫描前: recheck_start_time = ${fmtDbTime(mainWaveBefore && mainWaveBefore.recheck_start_time)}`);
lines.push(` S1 后 : recheck_start_time = ${fmtDbTime(mainWaveAfter1 && mainWaveAfter1.recheck_start_time)}`);
lines.push(` S2 后 : recheck_start_time = ${fmtDbTime(mainWaveAfter2 && mainWaveAfter2.recheck_start_time)}`);
lines.push(` 最终 : recheck_start_time = ${fmtDbTime(finalMain && finalMain.recheck_start_time)}`);
lines.push(` 最终 update_time = ${finalMain && finalMain.update_time}`);
lines.push('');
lines.push(`车号波次 ${CART_WAVE_NO} (${CART_WAVE_ID}):`);
lines.push(` 扫描前: recheck_start_time = ${fmtDbTime(cartWaveBefore && cartWaveBefore.recheck_start_time)}`);
lines.push(` S4 后 : recheck_start_time = ${fmtDbTime(cartWaveAfter && cartWaveAfter.recheck_start_time)}`);
lines.push(` 最终 : recheck_start_time = ${fmtDbTime(finalCart && finalCart.recheck_start_time)}`);
lines.push('```');
lines.push('');
lines.push('## 验证 SQL(只读 SELECT,未写库)');
lines.push('');
lines.push('```sql');
lines.push(`SELECT wave_id, wave_no,
DATE_FORMAT(recheck_start_time, '%Y-%m-%d %H:%i:%s.%f') AS recheck_start_time,
DATE_FORMAT(update_time, '%Y-%m-%d %H:%i:%s.%f') AS update_time
FROM wms_wave_batch
WHERE wave_id = ${MAIN_WAVE_ID} AND warehouse_id = ${TEST_WAREHOUSE_ID};`);
lines.push('```');
lines.push('');
lines.push('## 测试结果摘要');
lines.push('');
lines.push('| 结论 | 数量 |');
lines.push('|------|------|');
lines.push(`| PASS | ${passed} |`);
lines.push(`| FAIL | ${failed} |`);
lines.push(`| 总计 | ${results.length} |`);
lines.push('');
lines.push('| 用例 | 结果 | 详情 |');
lines.push('|------|------|------|');
for (const r of results) {
lines.push(`| ${r.testName} | ${r.passed ? 'PASS' : 'FAIL'} | ${r.detail} |`);
}
lines.push('');
lines.push('## 结论与建议');
lines.push('');
lines.push(`- 首次扫描写入: ${failed === 0 ? '验证通过' : '存在失败项'}。`);
lines.push('- 重复扫描不覆盖: 已验证(间隔 2.5s 后重扫,值不变,update_time 亦未刷新)。');
lines.push('- 多波次路径: 车号散单路径与团购任务路径均已验证,各波次按 IS NULL 条件各自写入。');
lines.push('- 备注: 本测试仅通过 HTTP 接口产生业务写入(scanOrder → markWaveRecheckStart),库验证全程 SELECT 只读;未对生产环境发起任何请求。');
lines.push('');
fs.writeFileSync(reportPath, lines.join('\n'), 'utf8');
console.log('\n报告已写入: ' + reportPath);
await db.end();
return { passed, failed, reportPath };
}
runTests()
.then(() => {
process.exit(0);
})
.catch(err => {
console.error('[FATAL] ' + (err && err.stack ? err.stack : err.message));
if (db) db.end().catch(() => {});
process.exit(1);
});

View File

@ -0,0 +1,86 @@
# recheck_start_time 写入行为 HTTP 验证报告
- 测试类型: 接口验证(HTTP 真实链路)+ 只读数据库校验
- 测试时间: 2026-09-07T20:20:19.227Z
- 目标服务: http://127.0.0.1:6060
- 测试仓库: 100000(roleId=4 角色切换后 store_id)
- 被测代码: `app/service/systemMethods/order/recheckOrder.js` — `scanOrder` / `markWaveRecheckStart`
## 测试目标
1. 首次扫描写入:HTTP 调用 `order.recheckOrder.scanOrder` 扫描有订单波次,验证 `wms_wave_batch.recheck_start_time` 写入非 NULL;
2. 重复扫描不覆盖:等待 ≥2 秒后重复扫描同一波次,验证值保持不变(只记第一次);
3. 多波次/其他路径(加分):车号(散单)与团购任务路径验证各波次各自写入。
## 测试范围
| 步骤 | 扫描方式 | 参数 | 目标波次 |
|------|---------|------|---------|
| S1 | 波次号 | wave_no=B2026081500099 | 1777970280349948 (B2026081500099) |
| S2 | 波次号(重复) | wave_no=B2026081500099 | 同上 |
| S3 | 运单号 | waybill_no=YT000000000276 | 同上 |
| S4 | 车号(散单) | cart_code=1919810 | 1777970280350088 (A2026090600014) |
| S5 | 车号(团购) | cart_code=car0008 | task 160 下全部团购波次 |
## 每次扫描 HTTP 报文与库值对比
| 步骤 | 请求时间(本地) | HTTP 状态 | flag | match_type | list_type | 库 recheck_start_time | 说明 |
|------|---------------|----------|------|-----------|-----------|----------------------|------|
| S1-波次号扫描 | 2026-09-07T20:20:11.155Z | 200 | success | wave | single | 2026-09-07 20:20:13.000000 | 首次扫描后写入 |
| S2-波次号重复扫描 | 2026-09-07T20:20:16.446Z | 200 | success | wave | single | 2026-09-07 20:20:13.000000 | 重复扫描后应不变 |
| S3-运单号扫描 | 2026-09-07T20:20:17.141Z | 200 | success | waybill | single | 2026-09-07 20:20:13.000000 | 运单号路径应不变 |
| S4-车号扫描(散单) | 2026-09-07T20:20:17.662Z | 200 | success | cart | single | 2026-09-07 20:16:48.000000 | 车号散单路径写入另一波次 |
### 关键库值快照
```text
主波次 B2026081500099 (1777970280349948):
扫描前: recheck_start_time = NULL
S1 后 : recheck_start_time = 2026-09-07 20:20:13.000000
S2 后 : recheck_start_time = 2026-09-07 20:20:13.000000
最终 : recheck_start_time = 2026-09-07 20:20:13.000000
最终 update_time = 2026-09-07 20:20:13.000000
车号波次 A2026090600014 (1777970280350088):
扫描前: recheck_start_time = 2026-09-07 20:16:48.000000
S4 后 : recheck_start_time = 2026-09-07 20:16:48.000000
最终 : recheck_start_time = 2026-09-07 20:16:48.000000
```
## 验证 SQL(只读 SELECT,未写库)
```sql
SELECT wave_id, wave_no,
DATE_FORMAT(recheck_start_time, '%Y-%m-%d %H:%i:%s.%f') AS recheck_start_time,
DATE_FORMAT(update_time, '%Y-%m-%d %H:%i:%s.%f') AS update_time
FROM wms_wave_batch
WHERE wave_id = 1777970280349948 AND warehouse_id = 100000;
```
## 测试结果摘要
| 结论 | 数量 |
|------|------|
| PASS | 10 |
| FAIL | 0 |
| 总计 | 10 |
| 用例 | 结果 | 详情 |
|------|------|------|
| auth-1: 登录并切换角色后 store_id=100000 | PASS | store_id=100000 |
| pre-1: 运单号 YT000000000276 归属仓库 100000 | PASS | order_id=70125,warehouse_id=100000 |
| base-1: 主波次扫描前 recheck_start_time 为 NULL | PASS | wave_id=1777970280349948 |
| case1: 波次号扫描成功且 recheck_start_time 已写入非 NULL | PASS | flag=success, match_type=wave, list_type=single, recheck_start_time=2026-09-07 20:20:13.000000 |
| case1-附带: 扫描返回波次视图非空 | PASS | list_len=500 |
| case2: 重复扫描后 recheck_start_time 保持不变(只记第一次) | PASS | first=2026-09-07 20:20:13.000000 second=2026-09-07 20:20:13.000000 |
| case2-附带: update_time 未被重复扫描刷新 | PASS | after1=2026-09-07 20:20:13.000000 after2=2026-09-07 20:20:13.000000 |
| case3: 运单号路径扫描后 recheck_start_time 仍保持不变 | PASS | match_type=waybill, value=2026-09-07 20:20:13.000000 |
| case4: 车号(散单)扫描后任务波次 recheck_start_time 写入非 NULL(重复扫描不覆盖) | PASS | match_type=cart, task_id=273, before=2026-09-07 20:16:48.000000, after=2026-09-07 20:16:48.000000 |
| case5: 团购任务路径下所有波次 recheck_start_time 非 NULL(重复扫描不覆盖) | PASS | match_type=cart, list_type=group, wave_count=20 |
## 结论与建议
- 首次扫描写入: 验证通过。
- 重复扫描不覆盖: 已验证(间隔 2.5s 后重扫,值不变,update_time 亦未刷新)。
- 多波次路径: 车号散单路径与团购任务路径均已验证,各波次按 IS NULL 条件各自写入。
- 备注: 本测试仅通过 HTTP 接口产生业务写入(scanOrder → markWaveRecheckStart),库验证全程 SELECT 只读;未对生产环境发起任何请求。