- waveClaimScan:仅未打印(print_status != fin)的拦截订单跳过领料;已打印的拦截订单面单实物已流出,照常置为已领料并写 ORDER_WAVE_CLAIM 日志,响应新增 intercept_skipped_order_count / claimed_intercepted_order_count - waveClaimScan:already_claimed 幂等分支在波次 claim_time 为空时补写领料时间,修复 order.wave.confirmPrintUnclaimedWaveCount 长期把已领料波次计为「已打印未领料」 - getWaveClaimGateStats:已打印的拦截订单仍需领料登记,未领料时阻隔创建拣货任务 - 新增 script/backfill-wave-claim-status.cjs 存量订正脚本(默认 dry-run,自动定位待处理/配送/历史/委托外仓分表,幂等) - 同步 methods/system.json、methods/changes/system.json、AI_METHOD_ROUTING.md Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
243 lines
9.4 KiB
JavaScript
243 lines
9.4 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 回补「已打印但未领料」存量订单的领料登记(一次性数据订正脚本)。
|
||
*
|
||
* 背景:waveClaimScan 曾对拦截订单整体跳过领料,导致「波次已确认打印 → 之后写入拦截 →
|
||
* 领单扫描」时该订单一直不置 claim_status=fin,但面单实物已打印并被领取。
|
||
* 代码已修复(已打印的拦截订单照常领料),本脚本用于订正修复前已产生的存量数据。
|
||
*
|
||
* 订正内容(幂等):
|
||
* 1. 订单 claim_status/claim_operator_id/claim_operator 回补为领料完成;
|
||
* 2. 若波次表 claim_time 为空,回补 claim_time/claim_operator;
|
||
* 3. 补一条 ORDER_WAVE_CLAIM 操作日志(message 标注「存量数据补记」)。
|
||
*
|
||
* 安全约束:
|
||
* - 默认预览模式,只有显式 --apply 才写入;
|
||
* - 仅处理 print_status='fin' 且未取消的订单,否则拒绝(--force 可强制);
|
||
* - 已领料(claim_status='fin')直接跳过,可重复执行;
|
||
* - 订单可能已迁移进配送表/历史表/委托外仓表,脚本会自动定位所在分表。
|
||
*
|
||
* 用法:
|
||
* node script/backfill-wave-claim-status.cjs --warehouse-id=1000028 --order-id=1314391
|
||
* node script/backfill-wave-claim-status.cjs --warehouse-id=1000028 --order-id=1314391 --apply
|
||
*
|
||
* 可选参数:
|
||
* --operator-id=65 指定领料人工号(缺省取同波次已领料订单的领料人)
|
||
* --operator-name=冯城礼 指定领料人姓名
|
||
* --no-log 不写操作日志
|
||
* --force 放宽 print_status 校验
|
||
* --config=<path> 数据库配置(默认 script/db-query-prod-config.js)
|
||
*/
|
||
|
||
const path = require('path');
|
||
const { createRequire } = require('module');
|
||
|
||
const APPLY = process.argv.includes('--apply');
|
||
const WITH_LOG = !process.argv.includes('--no-log');
|
||
const FORCE = process.argv.includes('--force');
|
||
|
||
/**
|
||
* 读取 --key=value 形式的命令行参数。
|
||
* @param {string} key 参数名。
|
||
* @param {*} [defaultValue] 缺省值。
|
||
* @return {*} 参数值。
|
||
*/
|
||
function getArg(key, defaultValue) {
|
||
const prefix = `--${key}=`;
|
||
const hit = process.argv.find(arg => arg.startsWith(prefix));
|
||
return hit ? hit.slice(prefix.length) : defaultValue;
|
||
}
|
||
|
||
async function main() {
|
||
const warehouseId = Number(getArg('warehouse-id', 0));
|
||
const orderId = Number(getArg('order-id', 0));
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('缺少合法参数 --warehouse-id');
|
||
}
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
throw new Error('缺少合法参数 --order-id');
|
||
}
|
||
|
||
const projectRoot = path.resolve(__dirname, '..');
|
||
const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
|
||
const mysql = projectRequire('mysql2/promise');
|
||
|
||
const configPath = path.resolve(__dirname, path.basename(getArg('config', 'db-query-prod-config.js')));
|
||
const cfg = require(configPath);
|
||
const client = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients.wms;
|
||
if (!client) {
|
||
throw new Error(`未找到 mysql clients.wms 配置: ${configPath}`);
|
||
}
|
||
|
||
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 orderTableBase = `wms_order_delivery_${warehouseId}`;
|
||
// 订单可能已迁移进配送表/历史表,按 待处理 → 配送 → 历史 → 委托外仓 顺序定位
|
||
const orderTableCandidates = [
|
||
orderTableBase,
|
||
`${orderTableBase}_dispatch`,
|
||
`${orderTableBase}_history`,
|
||
`${orderTableBase}_outsourced`,
|
||
];
|
||
|
||
try {
|
||
let orderTable = null;
|
||
let order = null;
|
||
for (const table of orderTableCandidates) {
|
||
try {
|
||
const [ rows ] = await conn.query(
|
||
`SELECT id, warehouse_id, wave_id, wave_no, claim_status, claim_operator_id, claim_operator,
|
||
print_status, confirm_print_status, intercept_status, status
|
||
FROM ${table}
|
||
WHERE warehouse_id = ? AND id = ?`,
|
||
[ warehouseId, orderId ]
|
||
);
|
||
if (rows.length > 0) {
|
||
orderTable = table;
|
||
order = rows[0];
|
||
break;
|
||
}
|
||
} catch (error) {
|
||
// 分表可能不存在,继续找下一张
|
||
}
|
||
}
|
||
if (!order) {
|
||
throw new Error(`订单不存在: ${orderTableCandidates.join(' / ')} id=${orderId}`);
|
||
}
|
||
|
||
console.log('订单所在表:', orderTable);
|
||
console.log('订单现状:', JSON.stringify(order));
|
||
if (order.status === 'cancel') {
|
||
throw new Error('订单已取消,不处理');
|
||
}
|
||
if (String(order.claim_status || '') === 'fin') {
|
||
console.log('订单已是已领料(claim_status=fin),无需处理');
|
||
return;
|
||
}
|
||
if (String(order.print_status || '') !== 'fin' && !FORCE) {
|
||
throw new Error(`订单未打印(print_status=${order.print_status}),拒绝订正;如确认需要请加 --force`);
|
||
}
|
||
|
||
const [ waveRows ] = await conn.query(
|
||
`SELECT wave_id, wave_no, claim_operator, claim_time
|
||
FROM wms_wave_batch
|
||
WHERE warehouse_id = ? AND wave_id = ?`,
|
||
[ warehouseId, Number(order.wave_id || 0) ]
|
||
);
|
||
const wave = waveRows[0] || null;
|
||
if (!wave) {
|
||
throw new Error(`波次不存在: warehouse_id=${warehouseId} wave_id=${order.wave_id}`);
|
||
}
|
||
console.log('波次现状:', JSON.stringify(wave));
|
||
|
||
let operatorId = Number(getArg('operator-id', 0)) || 0;
|
||
let operatorName = String(getArg('operator-name', '') || '').trim();
|
||
if (!operatorId || !operatorName) {
|
||
const [ siblingRows ] = await conn.query(
|
||
`SELECT claim_operator_id, claim_operator, COUNT(*) AS claimed_count
|
||
FROM ${orderTable}
|
||
WHERE warehouse_id = ? AND wave_id = ? AND claim_status = 'fin'
|
||
AND claim_operator_id IS NOT NULL
|
||
GROUP BY claim_operator_id, claim_operator
|
||
ORDER BY claimed_count DESC
|
||
LIMIT 1`,
|
||
[ warehouseId, Number(wave.wave_id || 0) ]
|
||
);
|
||
const sibling = siblingRows[0] || null;
|
||
if (sibling) {
|
||
operatorId = operatorId || Number(sibling.claim_operator_id || 0);
|
||
operatorName = operatorName || String(sibling.claim_operator || '').trim();
|
||
}
|
||
if (!operatorName) {
|
||
operatorName = String(wave.claim_operator || '').trim();
|
||
}
|
||
}
|
||
if (!operatorName) {
|
||
throw new Error('无法确定领料人,请通过 --operator-name 指定');
|
||
}
|
||
console.log('将回补领料人:', JSON.stringify({ operator_id: operatorId || null, operator_name: operatorName }));
|
||
|
||
const [ beforeLogs ] = await conn.query(
|
||
`SELECT id FROM wms_operation_log
|
||
WHERE business_type = 'order' AND business_id = ? AND operation_code = 'ORDER_WAVE_CLAIM'
|
||
LIMIT 1`,
|
||
[ String(orderId) ]
|
||
);
|
||
const hasClaimLog = beforeLogs.length > 0;
|
||
console.log('已有 ORDER_WAVE_CLAIM 日志:', hasClaimLog);
|
||
|
||
if (!APPLY) {
|
||
console.log('');
|
||
console.log('==== 预览(加 --apply 执行) ====');
|
||
console.log(`UPDATE ${orderTable} SET claim_status='fin', claim_operator_id=${operatorId || 'NULL'}, claim_operator='${operatorName}' WHERE id=${orderId}`);
|
||
if (!wave.claim_time) {
|
||
console.log(`UPDATE wms_wave_batch SET claim_operator='${operatorName}', claim_time=NOW() WHERE wave_id=${wave.wave_id} AND claim_time IS NULL`);
|
||
}
|
||
if (WITH_LOG && !hasClaimLog) {
|
||
console.log(`INSERT wms_operation_log (order ${orderId}, ORDER_WAVE_CLAIM, ${operatorName})`);
|
||
}
|
||
return;
|
||
}
|
||
|
||
await conn.beginTransaction();
|
||
try {
|
||
const [ updateResult ] = await conn.query(
|
||
`UPDATE ${orderTable}
|
||
SET claim_status = 'fin', claim_operator_id = ?, claim_operator = ?
|
||
WHERE warehouse_id = ? AND id = ? AND claim_status <> 'fin'`,
|
||
[ operatorId > 0 ? operatorId : null, operatorName, warehouseId, orderId ]
|
||
);
|
||
console.log('订单更新行数:', updateResult.affectedRows);
|
||
|
||
if (!wave.claim_time) {
|
||
const [ waveUpdateResult ] = await conn.query(
|
||
`UPDATE wms_wave_batch
|
||
SET claim_operator = ?, claim_time = NOW()
|
||
WHERE warehouse_id = ? AND wave_id = ? AND claim_time IS NULL`,
|
||
[ operatorName, warehouseId, Number(wave.wave_id || 0) ]
|
||
);
|
||
console.log('波次领料时间补写行数:', waveUpdateResult.affectedRows);
|
||
}
|
||
|
||
if (WITH_LOG && !hasClaimLog) {
|
||
const [ logResult ] = await conn.query(
|
||
`INSERT INTO wms_operation_log
|
||
(business_type, business_id, operation_code, operator_id, operator_name,
|
||
external_log_type, external_log_id, warehouse_id, before_changes, platform_code, message)
|
||
VALUES ('order', ?, 'ORDER_WAVE_CLAIM', ?, ?, 'NONE', NULL, ?, NULL, 'SYSTEM', ?)`,
|
||
[
|
||
String(orderId),
|
||
operatorId > 0 ? String(operatorId) : null,
|
||
operatorName,
|
||
warehouseId,
|
||
`存量数据补记:整波领单完成(波次 ${wave.wave_no || order.wave_no})`,
|
||
]
|
||
);
|
||
console.log('操作日志写入 id:', logResult.insertId);
|
||
}
|
||
|
||
await conn.commit();
|
||
console.log('');
|
||
console.log('==== 已执行完成 ====');
|
||
} catch (error) {
|
||
await conn.rollback();
|
||
throw error;
|
||
}
|
||
} finally {
|
||
await conn.end();
|
||
}
|
||
}
|
||
|
||
main().catch(err => {
|
||
console.error('领料存量回补失败:', err.message);
|
||
process.exit(1);
|
||
});
|