Compare commits

...

4 Commits

Author SHA1 Message Date
liufumingren
dfcc9b3e72 chore(scripts): 新增库存差异核对报表脚本并忽略导出文件
scripts/stock_diff_report.js 只读查询生产库,输出 库存差异核对_YYYYMMDD-HHmm.xlsx;
.gitignore 按 库存差异核对_*.xlsx 忽略带时间戳的导出文件。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-28 23:06:56 +08:00
liufumingren
3291699a63 fix(print): 自定义区模板地址切换到自有域名 qimen.wms.gztbyc.com
快手/拼多多自定义区模板与视频号 spa.html 由第三方(www.ye4s.com、ye4s.wms.gztbyc.com)
改为自有域名 https://qimen.wms.gztbyc.com/mb/,避免第三方站点不可用导致打印端取模板失败。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-28 23:06:52 +08:00
liufumingren
359b51eb37 fix(express): 寄件人国家默认值由空值改为 CN
菠萝派下单寄件人 country 传空会被平台判为无效地址,统一默认 CN。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-28 23:06:48 +08:00
liufumingren
226a2659d7 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 错误。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-28 23:06:43 +08:00
11 changed files with 709 additions and 85 deletions

2
.gitignore vendored
View File

@ -49,3 +49,5 @@ nginx-upstream-local.conf
# frpc binary (installed on demand by script/frp/frp-install.ps1)
script/frp/*.exe
# 库存差异核对导出(scripts/stock_diff_report.js 生成,文件名带时间戳)
库存差异核对_*.xlsx

View File

@ -893,7 +893,7 @@ class ExpressPlatformService extends MainService {
name: listByWarehousePlatformCode.sender_name || '',
phone: order.sys_platform_code === 'XHS' ? undefined : listByWarehousePlatformCode.sender_tel || '',
mobile: order.sys_platform_code === 'XHS' ? listByWarehousePlatformCode.sender_tel : undefined,
country: '',
country: 'CN',
city: listByWarehousePlatformCode.city_name || '',
province: listByWarehousePlatformCode.province_name || '',
area: listByWarehousePlatformCode.district_name || '',

View File

@ -389,7 +389,7 @@ class StockCheckService extends Service {
byStock.set(stockId, agg);
}
// 库位行账面:wms_storage 按 (space_id, stock_id) SUM(可用+锁定),并附到按商品聚合
// 库位行账面: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');
@ -416,7 +416,7 @@ class StockCheckService extends Service {
attributes: [
'space_id',
'stock_id',
[ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ],
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
group: [ 'space_id', 'stock_id' ],
raw: true,
@ -453,7 +453,7 @@ class StockCheckService extends Service {
where: { space_id: { [Op.in]: emptyLocationIds } },
attributes: [
'space_id',
[ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ],
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
group: [ 'space_id' ],
raw: true,
@ -1348,7 +1348,7 @@ class StockCheckService extends Service {
const existingStockIds = new Set(existingRows.map(item => Number(item.stock_id)));
// 商品在本仓库的启用库存库位(按库位拆分明细行:商品任务必须按库位盘点,
// 一个商品多个库位对应多行,各行账面 = 该库位库存 SUM(可用+锁定);无库存库位商品不可盘点;
// 一个商品多个库位对应多行,各行账面 = 该库位库存 SUM(可用数量);无库存库位商品不可盘点;
// 库位有效性:仅统计有效库位(所属 zone 存在且未删除),无头库位(zone 不存在/已删除)不纳入盘点)
const storageRows = await ctx.model.Storage.findAll({
where: {
@ -1362,7 +1362,7 @@ class StockCheckService extends Service {
attributes: [
'stock_id',
'space_id',
[ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ],
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
group: [ 'stock_id', 'space_id' ],
raw: true,
@ -2155,7 +2155,7 @@ class StockCheckService extends Service {
* (未盘库位为 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 为行内合计、
* 账面数量查 wms_storage SUM(available_quantity)(=可用数量,不含锁定待出库),行级 checked_quantity 为行内合计、
* diff_quantity 为行内各商品差异代数和;
* 未知商品单独输出行级 unknown_items [{ barcode, item_name, checked_quantity }]
* (无账面,差异 = 实盘 - 0 = 盘盈,已计入行级 checked_quantity/diff_quantity/is_diff)。
@ -2310,7 +2310,7 @@ class StockCheckService extends Service {
goodsGroups.get(stockId).push(detailRow);
}
// 库位行需要:记录商品快照(wms_stock_warehouse)与库位账面(wms_storage 可用+锁定)
// 库位行需要:记录商品快照(wms_stock_warehouse)与库位账面(wms_storage 可用数量)
const stockIds = new Set();
for (const detailRow of locationRows) {
const detailRecords = recordsByDetail.get(Number(detailRow.id)) || [];
@ -2330,7 +2330,7 @@ class StockCheckService extends Service {
stockMap = new Map(stockRows.map(item => [ Number(item.id), item ]));
}
// 库位行账面:wms_storage 按 (space_id, stock_id) SUM(可用+锁定)
// 库位行账面:wms_storage 按 (space_id, stock_id) SUM(可用数量)
const storageQuantityMap = new Map();
if (locationRows.length > 0 && stockIds.size > 0) {
const locationIds = [ ...new Set(locationRows
@ -2345,7 +2345,7 @@ class StockCheckService extends Service {
attributes: [
'space_id',
'stock_id',
[ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ],
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
group: [ 'space_id', 'stock_id' ],
raw: true,
@ -2647,7 +2647,7 @@ class StockCheckService extends Service {
if (isEmptyLocation && locationId > 0) {
const emptyStorageRows = await ctx.model.Storage.findAll({
where: { space_id: locationId },
attributes: [[ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ]],
attributes: [[ literal('SUM(available_quantity)'), 'totalQuantity' ]],
raw: true,
});
locationSystemTotal = Number(emptyStorageRows[0] && emptyStorageRows[0].totalQuantity) || 0;
@ -2822,6 +2822,9 @@ class StockCheckService extends Service {
* **space_id 必传**(wms_location_space.id,须属于本仓库且分区有效),库位以该 ID 为准,
* location 编码入参仅做一致性校验(不一致报 400),服务端不再按编码猜库位;
* 主表 approved 自动转 checking;重算 checked_items / diff_items / detail_status。
* 静态盘点(is_static=1)商品范围任务额外要求「该商品已完全拣货」:仓库内该商品
* wms_storage SUM(locked_quantity) > 0(存在已分配储位、尚未拣出的在途出库)时拒绝上报,
* 返回 400「商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货」。
* 数据库层由唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全。
*
* 未知商品上报口径(stock_id 与 barcode 至少传一项):
@ -3148,6 +3151,15 @@ class StockCheckService extends Service {
}
}
// 静态盘点要求「该商品已完全拣货」:商品仍有锁定量说明存在已分配储位但尚未拣出的在途出库,
// 此时上报的实盘数与账面快照之间会夹着这批货,差异不可信,直接拒绝上报
if (Number(check.is_static) === 1 && scopeType === 'goods' && normalizedStockId > 0) {
const stockLockedMap = await this._fetchStockLockedQuantityMap(warehouseId, [ normalizedStockId ]);
if ((stockLockedMap.get(normalizedStockId) || 0) > 0) {
throw this.createBusinessError('商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货');
}
}
const now = new Date();
// 覆盖式上报:已知商品按同明细 + 同商品 + 同库位编码(库位编码来自 space_id 对应库位)更新已有记录,
@ -3495,8 +3507,11 @@ class StockCheckService extends Service {
* location 行含 detail_id/location_id/location_code/location_name/status/has_unknown/
* checked_at/checkers/goods(已知商品与未知商品记录均入 goods,未知商品 stock_id=null);
* goods 行含 stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/locations
* (明盘另含 system_quantity(账面快照合计)/checked_quantity/diff_quantity/is_diff);
* space 行含 id/space_code/custom_barcode/custom_name/goods。
* (明盘另含 system_quantity(账面快照合计)/checked_quantity/diff_quantity/is_diff;
* 静态盘点另含 picking_completed(1=该商品已完成拣货/0=未完成,判定口径=仓库内该商品锁定量为 0)
* 与明盘下的 locked_quantity(该商品仓库内锁定量合计));
* space 行含 id/space_code/custom_barcode/custom_name/goods(goods 子项在静态盘点时
* 另含 picking_completed,口径与 goods 视图行一致)。
* @throws {Error} 任务不存在或任务状态非 approved/checking 时抛出业务错误(错误码 400)。
*/
async workData(params = {}) {
@ -3613,7 +3628,9 @@ class StockCheckService extends Service {
* 拉取盘点作业数据(space 视图分页版)。
* 行结构与 workData space 视图行一致(id=库位ID/location_id 同义库位ID/space_code/custom_barcode/custom_name/goods),
* 商品任务(scope_type=goods)按库位聚合;传入 location_id 时只返回该库位行(total=1),
* 不传时按分页返回全部库位行。
* 不传时按分页返回全部库位行。静态盘点(is_static=1)时 goods 子项含 picking_completed
* (1=该商品已完成拣货/0=未完成,口径=仓库内该商品 wms_storage SUM(locked_quantity) 是否为 0,
* 按商品维度判定,明盘盲盘均返回)。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
@ -3681,9 +3698,11 @@ class StockCheckService extends Service {
* summary 为商品级汇总(明盘含 system_quantity 账面快照合计/checked_quantity 实盘合计/
* diff_quantity/is_diff;盲盘不含数量字段);
* rows 为该商品每个库位一行(detail_id 该库位明细ID/location_id 与同义 space_id 库位ID/
* location_code 库位编码,明盘另含 system_quantity 该库位当前账面(可用+锁定)/
* location_code 库位编码,明盘另含 system_quantity 该库位当前账面(可用数量)/
* snapshot_quantity 该库位账面快照/locked_quantity 锁定数量/checked_quantity 该库位实盘/
* diff_quantity 该库位差异(实盘-快照),另有 checked_at/checker_name/record_ids/images)。
* diff_quantity 该库位差异(实盘-快照),另有 checked_at/checker_name/record_ids/images);
* 静态盘点另在顶层返回 picking_completed(1=该商品已完成拣货/0=未完成,判定口径=仓库内该商品
* wms_storage SUM(locked_quantity) 是否为 0)与明盘下的 locked_quantity(仓库内锁定量合计)。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
@ -3823,6 +3842,13 @@ class StockCheckService extends Service {
book_source: goodsRow.book_source === 'snapshot' ? 'snapshot' : 'storage',
rows,
};
// 静态盘点:该商品是否已完成拣货(1=已完成/0=未完成);盲盘不输出锁定量数值
if (Number(goodsRow.is_static) === 1) {
detail.picking_completed = Number(goodsRow.picking_completed) === 1 ? 1 : 0;
if (isOpen) {
detail.locked_quantity = Number(goodsRow.locked_quantity) || 0;
}
}
if (isOpen) {
detail.summary = {
system_quantity: Number(goodsRow.system_quantity) || 0,
@ -3997,13 +4023,16 @@ class StockCheckService extends Service {
* stock_id 为空/异常的明细行无法按商品归并,各自成行。
* locations 为商品所在全部库位(wms_storage 中该商品的 space_id 集合,按拣货路径排序):
* 明盘(mode=open)每库位含 system_quantity(该库位账面数量,wms_storage space+stock
* SUM(available_quantity+locked_quantity),无库存记录库位为 0)、locked_quantity(该库位锁定数量,
* SUM(available_quantity),无库存记录库位为 0)、locked_quantity(该库位锁定数量,
* wms_storage space+stock SUM(locked_quantity))与 quantity(该库位盘点数量=实盘合计,未盘库位为 0),三者区分开;
* 盲盘(mode=blind)只显示库位(location_code)不含任何数量字段;已盘库位额外含
* checked_at/checker_name/record_ids/images,未盘库位这些字段为 null/空数组;
* 商品库存已无记录但已盘的库位(仅记录库位)追加在末尾。
* 明盘行级返回 system_quantity(账面快照合计=该商品各库位明细行快照之和)/
* checked_quantity(已盘合计)/diff_quantity/is_diff;
* 静态盘点(is_static=1)另返回 picking_completed(1=该商品已完成拣货/0=未完成,
* 口径=仓库内该商品 wms_storage SUM(locked_quantity) 是否为 0)与明盘下的 locked_quantity
* (该商品仓库内锁定量合计;盲盘不输出该数值);
* 商品基础信息批量取自 stockWarehouse.getStockDetails(未命中回退明细商品快照),
* 货主名经 _resolveStoreNameMap 解析。
*
@ -4011,7 +4040,7 @@ class StockCheckService extends Service {
* @param {number} checkId 盘点任务ID。
* @param {string} mode 盘点方式:open=明盘/blind=盲盘。
* @param {boolean} [isStatic=false] 是否静态盘点(is_static=1):true=账面取明细快照,
* false=账面取当前 wms_storage(可用+锁定)。
* false=账面取当前 wms_storage(可用数量)。
* @return {Promise<Array<Object>>} 商品视图行列表(按商品首个明细 id 升序)。
*/
async _buildGoodsWorkRows(warehouseId, checkId, mode, isStatic = false) {
@ -4039,6 +4068,13 @@ class StockCheckService extends Service {
const stockIds = [ ...new Set(detailRows
.map(row => Number(row.stock_id))
.filter(stockId => Number.isInteger(stockId) && stockId > 0)) ];
// 静态盘点:拣货完成判定——商品在仓库内仍存在锁定量(wms_storage SUM(locked_quantity) > 0)
// 即说明有已分配储位但未拣出的在途出库,拣货未完成(report 对未完成拣货的商品拒绝上报)
const stockLockedQuantityMap = isStatic
? await this._fetchStockLockedQuantityMap(warehouseId, stockIds)
: new Map();
let stockDetailMap = new Map();
if (stockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, {
@ -4052,7 +4088,7 @@ class StockCheckService extends Service {
const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId);
// 商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id
// 同时按 stock+space 汇总账面数量(该库位系统库存,口径=可用+锁定)与锁定数量,
// 同时按 stock+space 汇总账面数量(该库位系统库存,口径=可用数量)与锁定数量,
// 供明盘 locations.system_quantity / locked_quantity 使用
const stockSpaceIdsMap = new Map();
const stockSpaceQuantityMap = new Map();
@ -4069,7 +4105,7 @@ class StockCheckService extends Service {
attributes: [
'stock_id',
'space_id',
[ literal('SUM(available_quantity + locked_quantity)'), 'system_quantity' ],
[ literal('SUM(available_quantity)'), 'system_quantity' ],
[ fn('SUM', col('locked_quantity')), 'locked_quantity' ],
],
group: [ 'stock_id', 'space_id' ],
@ -4236,6 +4272,15 @@ class StockCheckService extends Service {
book_source: isStatic ? 'snapshot' : 'storage',
locations: [],
};
// 静态盘点:该商品是否已完成拣货(1=已完成/0=未完成,判定口径=仓库内该商品锁定量是否为 0);
// 盲盘不输出锁定量数值(与盲盘不含数量字段口径一致),仅输出完成标记
if (isStatic) {
const lockedQuantity = stockLockedQuantityMap.get(stockId) || 0;
row.picking_completed = lockedQuantity > 0 ? 0 : 1;
if (isOpen) {
row.locked_quantity = lockedQuantity;
}
}
if (isOpen) {
row.system_quantity = 0;
row.checked_quantity = 0;
@ -4303,7 +4348,7 @@ class StockCheckService extends Service {
};
if (isOpen) {
// 明盘:逐库位账面按任务是否静态取值——静态盘点取该库位明细快照(盘点基准冻结),
// 非静态取当前 wms_storage 账面(可用+锁定);两者同时输出便于对照,
// 非静态取当前 wms_storage 账面(可用数量);两者同时输出便于对照,
// system_quantity 始终为「本次参与差异计算的账面」
const spaceQuantity = (spaceQuantityByStockMap.get(stockId) || new Map()).get(code || '') || {};
const storageQuantity = Number(spaceQuantity.system_quantity) || 0;
@ -4356,8 +4401,10 @@ class StockCheckService extends Service {
* 库位仅按拣货顺序排序:pick_sequence 升序(pick_priority/库位 id 不参与排序,
* 同值保持库位查询顺序);
* 行内 goods 为该库位下的任务商品:明盘含 system_quantity(wms_storage space+stock
* SUM(available_quantity+locked_quantity))、locked_quantity(wms_storage space+stock SUM(locked_quantity))
* SUM(available_quantity))、locked_quantity(wms_storage space+stock SUM(locked_quantity))
* 与 checked_quantity(该商品在该库位的实盘合计),盲盘不返回任何数量字段;
* 静态盘点(is_static=1)goods 子项另含 picking_completed(1=该商品已完成拣货/0=未完成,
* 口径=仓库内该商品 wms_storage SUM(locked_quantity) 是否为 0,按商品维度判定,明盘盲盘均返回);
* status 已盘口径:该 (库位, 商品) 存在作业记录(兼容按明细 + 库位编码命中);
* 未在 wms_storage 有库位的商品不入列表(无库位可聚)。
*
@ -4365,7 +4412,7 @@ class StockCheckService extends Service {
* @param {number} checkId 盘点任务ID。
* @param {string} mode 盘点方式:open=明盘/blind=盲盘。
* @param {boolean} [isStatic=false] 是否静态盘点(is_static=1):true=账面取明细快照,
* false=账面取当前 wms_storage(可用+锁定)。
* false=账面取当前 wms_storage(可用数量)。
* @return {Promise<Array<Object>>} 聚合库位视图行列表(按拣货路径排序)。
*/
async _buildSpaceWorkRows(warehouseId, checkId, mode, isStatic = false) {
@ -4386,6 +4433,13 @@ class StockCheckService extends Service {
const isOpen = mode !== 'blind';
// 静态盘点:拣货完成判定——商品在仓库内仍存在锁定量(wms_storage SUM(locked_quantity) > 0)
// 即说明有已分配储位但未拣出的在途出库,拣货未完成;判定按商品维度(非库位维度),
// 同一商品在各库位行上的 picking_completed 取值一致
const stockLockedQuantityMap = isStatic
? await this._fetchStockLockedQuantityMap(warehouseId, stockIds)
: new Map();
const records = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkId, warehouse_id: Number(warehouseId) },
order: [[ 'id', 'ASC' ]],
@ -4412,7 +4466,7 @@ class StockCheckService extends Service {
);
// 任务商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id,
// 同时按 (space_id, stock_id) 汇总账面数量(口径=可用+锁定)与锁定数量
// 同时按 (space_id, stock_id) 汇总账面数量(口径=可用数量)与锁定数量
const storageRows = await ctx.model.Storage.findAll({
where: {
warehouse_id: Number(warehouseId),
@ -4424,7 +4478,7 @@ class StockCheckService extends Service {
attributes: [
'space_id',
'stock_id',
[ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ],
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
[ fn('SUM', col('locked_quantity')), 'totalLockedQuantity' ],
],
group: [ 'space_id', 'stock_id' ],
@ -4712,6 +4766,11 @@ class StockCheckService extends Service {
0
);
}
// 静态盘点:该商品是否已完成拣货(1=已完成/0=未完成,按商品维度判定——
// 仓库内该商品锁定量为 0 才算完成;盲盘同样输出,便于上报前拦截提示)
if (isStatic) {
item.picking_completed = (stockLockedQuantityMap.get(stockId) || 0) > 0 ? 0 : 1;
}
item.status = locationRecords.length > 0 ? 'checked' : 'unchecked';
return item;
})
@ -5166,10 +5225,51 @@ class StockCheckService extends Service {
};
}
/**
* 查询商品在仓库内的锁定量合计(wms_storage SUM(locked_quantity)),用于判定是否已完成拣货。
* 分配储位(拣货锁库)只把 available_quantity 搬成 locked_quantity;拣货完成时
* quantity 与 locked_quantity 同时扣减、available_quantity 不变。因此
* locked_quantity > 0 即表示该商品仍有「已分配储位、尚未拣出」的在途出库,拣货未完成;
* locked_quantity = 0 即该商品已完全拣货。
*
* @param {number} warehouseId 仓库ID。
* @param {Array<number>|number} stockIds 商品库存ID(wms_stock_warehouse.id),单值自动转数组。
* @return {Promise<Map<number, number>>} stock_id → 锁定量合计(无库存记录的商品不在 Map 中)。
*/
async _fetchStockLockedQuantityMap(warehouseId, stockIds) {
const { ctx } = this;
const { Op, literal } = ctx.app.Sequelize;
const numericStockIds = [ ...new Set((Array.isArray(stockIds) ? stockIds : [ stockIds ])
.map(stockId => Number(stockId))
.filter(stockId => Number.isInteger(stockId) && stockId > 0)) ];
if (numericStockIds.length === 0) {
return new Map();
}
const rows = await ctx.model.Storage.findAll({
where: {
warehouse_id: Number(warehouseId),
stock_id: { [Op.in]: numericStockIds },
is_enabled: 1,
},
attributes: [
'stock_id',
[ literal('SUM(locked_quantity)'), 'lockedQuantity' ],
],
group: [ 'stock_id' ],
raw: true,
});
return new Map(rows.map(row => [ Number(row.stock_id), Number(row.lockedQuantity) || 0 ]));
}
/**
* 刷新商品范围明细行的账面快照(盘点基准)。
* 商品范围(scope_type=goods)任务把各明细行 system_quantity 刷新为该库位当时的账面
* SUM(available_quantity+locked_quantity)(库存记录不存在时按 0):
* 商品范围(scope_type=goods)任务把各明细行 system_quantity 刷新为该库位当时的可用数量
* SUM(available_quantity)(= 库存总量 − 锁定数量 − 拦截锁定数量;库存记录不存在时按 0):
* 账面只统计可用数量,不把 locked_quantity(已分配储位、待拣出库)计入:
* 分配储位只搬 available→locked(账面不变),拣货完成同时扣 quantity 与 locked、
* available 不变,因此「可用数量」口径在静态盘点窗口内对拣货动作不敏感。
* - 提交审核时调用(保证 result/差异对比使用提交时点的账面);
* - 审核通过时再次调用(盘点基准以「审核完成=开始盘点」时刻为准,覆盖提交后到达的出入库);
* 库位范围(scope_type=location)账面实时查 wms_storage,不处理。
@ -5195,7 +5295,7 @@ class StockCheckService extends Service {
.map(row => Number(row.stock_id))
.filter(stockId => Number.isInteger(stockId) && stockId > 0)) ];
// 按 (stock_id, space_id) 聚合当前账面:SUM(可用+锁定)
// 按 (stock_id, space_id) 聚合当前账面:SUM(可用数量)
const storageQuantityMap = new Map();
if (stockIds.length > 0) {
const storageRows = await ctx.model.Storage.findAll({
@ -5207,7 +5307,7 @@ class StockCheckService extends Service {
attributes: [
'stock_id',
'space_id',
[ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ],
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
group: [ 'stock_id', 'space_id' ],
raw: true,

View File

@ -1,4 +1,69 @@
[
{
"version": "0.3.321",
"date": "2026-10-28",
"type": "updated",
"summary": "space 视图补齐静态盘点拣货完成标记:stock.check.workData(space 视图)与 stock.check.workDataSpaceDetails 的 goods 子项在 is_static=1 时新增 picking_completed(是否已完成拣货),口径与 goods 视图一致",
"methods": [
"stock.check.workData",
"stock.check.workDataSpaceDetails"
],
"notes": [
"背景:0.3.320 已在 goods 视图行与商品钻取输出 picking_completed,但盘点作业前端默认使用 space 视图(workData 不传 is_goods)与 workDataSpaceDetails(库位分页),这两条链路拿不到拣货完成状态,无法在上报前提示/置灰。",
"现口径:_buildSpaceWorkRows 在 is_static=1 时按商品维度查询仓库内 SUM(locked_quantity)(_fetchStockLockedQuantityMap),goods 子项输出 picking_completed(1=已完成拣货/0=未完成);同一商品在各库位行上的取值一致(商品维度,非库位维度)。盲盘(mode=blind)同样返回该标记,但仍不返回任何数量字段(locked_quantity 仍只在明盘输出)。",
"workDataSpaceDetails 复用同一 space 视图构建函数,因此自动获得该字段,无需额外参数;与 stock.check.report 的静态盘点上报拦截配套(商品未完成拣货返回 400「商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货」)。",
"兼容性:非静态任务(is_static=0)不返回 picking_completed,行为与之前一致;未新增必填入参;原有 system_quantity/storage_quantity/locked_quantity/snapshot_quantity/checked_quantity 字段口径与取值均未变化。",
"测试:test/app/service/systems/stock_check.test.js 的「静态盘点拣货完成标记」用例补充 space 视图(workData 默认视图)与 workDataSpaceDetails(按 location_id 取库位行)的 picking_completed 断言,锁定量存在时为 0、清零后为 1。真实库全量 256 用例通过、ESLint 0 错误。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 2 条 method(stock.check.workData:description/response.rows 的 space 视图 goods 字段说明 + notes;stock.check.workDataSpaceDetails:description + 新增 notes);根版本 0.3.320 → 0.3.321、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位)。",
"代码依据:app/service/systems/stock_check.js#_buildSpaceWorkRows/#workDataSpaceDetails/#_fetchStockLockedQuantityMap。"
]
},
{
"version": "0.3.320",
"date": "2026-10-28",
"type": "updated",
"summary": "静态盘点拣货完成口径:stock.check.workData(goods 视图)与 stock.check.workDataDetail(商品钻取)新增 picking_completed(是否已完成拣货,判定=该商品在仓库内 wms_storage SUM(locked_quantity) 是否为 0)与明盘 locked_quantity;stock.check.report 对静态盘点且仍未完成拣货的商品拒绝上报",
"methods": [
"stock.check.workData",
"stock.check.workDataDetail",
"stock.check.report"
],
"notes": [
"背景:静态盘点审核通过即冻结账面基准,但盘点期间仍允许把「已分配储位、尚未拣出」的存量锁定货拣走(静态锁定只拦截新的储位分配,不拦截已有锁定)。若实盘发生在该批货拣完之前,实盘数与其后扣减的库位库存会相互矛盾,差异不可信(生产 PD20261027000001 商品 160240:快照后仍有 129 件在拣,最终产生 -115 的假盘亏)。",
"现口径:静态盘点(is_static=1)要求「该商品已完成拣货」——判定依据为 wms_storage 中该商品在仓库内 SUM(locked_quantity) 是否为 0。分配储位只把 available_quantity 搬成 locked_quantity(quantity 不变),拣货完成时 quantity 与 locked_quantity 同时扣减、available_quantity 不变,因此 locked_quantity>0 即表示仍有在途待拣出库。",
"新增字段:stock.check.workData goods 视图行在 is_static=1 时返回 picking_completed(1=已完成/0=未完成)与明盘 locked_quantity(该商品仓库内锁定量合计,盲盘不输出数值只输出完成标记);stock.check.workDataDetail 商品钻取在 is_static=1 时顶层返回同名两字段,口径一致。",
"上报拦截:stock.check.report 在任务 is_static=1 且为商品范围明细(scope_type=goods)时,写记录前校验该商品锁定量,>0 直接 400「商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货」。库位范围任务 is_static 恒为 0,不受影响;未知商品(stock_id 为空)无锁定量,不受影响。",
"兼容性:非静态任务(is_static=0)不返回 picking_completed,行为与之前一致;未新增必填入参,前端可忽略新字段。锁定量判定按仓库维度(不限任务库位范围),与静态锁定商品(stock 维度)口径一致。",
"测试:test/app/service/systems/stock_check.test.js 新增「静态盘点拣货完成标记」用例——人为把 available 搬成 locked 后断言 goods 视图/钻取 picking_completed=0 且 locked_quantity 正确、report 被拒;锁定量清零后 picking_completed=1 且上报成功。原「账面取值按任务静态标记」用例改为仅取无锁定量商品并在 finally 完成盘点释放静态锁定。真实库全量 256 用例通过、ESLint 0 错误。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 3 条 method(stock.check.workData:response.rows 商品视图字段补 picking_completed/locked_quantity + notes;stock.check.workDataDetail:description + notes;stock.check.report:description、errors 400 文案 + notes);根版本 0.3.319 → 0.3.320、updatedAt 2026-10-28;methods/changes/system.json 新增本条(插入数组首位)。",
"代码依据:app/service/systems/stock_check.js#_fetchStockLockedQuantityMap/#_buildGoodsWorkRows/#_formatGoodsWorkDetail/#report。"
]
},
{
"version": "0.3.319",
"date": "2026-10-28",
"type": "updated",
"summary": "盘点账面口径统一改为可用数量(wms_storage SUM(available_quantity)),不再把 locked_quantity(已分配储位、待拣出库的锁定量)计入账面;商品明细快照、动态实时账面、库位盘点、明盘工作台/钻取全部统一",
"methods": [
"stock.check.addDetail",
"stock.check.result",
"stock.check.report",
"stock.check.finish",
"stock.check.submit",
"stock.check.audit",
"stock.check.workData",
"stock.check.workDataDetail"
],
"notes": [
"背景:原账面口径为 SUM(available_quantity + locked_quantity)(=可用+锁定),会把已分配储位但尚未拣出的锁定量算进账面。静态盘点若在仍有在途拣货时开盘,快照会包含这批货,拣货完成后即变成假盘亏(生产 PD20261027000001:商品 160240 账面 248 vs 实盘 133,差异 -115,其中 129 件是快照后 19:02-20:51 才从库位拣出的)。",
"现口径:全部盘点账面统一取 wms_storage SUM(available_quantity)(= quantity - locked_quantity - intercept_locked_quantity)。涉及:addDetail 拆行快照、submit/audit 刷新快照、result 库位行与空库位标记、_recalcCheckSummary/report/finish 差异汇总、workData/workDataDetail 明盘实时账面。",
"语义依据:分配储位只把 available 搬成 locked(quantity 不变、账面不变);拣货完成同时扣 quantity 与 locked、available 不变。因此可用数量口径在盘点窗口内对拣货动作不敏感,锁定货拣完前后都成立。",
"兼容性:locked_quantity 字段继续单独输出(明细 locations.locked_quantity / space 视图 goods.locked_quantity),仅不再计入 system_quantity;前端如需「含锁定总量」请用 system_quantity + locked_quantity 或直接查 storage.quantity。",
"历史任务:已完成任务 system_quantity 为旧口径快照,本次不回刷;如需对齐新口径需驳回重新提交或重新审核触发快照刷新。",
"测试:test/app/service/systems/stock_check.test.js 账面 helper/断言同步改为 SUM(available_quantity),真实库全量 255 用例通过,ESLint 0 错误。",
"代码依据:app/service/systems/stock_check.js#_addGoodsDetailRows/#_refreshGoodsBookSnapshot/#_recalcCheckSummary/#result/#_formatDetailAggregationRow/#_buildGoodsWorkRows/#_buildSpaceWorkRows。"
]
},
{
"version": "0.3.318",
"date": "2026-10-28",

File diff suppressed because one or more lines are too long

View File

@ -52,7 +52,7 @@
"customData": {
"productInfo": "#0 B1340814-1-1 化妆品 商品总数 【2】\nE2区02-04-02 6973348850399;6974864094892 【2】 0\n\n验视员:"
},
"templateURL": "http://www.ye4s.com/mb/kuaishou.xml"
"templateURL": "https://qimen.wms.gztbyc.com/mb/kuaishou.xml"
}
]
}

View File

@ -43,7 +43,7 @@
},
"width": 560
},
"templateURL": "http://www.ye4s.com/mb/pdd.xml"
"templateURL": "https://qimen.wms.gztbyc.com/mb/pdd.xml"
}
],
"documentID": "777408273892067"

View File

@ -13,7 +13,7 @@
"splitControl": 1,
"showDeliveryLogo": 0,
"customInfo": {
"templateUrl": "https://ye4s.wms.gztbyc.com/spa.html",
"templateUrl": "https://qimen.wms.gztbyc.com/mb/spa.html",
"data": {
"description": "#0 B1340938-1-1 良田-轻货 商品总数 【4】<br>Y区04-02-02 6957815275250 【2】 0<br>临时库位 清洁剂纸箱2瓶装 【1】 0<br>临时库位 评价有礼 【1】 0<br> "
}

View File

@ -53,7 +53,7 @@ function log(title, payload) {
is_enabled: 1,
space_id: { [Op.in]: literal(validSpaceSql) },
},
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity + locked_quantity)'), 'qty' ]],
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity)'), 'qty' ]],
group: [ 'stock_id', 'space_id' ],
raw: true,
});

View File

@ -0,0 +1,306 @@
'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);
});

View File

@ -223,9 +223,12 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
* 拉取固定测试仓库下的真实库存行(用于生成盘点明细快照)。
*
* @param {number} count 行数。
* @param {Object} [options] 过滤选项。
* @param {boolean} [options.requireUnlocked=false] 仅取无锁定量商品
* (wms_storage SUM(locked_quantity)=0,静态盘点上报要求商品已完成拣货)。
* @return {Promise<Array<Object>>} 库存行。
*/
async function fetchStockRows(count = 2) {
async function fetchStockRows(count = 2, options = {}) {
// 取「仅在单个启用库位有库存」的商品:商品明细按「商品 + 库位」拆行后每商品 1 行,
// 保证 total_items 与商品数一致(多库位商品拆多行、无库存库位商品不可加入盘点)
const { Op, fn, col, literal } = ctx.app.Sequelize;
@ -235,12 +238,17 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
is_enabled: 1,
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
},
attributes: [ 'stock_id', [ fn('COUNT', fn('DISTINCT', col('space_id'))), 'spaceCount' ]],
attributes: [
'stock_id',
[ fn('COUNT', fn('DISTINCT', col('space_id'))), 'spaceCount' ],
[ literal('SUM(locked_quantity)'), 'lockedQuantity' ],
],
group: [ 'stock_id' ],
raw: true,
});
const singleSpaceStockIds = storageRows
.filter(row => Number(row.spaceCount) === 1)
.filter(row => options.requireUnlocked !== true || (Number(row.lockedQuantity) || 0) === 0)
.map(row => Number(row.stock_id));
return ctx.model.StockWarehouse.findAll({
@ -287,7 +295,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
}
/**
* 查询库位商品账面数量(wms_storage 按 stock_id SUM(可用+锁定),与实现口径一致)。
* 查询库位商品账面数量(wms_storage 按 stock_id SUM(可用数量),与实现口径一致)。
*
* @param {number} spaceId 库位ID。
* @param {Array<number>} stockIds 商品库存ID列表。
@ -300,7 +308,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
space_id: Number(spaceId),
stock_id: { [Op.in]: stockIds.map(id => Number(id)) },
},
attributes: [ 'stock_id', [ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ]],
attributes: [ 'stock_id', [ literal('SUM(available_quantity)'), 'totalQuantity' ]],
group: [ 'stock_id' ],
raw: true,
});
@ -329,7 +337,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
/**
* 取固定测试仓库下「只存放在单一库位」的有效商品与库位对(保证库位-商品一一对应,
* 供 space 视图聚合/排序用例使用),并附库位编码/名称与账面数量(账面口径与实现一致:
* wms_storage 按 warehouse+space+stock+is_enabled=1 SUM(available_quantity+locked_quantity))
* wms_storage 按 warehouse+space+stock+is_enabled=1 SUM(available_quantity))
* 及锁定数量(SUM(locked_quantity))。
*
* @param {number} count 对数。
@ -396,7 +404,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
is_enabled: 1,
},
attributes: [
[ ctx.app.Sequelize.literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ],
[ ctx.app.Sequelize.literal('SUM(available_quantity)'), 'totalQuantity' ],
[ fn('SUM', col('locked_quantity')), 'totalLockedQuantity' ],
],
raw: true,
@ -1310,7 +1318,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
assert.equal(row.item_code, stock.item_code, 'item_code 快照不一致');
assert.equal(row.item_name, stock.item_name, 'item_name 快照不一致');
assert.equal(row.spec, stock.sku_property, 'spec 应快照 sku_property');
// 拆行口径:system_quantity = 该商品在其库存库位的账面(wms_storage SUM(可用+锁定))
// 拆行口径:system_quantity = 该商品在其库存库位的账面(wms_storage SUM(可用数量))
const storageRows = await ctx.model.Storage.findAll({
where: {
warehouse_id: TEST_WAREHOUSE_ID,
@ -1321,7 +1329,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
raw: true,
});
const expectedSystemQuantity = storageRows.reduce(
(sum, item) => sum + (Number(item.available_quantity) || 0) + (Number(item.locked_quantity) || 0),
(sum, item) => sum + (Number(item.available_quantity) || 0),
0
);
assert.equal(Number(row.system_quantity), expectedSystemQuantity, 'system_quantity 应为该库位账面');
@ -1380,7 +1388,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
is_enabled: 1,
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
},
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ]],
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity)'), 'totalQuantity' ]],
group: [ 'stock_id', 'space_id' ],
raw: true,
});
@ -2356,7 +2364,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
const stockId = Number(detail.stock_id);
const spaceId = Number(detail.location_id);
// 提交前账面(口径与实现一致:SUM 可用+锁定)
// 提交前账面(口径与实现一致:SUM 可用数量)
const bookRows = await ctx.model.Storage.findAll({
where: {
warehouse_id: TEST_WAREHOUSE_ID,
@ -2365,7 +2373,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
is_enabled: 1,
},
attributes: [
[ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ],
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
raw: true,
});
@ -4109,7 +4117,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
is_enabled: 1,
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
},
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ]],
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity)'), 'totalQuantity' ]],
group: [ 'stock_id', 'space_id' ],
raw: true,
});
@ -5340,7 +5348,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
is_enabled: 1,
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
},
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ]],
attributes: [ 'stock_id', 'space_id', [ literal('SUM(available_quantity)'), 'totalQuantity' ]],
group: [ 'stock_id', 'space_id' ],
raw: true,
});
@ -5479,7 +5487,8 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
});
it('账面取值按任务静态标记:静态任务取明细快照、非静态任务取当前 storage(goods/space/workDataDetail 一致)', async () => {
const stocks = await fetchStockRows(1);
// 静态任务上报要求商品已完成拣货(无锁定量),故只取无锁定商品
const stocks = await fetchStockRows(1, { requireUnlocked: true });
const targetStock = stocks[0];
const DELTA = 7;
@ -5511,7 +5520,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
{ replacements: { delta: DELTA, warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId } }
);
const liveRows = await ctx.model.query(
`SELECT COALESCE(SUM(available_quantity + locked_quantity), 0) AS total
`SELECT COALESCE(SUM(available_quantity), 0) AS total
FROM wms_storage
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId`,
{
@ -5538,10 +5547,12 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
}
const spaceIdList = [];
const checkIdList = [];
try {
// ── 静态任务:账面=快照(冻结),当前 storage 仅作为参考字段输出 ──
const staticPrepared = await prepareCheck(true);
spaceIdList.push(staticPrepared.spaceId);
checkIdList.push(staticPrepared.check.id);
assert.ok(staticPrepared.liveBook > staticPrepared.snapshot, '前置:人为变动后当前账面应大于快照');
const staticGoods = await workDataCheck(staticPrepared.check.id, { isGoods: true });
@ -5589,6 +5600,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
// ── 非静态任务:账面=当前 storage,快照仅作参考字段 ──
const normalPrepared = await prepareCheck(false);
spaceIdList.push(normalPrepared.spaceId);
checkIdList.push(normalPrepared.check.id);
const normalGoods = await workDataCheck(normalPrepared.check.id, { isGoods: true });
const normalRow = normalGoods.rows[0];
@ -5621,6 +5633,139 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
for (const spaceId of spaceIdList) {
await restoreBook(spaceId);
}
// 收尾:完成盘点释放静态锁定,避免留存的 checking 静态任务影响后续锁定相关用例
for (const checkId of checkIdList) {
const latestRow = await findCheckRow(checkId);
if (latestRow && [ 'approved', 'checking' ].includes(String(latestRow.status))) {
await ctx.service.systems.stockCheck.finish({ warehouseId: TEST_WAREHOUSE_ID, id: checkId });
}
}
}
});
it('静态盘点拣货完成标记:商品仍有锁定量时 picking_completed=0 且 report 拒绝上报', async () => {
const stocks = await fetchStockRows(1, { requireUnlocked: true });
const targetStock = stocks[0];
const LOCK_DELTA = 2;
// 前置:测试商品在测试仓库不应有锁定量(否则 picking_completed 初值即为 0,用例无法区分)
const lockedBefore = await ctx.model.query(
`SELECT COALESCE(SUM(locked_quantity), 0) AS total
FROM wms_storage
WHERE warehouse_id = :warehouseId AND stock_id = :stockId`,
{
replacements: { warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id },
type: ctx.model.QueryTypes.SELECT,
}
);
assert.equal(
Number(lockedBefore[0] && lockedBefore[0].total) || 0,
0,
'前置:测试商品在测试仓库不应有锁定量'
);
const check = await createCheck({
title: uniqueTitle('静态拣货完成'),
type: 'goods',
isStatic: 1,
});
await addDetail(check.id, [ targetStock.id ]);
await submitCheck(check.id);
await auditCheck(check.id, 'approve');
const details = await detailCheck(check.id);
const detailRow = details.rows[0];
const spaceId = Number(detailRow.location_id);
// 模拟分配储位:available → locked(quantity 不变),即该商品仍有在途待拣出库
const shiftLock = async delta => {
await ctx.model.query(
`UPDATE wms_storage
SET available_quantity = available_quantity - :delta,
locked_quantity = locked_quantity + :delta
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId`,
{ replacements: { delta, warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId } }
);
};
try {
await shiftLock(LOCK_DELTA);
// goods 视图:picking_completed=0,并输出该商品仓库内锁定量合计
const lockedGoods = await workDataCheck(check.id, { isGoods: true });
const lockedRow = lockedGoods.rows[0];
assert.equal(Number(lockedRow.is_static), 1);
assert.equal(Number(lockedRow.picking_completed), 0, '商品仍有锁定量时 picking_completed 应为 0');
assert.equal(Number(lockedRow.locked_quantity), LOCK_DELTA, '行级应输出该商品锁定量合计');
// workDataDetail 同口径
const lockedDrill = await workDataDetailCheck({ id: check.id, stockId: targetStock.id });
assert.equal(Number(lockedDrill.picking_completed), 0, '钻取 picking_completed 应为 0');
assert.equal(Number(lockedDrill.locked_quantity), LOCK_DELTA, '钻取应输出该商品锁定量合计');
// space 视图(workData 默认视图)goods 子项同口径
const lockedSpace = await workDataCheck(check.id);
const lockedSpaceItem = lockedSpace.rows
.flatMap(row => row.goods || [])
.find(item => Number(item.stock_id) === Number(targetStock.id));
assert.ok(lockedSpaceItem, 'space 视图应含该商品');
assert.equal(Number(lockedSpaceItem.picking_completed), 0, 'space 视图 picking_completed 应为 0');
// workDataSpaceDetails(space 视图分页版)同口径
const lockedSpaceDetails = await ctx.service.systems.stockCheck.workDataSpaceDetails({
warehouseId: TEST_WAREHOUSE_ID,
id: check.id,
locationId: spaceId,
});
const lockedSpaceDetailItem = (lockedSpaceDetails.rows[0] && lockedSpaceDetails.rows[0].goods || [])
.find(item => Number(item.stock_id) === Number(targetStock.id));
assert.ok(lockedSpaceDetailItem, 'workDataSpaceDetails 库位行应含该商品');
assert.equal(
Number(lockedSpaceDetailItem.picking_completed),
0,
'workDataSpaceDetails picking_completed 应为 0'
);
// 未完成拣货:report 拒绝上报
await assert.rejects(
async () => reportCheck(check.id, detailRow.id, 1, detailRow.location_code),
/商品尚未完成拣货,不满足静态盘点要求,请先等待该商品完全完成拣货/
);
// 拣货完成(锁定量清零)后 picking_completed=1,可正常上报
await shiftLock(-LOCK_DELTA);
const doneGoods = await workDataCheck(check.id, { isGoods: true });
assert.equal(Number(doneGoods.rows[0].picking_completed), 1, '无锁定量时 picking_completed 应为 1');
assert.equal(Number(doneGoods.rows[0].locked_quantity), 0, '无锁定量时行级锁定量应为 0');
const doneSpaceDetails = await ctx.service.systems.stockCheck.workDataSpaceDetails({
warehouseId: TEST_WAREHOUSE_ID,
id: check.id,
locationId: spaceId,
});
const doneSpaceDetailItem = (doneSpaceDetails.rows[0] && doneSpaceDetails.rows[0].goods || [])
.find(item => Number(item.stock_id) === Number(targetStock.id));
assert.equal(
Number(doneSpaceDetailItem && doneSpaceDetailItem.picking_completed),
1,
'拣货完成后 workDataSpaceDetails 的 picking_completed 应为 1'
);
const reported = await reportCheck(check.id, detailRow.id, 1, detailRow.location_code);
assert.equal(Number(reported.record.quantity), 1, '拣货完成后应允许上报');
} finally {
// 收尾:完成盘点释放静态锁定,避免留存的 checking 静态任务影响后续锁定相关用例
const latestRow = await findCheckRow(check.id);
if (latestRow && [ 'approved', 'checking' ].includes(String(latestRow.status))) {
await ctx.service.systems.stockCheck.finish({ warehouseId: TEST_WAREHOUSE_ID, id: check.id });
}
// 兜底回滚:无论用例是否中途失败,都把锁定量搬回可用数量
await ctx.model.query(
`UPDATE wms_storage
SET available_quantity = available_quantity + locked_quantity,
locked_quantity = 0
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId
AND locked_quantity > 0`,
{ replacements: { warehouseId: TEST_WAREHOUSE_ID, stockId: targetStock.id, spaceId } }
);
}
});
@ -5630,7 +5775,6 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
await addDetail(check.id, [ stocks[0].id ]);
await submitCheck(check.id);
await auditCheck(check.id, 'approve');
const details = await detailCheck(check.id);
await reportCheck(check.id, details.rows[0].id, 5, TEST_LOCATION_CODE);
await reportCheck(check.id, details.rows[0].id, 3, TEST_LOCATION_CODE_2);
@ -5744,7 +5888,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
const reportedGoods = reportedRow.goods[0];
assert.equal(Number(reportedGoods.detail_id), Number(reportedDetail.id));
assert.equal(Number(reportedGoods.stock_id), reported.stockId);
assert.equal(Number(reportedGoods.system_quantity), reported.book, '库位账面应为 wms_storage SUM(可用+锁定)');
assert.equal(Number(reportedGoods.system_quantity), reported.book, '库位账面应为 wms_storage SUM(可用数量)');
assert.equal(Number(reportedGoods.locked_quantity), reported.bookLocked, '库位锁定数量应为 wms_storage SUM(locked_quantity)');
assert.equal(Number(reportedGoods.checked_quantity), reportedQuantity, '已盘应为该库位实盘合计');
assert.equal(reportedGoods.status, 'checked');
@ -6012,7 +6156,7 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
assert.equal(row.custom_name, target.customName || null);
assert.equal(row.goods.length, 1, '该库位仅一个任务商品');
assert.equal(Number(row.goods[0].stock_id), target.stockId, 'goods 应挂载该库位的任务商品');
assert.equal(Number(row.goods[0].system_quantity), target.book, '明盘库位账面应为 wms_storage SUM(可用+锁定)');
assert.equal(Number(row.goods[0].system_quantity), target.book, '明盘库位账面应为 wms_storage SUM(可用数量)');
assert.equal(Number(row.goods[0].locked_quantity), target.bookLocked, '明盘库位锁定数量应为 wms_storage SUM(locked_quantity)');
assert.equal(Number(row.goods[0].checked_quantity), 0, '未盘库位已盘应为 0');
assert.equal(row.goods[0].status, 'unchecked');
@ -8979,13 +9123,13 @@ runner('test/app/service/systems/stock_check.test.js(库存盘点真实库集
const spaceId = Number(targetDetail.location_id);
/**
* 读取指定商品在指定库位的当前账面(可用+锁定)。
* 读取指定商品在指定库位的当前账面(可用数量)。
*
* @return {Promise<number>} 账面数量。
*/
async function readSpaceBook() {
const rows = await ctx.model.query(
`SELECT COALESCE(SUM(available_quantity + locked_quantity), 0) AS total
`SELECT COALESCE(SUM(available_quantity), 0) AS total
FROM wms_storage
WHERE warehouse_id = :warehouseId AND stock_id = :stockId AND space_id = :spaceId`,
{