From c3f1c675922c0837b6bbe9023e369873cfa88071 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 13 Sep 2026 15:31:27 +0800 Subject: [PATCH] =?UTF-8?q?chore(script):=20=E6=B2=89=E6=B7=80=E6=B3=A2?= =?UTF-8?q?=E6=AC=A1=E6=B1=A0/=E6=8A=A5=E8=A1=A8/=E5=BA=93=E5=AD=98/?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E6=9C=AC=E5=9C=B0=E6=8E=92=E6=9F=A5=E8=84=9A?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增一批一次性排查脚本(script/tmp-*.cjs),与仓库既有 script/tmp- 约定保持一致, 覆盖波次池边界与优先级核对、库位/出库报表核对、订单状态与更新范围核验等场景 --- script/tmp-check-keep8-status.cjs | 47 ++ script/tmp-check-negative-order.cjs | 55 ++ script/tmp-check-order-table-rebuild-log.cjs | 26 + script/tmp-check-other-platform-express.cjs | 117 ++++ script/tmp-check-update-scope.cjs | 55 ++ script/tmp-check-video-record-request.cjs | 63 ++ script/tmp-check-wave-closure-log.cjs | 28 + script/tmp-check-wave-pick-debug.cjs | 65 ++ script/tmp-check-wave-pick-debug2.cjs | 85 +++ script/tmp-check-wave-strategy7-pool.cjs | 89 +++ script/tmp-check-wms-test-bootstrap.cjs | 53 ++ script/tmp-prepare-wave-pool-boundary.cjs | 95 +++ script/tmp-prepare-wave-pool-boundary3.cjs | 99 +++ script/tmp-prepare-wave-pool-today-orders.cjs | 73 ++ script/tmp-repro-first-pool-query.cjs | 78 +++ script/tmp-show-last-release.cjs | 28 + script/tmp-test-stockreport-fix-dev.cjs | 632 ++++++++++++++++++ script/tmp-trace-wave-closure-cause.cjs | 26 + script/tmp-unbind-prod-cart.cjs | 104 +++ script/tmp-verify-intercept-order-dev.cjs | 228 +++++++ script/tmp-verify-pool-after-complete.cjs | 151 +++++ script/tmp-verify-report-plan-2-preview.cjs | 77 +++ script/tmp-verify-stockreport-edge-prod.cjs | 226 +++++++ script/tmp-verify-wave-pool-boundary.cjs | 193 ++++++ script/tmp-verify-wave-pool-boundary2.cjs | 274 ++++++++ script/tmp-verify-wave-pool-boundary3.cjs | 190 ++++++ script/tmp-verify-wave-pool-priority.cjs | 170 +++++ script/tmp-watch-report-delivery.cjs | 100 +++ 28 files changed, 3427 insertions(+) create mode 100644 script/tmp-check-keep8-status.cjs create mode 100644 script/tmp-check-negative-order.cjs create mode 100644 script/tmp-check-order-table-rebuild-log.cjs create mode 100644 script/tmp-check-other-platform-express.cjs create mode 100644 script/tmp-check-update-scope.cjs create mode 100644 script/tmp-check-video-record-request.cjs create mode 100644 script/tmp-check-wave-closure-log.cjs create mode 100644 script/tmp-check-wave-pick-debug.cjs create mode 100644 script/tmp-check-wave-pick-debug2.cjs create mode 100644 script/tmp-check-wave-strategy7-pool.cjs create mode 100644 script/tmp-check-wms-test-bootstrap.cjs create mode 100644 script/tmp-prepare-wave-pool-boundary.cjs create mode 100644 script/tmp-prepare-wave-pool-boundary3.cjs create mode 100644 script/tmp-prepare-wave-pool-today-orders.cjs create mode 100644 script/tmp-repro-first-pool-query.cjs create mode 100644 script/tmp-show-last-release.cjs create mode 100644 script/tmp-test-stockreport-fix-dev.cjs create mode 100644 script/tmp-trace-wave-closure-cause.cjs create mode 100644 script/tmp-unbind-prod-cart.cjs create mode 100644 script/tmp-verify-intercept-order-dev.cjs create mode 100644 script/tmp-verify-pool-after-complete.cjs create mode 100644 script/tmp-verify-report-plan-2-preview.cjs create mode 100644 script/tmp-verify-stockreport-edge-prod.cjs create mode 100644 script/tmp-verify-wave-pool-boundary.cjs create mode 100644 script/tmp-verify-wave-pool-boundary2.cjs create mode 100644 script/tmp-verify-wave-pool-boundary3.cjs create mode 100644 script/tmp-verify-wave-pool-priority.cjs create mode 100644 script/tmp-watch-report-delivery.cjs diff --git a/script/tmp-check-keep8-status.cjs b/script/tmp-check-keep8-status.cjs new file mode 100644 index 0000000..d6610d3 --- /dev/null +++ b/script/tmp-check-keep8-status.cjs @@ -0,0 +1,47 @@ +'use strict'; + +/** + * 检查保留的 8 条今日前订单的状态字段,定位第一池查询返回 0 的原因。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ rows ] = await connection.query( + `SELECT id, create_at, items_hash, wave_id, step, post_status, storage_status, + print_status, status, outbound_status, intercept_status, lock_status + FROM wms_order_delivery_100000 + WHERE id IN (1245, 3014, 5547, 6327, 6462, 7797, 7909, 8455) + ORDER BY id ASC` + ); + console.log('===== 保留8条状态 ====='); + console.log(JSON.stringify(rows)); + + const [ hashRows ] = await connection.query( + `SELECT items_hash, COUNT(1) AS cnt, SUM(CASE WHEN wave_id = 0 THEN 1 ELSE 0 END) AS waveZero + FROM wms_order_delivery_100000 + WHERE items_hash IN (SELECT items_hash FROM wms_order_delivery_100000 WHERE id IN (1245, 3014, 5547)) + GROUP BY items_hash` + ); + console.log('===== 同结构计数 ====='); + console.log(JSON.stringify(hashRows)); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`查询失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-check-negative-order.cjs b/script/tmp-check-negative-order.cjs new file mode 100644 index 0000000..70f700c --- /dev/null +++ b/script/tmp-check-negative-order.cjs @@ -0,0 +1,55 @@ +'use strict'; + +/** + * 检查负向验证订单的实际快递字段与最新订单列表。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ recentOrders ] = await connection.query( + `SELECT id, sys_platform_code, logistics_code, sys_logistics_code, + post_status, storage_status, step, wave_id + FROM wms_order_delivery_100000 + WHERE id >= 122595 + ORDER BY id ASC + LIMIT 20` + ); + console.log('===== 最近订单 ====='); + console.log(JSON.stringify(recentOrders)); + + const [ expressRows ] = await connection.query( + `SELECT order_id, waybill_code, logistics_code, logistics_name, platform_code, status + FROM wms_order_express + WHERE order_id >= 122595 + ORDER BY id DESC + LIMIT 20` + ); + console.log('===== 最近运单 ====='); + console.log(JSON.stringify(expressRows)); + + const [ policyRow ] = await connection.query( + `SELECT policy_config FROM wms_store_warehouse WHERE id = 100000` + ); + console.log('===== 合约100000 policy_config ====='); + console.log(JSON.stringify(policyRow)); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`查询失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-check-order-table-rebuild-log.cjs b/script/tmp-check-order-table-rebuild-log.cjs new file mode 100644 index 0000000..911b0d4 --- /dev/null +++ b/script/tmp-check-order-table-rebuild-log.cjs @@ -0,0 +1,26 @@ +'use strict'; + +/** + * 只读排查脚本:抓取 2026-09-12 16:25:0x ~ 16:25:4x(CST)窗口内与订单分表结构/重建相关的日志。 + * 仅执行 grep 等只读命令,不做任何写入或清理。 + */ + +const { loadDeployConfig, runSsh } = require('./deploy-lib.cjs'); + +function buildRemoteScript() { + return [ + 'set -uo pipefail', + 'D=/root/logs/wms', + 'echo "===ALERT_WINDOW==="', + 'for f in "$D/wms-web.log.2026-09-12" "$D/common-error.log.2026-09-12" "$D/wms-web.log.2026-09-13"; do', + ' [ -f "$f" ] || continue', + ' echo "--- $f ---"', + ' grep -a "2026-09-12 16:2[4-6]:" "$f" 2>/dev/null | grep -aiE "alter|backup|重建|schema|watermark|自增|order_delivery" | head -20 || true', + 'done', + 'echo "===FACTORY_WARNINGS==="', + 'grep -ah "order_delivery_factory\\|订单工厂\\|alterManagedTableSchema\\|ensureAutoIncrementWatermark" "$D/wms-web.log.2026-09-12" 2>/dev/null | tail -25 || true', + ].join('\n'); +} + +const config = loadDeployConfig('production'); +console.log(runSsh(config, buildRemoteScript(), { stdio: 'pipe' })); diff --git a/script/tmp-check-other-platform-express.cjs b/script/tmp-check-other-platform-express.cjs new file mode 100644 index 0000000..0d207c9 --- /dev/null +++ b/script/tmp-check-other-platform-express.cjs @@ -0,0 +1,117 @@ +'use strict'; + +/** + * 检查本地开发库中 OTHER 平台/快递相关数据现状。 + * + * 用于定位「其他平台(OTHER)/其他快递(OTHER)分配不了运单号」的数据缺失点: + * - wms_platform 是否已有 OTHER 平台记录 + * - wms_express 是否已有 OTHER 快递记录 + * - wms_print_platform 是否已有 platform_code=OTHER 记录 + * - wms_express_interface 是否已有 platform_code=OTHER 的接口配置 + */ + +const mysql = require('mysql2/promise'); + +/** + * 查询本地开发库并输出结果。 + * + * @return {Promise} + */ +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ platformRows ] = await connection.query( + `SELECT code, name, print_platform_id FROM wms_platform ORDER BY code ASC` + ); + console.log('===== wms_platform ====='); + platformRows.forEach(row => { + console.log(`code=${row.code}, name=${row.name}, print_platform_id=${row.print_platform_id}`); + }); + + const [ expressOtherRows ] = await connection.query( + `SELECT code, name FROM wms_express WHERE UPPER(code) = 'OTHER'` + ); + console.log('===== wms_express code=OTHER ====='); + console.log(JSON.stringify(expressOtherRows)); + + const [ printPlatformRows ] = await connection.query( + `SELECT * FROM wms_print_platform WHERE id = 9 OR UPPER(platform_code) = 'OTHER' OR UPPER(request_platform_code) = 'OTHER'` + ); + console.log('===== wms_print_platform id=9 / OTHER ====='); + console.log(JSON.stringify(printPlatformRows)); + + const [ expressInterfaceRows ] = await connection.query( + `SELECT id, warehouse_id, platform_code, express_code, sys_express_code, is_enabled + FROM wms_express_interface + WHERE UPPER(platform_code) = 'OTHER' OR UPPER(express_code) = 'OTHER' OR UPPER(sys_express_code) = 'OTHER' + LIMIT 20` + ); + console.log('===== wms_express_interface 含 OTHER ====='); + console.log(JSON.stringify(expressInterfaceRows)); + + const [ allInterfaceRows ] = await connection.query( + `SELECT warehouse_id, platform_code, COUNT(1) AS cnt + FROM wms_express_interface + GROUP BY warehouse_id, platform_code + ORDER BY warehouse_id, platform_code` + ); + console.log('===== wms_express_interface 按仓库+平台统计 ====='); + console.log(JSON.stringify(allInterfaceRows)); + + const [ contractRows ] = await connection.query( + `SELECT id, store_id, warehouse_id, policy_config + FROM wms_store_warehouse + ORDER BY id DESC + LIMIT 10` + ); + console.log('===== wms_store_warehouse 最近合约 policy_config ====='); + contractRows.forEach(row => { + let policyText = String(row.policy_config || ''); + if (row.policy_config && typeof row.policy_config === 'object') { + policyText = JSON.stringify(row.policy_config); + } + console.log(`id=${row.id}, store=${row.store_id}, warehouse=${row.warehouse_id}, policy=${policyText.slice(0, 400)}`); + }); + + const [ tableRows ] = await connection.query( + `SHOW TABLES` + ); + console.log('===== 全部表名 ====='); + const allTableNames = tableRows.map(row => Object.values(row)[0]); + console.log(allTableNames.filter(name => /order|delivery/i.test(name)).join('\n')); + + const [ orderOtherRows ] = await connection.query( + `SELECT id, sys_platform_code, logistics_code, post_status, step, status, create_at + FROM wms_order_delivery_100000 + WHERE sys_platform_code = 'OTHER' OR logistics_code = 'OTHER' + ORDER BY id DESC + LIMIT 20` + ); + console.log('===== 仓库100000 OTHER 订单 ====='); + console.log(JSON.stringify(orderOtherRows)); + + const [ failLogRows ] = await connection.query( + `SELECT business_id, extras, create_at + FROM wms_operation_log + WHERE operation_code = 'ORDER_EXPRESS_ALLOCATE_FAILED' + ORDER BY id DESC + LIMIT 10` + ); + console.log('===== 最近快递分配失败日志 ====='); + console.log(JSON.stringify(failLogRows)); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`查询失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-check-update-scope.cjs b/script/tmp-check-update-scope.cjs new file mode 100644 index 0000000..dd20bc6 --- /dev/null +++ b/script/tmp-check-update-scope.cjs @@ -0,0 +1,55 @@ +'use strict'; + +/** + * 抽查 UPDATE 影响范围。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ sample ] = await connection.query( + `SELECT id, create_at + FROM wms_order_delivery_100000 + WHERE id BETWEEN 1591 AND 1660 + ORDER BY id ASC + LIMIT 15` + ); + console.log('===== 1591-1660 区间 ====='); + console.log(JSON.stringify(sample)); + + const [ todayCount ] = await connection.query( + `SELECT COUNT(1) AS cnt + FROM wms_order_delivery_100000 + WHERE create_at >= '2026-09-05 16:00:00'` + ); + console.log('===== 全表今天订单数 ====='); + console.log(JSON.stringify(todayCount)); + + const [ keepRows ] = await connection.query( + `SELECT id, create_at + FROM wms_order_delivery_100000 + WHERE id IN (1245, 3014, 5547, 6327, 6462, 7797, 7909, 8455) + ORDER BY id ASC` + ); + console.log('===== 保留8条 ====='); + console.log(JSON.stringify(keepRows)); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`查询失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-check-video-record-request.cjs b/script/tmp-check-video-record-request.cjs new file mode 100644 index 0000000..102a146 --- /dev/null +++ b/script/tmp-check-video-record-request.cjs @@ -0,0 +1,63 @@ +'use strict'; + +/** + * 临时校验:video_record_request 模型定义与 wms_video_record_request 表结构是否一致。 + * 仅只读(describeTable + findAll limit 1),默认连本地开发库: + * Remove-Item Env:\NODE_ENV; $env:WMS_DB_TARGET='local'; node script/tmp-check-video-record-request.cjs + */ + +const SequelizeLib = require('sequelize'); +const dbConfig = require('../database/config'); + +/** + * 主流程:加载模型定义并与实际表结构比对。 + * @return {Promise} 无返回值。 + */ +async function main() { + const config = dbConfig.production; + console.log(`[check] target=${config.host}:${config.port}/${config.database} (${(dbConfig.dbTarget || {}).source})`); + + const sequelize = new SequelizeLib(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: config.dialect || 'mysql', + logging: false, + }); + + const app = { + Sequelize: SequelizeLib, + model: { define: (name, attrs, opts) => sequelize.define(name, attrs, opts) }, + }; + + try { + const model = require('../app/model/video_record_request')(app); + const tableInfo = await sequelize.getQueryInterface().describeTable('wms_video_record_request'); + const tableCols = Object.keys(tableInfo); + const modelCols = Object.keys(model.rawAttributes); + + const missingInModel = tableCols.filter(col => !modelCols.includes(col)); + const missingInTable = modelCols.filter(col => !tableCols.includes(col)); + + console.log('[check] modelCols =', modelCols.join(',')); + console.log('[check] missingInModel =', JSON.stringify(missingInModel)); + console.log('[check] missingInTable =', JSON.stringify(missingInTable)); + + const rows = await model.findAll({ limit: 1, raw: true }); + console.log('[check] findAll ok, rows =', rows.length); + + // 状态机枚举可达性(只读:构造 where 不执行写入) + const counting = await model.count({ where: { status: 'pending' } }); + console.log('[check] count(status=pending) =', counting); + + console.log(missingInModel.length === 0 && missingInTable.length === 0 + ? '[check] OK: 模型与表结构一致' + : '[check] MISMATCH: 存在差异'); + } finally { + await sequelize.close(); + } +} + +main().catch(err => { + console.error('[check] FAILED:', err.message); + process.exitCode = 1; +}); diff --git a/script/tmp-check-wave-closure-log.cjs b/script/tmp-check-wave-closure-log.cjs new file mode 100644 index 0000000..a03902d --- /dev/null +++ b/script/tmp-check-wave-closure-log.cjs @@ -0,0 +1,28 @@ +'use strict'; + +/** + * 只读排查脚本:抓取生产环境 2026-09-12 08:2x 波次自动终结(wave-batch-closure)日志。 + * + * 目的:确认 08:25:33 那一轮 candidate/closed 数量,判断是"整表读空"还是"仅这 6 个波次读空"。 + * 仅执行 grep / zcat 等只读命令,不做任何写入或清理。 + */ + +const { loadDeployConfig, runSsh } = require('./deploy-lib.cjs'); + +function buildRemoteScript() { + return [ + 'set -uo pipefail', + 'D=/root/logs/wms', + 'echo "===FILES==="', + 'ls -lh "$D" 2>&1 | head -12 || true', + 'echo "===NONZERO_CLOSED_0912==="', + 'grep -ah "本轮完成 closed=" "$D/wms-web.log.2026-09-12" 2>/dev/null | grep -av "closed=0 " | tail -20 || true', + 'echo "===CLOSURE_DETAIL_0912==="', + 'grep -ah "波次终结结果" "$D/wms-web.log.2026-09-12" 2>/dev/null | tail -20 || true', + 'echo "===WINDOW_0825==="', + 'grep -ah "2026-09-12 08:2" "$D/wms-web.log.2026-09-12" 2>/dev/null | grep -a "本轮完成" | tail -10 || true', + ].join('\n'); +} + +const config = loadDeployConfig('production'); +console.log(runSsh(config, buildRemoteScript(), { stdio: 'pipe' })); diff --git a/script/tmp-check-wave-pick-debug.cjs b/script/tmp-check-wave-pick-debug.cjs new file mode 100644 index 0000000..cdd1e5d --- /dev/null +++ b/script/tmp-check-wave-pick-debug.cjs @@ -0,0 +1,65 @@ +'use strict'; + +/** + * 检查联调订单实际字段与任务状态。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ orderRows ] = await connection.query( + `SELECT id, sys_platform_code, logistics_code, sys_logistics_code, + post_status, storage_status, step, status, wave_id, wave_scan_result, + wave_strategy_version, items_hash + FROM wms_order_delivery_100000 + WHERE id IN (122546, 122547, 122548) + ORDER BY id ASC` + ); + console.log('===== 联调订单字段 ====='); + console.log(JSON.stringify(orderRows)); + + const [ taskRows ] = await connection.query( + `SELECT id, task_no, status, pick_mode, wave_id, pick_user_id + FROM wms_wave_pick_task + WHERE warehouse_id = 100000 AND status IN (0, 1) + ORDER BY id DESC + LIMIT 5` + ); + console.log('===== 活跃拣货任务 ====='); + console.log(JSON.stringify(taskRows)); + + const [ strategyRows ] = await connection.query( + `SELECT id, strategy_name, strategy_type, batch_mode, min_same_structure, status + FROM wms_wave_strategy + WHERE warehouse_id = 100000 + ORDER BY id DESC + LIMIT 5` + ); + console.log('===== 最近策略 ====='); + console.log(JSON.stringify(strategyRows)); + + const [ versionRows ] = await connection.query( + `SELECT subject_config FROM wms_store_warehouse WHERE id = 100000` + ); + console.log('===== 仓库 subject_config(版本) ====='); + console.log(JSON.stringify(versionRows)); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`查询失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-check-wave-pick-debug2.cjs b/script/tmp-check-wave-pick-debug2.cjs new file mode 100644 index 0000000..6c3bb4c --- /dev/null +++ b/script/tmp-check-wave-pick-debug2.cjs @@ -0,0 +1,85 @@ +'use strict'; + +/** + * 排查联调问题: + * 1. 历史成功订单(122442)使用的商品 stock_id(可用于选一个能完整走通的商品); + * 2. 订单 122546 储位分配失败原因; + * 3. 商品 159063 的库位库存分布。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ historyItems ] = await connection.query( + `SELECT order_id, item_id, stock_id, item_name, plan_qty + FROM wms_order_items_100000 + WHERE order_id IN (122442, 122546) + ORDER BY order_id ASC` + ); + console.log('===== 历史成功订单/联调订单明细 ====='); + console.log(JSON.stringify(historyItems)); + + const [ logColumns ] = await connection.query( + `SHOW COLUMNS FROM wms_operation_log` + ); + console.log('===== wms_operation_log 列 ====='); + console.log(JSON.stringify(logColumns.map(item => item.Field))); + + const [ failLogs ] = await connection.query( + `SELECT business_id, operation_code, message + FROM wms_operation_log + WHERE business_id IN ('122546', '122547') AND operation_code LIKE '%STORAGE%' + ORDER BY id DESC + LIMIT 10` + ); + console.log('===== 储位分配相关日志 ====='); + console.log(JSON.stringify(failLogs)); + + const [ stockWarehouseRows ] = await connection.query( + `SELECT id, store_id, quantity, locked_quantity, prohibited_id, is_valid, deleted_at + FROM wms_stock_warehouse WHERE id = 101397` + ); + console.log('===== 商品101397 主表 ====='); + console.log(JSON.stringify(stockWarehouseRows)); + + const [ stockLocationRows ] = await connection.query( + `SELECT id, stock_id, location_id, qty + FROM wms_stock_location WHERE stock_id = 101397 LIMIT 10` + ); + console.log('===== 商品101397 库位库存 ====='); + console.log(JSON.stringify(stockLocationRows)); + + const [ storageAllocRows ] = await connection.query( + `SELECT * FROM wms_order_storage_allocation + WHERE order_id IN (122546, 122547) + ORDER BY id DESC + LIMIT 10` + ); + console.log('===== 122546/122547 储位分配记录 ====='); + console.log(JSON.stringify(storageAllocRows)); + + const [ storageTables ] = await connection.query( + `SHOW TABLES LIKE '%storage%'` + ); + console.log('===== storage 相关表 ====='); + console.log(JSON.stringify(storageTables)); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`查询失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-check-wave-strategy7-pool.cjs b/script/tmp-check-wave-strategy7-pool.cjs new file mode 100644 index 0000000..1551b4d --- /dev/null +++ b/script/tmp-check-wave-strategy7-pool.cjs @@ -0,0 +1,89 @@ +'use strict'; + +/** + * 统计策略 7(边拣边分)候选订单池: + * 命中匹配表、未分配波次、状态满足抓取口径的订单,按同结构与创建时间分布统计。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ rows ] = await connection.query( + `SELECT + o.id, + o.items_hash, + o.create_at, + o.step, + o.post_status, + o.storage_status, + o.print_status, + o.status, + o.outbound_status, + o.intercept_status, + o.lock_status, + o.wave_id + FROM wms_order_wave_strategy_match m + INNER JOIN wms_order_delivery_100000 o + ON o.id = m.order_id + WHERE m.warehouse_id = 100000 + AND m.strategy_id = 7 + ORDER BY o.id DESC` + ); + console.log(`===== 命中策略7订单总数: ${rows.length} =====`); + + const todayStartUtc = Date.UTC(2026, 8, 5, 16, 0, 0); // 2026-09-06 00:00 +08:00 + const beforeToday = rows.filter(row => row.create_at && new Date(row.create_at).getTime() < todayStartUtc); + const today = rows.filter(row => row.create_at && new Date(row.create_at).getTime() >= todayStartUtc); + console.log(`今日前订单数: ${beforeToday.length}`); + console.log(`今日订单数: ${today.length}`); + + const eligible = rows.filter(row => + Number(row.wave_id) === 0 + && Number(row.step) !== 0 + && String(row.post_status) === 'fin' + && String(row.storage_status) === 'fin' + && String(row.print_status) !== 'fin' + && String(row.status) !== 'cancel' + && String(row.outbound_status) !== 'padding' + && String(row.intercept_status) === 'none' + && String(row.lock_status) === 'none' + ); + console.log(`===== 满足抓取口径订单数: ${eligible.length} =====`); + const eligibleBeforeToday = eligible.filter(row => new Date(row.create_at).getTime() < todayStartUtc); + const eligibleToday = eligible.filter(row => new Date(row.create_at).getTime() >= todayStartUtc); + console.log(` 其中今日前: ${eligibleBeforeToday.length}`); + console.log(` 其中今天: ${eligibleToday.length}`); + + const hashGroups = new Map(); + for (const row of eligible) { + const key = String(row.items_hash || '').trim(); + if (!key) continue; + if (!hashGroups.has(key)) hashGroups.set(key, []); + hashGroups.get(key).push(row); + } + console.log('===== 同结构分组(仅数量>=2) ====='); + for (const [ key, list ] of hashGroups.entries()) { + if (list.length < 2) continue; + const beforeCount = list.filter(row => new Date(row.create_at).getTime() < todayStartUtc).length; + console.log(`hash=${key.slice(0, 12)} 总数=${list.length} 今日前=${beforeCount} 今天=${list.length - beforeCount}`); + } + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`查询失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-check-wms-test-bootstrap.cjs b/script/tmp-check-wms-test-bootstrap.cjs new file mode 100644 index 0000000..8747ce5 --- /dev/null +++ b/script/tmp-check-wms-test-bootstrap.cjs @@ -0,0 +1,53 @@ +'use strict'; + +/** + * 查询联调所需测试数据:仓库 100000 下的货主合约与可用商品库存。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ contractRows ] = await connection.query( + `SELECT id, store_id, warehouse_id, auth_status + FROM wms_store_warehouse + WHERE warehouse_id = 100000 AND auth_status = 2 + ORDER BY id DESC + LIMIT 20` + ); + console.log('===== 仓库100000 已通过合约(auth_status=2) ====='); + console.log(JSON.stringify(contractRows)); + + const [ columns ] = await connection.query( + `SHOW COLUMNS FROM wms_stock_warehouse` + ); + console.log('===== wms_stock_warehouse 列 ====='); + console.log(JSON.stringify(columns.map(item => item.Field))); + + const [ stockRows ] = await connection.query( + `SELECT * FROM wms_stock_warehouse + WHERE warehouse_id = 100000 + ORDER BY id DESC + LIMIT 10` + ); + console.log('===== 仓库100000 库存示例 ====='); + console.log(JSON.stringify(stockRows)); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`查询失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-prepare-wave-pool-boundary.cjs b/script/tmp-prepare-wave-pool-boundary.cjs new file mode 100644 index 0000000..4da6faf --- /dev/null +++ b/script/tmp-prepare-wave-pool-boundary.cjs @@ -0,0 +1,95 @@ +'use strict'; + +/** + * 边界场景数据准备:让策略 7 的第一订单池(今日前)仅剩 8 条同结构订单, + * 其余满足抓取口径的候选订单全部改为今天,用于验证: + * - 第一池不足 20 时不会用第二池填充; + * - 第一池抓取完毕后,第二轮才开始抓第二池(今天订单)并抓满 20。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +const TODAY_TIME = '2026-09-06 11:00:00'; +const KEEP_COUNT = 8; + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ rows ] = await connection.query( + `SELECT o.id, o.create_at, o.items_hash + FROM wms_order_wave_strategy_match m + INNER JOIN wms_order_delivery_100000 o + ON o.id = m.order_id + WHERE m.warehouse_id = 100000 + AND m.strategy_id = 7 + 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' + ORDER BY o.id ASC` + ); + console.log(`满足口径且未分配波次的候选总数: ${rows.length}`); + + const todayStart = Date.UTC(2026, 8, 5, 16, 0, 0); // 2026-09-06 00:00 +08:00 + const beforeToday = rows.filter(row => new Date(row.create_at).getTime() < todayStart); + console.log(`其中今日前候选: ${beforeToday.length}`); + + // 选择同一 hash 的 8 条今日前订单保留 + const hashGroups = new Map(); + for (const row of beforeToday) { + const key = String(row.items_hash || '').trim(); + if (!key) continue; + if (!hashGroups.has(key)) hashGroups.set(key, []); + hashGroups.get(key).push(row); + } + let keepGroup = null; + for (const list of hashGroups.values()) { + if (list.length >= KEEP_COUNT) { + keepGroup = list; + break; + } + } + if (!keepGroup) { + console.log('未找到同结构数量>=8的今日前分组,改用任意8条'); + keepGroup = beforeToday.slice(0, KEEP_COUNT); + } + const keepIds = keepGroup.slice(0, KEEP_COUNT).map(row => Number(row.id)); + const keepSet = new Set(keepIds); + const moveIds = rows.map(row => Number(row.id)).filter(id => !keepSet.has(id)); + + console.log(`保留为今日前的订单(将不足20): [${keepIds.join(', ')}]`); + console.log(`改为今天的订单数: ${moveIds.length}`); + + if (moveIds.length > 0) { + const [ result ] = await connection.query( + `UPDATE wms_order_delivery_100000 + SET create_at = ? + WHERE id IN (?)`, + [ TODAY_TIME, moveIds ] + ); + console.log(`已更新行数: ${result.affectedRows}`); + } + console.log('数据准备完成'); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`执行失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-prepare-wave-pool-boundary3.cjs b/script/tmp-prepare-wave-pool-boundary3.cjs new file mode 100644 index 0000000..882d393 --- /dev/null +++ b/script/tmp-prepare-wave-pool-boundary3.cjs @@ -0,0 +1,99 @@ +'use strict'; + +/** + * 边界场景数据准备(v3): + * 当前今日前候选只有 ac1b 组 8 条(同结构总数 14,超 max_same_structure=12,不入选)。 + * 改为:从同结构总数 2~12 的组中选 8 条改为今日前,其余候选(含 ac1b 组 8 条)全部改为今天。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +const TODAY_TIME = '2026-09-06 12:30:00'; +const BEFORE_TODAY = '2026-01-13 07:26:07'; +const KEEP_COUNT = 8; + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ rows ] = await connection.query( + `SELECT o.id, o.items_hash + FROM wms_order_wave_strategy_match m + INNER JOIN wms_order_delivery_100000 o + ON o.id = m.order_id + WHERE m.warehouse_id = 100000 + AND m.strategy_id = 7 + 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' + ORDER BY o.id ASC` + ); + console.log(`候选总数: ${rows.length}`); + + const hashGroups = new Map(); + for (const row of rows) { + const key = String(row.items_hash || '').trim(); + if (!key) continue; + if (!hashGroups.has(key)) hashGroups.set(key, []); + hashGroups.get(key).push(row); + } + + let picked = null; + for (const [ key, list ] of hashGroups.entries()) { + if (list.length >= KEEP_COUNT && list.length <= 12) { + picked = { key, list }; + break; + } + } + if (!picked) { + // 选数量最小的 8~12 组,找不到则选任意 >=8 组 + for (const [ key, list ] of hashGroups.entries()) { + if (list.length >= KEEP_COUNT) { + picked = { key, list }; + break; + } + } + } + if (!picked) { + throw new Error('未找到可用的同结构分组'); + } + + const keepIds = picked.list.slice(0, KEEP_COUNT).map(row => Number(row.id)); + const keepSet = new Set(keepIds); + console.log(`选中分组: hash=${picked.key.slice(0, 12)} 总数=${picked.list.length}`); + console.log(`保留为今日前的订单: [${keepIds.join(', ')}]`); + + const allIds = rows.map(row => Number(row.id)); + await connection.query( + `UPDATE wms_order_delivery_100000 SET create_at = ? WHERE id IN (?)`, + [ TODAY_TIME, allIds ] + ); + await connection.query( + `UPDATE wms_order_delivery_100000 SET create_at = ? WHERE id IN (?)`, + [ BEFORE_TODAY, keepIds ] + ); + console.log(`其余 ${allIds.length - keepIds.length} 条已改为今天 ${TODAY_TIME}`); + console.log('数据准备完成'); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`执行失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-prepare-wave-pool-today-orders.cjs b/script/tmp-prepare-wave-pool-today-orders.cjs new file mode 100644 index 0000000..3c4cbc0 --- /dev/null +++ b/script/tmp-prepare-wave-pool-today-orders.cjs @@ -0,0 +1,73 @@ +'use strict'; + +/** + * 订单池分割测试数据准备: + * 将策略 7 候选订单中按 id 升序前 10 条的 create_at 改为今天(2026-09-06 09:00:00), + * 使候选池同时存在「今日前订单」与「今天订单」。 + * + * 选单口径与抓取候选一致(wave_id=0 且状态满足抓取条件)。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +const TARGET_DATE = '2026-09-06 09:00:00'; + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const [ rows ] = await connection.query( + `SELECT o.id, o.create_at, o.items_hash + FROM wms_order_wave_strategy_match m + INNER JOIN wms_order_delivery_100000 o + ON o.id = m.order_id + WHERE m.warehouse_id = 100000 + AND m.strategy_id = 7 + 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' + ORDER BY o.id ASC + LIMIT 10` + ); + console.log('===== 将被改为今天的订单(原 create_at) ====='); + rows.forEach(row => { + console.log(`id=${row.id}, 原create_at=${row.create_at && row.create_at.toISOString ? row.create_at.toISOString() : row.create_at}, hash=${String(row.items_hash || '').slice(0, 12)}`); + }); + + const ids = rows.map(row => Number(row.id)); + if (ids.length === 0) { + console.log('无候选订单可修改'); + return; + } + + const [ result ] = await connection.query( + `UPDATE wms_order_delivery_100000 + SET create_at = ? + WHERE id IN (?)`, + [ TARGET_DATE, ids ] + ); + console.log(`===== 已更新行数: ${result.affectedRows} =====`); + console.log(`被修改订单ID: [${ids.join(', ')}]`); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`执行失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-repro-first-pool-query.cjs b/script/tmp-repro-first-pool-query.cjs new file mode 100644 index 0000000..b8e4125 --- /dev/null +++ b/script/tmp-repro-first-pool-query.cjs @@ -0,0 +1,78 @@ +'use strict'; + +/** + * 复现 getWaveStrategyFetchCandidateOrders 的第一池查询, + * 验证 createdBefore='2026-09-06 00:00:00' 时 8 条今日前订单是否被命中。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +async function main() { + const connection = await mysql.createConnection({ + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + }); + + try { + const warehouseId = 100000; + const createdBefore = new Date(2026, 8, 6, 0, 0, 0); + const minSameStructure = 2; + const maxSameStructure = 999; + const [ rows ] = await connection.query( + `SELECT o.id, o.items_hash + FROM wms_order_wave_strategy_match m + INNER JOIN wms_order_delivery_100000 o + ON o.id = m.order_id + AND o.warehouse_id = ? + 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' + AND (? IS NULL OR o.create_at < ?) + INNER JOIN ( + SELECT + src.items_hash AS structure_key, + COUNT(1) AS same_structure_count + FROM wms_order_delivery_100000 src + WHERE src.warehouse_id = ? + 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 + ) same_structure + ON same_structure.structure_key = o.items_hash + WHERE m.warehouse_id = ? + AND m.strategy_id = 7 + AND same_structure.same_structure_count >= ? + AND (? IS NULL OR same_structure.same_structure_count <= ?) + ORDER BY o.id ASC`, + [ warehouseId, createdBefore, createdBefore, warehouseId, warehouseId, minSameStructure, maxSameStructure, maxSameStructure ] + ); + + console.log(`第一池(createdBefore=2026-09-06 00:00)命中数: ${rows.length}`); + console.log(JSON.stringify(rows.slice(0, 30))); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`查询失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-show-last-release.cjs b/script/tmp-show-last-release.cjs new file mode 100644 index 0000000..9ec3480 --- /dev/null +++ b/script/tmp-show-last-release.cjs @@ -0,0 +1,28 @@ +'use strict'; + +/** + * 只读脚本:读取生产环境最后一次发布信息(不触发任何发布/回退动作)。 + * 仅执行 cat / tail / ls / stat 等只读命令。 + */ + +const { loadDeployConfig, runSsh } = require('./deploy-lib.cjs'); + +function buildRemoteScript() { + return [ + 'set -uo pipefail', + 'ROOT=/www/wwwroot/qimen', + 'echo "===QIMEN_PROC_START==="', + 'ps -eo pid,lstart,cmd 2>/dev/null | grep "/www/wwwroot/qimen" | grep -v grep | head -6 || true', + 'echo "===V2_APP_NEWEST_FILES==="', + 'find "$ROOT/v2/app" "$ROOT/v2/methods" "$ROOT/v2/script" -type f -printf "%TY-%Tm-%Td %TH:%TM %p\\n" 2>/dev/null | sort | tail -12 || true', + 'echo "===V2_CONFIG_NEWEST==="', + 'find "$ROOT/v2/config" -maxdepth 1 -type f -printf "%TY-%Tm-%Td %TH:%TM %p\\n" 2>/dev/null | sort | tail -6 || true', + 'echo "===V2_APP_DIR_LS==="', + 'ls -lt --time-style=long-iso "$ROOT/v2/app" 2>/dev/null | head -6', + 'echo "===INCOMING_ALL==="', + 'ls -lt --time-style=long-iso "$ROOT/.deploy/incoming" 2>/dev/null || echo MISSING', + ].join('\n'); +} + +const config = loadDeployConfig('production'); +console.log(runSsh(config, buildRemoteScript(), { stdio: 'pipe' })); diff --git a/script/tmp-test-stockreport-fix-dev.cjs b/script/tmp-test-stockreport-fix-dev.cjs new file mode 100644 index 0000000..8d4c5d8 --- /dev/null +++ b/script/tmp-test-stockreport-fix-dev.cjs @@ -0,0 +1,632 @@ +/** + * 只读校验脚本(开发库 127.0.0.1:3307/wms,仅 SELECT): + * 验证 stock.report 修复后的 intervalEdge / preStart 快照 SQL 正确性。 + * + * 场景1:货主口径(wms_stock_transaction, store_id=1000000)全量恒等式 + oracle 对照 + * 场景3:库位口径(wms_storage_transaction, store_id=1000000)全量恒等式 + oracle 对照 + * 场景4:start_time 边界(preStart 快照,含同秒多行 tie-break)+ 带 start_time 的窗口恒等式 + * + * 无任何写操作、无清理逻辑。 + * 用法: + * Remove-Item Env:\NODE_ENV -ErrorAction SilentlyContinue + * node script/tmp-test-stockreport-fix-dev.cjs + */ + +'use strict'; + +const path = require('path'); +const { createRequire } = require('module'); + +const projectRoot = path.resolve(__dirname, '..'); +const projectRequire = createRequire(path.join(projectRoot, 'package.json')); +const mysql = projectRequire('mysql2/promise'); + +function loadDevDbConfig() { + const configPath = path.join(projectRoot, 'config', 'config.local.js'); + const factory = require(configPath); + const config = typeof factory === 'function' + ? factory({ name: 'tmp-test-stockreport-fix', baseDir: projectRoot }) + : factory; + const client = config && config.mysql && config.mysql.clients && config.mysql.clients.wms; + if (client && client.host) { + return { + host: client.host, + port: Number(client.port), + user: client.user, + password: client.password, + database: client.database, + }; + } + throw new Error('无法解析开发库配置 config.local.js(mysql.clients.wms)'); +} + +const STORE_ID = 1000000; + +/** 汇总通过/失败计数 */ +const counters = { pass: 0, fail: 0 }; +function verdict(name, pass, detail) { + if (pass) { + counters.pass += 1; + console.log(`PASS | ${name}${detail ? ` | ${detail}` : ''}`); + } else { + counters.fail += 1; + console.log(`FAIL | ${name}${detail ? ` | ${detail}` : ''}`); + } + return pass; +} + +function num(value) { + if (value === null || value === undefined) { + return null; + } + const n = Number(value); + return Number.isFinite(n) ? n : null; +} + +function dimKey(row, isBySpace) { + const spaceId = isBySpace ? (num(row.space_id) || 0) : 0; + return isBySpace + ? `${row.stock_id}_${spaceId}_${row.store_id}` + : `${row.stock_id}_${row.store_id}`; +} + +/** + * 用全量流水在 Node 侧推演 oracle 快照: + * 首条(created_at, id 最小)的 before_quantity、末条(created_at, id 最大)的 after_quantity。 + * ct 为 DATE_FORMAT 字符串('%Y-%m-%d %H:%i:%s.%f'),字典序即时间序。 + * @param {Object[]} rows 全量流水行 + * @param {boolean} isBySpace 是否按库位维度 + * @return {Map} oracle 映射 + */ +function buildFullOracle(rows, isBySpace) { + const map = new Map(); + for (const row of rows) { + const key = dimKey(row, isBySpace); + const id = num(row.id); + const ct = String(row.ct); + if (!map.has(key)) { + map.set(key, { + first: { ct, id, before: num(row.before_quantity) }, + last: { ct, id, after: num(row.after_quantity) }, + }); + continue; + } + const entry = map.get(key); + if (ct < entry.first.ct || (ct === entry.first.ct && id < entry.first.id)) { + entry.first = { ct, id, before: num(row.before_quantity) }; + } + if (ct > entry.last.ct || (ct === entry.last.ct && id > entry.last.id)) { + entry.last = { ct, id, after: num(row.after_quantity) }; + } + } + return map; +} + +/** + * 拉取指定维度全量流水明细(含格式化时间字符串)。 + * @param {Object} conn mysql2 连接 + * @param {string} tableName 表名 + * @param {boolean} isBySpace 是否按库位维度 + * @param {number} primaryVal 主维度值(store_id) + * @return {Promise} 流水明细列表 + */ +async function fetchAllRows(conn, tableName, isBySpace, primaryVal) { + const spaceSelect = isBySpace ? 'COALESCE(space_id, 0) AS space_id, ' : '0 AS space_id, '; + const [ rows ] = await conn.query( + `SELECT id, stock_id, ${spaceSelect}store_id, + transaction_type, quantity, before_quantity, after_quantity, + DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s.%f') AS ct + FROM ${tableName} + WHERE store_id = ?`, + [ primaryVal ] + ); + return rows; +} + +/** + * 构造 rangeRows 汇总 SQL(与 report.js 口径一致)。 + * @param {string} tableName 表名 + * @param {boolean} isBySpace 是否按库位维度 + * @param {boolean} withStart 是否带 created_at >= start 条件 + * @return {string} SQL 文本 + */ +function buildRangeSql(tableName, isBySpace, withStart) { + const spaceSelect = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id, ' : ''; + const spaceGroup = isBySpace ? ', COALESCE(t.space_id, 0)' : ''; + const startClause = withStart ? ' AND t.created_at >= ?' : ''; + return ` + SELECT t.stock_id, + ${spaceSelect}t.store_id, + SUM(CASE WHEN t.transaction_type = 'INBOUND' THEN t.quantity ELSE 0 END) AS inbound_total, + SUM(CASE WHEN t.transaction_type = 'OUTBOUND' THEN t.quantity ELSE 0 END) AS outbound_total + FROM ${tableName} t + WHERE t.store_id = ?${startClause} + GROUP BY t.stock_id${spaceGroup}, t.store_id + `; +} + +/** + * 构造 intervalEdge 快照 SQL(fixed:含 stock/store 关联;buggy:不含)。 + * @param {string} tableName 表名 + * @param {boolean} isBySpace 是否按库位维度 + * @param {boolean} withStart 是否带 created_at >= start 条件 + * @param {boolean} fixed 是否修复版 + * @return {string} SQL 文本 + */ +function buildEdgeSql(tableName, isBySpace, withStart, fixed) { + const spaceSelect = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id, ' : '0 AS space_id, '; + const spaceGroup = isBySpace ? ', COALESCE(t.space_id, 0)' : ''; + const startClauseG = withStart ? ' AND t.created_at >= ?' : ''; + const startClause2 = withStart ? ' AND t2.created_at >= ?' : ''; + const startClause3 = withStart ? ' AND t3.created_at >= ?' : ''; + const spaceJoin2 = isBySpace ? ' AND COALESCE(t2.space_id, 0) = g.space_id' : ''; + const spaceJoin3 = isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''; + const dimJoin2 = fixed ? ' AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id' : ''; + const dimJoin3 = fixed ? ' AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id' : ''; + return ` + SELECT g.stock_id, g.space_id, g.store_id, + ft.before_quantity, lt.after_quantity + FROM ( + SELECT t.stock_id, + ${spaceSelect}t.store_id, + MIN(t.created_at) AS _min_ct, + MAX(t.created_at) AS _max_ct + FROM ${tableName} t + WHERE t.store_id = ?${startClauseG} + GROUP BY t.stock_id${spaceGroup}, t.store_id + ) g + LEFT JOIN ${tableName} ft + ON ft.id = ( + SELECT MIN(t2.id) + FROM ${tableName} t2 + WHERE t2.store_id = ?${startClause2}${spaceJoin2}${dimJoin2} + AND t2.created_at = g._min_ct + ) + LEFT JOIN ${tableName} lt + ON lt.id = ( + SELECT MAX(t3.id) + FROM ${tableName} t3 + WHERE t3.store_id = ?${startClause3}${spaceJoin3}${dimJoin3} + AND t3.created_at = g._max_ct + ) + ORDER BY g.stock_id, g.space_id, g.store_id + `; +} + +/** + * 构造 preStart 快照 SQL(fixed:含 stock/store 关联;buggy:不含)。 + * @param {string} tableName 表名 + * @param {boolean} isBySpace 是否按库位维度 + * @param {boolean} fixed 是否修复版 + * @return {string} SQL 文本 + */ +function buildPreStartSql(tableName, isBySpace, fixed) { + const spaceSelect = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id, ' : '0 AS space_id, '; + const spaceGroup = isBySpace ? ', COALESCE(t.space_id, 0)' : ''; + const spaceJoin = isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''; + const dimJoin = fixed ? ' AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id' : ''; + return ` + SELECT g.stock_id, g.space_id, g.store_id, lt.after_quantity + FROM ( + SELECT t.stock_id, + ${spaceSelect}t.store_id, + MAX(t.created_at) AS _max_ct + FROM ${tableName} t + WHERE t.store_id = ? AND t.created_at < ? + GROUP BY t.stock_id${spaceGroup}, t.store_id + ) g + LEFT JOIN ${tableName} lt + ON lt.id = ( + SELECT MAX(t3.id) + FROM ${tableName} t3 + WHERE t3.store_id = ? AND t3.created_at < ?${spaceJoin}${dimJoin} + AND t3.created_at = g._max_ct + ) + ORDER BY g.stock_id, g.space_id, g.store_id + `; +} + +function edgeParams(storeId, withStart, startLiteral) { + const base = [ storeId ]; + if (withStart) { + base.push(startLiteral); + } + // g 外层 1 次 + t2 子查询 1 次 + t3 子查询 1 次 + return [ ...base, ...base, ...base ]; +} + +function preStartParams(storeId, startLiteral) { + return [ storeId, startLiteral, storeId, startLiteral ]; +} + +/** + * 分析每条维度键的流水链路一致性(原始数据质量),识别: + * - null_before_after:before/after 为 NULL + * - delta_mismatch:INBOUND 应为 +qty、OUTBOUND 应为 -qty、其他应为 0 + * - chain_break:前一条 after 与后一条 before 不衔接 + * @param {Object[]} rows 全量流水行 + * @param {boolean} isBySpace 是否按库位维度 + * @return {Map} 异常键到原因列表的映射 + */ +function analyzeChain(rows, isBySpace) { + const byKey = new Map(); + for (const row of rows) { + const key = dimKey(row, isBySpace); + if (!byKey.has(key)) { + byKey.set(key, []); + } + byKey.get(key).push(row); + } + + const anomalies = new Map(); + for (const [ key, list ] of byKey.entries()) { + list.sort((a, b) => { + if (a.ct !== b.ct) { + return a.ct < b.ct ? -1 : 1; + } + return num(a.id) - num(b.id); + }); + + const reasons = []; + let prevAfter = null; + for (let i = 0; i < list.length; i += 1) { + const row = list[i]; + const before = num(row.before_quantity); + const after = num(row.after_quantity); + if (before === null || after === null) { + reasons.push(`null_before_after@id=${row.id}`); + prevAfter = after; + continue; + } + const qty = num(row.quantity); + if (qty !== null) { + let expectedDelta = 0; + if (row.transaction_type === 'INBOUND') { + expectedDelta = qty; + } else if (row.transaction_type === 'OUTBOUND') { + expectedDelta = -qty; + } + if (after - before !== expectedDelta) { + reasons.push(`delta_mismatch@id=${row.id}`); + } + } + if (i > 0 && prevAfter !== null && prevAfter !== before) { + reasons.push(`chain_break@id=${row.id}(prev_after=${prevAfter},before=${before})`); + } + prevAfter = after; + } + if (reasons.length > 0) { + anomalies.set(key, reasons); + } + } + return anomalies; +} + +/** + * 全量(无 start_time)场景:fixed/buggy 快照 SQL vs oracle + 恒等式。 + * @param {Object} conn mysql2 连接 + * @param {string} tableName 表名 + * @param {boolean} isBySpace 是否按库位维度 + * @param {string} label 场景标签 + * @return {Promise} 校验中间结果 + */ +async function verifyFullRange(conn, tableName, isBySpace, label) { + console.log(`\n===== ${label}:全量 intervalEdge 快照校验(store_id=${STORE_ID}) =====`); + const rows = await fetchAllRows(conn, tableName, isBySpace, STORE_ID); + console.log(`全量流水行数: ${rows.length}`); + + const oracle = buildFullOracle(rows, isBySpace); + + const [ rangeRows ] = await conn.query(buildRangeSql(tableName, isBySpace, false), [ STORE_ID ]); + const [ fixedRows ] = await conn.query(buildEdgeSql(tableName, isBySpace, false, true), edgeParams(STORE_ID, false, null)); + const [ buggyRows ] = await conn.query(buildEdgeSql(tableName, isBySpace, false, false), edgeParams(STORE_ID, false, null)); + + const fixedMap = new Map(); + for (const row of fixedRows) { + fixedMap.set(dimKey(row, isBySpace), row); + } + const buggyMap = new Map(); + for (const row of buggyRows) { + buggyMap.set(dimKey(row, isBySpace), row); + } + const rangeMap = new Map(); + for (const row of rangeRows) { + rangeMap.set(dimKey(row, isBySpace), row); + } + + const dimKeyCount = oracle.size; + console.log(`维度键(stock[,space],store)数: ${dimKeyCount}`); + + const anomalies = analyzeChain(rows, isBySpace); + + let fixedBeginMismatch = 0; + let fixedEndMismatch = 0; + let buggyMismatch = 0; + let identityMismatch = 0; + let identityChecked = 0; + let nullEdgeKeys = 0; + const buggySamples = []; + const identitySamples = []; + + for (const [ key, expected ] of oracle.entries()) { + const fixedRow = fixedMap.get(key); + const buggyRow = buggyMap.get(key); + const rangeRow = rangeMap.get(key); + + if (!fixedRow) { + fixedBeginMismatch += 1; + fixedEndMismatch += 1; + continue; + } + const fixedBegin = num(fixedRow.before_quantity); + const fixedEnd = num(fixedRow.after_quantity); + if (fixedBegin === null || fixedEnd === null) { + nullEdgeKeys += 1; + } + if (fixedBegin !== expected.first.before) { + fixedBeginMismatch += 1; + } + if (fixedEnd !== expected.last.after) { + fixedEndMismatch += 1; + } + if (buggyRow && (num(buggyRow.before_quantity) !== expected.first.before + || num(buggyRow.after_quantity) !== expected.last.after)) { + buggyMismatch += 1; + if (buggySamples.length < 5) { + buggySamples.push(`${key}: oracle(${expected.first.before}/${expected.last.after}) buggy(${num(buggyRow.before_quantity)}/${num(buggyRow.after_quantity)})`); + } + } + + // 恒等式只对链路一致的键断言(null/断链/增量不一致属原始数据质量问题,与本次修复无关) + if (anomalies.has(key)) { + continue; + } + const inbound = rangeRow ? num(rangeRow.inbound_total) : 0; + const outbound = rangeRow ? num(rangeRow.outbound_total) : 0; + identityChecked += 1; + if (fixedEnd !== fixedBegin + inbound - outbound) { + identityMismatch += 1; + if (identitySamples.length < 5) { + identitySamples.push(`${key}: end=${fixedEnd} begin=${fixedBegin} in=${inbound} out=${outbound} diff=${fixedEnd - (fixedBegin + inbound - outbound)}`); + } + } + } + + verdict(`${label} | fixed 首条 before 与 oracle 完全一致`, fixedBeginMismatch === 0, + fixedBeginMismatch === 0 ? `0 不一致 / ${dimKeyCount} 键` : `${fixedBeginMismatch} 键不一致`); + verdict(`${label} | fixed 末条 after 与 oracle 完全一致`, fixedEndMismatch === 0, + fixedEndMismatch === 0 ? `0 不一致 / ${dimKeyCount} 键` : `${fixedEndMismatch} 键不一致`); + const consistentKeyCount = dimKeyCount - anomalies.size; + console.log(` 链路一致的维度键: ${consistentKeyCount}/${dimKeyCount};异常键(原始数据质量): ${anomalies.size}`); + if (nullEdgeKeys > 0) { + console.log(` 说明: ${nullEdgeKeys} 键的首/末行 before/after 为 NULL(原始数据既有,report.js toNumber 会按 0 处理),不属于修复问题`); + } + if (anomalies.size > 0) { + for (const [ key, reasons ] of anomalies.entries()) { + console.log(` 数据异常键 ${key}: ${reasons.slice(0, 4).join(' ; ')}`); + } + } + verdict(`${label} | 恒等式 end = begin + in - out(链路一致键)全部成立`, identityMismatch === 0, + `${identityMismatch} 违反 / 校验 ${identityChecked} 键`); + verdict(`${label} | buggy(无关联) 与 oracle 不一致样本数`, true, + `不一致 ${buggyMismatch} 键(用于说明缺陷影响面)`); + if (buggySamples.length > 0) { + console.log(` buggy 不一致样本: ${buggySamples.join(' ; ')}`); + } + if (identitySamples.length > 0) { + console.log(` 恒等式违反样本: ${identitySamples.join(' ; ')}`); + } + + return { rows, oracle, fixedMap, rangeMap, anomalies }; +} + +/** + * 场景4:start_time 边界——preStart 快照(start 前最近一条 after), + * 特别选取「期初边界处同秒多条流水」的时间点。 + * @param {Object} conn mysql2 连接 + * @param {string} tableName 表名 + * @param {boolean} isBySpace 是否按库位维度 + * @param {string} label 场景标签 + * @return {Promise} 校验中间结果 + */ +async function verifyPreStartBoundary(conn, tableName, isBySpace, label) { + console.log(`\n===== ${label}:start_time 边界 preStart 快照校验 =====`); + const rows = await fetchAllRows(conn, tableName, isBySpace, STORE_ID); + + // 找「两个相邻时间戳都含同键多行」的维度键,把较晚时间戳作为 start(前一批成为期初边界)。 + const byKey = new Map(); + for (const row of rows) { + const key = dimKey(row, isBySpace); + if (!byKey.has(key)) { + byKey.set(key, new Map()); + } + const ctMap = byKey.get(key); + ctMap.set(String(row.ct), (ctMap.get(String(row.ct)) || 0) + 1); + } + + let chosenKey = null; + let chosenStart = null; + for (const [ key, ctMap ] of byKey.entries()) { + const cts = [ ...ctMap.keys() ].sort(); + for (let i = 1; i < cts.length; i += 1) { + if ((ctMap.get(cts[i - 1]) || 0) >= 2 && (ctMap.get(cts[i]) || 0) >= 2) { + chosenKey = key; + chosenStart = cts[i]; + break; + } + } + if (chosenKey) { + break; + } + } + + if (!chosenStart) { + // 退而求其次:任一含同秒多行的时间戳,往后取相邻时间戳作为 start + let found = false; + for (const [ key, ctMap ] of byKey.entries()) { + if (found) { + break; + } + const cts = [ ...ctMap.keys() ].sort(); + for (let i = 0; i < cts.length; i += 1) { + if ((ctMap.get(cts[i]) || 0) >= 2) { + chosenKey = key; + chosenStart = i + 1 < cts.length ? cts[i + 1] : cts[i]; + found = true; + break; + } + } + } + } + + if (!chosenStart) { + verdict(`${label} | preStart 边界同秒样本`, false, '未找到同秒多行样本,跳过'); + return { oraclePreStart: null, chosenStart: null, rows, chosenKey: null }; + } + + console.log(`选中维度键: ${chosenKey}, start_time 边界: ${chosenStart}`); + + // oracle:created_at < start 的最近一条(created_at, id 排序) + const preStartOracle = new Map(); + for (const row of rows) { + const key = dimKey(row, isBySpace); + if (String(row.ct) >= chosenStart) { + continue; + } + const id = num(row.id); + const ct = String(row.ct); + const after = num(row.after_quantity); + if (!preStartOracle.has(key)) { + preStartOracle.set(key, { ct, id, after }); + continue; + } + const current = preStartOracle.get(key); + if (ct > current.ct || (ct === current.ct && id > current.id)) { + preStartOracle.set(key, { ct, id, after }); + } + } + + const [ fixedPreRows ] = await conn.query( + buildPreStartSql(tableName, isBySpace, true), + preStartParams(STORE_ID, chosenStart) + ); + const [ buggyPreRows ] = await conn.query( + buildPreStartSql(tableName, isBySpace, false), + preStartParams(STORE_ID, chosenStart) + ); + + const fixedPreMap = new Map(); + for (const row of fixedPreRows) { + fixedPreMap.set(dimKey(row, isBySpace), row); + } + const buggyPreMap = new Map(); + for (const row of buggyPreRows) { + buggyPreMap.set(dimKey(row, isBySpace), row); + } + + let fixedPreMismatch = 0; + let nullPreCount = 0; + let buggyPreMismatch = 0; + for (const [ key, expected ] of preStartOracle.entries()) { + const fixedRow = fixedPreMap.get(key); + if (!fixedRow) { + fixedPreMismatch += 1; + continue; + } + if (num(fixedRow.after_quantity) === null) { + nullPreCount += 1; + } + if (num(fixedRow.after_quantity) !== expected.after) { + fixedPreMismatch += 1; + } + const buggyRow = buggyPreMap.get(key); + if (buggyRow && num(buggyRow.after_quantity) !== expected.after) { + buggyPreMismatch += 1; + } + } + + verdict(`${label} | preStart 最近一条 after 与 oracle 完全一致`, fixedPreMismatch === 0, + `不一致 ${fixedPreMismatch},共 ${preStartOracle.size} 键`); + if (nullPreCount > 0) { + console.log(` 说明: ${nullPreCount} 键的期初行 after_quantity 为 NULL(原始数据既有,report.js toNumber 会按 0 处理),不属于修复问题`); + } + verdict(`${label} | preStart buggy 不一致样本数`, true, + `不一致 ${buggyPreMismatch} 键(用于说明缺陷影响面)`); + + // 窗口恒等式:以 chosenStart 为 start、以该键末条时间为 end,验证 + // end_total = preStartAfter + Σin - Σout(含 start_time 的 intervalEdge 修复版) + const chosenParts = chosenKey.split('_'); + const chosenStockId = chosenParts[0]; + const [ rangeWithStart ] = await conn.query( + buildRangeSql(tableName, isBySpace, true), + [ STORE_ID, chosenStart ] + ); + const [ edgeWithStart ] = await conn.query( + buildEdgeSql(tableName, isBySpace, true, true), + edgeParams(STORE_ID, true, chosenStart) + ); + const rangeWithStartMap = new Map(); + for (const row of rangeWithStart) { + rangeWithStartMap.set(dimKey(row, isBySpace), row); + } + const edgeWithStartMap = new Map(); + for (const row of edgeWithStart) { + edgeWithStartMap.set(dimKey(row, isBySpace), row); + } + + const anomalies = analyzeChain(rows, isBySpace); + let windowIdentityMismatch = 0; + let windowChecked = 0; + for (const [ key, expected ] of preStartOracle.entries()) { + if (anomalies.has(key)) { + continue; + } + const edgeRow = edgeWithStartMap.get(key); + const rangeRow = rangeWithStartMap.get(key); + if (!edgeRow || num(edgeRow.after_quantity) === null) { + continue; + } + const end = num(edgeRow.after_quantity); + const begin = expected.after; + const inbound = rangeRow ? num(rangeRow.inbound_total) : 0; + const outbound = rangeRow ? num(rangeRow.outbound_total) : 0; + windowChecked += 1; + if (end !== begin + inbound - outbound) { + windowIdentityMismatch += 1; + } + } + + verdict(`${label} | 带 start_time 窗口恒等式 end = 期初 + in - out(链路一致键)`, windowIdentityMismatch === 0, + `${windowIdentityMismatch} 违反 / 校验 ${windowChecked} 键`); + + return { oraclePreStart: preStartOracle, chosenStart, rows, chosenKey, chosenStockId }; +} + +(async () => { + const dbConfig = loadDevDbConfig(); + console.log('目标: 开发库', `${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`); + + const connection = await mysql.createConnection(dbConfig); + try { + // 场景1:货主口径(by_space=false 等价,维度键 stock+store) + await verifyFullRange(connection, 'wms_stock_transaction', false, '场景1 货主口径(wms_stock_transaction)'); + + // 场景3:库位口径(by_space=true,维度键 stock+space+store) + await verifyFullRange(connection, 'wms_storage_transaction', true, '场景3 库位口径(wms_storage_transaction)'); + + // 场景4:start_time 边界 + await verifyPreStartBoundary(connection, 'wms_stock_transaction', false, '场景4 货主口径 start_time 边界'); + await verifyPreStartBoundary(connection, 'wms_storage_transaction', true, '场景4 库位口径 start_time 边界'); + } finally { + await connection.end(); + } + + console.log('\n===== 汇总 ====='); + console.log(`PASS: ${counters.pass}, FAIL: ${counters.fail}`); + if (counters.fail > 0) { + process.exit(1); + } +})().catch(err => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); +}); diff --git a/script/tmp-trace-wave-closure-cause.cjs b/script/tmp-trace-wave-closure-cause.cjs new file mode 100644 index 0000000..e5faf50 --- /dev/null +++ b/script/tmp-trace-wave-closure-cause.cjs @@ -0,0 +1,26 @@ +'use strict'; + +/** + * 只读排查脚本:追踪 2026-09-12 当天与波次 1777888535813505 相关的 SQL 及订单表 DDL。 + * 仅执行 grep / cut / uniq 等只读命令。 + */ + +const { loadDeployConfig, runSsh } = require('./deploy-lib.cjs'); + +const WAVE_ID = '1777888535813505'; + +function buildRemoteScript() { + return [ + 'set -uo pipefail', + 'D=/root/logs/wms/wms-web.log.2026-09-12', + 'echo "===WRITES_AT_184428_CST==="', + 'grep -a "2026-09-12 18:44:2[0-9]" "$D" 2>/dev/null | grep -a "wms_order_delivery_1000028" | cut -c1-420 | head -20 || true', + 'echo "===WAVE_ID_CLEAR_STMTS_0912==="', + 'grep -a "UPDATE .wms_order_delivery_1000028. SET .wave_id" "$D" 2>/dev/null | cut -c1-19 | uniq -c | head -30 || true', + 'echo "===POST_METHODS_AT_162533==="', + 'grep -a "2026-09-12 16:25:33" "$D" 2>/dev/null | grep -ao "POST /system?method=[a-zA-Z.]*" | sort | uniq -c | head -20 || true', + ].join('\n'); +} + +const config = loadDeployConfig('production'); +console.log(runSsh(config, buildRemoteScript(), { stdio: 'pipe' })); diff --git a/script/tmp-unbind-prod-cart.cjs b/script/tmp-unbind-prod-cart.cjs new file mode 100644 index 0000000..6aec3a3 --- /dev/null +++ b/script/tmp-unbind-prod-cart.cjs @@ -0,0 +1,104 @@ +'use strict'; + +/** + * 一次性数据修复:解绑生产残留的拣货车绑定。 + * + * 背景:修复前打印解绑核实逻辑对「波次含拦截订单」的场景永远不满足, + * 导致 wms_pick_task_cart_binding.is_active=1 残留(车未解锁)。 + * 核对结论(2026-09-06): + * - 生产残留 39 条,全部 task.status=2(拣货完成待复核)、review_status=0; + * - 同车重复活跃绑定 0 条、已复核仍残留 0 条; + * - 关联订单已全部打印(散单/团购均无未打印订单)。 + * + * 用法: + * node script/tmp-unbind-prod-cart.cjs # dry-run:核对范围与快照,不写库 + * node script/tmp-unbind-prod-cart.cjs --apply # 执行解绑 UPDATE,并回读确认 + */ +const path = require('path'); +const { createRequire } = require('module'); + +(async () => { + const apply = process.argv.includes('--apply'); + const projectRoot = path.resolve(__dirname, '..'); + const projectRequire = createRequire(path.join(projectRoot, 'package.json')); + const mysql = projectRequire('mysql2/promise'); + + const configPath = path.join(projectRoot, 'script', 'db-query-prod-config.js'); + const config = require(configPath); + const client = config && config.mysql && config.mysql.clients + && config.mysql.clients.wms; + if (!client) { + throw new Error('生产连接配置缺失 (script/db-query-prod-config.js -> mysql.clients.wms)'); + } + + const connection = await mysql.createConnection({ + host: client.host, + port: Number(client.port), + user: client.user, + password: client.password, + database: client.database, + charset: client.charset || 'utf8mb4', + }); + + try { + // 目标范围:活跃绑定且任务已结束(待复核/完成/取消)。当前核对全部 status=2。 + const targetSql = ` + SELECT + b.id, b.task_id, b.cart_id, b.cart_code_snapshot, + b.warehouse_id, b.bind_user_id, + DATE_FORMAT(b.bind_time, '%Y-%m-%d %H:%i') AS bind_time, + t.task_no, t.status AS task_status, t.review_status + FROM wms_pick_task_cart_binding b + JOIN wms_wave_pick_task t ON t.id = b.task_id + WHERE b.is_active = 1 + AND t.status IN (2, 3, 9) + ORDER BY b.id ASC + `; + const [targetRows] = await connection.query(targetSql); + const targetIds = targetRows.map(row => Number(row.id)); + + console.log(`[unbind-prod-cart] 目标环境: ${client.host}:${client.port}/${client.database}`); + console.log(`[unbind-prod-cart] 命中活跃绑定: ${targetIds.length} 条`); + if (targetRows.length > 0) { + console.table(targetRows.slice(0, 50)); + } + + if (targetIds.length === 0) { + console.log('[unbind-prod-cart] 无待解绑记录,结束。'); + return; + } + + if (!apply) { + console.log('[unbind-prod-cart] dry-run 完成,未写库。确认无误后加 --apply 执行。'); + return; + } + + // 执行解绑(仅限命中范围,保留 is_active=1 条件防止并发误伤) + const [updateResult] = await connection.query(` + UPDATE wms_pick_task_cart_binding + SET is_active = 0, + unbind_user_id = 0, + unbind_time = NOW(), + update_time = NOW() + WHERE is_active = 1 + AND id IN (?) + `, [ targetIds ]); + console.log(`[unbind-prod-cart] 解绑 UPDATE 完成,受影响行数: ${updateResult.affectedRows}`); + + // 回读确认 + const [remainingRows] = await connection.query(` + SELECT COUNT(*) AS cnt + FROM wms_pick_task_cart_binding b + JOIN wms_wave_pick_task t ON t.id = b.task_id + WHERE b.is_active = 1 + AND t.status IN (2, 3, 9) + `); + const remainingCount = Number(remainingRows[0] && remainingRows[0].cnt || 0); + console.log(`[unbind-prod-cart] 回读确认:剩余活跃绑定 ${remainingCount} 条`); + } finally { + await connection.end(); + } +})().catch(error => { + console.error('[unbind-prod-cart] 执行失败:', error && error.message ? error.message : error); + process.exitCode = 1; +}); diff --git a/script/tmp-verify-intercept-order-dev.cjs b/script/tmp-verify-intercept-order-dev.cjs new file mode 100644 index 0000000..7d41df3 --- /dev/null +++ b/script/tmp-verify-intercept-order-dev.cjs @@ -0,0 +1,228 @@ +'use strict'; + +/** + * 临时端到端校验脚本(开发库,只读):库内确定拦截订单明细报表类型 interceptOrder。 + * + * 校验两条链路(不做任何数据库写操作): + * A. 真实查询器链路:以 egg 真实上下文(含 orderExport 服务与配送表模型) + * 调用查询器,验证 dispatch 表位/模型解析、dispath_time 区间 SQL、meta 口径可正常执行; + * 开发库历史拦截单 dispath_time 均为 NULL(该列 2026-09-07 才上线),因此预期 0 行。 + * B. 真实数据映射链路(对照 A 的非空场景):以「仅 intercept_status 过滤(不限时间)」 + * 调用 orderExport.buildOrderExportPage(mode=item),取真实拦截订单明细行, + * 经 pickReportRow 裁剪后用 renderSheetByType 渲染,核对表头 46 列与数据行。 + * + * 运行:node script/tmp-verify-intercept-order-dev.cjs + */ +const path = require('node:path'); +const mm = require('egg-mock'); + +const projectRoot = path.resolve(__dirname, '..'); +const interceptOrder = require(path.join(projectRoot, 'app/service/systems/report/queries/interceptOrder.js')); +const { renderSheetByType } = require(path.join(projectRoot, 'app/lib/report/render.js')); + +const WAREHOUSE_ID = 100000; + +let failed = 0; +const check = (condition, label, detail = '') => { + if (condition) { + console.log(` ✔ ${label}${detail ? ` | ${detail}` : ''}`); + return; + } + failed += 1; + console.log(` ✘ ${label}${detail ? ` | ${detail}` : ''}`); +}; + +(async () => { + mm.env('local'); + const app = mm.app({ baseDir: projectRoot }); + await app.ready(); + const ctx = app.createAnonymousContext(); + ctx.user = { store_id: WAREHOUSE_ID }; + const orderExport = ctx.service.systems.orderExport; + + try { + console.log('\n[A] 查询器真实链路(warehouse=%s,昨日自然日)', WAREHOUSE_ID); + const yesterdayDate = new Date(); + yesterdayDate.setDate(yesterdayDate.getDate() - 1); + const bizDate = `${yesterdayDate.getFullYear()}-${String(yesterdayDate.getMonth() + 1).padStart(2, '0')}` + + `-${String(yesterdayDate.getDate()).padStart(2, '0')}`; + const result = await interceptOrder({ + ctx, + storeId: null, + warehouseId: WAREHOUSE_ID, + params: { bizDate }, + }); + console.log(' meta=' + JSON.stringify(result.meta)); + console.log(' rows=' + result.rows.length); + check(result.meta.bizDate === bizDate, 'meta.bizDate 与入参一致', result.meta.bizDate); + check(result.meta.timeField === 'dispath_time', 'meta.timeField=dispath_time'); + check( + result.meta.interceptStatus === 'intercepted_at_warehouse', + 'meta.interceptStatus=intercepted_at_warehouse' + ); + check(result.meta.rowCount === result.rows.length, 'meta.rowCount 与行数一致'); + check(Array.isArray(result.windows) && result.windows.length === 0, 'windows 为空(无展开列)'); + check( + result.meta.startTime === `${bizDate} 00:00:00` && result.meta.endTime > result.meta.startTime, + '统计区间为指定自然日整天(左闭右开)', + `${result.meta.startTime} ~ ${result.meta.endTime}` + ); + // 开发库历史拦截单 dispath_time 多数为 NULL(仅补测的几单有值),此处校验口径一致性 + const distinctOrderCount = new Set(result.rows.map(row => Number(row.id))).size; + check( + distinctOrderCount === result.meta.orderCount, + 'meta.orderCount = 明细行去重订单数', + `orders=${distinctOrderCount}/${result.meta.orderCount}` + ); + + console.log('\n[B] 真实拦截订单明细映射链路(忽略时间过滤,仅验证列与取值)'); + const target = orderExport.resolveExportTarget({ tableType: 'dispatch' }); + const orderModel = await orderExport.getOrderModelByTableType('dispatch', WAREHOUSE_ID); + const pageResult = await orderExport.buildOrderExportPage({ + page: 1, + pageSize: 5, + queryWhere: { intercept_status: 'intercepted_at_warehouse' }, + order: [[ 'id', 'ASC' ]], + orderModel, + target, + warehouseId: WAREHOUSE_ID, + mode: 'item', + }); + console.log(` 命中订单=${pageResult.orderCount},导出行=${pageResult.exportRows.length}`); + check(pageResult.orderCount > 0, '开发库存在库内确定拦截订单(用于映射验证)', String(pageResult.orderCount)); + + const reportRows = pageResult.exportRows.map(row => interceptOrder.pickReportRow(row)); + const sample = reportRows[0] || {}; + console.log(' 明细首行抽样=' + JSON.stringify({ + id: sample.id, + delivery_order_code: sample.delivery_order_code, + item_name: sample.item_name, + item_quantity: sample.item_quantity, + waybill_code: sample.waybill_code, + outbound_status: sample.outbound_status, + create_channel: sample.create_channel, + }, null, 2)); + check( + reportRows.every(row => Object.keys(row).length === interceptOrder.fields.length), + '每行键数=注册字段数', + String(interceptOrder.fields.length) + ); + check( + reportRows.every(row => !Object.prototype.hasOwnProperty.call(row, 'item_image')), + '行不含商品图片列' + ); + check( + reportRows.some(row => Number(row.item_quantity) > 0) || reportRows.length > 0, + '存在数据行' + ); + + console.log('\n[C] 渲染链路(renderSheetByType)'); + const sheet = renderSheetByType({ + type: 'interceptOrder', + title: '库内确定拦截订单明细', + fields: interceptOrder.fields.map(field => ({ ...field })), + rows: reportRows, + windows: [], + }); + const header = sheet.rows[0]; + console.log(' 表头列数=' + header.length + ',总行数=' + sheet.rows.length); + check(sheet.name === '库内确定拦截订单明细', 'sheet 名称为报表标题', sheet.name); + check(header.length === interceptOrder.fields.length, '表头列数与注册字段一致', String(header.length)); + check(header[0] === '订单ID' && header[header.length - 2] === '通知拦截时间' + && header[header.length - 1] === '库内确定拦截时间', '表头首列与末尾两列拦截时间正确'); + check(sheet.rows.length === reportRows.length + 1, '单行表头 + 数据行(无展开列)'); + check( + Array.isArray(sheet.merges) && sheet.merges.length === 0, + '无展开列时不需要表头合并' + ); + check( + !Object.prototype.hasOwnProperty.call(sheet, 'textColumns'), + '未声明 asText,不输出 textColumns(与订单导出一致)' + ); + + console.log('\n[D] 附加列富化(平台交易单号 + 两列拦截时间,真实数据交叉核对)'); + const sampleOrders = await orderModel.findAll({ + where: { intercept_status: 'intercepted_at_warehouse' }, + attributes: [ 'id', 'source_order_codes', 'intercept_time', 'dispath_time' ], + order: [[ 'id', 'DESC' ]], + limit: 5, + raw: true, + }); + const timeRows = sampleOrders.map(row => ({ + id: Number(row.id), + source_order_codes: '', + intercept_notice_time: '', + intercept_confirm_time: '', + })); + await interceptOrder.enrichInterceptFields({ + ctx, + app: ctx.app, + orderModel, + warehouseId: WAREHOUSE_ID, + rows: timeRows, + }); + + const sampleIds = timeRows.map(row => String(row.id)); + const logRows = await ctx.model.query( + `SELECT business_id, MIN(created_at) AS notice_time + FROM wms_operation_log + WHERE business_type = 'order' + AND operation_code = 'ORDER_INTERCEPT_REQUEST' + AND warehouse_id = :warehouseId + AND business_id IN (:ids) + GROUP BY business_id`, + { + replacements: { warehouseId: WAREHOUSE_ID, ids: sampleIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + const logMap = new Map((Array.isArray(logRows) ? logRows : []).map(row => [ String(row.business_id), row.notice_time ])); + const formatExpected = value => { + if (value === null || value === undefined || value === '') { + return ''; + } + const date = new Date(value); + return Number.isNaN(date.getTime()) ? '' : ctx.app.formatDate(date); + }; + + for (const row of timeRows) { + const orderRow = sampleOrders.find(item => Number(item.id) === row.id) || {}; + const expectedNotice = formatExpected(orderRow.intercept_time) || formatExpected(logMap.get(String(row.id))); + const expectedConfirm = formatExpected(orderRow.dispath_time); + const expectedSourceOrderCodes = orderRow.source_order_codes === null || orderRow.source_order_codes === undefined + ? '' + : String(orderRow.source_order_codes); + console.log( + ` id=${row.id} 平台交易单号=${row.source_order_codes || '(空)'} / 期望=${expectedSourceOrderCodes || '(空)'}` + + ` | 通知拦截时间=${row.intercept_notice_time || '(空)'} / 期望=${expectedNotice || '(空)'}` + + ` | 库内确定拦截时间=${row.intercept_confirm_time || '(空)'} / 期望=${expectedConfirm || '(空)'}` + ); + check( + row.source_order_codes === expectedSourceOrderCodes, + `id=${row.id} 平台交易单号=配送表 source_order_codes 一致` + ); + check( + row.intercept_notice_time === expectedNotice, + `id=${row.id} 通知拦截时间=intercept_time(为空时回落 ORDER_INTERCEPT_REQUEST 日志)一致` + ); + check( + row.intercept_confirm_time === expectedConfirm, + `id=${row.id} 库内确定拦截时间=配送表 dispath_time 一致` + ); + } + check( + timeRows.every(row => typeof row.source_order_codes === 'string' + && typeof row.intercept_notice_time === 'string' + && typeof row.intercept_confirm_time === 'string'), + '附加列均为字符串(时间列为 YYYY-MM-DD HH:mm:ss 或空串)' + ); + } finally { + await app.close(); + } + + console.log(failed === 0 ? '\n全部校验通过' : `\n校验失败 ${failed} 项`); + process.exit(failed === 0 ? 0 : 1); +})().catch(error => { + console.error('脚本执行异常:', error && error.stack ? error.stack : error); + process.exit(1); +}); diff --git a/script/tmp-verify-pool-after-complete.cjs b/script/tmp-verify-pool-after-complete.cjs new file mode 100644 index 0000000..abac8f0 --- /dev/null +++ b/script/tmp-verify-pool-after-complete.cjs @@ -0,0 +1,151 @@ +'use strict'; + +/** + * 通过 pick.wavePickTaskComplete 提交任务 271 拣货完成(订单不回池), + * 然后再次抓取,验证第一池已清空后回落第二池抓满 20 条今天订单。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +const BASE_URL = 'http://127.0.0.1:6060'; +const DB_CONFIG = { + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', +}; +const TODAY_START_UTC = Date.UTC(2026, 8, 5, 16, 0, 0); + +/** + * 发送 /system POST 请求。 + * + * @param {string} token 登录令牌。 + * @param {string} method 方法名。 + * @param {Object} data 请求体。 + * @return {Promise} 响应 JSON。 + */ +async function sysCall(token, method, data) { + const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`; + const headers = { + 'Content-Type': 'application/json', + platform: 'web', + project: 'wms', + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }; + const res = await fetch(`${BASE_URL}/system?${qs}`, { + method: 'POST', + headers, + body: JSON.stringify(data), + }); + const text = await res.text(); + try { + return JSON.parse(text); + } catch (error) { + return { raw: text }; + } +} + +/** + * 深度优先查找对象中第一个匹配 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; +} + +/** + * 主流程入口。 + * + * @return {Promise} + */ +async function main() { + const login = await sysCall(null, 'user.login', { + username: 'liufumingren', + password: '111111', + }); + const token = deepFind(login, 'token'); + if (!token) { + throw new Error(`登录失败: ${JSON.stringify(login)}`); + } + console.log('[1] 登录成功'); + + // 1. 提交任务 271 拣货完成(订单不回池) + const completeRes = await sysCall(token, 'pick.wavePickTaskComplete', { + task_id: 271, + mode: 1, + }); + console.log(`[2] wavePickTaskComplete(271) 响应: ${JSON.stringify(completeRes).slice(0, 500)}`); + + // 2. 再次抓取 + let fetchRes = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 }); + let state = Number(deepFind(fetchRes, 'fetch_state') || 0); + let taskId = Number(deepFind(fetchRes, 'task_id') || 0); + if (state === 3 && taskId > 0) { + console.log(`[3] 存在未完成任务 ${taskId},取消后重试`); + await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: taskId }); + fetchRes = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 }); + state = Number(deepFind(fetchRes, 'fetch_state') || 0); + taskId = Number(deepFind(fetchRes, 'task_id') || 0); + } + if (state !== 1 || taskId <= 0) { + throw new Error(`抓取失败: ${JSON.stringify(fetchRes).slice(0, 400)}`); + } + console.log(`[3] 新任务 ${taskId} 创建成功`); + + // 3. 验证新任务订单 + const connection = await mysql.createConnection(DB_CONFIG); + try { + const [ taskOrderRows ] = await connection.query( + `SELECT order_id FROM wms_wave_pick_task_order WHERE task_id = ? ORDER BY box_no ASC`, + [ taskId ] + ); + const orderIds = taskOrderRows.map(row => Number(row.order_id)); + const [ orderRows ] = await connection.query( + `SELECT id, create_at FROM wms_order_delivery_100000 WHERE id IN (?) ORDER BY id ASC`, + [ orderIds ] + ); + const todayCount = orderRows.filter(row => new Date(row.create_at).getTime() >= TODAY_START_UTC).length; + console.log(`[4] 新任务抓取订单数: ${orderRows.length}, 其中今天订单: ${todayCount}`); + console.log(` 订单ID: [${orderIds.join(', ')}]`); + const passed = orderRows.length === 20 && todayCount === 20; + console.log(`结论: ${passed ? '✅ 拣货完成后订单不回池,第一池已空,回落第二池抓满 20 条今天订单' : '❌ 与预期不符'}`); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`验证失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-verify-report-plan-2-preview.cjs b/script/tmp-verify-report-plan-2-preview.cjs new file mode 100644 index 0000000..d9b209f --- /dev/null +++ b/script/tmp-verify-report-plan-2-preview.cjs @@ -0,0 +1,77 @@ +'use strict'; + +/** + * 临时预演脚本(只读,不投递):按投递计划 id=2(store 1000000 / report_definition_id=3 / + * 时间点 19:40 → biz_date=2026-09-09)的参数,走报表引擎 buildWorkbookSheets 生成工作簿, + * 检查「库内确定拦截订单明细」投递结果是否与预期一致(行数 / 表头 / 抽样单元格)。 + * + * 不做任何数据库写操作,不上传文件(用 generateBuffer)。 + * 运行:node script/tmp-verify-report-plan-2-preview.cjs + */ +const path = require('node:path'); +const mm = require('egg-mock'); + +const projectRoot = path.resolve(__dirname, '..'); +const STORE_ID = 1000000; +const WAREHOUSE_ID = 100000; +const REPORT_ID = 3; +const BIZ_DATE = '2026-09-09'; + +(async () => { + mm.env('local'); + const app = mm.app({ baseDir: projectRoot }); + await app.ready(); + const ctx = app.createAnonymousContext(); + ctx.user = { store_id: WAREHOUSE_ID, role: 1, id: 1, name: 'preview', employees_id: 1, employees_name: 'preview' }; + + try { + // 1) 查询器口径(含 storeId 过滤) + const querier = require(path.join(projectRoot, 'app/service/systems/report/queries/interceptOrder.js')); + const queryData = await querier({ + ctx, + storeId: STORE_ID, + warehouseId: WAREHOUSE_ID, + params: { bizDate: BIZ_DATE }, + }); + console.log('[查询器] meta=' + JSON.stringify(queryData.meta)); + console.log('[查询器] rows=' + queryData.rows.length); + for (const row of queryData.rows.slice(0, 5)) { + console.log(' ' + JSON.stringify({ + id: row.id, + delivery_order_code: row.delivery_order_code, + intercept_notice_time: row.intercept_notice_time, + intercept_confirm_time: row.intercept_confirm_time, + waybill_code: row.waybill_code, + item_quantity: row.item_quantity, + })); + } + + // 2) 报表引擎(按报表定义 id=3 的勾选字段渲染工作簿) + const workbook = await ctx.service.systems.report.buildWorkbookSheets({ + reportId: REPORT_ID, + storeId: STORE_ID, + warehouseId: WAREHOUSE_ID, + params: { bizDate: BIZ_DATE }, + }); + const sheet = workbook.sheets[0]; + console.log('[工作簿] filename=' + workbook.filename); + console.log('[工作簿] sheet=' + sheet.name + ' 表头列数=' + (sheet.rows[0] || []).length + ' 总行数=' + sheet.rows.length); + console.log('[工作簿] 表头=' + JSON.stringify(sheet.rows[0])); + for (const row of sheet.rows.slice(1, 6)) { + console.log('[工作簿] 数据行=' + JSON.stringify(row)); + } + + // 3) 结论 + const dataRows = Math.max(0, sheet.rows.length - 1); + console.log( + dataRows > 0 + ? `\n预演结果:投递将包含 ${dataRows} 行数据(订单 ${queryData.meta.orderCount} 单)` + : '\n预演结果:投递将为空表(0 行),需要检查统计窗口与 dispath_time 数据' + ); + } finally { + await app.close(); + } +})().catch(error => { + console.error('预演执行异常:', error && error.stack ? error.stack : error); + process.exit(1); +}); diff --git a/script/tmp-verify-stockreport-edge-prod.cjs b/script/tmp-verify-stockreport-edge-prod.cjs new file mode 100644 index 0000000..57aa97f --- /dev/null +++ b/script/tmp-verify-stockreport-edge-prod.cjs @@ -0,0 +1,226 @@ +/** + * 临时只读核对脚本(生产库,仅 SELECT): + * 核对 stock.report.searchStore 报表期初/期末快照 SQL 的关联缺失问题。 + * + * 用法(生产): + * $env:NODE_ENV='production'; node script/tmp-verify-stockreport-edge-prod.cjs + */ + +'use strict'; + +const path = require('path'); + +const projectRoot = path.resolve(__dirname, '..'); +const { createRequire } = require('module'); +const projectRequire = createRequire(path.join(projectRoot, 'package.json')); +const mysql = projectRequire('mysql2/promise'); + +function loadProdDbConfig() { + const defaultConfigPath = path.join(projectRoot, 'config', 'config.default.js'); + const defaultConfigFactory = require(defaultConfigPath); + const defaultConfig = typeof defaultConfigFactory === 'function' + ? defaultConfigFactory({ name: 'tmp-verify-stockreport-edge', baseDir: projectRoot }) + : defaultConfigFactory; + const sequelizeConfig = defaultConfig && defaultConfig.sequelize; + if (sequelizeConfig && sequelizeConfig.host) { + return { + host: sequelizeConfig.host, + port: Number(sequelizeConfig.port || 3306), + user: sequelizeConfig.username, + password: sequelizeConfig.password, + database: sequelizeConfig.database || 'wms', + }; + } + throw new Error('无法解析生产数据库配置'); +} + +(async () => { + const dbConfig = loadProdDbConfig(); + console.log('目标:', dbConfig.host + ':' + dbConfig.port + '/' + dbConfig.database, '(生产 config.default.js)'); + + const connection = await mysql.createConnection(dbConfig); + + try { + const storeId = 1000166; + const warehouseId = 1000028; + const stockIds = [ 132556, 132603, 132604, 132610, 132611, 133746, 133747, 133752 ]; + + console.log('\n=== 1) 目标 SKU 的仓库绑定与当前库存 ==='); + const [ swRows ] = await connection.query( + 'SELECT id, store_id, warehouse_id, quantity, item_code, item_name FROM wms_stock_warehouse WHERE id IN (?) ORDER BY id', + [ stockIds ] + ); + for (const row of swRows) { + console.log(JSON.stringify(row)); + } + + console.log('\n=== 2) 全部流水明细(wms_stock_transaction,按 SKU 分组) ==='); + const [ flowRows ] = await connection.query( + `SELECT id, stock_id, transaction_type, quantity, before_quantity, after_quantity, + DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') AS created_at + FROM wms_stock_transaction + WHERE stock_id IN (?) AND store_id = ? AND warehouse_id = ? + ORDER BY stock_id, created_at, id + LIMIT 300`, + [ stockIds, storeId, warehouseId ] + ); + let lastStockId = null; + for (const row of flowRows) { + if (row.stock_id !== lastStockId) { + console.log(`\n-- stock_id ${row.stock_id} --`); + lastStockId = row.stock_id; + } + console.log( + ` id=${row.id} type=${row.transaction_type} qty=${row.quantity} before=${row.before_quantity} after=${row.after_quantity} at=${row.created_at}` + ); + } + + console.log('\n=== 3) 区间汇总(rangeRows 口径:INBOUND/OUTBOUND 求和) ==='); + const [ rangeRows ] = await connection.query( + `SELECT t.stock_id, + SUM(CASE WHEN t.transaction_type = 'INBOUND' THEN t.quantity ELSE 0 END) AS inbound_total, + SUM(CASE WHEN t.transaction_type = 'OUTBOUND' THEN t.quantity ELSE 0 END) AS outbound_total + FROM wms_stock_transaction t + WHERE t.store_id = ? AND t.warehouse_id = ? AND t.stock_id IN (?) + GROUP BY t.stock_id, t.store_id + ORDER BY t.stock_id`, + [ storeId, warehouseId, stockIds ] + ); + for (const row of rangeRows) { + console.log(JSON.stringify(row)); + } + + console.log('\n=== 4) 现有快照 SQL(缺 stock_id 关联,BUG 版本) vs 修正版 ==='); + const [ buggy ] = await connection.query( + `SELECT g.stock_id, + ft.before_quantity AS buggy_begin, + lt.after_quantity AS buggy_end + FROM ( + SELECT t.stock_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct + FROM wms_stock_transaction t + WHERE t.store_id = ? AND t.warehouse_id = ? AND t.stock_id IN (?) + GROUP BY t.stock_id, t.store_id + ) g + LEFT JOIN wms_stock_transaction ft + ON ft.id = ( + SELECT MIN(t2.id) FROM wms_stock_transaction t2 + WHERE t2.store_id = ? AND t2.warehouse_id = ? AND t2.stock_id IN (?) + AND t2.created_at = g._min_ct + ) + LEFT JOIN wms_stock_transaction lt + ON lt.id = ( + SELECT MAX(t3.id) FROM wms_stock_transaction t3 + WHERE t3.store_id = ? AND t3.warehouse_id = ? AND t3.stock_id IN (?) + AND t3.created_at = g._max_ct + ) + ORDER BY g.stock_id`, + [ storeId, warehouseId, stockIds, storeId, warehouseId, stockIds, storeId, warehouseId, stockIds ] + ); + + const [ fixed ] = await connection.query( + `SELECT g.stock_id, + ft.before_quantity AS fixed_begin, + lt.after_quantity AS fixed_end + FROM ( + SELECT t.stock_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct + FROM wms_stock_transaction t + WHERE t.store_id = ? AND t.warehouse_id = ? AND t.stock_id IN (?) + GROUP BY t.stock_id, t.store_id + ) g + LEFT JOIN wms_stock_transaction ft + ON ft.id = ( + SELECT MIN(t2.id) FROM wms_stock_transaction t2 + WHERE t2.store_id = ? AND t2.warehouse_id = ? AND t2.stock_id IN (?) + AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id + AND t2.created_at = g._min_ct + ) + LEFT JOIN wms_stock_transaction lt + ON lt.id = ( + SELECT MAX(t3.id) FROM wms_stock_transaction t3 + WHERE t3.store_id = ? AND t3.warehouse_id = ? AND t3.stock_id IN (?) + AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id + AND t3.created_at = g._max_ct + ) + ORDER BY g.stock_id`, + [ storeId, warehouseId, stockIds, storeId, warehouseId, stockIds, storeId, warehouseId, stockIds ] + ); + + const buggyMap = new Map(buggy.map(r => [ r.stock_id, r ])); + console.log('stock_id | buggy_begin | buggy_end | fixed_begin | fixed_end'); + for (const row of fixed) { + const b = buggyMap.get(row.stock_id) || {}; + console.log( + `${row.stock_id} | ${b.buggy_begin} | ${b.buggy_end} | ${row.fixed_begin} | ${row.fixed_end}` + ); + } + + console.log('\n=== 5) 不带仓库过滤(货主全仓库口径,用户报表场景) ==='); + const [ buggy2 ] = await connection.query( + `SELECT g.stock_id, + ft.before_quantity AS buggy_begin, + lt.after_quantity AS buggy_end + FROM ( + SELECT t.stock_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct + FROM wms_stock_transaction t + WHERE t.store_id = ? AND t.stock_id IN (?) + GROUP BY t.stock_id, t.store_id + ) g + LEFT JOIN wms_stock_transaction ft + ON ft.id = ( + SELECT MIN(t2.id) FROM wms_stock_transaction t2 + WHERE t2.store_id = ? AND t2.stock_id IN (?) + AND t2.created_at = g._min_ct + ) + LEFT JOIN wms_stock_transaction lt + ON lt.id = ( + SELECT MAX(t3.id) FROM wms_stock_transaction t3 + WHERE t3.store_id = ? AND t3.stock_id IN (?) + AND t3.created_at = g._max_ct + ) + ORDER BY g.stock_id`, + [ storeId, stockIds, storeId, stockIds, storeId, stockIds ] + ); + + const [ fixed2 ] = await connection.query( + `SELECT g.stock_id, + ft.before_quantity AS fixed_begin, + lt.after_quantity AS fixed_end + FROM ( + SELECT t.stock_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct + FROM wms_stock_transaction t + WHERE t.store_id = ? AND t.stock_id IN (?) + GROUP BY t.stock_id, t.store_id + ) g + LEFT JOIN wms_stock_transaction ft + ON ft.id = ( + SELECT MIN(t2.id) FROM wms_stock_transaction t2 + WHERE t2.store_id = ? AND t2.stock_id IN (?) + AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id + AND t2.created_at = g._min_ct + ) + LEFT JOIN wms_stock_transaction lt + ON lt.id = ( + SELECT MAX(t3.id) FROM wms_stock_transaction t3 + WHERE t3.store_id = ? AND t3.stock_id IN (?) + AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id + AND t3.created_at = g._max_ct + ) + ORDER BY g.stock_id`, + [ storeId, stockIds, storeId, stockIds, storeId, stockIds ] + ); + + const buggy2Map = new Map(buggy2.map(r => [ r.stock_id, r ])); + console.log('stock_id | buggy_begin | buggy_end | fixed_begin | fixed_end'); + for (const row of fixed2) { + const b = buggy2Map.get(row.stock_id) || {}; + console.log( + `${row.stock_id} | ${b.buggy_begin} | ${b.buggy_end} | ${row.fixed_begin} | ${row.fixed_end}` + ); + } + } finally { + await connection.end(); + } +})().catch(err => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); +}); diff --git a/script/tmp-verify-wave-pool-boundary.cjs b/script/tmp-verify-wave-pool-boundary.cjs new file mode 100644 index 0000000..ce9d58e --- /dev/null +++ b/script/tmp-verify-wave-pool-boundary.cjs @@ -0,0 +1,193 @@ +'use strict'; + +/** + * 边界验证:第一订单池不足 20 时抓取行为。 + * + * 验证点: + * 1. 第一池(今日前)仅 8 条时,抓取数量 = 8,不会用第二池(今天订单)填充到 20; + * 2. 第一池抓取完毕后,第二轮抓取进入第二池,抓满 20 条今天订单。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +const BASE_URL = 'http://127.0.0.1:6060'; +const DB_CONFIG = { + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', +}; + +/** + * 发送 /system POST 请求。 + * + * @param {string} token 登录令牌。 + * @param {string} method 方法名。 + * @param {Object} data 请求体。 + * @return {Promise} 响应 JSON。 + */ +async function sysCall(token, method, data) { + const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`; + const headers = { + 'Content-Type': 'application/json', + platform: 'web', + project: 'wms', + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }; + const res = await fetch(`${BASE_URL}/system?${qs}`, { + method: 'POST', + headers, + body: JSON.stringify(data), + }); + const text = await res.text(); + try { + return JSON.parse(text); + } catch (error) { + return { raw: text }; + } +} + +/** + * 深度优先查找对象中第一个匹配 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; +} + +/** + * 执行一轮抓取,返回 { taskId, orderRows }。 + * + * @param {string} token 登录令牌。 + * @param {Object} connection 数据库连接。 + * @return {Promise} 抓取结果。 + */ +async function fetchOnce(token, connection, round) { + const fetchRes = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 }); + const fetchState = Number(deepFind(fetchRes, 'fetch_state') || 0); + const taskId = Number(deepFind(fetchRes, 'task_id') || 0); + if (fetchState === 3 && taskId > 0) { + await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: taskId }); + const retryRes = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 }); + const retryState = Number(deepFind(retryRes, 'fetch_state') || 0); + const retryTaskId = Number(deepFind(retryRes, 'task_id') || 0); + if (retryState !== 1 || retryTaskId <= 0) { + throw new Error(`第${round}轮抓取重试后仍未创建任务: ${JSON.stringify(retryRes).slice(0, 400)}`); + } + return { taskId: retryTaskId }; + } + if (fetchState !== 1 || taskId <= 0) { + throw new Error(`第${round}轮抓取未创建任务: ${JSON.stringify(fetchRes).slice(0, 400)}`); + } + return { taskId }; +} + +/** + * 读取任务订单与 create_at。 + * + * @param {Object} connection 数据库连接。 + * @param {number} taskId 任务 ID。 + * @return {Promise>} 订单行。 + */ +async function readTaskOrders(connection, taskId) { + const [ taskOrderRows ] = await connection.query( + `SELECT order_id FROM wms_wave_pick_task_order WHERE task_id = ? ORDER BY box_no ASC`, + [ taskId ] + ); + const orderIds = taskOrderRows.map(row => Number(row.order_id)); + if (orderIds.length === 0) { + return []; + } + const [ orderRows ] = await connection.query( + `SELECT id, create_at FROM wms_order_delivery_100000 WHERE id IN (?) ORDER BY id ASC`, + [ orderIds ] + ); + return orderRows; +} + +/** + * 主流程入口。 + * + * @return {Promise} + */ +async function main() { + const login = await sysCall(null, 'user.login', { + username: 'liufumingren', + password: '111111', + }); + const token = deepFind(login, 'token'); + if (!token) { + throw new Error(`登录失败: ${JSON.stringify(login)}`); + } + console.log('[1] 登录成功'); + + // 取消上一轮活跃任务 261 + await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: 261 }); + console.log('[2] 已取消任务 261'); + + const connection = await mysql.createConnection(DB_CONFIG); + try { + const todayStart = Date.UTC(2026, 8, 5, 16, 0, 0); // 2026-09-06 00:00 +08:00 + + // 第一轮:第一池仅 8 条今日前订单 + const first = await fetchOnce(token, connection, 1); + const firstOrders = await readTaskOrders(connection, first.taskId); + const firstBeforeToday = firstOrders.filter(row => new Date(row.create_at).getTime() < todayStart); + console.log(`[3] 第一轮任务 ${first.taskId} 抓取订单数: ${firstOrders.length}`); + console.log(` 今日前订单数: ${firstBeforeToday.length}, 订单ID: [${firstOrders.map(row => row.id).join(', ')}]`); + const firstPassed = firstOrders.length === 8 && firstBeforeToday.length === 8; + console.log(` 验证(不足20不填充): ${firstPassed ? '✅ 仅抓 8 条今日前订单,未填充今天订单' : '❌ 行为与预期不符'}`); + + // 第二轮:第一池已空,进入第二池抓满 20 + const second = await fetchOnce(token, connection, 2); + const secondOrders = await readTaskOrders(connection, second.taskId); + const secondToday = secondOrders.filter(row => new Date(row.create_at).getTime() >= todayStart); + console.log(`[4] 第二轮任务 ${second.taskId} 抓取订单数: ${secondOrders.length}`); + console.log(` 今天订单数: ${secondToday.length}, 订单ID: [${secondOrders.map(row => row.id).join(', ')}]`); + const secondPassed = secondOrders.length === 20 && secondToday.length === 20; + console.log(` 验证(第一池清空后抓满20条今天订单): ${secondPassed ? '✅ 第一池抓完后回落第二池并抓满 20' : '❌ 行为与预期不符'}`); + + console.log('==================== 总结 ===================='); + console.log(`第一轮(第一池8条): 实际抓取 ${firstOrders.length} 条 -> ${firstPassed ? 'PASS' : 'FAIL'}`); + console.log(`第二轮(第二池今天): 实际抓取 ${secondOrders.length} 条 -> ${secondPassed ? 'PASS' : 'FAIL'}`); + console.log(`结论: ${firstPassed && secondPassed ? '✅ 边界行为符合预期: 不足20不填充;第一池抓完才抓第二池' : '❌ 存在与预期不符的环节,请排查'}`); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`验证失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-verify-wave-pool-boundary2.cjs b/script/tmp-verify-wave-pool-boundary2.cjs new file mode 100644 index 0000000..f26efdd --- /dev/null +++ b/script/tmp-verify-wave-pool-boundary2.cjs @@ -0,0 +1,274 @@ +'use strict'; + +/** + * 订单池边界验证(重做版): + * 1. 取消所有活跃任务(释放订单回池); + * 2. 重建混合池:满足抓取口径且未分配波次的候选,保留 8 条同结构今日前订单,其余全部改为今天; + * 3. 第一轮抓取:预期仅抓 8 条今日前订单,不用今天订单填充到 20; + * 4. 第二轮抓取:第一池清空后回落第二池,抓满 20 条今天订单; + * 5. 输出验证结论。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +const BASE_URL = 'http://127.0.0.1:6060'; +const DB_CONFIG = { + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', +}; +const TODAY_TIME = '2026-09-06 12:00:00'; +const KEEP_COUNT = 8; +const TODAY_START_UTC = Date.UTC(2026, 8, 5, 16, 0, 0); // 2026-09-06 00:00 +08:00 + +/** + * 发送 /system POST 请求。 + * + * @param {string} token 登录令牌。 + * @param {string} method 方法名。 + * @param {Object} data 请求体。 + * @return {Promise} 响应 JSON。 + */ +async function sysCall(token, method, data) { + const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`; + const headers = { + 'Content-Type': 'application/json', + platform: 'web', + project: 'wms', + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }; + const res = await fetch(`${BASE_URL}/system?${qs}`, { + method: 'POST', + headers, + body: JSON.stringify(data), + }); + const text = await res.text(); + try { + return JSON.parse(text); + } catch (error) { + return { raw: text }; + } +} + +/** + * 深度优先查找对象中第一个匹配 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 {string} token 登录令牌。 + * @param {number} taskId 任务 ID。 + * @return {Promise} + */ +async function cancelTask(token, taskId) { + const res = await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: taskId }); + const count = Number(deepFind(res, 'cancelled_count') || 0); + console.log(` 取消任务 ${taskId}: cancelled_count=${count}`); +} + +/** + * 执行一轮抓取(存在未完成任务时取消后重试)。 + * + * @param {string} token 登录令牌。 + * @param {number} round 轮次。 + * @return {Promise} 任务 ID。 + */ +async function fetchOnce(token, round) { + const res = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 }); + let state = Number(deepFind(res, 'fetch_state') || 0); + let taskId = Number(deepFind(res, 'task_id') || 0); + if (state === 3 && taskId > 0) { + await cancelTask(token, taskId); + const retry = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 }); + state = Number(deepFind(retry, 'fetch_state') || 0); + taskId = Number(deepFind(retry, 'task_id') || 0); + } + if (state !== 1 || taskId <= 0) { + throw new Error(`第${round}轮抓取失败: state=${state}`); + } + return taskId; +} + +/** + * 读取任务抓取订单的 create_at。 + * + * @param {Object} connection 数据库连接。 + * @param {number} taskId 任务 ID。 + * @return {Promise>} 订单行。 + */ +async function readTaskOrders(connection, taskId) { + const [ taskOrderRows ] = await connection.query( + `SELECT order_id FROM wms_wave_pick_task_order WHERE task_id = ? ORDER BY box_no ASC`, + [ taskId ] + ); + const orderIds = taskOrderRows.map(row => Number(row.order_id)); + if (orderIds.length === 0) { + return []; + } + const [ orderRows ] = await connection.query( + `SELECT id, create_at FROM wms_order_delivery_100000 WHERE id IN (?) ORDER BY id ASC`, + [ orderIds ] + ); + return orderRows; +} + +/** + * 主流程入口。 + * + * @return {Promise} + */ +async function main() { + const login = await sysCall(null, 'user.login', { + username: 'liufumingren', + password: '111111', + }); + const token = deepFind(login, 'token'); + if (!token) { + throw new Error(`登录失败: ${JSON.stringify(login)}`); + } + console.log('[1] 登录成功'); + + const connection = await mysql.createConnection(DB_CONFIG); + try { + // 2. 取消所有活跃任务 + const [ activeTasks ] = await connection.query( + `SELECT id FROM wms_wave_pick_task WHERE warehouse_id = 100000 AND status IN (0, 1)` + ); + for (const row of activeTasks) { + await cancelTask(token, Number(row.id)); + } + console.log('[2] 已取消全部活跃任务'); + + // 3. 重建混合池 + const [ rows ] = await connection.query( + `SELECT o.id, o.create_at, o.items_hash + FROM wms_order_wave_strategy_match m + INNER JOIN wms_order_delivery_100000 o + ON o.id = m.order_id + WHERE m.warehouse_id = 100000 + AND m.strategy_id = 7 + 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' + ORDER BY o.id ASC` + ); + const beforeToday = rows.filter(row => new Date(row.create_at).getTime() < TODAY_START_UTC); + console.log(`[3] 候选总数: ${rows.length},其中今日前: ${beforeToday.length}`); + + const hashGroups = new Map(); + for (const row of beforeToday) { + const key = String(row.items_hash || '').trim(); + if (!key) continue; + if (!hashGroups.has(key)) hashGroups.set(key, []); + hashGroups.get(key).push(row); + } + + // 策略 7 max_same_structure=12(仓库下调),须选同结构总数 2~12 的组 + let keepGroup = null; + for (const list of hashGroups.values()) { + const groupHash = String(list[0] && list[0].items_hash || '').trim(); + const [ countRows ] = await connection.query( + `SELECT COUNT(1) AS cnt FROM wms_order_delivery_100000 + WHERE items_hash = ? AND wave_id = 0 AND step != 0 AND post_status = 'fin' + AND storage_status = 'fin' AND print_status != 'fin' AND status != 'cancel' + AND outbound_status != 'padding' AND intercept_status = 'none' AND lock_status = 'none'`, + [ groupHash ] + ); + const totalCount = Number(countRows && countRows[0] && countRows[0].cnt || 0); + if (totalCount >= KEEP_COUNT && totalCount <= 12) { + keepGroup = list; + console.log(`[3] 选中保留组: hash=${groupHash.slice(0, 12)} 同结构总数=${totalCount}`); + break; + } + } + if (!keepGroup) { + console.log('未找到同结构总数 8~12 的今日前分组'); + keepGroup = beforeToday.slice(0, KEEP_COUNT); + } + const keepIds = keepGroup.slice(0, KEEP_COUNT).map(row => Number(row.id)); + const keepSet = new Set(keepIds); + const moveIds = rows.map(row => Number(row.id)).filter(id => !keepSet.has(id)); + + if (moveIds.length > 0) { + const [ updateResult ] = await connection.query( + `UPDATE wms_order_delivery_100000 SET create_at = ? WHERE id IN (?)`, + [ TODAY_TIME, moveIds ] + ); + console.log(`[3] 保留今日前订单 ${keepIds.length} 条: [${keepIds.join(', ')}]`); + console.log(`[3] 其余 ${updateResult.affectedRows} 条已改为今天 ${TODAY_TIME}`); + } + + // 4. 第一轮抓取 + const firstTaskId = await fetchOnce(token, 1); + const firstOrders = await readTaskOrders(connection, firstTaskId); + const firstBeforeToday = firstOrders.filter(row => new Date(row.create_at).getTime() < TODAY_START_UTC); + const firstPassed = firstOrders.length === KEEP_COUNT && firstBeforeToday.length === KEEP_COUNT; + console.log(`[4] 第一轮任务 ${firstTaskId} 抓取订单数: ${firstOrders.length}`); + console.log(` 今日前订单数: ${firstBeforeToday.length}, 订单ID: [${firstOrders.map(row => row.id).join(', ')}]`); + console.log(` 验证(不足20不填充): ${firstPassed ? '✅ 仅抓 8 条今日前订单,未用今天订单填充' : '❌ 行为与预期不符'}`); + + // 5. 第二轮抓取 + const secondTaskId = await fetchOnce(token, 2); + const secondOrders = await readTaskOrders(connection, secondTaskId); + const secondToday = secondOrders.filter(row => new Date(row.create_at).getTime() >= TODAY_START_UTC); + const secondPassed = secondOrders.length === 20 && secondToday.length === 20; + console.log(`[5] 第二轮任务 ${secondTaskId} 抓取订单数: ${secondOrders.length}`); + console.log(` 今天订单数: ${secondToday.length}, 订单ID: [${secondOrders.map(row => row.id).join(', ')}]`); + console.log(` 验证(第一池清空后抓满20条今天订单): ${secondPassed ? '✅ 回落第二池并抓满 20' : '❌ 行为与预期不符'}`); + + console.log('==================== 总结 ===================='); + console.log(`第一轮(第一池8条): 实际 ${firstOrders.length} 条 -> ${firstPassed ? 'PASS' : 'FAIL'}`); + console.log(`第二轮(第二池今天): 实际 ${secondOrders.length} 条 -> ${secondPassed ? 'PASS' : 'FAIL'}`); + console.log(`结论: ${firstPassed && secondPassed ? '✅ 边界行为符合预期: 不足20不填充;第一池抓完才抓第二池' : '❌ 存在与预期不符的环节,请排查'}`); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`验证失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-verify-wave-pool-boundary3.cjs b/script/tmp-verify-wave-pool-boundary3.cjs new file mode 100644 index 0000000..a914e3a --- /dev/null +++ b/script/tmp-verify-wave-pool-boundary3.cjs @@ -0,0 +1,190 @@ +'use strict'; + +/** + * 边界验证(数据已由 tmp-prepare-wave-pool-boundary3 构造): + * 第一池=8 条今日前订单(c51053111531 组),其余候选为今天订单。 + * 验证:第一轮仅抓 8 条今日前(不填充到 20);第二轮回落第二池抓满 20 条今天订单。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +const BASE_URL = 'http://127.0.0.1:6060'; +const DB_CONFIG = { + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', +}; +const TODAY_START_UTC = Date.UTC(2026, 8, 5, 16, 0, 0); // 2026-09-06 00:00 +08:00 + +/** + * 发送 /system POST 请求。 + * + * @param {string} token 登录令牌。 + * @param {string} method 方法名。 + * @param {Object} data 请求体。 + * @return {Promise} 响应 JSON。 + */ +async function sysCall(token, method, data) { + const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`; + const headers = { + 'Content-Type': 'application/json', + platform: 'web', + project: 'wms', + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }; + const res = await fetch(`${BASE_URL}/system?${qs}`, { + method: 'POST', + headers, + body: JSON.stringify(data), + }); + const text = await res.text(); + try { + return JSON.parse(text); + } catch (error) { + return { raw: text }; + } +} + +/** + * 深度优先查找对象中第一个匹配 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 {string} token 登录令牌。 + * @param {number} round 轮次。 + * @return {Promise} 任务 ID。 + */ +async function fetchOnce(token, round) { + const res = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 }); + let state = Number(deepFind(res, 'fetch_state') || 0); + let taskId = Number(deepFind(res, 'task_id') || 0); + if (state === 3 && taskId > 0) { + await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: taskId }); + const retry = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 }); + state = Number(deepFind(retry, 'fetch_state') || 0); + taskId = Number(deepFind(retry, 'task_id') || 0); + } + if (state !== 1 || taskId <= 0) { + throw new Error(`第${round}轮抓取失败: state=${state}`); + } + return taskId; +} + +/** + * 读取任务抓取订单的 create_at。 + * + * @param {Object} connection 数据库连接。 + * @param {number} taskId 任务 ID。 + * @return {Promise>} 订单行。 + */ +async function readTaskOrders(connection, taskId) { + const [ taskOrderRows ] = await connection.query( + `SELECT order_id FROM wms_wave_pick_task_order WHERE task_id = ? ORDER BY box_no ASC`, + [ taskId ] + ); + const orderIds = taskOrderRows.map(row => Number(row.order_id)); + if (orderIds.length === 0) { + return []; + } + const [ orderRows ] = await connection.query( + `SELECT id, create_at FROM wms_order_delivery_100000 WHERE id IN (?) ORDER BY id ASC`, + [ orderIds ] + ); + return orderRows; +} + +/** + * 主流程入口。 + * + * @return {Promise} + */ +async function main() { + const login = await sysCall(null, 'user.login', { + username: 'liufumingren', + password: '111111', + }); + const token = deepFind(login, 'token'); + if (!token) { + throw new Error(`登录失败: ${JSON.stringify(login)}`); + } + console.log('[1] 登录成功'); + + const connection = await mysql.createConnection(DB_CONFIG); + try { + const [ activeTasks ] = await connection.query( + `SELECT id FROM wms_wave_pick_task WHERE warehouse_id = 100000 AND status IN (0, 1)` + ); + for (const row of activeTasks) { + await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: Number(row.id) }); + } + console.log(`[2] 已取消活跃任务: [${activeTasks.map(row => row.id).join(', ')}]`); + + // 第一轮 + const firstTaskId = await fetchOnce(token, 1); + const firstOrders = await readTaskOrders(connection, firstTaskId); + const firstBeforeToday = firstOrders.filter(row => new Date(row.create_at).getTime() < TODAY_START_UTC); + const firstPassed = firstOrders.length === 8 && firstBeforeToday.length === 8; + console.log(`[3] 第一轮任务 ${firstTaskId} 抓取订单数: ${firstOrders.length}`); + console.log(` 今日前订单数: ${firstBeforeToday.length}, 订单ID: [${firstOrders.map(row => row.id).join(', ')}]`); + console.log(` 验证(不足20不填充): ${firstPassed ? '✅ 仅抓 8 条今日前订单,未用今天订单填充' : '❌ 行为与预期不符'}`); + + // 第二轮 + const secondTaskId = await fetchOnce(token, 2); + const secondOrders = await readTaskOrders(connection, secondTaskId); + const secondToday = secondOrders.filter(row => new Date(row.create_at).getTime() >= TODAY_START_UTC); + const secondPassed = secondOrders.length === 20 && secondToday.length === 20; + console.log(`[4] 第二轮任务 ${secondTaskId} 抓取订单数: ${secondOrders.length}`); + console.log(` 今天订单数: ${secondToday.length}, 订单ID: [${secondOrders.map(row => row.id).join(', ')}]`); + console.log(` 验证(第一池清空后抓满20条今天订单): ${secondPassed ? '✅ 回落第二池并抓满 20' : '❌ 行为与预期不符'}`); + + console.log('==================== 总结 ===================='); + console.log(`第一轮(第一池8条): 实际 ${firstOrders.length} 条 -> ${firstPassed ? 'PASS' : 'FAIL'}`); + console.log(`第二轮(第二池今天): 实际 ${secondOrders.length} 条 -> ${secondPassed ? 'PASS' : 'FAIL'}`); + console.log(`结论: ${firstPassed && secondPassed ? '✅ 边界行为符合预期: 不足20不填充;第一池抓完才抓第二池' : '❌ 存在与预期不符的环节,请排查'}`); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`验证失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-verify-wave-pool-priority.cjs b/script/tmp-verify-wave-pool-priority.cjs new file mode 100644 index 0000000..2854f8e --- /dev/null +++ b/script/tmp-verify-wave-pool-priority.cjs @@ -0,0 +1,170 @@ +'use strict'; + +/** + * 订单池分割验证:抓取并验证「今日前订单优先、不掺入今天订单」。 + * + * 流程: + * 1. 登录测试账号; + * 2. 取消当前活跃任务(wavePickTaskCancelSelf,若存在); + * 3. waveStrategyFetchPda 按策略 7 抓取(batch_max_orders=20); + * 4. 从库中读取新任务抓取的订单,校验 create_at 全部早于今日 0 点。 + * + * @return {Promise} + */ + +const mysql = require('mysql2/promise'); + +const BASE_URL = 'http://127.0.0.1:6060'; +const DB_CONFIG = { + host: '127.0.0.1', + port: 3307, + user: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', +}; + +/** + * 发送 /system POST 请求。 + * + * @param {string} token 登录令牌。 + * @param {string} method 方法名。 + * @param {Object} data 请求体。 + * @return {Promise} 响应 JSON。 + */ +async function sysCall(token, method, data) { + const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`; + const headers = { + 'Content-Type': 'application/json', + platform: 'web', + project: 'wms', + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }; + const res = await fetch(`${BASE_URL}/system?${qs}`, { + method: 'POST', + headers, + body: JSON.stringify(data), + }); + const text = await res.text(); + try { + return JSON.parse(text); + } catch (error) { + return { raw: text }; + } +} + +/** + * 深度优先查找对象中第一个匹配 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; +} + +/** + * 主流程入口。 + * + * @return {Promise} + */ +async function main() { + const login = await sysCall(null, 'user.login', { + username: 'liufumingren', + password: '111111', + }); + const token = deepFind(login, 'token'); + if (!token) { + throw new Error(`登录失败: ${JSON.stringify(login)}`); + } + console.log('[1] 登录成功'); + + // 取消活跃任务 260(若存在) + const cancelRes = await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: 260 }); + console.log(`[2] 取消任务260响应: ${JSON.stringify(cancelRes).slice(0, 200)}`); + + // 按策略 7 抓取 + const fetchRes = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 }); + console.log(`[3] 抓取响应: ${JSON.stringify(fetchRes).slice(0, 600)}`); + const fetchState = Number(deepFind(fetchRes, 'fetch_state') || 0); + const taskId = Number(deepFind(fetchRes, 'task_id') || 0); + if (fetchState !== 1 || taskId <= 0) { + throw new Error(`抓取未创建新任务: fetch_state=${fetchState}`); + } + + // 从库读取该任务订单 + const connection = await mysql.createConnection(DB_CONFIG); + try { + const [ taskOrderRows ] = await connection.query( + `SELECT order_id, wave_id, box_no + FROM wms_wave_pick_task_order + WHERE task_id = ? + ORDER BY box_no ASC`, + [ taskId ] + ); + const orderIds = taskOrderRows.map(row => Number(row.order_id)); + console.log(`[4] 任务 ${taskId} 抓取订单数: ${orderIds.length}`); + console.log(` 订单ID: [${orderIds.join(', ')}]`); + + if (orderIds.length === 0) { + throw new Error('任务未关联任何订单'); + } + + const [ orderRows ] = await connection.query( + `SELECT id, create_at + FROM wms_order_delivery_100000 + WHERE id IN (?) + ORDER BY id ASC`, + [ orderIds ] + ); + + // 今日 0 点(+08:00):2026-09-06 00:00 本地 + const todayStart = Date.UTC(2026, 8, 5, 16, 0, 0); + const todayOrderIds = orderRows + .filter(row => new Date(row.create_at).getTime() >= todayStart) + .map(row => Number(row.id)); + const beforeTodayCount = orderRows.length - todayOrderIds.length; + + console.log('===== 验证结果 ====='); + console.log(`任务抓取订单总数: ${orderRows.length}`); + console.log(`其中今日前订单数: ${beforeTodayCount}`); + console.log(`其中今天订单数: ${todayOrderIds.length}`); + if (todayOrderIds.length > 0) { + console.log(`混入的今天订单ID: [${todayOrderIds.join(', ')}]`); + } + const passed = beforeTodayCount === orderRows.length && orderRows.length > 0; + console.log(`结论: ${passed ? '✅ 今日前订单优先出库验证通过,抓取未掺入今天订单' : '❌ 抓取掺入了今天订单,池分割未生效'}`); + } finally { + await connection.end(); + } +} + +main().catch(error => { + console.error(`验证失败: ${error.message}`); + process.exit(1); +}); diff --git a/script/tmp-watch-report-delivery.cjs b/script/tmp-watch-report-delivery.cjs new file mode 100644 index 0000000..207454d --- /dev/null +++ b/script/tmp-watch-report-delivery.cjs @@ -0,0 +1,100 @@ +'use strict'; + +/** + * 临时观察脚本:轮询开发库投递记录,等待指定时间点的报表投递完成并打印结果。 + * + * 作用:设置新投递时间点后无人值守地等结果(到点自动投递 → 打印 status/文件名/下载链接/错误)。 + * 只读(仅 SELECT),不修改任何数据。 + * + * 用法:node script/tmp-watch-report-delivery.cjs [timePoint] [timeoutSeconds] + * 默认 timePoint=20:25、timeout=900 秒(15 分钟) + */ +const path = require('node:path'); +const { createRequire } = require('node:module'); + +const projectRoot = path.resolve(__dirname, '..'); +const projectRequire = createRequire(path.join(projectRoot, 'package.json')); +const mysql = projectRequire('mysql2/promise'); + +const TIME_POINT = process.argv[2] || '20:25'; +const TIMEOUT_SECONDS = Number(process.argv[3] || 900); +const TARGET_DEFINITION_IDS = [ 1, 3 ]; +const POLL_INTERVAL_MS = 10000; + +/** + * 读取开发库连接配置。 + * @return {Object} mysql 连接参数 + */ +function loadDevDbConfig() { + const factory = require(path.join(projectRoot, 'config', 'config.local.js')); + const config = typeof factory === 'function' ? factory({ name: 'tmp-watch-delivery', baseDir: projectRoot }) : factory; + const client = config && config.mysql && config.mysql.clients && config.mysql.clients.wms; + if (!client || !client.host) { + throw new Error('无法解析开发库配置 config.local.js(mysql.clients.wms)'); + } + return { + host: client.host, + port: Number(client.port), + user: client.user, + password: client.password, + database: client.database, + charset: client.charset || 'utf8mb4', + }; +} + +(async () => { + const connection = await mysql.createConnection(loadDevDbConfig()); + const deadline = Date.now() + TIMEOUT_SECONDS * 1000; + console.log(`[watch] 等待 time_point=${TIME_POINT} 的投递(定义 ${TARGET_DEFINITION_IDS.join('/')}),超时 ${TIMEOUT_SECONDS}s`); + + try { + for (;;) { + const [ rows ] = await connection.query( + `SELECT id, store_id, report_definition_id, report_name, biz_date, time_point, status, + retry_count, error_message, delivered_at, file_url + FROM wms_report_delivery_log + WHERE time_point = ? + AND report_definition_id IN (${TARGET_DEFINITION_IDS.map(() => '?').join(',')}) + ORDER BY report_definition_id`, + [ TIME_POINT, ...TARGET_DEFINITION_IDS ] + ); + + const list = Array.isArray(rows) ? rows : []; + const pending = list.filter(row => [ 'pending', 'exporting' ].includes(String(row.status))); + const terminal = list.filter(row => [ 'delivered', 'failed', 'cancelled' ].includes(String(row.status))); + + if (list.length > 0) { + console.log(`[watch] ${new Date().toLocaleTimeString('zh-CN', { hour12: false })} 记录 ${list.length} 条(终态 ${terminal.length})`); + } + + if (terminal.length >= TARGET_DEFINITION_IDS.length || (list.length > 0 && pending.length === 0)) { + for (const row of list) { + console.log( + `\n[结果] 定义=${row.report_definition_id}(${row.report_name})` + + `\n status=${row.status} biz_date=${row.biz_date} time_point=${row.time_point}` + + `\n retry_count=${row.retry_count}` + + `\n delivered_at=${row.delivered_at || '(空)'}` + + `\n 文件=${row.file_url || '(空)'}` + + (row.error_message ? `\n 错误=${row.error_message}` : '') + ); + } + process.exit(0); + } + + if (Date.now() >= deadline) { + console.log(`\n[watch] 等待超时(${TIMEOUT_SECONDS}s),当前命中 ${list.length} 条记录`); + for (const row of list) { + console.log(` 定义=${row.report_definition_id} status=${row.status} 文件=${row.file_url || '(空)'} 错误=${row.error_message || '(空)'}`); + } + process.exit(list.length > 0 ? 0 : 1); + } + + await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS)); + } + } finally { + await connection.end(); + } +})().catch(error => { + console.error('[watch] 执行异常:', error && error.message ? error.message : error); + process.exit(1); +});