From c6224b471eae87688cd354079bf2eea3e9822072 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 20 Sep 2026 16:14:10 +0800 Subject: [PATCH] =?UTF-8?q?chore(script):=20=E4=B8=B4=E6=97=B6=E8=84=9A?= =?UTF-8?q?=E6=9C=AC=E7=A7=BB=E5=85=A5=20temp=20=E7=9B=AE=E5=BD=95?= =?UTF-8?q?=EF=BC=88gitignore=20=E8=8C=83=E5=9B=B4=EF=BC=8C=E9=80=80?= =?UTF-8?q?=E5=87=BA=E7=89=88=E6=9C=AC=E6=8E=A7=E5=88=B6=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- script/tmp-check-barcodes.cjs | 23 - ...mp-check-batch-no-array-backfill-scope.cjs | 51 -- script/tmp-check-claim-backfill-source.cjs | 55 -- script/tmp-check-claim-backfill-source2.cjs | 48 -- script/tmp-check-hidden-tables.cjs | 42 -- script/tmp-check-inbox-intercept-guard.cjs | 118 ---- 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-pending-migrations.cjs | 87 --- script/tmp-check-pick-mode-backfill-scope.cjs | 64 -- script/tmp-check-policy.cjs | 15 - script/tmp-check-role-permission.cjs | 12 - script/tmp-check-storage-rows.cjs | 28 - script/tmp-check-storage-stock.cjs | 41 -- 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-pick-task-mode.cjs | 75 --- script/tmp-check-wave-pick-task-mode2.cjs | 68 -- script/tmp-check-wave-pick-task-mode3.cjs | 76 --- script/tmp-check-wave-strategy7-pool.cjs | 89 --- script/tmp-check-wms-test-bootstrap.cjs | 53 -- script/tmp-clear-user-cache.cjs | 13 - script/tmp-compare-order-schema.cjs | 173 ----- script/tmp-explore-putaway-test-data.cjs | 58 -- script/tmp-gen-service-method-inventory.cjs | 99 --- .../tmp-generate-method-regression-test.cjs | 116 ---- script/tmp-init-qimen-methods.cjs | 194 ------ 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-push-inbox-robot-intercept.cjs | 318 --------- script/tmp-repro-first-pool-query.cjs | 78 --- script/tmp-show-last-release.cjs | 28 - script/tmp-struct-system-params.cjs | 421 ------------ script/tmp-test-clean-plan.cjs | 60 -- script/tmp-test-putaway-batch-compare.cjs | 136 ---- script/tmp-test-putaway-compare.cjs | 261 -------- script/tmp-test-putaway-full-compare.cjs | 281 -------- script/tmp-test-stockreport-fix-dev.cjs | 632 ------------------ script/tmp-trace-wave-closure-cause.cjs | 25 - script/tmp-unbind-prod-cart.cjs | 104 --- script/tmp-update-ai-method-routing.cjs | 30 - script/tmp-verify-all-tables.cjs | 103 --- script/tmp-verify-batch-no-array.cjs | 37 - script/tmp-verify-claim-operator.cjs | 39 -- script/tmp-verify-intercept-order-dev.cjs | 228 ------- script/tmp-verify-pick-task-claim.cjs | 39 -- script/tmp-verify-pool-after-complete.cjs | 151 ----- script/tmp-verify-pool-full-flow.cjs | 234 ------- script/tmp-verify-report-edge-sql.cjs | 341 ---------- 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 --- script/tmp-wave-edge-pick-http-test.cjs | 527 --------------- 63 files changed, 7709 deletions(-) delete mode 100644 script/tmp-check-barcodes.cjs delete mode 100644 script/tmp-check-batch-no-array-backfill-scope.cjs delete mode 100644 script/tmp-check-claim-backfill-source.cjs delete mode 100644 script/tmp-check-claim-backfill-source2.cjs delete mode 100644 script/tmp-check-hidden-tables.cjs delete mode 100644 script/tmp-check-inbox-intercept-guard.cjs delete mode 100644 script/tmp-check-keep8-status.cjs delete mode 100644 script/tmp-check-negative-order.cjs delete mode 100644 script/tmp-check-order-table-rebuild-log.cjs delete mode 100644 script/tmp-check-other-platform-express.cjs delete mode 100644 script/tmp-check-pending-migrations.cjs delete mode 100644 script/tmp-check-pick-mode-backfill-scope.cjs delete mode 100644 script/tmp-check-policy.cjs delete mode 100644 script/tmp-check-role-permission.cjs delete mode 100644 script/tmp-check-storage-rows.cjs delete mode 100644 script/tmp-check-storage-stock.cjs delete mode 100644 script/tmp-check-update-scope.cjs delete mode 100644 script/tmp-check-video-record-request.cjs delete mode 100644 script/tmp-check-wave-closure-log.cjs delete mode 100644 script/tmp-check-wave-pick-debug.cjs delete mode 100644 script/tmp-check-wave-pick-debug2.cjs delete mode 100644 script/tmp-check-wave-pick-task-mode.cjs delete mode 100644 script/tmp-check-wave-pick-task-mode2.cjs delete mode 100644 script/tmp-check-wave-pick-task-mode3.cjs delete mode 100644 script/tmp-check-wave-strategy7-pool.cjs delete mode 100644 script/tmp-check-wms-test-bootstrap.cjs delete mode 100644 script/tmp-clear-user-cache.cjs delete mode 100644 script/tmp-compare-order-schema.cjs delete mode 100644 script/tmp-explore-putaway-test-data.cjs delete mode 100644 script/tmp-gen-service-method-inventory.cjs delete mode 100644 script/tmp-generate-method-regression-test.cjs delete mode 100644 script/tmp-init-qimen-methods.cjs delete mode 100644 script/tmp-prepare-wave-pool-boundary.cjs delete mode 100644 script/tmp-prepare-wave-pool-boundary3.cjs delete mode 100644 script/tmp-prepare-wave-pool-today-orders.cjs delete mode 100644 script/tmp-push-inbox-robot-intercept.cjs delete mode 100644 script/tmp-repro-first-pool-query.cjs delete mode 100644 script/tmp-show-last-release.cjs delete mode 100644 script/tmp-struct-system-params.cjs delete mode 100644 script/tmp-test-clean-plan.cjs delete mode 100644 script/tmp-test-putaway-batch-compare.cjs delete mode 100644 script/tmp-test-putaway-compare.cjs delete mode 100644 script/tmp-test-putaway-full-compare.cjs delete mode 100644 script/tmp-test-stockreport-fix-dev.cjs delete mode 100644 script/tmp-trace-wave-closure-cause.cjs delete mode 100644 script/tmp-unbind-prod-cart.cjs delete mode 100644 script/tmp-update-ai-method-routing.cjs delete mode 100644 script/tmp-verify-all-tables.cjs delete mode 100644 script/tmp-verify-batch-no-array.cjs delete mode 100644 script/tmp-verify-claim-operator.cjs delete mode 100644 script/tmp-verify-intercept-order-dev.cjs delete mode 100644 script/tmp-verify-pick-task-claim.cjs delete mode 100644 script/tmp-verify-pool-after-complete.cjs delete mode 100644 script/tmp-verify-pool-full-flow.cjs delete mode 100644 script/tmp-verify-report-edge-sql.cjs delete mode 100644 script/tmp-verify-report-plan-2-preview.cjs delete mode 100644 script/tmp-verify-stockreport-edge-prod.cjs delete mode 100644 script/tmp-verify-wave-pool-boundary.cjs delete mode 100644 script/tmp-verify-wave-pool-boundary2.cjs delete mode 100644 script/tmp-verify-wave-pool-boundary3.cjs delete mode 100644 script/tmp-verify-wave-pool-priority.cjs delete mode 100644 script/tmp-watch-report-delivery.cjs delete mode 100644 script/tmp-wave-edge-pick-http-test.cjs diff --git a/script/tmp-check-barcodes.cjs b/script/tmp-check-barcodes.cjs deleted file mode 100644 index 26a92fe..0000000 --- a/script/tmp-check-barcodes.cjs +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; -const mysql = require('mysql2/promise'); -(async () => { - const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); - - // bindDetailProduct 自动写入的条码(本次测试的 TMPBC/FULLBC 前缀) - const [barcodes] = await c.query(` - SELECT id, stock_id, warehouse_id, barcode - FROM wms_stock_barcodes - WHERE barcode LIKE 'TMPBC%' OR barcode LIKE 'FULLBC%' - ORDER BY id`); - console.log('== wms_stock_barcodes 测试写入的条码(共 ' + barcodes.length + ' 行) =='); - console.log(JSON.stringify(barcodes, null, 2)); - - // 商品 159061/159064 上的全部条码 - const [all] = await c.query( - `SELECT id, stock_id, barcode FROM wms_stock_barcodes WHERE stock_id IN (159061, 159064) ORDER BY id` - ); - console.log('== 两商品全部条码 =='); - console.log(JSON.stringify(all, null, 2)); - await c.end(); - process.exit(0); -})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-batch-no-array-backfill-scope.cjs b/script/tmp-check-batch-no-array-backfill-scope.cjs deleted file mode 100644 index 59b0201..0000000 --- a/script/tmp-check-batch-no-array-backfill-scope.cjs +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -/** - * 回填 wms_wave_pick_task.batch_no_array(生产只读预检)。 - * - * 从 wms_wave_pick_task_wave 按 task_id 聚合 wave_no(逗号分隔,按 id 升序), - * 只更新 batch_no_array IS NULL 的任务,幂等可重复执行。 - */ - -const dbConfig = require('../database/config.js'); -const Sequelize = require('sequelize'); - -(async () => { - const cfg = dbConfig.production; - const s = new Sequelize(cfg.database, cfg.username, cfg.password, { - host: cfg.host, - port: cfg.port, - dialect: cfg.dialect || 'mysql', - logging: false, - }); - - const q = async (sql, repl) => { - const rows = await s.query(sql, { replacements: repl, type: Sequelize.QueryTypes.SELECT }); - return Array.isArray(rows) ? rows : []; - }; - - const total = await q('SELECT COUNT(*) AS c FROM wms_wave_pick_task'); - console.log('A. 任务总数:', JSON.stringify(total)); - - const nullable = await q("SELECT COUNT(*) AS c FROM wms_wave_pick_task WHERE batch_no_array IS NULL OR batch_no_array = ''"); - console.log('B. batch_no_array 为空的任务数:', JSON.stringify(nullable)); - - const backfillable = await q( - "SELECT COUNT(DISTINCT tw.task_id) AS c FROM wms_wave_pick_task_wave tw " - + "INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id " - + "WHERE tw.wave_no IS NOT NULL AND tw.wave_no <> '' " - + "AND (t.batch_no_array IS NULL OR t.batch_no_array = '')" - ); - console.log('C. 可回填的任务数(有 wave 记录且 batch_no_array 为空):', JSON.stringify(backfillable)); - - const byWaveRows = await q( - "SELECT task_id, COUNT(*) AS c FROM wms_wave_pick_task_wave " - + "WHERE wave_no IS NOT NULL AND wave_no <> '' GROUP BY task_id ORDER BY c DESC LIMIT 5" - ); - console.log('D. 单任务最多波次记录数样例:', JSON.stringify(byWaveRows)); - - await s.close(); -})().catch(e => { - console.error('ERROR:', e.message); - process.exit(1); -}); diff --git a/script/tmp-check-claim-backfill-source.cjs b/script/tmp-check-claim-backfill-source.cjs deleted file mode 100644 index 5d5840f..0000000 --- a/script/tmp-check-claim-backfill-source.cjs +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -/** - * 临时核验脚本:核实生产库历史任务的领料人回填来源。 - * 1) wms_wave_batch 波次表 claim 字段现状; - * 2) order_operation_log 中 ORDER_WAVE_CLAIM 领料日志数量与样例。 - */ - -const dbConfig = require('../database/config.js'); -const Sequelize = require('sequelize'); - -(async () => { - const cfg = dbConfig.production; - const s = new Sequelize(cfg.database, cfg.username, cfg.password, { - host: cfg.host, - port: cfg.port, - dialect: cfg.dialect || 'mysql', - logging: false, - }); - - const q = async sql => { - const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT }); - return Array.isArray(rows) ? rows : []; - }; - - const waveClaim = await q( - "SELECT wave_id, wave_no, claim_operator, claim_time FROM wms_wave_batch " - + "WHERE wave_no IN ('B2026081500040','B2026081500038','B2026081500084','B2026081500075','B2026081500023','B2026081500022','B2026081500085') " - + "ORDER BY wave_id DESC" - ); - console.log('A. 波次表 claim 现状:', JSON.stringify(waveClaim, null, 2)); - - const claimLogTotal = await q( - "SELECT COUNT(*) AS c FROM order_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM'" - ); - console.log('B. 领料日志总数:', JSON.stringify(claimLogTotal)); - - const claimLogSample = await q( - "SELECT id, business_id, operation_code, operator_id, operator_name, message, create_time " - + "FROM order_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM' " - + "ORDER BY id DESC LIMIT 10" - ); - console.log('C. 领料日志最近10条:', JSON.stringify(claimLogSample, null, 2)); - - const taskClaim = await q( - "SELECT id, task_no, pick_mode, source, claim_operator_id, claim_operator FROM wms_wave_pick_task " - + "WHERE id IN (259, 251, 229) ORDER BY id DESC" - ); - console.log('D. 任务表 claim 现状:', JSON.stringify(taskClaim, null, 2)); - - await s.close(); -})().catch(e => { - console.error('ERROR:', e.message); - process.exit(1); -}); diff --git a/script/tmp-check-claim-backfill-source2.cjs b/script/tmp-check-claim-backfill-source2.cjs deleted file mode 100644 index d307acb..0000000 --- a/script/tmp-check-claim-backfill-source2.cjs +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -/** - * 临时核验脚本 v2:核实生产库历史领料人回填来源(wms_operation_log)。 - */ - -const dbConfig = require('../database/config.js'); -const Sequelize = require('sequelize'); - -(async () => { - const cfg = dbConfig.production; - const s = new Sequelize(cfg.database, cfg.username, cfg.password, { - host: cfg.host, - port: cfg.port, - dialect: cfg.dialect || 'mysql', - logging: false, - }); - - const q = async sql => { - const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT }); - return Array.isArray(rows) ? rows : []; - }; - - const claimLogTotal = await q( - "SELECT COUNT(*) AS c, COUNT(DISTINCT warehouse_id) AS wh " - + "FROM wms_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM'" - ); - console.log('A. 领料日志总数/仓库数:', JSON.stringify(claimLogTotal)); - - const claimLogSample = await q( - "SELECT id, business_type, business_id, operation_code, operator_id, operator_name, message, warehouse_id, created_at " - + "FROM wms_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM' " - + "ORDER BY id DESC LIMIT 5" - ); - console.log('B. 领料日志最近5条:', JSON.stringify(claimLogSample, null, 2)); - - const claimLogByOperator = await q( - "SELECT operator_id, operator_name, COUNT(*) AS c FROM wms_operation_log " - + "WHERE operation_code = 'ORDER_WAVE_CLAIM' GROUP BY operator_id, operator_name " - + "ORDER BY c DESC LIMIT 10" - ); - console.log('C. 领料日志按操作人分布:', JSON.stringify(claimLogByOperator, null, 2)); - - await s.close(); -})().catch(e => { - console.error('ERROR:', e.message); - process.exit(1); -}); diff --git a/script/tmp-check-hidden-tables.cjs b/script/tmp-check-hidden-tables.cjs deleted file mode 100644 index cd9d13c..0000000 --- a/script/tmp-check-hidden-tables.cjs +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; -const mysql = require('mysql2/promise'); -(async () => { - const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); - - // 1. 请求日志表:本次重测 A(1530)/B(1531) 相关的接口调用日志 - const [sysLogs] = await c.query(` - SELECT id, method, v, store_id, use_time, LEFT(body, 120) AS body_snip, created_at - FROM wms_system_log - WHERE body LIKE '%R20688012%' OR body LIKE '%R20688013%' - OR body LIKE '%"receiving_id":1530%' OR body LIKE '%"receiving_id":1531%' - OR body LIKE '%"ids":[1530%' OR body LIKE '%"ids":[1531%' - OR body LIKE '%"entry_order_id":387%' OR body LIKE '%"entry_order_id":388%' - ORDER BY id`); - console.log('== wms_system_log 请求日志(本次重测相关,共 ' + sysLogs.length + ' 条) =='); - console.log(JSON.stringify(sysLogs, null, 2)); - - // 2. 通知发送日志表(失败才写) - const [notiLogs] = await c.query(` - SELECT id, trace_id, store_id, warehouse_id, business_name, event, status, http_status, created_at - FROM wms_notification_send_log - WHERE created_at >= DATE_SUB(NOW(), INTERVAL 2 DAY) - ORDER BY id DESC LIMIT 10`); - console.log('== wms_notification_send_log 最近两天(共 ' + notiLogs.length + ' 条) =='); - console.log(JSON.stringify(notiLogs, null, 2)); - - // 3. 商品资料异步补全相关(无图片/无重量时应无写入) - const [stockRow] = await c.query( - `SELECT id, is_images, gross_weight FROM wms_stock_warehouse WHERE id IN (159061, 159064)` - ); - console.log('== 商品资料快照(is_images/gross_weight,验证异步补全未触发) =='); - console.log(JSON.stringify(stockRow, null, 2)); - - const [fileRefs] = await c.query( - `SELECT id, business_type, business_id, file_id FROM wms_file_reference WHERE business_type='stock' AND business_id IN ('159061','159064')` - ); - console.log('== wms_file_reference(stock 类型,共 ' + fileRefs.length + ' 行) =='); - console.log(JSON.stringify(fileRefs, null, 2)); - - await c.end(); - process.exit(0); -})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-inbox-intercept-guard.cjs b/script/tmp-check-inbox-intercept-guard.cjs deleted file mode 100644 index 04040b5..0000000 --- a/script/tmp-check-inbox-intercept-guard.cjs +++ /dev/null @@ -1,118 +0,0 @@ -/** - * 临时校验:拦截规则防误判守卫(INTERCEPT_GUARD)修复效果。 - * 背景:机器人格式 "物流单号:SF123 拦截" 因含"物流"被守卫拦掉 → 规则未命中 → 静默不回信。 - * 用 fake ctx 直接实例化 inbox.rules Service,不连库、不写库。 - * 运行:node script/tmp-check-inbox-intercept-guard.cjs - */ -'use strict'; - -const RulesService = require('../app/service/inbox/rules'); - -function buildService(groupType, calls) { - const svc = Object.create(RulesService.prototype); - const registry = new Map([ - [ 'interceptWaybill', { groups: [ 'bound:store:after_sales' ] }], - [ 'cancelIntercept', { groups: [ 'bound:store:after_sales' ] }], - [ 'queryWeight', { groups: [ 'bound:store:after_sales' ] }], - [ 'changeAddr', { groups: [ 'bound:store:after_sales' ] }], - ]); - svc.ctx = { - inboxContext: { group_type: groupType }, - logger: { info() {}, warn() {}, error() {} }, - service: { - inbox: { - groups: { - resolveActiveGroups: () => [ 'bound:store:after_sales' ], - isFunctionAvailable: def => Array.isArray(def.groups) && def.groups.length > 0, - }, - functions: { - registry, - callFunction: async (fn, params) => { - calls.push({ fn, params }); - return { success: true, data: { direct_reply: true, message: `MOCK ${fn}` } }; - }, - }, - }, - }, - }; - return svc; -} - -const CASES = [ - // [说明, 正文, 期望是否已处理, 期望函数, 期望提取到的运单号(可选,'' 表示应为空)] - [ '机器人格式-物流单号+拦截', '优禾康官方旗舰店LSFJY202609143442\n物流单号:SF5151786672496 拦截', true, 'interceptWaybill' ], - [ '机器人格式-单号中间带空格', '罗斯福医疗器械专营店LSFJY202608307192\n物流单 号:SF5117392937919 拦截', true, 'interceptWaybill' ], - [ '机器人格式-物流二字被空格断开', '优禾康番茄健康监测专卖店LSFJY202609022796\n物 流单号:SF6048940605674 拦截', true, 'interceptWaybill' ], - [ '机器人格式-快递单号标签', '快递单号:SF5151786672496 拦截', true, 'interceptWaybill' ], - [ '普通拦截请求', '拦截 SF5151786672496', true, 'interceptWaybill' ], - [ '取消拦截(长词优先)', '取消拦截 SF5151786672496', true, 'cancelIntercept' ], - [ '查询物流到哪了(不应拦截)', '这个件拦截的物流到哪了 SF5151786672496', false, null ], - [ '标签外仍有物流查询词(不应拦截)', '物流单号:SF5151786672496 拦截,顺便查下这个物流到哪了', false, null ], - [ '查快递(无拦截词)', '帮我查快递 SF5151786672496 到哪了', false, null ], - [ '客服对话-物流显示签收+拦截有风险', '772077887170843:已登记退回,物流显示签收,已通知站点核实处理,因签收之后的包裹拦截有风险', false, null ], - [ '客服对话-物流轨迹查询', '麻烦看下这个件拦截了没有,物流轨迹一直没更新 SF5151786672496', false, null ], - [ '确认语静默', '好的', true, null ], - // 2026-09-15 回归:14 位纯数字运单号被“日期时间戳”过滤器误杀,规则只能回引导语 - [ '改地址+14位中通运单号(不应被日期戳过滤)', - '79140215263762 改地址 广东省广州市番禺区洛浦街道西三村友谊路1号菜鸟站(不打电话)收件人:王小姐19875119016', - true, 'changeAddr', '79140215263762' ], - [ '改地址+截断的11位手机号仍应被过滤(保留原行为)', - '改地址 19875119016', true, 'changeAddr', '' ], - [ '日期时间戳仍应被过滤(保留原行为)', - '改地址 20260914201201', true, 'changeAddr', '' ], -]; - -(async () => { - let pass = 0; - const fails = []; - for (const [ desc, text, expectHandled, expectFn, expectKeyword ] of CASES) { - const calls = []; - const svc = buildService('store', calls); - const res = await svc.handle(text); - const handled = !!res.handled; - const fn = res.fn || null; - const keyword = res.params && res.params.keyword != null ? String(res.params.keyword) : ''; - let ok = handled === expectHandled && fn === expectFn; - if (ok && expectKeyword !== undefined) { - ok = expectKeyword === '' ? keyword === '' : keyword.includes(expectKeyword); - } - if (ok) pass++; - else fails.push({ desc, expectHandled, expectFn, expectKeyword, handled, fn, keyword, silent: !!res.silent, calls }); - console.log( - `${ok ? '✅' : '❌'} ${desc} → handled=${handled} fn=${fn} silent=${!!res.silent} ` + - `keyword=${JSON.stringify(keyword)} ` + - `reply=${res.reply ? JSON.stringify(String(res.reply).slice(0, 40)) : '-'}` - ); - } - console.log(`\n结果:${pass}/${CASES.length} 通过`); - if (fails.length > 0) { - console.log('失败明细:', JSON.stringify(fails, null, 2)); - process.exitCode = 1; - } - - // ---- 生产群上下文模拟:真实分组解析 + 函数可用性(groups.js 为纯逻辑,不连库)---- - const GroupsService = require('../app/service/inbox/groups'); - const prodCtx = { - inboxContext: { - warehouse_id: 1000028, - store_id: 1000249, - group_type: 'store', - sub_type: 'after_sales', - group_id: '47357811653@chatroom', - }, - logger: { info() {}, warn() {}, error() {} }, - }; - const groupsSvc = Object.create(GroupsService.prototype); - groupsSvc.ctx = prodCtx; - const active = groupsSvc.resolveActiveGroups(); - const available = groupsSvc.isFunctionAvailable( - { groups: [ 'bound:warehouse:customer_service', 'bound:store:after_sales' ] }, - active - ); - console.log( - '\n生产群 47357811653@chatroom(store/after_sales/store_id=1000249) ' + - `activeGroups=${JSON.stringify(active)} interceptWaybill可用=${available}` - ); - if (!available) process.exitCode = 1; -})(); - diff --git a/script/tmp-check-keep8-status.cjs b/script/tmp-check-keep8-status.cjs deleted file mode 100644 index d6610d3..0000000 --- a/script/tmp-check-keep8-status.cjs +++ /dev/null @@ -1,47 +0,0 @@ -'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 deleted file mode 100644 index 70f700c..0000000 --- a/script/tmp-check-negative-order.cjs +++ /dev/null @@ -1,55 +0,0 @@ -'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 deleted file mode 100644 index 911b0d4..0000000 --- a/script/tmp-check-order-table-rebuild-log.cjs +++ /dev/null @@ -1,26 +0,0 @@ -'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 deleted file mode 100644 index 0d207c9..0000000 --- a/script/tmp-check-other-platform-express.cjs +++ /dev/null @@ -1,117 +0,0 @@ -'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-pending-migrations.cjs b/script/tmp-check-pending-migrations.cjs deleted file mode 100644 index 240e40f..0000000 --- a/script/tmp-check-pending-migrations.cjs +++ /dev/null @@ -1,87 +0,0 @@ -'use strict'; - -const fs = require('node:fs'); -const path = require('node:path'); -const Sequelize = require('sequelize'); - -const ROOT = path.resolve(__dirname, '..'); -const MIGRATIONS_DIR = path.join(ROOT, 'database', 'migrations'); - -async function main() { - // 1. 收集本地所有迁移文件 - const allFiles = fs.readdirSync(MIGRATIONS_DIR).filter(f => f.endsWith('.js')).sort(); - console.log(`[本地] 迁移文件总数: ${allFiles.length}`); - - // 2. 连接生产数据库 - const dbConfig = { - host: '112.124.21.102', - port: 3306, - user: 'wms', - password: 'P6j3YTHTpirepYWz', - database: 'wms', - }; - - const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, { - host: dbConfig.host, - port: dbConfig.port, - dialect: 'mysql', - logging: false, - }); - - try { - await sequelize.authenticate(); - console.log('[DB] 生产数据库连接成功'); - } catch (e) { - console.error('[DB] 生产数据库连接失败:', e.message); - process.exit(2); - } - - // 3. 检查 SequelizeMeta 表是否存在 - let appliedNames = []; - try { - const [rows] = await sequelize.query('SELECT name FROM SequelizeMeta ORDER BY name'); - appliedNames = rows.map(r => (typeof r === 'string' ? r : r.name)).filter(Boolean); - } catch (e) { - console.error('[DB] 读取 SequelizeMeta 失败:', e.message); - await sequelize.close(); - process.exit(2); - } - - console.log(`[DB] SequelizeMeta 已记录迁移数: ${appliedNames.length}`); - - // 4. 找出未执行的迁移 - const appliedSet = new Set(appliedNames); - const pending = allFiles.filter(f => !appliedSet.has(f)); - const archived = allFiles.filter(f => f.startsWith('archive/')); - - console.log(`\n========== 结果汇总 ==========`); - console.log(`本地迁移文件总数: ${allFiles.length}`); - console.log(`已执行 (SequelizeMeta): ${appliedNames.length}`); - console.log(`未执行 (pending): ${pending.length}`); - console.log(`===============================\n`); - - if (pending.length === 0) { - console.log('✅ 所有迁移脚本均已执行,无 pending migration。'); - } else { - console.log(`❌ 发现 ${pending.length} 个未执行的迁移脚本:\n`); - pending.forEach((f, i) => { - console.log(` ${String(i + 1).padStart(3, ' ')}. ${f}`); - }); - - // 额外检查:有没有本地没有但 DB 已记录的(可能被删除了) - const localSet = new Set(allFiles); - const orphanInDb = appliedNames.filter(n => !localSet.has(n)); - if (orphanInDb.length > 0) { - console.log(`\n⚠️ DB 中记录了 ${orphanInDb.length} 个本地已不存在的迁移(可能已被删除):`); - orphanInDb.forEach(n => console.log(` - ${n}`)); - } - } - - await sequelize.close(); - console.log('\n[DONE] 检查完成'); -} - -main().catch(err => { - console.error('脚本执行异常:', err); - process.exit(1); -}); diff --git a/script/tmp-check-pick-mode-backfill-scope.cjs b/script/tmp-check-pick-mode-backfill-scope.cjs deleted file mode 100644 index 4fc1939..0000000 --- a/script/tmp-check-pick-mode-backfill-scope.cjs +++ /dev/null @@ -1,64 +0,0 @@ -'use strict'; - -/** - * 临时脚本:影响范围确认(只读)—— - * wms_wave_pick_task WHERE pick_mode = 1 AND source = 2 的回填范围。 - */ - -const dbConfig = require('../database/config.js'); -const Sequelize = require('sequelize'); - -(async () => { - const cfg = dbConfig.production; - const s = new Sequelize(cfg.database, cfg.username, cfg.password, { - host: cfg.host, - port: cfg.port, - dialect: cfg.dialect || 'mysql', - logging: false, - }); - - const q = async sql => { - const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT }); - return Array.isArray(rows) ? rows : []; - }; - - const total = await q( - "SELECT COUNT(*) AS c FROM wms_wave_pick_task WHERE pick_mode = 1 AND source = 2" - ); - console.log('A. 目标行数 (pick_mode=1 AND source=2):', JSON.stringify(total)); - - const byStatus = await q( - 'SELECT status, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode = 1 AND source = 2 GROUP BY status ORDER BY status' - ); - console.log('B. 按任务状态分布:', JSON.stringify(byStatus)); - - const byWaveCount = await q( - 'SELECT wave_count, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode = 1 AND source = 2 GROUP BY wave_count ORDER BY wave_count' - ); - console.log('C. 按 wave_count 分布(确认单波次):', JSON.stringify(byWaveCount)); - - const byTaskNoPrefix = await q( - "SELECT LEFT(task_no, 2) AS prefix, COUNT(*) AS cnt FROM wms_wave_pick_task " - + "WHERE pick_mode = 1 AND source = 2 GROUP BY prefix" - ); - console.log('D. task_no 前缀分布(PK=拣货创建):', JSON.stringify(byTaskNoPrefix)); - - const waveRel = await q( - 'SELECT COUNT(*) AS c FROM wms_wave_pick_task t ' - + 'INNER JOIN wms_wave_pick_task_wave tw ON tw.task_id = t.id ' - + 'WHERE t.pick_mode = 1 AND t.source = 2' - ); - console.log('E. 目标任务中已有波次关联记录的任务数:', JSON.stringify(waveRel)); - - const noWaveRel = await q( - 'SELECT COUNT(*) AS c FROM wms_wave_pick_task t ' - + 'LEFT JOIN wms_wave_pick_task_wave tw ON tw.task_id = t.id ' - + 'WHERE t.pick_mode = 1 AND t.source = 2 AND tw.task_id IS NULL' - ); - console.log('F. 目标任务中无波次关联记录的任务数:', JSON.stringify(noWaveRel)); - - await s.close(); -})().catch(e => { - console.error('ERROR:', e.message); - process.exit(1); -}); diff --git a/script/tmp-check-policy.cjs b/script/tmp-check-policy.cjs deleted file mode 100644 index fb2ed32..0000000 --- a/script/tmp-check-policy.cjs +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; -const mysql = require('mysql2/promise'); -(async () => { - const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); - const [r] = await c.query( - `SELECT id, store_id, warehouse_id, warehouse_use_status, - JSON_EXTRACT(policy_config, '$.allow_receiving_direct_putaway') AS direct, - JSON_EXTRACT(policy_config, '$.allow_receiving_quick_putaway') AS quick - FROM wms_store_warehouse WHERE store_id = 1000000 AND warehouse_id = 100000` - ); - console.log('store_warehouse:', JSON.stringify(r, null, 2)); - const [r2] = await c.query('SELECT id, store_id, warehouse_id, status, is_review, storage_status FROM wms_receiving WHERE id IN (1521,1522,1523,1524)'); - console.log('receivings:', JSON.stringify(r2, null, 2)); - await c.end(); -})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-role-permission.cjs b/script/tmp-check-role-permission.cjs deleted file mode 100644 index d70fecb..0000000 --- a/script/tmp-check-role-permission.cjs +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; -const mysql = require('mysql2/promise'); -(async () => { - const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); - const [p] = await c.query("SELECT id, path, meta_title FROM wms_permission WHERE path LIKE 'storage.inventory%' AND type='api'"); - console.log('perms:', JSON.stringify(p)); - const [r] = await c.query('SELECT id, permissions FROM wms_role WHERE id IN (7)'); - console.log('roles:', JSON.stringify(r)); - const [col] = await c.query('SHOW COLUMNS FROM wms_role'); - console.log('cols:', col.map(x => x.Field + ':' + x.Type).join(', ')); - await c.end(); -})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-storage-rows.cjs b/script/tmp-check-storage-rows.cjs deleted file mode 100644 index 33a7542..0000000 --- a/script/tmp-check-storage-rows.cjs +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; -const mysql = require('mysql2/promise'); -(async () => { - const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); - - // 两个测试商品在 wms_storage 中的全部行 - const [rows] = await c.query(` - SELECT id, warehouse_id, store_id, space_id, stock_id, batch_no, inventory_type, - quantity, locked_quantity, available_quantity, - inbound_order_no, receiving_id, entry_order_id, inbound_time - FROM wms_storage - WHERE stock_id IN (159061, 159064) - ORDER BY id`); - console.log('== wms_storage 中两个测试商品的全部行(共 ' + rows.length + ' 行) =='); - console.log(JSON.stringify(rows, null, 2)); - - // 两商品的库位流水(逐笔证据) - const [txns] = await c.query(` - SELECT id, order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no - FROM wms_storage_transaction - WHERE stock_id IN (159061, 159064) - ORDER BY id`); - console.log('== wms_storage_transaction 两商品逐笔流水(共 ' + txns.length + ' 条) =='); - console.log(JSON.stringify(txns, null, 2)); - - await c.end(); - process.exit(0); -})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-storage-stock.cjs b/script/tmp-check-storage-stock.cjs deleted file mode 100644 index f3fa84d..0000000 --- a/script/tmp-check-storage-stock.cjs +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; -const mysql = require('mysql2/promise'); -(async () => { - const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); - - // 1. wms_storage 当前状态(A/B 共用的累加行) - const [storages] = await c.query(` - SELECT id, space_id, stock_id, batch_no, quantity, locked_quantity, available_quantity, - inbound_order_no, receiving_id, entry_order_id, inbound_time - FROM wms_storage WHERE id IN (408, 409)`); - console.log('== wms_storage 当前行(408/409) =='); - console.log(JSON.stringify(storages, null, 2)); - - // 2. wms_stock_warehouse 当前数量 - const [stocks] = await c.query(` - SELECT id, item_code, quantity, locked_quantity, is_valid - FROM wms_stock_warehouse WHERE id IN (159061, 159064)`); - console.log('== wms_stock_warehouse 当前数量 =='); - console.log(JSON.stringify(stocks, null, 2)); - - // 3. A(入库单 387)与 B(入库单 388)各自的库位流水(证明 storage 写入) - const [storageTxns] = await c.query(` - SELECT order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no - FROM wms_storage_transaction - WHERE order_id IN (387, 388) OR order_no IN ('SCRK202608240007','SCRK202608240008') - ORDER BY id`); - console.log('== wms_storage_transaction:A(387)/B(388) 的库位流水 =='); - console.log(JSON.stringify(storageTxns, null, 2)); - - // 4. A/B 各自的商品流水(证明 stock_warehouse 数量变更) - const [stockTxns] = await c.query(` - SELECT order_no, transaction_type, stock_id, quantity, before_quantity, after_quantity, entry_order_id - FROM wms_stock_transaction - WHERE entry_order_id IN (387, 388) OR order_no IN ('SCRK202608240007','SCRK202608240008') - ORDER BY id`); - console.log('== wms_stock_transaction:A(387)/B(388) 的商品流水 =='); - console.log(JSON.stringify(stockTxns, null, 2)); - - await c.end(); - process.exit(0); -})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-check-update-scope.cjs b/script/tmp-check-update-scope.cjs deleted file mode 100644 index dd20bc6..0000000 --- a/script/tmp-check-update-scope.cjs +++ /dev/null @@ -1,55 +0,0 @@ -'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 deleted file mode 100644 index 102a146..0000000 --- a/script/tmp-check-video-record-request.cjs +++ /dev/null @@ -1,63 +0,0 @@ -'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 deleted file mode 100644 index a03902d..0000000 --- a/script/tmp-check-wave-closure-log.cjs +++ /dev/null @@ -1,28 +0,0 @@ -'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 deleted file mode 100644 index cdd1e5d..0000000 --- a/script/tmp-check-wave-pick-debug.cjs +++ /dev/null @@ -1,65 +0,0 @@ -'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 deleted file mode 100644 index 6c3bb4c..0000000 --- a/script/tmp-check-wave-pick-debug2.cjs +++ /dev/null @@ -1,85 +0,0 @@ -'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-pick-task-mode.cjs b/script/tmp-check-wave-pick-task-mode.cjs deleted file mode 100644 index ddbcb91..0000000 --- a/script/tmp-check-wave-pick-task-mode.cjs +++ /dev/null @@ -1,75 +0,0 @@ -'use strict'; - -/** - * 临时核验脚本:核实生产库 wms_wave_pick_task 的 pick_mode / source / wave_count / - * batch_no 写入情况,以及团购任务(pick_mode=1/5)是否单波次。 - */ - -const dbConfig = require('../database/config.js'); -const Sequelize = require('sequelize'); - -(async () => { - const cfg = dbConfig.production; - const s = new Sequelize(cfg.database, cfg.username, cfg.password, { - host: cfg.host, - port: cfg.port, - dialect: cfg.dialect || 'mysql', - logging: false, - }); - - console.log('=== 1) 主表按 source/pick_mode 统计(batch_no / batch_no_array 非空数、wave_count 分布) ==='); - const [ rows1 ] = await s.query(` - SELECT t.source, - t.pick_mode, - COUNT(*) AS cnt, - SUM(t.batch_no IS NOT NULL AND t.batch_no <> '') AS with_batch_no, - SUM(t.batch_no_array IS NOT NULL AND t.batch_no_array <> '') AS with_batch_no_array, - MIN(t.wave_count) AS min_wave_count, - MAX(t.wave_count) AS max_wave_count - FROM wms_wave_pick_task t - GROUP BY t.source, t.pick_mode - ORDER BY t.source, t.pick_mode - `, { type: Sequelize.QueryTypes.SELECT }); - console.table(rows1); - - console.log('=== 2) 团购任务(pick_mode IN (1,5))与波次关联表记录数分布(判断单波次/多波次) ==='); - const [ rows2 ] = await s.query(` - SELECT t.source, - t.pick_mode, - t.wave_count, - COUNT(*) AS cnt - FROM wms_wave_pick_task t - WHERE t.pick_mode IN (1, 5) - GROUP BY t.source, t.pick_mode, t.wave_count - ORDER BY t.source, t.pick_mode, t.wave_count - `, { type: Sequelize.QueryTypes.SELECT }); - console.table(rows2); - - console.log('=== 3) 团购任务主表 wave_id 非空占比与 wave_count 实际值(抽样) ==='); - const [ rows3 ] = await s.query(` - SELECT t.id, t.task_no, t.source, t.pick_mode, t.wave_id, t.wave_count, t.batch_no, t.batch_no_array, - (SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows - FROM wms_wave_pick_task t - WHERE t.pick_mode IN (1, 5) - ORDER BY t.id DESC - LIMIT 20 - `, { type: Sequelize.QueryTypes.SELECT }); - console.table(rows3); - - console.log('=== 4) wms_wave_pick_task_wave 中单任务波次数 > 1 的任务(按 task_id 分组) ==='); - const [ rows4 ] = await s.query(` - SELECT tw.task_id, t.source, t.pick_mode, t.wave_count, COUNT(*) AS task_wave_rows - FROM wms_wave_pick_task_wave tw - INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id - GROUP BY tw.task_id, t.source, t.pick_mode, t.wave_count - HAVING COUNT(*) > 1 - ORDER BY tw.task_id DESC - LIMIT 20 - `, { type: Sequelize.QueryTypes.SELECT }); - console.table(rows4); - - await s.close(); -})().catch(e => { - console.error('ERROR:', e.message); - process.exit(1); -}); diff --git a/script/tmp-check-wave-pick-task-mode2.cjs b/script/tmp-check-wave-pick-task-mode2.cjs deleted file mode 100644 index 426f369..0000000 --- a/script/tmp-check-wave-pick-task-mode2.cjs +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -/** - * 临时核验脚本(v2):JSON 输出核实生产库 wms_wave_pick_task 的 - * pick_mode/source 分布与团购任务波次数。 - */ - -const dbConfig = require('../database/config.js'); -const Sequelize = require('sequelize'); - -(async () => { - const cfg = dbConfig.production; - const s = new Sequelize(cfg.database, cfg.username, cfg.password, { - host: cfg.host, - port: cfg.port, - dialect: cfg.dialect || 'mysql', - logging: false, - }); - - const [ total ] = await s.query('SELECT COUNT(*) AS c FROM wms_wave_pick_task', { type: Sequelize.QueryTypes.SELECT }); - console.log('A. 主表总数:', JSON.stringify(total)); - - const [ byMode ] = await s.query( - 'SELECT pick_mode, source, COUNT(*) AS cnt FROM wms_wave_pick_task GROUP BY pick_mode, source ORDER BY pick_mode, source', - { type: Sequelize.QueryTypes.SELECT } - ); - console.log('B. pick_mode/source 分布:', JSON.stringify(byMode)); - - const [ byWaveCount ] = await s.query( - 'SELECT pick_mode, wave_count, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode IN (1, 5) GROUP BY pick_mode, wave_count ORDER BY pick_mode, wave_count', - { type: Sequelize.QueryTypes.SELECT } - ); - console.log('C. 团购任务 wave_count 分布:', JSON.stringify(byWaveCount)); - - const [ multiWave ] = await s.query( - 'SELECT tw.task_id, t.pick_mode, t.source, t.wave_count, COUNT(*) AS task_wave_rows ' - + 'FROM wms_wave_pick_task_wave tw ' - + 'INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id ' - + 'GROUP BY tw.task_id, t.pick_mode, t.source, t.wave_count ' - + 'ORDER BY tw.task_id DESC LIMIT 10', - { type: Sequelize.QueryTypes.SELECT } - ); - console.log('D. 任务-波次关联(最近10条):', JSON.stringify(multiWave)); - - const [ taskWaveTotal ] = await s.query('SELECT COUNT(*) AS c FROM wms_wave_pick_task_wave', { type: Sequelize.QueryTypes.SELECT }); - console.log('E. 波次关联表总数:', JSON.stringify(taskWaveTotal)); - - const [ sampleGroup ] = await s.query( - "SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, " - + "(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows " - + "FROM wms_wave_pick_task t WHERE pick_mode = 1 ORDER BY id DESC LIMIT 10", - { type: Sequelize.QueryTypes.SELECT } - ); - console.log('F. 团购任务最近10条:', JSON.stringify(sampleGroup)); - - const [ sampleScatter ] = await s.query( - "SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, " - + "(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows " - + "FROM wms_wave_pick_task t WHERE pick_mode IN (2, 3, 4) ORDER BY id DESC LIMIT 10", - { type: Sequelize.QueryTypes.SELECT } - ); - console.log('G. 散单任务最近10条:', JSON.stringify(sampleScatter)); - - await s.close(); -})().catch(e => { - console.error('ERROR:', e.message); - process.exit(1); -}); diff --git a/script/tmp-check-wave-pick-task-mode3.cjs b/script/tmp-check-wave-pick-task-mode3.cjs deleted file mode 100644 index 8203119..0000000 --- a/script/tmp-check-wave-pick-task-mode3.cjs +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -/** - * 临时核验脚本(v3):修正 SELECT 结果解构,JSON 输出核实生产库 - * wms_wave_pick_task 的 pick_mode/source 分布与团购任务波次数。 - */ - -const dbConfig = require('../database/config.js'); -const Sequelize = require('sequelize'); - -(async () => { - const cfg = dbConfig.production; - const s = new Sequelize(cfg.database, cfg.username, cfg.password, { - host: cfg.host, - port: cfg.port, - dialect: cfg.dialect || 'mysql', - logging: false, - }); - - const q = async sql => { - const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT }); - return Array.isArray(rows) ? rows : []; - }; - - const total = await q('SELECT COUNT(*) AS c FROM wms_wave_pick_task'); - console.log('A. 主表总数:', JSON.stringify(total)); - - const byMode = await q( - 'SELECT pick_mode, source, COUNT(*) AS cnt FROM wms_wave_pick_task GROUP BY pick_mode, source ORDER BY pick_mode, source' - ); - console.log('B. pick_mode/source 分布:', JSON.stringify(byMode)); - - const byWaveCount = await q( - 'SELECT pick_mode, wave_count, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode IN (1, 5) GROUP BY pick_mode, wave_count ORDER BY pick_mode, wave_count' - ); - console.log('C. 团购任务 wave_count 分布:', JSON.stringify(byWaveCount)); - - const multiWave = await q( - 'SELECT tw.task_id, t.pick_mode, t.source, t.wave_count, COUNT(*) AS task_wave_rows ' - + 'FROM wms_wave_pick_task_wave tw ' - + 'INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id ' - + 'GROUP BY tw.task_id, t.pick_mode, t.source, t.wave_count ' - + 'HAVING COUNT(*) > 1 ' - + 'ORDER BY tw.task_id DESC LIMIT 10' - ); - console.log('D. 多波次任务样例:', JSON.stringify(multiWave)); - - const singleWave = await q( - 'SELECT tw.task_id, t.pick_mode, t.source, t.wave_count, COUNT(*) AS task_wave_rows ' - + 'FROM wms_wave_pick_task_wave tw ' - + 'INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id ' - + 'GROUP BY tw.task_id, t.pick_mode, t.source, t.wave_count ' - + 'HAVING COUNT(*) = 1 ' - + 'ORDER BY tw.task_id DESC LIMIT 10' - ); - console.log('E. 单波次任务样例:', JSON.stringify(singleWave)); - - const sampleGroup = await q( - 'SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, ' - + '(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows ' - + 'FROM wms_wave_pick_task t WHERE pick_mode = 1 ORDER BY id DESC LIMIT 10' - ); - console.log('F. 团购任务最近10条:', JSON.stringify(sampleGroup)); - - const sampleScatter = await q( - 'SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, ' - + '(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows ' - + 'FROM wms_wave_pick_task t WHERE pick_mode IN (2, 3, 4) ORDER BY id DESC LIMIT 10' - ); - console.log('G. 散单任务最近10条:', JSON.stringify(sampleScatter)); - - await s.close(); -})().catch(e => { - console.error('ERROR:', e.message); - process.exit(1); -}); diff --git a/script/tmp-check-wave-strategy7-pool.cjs b/script/tmp-check-wave-strategy7-pool.cjs deleted file mode 100644 index 1551b4d..0000000 --- a/script/tmp-check-wave-strategy7-pool.cjs +++ /dev/null @@ -1,89 +0,0 @@ -'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 deleted file mode 100644 index 8747ce5..0000000 --- a/script/tmp-check-wms-test-bootstrap.cjs +++ /dev/null @@ -1,53 +0,0 @@ -'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-clear-user-cache.cjs b/script/tmp-clear-user-cache.cjs deleted file mode 100644 index 6368f31..0000000 --- a/script/tmp-clear-user-cache.cjs +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; -const Redis = require('ioredis'); -(async () => { - const r = new Redis({ host: '127.0.0.1', port: 6379, password: 'qwe2019', db: 10 }); - const keys = await r.keys('user:info:*'); - console.log('matched keys:', keys); - for (const k of keys) { - await r.del(k); - console.log('deleted:', k); - } - r.disconnect(); - process.exit(0); -})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-compare-order-schema.cjs b/script/tmp-compare-order-schema.cjs deleted file mode 100644 index 5ff47e5..0000000 --- a/script/tmp-compare-order-schema.cjs +++ /dev/null @@ -1,173 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const { createRequire } = require('module'); - -function extractTopLevelFieldsFromObjectBody(body) { - const fields = []; - let i = 0; - let depth = 0; - while (i < body.length) { - const ch = body[i]; - if (ch === '{') { - depth++; - i++; - continue; - } - if (ch === '}') { - depth--; - i++; - continue; - } - - if (depth === 0) { - const m = body.slice(i).match(/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*\{/); - if (m) { - const key = m[1]; - fields.push(key); - i += m[0].length; - let inner = 1; - while (i < body.length && inner > 0) { - const c = body[i++]; - if (c === '{') inner++; - if (c === '}') inner--; - } - continue; - } - } - i++; - } - return [...new Set(fields)]; -} - -function getObjectBodyByMarker(text, marker) { - const start = text.indexOf(marker); - if (start < 0) return null; - const braceStart = text.indexOf('{', start + marker.length); - if (braceStart < 0) return null; - let i = braceStart + 1; - let depth = 1; - let body = ''; - while (i < text.length && depth > 0) { - const ch = text[i++]; - if (ch === '{') depth++; - if (ch === '}') depth--; - if (depth > 0) body += ch; - } - return body; -} - -function extractDefineFields(text) { - const definePos = text.indexOf('define('); - if (definePos < 0) return []; - const firstBrace = text.indexOf('{', definePos); - if (firstBrace < 0) return []; - let i = firstBrace + 1; - let depth = 1; - let body = ''; - while (i < text.length && depth > 0) { - const ch = text[i++]; - if (ch === '{') depth++; - if (ch === '}') depth--; - if (depth > 0) body += ch; - } - return extractTopLevelFieldsFromObjectBody(body); -} - -async function main() { - const root = process.cwd(); - const tempDir = path.join(root, 'temp'); - if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); - const projectRequire = createRequire(path.join(root, 'package.json')); - const mysql = projectRequire('mysql2/promise'); - const cfgFactory = require(path.join(root, 'config', 'config.local.js')); - const cfg = typeof cfgFactory === 'function' ? cfgFactory({ name: 'wms-debug' }) : cfgFactory; - const client = cfg?.mysql?.clients?.wms; - if (!client) throw new Error('mysql client wms not found'); - - const conn = await mysql.createConnection({ - host: client.host, - port: Number(client.port), - user: client.user, - password: client.password, - database: client.database, - charset: client.charset || 'utf8mb4', - }); - - const [tableRows] = await conn.query( - "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND (TABLE_NAME IN ('wms_order_delivery','wms_order_items','wms_entry_order') OR TABLE_NAME LIKE 'wms_order_delivery_%' OR TABLE_NAME LIKE 'wms_order_items_%') ORDER BY TABLE_NAME" - ); - - const tableSchemas = {}; - for (const t of tableRows.map(x => x.TABLE_NAME)) { - const [cols] = await conn.query( - "SELECT COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA,COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION", - [t] - ); - tableSchemas[t] = cols; - } - - const targets = [ - { table: 'wms_order_delivery', modelFile: 'app/model/order_delivery.js', type: 'baseModel' }, - { table: 'wms_order_items', modelFile: 'app/model/order_items.js', type: 'define' }, - { table: 'wms_entry_order', modelFile: 'app/model/entry_order.js', type: 'define' }, - ]; - - const compareWithModel = targets.map(t => { - const txt = fs.readFileSync(path.join(root, t.modelFile), 'utf8'); - let modelFields = []; - if (t.type === 'baseModel') { - const body = getObjectBodyByMarker(txt, 'const baseModel ='); - modelFields = body ? extractTopLevelFieldsFromObjectBody(body) : []; - } else { - modelFields = extractDefineFields(txt); - } - - const dbColumns = (tableSchemas[t.table] || []).map(c => c.COLUMN_NAME); - const modelOnly = modelFields.filter(f => !dbColumns.includes(f)); - const dbOnly = dbColumns.filter(c => !modelFields.includes(c)); - - return { - table: t.table, - modelFile: t.modelFile, - modelFieldCount: modelFields.length, - dbFieldCount: dbColumns.length, - modelOnly, - dbOnly, - allMatched: modelOnly.length === 0 && dbOnly.length === 0, - }; - }); - - const dynamicTableCheck = []; - const dynamicTables = Object.keys(tableSchemas).filter(t => t.endsWith('_100000')); - for (const dt of dynamicTables) { - const baseTable = dt.startsWith('wms_order_delivery_') ? 'wms_order_delivery' : dt.startsWith('wms_order_items_') ? 'wms_order_items' : null; - if (!baseTable) continue; - const baseCols = (tableSchemas[baseTable] || []).map(c => c.COLUMN_NAME); - const dynCols = (tableSchemas[dt] || []).map(c => c.COLUMN_NAME); - dynamicTableCheck.push({ - table: dt, - baseTable, - missingFromDynamic: baseCols.filter(c => !dynCols.includes(c)), - extraInDynamic: dynCols.filter(c => !baseCols.includes(c)), - allMatched: baseCols.length === dynCols.length && baseCols.every(c => dynCols.includes(c)), - }); - } - - const out = { - generatedAt: new Date().toISOString(), - dbName: client.database, - tables: tableRows.map(x => x.TABLE_NAME), - compareWithModel, - dynamicTableCheck, - schema: tableSchemas, - }; - - fs.writeFileSync(path.join(tempDir, 'tmp-order-schema-compare.json'), JSON.stringify(out, null, 2)); - await conn.end(); - console.log('WROTE temp/tmp-order-schema-compare.json'); -} - -main().catch(err => { - console.error(err && err.stack ? err.stack : String(err)); - process.exit(1); -}); diff --git a/script/tmp-explore-putaway-test-data.cjs b/script/tmp-explore-putaway-test-data.cjs deleted file mode 100644 index 9670c42..0000000 --- a/script/tmp-explore-putaway-test-data.cjs +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; -/* 临时探索脚本:查询直入/转入库单对比测试所需数据(只读) */ -const mysql = require('mysql2/promise'); - -(async () => { - const conn = await mysql.createConnection({ - host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms', - }); - - const [cols] = await conn.query('SHOW COLUMNS FROM wms_employee_role'); - console.log('== wms_employee_role columns =='); - console.log(cols.map(c => c.Field).join(',')); - - const [whUsers] = await conn.query(` - SELECT a.id account_id, a.username, a.status, e.id employee_id, e.store_id warehouse_id, r.id role_id, r.role_type - FROM wms_account a - JOIN wms_account_store_employee e ON e.account_id = a.id AND e.deleted_at IS NULL - LEFT JOIN wms_employee_role er ON er.employee_id = e.id - LEFT JOIN wms_role r ON r.id = er.role_id - WHERE a.status = 1 - ORDER BY e.id ASC LIMIT 8`); - console.log('== accounts =='); - console.log(JSON.stringify(whUsers, null, 2)); - - if (whUsers.length === 0) { await conn.end(); return; } - const whId = whUsers[0].warehouse_id; - console.log('== using warehouse_id = ' + whId + ' =='); - - const [stores] = await conn.query(` - SELECT sw.store_id, sw.warehouse_use_status, sw.policy_config, s.company_name - FROM wms_store_warehouse sw JOIN wms_store s ON s.id = sw.store_id - WHERE sw.warehouse_id = ? AND sw.warehouse_use_status = 1 - ORDER BY sw.id DESC LIMIT 5`, [ whId ]); - console.log('== store_warehouse contracts (warehouse=' + whId + ') =='); - console.log(JSON.stringify(stores, null, 2)); - - const [stocks] = await conn.query(` - SELECT sw.id, sw.item_code, sw.item_name, sw.is_batch_mgmt, sw.is_shelf_life_mgmt, sw.is_valid, sw.quantity, sw.store_id - FROM wms_stock_warehouse sw - WHERE sw.warehouse_id = ? AND sw.is_valid = 'Y' AND sw.deleted_at IS NULL - ORDER BY sw.id DESC LIMIT 8`, [ whId ]); - console.log('== stock_warehouse products =='); - console.log(JSON.stringify(stocks, null, 2)); - - const [spacesCols] = await conn.query('SHOW COLUMNS FROM wms_location_space'); - console.log('== wms_location_space columns =='); - console.log(spacesCols.map(c => c.Field).join(',')); - - const [spaces] = await conn.query(` - SELECT id, space_code, custom_name, is_enabled, current_quantity - FROM wms_location_space - WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL - ORDER BY id LIMIT 8`, [ whId ]); - console.log('== location spaces =='); - console.log(JSON.stringify(spaces, null, 2)); - - await conn.end(); -})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-gen-service-method-inventory.cjs b/script/tmp-gen-service-method-inventory.cjs deleted file mode 100644 index dde9654..0000000 --- a/script/tmp-gen-service-method-inventory.cjs +++ /dev/null @@ -1,99 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -const root = process.cwd(); -const tempDir = path.join(root, 'temp'); -const serviceRoot = path.join(root, 'app', 'service'); - -function walk(dir) { - const out = []; - for (const name of fs.readdirSync(dir)) { - const full = path.join(dir, name); - const st = fs.statSync(full); - if (st.isDirectory()) out.push(...walk(full)); - else if (name.endsWith('.js')) out.push(full); - } - return out; -} - -function extractClassMethods(content) { - const methods = []; - const classIdx = content.indexOf('class '); - if (classIdx < 0) return methods; - const braceStart = content.indexOf('{', classIdx); - if (braceStart < 0) return methods; - - let i = braceStart + 1; - let depth = 1; - let body = ''; - while (i < content.length && depth > 0) { - const ch = content[i++]; - if (ch === '{') depth++; - if (ch === '}') depth--; - if (depth > 0) body += ch; - } - - let p = 0; - let nested = 0; - while (p < body.length) { - const ch = body[p]; - if (ch === '{') { nested++; p++; continue; } - if (ch === '}') { nested--; p++; continue; } - - if (nested === 0) { - const slice = body.slice(p); - const m = slice.match(/^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*\(/); - if (m) { - const name = m[1]; - if (name !== 'constructor') methods.push(name); - - // move to method body end - p += m[0].length; - while (p < body.length && body[p] !== '{') p++; - if (body[p] === '{') { - p++; - let inMethod = 1; - while (p < body.length && inMethod > 0) { - if (body[p] === '{') inMethod++; - else if (body[p] === '}') inMethod--; - p++; - } - } - continue; - } - } - p++; - } - - return [...new Set(methods)]; -} - -const files = walk(serviceRoot) - .map(full => path.relative(root, full).replace(/\\/g, '/')) - .sort((a, b) => a.localeCompare(b)); - -const inventory = []; -for (const rel of files) { - const full = path.join(root, rel); - const content = fs.readFileSync(full, 'utf8'); - const methods = extractClassMethods(content); - inventory.push({ file: rel, methodCount: methods.length, methods }); -} - -const now = new Date().toISOString(); -let md = ''; -md += `自动生成时间: ${now}\n\n`; -md += `扫描范围: app/service/**/*.js\n`; -md += `文件数: ${inventory.length}\n\n`; -for (const item of inventory) { - md += `- ${item.file} (${item.methodCount})\n`; - if (item.methods.length === 0) { - md += ` - \n`; - } else { - md += ` - ${item.methods.join(', ')}\n`; - } -} - -if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); -fs.writeFileSync(path.join(tempDir, 'tmp-service-method-inventory.md'), md, 'utf8'); -console.log('WROTE temp/tmp-service-method-inventory.md'); diff --git a/script/tmp-generate-method-regression-test.cjs b/script/tmp-generate-method-regression-test.cjs deleted file mode 100644 index 9655cf7..0000000 --- a/script/tmp-generate-method-regression-test.cjs +++ /dev/null @@ -1,116 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -const root = process.cwd(); -const defaultBaselinePath = path.join(root, 'temp', 'method-output', 'method-output-baseline.json'); -const defaultTargetPath = path.join(root, 'temp', 'generated-tests', 'system.method-output.generated.test.js'); -const legacyBaselinePath = path.join(root, 'run', 'method-output-baseline.json'); -let baselinePath = process.argv[2] - ? path.resolve(process.argv[2]) - : defaultBaselinePath; -const targetPath = process.argv[3] - ? path.resolve(process.argv[3]) - : defaultTargetPath; - -if (!process.argv[2] && !fs.existsSync(baselinePath) && fs.existsSync(legacyBaselinePath)) { - baselinePath = legacyBaselinePath; -} - -const supportClientPath = path.relative( - path.dirname(targetPath), - path.join(root, 'test', 'support', 'system_method_client') -).replace(/\\/g, '/'); -const supportRequirePath = supportClientPath.startsWith('.') ? supportClientPath : `./${supportClientPath}`; -const describePath = path.relative(root, targetPath).replace(/\\/g, '/'); - -if (!fs.existsSync(baselinePath)) { - console.error(`Baseline not found: ${baselinePath}`); - process.exit(1); -} - -const baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf8')); -const cases = Array.isArray(baseline.cases) ? baseline.cases : []; - -const header = `// @eggjs-test-generated -// @purpose 接口返回数据一致性校验(自动生成,请勿手改) -// @source ${path.relative(root, baselinePath).replace(/\\/g, '/')} -// @generatedAt ${new Date().toISOString()} -'use strict'; - -const assert = require('node:assert/strict'); -const { - getAuthToken, - invokeSystemMethod, -} = require('${supportRequirePath}'); - -const VOLATILE_KEYS = new Set([ - 'timestamp', - 'token', - 'last_login_at', - 'updated_at', - 'update_at', - 'created_at', - 'create_at', - 'login_time', - 'iat', - 'exp', -]); - -function normalize(value) { - if (value === null || value === undefined) return value; - if (Array.isArray(value)) return value.map(item => normalize(item)); - if (typeof value !== 'object') return value; - const out = {}; - for (const key of Object.keys(value)) { - if (VOLATILE_KEYS.has(key)) { - out[key] = '__VOLATILE__'; - continue; - } - out[key] = normalize(value[key]); - } - return out; -} - -describe(${JSON.stringify(describePath)}, () => { - let token = ''; - - before(async () => { - const auth = await getAuthToken(); - token = auth.token; - assert.ok(token, 'token should be available'); - }); -`; - -const body = cases.map((item, idx) => { - const title = `[${idx + 1}] ${item.method} (sourceId=${item.sourceId})`; - const requestBody = JSON.stringify(item.requestBody || {}, null, 2); - const expected = JSON.stringify(item.normalized || {}, null, 2); - const platform = JSON.stringify((item.headers && item.headers.platform) || 'web'); - const project = JSON.stringify((item.headers && item.headers.project) || 'wms'); - - return ` - it(${JSON.stringify(title)}, async () => { - const res = await invokeSystemMethod( - ${JSON.stringify(item.method)}, - ${requestBody}, - token, - { platform: ${platform}, project: ${project} } - ); - - assert.equal(res.status, ${Number(item.httpStatus || 200)}); - const normalized = normalize(res.body); - const expected = ${expected}; - assert.deepEqual(normalized, expected); - }); -`; -}).join('\n'); - -const footer = ` -}); -`; - -fs.mkdirSync(path.dirname(targetPath), { recursive: true }); -fs.writeFileSync(targetPath, header + body + footer, 'utf8'); - -console.log(`GENERATED ${targetPath}`); -console.log(`CASE_COUNT ${cases.length}`); diff --git a/script/tmp-init-qimen-methods.cjs b/script/tmp-init-qimen-methods.cjs deleted file mode 100644 index c82e334..0000000 --- a/script/tmp-init-qimen-methods.cjs +++ /dev/null @@ -1,194 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -const root = process.cwd(); -const methodsDir = path.join(root, 'app', 'service', 'qimenMethods'); -const outputPath = path.join(root, 'methods', 'qimen.json'); - -function walk(dir) { - const out = []; - for (const name of fs.readdirSync(dir)) { - const full = path.join(dir, name); - const stat = fs.statSync(full); - if (stat.isDirectory()) { - out.push(...walk(full)); - } else if (name.endsWith('.js')) { - out.push(full); - } - } - return out; -} - -function extractAsyncMethods(content) { - const methods = []; - const classMatch = content.match(/class\s+[A-Za-z_$][\w$]*\s+extends\s+[A-Za-z_$][\w$]*\s*\{([\s\S]*)\}\s*module\.exports\s*=\s*/); - if (!classMatch) { - return methods; - } - - const body = classMatch[1]; - const regex = /async\s+([A-Za-z_$][\w$]*)\s*\(/g; - let m = regex.exec(body); - while (m) { - if (m[1] !== 'constructor') { - methods.push(m[1]); - } - m = regex.exec(body); - } - - return Array.from(new Set(methods)); -} - -function extractRequestKeys(content) { - const keys = new Set(); - const patterns = [ - /data\.request(?:\?|)\.(\w+)/g, - /data\?\.request\?\.(\w+)/g, - ]; - - for (const re of patterns) { - let m = re.exec(content); - while (m) { - const key = m[1]; - if (key) keys.add(key); - m = re.exec(content); - } - } - - return Array.from(keys).sort((a, b) => a.localeCompare(b)); -} - -function buildMethodItem(fullMethod, requestKeys) { - const params = [ - { - name: 'app_key', - type: 'string', - required: true, - source: 'query', - description: 'app_key 参数', - }, - { - name: 'method', - type: 'string', - required: true, - source: 'query', - description: 'method 参数', - }, - { - name: 'v', - type: 'string', - required: true, - source: 'query', - description: 'v 参数', - }, - { - name: 'format', - type: 'string', - required: true, - source: 'query', - description: 'format 参数', - }, - { - name: 'sign_method', - type: 'string', - required: true, - source: 'query', - description: 'sign_method 参数', - }, - { - name: 'sign', - type: 'string', - required: true, - source: 'query', - description: 'sign 参数', - }, - { - name: 'timestamp', - type: 'string', - required: true, - source: 'query', - description: 'timestamp 参数', - }, - { - name: 'request', - type: 'object', - required: true, - source: 'body', - description: 'request XML 节点', - }, - ]; - - for (const key of requestKeys) { - params.push({ - name: `request.${key}`, - type: 'string', - required: false, - source: 'body', - description: `request.${key} 参数`, - }); - } - - return { - method: fullMethod, - description: `${fullMethod} 接口`, - isNeedAuth: false, - isNeedLogin: false, - headers: [], - params, - response: [], - errors: [], - }; -} - -function main() { - if (!fs.existsSync(methodsDir)) { - throw new Error(`目录不存在: ${methodsDir}`); - } - - const files = walk(methodsDir).sort((a, b) => a.localeCompare(b)); - const groupMap = new Map(); - - for (const file of files) { - const content = fs.readFileSync(file, 'utf8'); - const rel = path.relative(methodsDir, file).replace(/\\/g, '/').replace(/\.js$/, ''); - const moduleName = rel.replace(/\//g, '.'); - const methodNames = extractAsyncMethods(content); - const requestKeys = extractRequestKeys(content); - - if (!groupMap.has(moduleName)) { - groupMap.set(moduleName, []); - } - - for (const methodName of methodNames) { - const fullMethod = `${moduleName}.${methodName}`; - groupMap.get(moduleName).push(buildMethodItem(fullMethod, requestKeys)); - } - } - - const groups = Array.from(groupMap.entries()) - .map(([ moduleName, list ]) => ({ - groupName: `${moduleName} 模块`, - module: moduleName, - list: list.sort((a, b) => a.method.localeCompare(b.method)), - })) - .sort((a, b) => a.module.localeCompare(b.module)); - - const now = new Date().toISOString().slice(0, 10); - const doc = { - module: 'qimen', - description: '奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)', - version: '0.3.0', - updatedAt: now, - headers: [], - methods: { - groups, - }, - }; - - fs.writeFileSync(outputPath, JSON.stringify(doc, null, 2) + '\n', 'utf8'); - - const methodCount = groups.reduce((sum, group) => sum + group.list.length, 0); - console.log(`WROTE methods/qimen.json, groups=${groups.length}, methods=${methodCount}`); -} - -main(); \ No newline at end of file diff --git a/script/tmp-prepare-wave-pool-boundary.cjs b/script/tmp-prepare-wave-pool-boundary.cjs deleted file mode 100644 index 4da6faf..0000000 --- a/script/tmp-prepare-wave-pool-boundary.cjs +++ /dev/null @@ -1,95 +0,0 @@ -'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 deleted file mode 100644 index 882d393..0000000 --- a/script/tmp-prepare-wave-pool-boundary3.cjs +++ /dev/null @@ -1,99 +0,0 @@ -'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 deleted file mode 100644 index 3c4cbc0..0000000 --- a/script/tmp-prepare-wave-pool-today-orders.cjs +++ /dev/null @@ -1,73 +0,0 @@ -'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-push-inbox-robot-intercept.cjs b/script/tmp-push-inbox-robot-intercept.cjs deleted file mode 100644 index 29b2932..0000000 --- a/script/tmp-push-inbox-robot-intercept.cjs +++ /dev/null @@ -1,318 +0,0 @@ -/** - * 临时脚本:本地以「机器人拦截格式」推送一条站内信,验证规则引擎修复效果(不连生产、不清理数据)。 - * - * 格式来源(生产 优禾康(天豹)顺丰对接群 实测): - * <店铺名>LSFJY<日期><序号>\n物流单号:<运单号> 拦截 - * - * 走真实入站链路:POST /warehouse?method=inbox.push(interface_type_id=3,MD5 签名) - * → receiver.receive 写库 → setImmediate 异步 handleApiMessage → rules 规则引擎 → 回信 - * - * 用法:node script/tmp-push-inbox-robot-intercept.cjs - */ -'use strict'; - -const path = require('path'); - -const projectRoot = path.resolve(__dirname, '..'); -const mysql = require('mysql2/promise'); -const { signRequest } = require('../app/lib/api_sign'); - -const BASE_URL = process.env.INBOX_BASE_URL || 'http://127.0.0.1:6060'; -const APP_KEY = process.env.INBOX_APP_KEY || 'AK2026080103072276d0e140'; // 本地 warehouse 100000 应用 - -/** 测试群(本地 100000 / 货主 1000000 的售后群) */ -const GROUP = { - group_id: 'g_after_sales_1785917104039', - group_name: '测试售后群_1785917104039', - user_id: 'wxid_robot_uat_0001', - user_name: '探域售后机器人', -}; - -/** - * 用例来源:从本地库自动挑选**真实存在**的顺丰运单(货主 1000000、订单在待处理/波次中、 - * 未拦截、无未完结拦截工单),并按运单号形态去重覆盖(纯数字 / SF+数字 / 其他前缀)。 - * 正文固定用生产机器人原文格式。 - */ -const WAREHOUSE_ID = 100000; -const STORE_ID = 1000000; -const CASE_LIMIT = Number(process.env.INBOX_CASE_LIMIT || 4); - -/** 生产原文里的店铺单号前缀(仅用于拼出同款正文) */ -const SHOP_CODE = '优禾康官方旗舰店LSFJY202609143442'; - -/** - * 运单号形态归类:开头字母前缀;纯数字归 DIGITS - * @param {string} code 运单号。 - * @return {string} 形态标签。 - */ -function waybillPattern(code) { - const m = String(code).match(/^[A-Za-z]+/); - return m ? m[0].toUpperCase() : 'DIGITS'; -} - -/** - * 查询可用的顺丰测试运单。 - * @param {Object} conn mysql2 连接。 - * @param {number} limit 最多取几个(按运单号形态去重后)。 - * @return {Promise} 用例列表 [{ tag, desc, waybill, expressId, orderId, content }]。 - */ -async function findSfCases(conn, limit) { - const [ rows ] = await conn.query( - 'SELECT e.id AS express_id, e.waybill_code, e.order_id, e.logistics_name, e.logistics_interface_id, ' + - 'd.step, d.wave_id, d.intercept_status ' + - 'FROM wms_order_express e JOIN wms_order_delivery_100000 d ON d.id = e.order_id ' + - 'WHERE e.warehouse_id = ? AND e.store_id = ? AND e.logistics_code = "SF" ' + - 'AND d.step IN (1,2,3) AND (d.intercept_status IS NULL OR d.intercept_status = "none") ' + - 'AND (e.is_intercept IS NULL OR e.is_intercept <> "Y") ' + - 'AND e.id NOT IN (SELECT waybill_id FROM wms_after_sale WHERE waybill_id IS NOT NULL ' + - ' AND sub_type = "intercept" AND status NOT IN ("completed","closed","cancelled")) ' + - 'ORDER BY e.id DESC', - [ WAREHOUSE_ID, STORE_ID ] - ); - - const picked = []; - const usedPatterns = new Set(); - for (const row of rows) { - const pattern = waybillPattern(row.waybill_code); - if (usedPatterns.has(pattern)) continue; - usedPatterns.add(pattern); - picked.push({ - tag: String(picked.length + 1), - waybill: row.waybill_code, - expressId: row.express_id, - orderId: row.order_id, - desc: `形态=${pattern} 顺丰运单 ${row.waybill_code} (express id=${row.express_id}, order=${row.order_id})`, - content: `${SHOP_CODE}\n物流单号:${row.waybill_code} 拦截`, - }); - if (picked.length >= limit) break; - } - return picked; -} - -function loadDbConfig() { - const factory = require(path.resolve(projectRoot, 'config/config.local.js')); - const config = typeof factory === 'function' ? factory({ name: 'wms-inbox-push' }) : factory; - const client = config.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 function getAppSecret(conn, appKey) { - const [ rows ] = await conn.query( - 'SELECT self_app_key, self_app_secret, warehouse_id FROM wms_api_app WHERE self_app_key = ?', - [ appKey ] - ); - if (rows.length === 0) throw new Error(`本地库未找到 app_key=${appKey} 的应用`); - return rows[0]; -} - -async function pushMessage({ appKey, secret, requestId, content }) { - const body = { - requestId, - groupId: GROUP.group_id, - groupName: GROUP.group_name, - userId: GROUP.user_id, - userName: GROUP.user_name, - content, - extData: { type: 1, source: 'wx' }, - flags: {}, - }; - const query = { - method: 'inbox.push', - v: '1.0', - timestamp: String(Math.floor(Date.now() / 1000)), - app_key: appKey, - }; - const { sign, canonicalQuery } = signRequest({ query, body, selfAppSecret: secret }); - const search = new URLSearchParams({ ...query, sign }).toString(); - const url = `${BASE_URL}/warehouse?${search}`; - - const res = await fetch(url, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), - }); - const text = await res.text(); - let json = null; - try { - json = JSON.parse(text); - } catch (e) { /* 保留原始文本 */ } - return { status: res.status, json, text, canonicalQuery }; -} - -/** - * 轮询等待异步处理完成(ai_thoughts 或回信出现)。 - * @param {Object} conn mysql2 连接实例。 - * @param {string} extId 入站消息外部唯一键。 - * @param {Object} [opts] 轮询配置。 - * @param {number} [opts.timeoutMs] 最长等待毫秒数。 - * @param {number} [opts.intervalMs] 轮询间隔毫秒数。 - * @return {Promise} { inbound, replies, timedOut }。 - */ -async function waitProcessed(conn, extId, { timeoutMs = 20000, intervalMs = 1000 } = {}) { - const deadline = Date.now() + timeoutMs; - let inbound = null; - while (Date.now() < deadline) { - const [ rows ] = await conn.query( - 'SELECT id, direction, group_id, group_name, user_id, user_name, content, ai_thoughts, push_status, created_at ' + - 'FROM wms_inbox_message WHERE ext_id = ? AND direction = "inbound" ORDER BY id DESC LIMIT 1', - [ extId ] - ); - inbound = rows[0] || null; - if (inbound) { - const [ replies ] = await conn.query( - 'SELECT id, content, push_status, created_at FROM wms_inbox_message WHERE parent_id = ? ORDER BY id', - [ inbound.id ] - ); - if ((inbound.ai_thoughts && String(inbound.ai_thoughts).length > 2) || replies.length > 0) { - return { inbound, replies }; - } - } - await new Promise(r => setTimeout(r, intervalMs)); - } - const [ replies ] = inbound - ? await conn.query('SELECT id, content, push_status, created_at FROM wms_inbox_message WHERE parent_id = ? ORDER BY id', [ inbound.id ]) - : [[]]; - return { inbound, replies, timedOut: true }; -} - -async function collectSideEffects(conn, waybills) { - if (waybills.length === 0) return { express: [], afterSales: [], orders: [] }; - const [ express ] = await conn.query( - 'SELECT id, waybill_code, order_id, store_id, is_intercept FROM wms_order_express WHERE warehouse_id = ? AND waybill_code IN (?)', - [ WAREHOUSE_ID, waybills ] - ); - const expressIds = express.map(r => r.id); - const orderIds = express.map(r => r.order_id).filter(Boolean); - let afterSales = []; - if (expressIds.length > 0) { - const [ rows ] = await conn.query( - 'SELECT id, after_sale_no, waybill_id, waybill_no, type, sub_type, status, title FROM wms_after_sale WHERE waybill_id IN (?) ORDER BY id DESC', - [ expressIds ] - ); - afterSales = rows; - } - let orders = []; - if (orderIds.length > 0) { - const [ rows ] = await conn.query( - 'SELECT id, step, wave_id, intercept_status, intercept_time FROM wms_order_delivery_100000 WHERE id IN (?)', - [ orderIds ] - ); - orders = rows; - } - return { express, afterSales, orders }; -} - -(async () => { - const dbConfig = loadDbConfig(); - const conn = await mysql.createConnection(dbConfig); - const app = await getAppSecret(conn, APP_KEY); - console.log(`目标服务: ${BASE_URL} 应用: ${app.self_app_key} (warehouse ${app.warehouse_id})`); - console.log(`测试群: ${GROUP.group_name} / ${GROUP.group_id} 发送人: ${GROUP.user_name}\n`); - - // 支持临时指定正文(INBOX_CONTENT=...),用于其它规则的端到端复现;不指定则自动挑顺丰运单 - const adhoc = String(process.env.INBOX_CONTENT || '').trim(); - let cases; - if (adhoc) { - cases = [{ tag: 'X', waybill: '-', desc: '自定义正文(INBOX_CONTENT)', content: adhoc }]; - console.log('使用自定义正文(INBOX_CONTENT)'); - } else { - cases = await findSfCases(conn, CASE_LIMIT); - if (cases.length === 0) { - console.log('❌ 本地库没有可用的未拦截顺丰运单样本'); - await conn.end(); - return; - } - console.log(`自动挑选到 ${cases.length} 个真实顺丰运单样本(按运单号形态去重):`); - for (const c of cases) console.log(` - ${c.desc}`); - } - - const waybills = cases.map(c => c.waybill).filter(code => code && code !== '-'); - const results = []; - - for (const item of cases) { - const requestId = `UATTEST${item.tag}${Date.now()}`; - const extId = `api:${APP_KEY}:${requestId}`; - console.log('\n' + '='.repeat(96)); - console.log(`【用例 ${item.tag}】${item.desc}`); - console.log(`正文: ${JSON.stringify(item.content)}`); - console.log(`requestId=${requestId} ext_id=${extId}`); - - const pushRes = await pushMessage({ - appKey: APP_KEY, - secret: app.self_app_secret, - requestId, - content: item.content, - }); - console.log(`入站响应: HTTP ${pushRes.status} ${pushRes.text}`); - - const { inbound, replies, timedOut } = await waitProcessed(conn, extId); - if (!inbound) { - console.log('❌ 未查到入站消息记录,请检查 dev 服务日志'); - results.push({ ...item, ok: false, note: '未查到入站记录' }); - continue; - } - const thoughts = Array.isArray(inbound.ai_thoughts) - ? inbound.ai_thoughts - : (inbound.ai_thoughts ? [ inbound.ai_thoughts ] : []); - const fnName = thoughts[0] ? thoughts[0].function || '-' : '-'; - console.log(`\n入站记录: id=${inbound.id} group=${inbound.group_name} 用户=${inbound.user_name}`); - console.log(` ai_thoughts = ${inbound.ai_thoughts ? JSON.stringify(inbound.ai_thoughts) : 'null'}`); - console.log(` push_status = ${inbound.push_status}`); - if (replies.length === 0) { - console.log(` ⚠ 无回信记录${timedOut ? '(等待超时)' : ''}`); - } else { - for (const r of replies) { - console.log(` 回信 id=${r.id} push_status=${r.push_status}: ${JSON.stringify(r.content)}`); - } - } - if (timedOut) console.log(' (等待处理超时,可能仍在异步处理中)'); - results.push({ - ...item, - inboundId: inbound.id, - fn: fnName, - reply: replies.map(r => r.content).join(' | ') || '(无回信)', - ok: replies.length > 0, - }); - } - - const { express, afterSales, orders } = await collectSideEffects(conn, waybills); - console.log('\n' + '='.repeat(96)); - console.log('副作用核对(本地库,保留不清理)'); - console.log('运单:'); - for (const e of express) { - console.log(` express id=${e.id} ${e.waybill_code} order_id=${e.order_id} store_id=${e.store_id} is_intercept=${e.is_intercept}`); - } - console.log('售后工单:'); - for (const a of afterSales) { - console.log(` ${a.after_sale_no} waybill=${a.waybill_no} ${a.type}/${a.sub_type} status=${a.status}\n title=${a.title}`); - } - if (afterSales.length === 0) console.log(' (无)'); - console.log('订单拦截状态:'); - for (const o of orders) { - console.log(` order id=${o.id} step=${o.step} wave_id=${o.wave_id} intercept_status=${o.intercept_status} intercept_time=${o.intercept_time ? o.intercept_time.toISOString() : null}`); - } - if (orders.length === 0) console.log(' (无)'); - - console.log('\n' + '='.repeat(96)); - console.log('汇总'); - let pass = 0; - for (const r of results) { - if (r.ok) pass++; - console.log( - `${r.ok ? '✅' : '❌'} 用例${r.tag} ${r.waybill} | fn=${r.fn || '-'} | 入站id=${r.inboundId || '-'} | ${r.reply}` - ); - } - console.log(`\n有回信用例:${pass}/${results.length}`); - - await conn.end(); -})().catch(err => { - console.error('脚本执行失败:', err); - process.exitCode = 1; -}); diff --git a/script/tmp-repro-first-pool-query.cjs b/script/tmp-repro-first-pool-query.cjs deleted file mode 100644 index b8e4125..0000000 --- a/script/tmp-repro-first-pool-query.cjs +++ /dev/null @@ -1,78 +0,0 @@ -'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 deleted file mode 100644 index 9ec3480..0000000 --- a/script/tmp-show-last-release.cjs +++ /dev/null @@ -1,28 +0,0 @@ -'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-struct-system-params.cjs b/script/tmp-struct-system-params.cjs deleted file mode 100644 index 5d89be3..0000000 --- a/script/tmp-struct-system-params.cjs +++ /dev/null @@ -1,421 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const acorn = require('acorn'); - -const baseDir = process.cwd(); -const methodsDir = path.join(baseDir, 'app', 'service', 'systemMethods'); -const jsonPath = path.join(baseDir, 'methods', 'system.json'); - -function walk(node, visitor, parent = null) { - if (!node || typeof node !== 'object') return; - visitor(node, parent); - for (const key of Object.keys(node)) { - const value = node[key]; - if (!value) continue; - if (Array.isArray(value)) { - for (const item of value) walk(item, visitor, node); - } else if (typeof value === 'object' && value.type) { - walk(value, visitor, node); - } - } -} - -function walkFiles(dir) { - const files = []; - for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { - const full = path.join(dir, entry.name); - if (entry.isDirectory()) files.push(...walkFiles(full)); - if (entry.isFile() && entry.name.endsWith('.js')) files.push(full); - } - return files; -} - -function getPropName(node) { - if (!node) return null; - if (node.type === 'Identifier') return node.name; - if (node.type === 'Literal') return String(node.value); - return null; -} - -function memberPath(node) { - if (!node) return null; - if (node.type === 'ChainExpression') return memberPath(node.expression); - if (node.type === 'Identifier') return node.name; - if (node.type === 'ThisExpression') return 'this'; - if (node.type !== 'MemberExpression') return null; - const left = memberPath(node.object); - if (!left) return null; - if (node.computed) { - if (node.property.type === 'Literal') return `${left}.${String(node.property.value)}`; - if (node.property.type === 'Identifier') return left; - return left; - } - const right = getPropName(node.property); - return right ? `${left}.${right}` : left; -} - -function classifySourceByExpr(expr, signatureSet) { - const sources = new Set(); - const visit = node => { - if (!node) return; - if (node.type === 'Identifier' && signatureSet.has(node.name)) { - sources.add('body'); - return; - } - if (node.type === 'MemberExpression' || node.type === 'ChainExpression') { - const p = memberPath(node); - if (p && p.startsWith('ctx.request.body')) sources.add('body'); - else if (p && p.startsWith('ctx.query')) sources.add('query'); - else if (p && p.startsWith('ctx.params')) sources.add('path'); - else if (p && p.startsWith('ctx.headers')) sources.add('header'); - return; - } - if (node.type === 'LogicalExpression' || node.type === 'BinaryExpression') { - visit(node.left); - visit(node.right); - return; - } - if (node.type === 'ConditionalExpression') { - visit(node.consequent); - visit(node.alternate); - return; - } - }; - visit(expr); - if (!sources.size) return null; - return Array.from(sources).sort().join('|'); -} - -function inferTypeByName(name) { - if (!name) return 'string'; - if (/ids$/i.test(name)) return 'array'; - if (/^(where|pagination|item|template|data|filters?)$/i.test(name)) return 'object'; - if (/^(is_|has_|need|sync)/i.test(name)) return 'boolean'; - if (/(^id$|_id$|^page$|^pageSize$|^limit$|^offset$|^count$|_count$|^x$|^y$|^z$|^rows$|^columns$|^levels$|^width$|^height$|^length$)/i.test(name)) return 'number'; - if (/(^date$|_date$|^time$|_time$|timestamp)/i.test(name)) return 'string'; - return 'string'; -} - -function inferTypeByNode(node, fallbackName = '') { - if (!node) return inferTypeByName(fallbackName); - if (node.type === 'Literal') { - if (typeof node.value === 'number') return 'number'; - if (typeof node.value === 'boolean') return 'boolean'; - return 'string'; - } - if (node.type === 'ObjectExpression') return 'object'; - if (node.type === 'ArrayExpression') return 'array'; - return inferTypeByName(fallbackName); -} - -function mapValidateType(v) { - if (!v) return 'string'; - const t = String(v).toLowerCase(); - if (t === 'int' || t === 'integer' || t === 'number') return 'number'; - if (t === 'boolean' || t === 'bool') return 'boolean'; - if (t === 'array') return 'array'; - if (t === 'object') return 'object'; - return 'string'; -} - -function extractNoNeedLists(classNode) { - const result = { noNeedLogin: [], noNeedAuth: ['*'] }; - const ctor = classNode.body.body.find(m => m.type === 'MethodDefinition' && m.kind === 'constructor'); - if (!ctor) return result; - - for (const stmt of ctor.value.body.body || []) { - if (stmt.type !== 'VariableDeclaration') continue; - for (const decl of stmt.declarations || []) { - if (decl.id.type !== 'Identifier' || !decl.init || decl.init.type !== 'Literal') continue; - const name = decl.id.name; - const value = String(decl.init.value || ''); - if (name === '_noNeedLogin') result.noNeedLogin = value.split(',').map(s => s.trim()).filter(Boolean); - if (name === '_noNeedAuth') result.noNeedAuth = value.split(',').map(s => s.trim()).filter(Boolean); - } - } - return result; -} - -function collectMethodParams(methodNode) { - const signatureNames = []; - for (const p of methodNode.value.params || []) { - if (p.type === 'Identifier') signatureNames.push(p.name); - else if (p.type === 'AssignmentPattern' && p.left.type === 'Identifier') signatureNames.push(p.left.name); - } - const signatureSet = new Set(signatureNames); - const aliasMap = new Map(); - const entries = new Map(); - const listFields = []; - - function resolveName(localName) { - return aliasMap.get(localName) || localName; - } - - function ensure(name) { - if (!entries.has(name)) { - entries.set(name, { - name, - type: inferTypeByName(name), - required: false, - source: new Set(), - }); - } - return entries.get(name); - } - - function addParam(name, patch = {}) { - if (!name) return; - if ([ 'ctx', 'service', 'app', 'result', 'error', 'e' ].includes(name)) return; - const item = ensure(name); - if (patch.type) item.type = patch.type; - if (patch.required === true) item.required = true; - if (patch.source) item.source.add(patch.source); - } - - function addRequiredFromTest(testNode) { - if (!testNode) return; - if (testNode.type === 'UnaryExpression' && testNode.operator === '!') { - if (testNode.argument.type === 'Identifier') { - const local = testNode.argument.name; - const resolved = resolveName(local); - if (resolved !== local || entries.has(resolved)) { - addParam(resolved, { required: true }); - } - } - if (testNode.argument.type === 'MemberExpression' || testNode.argument.type === 'ChainExpression') { - const p = memberPath(testNode.argument); - if (!p) return; - const parts = p.split('.'); - if (parts.length === 2 && signatureSet.has(parts[0])) { - addParam(parts[1], { required: true, source: 'body' }); - } - } - return; - } - if (testNode.type === 'LogicalExpression') { - addRequiredFromTest(testNode.left); - addRequiredFromTest(testNode.right); - return; - } - if (testNode.type === 'CallExpression') { - const callee = memberPath(testNode.callee); - if (callee === 'Array.isArray' && testNode.arguments[0] && testNode.arguments[0].type === 'Identifier') { - const local = testNode.arguments[0].name; - const resolved = resolveName(local); - if (resolved !== local || entries.has(resolved)) { - addParam(resolved, { required: true, type: 'array' }); - } - } - } - } - - walk(methodNode.value.body, (node, parent) => { - if (node.type === 'VariableDeclarator') { - if (node.id.type === 'ObjectPattern' && node.init) { - const source = classifySourceByExpr(node.init, signatureSet); - if (!source) return; - for (const prop of node.id.properties || []) { - if (prop.type !== 'Property') continue; - const keyName = getPropName(prop.key); - if (!keyName) continue; - - let localName = keyName; - let type = inferTypeByName(keyName); - - if (prop.value.type === 'Identifier') { - localName = prop.value.name; - } else if (prop.value.type === 'AssignmentPattern') { - if (prop.value.left.type === 'Identifier') localName = prop.value.left.name; - type = inferTypeByNode(prop.value.right, keyName); - } - - aliasMap.set(localName, keyName); - addParam(keyName, { source, type }); - } - } - - if (node.id.type === 'Identifier' && node.init) { - const local = node.id.name; - - if (node.init.type === 'MemberExpression' || node.init.type === 'ChainExpression') { - const p = memberPath(node.init); - if (p) { - const parts = p.split('.'); - if (parts.length === 2 && signatureSet.has(parts[0])) { - aliasMap.set(local, parts[1]); - addParam(parts[1], { source: 'body' }); - } - if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'query') { - aliasMap.set(local, parts[2]); - addParam(parts[2], { source: 'query' }); - } - if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'params') { - aliasMap.set(local, parts[2]); - addParam(parts[2], { source: 'path' }); - } - if (parts.length >= 4 && parts[0] === 'ctx' && parts[1] === 'request' && parts[2] === 'body') { - aliasMap.set(local, parts[3]); - addParam(parts[3], { source: 'body' }); - } - } - } - - if ((/allowedFields|eqFields/i).test(local) && node.init.type === 'ArrayExpression') { - const arr = []; - for (const el of node.init.elements || []) { - if (el && el.type === 'Literal' && typeof el.value === 'string') arr.push(el.value); - } - if (arr.length) listFields.push(...arr); - } - } - } - - if (node.type === 'IfStatement') { - addRequiredFromTest(node.test); - } - - if (node.type === 'CallExpression') { - const callee = memberPath(node.callee); - - if (callee === 'ctx.validate' && node.arguments[0] && node.arguments[0].type === 'ObjectExpression') { - for (const p of node.arguments[0].properties || []) { - if (p.type !== 'Property') continue; - const field = getPropName(p.key); - if (!field || p.value.type !== 'ObjectExpression') continue; - let required = false; - let type = null; - for (const conf of p.value.properties || []) { - if (conf.type !== 'Property') continue; - const confKey = getPropName(conf.key); - if (!confKey) continue; - if (confKey === 'required' && conf.value.type === 'Literal') { - required = Boolean(conf.value.value); - } - if (confKey === 'type' && conf.value.type === 'Literal') { - type = mapValidateType(conf.value.value); - } - } - addParam(field, { required, type: type || inferTypeByName(field), source: 'body' }); - } - } - - if (callee === 'Array.isArray' && node.arguments[0] && node.arguments[0].type === 'Identifier') { - const local = node.arguments[0].name; - const resolved = resolveName(local); - if (resolved !== local || entries.has(resolved)) { - addParam(resolved, { type: 'array' }); - } - } - - if ((callee === 'parseInt' || callee === 'Number') && node.arguments[0]) { - const arg = node.arguments[0]; - if (arg.type === 'Identifier') { - const resolved = resolveName(arg.name); - if (resolved !== arg.name || entries.has(resolved)) { - addParam(resolved, { type: 'number' }); - } - } - if (arg.type === 'MemberExpression' || arg.type === 'ChainExpression') { - const p = memberPath(arg); - if (p) { - const parts = p.split('.'); - if (parts.length === 2 && signatureSet.has(parts[0])) addParam(parts[1], { type: 'number', source: 'body' }); - } - } - } - } - - if (node.type === 'MemberExpression' || node.type === 'ChainExpression') { - const p = memberPath(node); - if (!p) return; - const parts = p.split('.'); - if (parts.length === 2 && signatureSet.has(parts[0])) { - addParam(parts[1], { source: 'body' }); - } - if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'query') { - addParam(parts[2], { source: 'query' }); - } - if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'params') { - addParam(parts[2], { source: 'path' }); - } - if (parts.length >= 4 && parts[0] === 'ctx' && parts[1] === 'request' && parts[2] === 'body') { - addParam(parts[3], { source: 'body' }); - } - } - }); - - for (const f of listFields) { - addParam(f, { source: 'body' }); - } - - const result = Array.from(entries.values()).map(item => ({ - name: item.name, - type: item.type, - required: item.required, - source: item.source.size ? Array.from(item.source).sort().join('|') : 'body', - description: `${item.name} 参数`, - })); - - result.sort((a, b) => { - if (a.required !== b.required) return a.required ? -1 : 1; - return a.name.localeCompare(b.name); - }); - - return result; -} - -function buildMethodParamMap() { - const map = new Map(); - const files = walkFiles(methodsDir); - - for (const file of files) { - const source = fs.readFileSync(file, 'utf8'); - const ast = acorn.parse(source, { ecmaVersion: 'latest', sourceType: 'script' }); - const relative = path.relative(methodsDir, file).replace(/\\/g, '/').replace(/\.js$/, ''); - const moduleName = relative.replace(/\//g, '.'); - - for (const node of ast.body) { - if (node.type !== 'ClassDeclaration') continue; - const noNeed = extractNoNeedLists(node); - for (const method of node.body.body) { - if (method.type !== 'MethodDefinition') continue; - if (method.kind !== 'method') continue; - if (!method.value.async) continue; - const methodName = method.key && method.key.name; - if (!methodName) continue; - - const fullMethod = `${moduleName}.${methodName}`; - const params = collectMethodParams(method); - - for (const p of params) { - if (noNeed.noNeedLogin.includes('*') || noNeed.noNeedLogin.includes(methodName)) { - if (p.name.toLowerCase().includes('authorization') || p.source === 'header') p.required = false; - } - } - - map.set(fullMethod, params); - } - } - } - - return map; -} - -const methodParamMap = buildMethodParamMap(); -const doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); - -let updated = 0; -for (const group of doc.methods.groups || []) { - for (const item of group.list || []) { - const next = methodParamMap.get(item.method) || []; - item.params = next; - updated++; - } -} - -doc.version = '0.3.0'; -doc.updatedAt = '2026-03-22'; - -fs.writeFileSync(jsonPath, JSON.stringify(doc, null, 2) + '\n', 'utf8'); -console.log(`updated methods: ${updated}`); -console.log(`mapped methods: ${methodParamMap.size}`); diff --git a/script/tmp-test-clean-plan.cjs b/script/tmp-test-clean-plan.cjs deleted file mode 100644 index 7fbe9da..0000000 --- a/script/tmp-test-clean-plan.cjs +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -/** - * 本地自测桩:模拟远端只读探测输出,验证 check-root-logs.cjs 的 - * --clean dry-run 删除计划逻辑(不连接任何真实服务器)。 - * - * 用法:node script/tmp-test-clean-plan.cjs --clean - */ - -const path = require('node:path'); - -const deployLibPath = require.resolve('./deploy-lib.cjs'); - -/** - * 构造模拟的远端探测输出: - * 总大小约 6.37 GiB(超过 4 GiB 阈值),包含活跃日志、7 个轮转日志、 - * 其他命名模式的日志与 .gz 文件,用于验证排除规则与删除计划 - * - * @return {string} 模拟的远端探测标准输出 - */ -function buildFakeProbeOutput() { - const files = [ - // 正在写入的活跃日志(无日期后缀),必须被排除 - { mtime: 1757780000, size: 1181116006, filePath: '/root/logs/wms/wms-web.log' }, - // 历史轮转日志(mtime 升序,最旧的 4 个较大) - { mtime: 1756150000, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-24' }, - { mtime: 1756236400, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-25' }, - { mtime: 1756322800, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-26' }, - { mtime: 1756409200, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-27' }, - { mtime: 1756495600, size: 214748365, filePath: '/root/logs/wms/wms-web.log.2026-08-28' }, - { mtime: 1756582000, size: 107374182, filePath: '/root/logs/wms/wms-web.log.2026-08-29' }, - { mtime: 1756668400, size: 107374182, filePath: '/root/logs/wms/wms-web.log.2026-08-30' }, - // 非 wms-web 轮转命名模式的文件,必须被排除 - { mtime: 1756583000, size: 29360128, filePath: '/root/logs/wms/common-error.log.2026-08-29' }, - { mtime: 1756720000, size: 12582912, filePath: '/root/logs/wms/egg-schedule.log.2026-08-31' }, - // .gz 后缀文件不符合严格命名模式,必须被排除 - { mtime: 1756730000, size: 31457280, filePath: '/root/logs/wms/wms-web.log.2026-08-31.gz' }, - ]; - const totalBytes = files.reduce((sum, item) => sum + item.size, 0); - return [ - `PROBE_TOTAL_BYTES=${totalBytes}`, - ...files.map(item => `${item.mtime}\t${item.size}\t${item.filePath}`), - ].join('\n'); -} - -// 将 deploy-lib.cjs 替换为本地桩,避免真实 SSH 连接 -require.cache[deployLibPath] = { - id: deployLibPath, - filename: deployLibPath, - loaded: true, - exports: { - ensureCommandAvailable() {}, - loadDeployConfig: () => ({ envName: 'production', username: 'root', host: '127.0.0.1', port: 22 }), - quoteForBash: value => `'${String(value)}'`, - runSsh: () => buildFakeProbeOutput(), - }, -}; - -// 加载被测脚本(其 main() 会读取当前进程参数,即 --clean) -require(path.resolve(__dirname, 'check-root-logs.cjs')); diff --git a/script/tmp-test-putaway-batch-compare.cjs b/script/tmp-test-putaway-batch-compare.cjs deleted file mode 100644 index d8963f7..0000000 --- a/script/tmp-test-putaway-batch-compare.cjs +++ /dev/null @@ -1,136 +0,0 @@ -'use strict'; -/** - * 批次维度对比测试(真实接口): - * 1. A 两步:批次 B-A-1 入库 10 件 → storage 建行 - * 2. B 一步:批次 B-B-1 入库 10 件 → storage 建行(不同批次不互相影响) - * 3. A 两步:批次 B-A-1 再入库 5 件 → 同批次累加到 15 - * 4. B 一步:批次 B-B-1 再入库 5 件 → 同批次累加到 15 - * 商品 159061 / 库位 5918。测试数据不清理。 - */ -const mysql = require('mysql2/promise'); -const jwt = require('jsonwebtoken'); - -const BASE = 'http://127.0.0.1:6060'; -const JWT_SECRET = 'E5#ex.g@,GfL_8?'; -const ACCOUNT_ID = 1; -const STORE_ID = 1000000; -const STOCK_ID = 159061; -const SPACE_ID = 5918; - -const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 }); - -async function db() { - return mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' }); -} - -async function call(method, data) { - const res = await fetch(`${BASE}/system?method=${method}&v=1×tamp=${Date.now()}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - platform: 'web', - project: 'all', - authorization: `Bearer ${token}`, - }, - body: JSON.stringify(data || {}), - }); - const text = await res.text(); - let parsed; - try { parsed = JSON.parse(text); } catch { parsed = text; } - return { http: res.status, body: parsed }; -} - -function step(name, res) { - const code = res.body && res.body.code; - const ok = res.http === 200 && res.body && res.body.flag === 'success' && (code === 200 || code === 1); - console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${code} msg=${res.body && res.body.message}`); - if (!ok) console.log(' 响应:', JSON.stringify(res.body).slice(0, 600)); - return ok; -} - -async function runFlow(tag, mode, batchNo, qty) { - console.log(`\n===== ${tag}:批次=${batchNo} 数量=${qty} =====`); - const conn = await db(); - const [before] = await conn.query( - `SELECT quantity FROM wms_stock_warehouse WHERE id = ?`, [ STOCK_ID ] - ); - - // 收货单全链路 - const createRes = await call('storage.receiving.create', { - store_id: STORE_ID, delivery_method: 'other', loading_method: 'with_pallet', - remark: `[批次对比-${tag}-${batchNo}]`, status: 'receiving', - }); - const b = createRes.body || {}; - const receivingId = (b.data && b.data.id) || b.id; - if (!step('创建收货单', createRes)) { await conn.end(); return null; } - - const addRes = await call('storage.receiving.addDetail', { - receiving_id: receivingId, - item: { product_name: '批次对比测试商品', barcode: `B${Date.now()}`, actual_quantity: qty, batch_number: batchNo, space_id: SPACE_ID }, - }); - const addBody = addRes.body || {}; - const addData = addBody.data || addBody; - const detailId = addData.selectId || (addData.details && addData.details[0] && addData.details[0].id); - if (!step('添加明细', addRes)) { await conn.end(); return null; } - - if (!step('绑定商品', await call('storage.receiving.bindDetailProduct', { detail_id: detailId, system_product_id: STOCK_ID }))) { await conn.end(); return null; } - if (!step('完成收货', await call('storage.receiving.completeReceiving', { id: receivingId }))) { await conn.end(); return null; } - if (!step('审核', await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] }))) { await conn.end(); return null; } - - let entryOrderId; - if (mode === 'A') { - const pRes = await call('storage.inventory.quickPutaway', { receiving_id: receivingId }); - if (!step('quickPutaway', pRes)) { await conn.end(); return null; } - entryOrderId = pRes.body.data.entry_order_id; - if (!step('addItem(绑定收货明细)', await call('storage.entry.addItem', { - entry_order_id: entryOrderId, - items: [{ stock_id: STOCK_ID, quantity: qty, space_id: SPACE_ID, receiving_detail_id: detailId, allocated_quantity: qty, inbound_type: 'pda' }], - }))) { await conn.end(); return null; } - if (!step('commit', await call('storage.entry.commit', { entry_order_id: entryOrderId }))) { await conn.end(); return null; } - } else { - const dRes = await call('storage.inventory.directPutaway', { receiving_id: receivingId }); - if (!step('directPutaway', dRes)) { await conn.end(); return null; } - entryOrderId = dRes.body.data.entry_order_id; - } - - const [after] = await conn.query( - `SELECT quantity FROM wms_stock_warehouse WHERE id = ?`, [ STOCK_ID ] - ); - console.log(` ── wms_stock_warehouse ${STOCK_ID}: ${before[0].quantity} → ${after[0].quantity}(+${qty})`); - - const [storages] = await conn.query( - `SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, available_quantity, inbound_order_no, entry_order_id - FROM wms_storage WHERE stock_id = ? AND space_id = ? ORDER BY batch_no`, [ STOCK_ID, SPACE_ID ] - ); - console.log(' ── wms_storage(商品 159061 / 库位 5918 全部行)──'); - console.log(' ', JSON.stringify(storages)); - - await conn.end(); - return { receivingId, entryOrderId }; -} - -async function main() { - await runFlow('① A-两步', 'A', 'B-A-1', 10); - await runFlow('② B-一步', 'B', 'B-B-1', 10); - await runFlow('③ A-两步(同批次累加)', 'A', 'B-A-1', 5); - await runFlow('④ B-一步(同批次累加)', 'B', 'B-B-1', 5); - - const conn = await db(); - const [storages] = await conn.query( - `SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, inbound_order_no, receiving_id, entry_order_id - FROM wms_storage WHERE stock_id = 159061 AND space_id = 5918 ORDER BY batch_no` - ); - console.log('\n========== 最终 wms_storage 对比(商品 159061 / 库位 5918) =========='); - console.log(JSON.stringify(storages, null, 2)); - - const [txns] = await conn.query( - `SELECT order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type - FROM wms_storage_transaction WHERE stock_id = 159061 AND space_id = 5918 AND batch_no IN ('B-A-1','B-B-1') ORDER BY id` - ); - console.log('\n========== 库位流水(批次 B-A-1 / B-B-1) =========='); - console.log(JSON.stringify(txns, null, 2)); - await conn.end(); - console.log('\n================ 批次对比测试结束 ================'); -} - -main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-test-putaway-compare.cjs b/script/tmp-test-putaway-compare.cjs deleted file mode 100644 index 8042905..0000000 --- a/script/tmp-test-putaway-compare.cjs +++ /dev/null @@ -1,261 +0,0 @@ -'use strict'; -/** - * 临时对比测试:quickPutaway(转入库单) vs directPutaway(直入库存) - * 全链路走真实接口:创建收货单 → 添加明细 → 绑定商品 → 完成收货 → 审核 → 上架。 - * 测试数据不清理,保留以便核对。 - * 用法:node script/tmp-test-putaway-compare.cjs - */ -const mysql = require('mysql2/promise'); -const jwt = require('jsonwebtoken'); - -const BASE = 'http://127.0.0.1:6060'; -const JWT_SECRET = 'E5#ex.g@,GfL_8?'; -const ACCOUNT_ID = 1; -const WAREHOUSE_ID = 100000; -const STORE_ID = 1000000; - -// 商品:159061 非批次非效期;159064 效期管理(非批次) -const PRODUCTS = [ - { stock_id: 159061, item_code: '20260703', qty: 30, batch_number: 'TQB1', space_id: null }, - { stock_id: 159064, item_code: '544354', qty: 7, batch_number: 'TQB2', production_date: '2026-01-01', expiry_date: '2027-01-01', space_id: null }, -]; - -const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 }); - -async function db() { - return mysql.createConnection({ - host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms', - }); -} - -async function call(method, data) { - const res = await fetch(`${BASE}/system?method=${method}&v=1×tamp=${Date.now()}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - platform: 'web', - project: 'all', - authorization: `Bearer ${token}`, - }, - body: JSON.stringify(data || {}), - }); - const text = await res.text(); - let parsed; - try { parsed = JSON.parse(text); } catch { parsed = text; } - return { http: res.status, body: parsed }; -} - -function step(name, res, extract) { - const bodyCode = res.body && res.body.code; - const ok = res.http === 200 && res.body && res.body.flag === 'success' && (bodyCode === 200 || bodyCode === 1); - let extra = ''; - if (extract && res.body && res.body.data) { - try { extra = JSON.stringify(extract(res.body.data)); } catch (e) { /* ignore */ } - } - console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${bodyCode} msg=${res.body && res.body.message} ${extra}`); - return ok; -} - -async function runFlow(tag, putawayMethod) { - console.log(`\n================ 流程 ${tag}(${putawayMethod}) ================`); - const conn = await db(); - - // 快照入库前商品总库存 - const stockIds = PRODUCTS.map(p => p.stock_id); - const [beforeStock] = await conn.query( - `SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ] - ); - - // 1. 创建收货单 - const createRes = await call('storage.receiving.create', { - store_id: STORE_ID, - delivery_method: 'other', - loading_method: 'with_pallet', - remark: `[自动对比测试-${tag}]`, - status: 'receiving', - }); - const createBody = createRes.body || {}; - const receivingId = createBody.data && createBody.data.id ? createBody.data.id : createBody.id; - const receivingNumber = (createBody.data && createBody.data.receiving_number) || createBody.receiving_number; - if (!step('创建收货单', createRes, () => ({ id: receivingId, receiving_number: receivingNumber }))) { - console.log(' create 响应:', JSON.stringify(createBody).slice(0, 600)); - return { conn, receivingId: 0 }; - } - console.log(` receiving_id=${receivingId} receiving_number=${receivingNumber}`); - - // 2. 添加明细(含库位) - const detailIds = []; - for (let i = 0; i < PRODUCTS.length; i++) { - const p = PRODUCTS[i]; - const addRes = await call('storage.receiving.addDetail', { - receiving_id: receivingId, - item: { - product_name: `对比测试商品${i + 1}`, - barcode: `TMPBC${Date.now()}${i}`, - actual_quantity: p.qty, - batch_number: p.batch_number, - production_date: p.production_date || null, - expiry_date: p.expiry_date || null, - space_id: p.space_id, - }, - }); - const addBody = addRes.body || {}; - const addData = addBody.data || addBody; - const newDetailId = addData.selectId - || (addData.details && Array.isArray(addData.details) && addData.details[0] && addData.details[0].id); - if (!step(`添加明细#${i + 1}`, addRes, () => ({ detail_id: newDetailId }))) { - console.log(' addDetail 响应:', JSON.stringify(addBody).slice(0, 600)); - return { conn, receivingId }; - } - detailIds.push(newDetailId); - } - - // 3. 绑定系统商品 - for (let i = 0; i < PRODUCTS.length; i++) { - const bindRes = await call('storage.receiving.bindDetailProduct', { - detail_id: detailIds[i], - system_product_id: PRODUCTS[i].stock_id, - }); - if (!step(`绑定商品#${i + 1}`, bindRes, d => ({ detail_id: d.detail_id, system_product_id: d.system_product_id }))) return { conn, receivingId }; - } - - // 4. 完成收货 - const completeRes = await call('storage.receiving.completeReceiving', { id: receivingId }); - if (!step('完成收货', completeRes, d => ({ status: d.status || d.receiving_status }))) { - console.log(' completeReceiving 响应:', JSON.stringify(completeRes.body).slice(0, 500)); - return { conn, receivingId }; - } - - // 5. 审核 - const reviewRes = await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] }); - if (!step('审核收货单', reviewRes)) { - console.log(' reviewReceiving 响应:', JSON.stringify(reviewRes.body).slice(0, 500)); - return { conn, receivingId }; - } - - // 6. 上架 - const putawayRes = await call(putawayMethod, { receiving_id: receivingId }); - if (!step(`上架(${putawayMethod})`, putawayRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) { - console.log(' 上架响应:', JSON.stringify(putawayRes.body).slice(0, 800)); - return { conn, receivingId }; - } - - // 7. 对比验证数据 - const entryOrderId = putawayRes.body.data.entry_order_id; - const entryOrderCode = putawayRes.body.data.entry_order_code; - - const [afterStock] = await conn.query( - `SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ] - ); - console.log(' ── 商品总库存(wms_stock_warehouse)──'); - for (const b of beforeStock) { - const a = afterStock.find(x => String(x.id) === String(b.id)) || { quantity: '?', locked_quantity: '?' }; - console.log(` stock_id=${b.id} before=${b.quantity} after=${a.quantity} locked=${a.locked_quantity}`); - } - - const [entryOrder] = await conn.query( - `SELECT id, entry_order_code, order_type, order_status, sync_status, total_order_lines FROM wms_entry_order WHERE id = ?`, [ entryOrderId ] - ); - console.log(' ── 入库单(wms_entry_order)──'); - console.log(' ', JSON.stringify(entryOrder[0] || null)); - - const [entryItems] = await conn.query( - `SELECT order_line_no, item_code, stock_id, count, received_quantity, inventory_type FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ entryOrderId ] - ); - console.log(' ── 入库单明细(wms_entry_items,共 ' + entryItems.length + ' 行)──'); - console.log(' ', JSON.stringify(entryItems)); - - const [orderReceiving] = await conn.query( - `SELECT entry_order_id, receiving_id FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ entryOrderId ] - ); - console.log(' ── 绑定(wms_entry_order_receiving)──'); - console.log(' ', JSON.stringify(orderReceiving)); - - const [receivingRow] = await conn.query( - `SELECT id, status, is_review, storage_status, detail_status FROM wms_receiving WHERE id = ?`, [ receivingId ] - ); - console.log(' ── 收货单主表(wms_receiving)──'); - console.log(' ', JSON.stringify(receivingRow[0] || null)); - - const [receivingDetails] = await conn.query( - `SELECT id, system_product_id, actual_quantity, stored_quantity, storage_status, space_id, batch_number FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ receivingId ] - ); - console.log(' ── 收货明细(wms_receiving_detail)──'); - console.log(' ', JSON.stringify(receivingDetails)); - - const [storages] = await conn.query( - `SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, - inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date - FROM wms_storage - WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?) - ORDER BY id`, [ entryOrderId, entryOrderCode, receivingId ] - ); - console.log(' ── 库位库存(wms_storage,共 ' + storages.length + ' 行)──'); - console.log(' ', JSON.stringify(storages)); - - const [stockTxns] = await conn.query( - `SELECT transaction_type, stock_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id - FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ] - ); - console.log(' ── 商品流水(wms_stock_transaction,共 ' + stockTxns.length + ' 行)──'); - console.log(' ', JSON.stringify(stockTxns)); - - const [storageTxns] = await conn.query( - `SELECT transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no - FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ] - ); - console.log(' ── 库位流水(wms_storage_transaction,共 ' + storageTxns.length + ' 行)──'); - console.log(' ', JSON.stringify(storageTxns)); - - const [opLogs] = await conn.query( - `SELECT business_type, operation_code, business_id, operator_name, message - FROM wms_operation_log WHERE business_id = ? ORDER BY id`, [ String(entryOrderId) ] - ); - console.log(' ── 操作日志(wms_operation_log,共 ' + opLogs.length + ' 行)──'); - console.log(' ', JSON.stringify(opLogs)); - - await conn.end(); - return { receivingId, entryOrderId, entryOrderCode }; -} - -async function main() { - const conn = await db(); - // 取两个真实库位 - const [spaces] = await conn.query( - `SELECT id, space_code FROM wms_location_space WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL ORDER BY id LIMIT 3`, - [ WAREHOUSE_ID ] - ); - console.log('使用库位:', JSON.stringify(spaces)); - PRODUCTS[0].space_id = spaces[0].id; - PRODUCTS[1].space_id = spaces[1] ? spaces[1].id : spaces[0].id; - - // 开关状态:quick 已开(货主 1000000 配置为 1);direct 需开启 - const [beforePolicy] = await conn.query( - `SELECT policy_config FROM wms_store_warehouse WHERE store_id = ? AND warehouse_id = ?`, [ STORE_ID, WAREHOUSE_ID ] - ); - console.log('货主 policy_config:', JSON.stringify(beforePolicy[0] && beforePolicy[0].policy_config)); - await conn.end(); - - // 流程 A:转入库单(可用 node script/tmp-test-putaway-compare.cjs A 单独跑) - if (!process.argv[2] || process.argv[2] === 'A') { - await runFlow('A-quickPutaway', 'storage.inventory.quickPutaway'); - } - - // 开启直入开关(测试准备,SQL 直接配置) - const conn2 = await db(); - await conn2.query( - `UPDATE wms_store_warehouse SET policy_config = JSON_SET(COALESCE(policy_config,'{}'), '$.allow_receiving_direct_putaway', 1) - WHERE store_id = ? AND warehouse_id = ?`, [ STORE_ID, WAREHOUSE_ID ] - ); - await conn2.end(); - console.log('\n已开启 allow_receiving_direct_putaway=1(store=1000000, warehouse=100000)'); - - // 流程 B:直入库存 - if (!process.argv[2] || process.argv[2] === 'B') { - await runFlow('B-directPutaway', 'storage.inventory.directPutaway'); - } - - console.log('\n================ 测试结束 ================'); -} - -main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-test-putaway-full-compare.cjs b/script/tmp-test-putaway-full-compare.cjs deleted file mode 100644 index 7336513..0000000 --- a/script/tmp-test-putaway-full-compare.cjs +++ /dev/null @@ -1,281 +0,0 @@ -'use strict'; -/** - * 临时完整对比测试: - * 流程 A(两步):storage.inventory.quickPutaway(转入库单) - * → storage.entry.addItem(导入入库,绑定收货明细) - * → storage.entry.commit(提交确认写库存) - * 流程 B(一步):storage.inventory.directPutaway(直入库存) - * 收货单链路全部走真实接口。测试数据不清理。 - * 用法:node script/tmp-test-putaway-full-compare.cjs [A|B] - */ -const mysql = require('mysql2/promise'); -const jwt = require('jsonwebtoken'); - -const BASE = 'http://127.0.0.1:6060'; -const JWT_SECRET = 'E5#ex.g@,GfL_8?'; -const ACCOUNT_ID = 1; -const WAREHOUSE_ID = 100000; -const STORE_ID = 1000000; - -const PRODUCTS = [ - { stock_id: 159061, item_code: '20260703', qty: 30, batch_number: 'TQB1', space_id: null }, - { stock_id: 159064, item_code: '544354', qty: 7, batch_number: 'TQB2', production_date: '2026-01-01', expiry_date: '2027-01-01', space_id: null }, -]; - -const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 }); - -async function db() { - return mysql.createConnection({ - host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms', - }); -} - -async function call(method, data) { - const res = await fetch(`${BASE}/system?method=${method}&v=1×tamp=${Date.now()}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - platform: 'web', - project: 'all', - authorization: `Bearer ${token}`, - }, - body: JSON.stringify(data || {}), - }); - const text = await res.text(); - let parsed; - try { parsed = JSON.parse(text); } catch { parsed = text; } - return { http: res.status, body: parsed }; -} - -function step(name, res, extract) { - const bodyCode = res.body && res.body.code; - const ok = res.http === 200 && res.body && res.body.flag === 'success' && (bodyCode === 200 || bodyCode === 1); - let extra = ''; - if (extract && res.body && res.body.data) { - try { extra = JSON.stringify(extract(res.body.data)); } catch (e) { /* ignore */ } - } - console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${bodyCode} msg=${res.body && res.body.message} ${extra}`); - return ok; -} - -async function verifyFlow(conn, tag, receivingId, entryOrderId, entryOrderCode, beforeStock) { - const stockIds = PRODUCTS.map(p => p.stock_id); - const [afterStock] = await conn.query( - `SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ] - ); - console.log(` ── [${tag}] 商品总库存(wms_stock_warehouse)──`); - for (const b of beforeStock) { - const a = afterStock.find(x => String(x.id) === String(b.id)) || { quantity: '?', locked_quantity: '?' }; - console.log(` stock_id=${b.id} before=${b.quantity} after=${a.quantity} locked=${a.locked_quantity}`); - } - - const [entryOrder] = await conn.query( - `SELECT id, entry_order_code, order_type, order_status, sync_status, total_order_lines FROM wms_entry_order WHERE id = ?`, [ entryOrderId ] - ); - console.log(` ── [${tag}] 入库单(wms_entry_order)──`); - console.log(' ', JSON.stringify(entryOrder[0] || null)); - - const [entryItems] = await conn.query( - `SELECT order_line_no, item_code, stock_id, count, received_quantity, inventory_type FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ entryOrderId ] - ); - console.log(` ── [${tag}] 入库单明细(wms_entry_items,共 ${entryItems.length} 行)──`); - console.log(' ', JSON.stringify(entryItems)); - - const [orderReceiving] = await conn.query( - `SELECT entry_order_id, receiving_id FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ entryOrderId ] - ); - console.log(` ── [${tag}] 绑定(wms_entry_order_receiving)──`); - console.log(' ', JSON.stringify(orderReceiving)); - - const [receivingRow] = await conn.query( - `SELECT id, status, is_review, storage_status, detail_status FROM wms_receiving WHERE id = ?`, [ receivingId ] - ); - console.log(` ── [${tag}] 收货单主表(wms_receiving)──`); - console.log(' ', JSON.stringify(receivingRow[0] || null)); - - const [receivingDetails] = await conn.query( - `SELECT id, system_product_id, actual_quantity, stored_quantity, storage_status, space_id, batch_number FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ receivingId ] - ); - console.log(` ── [${tag}] 收货明细(wms_receiving_detail)──`); - console.log(' ', JSON.stringify(receivingDetails)); - - const [storages] = await conn.query( - `SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, - inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date - FROM wms_storage - WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?) - ORDER BY id`, [ entryOrderId, entryOrderCode, receivingId ] - ); - console.log(` ── [${tag}] 库位库存(wms_storage,共 ${storages.length} 行)──`); - console.log(' ', JSON.stringify(storages)); - - const [stockTxns] = await conn.query( - `SELECT transaction_type, stock_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id - FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ] - ); - console.log(` ── [${tag}] 商品流水(wms_stock_transaction,共 ${stockTxns.length} 行)──`); - console.log(' ', JSON.stringify(stockTxns)); - - const [storageTxns] = await conn.query( - `SELECT transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no - FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ] - ); - console.log(` ── [${tag}] 库位流水(wms_storage_transaction,共 ${storageTxns.length} 行)──`); - console.log(' ', JSON.stringify(storageTxns)); - - const [directLogs] = await conn.query( - `SELECT id, stock_id, quantity, entry_item_id, receiving_detail_id, space_id, status, inbound_type - FROM wms_inbound_direct_log WHERE entry_order_id = ? ORDER BY id`, [ entryOrderId ] - ); - console.log(` ── [${tag}] 导入入库记录(wms_inbound_direct_log,共 ${directLogs.length} 行)──`); - console.log(' ', JSON.stringify(directLogs)); - - const [opLogs] = await conn.query( - `SELECT business_type, operation_code, operator_name, message - FROM wms_operation_log WHERE business_id = ? AND operation_code IN - ('ENTRY_ORDER_QUICK_PUTAWAY','ENTRY_ORDER_DIRECT_PUTAWAY','STORAGE_DIRECT_PUTAWAY','STOCK_DIRECT_PUTAWAY','DIRECT_INBOUND_ADD','DIRECT_INBOUND_COMMIT') - ORDER BY id`, [ String(entryOrderId) ] - ); - console.log(` ── [${tag}] 本流程操作日志(wms_operation_log,共 ${opLogs.length} 行)──`); - console.log(' ', JSON.stringify(opLogs)); -} - -async function runFlow(tag, mode) { - console.log(`\n================ 流程 ${tag}(${mode}) ================`); - const conn = await db(); - - const stockIds = PRODUCTS.map(p => p.stock_id); - const [beforeStock] = await conn.query( - `SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ] - ); - - // 收货单全链路 - const createRes = await call('storage.receiving.create', { - store_id: STORE_ID, - delivery_method: 'other', - loading_method: 'with_pallet', - remark: `[完整对比测试-${tag}]`, - status: 'receiving', - }); - const createBody = createRes.body || {}; - const receivingId = createBody.data && createBody.data.id ? createBody.data.id : createBody.id; - const receivingNumber = (createBody.data && createBody.data.receiving_number) || createBody.receiving_number; - if (!step('创建收货单', createRes, () => ({ id: receivingId, receiving_number: receivingNumber }))) { - await conn.end(); return; - } - console.log(` receiving_id=${receivingId} receiving_number=${receivingNumber}`); - - const detailIds = []; - for (let i = 0; i < PRODUCTS.length; i++) { - const p = PRODUCTS[i]; - const addRes = await call('storage.receiving.addDetail', { - receiving_id: receivingId, - item: { - product_name: `完整对比测试商品${i + 1}`, - barcode: `FULLBC${Date.now()}${i}`, - actual_quantity: p.qty, - batch_number: p.batch_number, - production_date: p.production_date || null, - expiry_date: p.expiry_date || null, - space_id: p.space_id, - }, - }); - const addBody = addRes.body || {}; - const addData = addBody.data || addBody; - const newDetailId = addData.selectId - || (addData.details && Array.isArray(addData.details) && addData.details[0] && addData.details[0].id); - if (!step(`添加明细#${i + 1}`, addRes, () => ({ detail_id: newDetailId }))) { await conn.end(); return; } - detailIds.push(newDetailId); - } - - for (let i = 0; i < PRODUCTS.length; i++) { - const bindRes = await call('storage.receiving.bindDetailProduct', { - detail_id: detailIds[i], - system_product_id: PRODUCTS[i].stock_id, - }); - if (!step(`绑定商品#${i + 1}`, bindRes, d => ({ detail_id: d.detail_id, system_product_id: d.system_product_id }))) { await conn.end(); return; } - } - - const completeRes = await call('storage.receiving.completeReceiving', { id: receivingId }); - if (!step('完成收货', completeRes)) { - console.log(' completeReceiving 响应:', JSON.stringify(completeRes.body).slice(0, 500)); - await conn.end(); return; - } - - const reviewRes = await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] }); - if (!step('审核收货单', reviewRes)) { - console.log(' reviewReceiving 响应:', JSON.stringify(reviewRes.body).slice(0, 500)); - await conn.end(); return; - } - - let entryOrderId; - let entryOrderCode; - - if (mode === 'A') { - // 两步流程第一步:转入库单 - const putawayRes = await call('storage.inventory.quickPutaway', { receiving_id: receivingId }); - if (!step('① quickPutaway(转入库单)', putawayRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) { - console.log(' 响应:', JSON.stringify(putawayRes.body).slice(0, 600)); - await conn.end(); return; - } - entryOrderId = putawayRes.body.data.entry_order_id; - entryOrderCode = putawayRes.body.data.entry_order_code; - - // 两步流程第二步:导入入库(绑定收货明细 + 收货明细库位) - const addItemRes = await call('storage.entry.addItem', { - entry_order_id: entryOrderId, - items: [ - { stock_id: PRODUCTS[0].stock_id, quantity: PRODUCTS[0].qty, space_id: PRODUCTS[0].space_id, receiving_detail_id: detailIds[0], allocated_quantity: PRODUCTS[0].qty, inbound_type: 'pda' }, - { stock_id: PRODUCTS[1].stock_id, quantity: PRODUCTS[1].qty, space_id: PRODUCTS[1].space_id, receiving_detail_id: detailIds[1], allocated_quantity: PRODUCTS[1].qty, inbound_type: 'pda' }, - ], - }); - if (!step('② storage.entry.addItem(导入入库,绑定收货明细)', addItemRes, d => ({ count: d.count, total_quantity: d.total_quantity }))) { - console.log(' 响应:', JSON.stringify(addItemRes.body).slice(0, 800)); - await conn.end(); return; - } - - // 两步流程第三步:提交确认写库存 - const commitRes = await call('storage.entry.commit', { entry_order_id: entryOrderId }); - if (!step('③ storage.entry.commit(提交确认入库)', commitRes, d => ({ success: d.success, message: d.message }))) { - console.log(' 响应:', JSON.stringify(commitRes.body).slice(0, 800)); - await conn.end(); return; - } - } else { - // 一步直入 - const directRes = await call('storage.inventory.directPutaway', { receiving_id: receivingId }); - if (!step('① directPutaway(一步直入)', directRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) { - console.log(' 响应:', JSON.stringify(directRes.body).slice(0, 600)); - await conn.end(); return; - } - entryOrderId = directRes.body.data.entry_order_id; - entryOrderCode = directRes.body.data.entry_order_code; - } - - await verifyFlow(conn, tag, receivingId, entryOrderId, entryOrderCode, beforeStock); - await conn.end(); - console.log(`================ 流程 ${tag} 完成:receiving=${receivingId} entry_order=${entryOrderId} ================`); -} - -async function main() { - const conn = await db(); - const [spaces] = await conn.query( - `SELECT id, space_code FROM wms_location_space WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL ORDER BY id LIMIT 2`, - [ WAREHOUSE_ID ] - ); - console.log('使用库位:', JSON.stringify(spaces)); - PRODUCTS[0].space_id = spaces[0].id; - PRODUCTS[1].space_id = spaces[1] ? spaces[1].id : spaces[0].id; - await conn.end(); - - const only = (process.argv[2] || '').toUpperCase(); - if (!only || only === 'A') { - await runFlow('A-两步', 'A'); - } - if (!only || only === 'B') { - await runFlow('B-一步', 'B'); - } - - console.log('\n================ 测试结束 ================'); -} - -main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-test-stockreport-fix-dev.cjs b/script/tmp-test-stockreport-fix-dev.cjs deleted file mode 100644 index 8d4c5d8..0000000 --- a/script/tmp-test-stockreport-fix-dev.cjs +++ /dev/null @@ -1,632 +0,0 @@ -/** - * 只读校验脚本(开发库 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 deleted file mode 100644 index 83c9c83..0000000 --- a/script/tmp-trace-wave-closure-cause.cjs +++ /dev/null @@ -1,25 +0,0 @@ -'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', - 'F=/www/wwwroot/qimen/v2/app/service/systemMethods/order/wave.js', - 'echo "===GREP_FUNCS==="', - 'grep -n "async batchCancel\\|batchCancelWave\\|cancelSingleWave\\|wave_status = -1\\|wave_status: -1" "$F" 2>/dev/null | head -20 || true', - 'echo "===SHOW_BATCHCANCEL_REGION==="', - 'S=$(grep -n "async batchCancel(" "$F" | head -1 | cut -d: -f1)', - 'if [ -n "$S" ]; then sed -n "${S},$((S+120))p" "$F"; fi', - ].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 deleted file mode 100644 index 6aec3a3..0000000 --- a/script/tmp-unbind-prod-cart.cjs +++ /dev/null @@ -1,104 +0,0 @@ -'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-update-ai-method-routing.cjs b/script/tmp-update-ai-method-routing.cjs deleted file mode 100644 index aee37fc..0000000 --- a/script/tmp-update-ai-method-routing.cjs +++ /dev/null @@ -1,30 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -const root = process.cwd(); -const target = path.join(root, 'AI_METHOD_ROUTING.md'); -const inventoryPath = path.join(root, 'temp', 'tmp-service-method-inventory.md'); - -const base = fs.readFileSync(target, 'utf8'); -const inventory = fs.readFileSync(inventoryPath, 'utf8').trim(); - -const section = `\n\n## 6. 全量 Service Method 能力清单(自动扫描)\n\n维护说明:\n- 扫描范围:app/service/**/*.js\n- 本节内容由脚本生成,新增/修改 service 后请同步刷新。\n- 刷新命令:node .\\script\\tmp-gen-service-method-inventory.cjs\n- 临时清单输出:temp/tmp-service-method-inventory.md\n\n\n${inventory}\n\n`; - -const begin = ''; -const end = ''; - -let next; -if (base.includes(begin) && base.includes(end)) { - const start = base.indexOf(begin); - const finish = base.indexOf(end) + end.length; - const head = base.slice(0, base.lastIndexOf('\n## 6. 全量 Service Method 能力清单(自动扫描)', start) >= 0 - ? base.lastIndexOf('\n## 6. 全量 Service Method 能力清单(自动扫描)', start) - : start); - const tail = base.slice(finish); - next = head.trimEnd() + section + tail; -} else { - next = base.trimEnd() + section; -} - -fs.writeFileSync(target, next + '\n', 'utf8'); -console.log('UPDATED AI_METHOD_ROUTING.md'); diff --git a/script/tmp-verify-all-tables.cjs b/script/tmp-verify-all-tables.cjs deleted file mode 100644 index a022480..0000000 --- a/script/tmp-verify-all-tables.cjs +++ /dev/null @@ -1,103 +0,0 @@ -'use strict'; -/** - * 全表核对:A 两步链路(收货单 1526 / 入库单 383) vs B 一步直入(收货单 1528 / 入库单 385) - * 覆盖 A 链路涉及的所有表(收货单阶段 + 转入库单 + 导入入库 + 提交确认)。 - * 只读,不产生数据。 - */ -const mysql = require('mysql2/promise'); - -const A = { receiving: 1526, entryOrder: 383, code: 'SCRK202608240003', detailIds: [ 2711, 2712 ] }; -const B = { receiving: 1528, entryOrder: 385, code: 'SCRK202608240005', detailIds: [ 2715, 2716 ] }; - -(async () => { - const conn = await mysql.createConnection({ - host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms', - }); - - const show = async (title, sql, params) => { - const [rows] = await conn.query(sql, params); - console.log(`\n===== ${title} =====`); - console.log(JSON.stringify(rows, null, 2)); - }; - - for (const [ tag, t ] of [ [ 'A-两步', A ], [ 'B-一步', B ] ]) { - console.log(`\n########## ${tag}(receiving=${t.receiving}, entry_order=${t.entryOrder}) ##########`); - - await show('1. wms_receiving 收货单主表', ` - SELECT id, receiving_number, status, is_review, storage_status, detail_status, store_id, warehouse_id, total_items, total_quantity - FROM wms_receiving WHERE id = ?`, [ t.receiving ]); - - await show('2. wms_receiving_detail 收货明细', ` - SELECT id, receiving_id, system_product_id, actual_quantity, stored_quantity, storage_status, - space_id, batch_number, production_date, expiry_date, barcode, receiving_status - FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ t.receiving ]); - - await show('3. wms_entry_order 入库单', ` - SELECT id, entry_order_code, order_type, order_status, sync_status, sync_message, source_type, - total_order_lines, warehouse_id, store_id, store_name, warehouse_name, remark - FROM wms_entry_order WHERE id = ?`, [ t.entryOrder ]); - - await show('4. wms_entry_items 入库明细', ` - SELECT id, order_id, order_line_no, item_code, stock_id, count, received_quantity, confirm_quantity, inventory_type - FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ t.entryOrder ]); - - await show('5. wms_entry_order_receiving 主表绑定', ` - SELECT id, entry_order_id, receiving_id, created_at FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ t.entryOrder ]); - - await show('6. wms_inbound_direct_log 导入入库记录(两步中间态)', ` - SELECT id, entry_order_id, entry_order_code, stock_id, quantity, entry_item_id, receiving_detail_id, space_id, status, inbound_type, remark - FROM wms_inbound_direct_log WHERE entry_order_id = ? ORDER BY id`, [ t.entryOrder ]); - - await show('7. wms_stock_warehouse 商品总库存', ` - SELECT id, item_code, quantity, locked_quantity, is_valid FROM wms_stock_warehouse WHERE id IN (159061, 159064) ORDER BY id`); - - await show('8. wms_storage 库位库存', ` - SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, - inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date, inbound_time - FROM wms_storage WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?) ORDER BY id`, - [ t.entryOrder, t.code, t.receiving ]); - - await show('9. wms_stock_transaction 商品流水', ` - SELECT id, transaction_type, stock_id, quantity, before_quantity, after_quantity, - before_locked_quantity, after_locked_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id, remark - FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ t.code, t.entryOrder ]); - - await show('10. wms_storage_transaction 库位流水', ` - SELECT id, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, - before_locked_quantity, after_locked_quantity, batch_no, inventory_type, order_type, order_no, order_id - FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ t.code, t.entryOrder ]); - - await show('11. wms_operation_log 本流程操作日志', ` - SELECT id, business_type, business_id, operation_code, operator_name, warehouse_id, message - FROM wms_operation_log - WHERE business_id = ? AND operation_code IN - ('RECEIVING_CREATE','RECEIVING_ADD_DETAIL','RECEIVING_BIND_PRODUCT','RECEIVING_COMPLETE','RECEIVING_REVIEW', - 'ENTRY_ORDER_QUICK_PUTAWAY','DIRECT_INBOUND_ADD','DIRECT_INBOUND_COMMIT', - 'ENTRY_ORDER_DIRECT_PUTAWAY','STORAGE_DIRECT_PUTAWAY','STOCK_DIRECT_PUTAWAY') - ORDER BY id`, [ String(t.entryOrder) ]); - - await show('12. wms_operation_log 收货单维度操作日志', ` - SELECT id, business_type, business_id, operation_code, operator_name, warehouse_id, message - FROM wms_operation_log WHERE business_id = ? ORDER BY id`, [ String(t.receiving) ]); - - await show('13. wms_store_warehouse 货主签约与开关', ` - SELECT id, store_id, warehouse_id, warehouse_use_status, - JSON_EXTRACT(policy_config, '$.allow_receiving_quick_putaway') AS quick, - JSON_EXTRACT(policy_config, '$.allow_receiving_direct_putaway') AS direct - FROM wms_store_warehouse WHERE store_id = 1000000 AND warehouse_id = 100000`); - - await show('14. wms_stock_barcodes 本次绑定的条码', ` - SELECT id, stock_id, warehouse_id, barcode - FROM wms_stock_barcodes - WHERE stock_id IN (159061, 159064) - AND barcode IN (SELECT barcode FROM wms_receiving_detail WHERE receiving_id = ?) - ORDER BY id`, [ t.receiving ]); - - await show('15. wms_location_space 库位统计快照(入库链路不维护该统计)', ` - SELECT id, space_code, current_quantity, current_sku_count, is_enabled - FROM wms_location_space WHERE id IN (5918, 5919)`); - } - - await conn.end(); - process.exit(0); -})().catch(e => { console.error(e); process.exit(1); }); diff --git a/script/tmp-verify-batch-no-array.cjs b/script/tmp-verify-batch-no-array.cjs deleted file mode 100644 index ac13d43..0000000 --- a/script/tmp-verify-batch-no-array.cjs +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -/** - * 临时核验脚本:查询生产库 wms_wave_pick_task.batch_no_array 字段是否已添加。 - */ - -const dbConfig = require('../database/config.js'); -const Sequelize = require('sequelize'); - -(async () => { - const cfg = dbConfig.production; - const s = new Sequelize(cfg.database, cfg.username, cfg.password, { - host: cfg.host, - port: cfg.port, - dialect: cfg.dialect || 'mysql', - logging: false, - }); - - const [ rows ] = await s.query( - "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT " - + "FROM INFORMATION_SCHEMA.COLUMNS " - + "WHERE TABLE_SCHEMA = DATABASE() " - + "AND TABLE_NAME = 'wms_wave_pick_task' " - + "AND COLUMN_NAME = 'batch_no_array'" - ); - console.log(JSON.stringify(rows, null, 2)); - - const [ meta ] = await s.query( - "SELECT name FROM SequelizeMeta WHERE name = '20260904120000-add-batch-no-array-to-wms-wave-pick-task.js'" - ); - console.log('SequelizeMeta 记录:', JSON.stringify(meta)); - - await s.close(); -})().catch(e => { - console.error('ERROR:', e.message); - process.exit(1); -}); diff --git a/script/tmp-verify-claim-operator.cjs b/script/tmp-verify-claim-operator.cjs deleted file mode 100644 index 003025e..0000000 --- a/script/tmp-verify-claim-operator.cjs +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -/** - * 临时核验脚本:查询生产库 wms_wave_batch 领料字段与 SequelizeMeta 记录。 - */ - -const dbConfig = require('../database/config.js'); -const Sequelize = require('sequelize'); - -(async () => { - const cfg = dbConfig.production; - const s = new Sequelize(cfg.database, cfg.username, cfg.password, { - host: cfg.host, - port: cfg.port, - dialect: cfg.dialect || 'mysql', - logging: false, - }); - - const rows = await s.query( - "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_COMMENT " - + "FROM INFORMATION_SCHEMA.COLUMNS " - + "WHERE TABLE_SCHEMA = DATABASE() " - + "AND TABLE_NAME = 'wms_wave_batch' " - + "AND COLUMN_NAME IN ('claim_operator', 'claim_time')", - { type: Sequelize.QueryTypes.SELECT } - ); - console.log('字段:', JSON.stringify(rows)); - - const meta = await s.query( - "SELECT name FROM SequelizeMeta WHERE name = '20260904130000-add-claim-operator-to-wms-wave-batch.js'", - { type: Sequelize.QueryTypes.SELECT } - ); - console.log('Meta:', JSON.stringify(meta)); - - await s.close(); -})().catch(e => { - console.error('ERROR:', e.message); - process.exit(1); -}); diff --git a/script/tmp-verify-intercept-order-dev.cjs b/script/tmp-verify-intercept-order-dev.cjs deleted file mode 100644 index 7d41df3..0000000 --- a/script/tmp-verify-intercept-order-dev.cjs +++ /dev/null @@ -1,228 +0,0 @@ -'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-pick-task-claim.cjs b/script/tmp-verify-pick-task-claim.cjs deleted file mode 100644 index afc5053..0000000 --- a/script/tmp-verify-pick-task-claim.cjs +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -/** - * 临时核验脚本:查询生产库 wms_wave_pick_task 领料字段与 SequelizeMeta 记录。 - */ - -const dbConfig = require('../database/config.js'); -const Sequelize = require('sequelize'); - -(async () => { - const cfg = dbConfig.production; - const s = new Sequelize(cfg.database, cfg.username, cfg.password, { - host: cfg.host, - port: cfg.port, - dialect: cfg.dialect || 'mysql', - logging: false, - }); - - const rows = await s.query( - "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_COMMENT " - + "FROM INFORMATION_SCHEMA.COLUMNS " - + "WHERE TABLE_SCHEMA = DATABASE() " - + "AND TABLE_NAME = 'wms_wave_pick_task' " - + "AND COLUMN_NAME IN ('claim_operator_id', 'claim_operator')", - { type: Sequelize.QueryTypes.SELECT } - ); - console.log('字段:', JSON.stringify(rows)); - - const meta = await s.query( - "SELECT name FROM SequelizeMeta WHERE name = '20260904140000-add-claim-operator-to-wms-wave-pick-task.js'", - { type: Sequelize.QueryTypes.SELECT } - ); - console.log('Meta:', JSON.stringify(meta)); - - await s.close(); -})().catch(e => { - console.error('ERROR:', e.message); - process.exit(1); -}); diff --git a/script/tmp-verify-pool-after-complete.cjs b/script/tmp-verify-pool-after-complete.cjs deleted file mode 100644 index abac8f0..0000000 --- a/script/tmp-verify-pool-after-complete.cjs +++ /dev/null @@ -1,151 +0,0 @@ -'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-pool-full-flow.cjs b/script/tmp-verify-pool-full-flow.cjs deleted file mode 100644 index 5cc7d95..0000000 --- a/script/tmp-verify-pool-full-flow.cjs +++ /dev/null @@ -1,234 +0,0 @@ -'use strict'; - -/** - * 完整流程验证(按正规接口): - * 1. 恢复 8 条今日前订单(1552 等)为未分配(wave_id=0),构成第一池; - * 2. 取消活跃任务; - * 3. 抓取 -> 新任务仅抓 8 条今日前订单(不足20不填充); - * 4. pickCart.bindTaskCart 绑定拣货车; - * 5. pick.wavePickTaskComplete 提交拣货完成 -> 订单不回池; - * 6. 再次抓取 -> 第一池已空,回落第二池抓满 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); -const KEEP_ORDER_IDS = [ 1552, 1757, 1859, 2229, 2555, 4705, 6260, 6488 ]; - -/** - * 发送 /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, wave_id 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 { - // 1. 恢复 8 条今日前订单为未分配 - await connection.query( - 'UPDATE wms_order_delivery_100000 SET wave_id = 0 WHERE id IN (?)', - [ KEEP_ORDER_IDS ] - ); - console.log(`[2] 已恢复 8 条今日前订单为未分配: [${KEEP_ORDER_IDS.join(', ')}]`); - - // 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 sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: Number(row.id) }); - } - console.log(`[3] 已取消活跃任务: [${activeTasks.map(row => row.id).join(', ')}]`); - - // 3. 第一轮抓取 - 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(`[4] 第一轮任务 ${firstTaskId} 抓取订单数: ${firstOrders.length}`); - console.log(` 今日前订单数: ${firstBeforeToday.length}, 订单ID: [${firstOrders.map(row => row.id).join(', ')}]`); - console.log(` 验证(不足20不填充): ${firstPassed ? '✅ 仅抓 8 条今日前订单' : '❌ 与预期不符'}`); - - // 4. 找一台可用拣货车并绑车 - const [ cartRows ] = await connection.query( - `SELECT id, cart_code FROM wms_pick_cart - WHERE warehouse_id = 100000 AND status = 1 - ORDER BY id ASC LIMIT 1` - ); - if (cartRows.length === 0) { - throw new Error('仓库 100000 无可用拣货车'); - } - const cartId = Number(cartRows[0].id); - const bindRes = await sysCall(token, 'pickCart.bindTaskCart', { - task_id: firstTaskId, - cart_id: cartId, - }); - console.log(`[5] 绑车(cart_id=${cartId})响应: ${JSON.stringify(bindRes).slice(0, 300)}`); - - // 5. 提交拣货完成(订单不回池) - const completeRes = await sysCall(token, 'pick.wavePickTaskComplete', { - task_id: firstTaskId, - mode: 1, - }); - console.log(`[6] wavePickTaskComplete 响应: ${JSON.stringify(completeRes).slice(0, 400)}`); - - const [ afterCompleteOrders ] = await connection.query( - 'SELECT id, wave_id FROM wms_order_delivery_100000 WHERE id IN (?)', - [ KEEP_ORDER_IDS ] - ); - const stayOutOfPool = afterCompleteOrders.every(row => Number(row.wave_id) > 0); - console.log(`[7] 拣货完成后订单 wave_id 保持非0(不回池): ${stayOutOfPool ? '✅' : '❌'}`); - - // 6. 第二轮抓取(第一池已空,回落第二池) - 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(`[8] 第二轮任务 ${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(`拣货完成不回池: ${stayOutOfPool ? 'PASS' : 'FAIL'}`); - console.log(`第二轮(第二池今天): 实际 ${secondOrders.length} 条 -> ${secondPassed ? 'PASS' : 'FAIL'}`); - console.log(`结论: ${firstPassed && stayOutOfPool && secondPassed ? '✅ 全部通过: 不足20不填充;拣货完成后订单不回池;第一池清空后回落第二池抓满20' : '❌ 存在与预期不符的环节'}`); - } finally { - await connection.end(); - } -} - -main().catch(error => { - console.error(`验证失败: ${error.message}`); - process.exit(1); -}); diff --git a/script/tmp-verify-report-edge-sql.cjs b/script/tmp-verify-report-edge-sql.cjs deleted file mode 100644 index e894fae..0000000 --- a/script/tmp-verify-report-edge-sql.cjs +++ /dev/null @@ -1,341 +0,0 @@ -/** - * 临时验证脚本:对比 stock.report.search 改造后的 SQL(聚合极值)与旧 SQL(全量明细+JS归并)在开发库的结果等价性。 - * 用法:node script/tmp-verify-report-edge-sql.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 buildOldEdgeMap(rows, keyFn) { - const map = new Map(); - for (const row of rows) { - const key = keyFn(row); - if (!map.has(key)) { - map.set(key, { - first_before: row.before_quantity, - last_after: row.after_quantity, - }); - } else { - map.get(key).last_after = row.after_quantity; - } - } - return map; -} - -function buildOldPreStartMap(rows, keyFn) { - const latest = new Map(); - for (const row of rows) { - const key = keyFn(row); - if (!key) continue; - const ct = new Date(row.created_at).getTime(); - const id = Number(row.id); - const cur = latest.get(key); - if (!cur || ct > cur.ct || (ct === cur.ct && id > cur.id)) { - latest.set(key, { after_quantity: row.after_quantity, ct, id }); - } - } - const map = new Map(); - for (const [ key, v ] of latest.entries()) { - map.set(key, v.after_quantity); - } - return map; -} - -function diffMaps(label, oldMap, newMap) { - const keys = new Set([ ...oldMap.keys(), ...newMap.keys() ]); - const diffs = []; - for (const key of keys) { - const a = oldMap.get(key); - const b = newMap.get(key); - const isScalarOld = a === null || typeof a !== 'object'; - const isScalarNew = b === null || typeof b !== 'object'; - if (isScalarOld || isScalarNew) { - const av = Number(a === undefined || a === null ? 0 : a); - const bv = Number(b === undefined || b === null ? 0 : b); - if (av !== bv) { - diffs.push(`${key}: old=${JSON.stringify(a)} new=${JSON.stringify(b)}`); - } - continue; - } - const aFirst = a.first_before === undefined ? null : a.first_before; - const aLast = a.last_after === undefined ? null : a.last_after; - const bFirst = b.first_before === undefined ? null : b.first_before; - const bLast = b.last_after === undefined ? null : b.last_after; - if (Number(aFirst) !== Number(bFirst) || Number(aLast) !== Number(bLast)) { - diffs.push(`${key}: old=(${aFirst},${aLast}) new=(${bFirst},${bLast})`); - } - } - console.log(`[${label}] old keys=${oldMap.size}, new keys=${newMap.size}, diffs=${diffs.length}`); - diffs.slice(0, 10).forEach(d => console.log(' DIFF ' + d)); - return diffs.length === 0; -} - -(async () => { - const configFactory = require(path.join(projectRoot, 'config', 'config.local.js')); - const config = typeof configFactory === 'function' ? configFactory({ name: 'wms-debug' }) : configFactory; - const client = config.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: 'utf8mb4', - }); - - try { - const startTime = '2026-08-01 00:00:00'; - const endTime = '2026-08-31 23:59:59'; - // by_space=false 分支用更宽区间(覆盖区间内有流水的场景) - const wideStart = '2026-05-01 00:00:00'; - const wideEnd = '2026-09-03 00:00:00'; - - // ============ by_space=false(wms_stock_transaction) ============ - const warehouseId = 1000028; - const oldRangeParams = [ warehouseId, wideStart, wideEnd ]; - - const oldIntervalRows = (await connection.query( - `SELECT t.id, t.stock_id, t.store_id, t.before_quantity, t.after_quantity, t.created_at - FROM wms_stock_transaction t - WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ? - ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at ASC, t.id ASC`, - oldRangeParams - ))[0]; - - const newIntervalRows = (await connection.query( - `SELECT - g.stock_id, - g.space_id, - g.store_id, - ft.before_quantity, - lt.after_quantity, - ft.created_at - FROM ( - SELECT - t.stock_id, - 0 AS space_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.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ? - 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.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ? - 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.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ? - 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 ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC`, - [ warehouseId, wideStart, wideEnd, warehouseId, wideStart, wideEnd, warehouseId, wideStart, wideEnd ] - ))[0]; - - const oldEdge = buildOldEdgeMap(oldIntervalRows, r => `${r.stock_id}_${r.store_id}`); - const newEdge = new Map(newIntervalRows.map(r => [ - `${r.stock_id}_${r.store_id}`, - { first_before: r.before_quantity, last_after: r.after_quantity }, - ])); - const edgeOk = diffMaps('edge by_space=false', oldEdge, newEdge); - - // 旧 preStart(全量历史 + JS 归并) - const oldPreRows = (await connection.query( - `SELECT t.id, t.stock_id, t.store_id, t.after_quantity, t.created_at - FROM wms_stock_transaction t - WHERE t.warehouse_id = ? AND t.created_at < ? - ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at DESC, t.id DESC`, - [ warehouseId, startTime ] - ))[0]; - - const newPreRows = (await connection.query( - `SELECT - g.stock_id, - g.space_id, - g.store_id, - lt.after_quantity, - lt.created_at - FROM ( - SELECT - t.stock_id, - 0 AS space_id, - t.store_id, - MAX(t.created_at) AS _max_ct - FROM wms_stock_transaction t - WHERE t.warehouse_id = ? AND t.created_at < ? - GROUP BY t.stock_id, t.store_id - ) g - LEFT JOIN wms_stock_transaction lt - ON lt.id = ( - SELECT MAX(t3.id) - FROM wms_stock_transaction t3 - WHERE t3.warehouse_id = ? AND t3.created_at < ? - 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 ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC`, - [ warehouseId, startTime, warehouseId, startTime ] - ))[0]; - - const oldPre = buildOldPreStartMap(oldPreRows, r => `${r.stock_id}_${r.store_id}`); - const newPre = new Map(newPreRows.map(r => [ `${r.stock_id}_${r.store_id}`, r.after_quantity ])); - const preOk = diffMaps('preStart by_space=false', oldPre, newPre); - - // ============ by_space=true(wms_storage_transaction) ============ - const whRows = (await connection.query( - 'SELECT warehouse_id, COUNT(*) AS cnt FROM wms_storage_transaction GROUP BY warehouse_id ORDER BY cnt DESC LIMIT 1' - ))[0]; - const storageWh = Number(whRows[0] && whRows[0].warehouse_id) || 0; - console.log(`storage_transaction max warehouse_id=${storageWh}`); - - const oldSpaceRows = (await connection.query( - `SELECT t.id, t.stock_id, COALESCE(t.space_id, 0) AS space_id, t.store_id, t.before_quantity, t.after_quantity, t.created_at - FROM wms_storage_transaction t - WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ? - ORDER BY t.stock_id ASC, COALESCE(t.space_id, 0) ASC, t.store_id ASC, t.created_at ASC, t.id ASC`, - [ storageWh, startTime, endTime ] - ))[0]; - - const newSpaceRows = (await connection.query( - `SELECT - g.stock_id, - g.space_id, - g.store_id, - ft.before_quantity, - lt.after_quantity, - ft.created_at - FROM ( - SELECT - t.stock_id, - COALESCE(t.space_id, 0) AS space_id, - t.store_id, - MIN(t.created_at) AS _min_ct, - MAX(t.created_at) AS _max_ct - FROM wms_storage_transaction t - WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ? - GROUP BY t.stock_id, COALESCE(t.space_id, 0), t.store_id - ) g - LEFT JOIN wms_storage_transaction ft - ON ft.id = ( - SELECT MIN(t2.id) - FROM wms_storage_transaction t2 - WHERE t2.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ? - AND t2.stock_id = g.stock_id AND COALESCE(t2.space_id, 0) = g.space_id AND t2.store_id = g.store_id - AND t2.created_at = g._min_ct - ) - LEFT JOIN wms_storage_transaction lt - ON lt.id = ( - SELECT MAX(t3.id) - FROM wms_storage_transaction t3 - WHERE t3.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ? - AND t3.stock_id = g.stock_id AND COALESCE(t3.space_id, 0) = g.space_id AND t3.store_id = g.store_id - AND t3.created_at = g._max_ct - ) - ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC`, - [ storageWh, startTime, endTime, storageWh, startTime, endTime, storageWh, startTime, endTime ] - ))[0]; - - const oldSpaceEdge = buildOldEdgeMap(oldSpaceRows, r => `${r.stock_id}_${r.space_id}_${r.store_id}`); - const newSpaceEdge = new Map(newSpaceRows.map(r => [ - `${r.stock_id}_${r.space_id}_${r.store_id}`, - { first_before: r.before_quantity, last_after: r.after_quantity }, - ])); - const spaceEdgeOk = diffMaps('edge by_space=true', oldSpaceEdge, newSpaceEdge); - - const oldSpacePreRows = (await connection.query( - `SELECT t.id, t.stock_id, COALESCE(t.space_id, 0) AS space_id, t.store_id, t.after_quantity, t.created_at - FROM wms_storage_transaction t - WHERE t.warehouse_id = ? AND t.created_at < ? - ORDER BY t.stock_id ASC, COALESCE(t.space_id, 0) ASC, t.store_id ASC, t.created_at DESC, t.id DESC`, - [ storageWh, startTime ] - ))[0]; - - const newSpacePreRows = (await connection.query( - `SELECT - g.stock_id, - g.space_id, - g.store_id, - lt.after_quantity, - lt.created_at - FROM ( - SELECT - t.stock_id, - COALESCE(t.space_id, 0) AS space_id, - t.store_id, - MAX(t.created_at) AS _max_ct - FROM wms_storage_transaction t - WHERE t.warehouse_id = ? AND t.created_at < ? - GROUP BY t.stock_id, COALESCE(t.space_id, 0), t.store_id - ) g - LEFT JOIN wms_storage_transaction lt - ON lt.id = ( - SELECT MAX(t3.id) - FROM wms_storage_transaction t3 - WHERE t3.warehouse_id = ? AND t3.created_at < ? - AND t3.stock_id = g.stock_id AND COALESCE(t3.space_id, 0) = g.space_id AND t3.store_id = g.store_id - AND t3.created_at = g._max_ct - ) - ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC`, - [ storageWh, startTime, storageWh, startTime ] - ))[0]; - - const oldSpacePre = buildOldPreStartMap(oldSpacePreRows, r => `${r.stock_id}_${r.space_id}_${r.store_id}`); - const newSpacePre = new Map(newSpacePreRows.map(r => [ `${r.stock_id}_${r.space_id}_${r.store_id}`, r.after_quantity ])); - const spacePreOk = diffMaps('preStart by_space=true', oldSpacePre, newSpacePre); - - // ============ EXPLAIN 新 intervalEdge SQL ============ - const explainRows = (await connection.query( - `EXPLAIN - SELECT - g.stock_id, g.space_id, g.store_id, ft.before_quantity, lt.after_quantity, ft.created_at - FROM ( - SELECT t.stock_id, 0 AS space_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.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ? - 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.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ? - 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.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ? - AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id - AND t3.created_at = g._max_ct - )`, - [ warehouseId, startTime, endTime, warehouseId, startTime, endTime, warehouseId, startTime, endTime ] - ))[0]; - console.log('--- EXPLAIN new intervalEdge ---'); - explainRows.forEach(r => console.log(` ${r.id} | ${r.select_type} | ${r.table} | type=${r.type} | possible_keys=${r.possible_keys} | key=${r.key} | rows=${r.rows}`)); - - const allOk = edgeOk && preOk && spaceEdgeOk && spacePreOk; - console.log(allOk ? '\n=== ALL PASS ===' : '\n=== FAIL ==='); - process.exit(allOk ? 0 : 1); - } finally { - await connection.end(); - } -})().catch(err => { - console.error(err); - process.exit(1); -}); diff --git a/script/tmp-verify-report-plan-2-preview.cjs b/script/tmp-verify-report-plan-2-preview.cjs deleted file mode 100644 index d9b209f..0000000 --- a/script/tmp-verify-report-plan-2-preview.cjs +++ /dev/null @@ -1,77 +0,0 @@ -'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 deleted file mode 100644 index 57aa97f..0000000 --- a/script/tmp-verify-stockreport-edge-prod.cjs +++ /dev/null @@ -1,226 +0,0 @@ -/** - * 临时只读核对脚本(生产库,仅 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 deleted file mode 100644 index ce9d58e..0000000 --- a/script/tmp-verify-wave-pool-boundary.cjs +++ /dev/null @@ -1,193 +0,0 @@ -'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 deleted file mode 100644 index f26efdd..0000000 --- a/script/tmp-verify-wave-pool-boundary2.cjs +++ /dev/null @@ -1,274 +0,0 @@ -'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 deleted file mode 100644 index a914e3a..0000000 --- a/script/tmp-verify-wave-pool-boundary3.cjs +++ /dev/null @@ -1,190 +0,0 @@ -'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 deleted file mode 100644 index 2854f8e..0000000 --- a/script/tmp-verify-wave-pool-priority.cjs +++ /dev/null @@ -1,170 +0,0 @@ -'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 deleted file mode 100644 index 207454d..0000000 --- a/script/tmp-watch-report-delivery.cjs +++ /dev/null @@ -1,100 +0,0 @@ -'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); -}); diff --git a/script/tmp-wave-edge-pick-http-test.cjs b/script/tmp-wave-edge-pick-http-test.cjs deleted file mode 100644 index 183d18a..0000000 --- a/script/tmp-wave-edge-pick-http-test.cjs +++ /dev/null @@ -1,527 +0,0 @@ -'use strict'; - -/** - * 边拣边分(batch_mode=3)策略 HTTP 联调脚本(含货主配置 OTHER 场景)。 - * - * 通过 /system 入口按顺序完成: - * 1. user.login 登录获取 token(请使用仓库账号,策略配置仅仓库主体可维护); - * 2. 探测签约关系 id(优先环境变量 WMS_TEST_CONTRACT_ID,否则从签约列表自动查找); - * 3. storeWarehouse.store.getPolicyConfig 读取当前货主配置; - * 4. storeWarehouse.store.savePolicyConfig 修改货主配置: - * 默认平台 default_platform_code = OTHER(其他平台)、默认快递 default_express_code = OTHER(其他快递); - * 5. order.wave.waveStrategyCreate 创建散单-边拣边分策略; - * 6. order.pendingOrder.createOrder 创建 N 条同商品结构订单(显式 OTHER 平台 + OTHER 快递,items_hash 相同); - * 7. order.reviewOrder.reviewOrder 审核(仅当订单创建后 step=0); - * 8. order.pendingOrder.allocateExpressCode 分配快递并轮询进度(OTHER+OTHER 应成功); - * 9. order.pendingOrder.allocateStorage 分配储位并轮询进度; - * 10. order.wave.waveStrategyQuickScan 触发策略快速扫描并轮询进度; - * 11. order.wave.waveStrategyFetchPda 提交按策略抓取任务(存在未完成任务时自动取消本人任务后重试); - * 12. 负向验证:临时把货主默认快递改为非 OTHER 快递(默认 STO)→ 创建订单并分配快递, - * 预期分配不了运单号(该仓库仅有 QT+OTHER 接口配置);验证后还原货主默认快递为 OTHER。 - * - * 用法(PowerShell 示例): - * $env:WMS_TEST_USERNAME='仓库账号'; $env:WMS_TEST_PASSWORD='密码'; - * $env:WMS_TEST_STORE_ID='货主ID'; $env:WMS_TEST_ITEM_ID='商品库存ID'; - * node .\script\tmp-wave-edge-pick-http-test.cjs - * - * 可选环境变量: - * WMS_BASE_URL 服务地址(默认 http://127.0.0.1:6060) - * WMS_TEST_CONTRACT_ID 签约关系 ID(不传则自动从签约列表探测) - * WMS_TEST_PLATFORM_CODE 货主默认平台编码(默认 OTHER) - * WMS_TEST_EXPRESS_CODE 货主默认快递编码(默认 OTHER) - * WMS_TEST_ORDER_COUNT 同结构订单数量(默认 2) - * WMS_TEST_PLAN_QTY 每条明细计划数量(默认 1) - * WMS_TEST_MIN_SAME_STRUCTURE 策略最小同结构订单数(默认 2,需 <= 订单数量) - * WMS_TEST_NEGATIVE_EXPRESS 负向验证快递编码(默认 STO) - */ - -const BASE_URL = process.env.WMS_BASE_URL || 'http://127.0.0.1:6060'; -const USERNAME = process.env.WMS_TEST_USERNAME || ''; -const PASSWORD = process.env.WMS_TEST_PASSWORD || ''; -const STORE_ID = Number(process.env.WMS_TEST_STORE_ID || 0); -const ITEM_ID = Number(process.env.WMS_TEST_ITEM_ID || 0); -const CONTRACT_ID = Number(process.env.WMS_TEST_CONTRACT_ID || 0); -const PLATFORM_CODE = String(process.env.WMS_TEST_PLATFORM_CODE || 'OTHER').trim() || 'OTHER'; -const EXPRESS_CODE = String(process.env.WMS_TEST_EXPRESS_CODE || 'OTHER').trim() || 'OTHER'; -const NEGATIVE_EXPRESS = String(process.env.WMS_TEST_NEGATIVE_EXPRESS || 'STO').trim() || 'STO'; -const PLAN_QTY = Number(process.env.WMS_TEST_PLAN_QTY || 1); -const ORDER_COUNT = Number(process.env.WMS_TEST_ORDER_COUNT || 2); -const MIN_SAME_STRUCTURE = Number(process.env.WMS_TEST_MIN_SAME_STRUCTURE || 2); -const POLL_TIMEOUT_MS = 90 * 1000; -const POLL_INTERVAL_MS = 1500; - -/** - * 发送 /system POST 请求。 - * - * @param {string} method 方法名(如 order.wave.waveStrategyCreate)。 - * @param {Object} [data={}] 请求体参数。 - * @param {string|null} [token=null] 登录令牌。 - * @return {Promise} { httpStatus, json } 响应结果。 - */ -async function callSystem(method, data = {}, token = null) { - const url = `${BASE_URL}/system?method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`; - const headers = { - 'Content-Type': 'application/json', - }; - if (token) { - headers.Authorization = `Bearer ${token}`; - } - - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), 30 * 1000); - try { - const response = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - platform: 'web', - project: 'wms', - ...(token ? { Authorization: `Bearer ${token}` } : {}), - }, - body: JSON.stringify(data), - signal: controller.signal, - }); - const text = await response.text(); - let json = null; - try { - json = JSON.parse(text); - } catch (error) { - json = { raw: text }; - } - return { httpStatus: response.status, json }; - } finally { - clearTimeout(timer); - } -} - -/** - * 深度优先查找对象中第一个匹配 key 的非空值。 - * - * @param {*} target 待查找对象。 - * @param {string} key 目标字段名。 - * @return {*} 匹配值或 undefined。 - */ -function deepFind(target, key) { - if (target === null || target === undefined) { - return undefined; - } - if (Array.isArray(target)) { - for (const item of target) { - const found = deepFind(item, key); - if (found !== undefined) { - return found; - } - } - return undefined; - } - if (typeof target === 'object') { - for (const [ currentKey, value ] of Object.entries(target)) { - if (currentKey === key && value !== null && value !== undefined && value !== '') { - return value; - } - } - for (const value of Object.values(target)) { - const found = deepFind(value, key); - if (found !== undefined) { - return found; - } - } - } - return undefined; -} - -/** - * 从列表响应中按匹配函数查找首个满足条件的记录。 - * - * @param {Object} json 响应 JSON。 - * @param {Function} matcher 匹配函数,接收 list 项返回 boolean。 - * @return {Object|null} 命中的记录或 null。 - */ -function findListRecord(json, matcher) { - const list = deepFind(json, 'list'); - if (!Array.isArray(list)) { - return null; - } - return list.find(item => typeof matcher === 'function' && matcher(item)) || null; -} - -/** - * 按条件轮询异步任务直到完成或超时。 - * - * @param {Function} pollFn 轮询函数,返回 { done:boolean, payload:* }。 - * @param {number} timeoutMs 超时毫秒数。 - * @param {number} intervalMs 轮询间隔毫秒数。 - * @return {Promise} { ok, payload } 最终结果。 - */ -async function pollUntilDone(pollFn, timeoutMs = POLL_TIMEOUT_MS, intervalMs = POLL_INTERVAL_MS) { - const startedAt = Date.now(); - let lastPayload = null; - while (Date.now() - startedAt < timeoutMs) { - const result = await pollFn(); - lastPayload = result.payload; - if (result.done) { - return { ok: true, payload: lastPayload }; - } - await new Promise(resolve => setTimeout(resolve, intervalMs)); - } - return { ok: false, payload: lastPayload }; -} - -/** - * 校验脚本运行所需环境变量。 - * - * @return {void} - */ -function ensureEnv() { - const missingList = []; - if (!USERNAME) { - missingList.push('WMS_TEST_USERNAME'); - } - if (!PASSWORD) { - missingList.push('WMS_TEST_PASSWORD'); - } - if (!Number.isInteger(STORE_ID) || STORE_ID <= 0) { - missingList.push('WMS_TEST_STORE_ID'); - } - if (!Number.isInteger(ITEM_ID) || ITEM_ID <= 0) { - missingList.push('WMS_TEST_ITEM_ID'); - } - if (missingList.length > 0) { - throw new Error(`缺少环境变量: ${missingList.join(', ')}`); - } -} - -/** - * 探测货主在当前仓库下的签约关系 ID。 - * - * 优先使用 WMS_TEST_CONTRACT_ID;否则依次从仓库侧签约列表与货主侧签约列表查找。 - * - * @param {string} token 登录令牌。 - * @return {Promise} 签约关系 ID。 - */ -async function resolveContractId(token) { - if (Number.isInteger(CONTRACT_ID) && CONTRACT_ID > 0) { - return CONTRACT_ID; - } - - const warehouseListRes = await callSystem('storeWarehouse.warehouse.list', { - page: 1, - page_size: 100, - }, token); - const warehouseSide = findListRecord(warehouseListRes.json, item => Number(item && item.store_id) === STORE_ID); - if (warehouseSide && Number(warehouseSide.id) > 0) { - return Number(warehouseSide.id); - } - - const storeListRes = await callSystem('storeWarehouse.store.list', { - page: 1, - page_size: 100, - }, token); - const storeSide = findListRecord(storeListRes.json, item => Number(item && item.warehouse_id) > 0); - if (storeSide && Number(storeSide.id) > 0) { - return Number(storeSide.id); - } - - throw new Error(`未能从签约列表自动探测货主 ${STORE_ID} 的签约关系,请设置 WMS_TEST_CONTRACT_ID`); -} - -/** - * 创建一条测试订单。 - * - * @param {string} token 登录令牌。 - * @param {Object} [options={}] 订单参数。 - * @param {string} [options.platformCode] 系统平台编码(默认取 PLATFORM_CODE)。 - * @param {string} [options.logisticsCode] 快递编码(默认取 EXPRESS_CODE)。 - * @param {number} [options.suffix=0] 收件人手机与地址后缀。 - * @return {Promise} 订单 ID。 - */ -async function createTestOrder(token, options = {}) { - const platformCode = String(options.platformCode || PLATFORM_CODE).trim(); - const hasLogisticsCode = options.logisticsCode !== undefined && options.logisticsCode !== null; - const logisticsCode = hasLogisticsCode ? String(options.logisticsCode).trim() : ''; - const suffix = Number(options.suffix || 0); - const items = [{ item_id: ITEM_ID, plan_qty: PLAN_QTY }]; - - const body = { - store_id: STORE_ID, - name: '联调测试收件人', - mobile: `1380000${String(suffix).padStart(4, '0')}`, - detail_address: `联调测试地址${suffix + 1}号`, - province: '广东省', - city: '广州市', - area: '天河区', - sys_platform_code: platformCode, - items, - }; - if (hasLogisticsCode) { - body.logistics_code = logisticsCode; - } - - const orderRes = await callSystem('order.pendingOrder.createOrder', body, token); - const orderId = Number(deepFind(orderRes.json, 'order_id') || 0); - if (!Number.isInteger(orderId) || orderId <= 0) { - throw new Error(`订单创建失败,响应: ${JSON.stringify(orderRes.json)}`); - } - return orderId; -} - -/** - * 主流程入口。 - * - * @return {Promise} - */ -async function main() { - ensureEnv(); - console.log(`[联调] 目标服务: ${BASE_URL}`); - console.log(`[联调] 货主ID: ${STORE_ID},商品ID: ${ITEM_ID},订单数: ${ORDER_COUNT}`); - console.log(`[联调] 目标平台: ${PLATFORM_CODE},目标快递: ${EXPRESS_CODE},负向快递: ${NEGATIVE_EXPRESS}`); - - // 1. 登录 - const loginRes = await callSystem('user.login', { - username: USERNAME, - password: PASSWORD, - }); - const token = deepFind(loginRes.json, 'token'); - if (!token) { - throw new Error(`登录失败,响应: ${JSON.stringify(loginRes.json)}`); - } - console.log('[1/12] 登录成功,已获取 token'); - - // 2. 探测签约关系 ID - const contractId = await resolveContractId(token); - console.log(`[2/12] 签约关系 ID: ${contractId}`); - - // 3. 读取当前货主配置 - const configRes = await callSystem('storeWarehouse.store.getPolicyConfig', { id: contractId }, token); - const currentPolicy = deepFind(configRes.json, 'policy_config'); - const currentPolicyObject = currentPolicy && typeof currentPolicy === 'object' && !Array.isArray(currentPolicy) - ? currentPolicy - : {}; - console.log(`[3/12] 当前货主配置: ${JSON.stringify(currentPolicyObject).slice(0, 300)}`); - - // 4. 修改货主配置:默认平台/默认快递改为 OTHER(其他平台/其他快递) - const updatedPolicy = { - ...currentPolicyObject, - default_platform_code: PLATFORM_CODE, - default_express_code: EXPRESS_CODE, - }; - const saveConfigRes = await callSystem('storeWarehouse.store.savePolicyConfig', { - id: contractId, - policy_config: updatedPolicy, - }, token); - const savedPolicy = deepFind(saveConfigRes.json, 'policy_config'); - const savedDefaultPlatform = String(savedPolicy && savedPolicy.default_platform_code || '').trim(); - const savedDefaultExpress = String(savedPolicy && savedPolicy.default_express_code || '').trim(); - console.log(`[4/12] 货主配置已更新: 默认平台=${savedDefaultPlatform}, 默认快递=${savedDefaultExpress}`); - if (savedDefaultPlatform !== PLATFORM_CODE || savedDefaultExpress !== EXPRESS_CODE) { - console.warn(`[4/12] 警告: 保存结果与预期不一致,响应: ${JSON.stringify(saveConfigRes.json)}`); - } - - // 5. 创建边拣边分策略 - const strategyName = `HTTP联调-边拣边分-${Date.now()}`; - const strategyRes = await callSystem('order.wave.waveStrategyCreate', { - strategy_name: strategyName, - strategy_type: 1, - batch_mode: 3, - status: 1, - min_same_structure: MIN_SAME_STRUCTURE, - require_same_express: false, - batch_max_orders: 20, - batch_max_skus: 50, - description: 'HTTP 联调用边拣边分策略', - }, token); - const strategyId = Number(deepFind(strategyRes.json, 'id') || 0); - if (!Number.isInteger(strategyId) || strategyId <= 0) { - throw new Error(`策略创建失败,响应: ${JSON.stringify(strategyRes.json)}`); - } - console.log(`[5/12] 策略创建成功: id=${strategyId}, name=${strategyName}`); - - // 6. 创建同结构订单(显式 OTHER 平台 + OTHER 快递) - const orderIds = []; - for (let index = 0; index < ORDER_COUNT; index += 1) { - const orderId = await createTestOrder(token, { - platformCode: PLATFORM_CODE, - logisticsCode: EXPRESS_CODE, - suffix: index, - }); - orderIds.push(orderId); - } - console.log(`[6/12] 同结构订单创建成功: order_ids=[${orderIds.join(', ')}]`); - - // 7. 若存在待审核订单则审核 - let needReview = false; - for (const orderId of orderIds) { - const detailRes = await callSystem('order.pendingOrder.detail', { id: orderId }, token); - const step = Number(deepFind(detailRes.json, 'step') || 0); - if (step === 0) { - needReview = true; - break; - } - } - if (needReview) { - const reviewRes = await callSystem('order.reviewOrder.reviewOrder', { ids: orderIds }, token); - console.log(`[7/12] 订单审核完成: ${JSON.stringify(reviewRes.json)}`); - } else { - console.log('[7/12] 订单无需审核(step 已非 0),跳过'); - } - - // 8. 分配快递并轮询(OTHER 平台 + OTHER 快递应成功) - const expressRes = await callSystem('order.pendingOrder.allocateExpressCode', { ids: orderIds }, token); - const expressTaskId = deepFind(expressRes.json, 'task_id'); - if (!expressTaskId) { - throw new Error(`快递分配提交失败,响应: ${JSON.stringify(expressRes.json)}`); - } - const expressPoll = await pollUntilDone(async () => { - const progressRes = await callSystem('order.pendingOrder.allocateExpressCodeTaskProgress', { task_id: expressTaskId }, token); - const status = String(deepFind(progressRes.json, 'status') || ''); - const progress = Number(deepFind(progressRes.json, 'progress') || 0); - return { - done: [ 'success', 'failed', 'error', 'finish' ].includes(status) || progress >= 100, - payload: progressRes.json, - }; - }); - if (!expressPoll.ok) { - console.warn('[8/12] 快递分配轮询超时,可能仍在中途,请稍后复查'); - } else { - console.log(`[8/12] 快递分配任务结束: ${JSON.stringify(expressPoll.payload).slice(0, 300)}`); - } - - // 9. 分配储位并轮询 - const storageRes = await callSystem('order.pendingOrder.allocateStorage', { order_ids: orderIds }, token); - const requestId = deepFind(storageRes.json, 'request_id'); - if (!requestId) { - throw new Error(`储位分配提交失败,响应: ${JSON.stringify(storageRes.json)}`); - } - const storagePoll = await pollUntilDone(async () => { - const progressRes = await callSystem('order.pendingOrder.allocateStorageProgress', { request_id: requestId }, token); - const status = String(deepFind(progressRes.json, 'status') || ''); - const progress = Number(deepFind(progressRes.json, 'progress') || 0); - return { - done: [ 'success', 'failed', 'error', 'finish' ].includes(status) || progress >= 100, - payload: progressRes.json, - }; - }); - if (!storagePoll.ok) { - console.warn('[9/12] 储位分配轮询超时,可能仍在中途,请稍后复查'); - } else { - console.log(`[9/12] 储位分配任务结束: ${JSON.stringify(storagePoll.payload).slice(0, 300)}`); - } - - // 10. 快速扫描并轮询 - const scanRes = await callSystem('order.wave.waveStrategyQuickScan', {}, token); - const scanTaskId = deepFind(scanRes.json, 'task_id'); - if (!scanTaskId) { - throw new Error(`快速扫描提交失败,响应: ${JSON.stringify(scanRes.json)}`); - } - const scanPoll = await pollUntilDone(async () => { - const progressRes = await callSystem('order.wave.waveStrategyQuickScanTaskProgress', { task_id: scanTaskId }, token); - const state = String(deepFind(progressRes.json, 'state') || ''); - return { - done: [ 'success', 'failed' ].includes(state), - payload: progressRes.json, - }; - }); - if (!scanPoll.ok) { - throw new Error(`快速扫描超时: ${JSON.stringify(scanPoll.payload)}`); - } - const matchedCount = Number(deepFind(scanPoll.payload, 'matched_order_count') || 0); - const unmatchedCount = Number(deepFind(scanPoll.payload, 'unmatched_order_count') || 0); - console.log(`[10/12] 快速扫描完成: matched=${matchedCount}, unmatched=${unmatchedCount}`); - if (matchedCount <= 0) { - console.warn('[10/12] 提示: matched=0。订单可能已被自动扫描(wave_strategy_version 与当前一致,不在扫描范围),以 PDA 抓取结果为准'); - } - - // 11. PDA 按策略抓取(存在未完成任务时先取消本人任务再重试) - let fetchRes = await callSystem('order.wave.waveStrategyFetchPda', { strategy_id: strategyId }, token); - let flag = String(deepFind(fetchRes.json, 'flag') || ''); - let fetchState = Number(deepFind(fetchRes.json, 'fetch_state') || 0); - let taskId = deepFind(fetchRes.json, 'task_id'); - let taskNo = deepFind(fetchRes.json, 'task_no'); - if (fetchState === 3 && Number(taskId) > 0) { - console.log(`[11/12] 检测到未完成任务 ${taskId}(${taskNo || ''}),先取消本人任务后重试`); - const cancelRes = await callSystem('order.wave.wavePickTaskCancelSelf', { task_id: Number(taskId) }, token); - console.log(`[11/12] 取消任务响应: ${JSON.stringify(cancelRes.json).slice(0, 300)}`); - fetchRes = await callSystem('order.wave.waveStrategyFetchPda', { strategy_id: strategyId }, token); - flag = String(deepFind(fetchRes.json, 'flag') || ''); - fetchState = Number(deepFind(fetchRes.json, 'fetch_state') || 0); - taskId = deepFind(fetchRes.json, 'task_id'); - taskNo = deepFind(fetchRes.json, 'task_no'); - } - console.log(`[11/12] PDA 抓取响应: ${JSON.stringify(fetchRes.json)}`); - - // 12. 负向验证:临时把货主默认快递改为非 OTHER 快递,预期分配不了运单号 - let negativeAllocated = null; - try { - console.log(`[12/12] 负向验证开始: 临时改货主默认快递为 ${NEGATIVE_EXPRESS}`); - const negativeConfigRes = await callSystem('storeWarehouse.store.savePolicyConfig', { - id: contractId, - policy_config: { - ...currentPolicyObject, - default_platform_code: PLATFORM_CODE, - default_express_code: NEGATIVE_EXPRESS, - }, - }, token); - const negativeDefaultExpress = String(deepFind(negativeConfigRes.json, 'default_express_code') || '').trim(); - if (negativeDefaultExpress !== NEGATIVE_EXPRESS) { - throw new Error(`负向配置切换失败: ${JSON.stringify(negativeConfigRes.json)}`); - } - - const negativeOrderId = await createTestOrder(token, { - platformCode: PLATFORM_CODE, - logisticsCode: null, - suffix: ORDER_COUNT + 99, - }); - const negativeDetailRes = await callSystem('order.pendingOrder.detail', { id: negativeOrderId }, token); - const negativeStep = Number(deepFind(negativeDetailRes.json, 'step') || 0); - if (negativeStep === 0) { - await callSystem('order.reviewOrder.reviewOrder', { ids: [ negativeOrderId ] }, token); - } - const negativeExpressRes = await callSystem('order.pendingOrder.allocateExpressCode', { ids: [ negativeOrderId ] }, token); - const negativeTaskId = deepFind(negativeExpressRes.json, 'task_id'); - if (!negativeTaskId) { - throw new Error(`负向订单快递分配提交失败: ${JSON.stringify(negativeExpressRes.json)}`); - } - const negativePoll = await pollUntilDone(async () => { - const progressRes = await callSystem('order.pendingOrder.allocateExpressCodeTaskProgress', { task_id: negativeTaskId }, token); - const status = String(deepFind(progressRes.json, 'status') || ''); - const progress = Number(deepFind(progressRes.json, 'progress') || 0); - return { - done: [ 'success', 'failed', 'error', 'finish' ].includes(status) || progress >= 100, - payload: progressRes.json, - }; - }); - const negativeStatus = String(deepFind(negativePoll.payload, 'status') || ''); - negativeAllocated = negativePoll.ok && negativeStatus === 'success'; - console.log(`[12/12] 负向订单(${PLATFORM_CODE}+${NEGATIVE_EXPRESS})分配结果: ${JSON.stringify(negativePoll.payload).slice(0, 300)}`); - } catch (error) { - console.warn(`[12/12] 负向验证执行异常(不影响主流程): ${error.message}`); - } finally { - await callSystem('storeWarehouse.store.savePolicyConfig', { - id: contractId, - policy_config: { - ...currentPolicyObject, - default_platform_code: PLATFORM_CODE, - default_express_code: EXPRESS_CODE, - }, - }, token).catch(error => { - console.warn(`[12/12] 还原货主配置失败: ${error.message}`); - }); - console.log(`[12/12] 货主配置已还原: 默认平台=${PLATFORM_CODE}, 默认快递=${EXPRESS_CODE}`); - } - - console.log('==================== 联调总结 ===================='); - console.log(`策略ID: ${strategyId}(batch_mode=3 边拣边分)`); - console.log(`订单: [${orderIds.join(', ')}]`); - console.log(`快速扫描命中订单数: ${matchedCount}`); - console.log(`PDA 抓取: flag=${flag}, fetch_state=${fetchState}, task_id=${taskId || '无'}, task_no=${taskNo || '无'}`); - const passed = flag === 'success' && (fetchState === 1 || fetchState === 3); - console.log(`结论: ${passed ? '策略命中,抓取任务创建成功 ✅' : '未达成预期,请根据上述响应排查 ❌'}`); - if (negativeAllocated !== null) { - console.log(`负向验证: ${PLATFORM_CODE}+${NEGATIVE_EXPRESS} ${negativeAllocated ? '居然分配成功(与预期不符,需排查)❌' : '分配不了运单号(符合预期)✅'}`); - } -} - -main().catch(error => { - console.error(`[联调] 执行失败: ${error.message}`); - process.exit(1); -});