fix(stock.check): result 商品范围按商品聚合输出,库位账面快照随行输出(0.3.259)

This commit is contained in:
liufumingren 2026-10-10 02:33:43 +08:00
parent e4472e2c74
commit ae107e5cbe
3 changed files with 394 additions and 125 deletions

View File

@ -230,12 +230,64 @@ class StockCheckService extends Service {
});
}
/**
* 计算盘点任务范围口径的条数汇总(total_items / checked_items,纯查询无副作用)。
* 商品范围(scope_type=goods)按商品(stock_id)去重计数(一个商品多个库位明细行合并为 1 项),
* 库位范围(scope_type=location)按明细行计数;已盘口径:明细存在盘点作业记录
* (wms_stock_check_record),商品范围按「商品下任一明细行有记录」计已盘。
*
* @param {number} checkId 盘点任务ID。
* @return {Promise<Object>} { total_items, checked_items }。
*/
async _countScopeSummary(checkId) {
const { ctx } = this;
const checkIdNumber = Number(checkId);
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { check_id: checkIdNumber },
attributes: [ 'id', 'scope_type', 'stock_id' ],
raw: true,
});
const recordRows = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkIdNumber },
attributes: [ 'detail_id' ],
raw: true,
});
const checkedDetailIds = new Set(recordRows.map(row => Number(row.detail_id)));
const goodsStockIds = new Set();
const checkedGoodsStockIds = new Set();
let locationCount = 0;
let checkedLocationCount = 0;
for (const detailRow of detailRows) {
if ((detailRow.scope_type || 'goods') === 'location') {
locationCount++;
if (checkedDetailIds.has(Number(detailRow.id))) {
checkedLocationCount++;
}
continue;
}
const stockId = Number(detailRow.stock_id);
goodsStockIds.add(stockId);
if (checkedDetailIds.has(Number(detailRow.id))) {
checkedGoodsStockIds.add(stockId);
}
}
return {
total_items: goodsStockIds.size + locationCount,
checked_items: checkedGoodsStockIds.size + checkedLocationCount,
};
}
/**
* 重算盘点主表的盘点进度汇总(checked_items / diff_items / detail_status)。
* 明细已盘口径:该明细存在盘点作业记录(wms_stock_check_record);
* 差异口径:明细行内任一商品「实盘合计 ≠ 账面」即该行有差异,按明细去重计数;
* 商品行账面 = system_quantity 快照,库位行账面 = wms_storage 按 (space_id, stock_id) 汇总
* (location_id 为空时账面按 0);
* 计数口径(与 _countScopeSummary 一致):商品范围(scope_type=goods)按商品(stock_id)
* 去重计数,库位范围按明细行计数;明细已盘口径:该明细存在盘点作业记录(wms_stock_check_record)。
* 差异口径:商品范围按商品聚合判断(商品实盘合计 ≠ 账面快照 system_quantity 合计即该商品有差异,
* 仅存在作业记录的商品计入,未盘商品不提前计差异——finish 时按实盘 0 计盘亏);
* 库位范围行内任一商品「实盘合计 ≠ 账面」即该行有差异,按明细去重计数,
* 库位行账面 = wms_storage 按 (space_id, stock_id) 汇总(location_id 为空时账面按 0);
* 未知商品(stock_id 为空)无账面,按 barcode 维度归组,实盘 > 0 即盘盈、必然计入差异;
* detail_status 按已盘明细占比自动重算:none_checked → partial_checked → all_checked。
*
@ -244,19 +296,15 @@ class StockCheckService extends Service {
*/
async _recalcCheckSummary(checkId) {
const { ctx } = this;
const { fn, col, Op, literal } = ctx.app.Sequelize;
const { Op, literal } = ctx.app.Sequelize;
const checkIdNumber = Number(checkId);
const detailWhere = { check_id: checkIdNumber };
const totalItems = await ctx.model.StockCheckDetail.count({ where: detailWhere });
// 有作业记录的明细数(DISTINCT detail_id)
const checkedCountRows = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkIdNumber },
attributes: [[ fn('COUNT', fn('DISTINCT', col('detail_id'))), 'checkedCount' ]],
raw: true,
});
const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0;
// 范围口径汇总:商品范围按商品(stock_id)计数,库位范围按明细行计数
const scopeSummary = await this._countScopeSummary(checkIdNumber);
const totalItems = scopeSummary.total_items;
const checkedItems = scopeSummary.checked_items;
// 明细与作业记录
const detailRows = await ctx.model.StockCheckDetail.findAll({
@ -313,6 +361,7 @@ class StockCheckService extends Service {
// 库位行账面:wms_storage 按 (space_id, stock_id) SUM(可用+锁定),并附到按商品聚合
const storageQuantityMap = new Map();
const locationDetailRows = detailRows.filter(row => (row.scope_type || 'goods') === 'location');
const goodsDetailRows = detailRows.filter(row => (row.scope_type || 'goods') !== 'location');
if (locationDetailRows.length > 0) {
const locationIds = [ ...new Set(locationDetailRows
.filter(row => row.location_id)
@ -396,14 +445,15 @@ class StockCheckService extends Service {
}
}
// 差异明细数:明细行内任一商品「实盘合计 ≠ 账面」即该行有差异,按明细去重计数;
// 差异项数:库位范围按明细行去重计数(行内任一商品实盘≠账面即该行有差异;
// 未知商品(stock_id 为空)无账面,实盘 > 0 即盘盈、必然计入差异;
// 空库位标记明细:账面有库存即盘亏差异(标记空与实际不符)
// 空库位标记明细:账面有库存即盘亏差异(标记空与实际不符));
// 商品范围按商品聚合计数(实盘合计 ≠ 账面快照合计即该商品有差异,仅存在作业记录的商品计入,
// 未盘商品不提前计差异——finish 时按实盘 0 计盘亏)
let diffItems = 0;
for (const detailRow of detailRows) {
for (const detailRow of locationDetailRows) {
const detailId = Number(detailRow.id);
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
if (scopeType === 'location' && emptyDetailIds.has(detailId)) {
if (emptyDetailIds.has(detailId)) {
if ((emptyLocationSystemMap.get(detailId) || 0) > 0) {
diffItems++;
}
@ -415,30 +465,48 @@ class StockCheckService extends Service {
continue;
}
let hasDiff = false;
if (scopeType === 'goods') {
const systemQuantity = Number(detailRow.system_quantity || 0);
hasDiff = (checkedQuantityByDetail.get(detailId) || 0) !== systemQuantity;
} else {
for (const agg of (byStock ? byStock.values() : [])) {
if (agg.checked !== (agg.system || 0)) {
for (const agg of (byStock ? byStock.values() : [])) {
if (agg.checked !== (agg.system || 0)) {
hasDiff = true;
break;
}
}
if (!hasDiff && byUnknown) {
for (const agg of byUnknown.values()) {
if (agg.checked > 0) {
hasDiff = true;
break;
}
}
if (!hasDiff && byUnknown) {
for (const agg of byUnknown.values()) {
if (agg.checked > 0) {
hasDiff = true;
break;
}
}
}
}
if (hasDiff) {
diffItems++;
}
}
// 商品范围差异:按商品(stock_id)聚合判断(多个库位明细行合并为一个商品)
const goodsCheckedByStock = new Map();
const goodsSnapshotByStock = new Map();
for (const detailRow of goodsDetailRows) {
const stockId = Number(detailRow.stock_id);
goodsSnapshotByStock.set(
stockId,
(goodsSnapshotByStock.get(stockId) || 0) + Number(detailRow.system_quantity || 0)
);
const checkedQuantity = checkedQuantityByDetail.get(Number(detailRow.id));
if (checkedQuantity !== undefined) {
goodsCheckedByStock.set(
stockId,
(goodsCheckedByStock.get(stockId) || 0) + checkedQuantity
);
}
}
for (const [ stockId, checkedQuantity ] of goodsCheckedByStock) {
if (checkedQuantity !== (goodsSnapshotByStock.get(stockId) || 0)) {
diffItems++;
}
}
const detailStatus = totalItems === 0 || checkedItems === 0
? 'none_checked'
: (checkedItems >= totalItems ? 'all_checked' : 'partial_checked');
@ -918,10 +986,9 @@ class StockCheckService extends Service {
await ctx.model.StockCheckDetail.bulkCreate(toCreate);
}
// 重算并更新主表 total_items
const totalItems = await ctx.model.StockCheckDetail.count({
where: { check_id: record.id },
});
// 重算并更新主表 total_items(商品范围按商品计数,库位范围按明细行计数)
const scopeSummary = await this._countScopeSummary(record.id);
const totalItems = scopeSummary.total_items;
await record.update({ total_items: totalItems });
const plainRecord = record.get({ plain: true });
@ -1101,10 +1168,9 @@ class StockCheckService extends Service {
await ctx.model.StockCheckDetail.bulkCreate(toCreate);
}
// 重算主表 total_items
const totalItems = await ctx.model.StockCheckDetail.count({
where: { check_id: checkId },
});
// 重算主表 total_items(商品范围按商品计数,库位范围按明细行计数)
const scopeSummary = await this._countScopeSummary(checkId);
const totalItems = scopeSummary.total_items;
await check.update({ total_items: totalItems });
// 写入操作日志(失败不影响主流程)
@ -1559,10 +1625,9 @@ class StockCheckService extends Service {
});
}
// 删除明细后重算主表 total_items
const totalItems = await ctx.model.StockCheckDetail.count({
where: { check_id: checkId },
});
// 删除明细后重算主表 total_items(商品范围按商品计数,库位范围按明细行计数)
const scopeSummary = await this._countScopeSummary(checkId);
const totalItems = scopeSummary.total_items;
await check.update({ total_items: totalItems });
// 写入操作日志(失败不影响主流程)
@ -1633,19 +1698,24 @@ class StockCheckService extends Service {
}
/**
* 拉取盘点明细结果(按范围行聚合作业记录)。
* 商品行聚合其库位作业记录,库位行按商品聚合作业记录并从 wms_storage 补齐账面数量。
* 拉取盘点明细结果(按范围聚合作业记录)。
* 商品范围(scope_type=goods)按商品合并输出(一个商品一行,多个库位明细行合并),
* 行内 locations 输出该商品所在库位与账面快照数量;库位范围(scope_type=location)
* 按明细行输出,行内按商品聚合作业记录并从 wms_storage 补齐账面数量。
* 未知商品(记录 stock_id 为空)按 barcode 维度归组,行级额外输出 unknown_items;
* 每条作业记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径)。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @return {Promise<Object>} { check, rows, total };商品行含商品快照 + 已盘聚合
* (checked_quantity=记录数量合计、diff_quantity=实盘-账面、is_diff、status、location_codes、
* checkers、last_checked_at)、records(该明细全部作业记录,每条含 barcode/item_name/images)与 locations
* (按库位聚合 [{ location_id, location_code, quantity }],按首条记录 id 升序);
* 库位行输出 { ...row, scope_type: 'location', stocks },stocks 按商品聚合该明细下记录
* @return {Promise<Object>} { check, rows, total };商品范围按商品聚合(一个商品一行):
* 行含商品快照(item_code/item_name/spec/batch_no)+ system_quantity(账面快照合计)+ 已盘聚合
* (checked_quantity=记录数量合计、diff_quantity=实盘-账面快照合计、is_diff、status、location_codes、
* checkers、last_checked_at)、records(该商品全部作业记录,每条含 barcode/item_name/images)与
* locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }]——
* system_quantity 为该库位账面快照(创建明细时落库,盘点时做快照)、quantity 为该库位实盘合计
* (未盘库位为 0),仅作业记录存在而快照不存在的库位追加在末尾(system_quantity=0));
* 库位范围行输出 { ...row, scope_type: 'location', stocks },stocks 按商品聚合该明细下记录
* [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],
* 账面数量查 wms_storage SUM(available_quantity+locked_quantity)(=可用+锁定),行级 checked_quantity 为行内合计、
* diff_quantity 为行内各商品差异代数和;
@ -1684,8 +1754,15 @@ class StockCheckService extends Service {
const rows = await this._buildDetailAggregations({ detailRows, recordRows: records });
// 主表计数按聚合行口径同步输出(商品范围按商品计数):历史任务主表可能残留
// 按库位拆行写入的 total_items/checked_items/diff_items,响应口径以聚合行为准
const formattedCheck = this._formatCheckRow(check.get({ plain: true }));
formattedCheck.total_items = rows.length;
formattedCheck.checked_items = rows.filter(row => row.status === 'checked').length;
formattedCheck.diff_items = rows.filter(row => row.is_diff === 1).length;
return {
check: this._formatCheckRow(check.get({ plain: true })),
check: formattedCheck,
rows,
total: rows.length,
};
@ -1743,13 +1820,16 @@ class StockCheckService extends Service {
}
/**
* 构建盘点明细聚合行(商品行聚合其库位作业记录;库位行按商品聚合作业记录,
* 并从 wms_storage 补齐各商品账面数量;未知商品按 barcode 维度归组输出 unknown_items)。
* 构建盘点明细聚合行。
* 商品范围(scope_type=goods):按商品(stock_id)合并输出(一个商品一行,多个库位明细行合并)——
* 行含账面快照合计与商品所在库位列表(每库位 system_quantity 账面快照 + quantity 实盘合计);
* 库位范围(scope_type=location):按明细行输出,行内按商品聚合作业记录,
* 并从 wms_storage 补齐各商品账面数量;未知商品按 barcode 维度归组输出 unknown_items。
*
* @param {Object} params 聚合参数。
* @param {Array<Object>} params.detailRows 明细原始行。
* @param {Array<Object>} params.recordRows 作业记录原始行。
* @return {Promise<Array<Object>>} 格式化后的明细行列表。
* @return {Promise<Array<Object>>} 格式化后的聚合行列表(按首条明细 id 升序)。
*/
async _buildDetailAggregations(params = {}) {
const { detailRows, recordRows } = params;
@ -1766,27 +1846,32 @@ class StockCheckService extends Service {
recordsByDetail.get(detailRowId).push(record);
}
// 收集商品 ID 集合:商品行取明细 stock_id,库位行取记录 stock_id
const stockIds = new Set();
// 分拣:商品范围行按 stock_id 分组合并(按商品盘点一行一商品),库位范围行按明细行处理
const locationRows = [];
const goodsGroups = new Map();
for (const detailRow of detailRows) {
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
if (scopeType === 'goods') {
if (detailRow.stock_id) {
stockIds.add(Number(detailRow.stock_id));
}
} else {
if (scopeType === 'location') {
locationRows.push(detailRow);
const detailRecords = recordsByDetail.get(Number(detailRow.id)) || [];
for (const record of detailRecords) {
if (record.stock_id) {
stockIds.add(Number(record.stock_id));
}
continue;
}
const stockId = Number(detailRow.stock_id);
if (!goodsGroups.has(stockId)) {
goodsGroups.set(stockId, []);
}
goodsGroups.get(stockId).push(detailRow);
}
// 库位行需要:记录商品快照(wms_stock_warehouse)与库位账面(wms_storage 可用+锁定)
const stockIds = new Set();
for (const detailRow of locationRows) {
const detailRecords = recordsByDetail.get(Number(detailRow.id)) || [];
for (const record of detailRecords) {
if (record.stock_id) {
stockIds.add(Number(record.stock_id));
}
}
}
// 商品快照(item_code/item_name)从 wms_stock_warehouse 补齐
let stockMap = new Map();
if (stockIds.size > 0) {
const stockRows = await ctx.model.StockWarehouse.findAll({
@ -1826,18 +1911,191 @@ class StockCheckService extends Service {
}
}
return Promise.all(detailRows.map(detailRow => this._formatDetailAggregationRow({
// 商品范围:按商品合并输出(账面快照按库位明细行汇总,实盘按作业记录聚合)
const formattedRows = [];
for (const groupRows of goodsGroups.values()) {
const row = this._formatMergedGoodsAggregationRow({ groupRows, recordsByDetail });
formattedRows.push({ row, firstDetailId: Number(groupRows[0].id) });
}
const locationFormatted = await Promise.all(locationRows.map(detailRow => this._formatDetailAggregationRow({
detailRow,
recordsByDetail,
stockMap,
storageQuantityMap,
})));
for (const item of locationFormatted) {
formattedRows.push({ row: item, firstDetailId: Number(item.id) });
}
return formattedRows
.sort((left, right) => left.firstDetailId - right.firstDetailId)
.map(item => item.row);
}
/**
* 将单条盘点明细格式化为聚合输出行。
* 商品行:聚合作业记录输出已盘数量/差异/库位列表等;
* 库位行:按商品聚合作业记录输出 stocks 列表(含 wms_storage 账面与差异);
* 将同商品的多个库位明细行合并格式化为一条商品聚合输出行(按商品盘点一行一商品)。
* 行含商品快照 + system_quantity(账面快照合计,各库位明细行 system_quantity 之和)+
* locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }]:
* system_quantity 为该库位账面快照(创建明细时落库,盘点时做快照)、quantity 为该库位实盘合计
* (未盘库位为 0;仅作业记录存在而快照不存在的库位追加在末尾,system_quantity=0))+
* checked_quantity(作业记录数量合计)/diff_quantity(实盘-账面快照合计)/is_diff/status/location_codes/
* checkers/last_checked_at/records/unknown_items,与库位范围行输出字段口径一致。
*
* @param {Object} params 格式化参数。
* @param {Array<Object>} params.groupRows 同商品明细原始行(按明细 id 升序)。
* @param {Map<number, Array<Object>>} params.recordsByDetail 按明细ID分组的作业记录。
* @return {Object} 格式化后的商品聚合行。
*/
_formatMergedGoodsAggregationRow(params = {}) {
const { groupRows, recordsByDetail } = params;
const firstRow = groupRows[0];
// 该商品全部作业记录(按明细 id 升序 → 记录 id 升序)
const detailRecords = [];
for (const groupRow of groupRows) {
const rows = recordsByDetail.get(Number(groupRow.id)) || [];
detailRecords.push(...rows);
}
// 已盘聚合(与库位范围行口径一致)
const locationCodes = [ ...new Set(detailRecords
.map(record => String(record.location_code || '').trim())
.filter(Boolean)) ];
const checkers = [ ...new Set(detailRecords
.map(record => String(record.checker_name || '').trim())
.filter(Boolean)) ];
const lastCheckedAt = detailRecords.length > 0
? detailRecords[detailRecords.length - 1].checked_at
: null;
// 未知商品(stock_id 为空)按 barcode 维度归组(无账面,差异 = 实盘 - 0 = 盘盈);
// 空库位标记记录不参与未知商品聚合
const unknownByBarcode = new Map();
for (const record of detailRecords) {
if (record.is_empty) {
continue;
}
const recordStockId = Number(record.stock_id);
if (Number.isInteger(recordStockId) && recordStockId > 0) {
continue;
}
const recordBarcode = String(record.barcode || '').trim() || null;
const barcodeKey = recordBarcode || 'unknown';
const unknownAgg = unknownByBarcode.get(barcodeKey) || {
barcode: recordBarcode,
item_name: record.item_name || null,
checked: 0,
};
unknownAgg.checked += Number(record.quantity) || 0;
unknownByBarcode.set(barcodeKey, unknownAgg);
}
const unknownItems = [ ...unknownByBarcode.values() ]
.sort((left, right) => String(left.barcode || '').localeCompare(String(right.barcode || '')))
.map(agg => ({
barcode: agg.barcode,
item_name: agg.item_name,
checked_quantity: agg.checked,
}));
// 账面快照库位(创建明细时落库,盘点时做快照,按明细 id 升序)
const locations = groupRows.map(groupRow => ({
location_id: groupRow.location_id !== null && groupRow.location_id !== undefined
? Number(groupRow.location_id)
: null,
location_code: groupRow.location_code !== null && groupRow.location_code !== undefined
? String(groupRow.location_code).trim()
: null,
system_quantity: Number(groupRow.system_quantity) || 0,
quantity: 0,
}));
const snapshotIndexByCode = new Map();
const snapshotIndexByLocationId = new Map();
locations.forEach((location, index) => {
if (location.location_code) {
snapshotIndexByCode.set(location.location_code, index);
}
if (location.location_id !== null && location.location_id !== undefined) {
snapshotIndexByLocationId.set(location.location_id, index);
}
});
// 按库位聚合作业记录(库位为空归入"无库位"分组,location_code 为 null),按首条记录 id 升序
const locationGroups = new Map();
for (const record of detailRecords) {
const recordLocationCode = record.location_code !== null && record.location_code !== undefined
? String(record.location_code).trim()
: '';
if (!locationGroups.has(recordLocationCode)) {
locationGroups.set(recordLocationCode, {
location_id: recordLocationCode ? (Number(record.location_id) || null) : null,
location_code: recordLocationCode || null,
quantity: 0,
first_record_id: Number(record.id) || 0,
});
}
const locationGroup = locationGroups.get(recordLocationCode);
locationGroup.quantity += Number(record.quantity) || 0;
}
// 已盘库位与账面快照库位合并:优先按库位编码匹配、其次按库位ID兜底;
// 未命中快照的已盘库位(商品移动后新出现的库位)追加在末尾
const extraGroups = [];
for (const group of locationGroups.values()) {
const groupCode = group.location_code || '';
let targetIndex = groupCode ? snapshotIndexByCode.get(groupCode) : undefined;
if (targetIndex === undefined && group.location_id !== null && group.location_id !== undefined) {
targetIndex = snapshotIndexByLocationId.get(group.location_id);
}
if (targetIndex === undefined) {
extraGroups.push(group);
continue;
}
const target = locations[targetIndex];
target.quantity = group.quantity;
if ((target.location_id === null || target.location_id === undefined) && group.location_id != null) {
target.location_id = group.location_id;
}
if (!target.location_code && group.location_code) {
target.location_code = group.location_code;
}
}
extraGroups
.sort((left, right) => left.first_record_id - right.first_record_id)
.forEach(group => {
locations.push({
location_id: group.location_id,
location_code: group.location_code,
system_quantity: 0,
quantity: group.quantity,
});
});
const systemQuantity = locations.reduce((sum, location) => sum + location.system_quantity, 0);
const checkedQuantity = detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0);
const diffQuantity = checkedQuantity - systemQuantity;
return {
...firstRow,
scope_type: 'goods',
location_id: null,
location_code: null,
system_quantity: systemQuantity,
location_codes: locationCodes,
checkers,
last_checked_at: lastCheckedAt,
records: detailRecords,
locations,
checked_quantity: detailRecords.length > 0 ? checkedQuantity : null,
diff_quantity: detailRecords.length > 0 ? diffQuantity : null,
is_diff: detailRecords.length > 0 && diffQuantity !== 0 ? 1 : 0,
status: detailRecords.length > 0 ? 'checked' : 'unchecked',
unknown_items: unknownItems,
};
}
/**
* 将单条库位范围明细格式化为聚合输出行(商品范围行由 _formatMergedGoodsAggregationRow 合并处理)。
* 按商品聚合作业记录输出 stocks 列表(含 wms_storage 账面与差异);
* 未知商品(记录 stock_id 为空)按 barcode 维度归组,行级输出 unknown_items:
* [{ barcode, item_name, checked_quantity }](无账面,差异 = 实盘 - 0 = 盘盈,
* 已计入行级 checked_quantity/diff_quantity/is_diff),stocks 保持只输出已知商品。
@ -1931,20 +2189,7 @@ class StockCheckService extends Service {
locations,
};
if (scopeType === 'goods') {
const checkedQuantity = detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0);
const diffQuantity = checkedQuantity - Number(detailRow.system_quantity || 0);
return {
...base,
checked_quantity: detailRecords.length > 0 ? checkedQuantity : null,
diff_quantity: detailRecords.length > 0 ? diffQuantity : null,
is_diff: detailRecords.length > 0 && diffQuantity !== 0 ? 1 : 0,
status: detailRecords.length > 0 ? 'checked' : 'unchecked',
unknown_items: unknownItems,
};
}
// 库位行:按商品聚合记录,账面从 wms_storage 取(location_id 为空时账面按 0);
// 库位范围行:按商品聚合记录,账面从 wms_storage 取(location_id 为空时账面按 0);
// 空库位标记:无商品聚合,账面有库存即盘亏(差异 = -账面总量)
const isEmptyLocation = detailRecords.some(record => record.is_empty);
const locationId = detailRow.location_id !== null && detailRow.location_id !== undefined
@ -3805,8 +4050,9 @@ class StockCheckService extends Service {
* 计算任务数量差异汇总(盘盈/盘亏/差异明细数,纯查询无副作用)。
*
* 口径:
* - 商品行(scope_type=goods):聚合 vs 账面快照 system_quantity;未盘商品行按实盘 0 处理
* (差异 = -账面快照,即盘亏);
* - 商品范围(scope_type=goods):按商品聚合(一行一商品,多个库位明细行合并)——
* 已盘商品差异 = 商品实盘合计 - 账面快照 system_quantity 合计;未盘商品按实盘 0 处理
* (差异 = -账面快照合计,即盘亏);
* - 库位行(scope_type=location):按商品聚合 vs wms_storage 账面;未盘库位行无法枚举商品,
* 不计差异;
* - 未知商品(记录 stock_id 为空)无账面:实盘 > 0 即盘盈,必然计入差异。
@ -3824,30 +4070,45 @@ class StockCheckService extends Service {
const unknownQuantityByDetail = summary.unknown_quantity_by_detail || new Map();
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { check_id: Number(checkId) },
attributes: [ 'id', 'scope_type', 'system_quantity' ],
attributes: [ 'id', 'scope_type', 'stock_id', 'system_quantity' ],
raw: true,
});
let profitTotal = 0;
let lossTotal = 0;
let diffItems = 0;
// 商品范围:按商品聚合(一行一商品,多个库位明细行合并)——
// 已盘商品差异 = 商品实盘合计 - 账面快照合计;未盘商品按实盘 0 处理(差异 = -账面快照合计,即盘亏)
const goodsByStock = new Map();
for (const detailRow of detailRows) {
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
if (scopeType !== 'goods') {
continue;
}
const stockId = Number(detailRow.stock_id);
const agg = goodsByStock.get(stockId) || { snapshot: 0, checked: 0, hasRecords: false };
agg.snapshot += Number(detailRow.system_quantity || 0);
const checkedQuantity = checkedQuantityByDetail.get(Number(detailRow.id));
if (checkedQuantity !== undefined) {
agg.hasRecords = true;
agg.checked += checkedQuantity;
}
goodsByStock.set(stockId, agg);
}
for (const agg of goodsByStock.values()) {
const diffQuantity = agg.hasRecords ? agg.checked - agg.snapshot : -agg.snapshot;
if (diffQuantity !== 0) {
diffItems++;
if (diffQuantity > 0) {
profitTotal += diffQuantity;
} else {
lossTotal += Math.abs(diffQuantity);
}
}
}
for (const detailRow of detailRows) {
const detailId = Number(detailRow.id);
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
if (scopeType === 'goods') {
const systemQuantity = Number(detailRow.system_quantity || 0);
const checkedQuantity = checkedQuantityByDetail.get(detailId);
// 已盘商品行按记录聚合差异;未盘商品行按实盘 0 处理(差异 = -账面快照,即盘亏)
const diffQuantity = checkedQuantity === undefined
? -systemQuantity
: checkedQuantity - systemQuantity;
if (diffQuantity !== 0) {
diffItems++;
if (diffQuantity > 0) {
profitTotal += diffQuantity;
} else {
lossTotal += Math.abs(diffQuantity);
}
}
if (scopeType !== 'location') {
continue;
}
// 库位行:按商品聚合 vs wms_storage 账面;未盘库位行无法枚举商品,不计差异
@ -3904,7 +4165,6 @@ class StockCheckService extends Service {
async finish(params = {}) {
const { warehouseId, id } = params;
const { ctx } = this;
const { fn, col } = ctx.app.Sequelize;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
@ -3919,17 +4179,10 @@ class StockCheckService extends Service {
throw this.createBusinessError(`当前状态(${check.status})不允许完成盘点`);
}
const totalItems = await ctx.model.StockCheckDetail.count({
where: { check_id: checkId },
});
// 已盘明细数:存在作业记录(wms_stock_check_record)的明细数
const checkedCountRows = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkId },
attributes: [[ fn('COUNT', fn('DISTINCT', col('detail_id'))), 'checkedCount' ]],
raw: true,
});
const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0;
// 范围口径汇总:商品范围按商品计数,库位范围按明细行计数(与 _recalcCheckSummary 一致)
const scopeSummary = await this._countScopeSummary(checkId);
const totalItems = scopeSummary.total_items;
const checkedItems = scopeSummary.checked_items;
const uncheckedItems = totalItems - checkedItems;
// 数量差异汇总(盘盈/盘亏/差异明细数,口径见 _calcQuantityDiffSummary)

View File

@ -1,4 +1,20 @@
[
{
"version": "0.3.259",
"date": "2026-10-10",
"type": "updated",
"summary": "stock.check.result 商品范围按商品聚合输出(一个商品一行,多个库位明细行合并),行内 locations 输出各库位账面快照与实盘;主表计数同步商品口径(0.3.258 → 0.3.259)",
"methods": [
"stock.check.result",
"stock.check.detail"
],
"notes": [
"变更内容:按商品盘点(scope_type=goods)不再按库位拆行输出——result 商品范围按 stock_id 合并(一行一商品),行含 system_quantity(账面快照合计=各库位明细行 system_quantity 之和,创建明细时落库=盘点时做快照)与 locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }]:system_quantity 为该库位账面快照、quantity 为该库位实盘合计(未盘为 0),仅作业记录存在而快照不存在的库位追加在末尾且 system_quantity=0);行级 checked_quantity/diff_quantity/is_diff/status 按合并后的商品口径计算;主表计数 total_items/checked_items/diff_items 响应口径以聚合行为准(total_items=行数、checked_items=已盘行数、diff_items=差异行数)。",
"同步改动:主表 total_items 商品范围改为按商品计数(addDetail/detailDelete/patternCreate/_countScopeSummary);_recalcCheckSummary 的 checked_items/diff_items 与 finish/_calcQuantityDiffSummary 的盘盈盘亏汇总(detail profit/loss 同口径)均改为商品范围按商品聚合;detail 描述同步。",
"代码依据:app/service/systems/stock_check.js#result/#_buildDetailAggregations(新增 _formatMergedGoodsAggregationRow 商品合并格式化器,_formatDetailAggregationRow 仅保留库位行)、#_countScopeSummary(新增)、#_recalcCheckSummary、#finish、#_calcQuantityDiffSummary;回归测试新增「多库位商品合并为一行」用例(全部库位上报、差异=实盘合计-账面快照合计),stock_check 全量 229 用例通过、ESLint 0 错误。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.result(description/response.rows/notes 同步商品范围合并口径)与 stock.check.detail(description 盘盈盘亏口径短语同步)两条;根版本 0.3.258 → 0.3.259、updatedAt 2026-10-09 → 2026-10-10;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组仍为 24 条)。"
]
},
{
"version": "0.3.258",
"date": "2026-10-09",

View File

@ -1,8 +1,8 @@
{
"module": "system",
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
"version": "0.3.258",
"updatedAt": "2026-10-09",
"version": "0.3.259",
"updatedAt": "2026-10-10",
"headers": [
{
"name": "platform",
@ -38475,7 +38475,7 @@
},
{
"method": "stock.check.detail",
"description": "拉取盘点任务详情(只返回任务本身信息):入参 id(盘点任务ID);返回 { check },check 为盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at;start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间))+ 数量差异汇总 profit_total(盘盈合计数量)/loss_total(盘亏合计数量,正数口径,与 finish 一致;商品行聚合 vs 账面快照(未盘商品行按实盘 0 计盘亏)、库位行按商品聚合 vs wms_storage 账面(SUM(available_quantity+locked_quantity)=可用+锁定,未盘库位行不计差异)、未知商品按实盘计盘盈;无作业记录时均为 0);不再返回明细范围行(rows)与明细总条数(total)——盘点明细范围行/盘点结果聚合请调用 stock.check.result,作业记录请调用 stock.check.recordList,盘点作业数据请调用 stock.check.workData;400 边界(任务ID为空/任务不存在)。",
"description": "拉取盘点任务详情(只返回任务本身信息):入参 id(盘点任务ID);返回 { check },check 为盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at;start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间))+ 数量差异汇总 profit_total(盘盈合计数量)/loss_total(盘亏合计数量,正数口径,与 finish 一致;商品范围按商品聚合 vs 账面快照合计(未盘商品按实盘 0 计盘亏)、库位行按商品聚合 vs wms_storage 账面(SUM(available_quantity+locked_quantity)=可用+锁定,未盘库位行不计差异)、未知商品按实盘计盘盈;无作业记录时均为 0);不再返回明细范围行(rows)与明细总条数(total)——盘点明细范围行/盘点结果聚合请调用 stock.check.result,作业记录请调用 stock.check.recordList,盘点作业数据请调用 stock.check.workData;400 边界(任务ID为空/任务不存在)。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -38555,7 +38555,7 @@
},
{
"method": "stock.check.result",
"description": "拉取盘点明细结果(按范围行聚合作业记录):入参 id(盘点任务ID);返回 { check, rows, total };商品行(scope_type=goods)含商品快照 + 已盘聚合(checked_quantity=作业记录数量合计、diff_quantity=实盘-账面、is_diff、status=checked|unchecked、location_codes、checkers、last_checked_at)+ records(该明细在 wms_stock_check_record 的全部作业记录,每条含 barcode/item_name 与 images 图片列表)+ locations(按库位聚合 [{ location_id, location_code, quantity }],空库位归 location_code=null 组,按首条记录 id 升序)+ unknown_items(未知商品按条码聚合 [{ barcode, item_name, checked_quantity }],无账面、差异=实盘-0=盘盈);库位行(scope_type=location)含 is_empty(是否空库位标记)+ checked_quantity(行级合计=行内商品实盘合计)、diff_quantity(行内各商品差异代数和)、is_diff、status + records/locations + stocks(按商品聚合 [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],按 stock_id 升序,账面 system_quantity 查 wms_storage(space_id+stock_id SUM(available_quantity+locked_quantity)=可用+锁定),location_id 为空时账面按 0)+ unknown_items(口径同商品行);每条作业记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径);空库位标记(is_empty=true)时:stocks=[]、unknown_items=[]、checked_quantity=0、status=checked(视为已盘点),账面有库存时 diff_quantity 为负数(盘亏,差异=0-库位账面库存总量)、is_diff=1;无作业记录时聚合字段为 null、records/locations/stocks 为空数组。",
"description": "拉取盘点明细结果(按范围聚合作业记录):入参 id(盘点任务ID);返回 { check, rows, total };商品范围按商品聚合(一个商品一行,多个库位明细行合并):行含商品快照 + system_quantity(账面快照合计=各库位明细行 system_quantity 之和,创建明细时落库=盘点时做快照)+ 已盘聚合(checked_quantity=作业记录数量合计、diff_quantity=实盘-账面快照合计、is_diff、status=checked|unchecked、location_codes、checkers、last_checked_at)+ records(该商品在 wms_stock_check_record 的全部作业记录,每条含 barcode/item_name 与 images 图片列表)+ locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }],system_quantity 为该库位账面快照(盘点时做快照)、quantity 为该库位实盘合计(未盘库位为 0),按明细 id 升序;仅作业记录存在而快照不存在的库位追加在末尾且 system_quantity=0)+ unknown_items(未知商品按条码聚合 [{ barcode, item_name, checked_quantity }],无账面、差异=实盘-0=盘盈);库位行(scope_type=location)含 is_empty(是否空库位标记)+ checked_quantity(行级合计=行内商品实盘合计)、diff_quantity(行内各商品差异代数和)、is_diff、status + records/locations + stocks(按商品聚合 [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],按 stock_id 升序,账面 system_quantity 查 wms_storage(space_id+stock_id SUM(available_quantity+locked_quantity)=可用+锁定),location_id 为空时账面按 0)+ unknown_items(口径同商品范围);主表计数 check.total_items/checked_items/diff_items 按聚合行口径同步输出(商品范围按商品计数);每条作业记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径);空库位标记(is_empty=true)时:stocks=[]、unknown_items=[]、checked_quantity=0、status=checked(视为已盘点),账面有库存时 diff_quantity 为负数(盘亏,差异=0-库位账面库存总量)、is_diff=1;无作业记录时聚合字段为 null、records 为空数组。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -38610,7 +38610,7 @@
"name": "rows",
"type": "array",
"required": true,
"description": "明细结果行列表:商品行(scope_type=goods)含范围行字段 + 已盘聚合字段(checked_quantity 已盘数量=作业记录 quantity 合计,无记录为 null;diff_quantity 差异数量=已盘-账面快照,无记录为 null;is_diff 是否有差异 0|1;status 盘点状态 checked|unchecked;location_codes 库位编码数组去重;checkers 盘点人数组去重;last_checked_at 最近上报时间,无记录为 null)+ records(该明细全部盘点作业记录,每条含 id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/barcode/item_name/created_at/updated_at + images 图片列表 [{ id: file_id, url }],FileReference business_type=stock_check_record)+ locations(按库位聚合数组 [{ location_id, location_code, quantity }],quantity 为该库位下作业记录数量合计,空库位记录归 location_code=null 组,按首条记录 id 升序)+ unknown_items(未知商品聚合数组 [{ barcode, item_name, checked_quantity }],按条码升序;记录 stock_id 为空的未知商品按条码归组,无账面、差异=实盘-0=盘盈,已计入行级 checked_quantity/diff_quantity/is_diff;无未知商品为空数组);库位行(scope_type=location)含范围行字段 + is_empty(是否空库位标记:该明细存在空标记记录(is_empty=1)时为 true)+ stocks(按商品聚合数组 [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],按 stock_id 升序,仅含存在作业记录的已知商品;system_quantity 为 wms_storage 账面(space_id+stock_id SUM(available_quantity+locked_quantity)=可用+锁定),location_id 为空时按 0)+ checked_quantity(行级合计=行内商品实盘合计,无记录为 null)/ diff_quantity(行内各商品差异代数和,无记录为 null)/ is_diff / status + location_codes / checkers / last_checked_at + records / locations + unknown_items(口径同商品行);空库位标记(is_empty=true)时:stocks=[]、unknown_items=[]、checked_quantity=0、diff_quantity=0-库位账面库存总量(账面有库存时为负数=盘亏、账面为 0 时为 0)、is_diff=账面有库存时为 1、status=checked(视为已盘点);无作业记录时 records/locations/stocks/unknown_items 为空数组、checked_quantity/diff_quantity/last_checked_at 为 null"
"description": "明细结果行列表:商品范围按商品聚合(一个商品一行,多个库位明细行合并)——行含范围行字段(合并后行级 location_id/location_code 为 null)+ system_quantity(账面快照合计=各库位明细行 system_quantity 之和,创建明细时落库=盘点时做快照)+ 已盘聚合字段(checked_quantity 已盘数量=作业记录 quantity 合计,无记录为 null;diff_quantity 差异数量=已盘-账面快照合计,无记录为 null;is_diff 是否有差异 0|1;status 盘点状态 checked|unchecked;location_codes 库位编码数组去重;checkers 盘点人数组去重;last_checked_at 最近上报时间,无记录为 null)+ records(该商品全部盘点作业记录,每条含 id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/barcode/item_name/created_at/updated_at + images 图片列表 [{ id: file_id, url }],FileReference business_type=stock_check_record)+ locations(商品所在库位列表 [{ location_id, location_code, system_quantity, quantity }],system_quantity 为该库位账面快照(创建明细时落库)、quantity 为该库位实盘合计(未盘库位为 0),按明细 id 升序;仅作业记录存在而快照不存在的库位追加在末尾且 system_quantity=0)+ unknown_items(未知商品聚合数组 [{ barcode, item_name, checked_quantity }],按条码升序;记录 stock_id 为空的未知商品按条码归组,无账面、差异=实盘-0=盘盈,已计入行级 checked_quantity/diff_quantity/is_diff;无未知商品为空数组);库位行(scope_type=location)含范围行字段 + is_empty(是否空库位标记:该明细存在空标记记录(is_empty=1)时为 true)+ stocks(按商品聚合数组 [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],按 stock_id 升序,仅含存在作业记录的已知商品;system_quantity 为 wms_storage 账面(space_id+stock_id SUM(available_quantity+locked_quantity)=可用+锁定),location_id 为空时按 0)+ checked_quantity(行级合计=行内商品实盘合计,无记录为 null)/ diff_quantity(行内各商品差异代数和,无记录为 null)/ is_diff / status + location_codes / checkers / last_checked_at + records / locations + unknown_items(口径同商品行);空库位标记(is_empty=true)时:stocks=[]、unknown_items=[]、checked_quantity=0、diff_quantity=0-库位账面库存总量(账面有库存时为负数=盘亏、账面为 0 时为 0)、is_diff=账面有库存时为 1、status=checked(视为已盘点);无作业记录时 records/locations/stocks/unknown_items 为空数组、checked_quantity/diff_quantity/last_checked_at 为 null"
},
{
"name": "total",
@ -38639,10 +38639,10 @@
],
"notes": [
"权限口径:随 ALL_METHOD_NAMES(16 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog(list/detail/result/recordList/export/exportTaskProgress)。",
"商品行聚合口径:checked_quantity=该明细全部作业记录 quantity 合计;diff_quantity=已盘-账面(账面为明细 system_quantity 快照);is_diff=存在记录且差异非 0 时为 1;status=存在记录 checked,否则 unchecked。",
"商品范围聚合口径:按商品合并(一个商品一行,多个库位明细行合并)——checked_quantity=该商品全部作业记录 quantity 合计;diff_quantity=已盘-账面快照合计(各库位明细行 system_quantity 之和,创建明细时落库=盘点时做快照);locations 各库位同时输出 system_quantity(该库位账面快照)与 quantity(该库位实盘合计,未盘库位为 0);is_diff=存在记录且差异非 0 时为 1;status=存在记录 checked,否则 unchecked。主表计数 check.total_items/checked_items/diff_items 按聚合行口径同步输出(total_items=行数、checked_items=已盘行数、diff_items=差异行数),历史任务主表残留的按库位拆行计数在响应中以聚合行为准。",
"库位行账面口径:wms_storage 按 (space_id, stock_id) SUM(available_quantity+locked_quantity)(=可用+锁定)现算(与 finish/export 汇总口径一致),location_id 为空时账面按 0;库位行 stocks 仅含存在作业记录的已知商品(stock_id 有值,无记录时为空数组),商品快照 item_code/item_name 从 wms_stock_warehouse 补齐。",
"无作业记录时:checked_quantity/diff_quantity/last_checked_at 为 null、records/locations/stocks 为空数组、status=unchecked、is_diff=0。",
"未知商品聚合口径:stock_id 为空的作业记录按 barcode 维度归组输出行级 unknown_items [{ barcode, item_name, checked_quantity }](按条码升序,item_name 为上报名称快照);未知商品无账面,差异=实盘-0=盘盈,已计入行级 checked_quantity/diff_quantity/is_diff;stocks 保持只输出已知商品(stock_id 有值)。代码依据:app/service/systems/stock_check.js#_formatDetailAggregationRow。",
"无作业记录时:checked_quantity/diff_quantity/last_checked_at 为 null、records 为空数组、status=unchecked、is_diff=0(商品范围 locations 仍输出账面快照库位且 quantity 为 0;库位范围 locations/stocks 为空数组)。",
"未知商品聚合口径:stock_id 为空的作业记录按 barcode 维度归组输出行级 unknown_items [{ barcode, item_name, checked_quantity }](按条码升序,item_name 为上报名称快照);未知商品无账面,差异=实盘-0=盘盈,已计入行级 checked_quantity/diff_quantity/is_diff;stocks 保持只输出已知商品(stock_id 有值)。代码依据:app/service/systems/stock_check.js#_formatMergedGoodsAggregationRow(商品范围合并行)/#_formatDetailAggregationRow(库位行)。",
"图片挂载口径(图片独立维护,仿收货 receivingItem):_attachRecordImages 查询 wms_file_reference(business_type=stock_check_record,business_id in 记录ID)并关联 wms_file 取 file_url,每条作业记录挂载 images [{ id: file_id, url }],无图片返回空数组;上传走通用上传接口(uploadSuccessNotify 传 businessType=stock_check_record + businessId=作业记录ID,建 FileReference)。代码依据:app/service/systems/stock_check.js#result/#_attachRecordImages。",
"响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。",
"空库位标记口径(本次新增):库位行存在空标记记录(is_empty=1)时 is_empty=true——stocks 为空数组、unknown_items 为空数组、checked_quantity=0、status=checked(视为已盘点);账面口径:按 location_id 查 wms_storage SUM(available_quantity+locked_quantity)(该库位全部库存账面总量=可用+锁定,location_id 为空时按 0),账面>0 时 diff_quantity=-账面总量(盘亏)、is_diff=1,账面=0 时 diff_quantity=0、is_diff=0。代码依据:app/service/systems/stock_check.js#_formatDetailAggregationRow。",