WMS_MAIN/scripts/stock_diff_report.js
liufumingren 9d86c3f149 chore(scripts): 新增库存差异核对报表脚本并忽略导出文件
scripts/stock_diff_report.js 只读查询生产库,输出 库存差异核对_YYYYMMDD-HHmm.xlsx;.gitignore 按 库存差异核对_*.xlsx 忽略带时间戳的导出文件。
2026-10-28 23:08:07 +08:00

307 lines
14 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';
/**
* 生成"库存差异核对"xlsx(生产库只读查询)。
* 输出:项目根目录 库存差异核对_YYYYMMDD-HHmm.xlsx
*/
const path = require('node:path');
const mysql = require('mysql2/promise');
const ExcelJS = require('exceljs');
const cfgModule = require(path.join(__dirname, '..', 'database', 'config.js'));
const cfg = cfgModule && cfgModule.production ? cfgModule.production : cfgModule;
const fmt = d => {
if (!d) return '';
const dt = d instanceof Date ? d : new Date(d);
const p = n => String(n).padStart(2, '0');
return `${dt.getFullYear()}-${p(dt.getMonth() + 1)}-${p(dt.getDate())} ${p(dt.getHours())}:${p(dt.getMinutes())}:${p(dt.getSeconds())}`;
};
const num = v => Number(v || 0);
async function main() {
const conn = await mysql.createConnection({
host: cfg.host,
port: cfg.port,
user: cfg.username || cfg.user,
password: cfg.password,
database: cfg.database,
dateStrings: true,
multipleStatements: false,
});
console.log('[1/6] 查询差异 SKU 明细...');
const [ stocks ] = await conn.query(`
SELECT sw.id AS stock_id, sw.warehouse_id, sw.store_id, sw.item_code, sw.item_name,
sw.quantity AS sw_quantity, sw.locked_quantity AS sw_locked,
COALESCE(SUM(st.quantity), 0) AS st_quantity,
COALESCE(SUM(st.locked_quantity), 0) AS st_locked,
COALESCE(SUM(st.available_quantity), 0) AS st_available,
COALESCE(SUM(st.intercept_locked_quantity), 0) AS st_intercept,
COUNT(st.id) AS st_rows
FROM wms_stock_warehouse sw
LEFT JOIN wms_storage st ON st.stock_id = sw.id AND st.delete_at IS NULL
WHERE sw.delete_at IS NULL
GROUP BY sw.id, sw.warehouse_id, sw.store_id, sw.item_code, sw.item_name, sw.quantity, sw.locked_quantity
HAVING COALESCE(SUM(st.quantity), 0) <> sw.quantity
ORDER BY (COALESCE(SUM(st.quantity), 0) - sw.quantity) DESC
`);
console.log(` 差异 SKU: ${stocks.length}`);
const ids = stocks.map(s => s.stock_id);
if (!ids.length) {
console.log('无差异,退出');
await conn.end();
return;
}
const idList = ids.join(',');
console.log('[2/6] 查询库位流水汇总...');
const [ stAgg ] = await conn.query(`
SELECT stock_id,
SUM(CASE WHEN transaction_type = 'INBOUND' THEN quantity ELSE 0 END) AS st_in,
SUM(CASE WHEN transaction_type = 'OUTBOUND' THEN quantity ELSE 0 END) AS st_out,
SUM(CASE WHEN transaction_type = 'INBOUND' AND order_type = 'INTERCEPT_LOCK' THEN quantity ELSE 0 END) AS intercept_return_in,
SUM(CASE WHEN transaction_type = 'LOCK' AND order_type = 'INTERCEPT_LOCK' THEN quantity ELSE 0 END) AS intercept_lock_qty,
SUM(CASE WHEN order_type = 'INTERCEPT_GAP' THEN quantity ELSE 0 END) AS gap_qty
FROM wms_storage_transaction
WHERE stock_id IN (${idList})
GROUP BY stock_id
`);
console.log('[3/6] 查询 SKU 流水汇总...');
const [ swAgg ] = await conn.query(`
SELECT stock_id,
SUM(CASE WHEN transaction_type = 'INBOUND' THEN quantity ELSE 0 END) AS sw_in,
SUM(CASE WHEN transaction_type = 'OUTBOUND' THEN quantity ELSE 0 END) AS sw_out
FROM wms_stock_transaction
WHERE stock_id IN (${idList})
GROUP BY stock_id
`);
console.log('[4/6] 查询拦截/GAP 单据明细...');
const [ interceptRows ] = await conn.query(`
SELECT id, stock_id, transaction_type, order_type, order_no, order_id, storage_id, quantity,
before_intercept_locked_quantity, after_intercept_locked_quantity, created_at, remark
FROM wms_storage_transaction
WHERE stock_id IN (${idList}) AND order_type IN ('INTERCEPT_LOCK', 'INTERCEPT_GAP')
ORDER BY stock_id, created_at
`);
console.log(` 拦截/GAP 流水: ${interceptRows.length}`);
console.log('[5/6] 查询"SKU 已出库但无拣货完成记录"的单据...');
const [ noPickRows ] = await conn.query(`
SELECT t.stock_id, t.order_id, MIN(t.order_no) AS order_no, SUM(t.quantity) AS qty,
MIN(t.created_at) AS first_at, MAX(t.created_at) AS last_at
FROM wms_stock_transaction t
WHERE t.stock_id IN (${idList}) AND t.transaction_type = 'OUTBOUND'
AND NOT EXISTS (
SELECT 1 FROM wms_picking p
WHERE p.order_id = t.order_id AND p.status IN ('fin', 'fin_compensated')
)
GROUP BY t.stock_id, t.order_id
ORDER BY t.stock_id, first_at
`);
console.log(` 疑似少扣单据: ${noPickRows.length}`);
console.log('[6/6] 生成 xlsx...');
const stMap = new Map(stAgg.map(r => [ r.stock_id, r ]));
const swMap = new Map(swAgg.map(r => [ r.stock_id, r ]));
const noPickMap = new Map();
for (const r of noPickRows) {
const cur = noPickMap.get(r.stock_id) || { cnt: 0, qty: 0 };
cur.cnt += 1;
cur.qty += num(r.qty);
noPickMap.set(r.stock_id, cur);
}
const interceptByStock = new Map();
for (const r of interceptRows) {
const arr = interceptByStock.get(r.stock_id) || [];
arr.push(r);
interceptByStock.set(r.stock_id, arr);
}
const wb = new ExcelJS.Workbook();
wb.creator = 'WMS 库存差异核对';
wb.created = new Date();
const headerFill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF1F4E79' } };
const headerFont = { color: { argb: 'FFFFFFFF' }, bold: true };
const styleHeader = ws => {
const row = ws.getRow(1);
row.font = headerFont;
row.fill = headerFill;
row.alignment = { vertical: 'middle', horizontal: 'center' };
row.height = 22;
ws.views = [{ state: 'frozen', ySplit: 1 }];
};
// ── Sheet1 差异汇总 ──
const ws1 = wb.addWorksheet('差异汇总');
ws1.columns = [
{ header: '序号', key: 'no', width: 6 },
{ header: '仓库ID', key: 'warehouse_id', width: 11 },
{ header: '货主ID', key: 'store_id', width: 11 },
{ header: 'SKU(stock_id)', key: 'stock_id', width: 12 },
{ header: '商品编码', key: 'item_code', width: 18 },
{ header: '商品名称', key: 'item_name', width: 30 },
{ header: 'SKU库存', key: 'sw_quantity', width: 11 },
{ header: 'SKU锁定', key: 'sw_locked', width: 10 },
{ header: '库位数量合计', key: 'st_quantity', width: 14 },
{ header: '库位可用', key: 'st_available', width: 11 },
{ header: '库位锁定', key: 'st_locked', width: 11 },
{ header: '库位拦截锁定', key: 'st_intercept', width: 14 },
{ header: '库位记录数', key: 'st_rows', width: 11 },
{ header: '差额(库位-SKU)', key: 'diff', width: 15 },
{ header: '库位入库合计', key: 'st_in', width: 14 },
{ header: '库位出库合计', key: 'st_out', width: 14 },
{ header: 'SKU入库合计', key: 'sw_in', width: 13 },
{ header: 'SKU出库合计', key: 'sw_out', width: 13 },
{ header: '拦截实物返还(件)', key: 'intercept_return_in', width: 17 },
{ header: '拦截锁定(件)', key: 'intercept_lock_qty', width: 14 },
{ header: 'GAP挂账(件)', key: 'gap_qty', width: 13 },
{ header: '无拣货完成记录的出库单数', key: 'nopick_cnt', width: 18 },
{ header: '无拣货完成记录出库数量', key: 'nopick_qty', width: 18 },
{ header: '建议冲正方向', key: 'suggest_dir', width: 22 },
{ header: '建议冲正数量', key: 'suggest_qty', width: 14 },
{ header: '备注', key: 'note', width: 46 },
];
styleHeader(ws1);
stocks.forEach((s, i) => {
const st = stMap.get(s.stock_id) || {};
const sw = swMap.get(s.stock_id) || {};
const nop = noPickMap.get(s.stock_id) || { cnt: 0, qty: 0 };
const diff = num(s.st_quantity) - num(s.sw_quantity);
const notes = [];
if (num(st.intercept_return_in) > 0) notes.push(`含拦截已拣货实物返还 ${num(st.intercept_return_in)} 件`);
if (nop.cnt > 0) notes.push(`含 ${nop.cnt} 张 SKU 已出库但无拣货完成记录的单据(${nop.qty} 件)`);
if (num(st.gap_qty) !== 0) notes.push(`GAP 差异对账挂账 ${num(st.gap_qty)} 件`);
if (num(s.st_intercept) > 0) notes.push(`库位当前拦截锁定 ${num(s.st_intercept)} 件`);
ws1.addRow({
no: i + 1,
warehouse_id: s.warehouse_id,
store_id: s.store_id,
stock_id: s.stock_id,
item_code: s.item_code,
item_name: s.item_name,
sw_quantity: num(s.sw_quantity),
sw_locked: num(s.sw_locked),
st_quantity: num(s.st_quantity),
st_available: num(s.st_available),
st_locked: num(s.st_locked),
st_intercept: num(s.st_intercept),
st_rows: num(s.st_rows),
diff,
st_in: num(st.st_in),
st_out: num(st.st_out),
sw_in: num(sw.sw_in),
sw_out: num(sw.sw_out),
intercept_return_in: num(st.intercept_return_in),
intercept_lock_qty: num(st.intercept_lock_qty),
gap_qty: num(st.gap_qty),
nopick_cnt: nop.cnt,
nopick_qty: nop.qty,
suggest_dir: diff > 0 ? '库位多 → SKU 补 +' : 'SKU 多 → 库位核减 / SKU 核减',
suggest_qty: Math.abs(diff),
note: notes.join(';'),
});
});
ws1.autoFilter = { from: 'A1', to: `Z${ws1.rowCount}` };
ws1.getColumn('diff').numFmt = '#,##0;[Red]-#,##0';
// ── Sheet2 拦截/GAP 单据明细 ──
const ws2 = wb.addWorksheet('拦截与GAP单据明细');
ws2.columns = [
{ header: '库存流水ID', key: 'id', width: 12 },
{ header: 'SKU(stock_id)', key: 'stock_id', width: 12 },
{ header: '商品编码', key: 'item_code', width: 18 },
{ header: '库存记录ID', key: 'storage_id', width: 12 },
{ header: '流水类型', key: 'transaction_type', width: 11 },
{ header: '单据类型', key: 'order_type', width: 15 },
{ header: '单据号', key: 'order_no', width: 26 },
{ header: '单据ID', key: 'order_id', width: 11 },
{ header: '数量', key: 'quantity', width: 9 },
{ header: '拦截锁-前', key: 'before_intercept_locked_quantity', width: 12 },
{ header: '拦截锁-后', key: 'after_intercept_locked_quantity', width: 12 },
{ header: '发生时间', key: 'created_at', width: 20 },
{ header: '备注', key: 'remark', width: 40 },
];
styleHeader(ws2);
const codeMap = new Map(stocks.map(s => [ s.stock_id, s.item_code ]));
for (const r of interceptRows) {
ws2.addRow({
id: r.id,
stock_id: r.stock_id,
item_code: codeMap.get(r.stock_id) || '',
storage_id: r.storage_id,
transaction_type: r.transaction_type,
order_type: r.order_type,
order_no: r.order_no,
order_id: r.order_id,
quantity: num(r.quantity),
before_intercept_locked_quantity: r.before_intercept_locked_quantity === null ? '' : num(r.before_intercept_locked_quantity),
after_intercept_locked_quantity: r.after_intercept_locked_quantity === null ? '' : num(r.after_intercept_locked_quantity),
created_at: fmt(r.created_at),
remark: r.remark,
});
}
ws2.autoFilter = { from: 'A1', to: `M${ws2.rowCount}` };
// ── Sheet3 SKU 已出库但无有效拣货记录 ──
const ws3 = wb.addWorksheet('疑似少扣库位的出库单');
ws3.columns = [
{ header: 'SKU(stock_id)', key: 'stock_id', width: 12 },
{ header: '商品编码', key: 'item_code', width: 18 },
{ header: '发货单ID', key: 'order_id', width: 12 },
{ header: '平台/出库单号', key: 'order_no', width: 24 },
{ header: 'SKU出库数量', key: 'qty', width: 13 },
{ header: '出库时间', key: 'first_at', width: 20 },
];
styleHeader(ws3);
for (const r of noPickRows) {
ws3.addRow({
stock_id: r.stock_id,
item_code: codeMap.get(r.stock_id) || '',
order_id: r.order_id,
order_no: r.order_no,
qty: num(r.qty),
first_at: fmt(r.first_at),
});
}
ws3.autoFilter = { from: 'A1', to: `F${ws3.rowCount}` };
// ── Sheet4 说明 ──
const ws4 = wb.addWorksheet('口径说明与冲正建议');
ws4.columns = [{ header: '项目', key: 'k', width: 26 }, { header: '说明', key: 'v', width: 110 }];
styleHeader(ws4);
[
[ '数据来源', '生产库 wms(只读):wms_stock_warehouse / wms_storage / wms_storage_transaction / wms_stock_transaction / wms_picking' ],
[ '生成时间', fmt(new Date()) ],
[ '差异口径', '差额 = SUM(wms_storage.quantity) − wms_stock_warehouse.quantity(仅统计 delete_at IS NULL 的库位记录)' ],
[ '差异 SKU 数', String(stocks.length) ],
[ '已识别成因一', '拦截确认「已拣货实物返还」只加库位(INBOUND/INTERCEPT_LOCK)并加拦截锁,SKU 侧出库扣减不回补 → 库位比 SKU 多' ],
[ '已识别成因二', 'SKU 侧「订单出库」(stock_store.outbound)已扣,但库位侧从未拣货完成扣减(拣货行 pending/软删/不存在)→ 库位比 SKU 多' ],
[ '已识别成因三', 'GAP 差异对账挂账(INTERCEPT_GAP)会把差额以拦截锁定形式挂在库位上,冲正时需一并释放' ],
[ '冲正方向判定', '库位数量 > SKU:实物多则 SKU 补 +差额;账实已发出则核减库位数量(并释放对应拦截锁)' ],
[ '冲正前必查', '1) 该 SKU 是否有未完成拣货/在途拦截;2) 库位拦截锁定是否需要在冲正后释放;3) 冲正流水需留痕(transaction_type/remark)' ],
[ '相关代码位置', 'app/service/systems/order_async.js:709(order 出库只扣 SKU)、app/service/systems/stock_store.js:1209(outbound)、app/service/systems/order_storage_allocation.js:2668(拦截实物返还)、app/service/systems/pick.js:2404(拣货完成扣库位)' ],
].forEach(([ k, v ]) => ws4.addRow({ k, v }));
ws4.getColumn('v').alignment = { wrapText: true, vertical: 'top' };
const ts = new Date();
const p = n => String(n).padStart(2, '0');
const fileName = `库存差异核对_${ts.getFullYear()}${p(ts.getMonth() + 1)}${p(ts.getDate())}-${p(ts.getHours())}${p(ts.getMinutes())}.xlsx`;
const outPath = path.join(__dirname, '..', fileName);
await wb.xlsx.writeFile(outPath);
console.log(`\n已生成: ${outPath}`);
console.log(`汇总 ${stocks.length} 行 / 拦截明细 ${interceptRows.length} 行 / 疑似少扣单据 ${noPickRows.length} 行`);
await conn.end();
}
main().catch(err => {
console.error('生成失败:', err && err.message);
console.error(err && err.stack);
process.exit(1);
});