WMS_MAIN/script/stock-check-goods-summary-verify.cjs
liufumingren 9edc0e3e47 fix(stock.check): 账面口径改取可用数量并新增静态盘点拣货完成校验
账面口径统一为 wms_storage SUM(available_quantity)(不再加 locked_quantity),避免静态盘点在仍有在途拣货时开盘产生假盘亏(PD20261027000001 商品 160240 -115)。

静态盘点(is_static=1)新增拣货完成判定 _fetchStockLockedQuantityMap:workData/workDataDetail 输出 picking_completed 与明盘 locked_quantity,report 对仍有锁定量(未完成拣货)的商品返回 400 拒绝上报。

同步更新 methods/system.json(0.3.319~0.3.321)与 changes 变更记录。ESLint 0 错误。
2026-10-28 23:08:00 +08:00

183 lines
8.0 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';
/**
* 开发环境实测脚本:盘点商品视图汇总 + workDataDetail 商品钻取 + report 免 detail_id。
*
* 直连本地开发库(config.local.js,127.0.0.1:3307),全程走 systemMethods 方法层(含统一 success 包装),
* 完整复现一条盘点到上报链路:
* 1. 取一个多库位库存商品(模拟同 stock_id 多条库位明细);
* 2. create → addDetail → submit → audit(approve);
* 3. report 只传 id + stock_id + space_id(不传 detail_id),验证反查明细;
* 4. workData(is_goods=true) 校验商品视图汇总(行级无 detail_id、locations 带 detail_id/snapshot_quantity);
* 5. workDataDetail(id + stock_id) 校验 summary + 按库位分行(明细ID/库位ID/账面快照/实盘/差异);
* 6. 交叉校验明细快照合计 = goods 行级账面 = summary 账面,分行实盘合计 = 行级实盘 = summary 实盘。
*
* 数据策略:脚本会在开发库新建一条盘点任务(单号 PD+日期+序号,标题以「实测_商品汇总_」开头)
* 作为核对样张保留,不做清理;不要在预发/生产库执行。
*
* 用法:node script/stock-check-goods-summary-verify.cjs
*/
const mm = require('egg-mock');
const WAREHOUSE_ID = 100000;
const CREATOR_ID = 4;
const CREATOR_NAME = '阿猫';
function log(title, payload) {
console.log(`\n===== ${title} =====`);
console.log(typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2));
}
(async () => {
const app = mm.app({
baseDir: process.cwd(),
env: 'local',
clean: false,
cache: false,
});
await app.ready();
const ctx = app.createAnonymousContext();
ctx.user = { id: CREATOR_ID, store_id: WAREHOUSE_ID, employees_name: CREATOR_NAME };
const { Op, literal } = app.Sequelize;
const validSpaceSql = '(SELECT ls.id FROM wms_location_space ls '
+ 'JOIN wms_location_zone z ON z.id = ls.zone_id AND z.deleted_at IS NULL '
+ 'WHERE ls.deleted_at IS NULL)';
try {
// 1. 找一个在两个及以上有效库位都有库存的商品(模拟生产里同 stock_id 多库位明细的场景)
const storageRows = await ctx.model.Storage.findAll({
where: {
warehouse_id: WAREHOUSE_ID,
is_enabled: 1,
space_id: { [Op.in]: literal(validSpaceSql) },
},
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity)'), 'qty' ]],
group: [ 'stock_id', 'space_id' ],
raw: true,
});
const spacesByStock = new Map();
for (const row of storageRows) {
const stockId = Number(row.stock_id);
if (!spacesByStock.has(stockId)) {
spacesByStock.set(stockId, []);
}
spacesByStock.get(stockId).push(row);
}
const multiEntry = [ ...spacesByStock.entries() ]
.filter(([ , rows ]) => rows.length >= 2)
.sort((left, right) => left[0] - right[0])[0];
if (!multiEntry) {
throw new Error('开发库中未找到多库位库存商品,无法实测汇总口径');
}
const [ stockId, stockSpaces ] = multiEntry;
const stock = await ctx.model.StockWarehouse.findOne({ where: { id: stockId, warehouse_id: WAREHOUSE_ID }, raw: true });
log('1. 选中的多库位商品', {
stock_id: stockId,
item_code: stock.item_code,
item_name: stock.item_name,
store_id: stock.store_id,
spaces: stockSpaces.map(row => ({ space_id: Number(row.space_id), qty: Number(row.qty) })),
});
// 2. 创建任务 → 添加明细 → 提交 → 审核(走方法层,含 success 包装)
const created = await ctx.service.systemMethods.stock.check.create({
title: `实测_商品汇总_${Date.now()}`,
type: 'goods',
mode: 'open',
store_id: stock.store_id || undefined,
});
if (created.flag !== 'success') {
throw new Error(`create 失败: ${created.message}`);
}
const checkId = Number(created.data.id);
const added = await ctx.service.systemMethods.stock.check.addDetail({ id: checkId, stock_ids: [ stockId ] });
console.log(`\n2. 任务创建 ${created.data.check_no}(id=${checkId}),添加明细:added=${added.data.added} skipped=${added.data.skipped}`);
await ctx.service.systemMethods.stock.check.submit({ id: checkId });
const audited = await ctx.service.systemMethods.stock.check.audit({ id: checkId, action: 'approve' });
if (audited.flag !== 'success') {
throw new Error(`audit 失败: ${JSON.stringify(audited)}`);
}
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { check_id: checkId, scope_type: 'goods' },
order: [[ 'id', 'ASC' ]],
raw: true,
});
log('3. 明细行(商品按库位拆行,账面快照逐库位)', detailRows.map(row => ({
detail_id: Number(row.id),
stock_id: Number(row.stock_id),
location_id: Number(row.location_id),
location_code: row.location_code,
system_quantity: Number(row.system_quantity),
})));
// 4. report 免 detail_id:只传 id + stock_id + space_id(goods 汇总视图行不再带明细ID)
const reportTargets = detailRows.slice(0, 2);
for (const [ index, detailRow ] of reportTargets.entries()) {
const reported = await ctx.service.systemMethods.stock.check.report({
id: checkId,
stock_id: stockId,
space_id: Number(detailRow.location_id),
quantity: index === 0 ? 7 : 3,
});
log(`4.${index + 1} report 免 detail_id(space_id=${detailRow.location_id})`, {
flag: reported.flag,
code: reported.code,
message: reported.message,
resolved_detail_id: reported.data && reported.data.detail_id,
record: reported.data && {
id: reported.data.record.id,
detail_id: reported.data.record.detail_id,
stock_id: reported.data.record.stock_id,
location_id: reported.data.record.location_id,
location_code: reported.data.record.location_code,
quantity: reported.data.record.quantity,
},
});
}
// 5. workData goods 视图:一个商品一行,行级无 detail_id,locations 带 detail_id/snapshot_quantity
const workData = await ctx.service.systemMethods.stock.check.workData({ id: checkId, is_goods: true });
const goodsRow = workData.data.rows[0];
log('5. workData(is_goods=true) 商品视图行', {
view: workData.data.view,
total: workData.data.total,
row: goodsRow,
});
console.log(' → 行级是否含 detail_id:', Object.prototype.hasOwnProperty.call(goodsRow, 'detail_id'));
// 6. workDataDetail 商品钻取:id + stock_id → summary + rows
const drill = await ctx.service.systemMethods.stock.check.workDataDetail({ id: checkId, stock_id: stockId });
log('6. workDataDetail(id + stock_id) 商品钻取', {
flag: drill.flag,
data: drill.data,
});
// 7. 口径交叉校验
const snapshotTotal = detailRows.reduce((sum, row) => sum + Number(row.system_quantity), 0);
const rowsChecked = drill.data.rows.reduce((sum, row) => sum + Number(row.checked_quantity), 0);
log('7. 口径交叉校验', {
明细快照合计: snapshotTotal,
'goods 行级 system_quantity': goodsRow.system_quantity,
'goods 行级 checked_quantity': goodsRow.checked_quantity,
'drill.summary.system_quantity': drill.data.summary.system_quantity,
'drill.summary.checked_quantity': drill.data.summary.checked_quantity,
'drill.rows 实盘合计': rowsChecked,
'locations[].detail_id': goodsRow.locations.map(item => ({ code: item.location_code, detail_id: item.detail_id, snapshot: item.snapshot_quantity })),
一致: snapshotTotal === goodsRow.system_quantity
&& goodsRow.system_quantity === drill.data.summary.system_quantity
&& goodsRow.checked_quantity === drill.data.summary.checked_quantity
&& rowsChecked === drill.data.summary.checked_quantity,
});
} finally {
await app.close();
}
})().catch(error => {
console.error('实测失败:', error && error.stack || error);
process.exit(1);
});