WMS_MAIN/script/stock-check-record-deleted-location.cjs
liufumingren de2f66a2d1 fix(stock.check): 上报强制 space_id 并按库位ID落库,修复作业挂到已删除分区的库位
- stock.check.report:space_id 必传(兼容 spaceId/location_id/locationId),校验仓库归属、分区有效、与 location 编码一致,缺失/非法/跨仓库/无头库位均返回 400;服务端不再按库位编码猜库位
- report:实盘数量上限 2147483647(原超限落库 Out of range 变 500);写库库位以 space_id 为准
- workData / workDataSpaceDetails / workDataDetail:space 视图行与 goods 视图 locations[] 补 space_id、location_id;space 视图记录库位归一(同编码不再出现幽灵行),明细按「库位+商品」索引、记录按「库位+商品」聚合
- 操作日志 STOCK_CHECK_REPORT:message 补库位编码/库位ID,before_changes 落库位与明细库位快照
- location.zone:createZone/updateZone 增加同仓库 zone_code 唯一校验(归档分区不占用编码,沿用规则编码),避免重复货架生成同编码库位
- 新增运维脚本(默认只读,--prod 指定生产):盘点库位一致性体检/订正(只改坏记录,两分支互斥)、作业记录指向已删除库位体检与 CSV 导出;无头库位引用统计改为分批 IN 查询,避免大表相关子查询导致生产连接重置

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-27 03:04:07 +08:00

224 lines
9.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 盘点作业记录「库位指向异常」体检(只读)。
*
* 输出三类异常,均以 wms_stock_check_record.location_id 为准:
* A 已归档库位:location_id 命中 wms_location_space 且 deleted_at IS NOT NULL(软删除/归档行)
* B 无头库位:库位未归档,但所属 zone 不存在或已删除(分区被删后库位行漏归档)
* C 悬空库位:location_id 在 wms_location_space 中查不到(行已被物理删除)
*
* 用法:
* node script/stock-check-record-deleted-location.cjs # 开发库(只读)
* node script/stock-check-record-deleted-location.cjs --prod # 生产库(只读)
* node script/stock-check-record-deleted-location.cjs --prod --limit=30 --top=30
* node script/stock-check-record-deleted-location.cjs --prod --csv-out=temp/records.csv
*/
const path = require('path');
const fs = require('fs');
const PROJECT_ROOT = path.resolve(__dirname, '..');
/**
* 解析命令行参数。
* @return {Object} 选项。
*/
function parseArgs() {
const args = process.argv.slice(2);
const options = { prod: false, limit: 20, top: 20, csvOut: '', config: '' };
for (const arg of args) {
if (arg === '--prod') {
options.prod = true;
} else if (arg.startsWith('--limit=')) {
options.limit = Math.max(1, Number(arg.slice('--limit='.length)) || 20);
} else if (arg.startsWith('--top=')) {
options.top = Math.max(1, Number(arg.slice('--top='.length)) || 20);
} else if (arg.startsWith('--csv-out=')) {
options.csvOut = arg.slice('--csv-out='.length);
} else if (arg.startsWith('--config=')) {
options.config = arg.slice('--config='.length);
}
}
return options;
}
/**
* 读取数据库连接配置。
* @param {Object} options 命令行选项。
* @return {Object} mysql2 连接参数。
*/
function resolveClient(options) {
const configPath = options.config
? path.resolve(PROJECT_ROOT, options.config)
: path.resolve(PROJECT_ROOT, options.prod ? 'script/db-query-prod-config.js' : 'config/config.local.js');
// eslint-disable-next-line global-require
const configFactory = require(configPath);
const config = typeof configFactory === 'function' ? configFactory({ name: 'wms-script' }) : configFactory;
const client = config && config.mysql && config.mysql.clients && config.mysql.clients.wms;
if (!client) {
throw new Error(`未在 ${configPath} 找到 mysql.clients.wms 配置`);
}
return {
host: client.host,
port: Number(client.port),
user: client.user,
password: client.password,
database: client.database,
charset: client.charset || 'utf8mb4',
};
}
/** 分类条件(A 已归档 / B 无头 / C 悬空 / D 无库位ID),均以记录 location_id 为基准 */
const CATEGORY_SQL = {
A: 'ls.id IS NOT NULL AND ls.deleted_at IS NOT NULL',
B: 'ls.id IS NOT NULL AND ls.deleted_at IS NULL AND (z.id IS NULL OR z.deleted_at IS NOT NULL)',
C: 'r.location_id IS NOT NULL AND ls.id IS NULL',
D: 'r.location_id IS NULL',
};
const BASE_FROM = `FROM wms_stock_check_record r
LEFT JOIN wms_stock_check c ON c.id = r.check_id
LEFT JOIN wms_location_space ls ON ls.id = r.location_id
LEFT JOIN wms_location_zone z ON z.id = ls.zone_id`;
/**
* 主流程。
* @return {Promise<void>} 无返回值。
*/
async function main() {
const options = parseArgs();
// eslint-disable-next-line global-require
const mysql = require(path.join(PROJECT_ROOT, 'node_modules/mysql2/promise'));
const client = resolveClient(options);
const connection = await mysql.createConnection(client);
try {
const summary = { target: `${client.host}:${client.port}/${client.database}`, categories: {} };
const [ totalRows ] = await connection.query('SELECT COUNT(*) cnt FROM wms_stock_check_record');
summary.totalRecords = Number(totalRows[0].cnt) || 0;
for (const [ key, condition ] of Object.entries(CATEGORY_SQL)) {
const [ rows ] = await connection.query(
`SELECT COUNT(*) cnt, COUNT(DISTINCT r.check_id) checks FROM wms_stock_check_record r
LEFT JOIN wms_location_space ls ON ls.id = r.location_id
LEFT JOIN wms_location_zone z ON z.id = ls.zone_id
WHERE ${condition}`
);
summary.categories[key] = {
records: Number(rows[0].cnt) || 0,
checks: Number(rows[0].checks) || 0,
};
}
// 明细明细:A(已归档库位)与 B(无头库位)分别出「按盘点单 / 按库位 / 样本」三段
summary.details = {};
for (const key of [ 'A', 'B' ]) {
const condition = CATEGORY_SQL[key];
const [ topChecks ] = await connection.query(
`SELECT r.check_id, MAX(c.check_no) check_no, MAX(r.warehouse_id) warehouse_id,
COUNT(*) records, COUNT(DISTINCT r.detail_id) details
${BASE_FROM}
WHERE ${condition}
GROUP BY r.check_id
ORDER BY records DESC
LIMIT ${options.top}`
);
const [ topLocations ] = await connection.query(
`SELECT r.location_id, MAX(ls.space_code) space_code, MAX(ls.zone_id) zone_id,
COUNT(*) records, COUNT(DISTINCT r.check_id) checks
${BASE_FROM}
WHERE ${condition}
GROUP BY r.location_id
ORDER BY records DESC
LIMIT ${options.top}`
);
const [ samples ] = await connection.query(
`SELECT r.id record_id, r.check_id, c.check_no, r.detail_id, r.stock_id,
r.location_id, r.location_code, ls.space_code space_code, ls.zone_id zone_id,
z.id zone_exists, z.deleted_at zone_deleted_at,
r.quantity, r.checker_name, r.checked_at
${BASE_FROM}
WHERE ${condition}
ORDER BY r.id DESC
LIMIT ${options.limit}`
);
summary.details[key] = {
topChecks: topChecks.map(row => ({
check_id: Number(row.check_id),
check_no: row.check_no,
warehouse_id: Number(row.warehouse_id),
records: Number(row.records),
details: Number(row.details),
})),
topLocations: topLocations.map(row => ({
location_id: Number(row.location_id),
space_code: row.space_code,
zone_id: row.zone_id === null ? null : Number(row.zone_id),
records: Number(row.records),
checks: Number(row.checks),
})),
samples: samples.map(row => ({
record_id: Number(row.record_id),
check_id: Number(row.check_id),
check_no: row.check_no,
detail_id: Number(row.detail_id),
stock_id: row.stock_id === null ? null : Number(row.stock_id),
location_id: Number(row.location_id),
record_location_code: row.location_code,
space_code: row.space_code,
zone_id: row.zone_id === null ? null : Number(row.zone_id),
zone_exists: row.zone_exists !== null && row.zone_exists !== undefined,
zone_deleted_at: row.zone_deleted_at,
quantity: Number(row.quantity),
checker_name: row.checker_name,
checked_at: row.checked_at,
})),
};
}
if (options.csvOut) {
const header = 'category,record_id,check_id,check_no,detail_id,stock_id,location_id,record_location_code,detail_location_code,detail_location_id,space_code,zone_id,zone_exists,zone_deleted_at,quantity,checker_name,checked_at';
const lines = [];
for (const key of [ 'A', 'B' ]) {
if ((summary.categories[key].records || 0) === 0) {
continue;
}
const [ rows ] = await connection.query(
`SELECT r.id record_id, r.check_id, c.check_no, r.detail_id, r.stock_id,
r.location_id, r.location_code, d.location_code detail_location_code,
d.location_id detail_location_id, ls.space_code space_code, ls.zone_id zone_id,
z.id zone_exists, z.deleted_at zone_deleted_at,
r.quantity, r.checker_name, r.checked_at
${BASE_FROM}
LEFT JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id
WHERE ${CATEGORY_SQL[key]}
ORDER BY r.check_id ASC, r.id ASC`
);
for (const item of rows) {
lines.push([
key, item.record_id, item.check_id, item.check_no, item.detail_id, item.stock_id,
item.location_id, item.location_code, item.detail_location_code, item.detail_location_id,
item.space_code, item.zone_id, item.zone_exists ? 1 : 0, item.zone_deleted_at,
item.quantity, item.checker_name,
item.checked_at instanceof Date ? item.checked_at.toISOString() : item.checked_at,
].map(value => (value === null || value === undefined ? '' : String(value).replace(/,/g, ' '))).join(','));
}
}
const outPath = path.resolve(PROJECT_ROOT, options.csvOut);
fs.mkdirSync(path.dirname(outPath), { recursive: true });
fs.writeFileSync(outPath, [ header, ...lines ].join('\n'), 'utf8');
summary.csvOut = outPath;
}
console.log(JSON.stringify(summary, null, 2));
} finally {
await connection.end();
}
}
main().catch(error => {
console.error('[stock-check-record-deleted-location] 执行失败:', error.message);
process.exit(1);
});