'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} 无返回值。 */ 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); });