WMS_MAIN/app/service/systems/stock_check.js
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

6378 lines
272 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';
const crypto = require('node:crypto');
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const ExcelJS = require('exceljs');
const Service = require('egg').Service;
/** 盘点范围类型枚举(wms_stock_check.type) */
const STOCK_CHECK_TYPES = Object.freeze([ 'store', 'goods', 'location' ]);
/** 盘点方式枚举(wms_stock_check.mode) */
const STOCK_CHECK_MODES = Object.freeze([ 'open', 'blind' ]);
/** 允许添加明细的主表状态 */
const ADD_DETAIL_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]);
/** 单次批量添加库位明细允许的最大库位ID数量 */
const STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS = 200;
/** 允许盘点作业上报/完成的主表状态 */
const REPORT_ALLOWED_STATUSES = Object.freeze([ 'approved', 'checking' ]);
/**
* 单次上报实盘数量上限(wms_stock_check_record.quantity 为 int(12) 有符号列,
* 实际可存上限 2147483647;超限直接落库会抛 Out of range 变成 500)。
*/
const REPORT_MAX_QUANTITY = 2147483647;
/** 允许提交审核的主表状态 */
const SUBMIT_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]);
/** 允许取消的主表状态 */
const CANCEL_ALLOWED_STATUSES = Object.freeze([ 'created', 'submitted', 'rejected' ]);
/**
* 静态盘点锁定中口径:is_static=1 且主表状态为「未结束」的任务(审核完成即开始锁定,
* 盘点作业中持续锁定;提交审核前、已完成/已取消/已驳回均不锁定)。
*/
const STATIC_LOCK_ALLOWED_STATUSES = Object.freeze([ 'approved', 'checking' ]);
/** 静态盘点锁定缓存键前缀(按仓库维度缓存 stock_id 集合) */
const STATIC_LOCK_CACHE_KEY_PREFIX = 'stock_check:static_lock:';
/** 静态盘点锁定代次键前缀(状态流转时递增,供回源前后一致性校验防脏读) */
const STATIC_LOCK_GENERATION_KEY_PREFIX = 'stock_check:static_lock_gen:';
/** 锁定代次进程内回退计数(Redis 不可用时使用) */
const STATIC_LOCK_GENERATION_LOCAL = new Map();
/** 静态盘点锁定缓存 TTL(秒):状态流转时主动重建,此处仅作兜底过期 */
const STATIC_LOCK_CACHE_TTL_SECONDS = 300;
/**
* 进程内 singleflight 表(键=缓存键,值=回源 Promise):
* 缓存未命中/失效瞬间的并发查询共用同一次数据库回源,避免瞬时击穿。
*/
const STATIC_LOCK_INFLIGHT = new Map();
/**
* 有效库位过滤 SQL(库位未删除且所属 zone 存在且未删除)。
* 无头库位(zone 不存在/已删除)不纳入盘点范围:明细生成、商品作业视图库位枚举均按此过滤。
*/
const VALID_SPACE_SQL = '(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)';
/** 盘点范围类型中文标签 */
const STOCK_CHECK_TYPE_LABELS = Object.freeze({
store: '按货主',
goods: '按商品',
location: '按库位',
});
/** 盘点方式中文标签 */
const STOCK_CHECK_MODE_LABELS = Object.freeze({
open: '明盘',
blind: '盲盘',
});
/** 主表状态中文标签 */
const STOCK_CHECK_STATUS_LABELS = Object.freeze({
created: '已创建',
submitted: '待审核',
rejected: '已驳回',
approved: '审核完成',
checking: '盘点作业中',
completed: '已完成',
cancelled: '已取消',
});
/** 明细盘点进度中文标签(主表 detail_status) */
const STOCK_CHECK_DETAIL_PROGRESS_LABELS = Object.freeze({
none_checked: '未盘',
partial_checked: '部分已盘',
all_checked: '全部已盘',
});
/**
* 库存盘点模块业务逻辑层。
* 负责 wms_stock_check(主表)/ wms_stock_check_detail(明细)的状态机流转与增删查,
* 以及导出 Excel 生成与 COS 上传等核心操作。
* 所有数据库交互集中在此层,供 systemMethods/stock/check.js 调用。
*/
class StockCheckService extends Service {
/**
* 创建带业务错误码的异常对象。
*
* @param {string} message 错误信息。
* @param {number} [code=400] 业务错误码。
* @return {Error} 包含 code 的异常对象。
*/
createBusinessError(message, code = 400) {
const error = new Error(`${message}`);
error.code = code;
return error;
}
/**
* 获取当前日期片段(YYYYMMDD)。
*
* @return {string} 当前日期片段。
*/
_getCurrentDatePart() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}${month}${day}`;
}
/**
* 生成盘点单号。
* 格式:PD + YYYYMMDD + 6位序号(如 PD20260929000001)。
* 序号全局递增(不按仓库隔离):uk_check_no 为全局唯一索引,按仓各自从 1 起会跨仓撞号;
* 并发创建时的撞号由 create 方法的唯一键重试兜底(参照收货单 receiving_number 口径)。
*
* @return {Promise<string>} 盘点单号。
*/
async generateCheckNo() {
const { ctx } = this;
const datePart = this._getCurrentDatePart();
const prefix = 'PD';
const pattern = `${prefix}${datePart}%`;
const rows = await ctx.model.query(
`
SELECT check_no
FROM wms_stock_check
WHERE check_no LIKE :pattern
ORDER BY check_no DESC
LIMIT 1
`,
{
replacements: { pattern },
type: ctx.model.QueryTypes.SELECT,
}
);
const latestNo = String(rows && rows[0] && rows[0].check_no || '').trim();
let sequence = 1;
if (latestNo) {
const match = latestNo.match(/(\d{6})$/);
const lastSequence = match ? Number(match[1]) : 0;
if (Number.isInteger(lastSequence) && lastSequence > 0) {
sequence = lastSequence + 1;
}
}
return `${prefix}${datePart}${String(sequence).padStart(6, '0')}`;
}
/**
* 判断创建盘点任务异常是否由单号唯一键冲突引起。
* 参照收货单 isReceivingNumberDuplicateError 口径:ER_DUP_ENTRY 且命中 check_no 唯一索引。
*
* @param {Error} error 创建异常。
* @return {boolean} 是单号重复错误返回 true。
*/
isCheckNoDuplicateError(error) {
const parentCode = error && error.parent && error.parent.code;
const sqlMessage = String((error && error.parent && error.parent.sqlMessage) || error.message || '');
return parentCode === 'ER_DUP_ENTRY' && /uk_check_no|check_no/i.test(sqlMessage);
}
/**
* 将主表行格式化为对外输出结构(补齐可空字段默认值)。
*
* @param {Object} row 主表原始行数据。
* @return {Object} 格式化后的主表行。
*/
_formatCheckRow(row = {}) {
return {
id: row.id,
check_no: row.check_no,
title: row.title || '',
type: row.type || 'location',
mode: row.mode || 'open',
store_id: row.store_id || null,
is_static: Number(row.is_static) === 1 ? 1 : 0,
status: row.status || 'created',
detail_status: row.detail_status || 'none_checked',
start_time: row.start_time || null,
end_time: row.end_time || null,
creator_id: row.creator_id || 0,
creator_name: row.creator_name || '',
total_items: row.total_items || 0,
checked_items: row.checked_items || 0,
diff_items: row.diff_items || 0,
remark: row.remark || '',
created_at: row.created_at || null,
updated_at: row.updated_at || null,
};
}
/**
* 将 ID 入参(单值或数组)归一化为去重后的正整数列表。
*
* @param {number|Array<number>} values 原始 ID 入参。
* @return {Array<number>} 去重后的正整数 ID 列表。
*/
_normalizeIdList(values) {
const list = Array.isArray(values) ? values : [ values ];
return [ ...new Set(list.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ];
}
/**
* 将库位编码入参(单值或数组)归一化为去重后的非空字符串列表(保持传入顺序)。
*
* @param {string|Array<string>} values 原始库位编码入参。
* @return {Array<string>} 去重后的非空库位编码列表。
*/
_normalizeCodeList(values) {
const list = Array.isArray(values) ? values : [ values ];
return [ ...new Set(
list
.map(value => (value === null || value === undefined ? '' : String(value)).trim())
.filter(Boolean)
) ];
}
/**
* 将日期值格式化为本地时间字符串(YYYY-MM-DD HH:mm:ss),供 Excel 导出使用。
*
* @param {*} value 日期值(Date 实例或可解析字符串/数字)。
* @return {string} 格式化后的本地时间字符串,非法值返回空字符串。
*/
_formatLocalDateTime(value) {
if (!value) {
return '';
}
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) {
return '';
}
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
/**
* 按仓库隔离维度查询盘点主表。
*
* @param {number} warehouseId 仓库ID。
* @param {number} id 主表ID。
* @return {Promise<Object|null>} 主表模型实例,不存在时返回 null。
*/
async _findCheck(warehouseId, id) {
return this.ctx.model.StockCheck.findOne({
where: { id: Number(id), warehouse_id: Number(warehouseId) },
});
}
/**
* 计算盘点任务范围口径的条数汇总(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)。
* 计数口径(与 _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。
*
* @param {number} checkId 盘点任务ID。
* @return {Promise<Object>} 重算后的汇总信息(含 finish 复用的按明细/按商品/未知商品聚合数据)。
*/
async _recalcCheckSummary(checkId) {
const { ctx } = this;
const { Op, literal } = ctx.app.Sequelize;
const checkIdNumber = Number(checkId);
const detailWhere = { check_id: checkIdNumber };
// 范围口径汇总:商品范围按商品(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({
where: detailWhere,
attributes: [ 'id', 'scope_type', 'stock_id', 'system_quantity', 'location_id' ],
raw: true,
});
const recordRows = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkIdNumber },
attributes: [ 'detail_id', 'stock_id', 'barcode', 'item_name', 'quantity', 'is_empty' ],
raw: true,
});
// 按明细聚合作业记录:明细总实盘 + 按商品分组实盘 + 未知商品按条码分组实盘
const checkedQuantityByDetail = new Map();
const stockQuantityByDetail = new Map();
const unknownQuantityByDetail = new Map();
const emptyDetailIds = new Set();
for (const record of recordRows) {
const detailId = Number(record.detail_id);
// 空库位标记:不参与商品/数量聚合(差异按该库位账面单独判断)
if (record.is_empty) {
emptyDetailIds.add(detailId);
continue;
}
const stockId = Number(record.stock_id);
const quantity = Number(record.quantity) || 0;
checkedQuantityByDetail.set(detailId, (checkedQuantityByDetail.get(detailId) || 0) + quantity);
if (!Number.isInteger(stockId) || stockId <= 0) {
// 未知商品(stock_id 为空):按条码维度归组(无账面,差异 = 实盘 = 盘盈)
const barcodeKey = String(record.barcode || '').trim() || 'unknown';
if (!unknownQuantityByDetail.has(detailId)) {
unknownQuantityByDetail.set(detailId, new Map());
}
const byBarcode = unknownQuantityByDetail.get(detailId);
const unknownAgg = byBarcode.get(barcodeKey) || {
barcode: String(record.barcode || '').trim() || null,
item_name: record.item_name || null,
checked: 0,
};
unknownAgg.checked += quantity;
byBarcode.set(barcodeKey, unknownAgg);
continue;
}
if (!stockQuantityByDetail.has(detailId)) {
stockQuantityByDetail.set(detailId, new Map());
}
const byStock = stockQuantityByDetail.get(detailId);
const agg = byStock.get(stockId) || { checked: 0 };
agg.checked += quantity;
byStock.set(stockId, agg);
}
// 库位行账面: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)
.map(row => Number(row.location_id))) ];
const stockIds = new Set();
for (const locationRow of locationDetailRows) {
const byStock = stockQuantityByDetail.get(Number(locationRow.id));
if (!byStock) {
continue;
}
for (const stockId of byStock.keys()) {
stockIds.add(stockId);
}
}
if (locationIds.length > 0 && stockIds.size > 0) {
const storageRows = await ctx.model.Storage.findAll({
where: {
space_id: { [Op.in]: locationIds },
stock_id: { [Op.in]: [ ...stockIds ] },
},
attributes: [
'space_id',
'stock_id',
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
group: [ 'space_id', 'stock_id' ],
raw: true,
});
for (const storageRow of storageRows) {
storageQuantityMap.set(
`${Number(storageRow.space_id)}_${Number(storageRow.stock_id)}`,
Number(storageRow.totalQuantity) || 0
);
}
}
// 账面附到按商品聚合(location_id 为空时账面按 0)
for (const locationRow of locationDetailRows) {
const byStock = stockQuantityByDetail.get(Number(locationRow.id));
if (!byStock) {
continue;
}
const locationId = locationRow.location_id ? Number(locationRow.location_id) : 0;
for (const [ stockId, agg ] of byStock) {
agg.system = locationId > 0 ? (storageQuantityMap.get(`${locationId}_${stockId}`) || 0) : 0;
}
}
}
// 空库位标记明细的库位账面汇总(差异口径:账面有库存即盘亏)
const emptyLocationSystemMap = new Map();
if (emptyDetailIds.size > 0) {
const emptyDetailRows = detailRows.filter(row => emptyDetailIds.has(Number(row.id)));
const emptyLocationIds = [ ...new Set(emptyDetailRows
.filter(row => row.location_id)
.map(row => Number(row.location_id))) ];
if (emptyLocationIds.length > 0) {
const emptyStorageRows = await ctx.model.Storage.findAll({
where: { space_id: { [Op.in]: emptyLocationIds } },
attributes: [
'space_id',
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
group: [ 'space_id' ],
raw: true,
});
const systemBySpace = new Map(emptyStorageRows.map(row => [
Number(row.space_id),
Number(row.totalQuantity) || 0,
]));
for (const emptyRow of emptyDetailRows) {
const emptyLocationId = emptyRow.location_id ? Number(emptyRow.location_id) : 0;
emptyLocationSystemMap.set(
Number(emptyRow.id),
emptyLocationId > 0 ? (systemBySpace.get(emptyLocationId) || 0) : 0
);
}
} else {
for (const emptyRow of emptyDetailRows) {
emptyLocationSystemMap.set(Number(emptyRow.id), 0);
}
}
}
// 差异项数:库位范围按明细行去重计数(行内任一商品实盘≠账面即该行有差异;
// 未知商品(stock_id 为空)无账面,实盘 > 0 即盘盈、必然计入差异;
// 空库位标记明细:账面有库存即盘亏差异(标记空与实际不符));
// 商品范围按商品聚合计数(实盘合计 ≠ 账面快照合计即该商品有差异,仅存在作业记录的商品计入,
// 未盘商品不提前计差异——finish 时按实盘 0 计盘亏)
let diffItems = 0;
for (const detailRow of locationDetailRows) {
const detailId = Number(detailRow.id);
if (emptyDetailIds.has(detailId)) {
if ((emptyLocationSystemMap.get(detailId) || 0) > 0) {
diffItems++;
}
continue;
}
const byStock = stockQuantityByDetail.get(detailId);
const byUnknown = unknownQuantityByDetail.get(detailId);
if ((!byStock || byStock.size === 0) && (!byUnknown || byUnknown.size === 0)) {
continue;
}
let hasDiff = false;
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) {
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');
await ctx.model.StockCheck.update(
{
checked_items: checkedItems,
diff_items: diffItems,
detail_status: detailStatus,
},
{ where: { id: checkIdNumber } }
);
return {
total_items: totalItems,
checked_items: checkedItems,
diff_items: diffItems,
detail_status: detailStatus,
checked_quantity_by_detail: checkedQuantityByDetail,
stock_quantity_by_detail: stockQuantityByDetail,
unknown_quantity_by_detail: unknownQuantityByDetail,
};
}
/**
* 创建盘点任务(空任务)。
* 生成单号 PD+YYYYMMDD+6位序号,初始状态 created,明细进度 none_checked。
*
* @param {Object} params 创建参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {string} [params.title] 盘点名称/主题。
* @param {string} [params.type='location'] 盘点范围类型:location/store/goods。
* @param {string} [params.mode='open'] 盘点方式:open=明盘/blind=盲盘;
* 按库位盘点(location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
* @param {number} [params.storeId] 货主ID(按货主盘点时必填)。
* @param {boolean|number} [params.isStatic] 是否静态盘点(纯标记):true/'true'/1/'1' 记为静态,
* 缺省与其他值为普通盘点;**仅对商品盘点(store/goods)有效**,按库位盘点(location)一律为 0
* (忽略入参);静态盘点定式创建的任务自动置 1。
* @param {string} [params.remark] 备注。
* 盘点日期固定为今天,前端不传。
* @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。
* @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。
* @return {Promise<Object>} 新建的盘点任务信息。
* @throws {Error} 参数非法时抛出业务错误(错误码 400)。
*/
async create(params = {}) {
const {
warehouseId,
title,
type,
mode,
storeId,
isStatic,
remark,
creatorId,
creatorName,
} = params;
const { ctx } = this;
const normalizedWarehouseId = Number(warehouseId);
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
throw this.createBusinessError('无法获取当前仓库上下文');
}
const normalizedType = type ? String(type).trim() : 'location';
if (!STOCK_CHECK_TYPES.includes(normalizedType)) {
throw this.createBusinessError(`盘点范围类型不合法,仅支持 ${STOCK_CHECK_TYPES.join('/')}`);
}
let normalizedMode = mode ? String(mode).trim() : 'open';
if (!STOCK_CHECK_MODES.includes(normalizedMode)) {
throw this.createBusinessError(`盘点方式不合法,仅支持 ${STOCK_CHECK_MODES.join('/')}`);
}
// 按库位盘点一律盲盘,不管前端传入什么;
// 按商品盘点(store/goods)按传入值(默认明盘)
if (normalizedType === 'location') {
normalizedMode = 'blind';
}
const normalizedStoreId = storeId !== undefined && storeId !== null && storeId !== ''
? Number(storeId)
: null;
if (normalizedType === 'store' && (!Number.isInteger(normalizedStoreId) || normalizedStoreId <= 0)) {
throw this.createBusinessError('按货主盘点时必须指定货主');
}
// 是否静态盘点:纯标记(true/'true'/1/'1' 视为开启,缺省/其他值为普通盘点);
// 仅对商品盘点有效——按库位盘点(type=location)一律为 0,忽略入参
const isStaticRequested = isStatic === true || isStatic === 'true' || isStatic === 1 || isStatic === '1';
const normalizedIsStatic = normalizedType === 'location' || !isStaticRequested ? 0 : 1;
// 创建盘点任务(并发下撞 uk_check_no 唯一键时自动重取单号,参照收货单口径,最多重试 5 次)
const maxCreateRetries = 5;
let record = null;
for (let attempt = 1; attempt <= maxCreateRetries; attempt++) {
const checkNo = await this.generateCheckNo();
try {
record = await ctx.model.StockCheck.create({
warehouse_id: normalizedWarehouseId,
check_no: checkNo,
title: title ? String(title).trim() : null,
type: normalizedType,
mode: normalizedMode,
store_id: normalizedStoreId,
is_static: normalizedIsStatic,
scope_snapshot: null,
status: 'created',
detail_status: 'none_checked',
creator_id: creatorId ? Number(creatorId) : 0,
creator_name: creatorName || null,
remark: remark ? String(remark).trim() : null,
});
break;
} catch (error) {
if (this.isCheckNoDuplicateError(error) && attempt < maxCreateRetries) {
ctx.logger.warn(`[StockCheckCreateRetry] check_no 冲突,准备重试第 ${attempt + 1} 次`, {
warehouse_id: normalizedWarehouseId,
});
continue;
}
throw error;
}
}
const plainRecord = record.get({ plain: true });
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: plainRecord.id,
operationCode: 'STOCK_CHECK_CREATE',
operationAction: 'CREATE',
changeSummary: `创建盘点任务:单号 ${plainRecord.check_no},范围类型 ${STOCK_CHECK_TYPE_LABELS[normalizedType]},盘点方式 ${STOCK_CHECK_MODE_LABELS[normalizedMode]}${normalizedIsStatic ? ',静态盘点' : ''}`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: normalizedWarehouseId,
checkNo: plainRecord.check_no,
type: normalizedType,
mode: normalizedMode,
isStatic: normalizedIsStatic,
message: `创建盘点任务 ${plainRecord.check_no}(${STOCK_CHECK_TYPE_LABELS[normalizedType]}/${STOCK_CHECK_MODE_LABELS[normalizedMode]}${normalizedIsStatic ? '/静态' : ''})`,
},
});
return this._formatCheckRow(plainRecord);
}
/**
* 批量解析货主名称映射。
* 优先取合约表 wms_store_warehouse.store_remask(货主备注名称,按 store_id + warehouse_id),
* 无合约或备注为空时回退 wms_store.company_name(公司全称)。
*
* @param {Array<number|string>} storeIds 货主ID列表。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Map<number, string>>} store_id → 货主名称。
*/
async _resolveStoreNameMap(storeIds, warehouseId) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const normalizedIds = [ ...new Set((storeIds || []).map(v => Number(v)).filter(v => v > 0)) ];
const resultMap = new Map();
if (normalizedIds.length === 0) return resultMap;
const contractRows = await ctx.model.StoreWarehouse.findAll({
where: {
store_id: { [Op.in]: normalizedIds },
warehouse_id: Number(warehouseId),
},
attributes: [ 'store_id', 'store_remask' ],
raw: true,
});
for (const row of contractRows) {
resultMap.set(Number(row.store_id), row.store_remask || '');
}
const storeRows = await ctx.model.Store.findAll({
where: { id: { [Op.in]: normalizedIds } },
attributes: [ 'id', 'company_name' ],
raw: true,
});
for (const row of storeRows) {
if (!resultMap.get(Number(row.id))) {
resultMap.set(Number(row.id), row.company_name || '');
}
}
return resultMap;
}
/**
* 构建时间范围查询条件。
* 支持:[from, to] 数组(between)/ 单值(>=)/ 空值忽略。
*
* @param {*} value 时间范围入参(数组或单值)。
* @param {Object} Op Sequelize 操作符对象。
* @return {Object|null} Sequelize where 条件片段,无有效值返回 null。
*/
_buildTimeRangeCondition(value, Op) {
if (Array.isArray(value)) {
const [ from, to ] = value;
const fromDate = from ? new Date(from) : null;
const toDate = to ? new Date(to) : null;
if (fromDate && !Number.isNaN(fromDate.getTime()) && toDate && !Number.isNaN(toDate.getTime())) {
return { [Op.between]: [ fromDate, toDate ] };
}
if (fromDate && !Number.isNaN(fromDate.getTime())) {
return { [Op.gte]: fromDate };
}
if (toDate && !Number.isNaN(toDate.getTime())) {
return { [Op.lte]: toDate };
}
return null;
}
if (value === undefined || value === null || value === '') {
return null;
}
const parsedDate = new Date(value);
if (Number.isNaN(parsedDate.getTime())) {
return null;
}
return { [Op.gte]: parsedDate };
}
/**
* 将单值/数组归一化为字符串列表(供 type/mode/status 等枚举筛选)。
*
* @param {*} value 原始值。
* @return {Array<string>} 归一化后的字符串列表。
*/
_normalizeEnumValues(value) {
const list = Array.isArray(value) ? value : [ value ];
return [ ...new Set(list
.map(item => String(item === null || item === undefined ? '' : item).trim())
.filter(Boolean)) ];
}
/**
* 拉取盘点任务列表。
* 支持筛选:status(状态,单值或数组)、type(范围类型)、mode(盘点方式)、
* store_id(货主)、keyword(单号/标题模糊)、created_at(创建时间范围)、
* start_time(盘点开始时间范围)、end_time(盘点结束时间范围)与分页。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {string|Array<string>} [params.status] 状态筛选。
* @param {string|Array<string>} [params.type] 范围类型筛选。
* @param {string|Array<string>} [params.mode] 盘点方式筛选。
* @param {number|string} [params.storeId] 货主筛选。
* @param {string} [params.keyword] 关键字(盘点单号/标题模糊匹配)。
* @param {*} [params.createdAt] 创建时间筛选(单值=当天起,[from,to]=区间)。
* @param {*} [params.startTime] 盘点开始时间筛选。
* @param {*} [params.endTime] 盘点结束时间筛选。
* @param {Object} [params.pagination] 分页参数。
* @return {Promise<Object>} { rows, total, page, pageSize }。
*/
async list(params = {}) {
const {
warehouseId,
status,
type,
mode,
storeId,
keyword,
createdAt,
startTime,
endTime,
pagination = {},
} = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const page = Math.max(1, Number(pagination.page) || 1);
const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20));
const where = { warehouse_id: Number(warehouseId) };
if (status !== undefined && status !== null && status !== '') {
const statusList = this._normalizeEnumValues(status);
if (statusList.length === 1) {
where.status = statusList[0];
} else if (statusList.length > 1) {
where.status = { [Op.in]: statusList };
}
}
if (type !== undefined && type !== null && type !== '') {
const typeList = this._normalizeEnumValues(type);
if (typeList.length === 1) {
where.type = typeList[0];
} else if (typeList.length > 1) {
where.type = { [Op.in]: typeList };
}
}
if (mode !== undefined && mode !== null && mode !== '') {
const modeList = this._normalizeEnumValues(mode);
if (modeList.length === 1) {
where.mode = modeList[0];
} else if (modeList.length > 1) {
where.mode = { [Op.in]: modeList };
}
}
if (storeId !== undefined && storeId !== null && storeId !== '') {
where.store_id = Number(storeId);
}
const createdRange = this._buildTimeRangeCondition(createdAt, Op);
if (createdRange) {
where.created_at = createdRange;
}
const startRange = this._buildTimeRangeCondition(startTime, Op);
if (startRange) {
where.start_time = startRange;
}
const endRange = this._buildTimeRangeCondition(endTime, Op);
if (endRange) {
where.end_time = endRange;
}
const keywordValue = keyword ? String(keyword).trim() : '';
if (keywordValue) {
where[Op.or] = [
{ check_no: { [Op.like]: `%${keywordValue}%` } },
{ title: { [Op.like]: `%${keywordValue}%` } },
];
}
const { count, rows } = await ctx.model.StockCheck.findAndCountAll({
where,
order: [[ 'id', 'DESC' ]],
offset: (page - 1) * pageSize,
limit: pageSize,
raw: true,
});
// 补齐货主名称(合约货主备注优先、公司全称兜底)
const storeNameMap = await this._resolveStoreNameMap(
rows.map(row => row.store_id),
warehouseId
);
const formattedRows = rows.map(row => ({
...row,
store_name: storeNameMap.get(Number(row.store_id)) || '',
}));
return { rows: formattedRows, total: count, page, pageSize };
}
/**
* 拉取盘点定式清单。
* 转调 stockCheckPatterns.listPatterns(),返回全部可用定式(id/name/description/type)。
*
* @return {Promise<Object>} { patterns, total }。
*/
async patternList() {
const { ctx } = this;
const patterns = ctx.service.systems.stockCheckPatterns.listPatterns();
return { patterns, total: patterns.length };
}
/**
* 按定式快速创建盘点任务。
* 按定式收集盘点对象(goods 型得到 stock_ids、location 型得到库位编码列表),
* 无符合条件对象时拒绝创建(错误码 400);创建后主表状态直接为 submitted(待审核)、
* detail_status=none_checked、total_items 按明细重算;static 定式在任务创建成功后
* 把命中的 stock_id 写入 wms_stock_static_check_task(写失败不影响主流程)。
*
* @param {Object} params 创建参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {string} params.patternId 定式ID(pattern_id)。
* @param {string} [params.title] 盘点名称/主题,缺省取定式 name。
* @param {string} [params.remark] 备注。
* @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。
* @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。
* 盘点方式由定式范围类型固定:库位类定式一律盲盘(blind)、商品类定式一律明盘(open);
* 盘点日期固定为今天,前端不传。
* @return {Promise<Object>} { check, total_items, pattern_id }。
* @throws {Error} 仓库上下文缺失/定式不存在/参数非法/无符合条件对象时抛出业务错误(错误码 400)。
*/
async patternCreate(params = {}) {
const {
warehouseId,
patternId,
title,
remark,
creatorId,
creatorName,
} = params;
const { ctx } = this;
const normalizedWarehouseId = Number(warehouseId);
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
throw this.createBusinessError('无法获取当前仓库上下文');
}
const normalizedPatternId = String(patternId || '').trim();
const pattern = normalizedPatternId
? ctx.service.systems.stockCheckPatterns.getPatternById(normalizedPatternId)
: null;
if (!pattern) {
throw this.createBusinessError('盘点定式不存在');
}
// 盘点方式由定式范围类型固定:库位类一律盲盘、商品类一律明盘(前端不传)
const normalizedMode = pattern.type === 'location' ? 'blind' : 'open';
// 静态定式创建的任务标记为静态盘点(纯标记,不改变流程与数量口径);
// 静态盘点仅对商品盘点有效,库位类定式一律 0
const normalizedIsStatic = pattern.id === 'static' && pattern.type !== 'location' ? 1 : 0;
const normalizedTitle = title ? String(title).trim() : pattern.name;
// 按定式收集盘点对象
const collected = await ctx.service.systems.stockCheckPatterns.collectById(pattern.id, {
warehouseId: normalizedWarehouseId,
});
const stockIds = Array.isArray(collected && collected.stock_ids) ? collected.stock_ids : [];
const locations = Array.isArray(collected && collected.locations) ? collected.locations : [];
if (pattern.type === 'location' && locations.length === 0) {
throw this.createBusinessError('当前仓库没有账面为空的库位');
}
if (pattern.type === 'goods' && stockIds.length === 0) {
throw this.createBusinessError('没有符合条件的商品');
}
// 创建主表(并发下撞 uk_check_no 唯一键时自动重取单号,最多重试 5 次)
const maxCreateRetries = 5;
let record = null;
for (let attempt = 1; attempt <= maxCreateRetries; attempt++) {
const checkNo = await this.generateCheckNo();
try {
record = await ctx.model.StockCheck.create({
warehouse_id: normalizedWarehouseId,
check_no: checkNo,
title: normalizedTitle,
type: pattern.type,
mode: normalizedMode,
store_id: null,
is_static: normalizedIsStatic,
scope_snapshot: null,
status: 'submitted',
detail_status: 'none_checked',
creator_id: creatorId ? Number(creatorId) : 0,
creator_name: creatorName || null,
remark: remark ? String(remark).trim() : null,
total_items: 0,
});
break;
} catch (error) {
if (this.isCheckNoDuplicateError(error) && attempt < maxCreateRetries) {
ctx.logger.warn(`[StockCheckPatternCreateRetry] check_no 冲突,准备重试第 ${attempt + 1} 次`, {
warehouse_id: normalizedWarehouseId,
pattern_id: pattern.id,
});
continue;
}
throw error;
}
}
// 明细写入(goods 型按商品快照,location 型按库位)
const toCreate = [];
if (pattern.type === 'goods') {
await this._addGoodsDetailRows({
checkId: record.id,
check: record,
warehouseId: normalizedWarehouseId,
numericStockIds: stockIds,
toCreate,
skippedItems: [],
invalidStockIds: [],
});
} else {
const codes = [ ...new Set(
locations
.map(location => String(location && location.location_code || '').trim())
.filter(Boolean)
) ];
await this._addLocationDetailRows({
checkId: record.id,
warehouseId: normalizedWarehouseId,
codes,
toCreate,
skippedItems: [],
invalidLocations: [],
});
}
if (toCreate.length > 0) {
await ctx.model.StockCheckDetail.bulkCreate(toCreate);
}
// 重算并更新主表 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 });
// static 定式:任务创建成功后写入静态盘点任务关联记录(失败不影响主流程)
if (pattern.id === 'static' && stockIds.length > 0) {
try {
await ctx.model.StockStaticCheckTask.bulkCreate(
stockIds.map(stockId => ({
stock_id: Number(stockId),
task_time: new Date(),
}))
);
} catch (error) {
ctx.logger.warn(
`[StockCheckPatternCreate] 写入静态盘点任务关联记录失败 pattern=${pattern.id}: ${error && error.message}`
);
}
}
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: plainRecord.id,
operationCode: 'STOCK_CHECK_CREATE',
operationAction: 'CREATE',
changeSummary: `按定式创建盘点任务:单号 ${plainRecord.check_no},定式 ${pattern.name}(${pattern.id}),范围类型 ${STOCK_CHECK_TYPE_LABELS[pattern.type]},盘点方式 ${STOCK_CHECK_MODE_LABELS[normalizedMode]}${normalizedIsStatic ? ',静态盘点' : ''}`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: normalizedWarehouseId,
patternId: pattern.id,
checkNo: plainRecord.check_no,
total_items: totalItems,
message: `按定式创建盘点任务 ${plainRecord.check_no}(${pattern.name}/${pattern.id})`,
},
});
return {
check: this._formatCheckRow(plainRecord),
total_items: totalItems,
pattern_id: pattern.id,
};
}
/**
* 添加盘点明细(商品或库位,按任务盘点类型决定)。
* 仅 created/rejected 状态允许;store/goods 类型按 stock_ids 添加商品行(商品必须属于
* 任务货主);location 类型按 locations(库位编码,兼容旧调用)或 location_ids
* (库位ID,直接查库校验,不再解析编码)添加库位行,两者都传时 location_ids 优先、
* locations 忽略;location 未传库位且未传库位ID时自动拉取全仓库启用库位(原全盘语义);
* 已存在的同盘点项跳过(幂等),重算主表 total_items。
*
* @param {Object} params 添加明细参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {number|Array<number>} [params.stockIds] 商品库存ID列表(wms_stock_warehouse.id,按商品盘点类型使用)。
* @param {string|Array<string>} [params.locations] 库位编码列表(按库位盘点类型使用,兼容旧调用;
* 与 locationIds 同时传入时被忽略)。
* @param {number|Array<number>} [params.locationIds] 库位ID列表(wms_location_space.id,按库位盘点类型使用;
* 与 locations 同时传入时优先使用)。
* @return {Promise<Object>} { added, skipped, invalid_stock_ids, invalid_locations, invalid_location_ids, total_items }。
* @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。
*/
async addDetail(params = {}) {
const { warehouseId, id, stockIds, locations, locationIds } = params;
const { ctx } = this;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!ADD_DETAIL_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${check.status})不允许添加明细`);
}
const checkType = String(check.type || 'location').trim();
const isGoodsScope = checkType === 'store' || checkType === 'goods';
const isLocationScope = checkType === 'location';
if (!isGoodsScope && !isLocationScope) {
throw this.createBusinessError(`盘点范围类型不合法(${checkType})`);
}
const numericStockIds = this._normalizeIdList(stockIds);
const locationCodes = this._normalizeCodeList(locations);
const numericLocationIds = this._normalizeIdList(locationIds);
// 按盘点类型校验入参维度(商品与库位互斥)
if (isGoodsScope && locationCodes.length > 0) {
throw this.createBusinessError('当前盘点类型按商品盘点,请传 stock_ids');
}
if (isGoodsScope && numericLocationIds.length > 0) {
throw this.createBusinessError('当前盘点类型按商品盘点,不能添加库位明细');
}
if (isLocationScope && numericStockIds.length > 0) {
throw this.createBusinessError('当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)');
}
const toCreate = [];
const skippedItems = [];
const invalidStockIds = [];
const invalidLocations = [];
const invalidLocationIds = [];
if (isGoodsScope) {
if (numericStockIds.length === 0) {
throw this.createBusinessError('请至少选择一个商品');
}
await this._addGoodsDetailRows({
checkId,
check,
warehouseId,
numericStockIds,
toCreate,
skippedItems,
invalidStockIds,
});
} else if (isLocationScope) {
// location_ids 优先:两者都传时忽略 locations,直接按 ID 查库校验(不再解析编码)
if (numericLocationIds.length > 0) {
await this._addLocationRowsByIds({
checkId,
warehouseId,
numericLocationIds,
toCreate,
skippedItems,
invalidLocationIds,
});
} else {
let codes = locationCodes;
// 未显式传库位时自动拉取全仓库启用库位(原全盘语义);
// 排除无头库位:zone 必须存在且未删除
if (codes.length === 0) {
const enabledSpaces = await ctx.model.LocationSpace.findAll({
where: { warehouse_id: Number(warehouseId), is_enabled: true },
attributes: [ 'space_code' ],
include: [{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [],
required: true,
}],
order: [[ 'id', 'ASC' ]],
raw: true,
});
codes = [ ...new Set(enabledSpaces
.map(space => String(space.space_code || '').trim())
.filter(Boolean)) ];
if (codes.length === 0) {
throw this.createBusinessError('当前仓库没有启用库位,无法按全盘自动生成盘点范围');
}
}
await this._addLocationDetailRows({
checkId,
warehouseId,
codes,
toCreate,
skippedItems,
invalidLocations,
});
}
}
if (toCreate.length > 0) {
await ctx.model.StockCheckDetail.bulkCreate(toCreate);
}
// 重算主表 total_items(商品范围按商品计数,库位范围按明细行计数)
const scopeSummary = await this._countScopeSummary(checkId);
const totalItems = scopeSummary.total_items;
await check.update({ total_items: totalItems });
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_ADD_DETAIL',
operationAction: 'UPDATE',
changeSummary: `添加盘点明细:新增 ${toCreate.length},跳过 ${skippedItems.length},无效商品 ${invalidStockIds.length},无效库位 ${invalidLocations.length},无效库位ID ${invalidLocationIds.length}`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
checkNo: check.check_no,
added: toCreate.length,
skipped: skippedItems.length,
invalidStockIds,
invalidLocations,
invalidLocationIds,
message: `添加盘点明细 ${toCreate.length} 条,跳过 ${skippedItems.length} 条`,
},
});
return {
added: toCreate.length,
skipped: skippedItems.length,
invalid_stock_ids: invalidStockIds,
invalid_locations: invalidLocations,
invalid_location_ids: invalidLocationIds,
total_items: totalItems,
};
}
/**
* 批量添加库位明细(兼容入口,薄封装转调 addDetail 的库位ID直查路径)。
* 入参库位ID列表,服务端直接按 ID 查库校验,不经过 space_code 二次解析;
* 转发前保留旧口径的参数校验(任务ID不能为空、库位ID不能为空、单次上限 200),
* 任务存在性/状态/类型分派校验统一由 addDetail 处理;
* 返回结构从 addDetail 映射为 { added, skipped, invalid_location_ids, total_items }
* (过滤 invalid_locations/invalid_stock_ids),保持原返回口径不变。
*
* @param {Object} params 批量添加库位明细参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {number|Array<number>} params.locationIds 库位ID列表(wms_location_space.id,单次上限 200)。
* @return {Promise<Object>} { added, skipped, invalid_location_ids, total_items }。
* @throws {Error} 参数非法或状态不允许时抛出业务错误(错误码 400):
* - 盘点任务ID不能为空
* - 请至少选择一个库位
* - 单次最多添加 200 个库位
* 其余校验(任务不存在/状态不允许/商品任务不可添加库位明细)由 addDetail 透传同款错误。
*/
async addLocationDetail(params = {}) {
const { warehouseId, id, locationIds } = params;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
// 库位ID归一化(去重正整数)与数量上限校验(保留旧口径,转发前拦截)
const numericLocationIds = this._normalizeIdList(locationIds);
if (numericLocationIds.length === 0) {
throw this.createBusinessError('请至少选择一个库位');
}
if (numericLocationIds.length > STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS) {
throw this.createBusinessError(`单次最多添加 ${STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS} 个库位`);
}
// 转调 addDetail(库位ID直查路径,空 stockIds/locations),过滤出兼容返回结构
const result = await this.addDetail({
warehouseId,
id,
stockIds: [],
locations: [],
locationIds: numericLocationIds,
});
return {
added: result.added,
skipped: result.skipped,
invalid_location_ids: result.invalid_location_ids,
total_items: result.total_items,
};
}
/**
* 生成按商品盘点明细的待创建行(store/goods 类型)。
* 商品必须属于当前仓库;任务货主非空时商品货主必须与任务货主一致,否则记入 invalidStockIds;
* 已存在同 check_id+stock_id 的明细跳过(幂等)。
*
* @param {Object} params 生成参数。
* @param {number} params.checkId 盘点任务ID。
* @param {Object} params.check 盘点主表模型实例(含 store_id)。
* @param {number} params.warehouseId 仓库ID。
* @param {Array<number>} params.numericStockIds 归一化后的商品ID列表。
* @param {Array<Object>} params.toCreate 待创建行收集数组(原地追加)。
* @param {Array<number>} params.skippedItems 跳过项收集数组(原地追加)。
* @param {Array<number>} params.invalidStockIds 非法商品ID收集数组(原地追加)。
* @return {Promise<void>} 无返回值。
*/
async _addGoodsDetailRows(params = {}) {
const {
checkId,
check,
warehouseId,
numericStockIds,
toCreate,
skippedItems,
invalidStockIds,
} = params;
const { ctx } = this;
const { Op, literal } = ctx.app.Sequelize;
// 按 stock_ids 查询库存商品快照(限定当前仓库,自动过滤已删除)
const stockRows = await ctx.model.StockWarehouse.findAll({
where: {
id: { [Op.in]: numericStockIds },
warehouse_id: Number(warehouseId),
},
raw: true,
});
const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ]));
// 幂等:已存在同 stock_id 的明细跳过(同商品整体跳过,兼容历史单行与拆行)
const existingRows = await ctx.model.StockCheckDetail.findAll({
where: {
check_id: checkId,
stock_id: { [Op.in]: numericStockIds },
},
attributes: [ 'stock_id' ],
raw: true,
});
const existingStockIds = new Set(existingRows.map(item => Number(item.stock_id)));
// 商品在本仓库的启用库存库位(按库位拆分明细行:商品任务必须按库位盘点,
// 一个商品多个库位对应多行,各行账面 = 该库位库存 SUM(可用数量);无库存库位商品不可盘点;
// 库位有效性:仅统计有效库位(所属 zone 存在且未删除),无头库位(zone 不存在/已删除)不纳入盘点)
const storageRows = await ctx.model.Storage.findAll({
where: {
warehouse_id: Number(warehouseId),
stock_id: { [Op.in]: numericStockIds },
is_enabled: 1,
space_id: {
[Op.in]: literal(VALID_SPACE_SQL),
},
},
attributes: [
'stock_id',
'space_id',
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
group: [ 'stock_id', 'space_id' ],
raw: true,
});
const stockStorageMap = new Map();
for (const storageRow of storageRows) {
const stockId = Number(storageRow.stock_id);
if (!stockStorageMap.has(stockId)) {
stockStorageMap.set(stockId, []);
}
stockStorageMap.get(stockId).push({
spaceId: Number(storageRow.space_id),
quantity: Number(storageRow.totalQuantity) || 0,
});
}
const storageSpaceIds = [ ...new Set(storageRows.map(row => Number(row.space_id))) ];
let spaceCodeMap = new Map();
if (storageSpaceIds.length > 0) {
const spaceRows = await ctx.model.LocationSpace.findAll({
where: { id: { [Op.in]: storageSpaceIds } },
attributes: [ 'id', 'space_code' ],
raw: true,
});
spaceCodeMap = new Map(spaceRows.map(item => [ Number(item.id), String(item.space_code || '').trim() ]));
}
// 货主限制:任务货主非空时,商品货主必须与任务货主一致(限制非本货主商品加入盘点)
const checkStoreId = check.store_id !== null && check.store_id !== undefined
? Number(check.store_id)
: 0;
for (const stockId of numericStockIds) {
const stock = stockMap.get(stockId);
if (!stock) {
invalidStockIds.push(stockId);
continue;
}
if (checkStoreId > 0 && Number(stock.store_id) !== checkStoreId) {
invalidStockIds.push(stockId);
continue;
}
if (existingStockIds.has(stockId)) {
skippedItems.push(stockId);
continue;
}
const stockLocations = stockStorageMap.get(stockId) || [];
if (stockLocations.length === 0) {
// 商品在仓库中没有启用库存库位 → 不可加入盘点
invalidStockIds.push(stockId);
continue;
}
for (const stockLocation of stockLocations) {
toCreate.push({
check_id: checkId,
warehouse_id: Number(warehouseId),
scope_type: 'goods',
stock_id: stockId,
item_code: stock.item_code,
item_name: stock.item_name || null,
spec: stock.sku_property || null,
batch_no: null,
system_quantity: stockLocation.quantity,
location_id: stockLocation.spaceId,
location_code: spaceCodeMap.get(stockLocation.spaceId) || null,
});
}
}
}
/**
* 生成按库位盘点明细的待创建行(location 类型)。
* 按 space_code 匹配 wms_location_space(warehouse_id + space_code),
* 不存在的编码记入 invalidLocations;已存在同 check_id+location_code 的明细跳过(幂等)。
*
* @param {Object} params 生成参数。
* @param {number} params.checkId 盘点任务ID。
* @param {number} params.warehouseId 仓库ID。
* @param {Array<string>} params.codes 归一化后的库位编码列表。
* @param {Array<Object>} params.toCreate 待创建行收集数组(原地追加)。
* @param {Array<string>} params.skippedItems 跳过项收集数组(原地追加)。
* @param {Array<string>} params.invalidLocations 非法库位编码收集数组(原地追加)。
* @return {Promise<void>} 无返回值。
*/
async _addLocationDetailRows(params = {}) {
const { checkId, warehouseId, codes, toCreate, skippedItems, invalidLocations } = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const spaceRows = await ctx.model.LocationSpace.findAll({
where: {
warehouse_id: Number(warehouseId),
space_code: { [Op.in]: codes },
},
attributes: [ 'id', 'space_code' ],
// 库位有效性:zone 必须存在且未删除(无头库位记入 invalidLocations,与不存在同口径)
include: [{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [],
required: true,
}],
raw: true,
});
const spaceByCode = new Map(spaceRows.map(item => [ String(item.space_code), item ]));
// 幂等:已存在同 location_code 的明细跳过
const existingRows = await ctx.model.StockCheckDetail.findAll({
where: {
check_id: checkId,
location_code: { [Op.in]: codes },
},
attributes: [ 'location_code' ],
raw: true,
});
const existingLocationCodes = new Set(existingRows
.map(item => String(item.location_code || '').trim())
.filter(Boolean));
for (const code of codes) {
const space = spaceByCode.get(code);
if (!space) {
invalidLocations.push(code);
continue;
}
if (existingLocationCodes.has(code)) {
skippedItems.push(code);
continue;
}
toCreate.push({
check_id: checkId,
warehouse_id: Number(warehouseId),
scope_type: 'location',
stock_id: null,
item_code: null,
item_name: null,
spec: null,
batch_no: null,
system_quantity: 0,
location_id: Number(space.id),
location_code: String(space.space_code),
});
}
}
/**
* 生成按库位盘点明细的待创建行(库位ID直查路径,location 类型)。
* 直接按 wms_location_space.id 查库校验(warehouse_id 仓库隔离),不经过 space_code 二次解析;
* 查不到的 ID 记入 invalidLocationIds(不报错);库位编码为空(脏数据)或已存在
* 同 check_id+location_code 的明细跳过(uk_check_location 唯一索引口径,幂等),
* 跳过项按库位ID记入 skippedItems;供 addDetail 与 addLocationDetail 共用。
*
* @param {Object} params 生成参数。
* @param {number} params.checkId 盘点任务ID。
* @param {number} params.warehouseId 仓库ID。
* @param {Array<number>} params.numericLocationIds 归一化后的库位ID列表。
* @param {Array<Object>} params.toCreate 待创建行收集数组(原地追加)。
* @param {Array<number>} params.skippedItems 跳过项收集数组(原地追加,记库位ID)。
* @param {Array<number>} params.invalidLocationIds 非法库位ID收集数组(原地追加)。
* @return {Promise<void>} 无返回值。
*/
async _addLocationRowsByIds(params = {}) {
const {
checkId,
warehouseId,
numericLocationIds,
toCreate,
skippedItems,
invalidLocationIds,
} = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
// 直接按 ID 查库校验(仓库隔离),查不到的 ID 记入 invalidLocationIds(不报错);
// 库位有效性:zone 必须存在且未删除(无头库位同样记入 invalidLocationIds)
const spaceRows = await ctx.model.LocationSpace.findAll({
where: {
id: { [Op.in]: numericLocationIds },
warehouse_id: Number(warehouseId),
},
attributes: [ 'id', 'space_code' ],
include: [{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [],
required: true,
}],
raw: true,
});
const spaceById = new Map(spaceRows.map(item => [ Number(item.id), item ]));
// 幂等:已存在同 check_id+location_code 的明细跳过(uk_check_location 唯一索引口径)
const spaceCodes = [ ...new Set(spaceRows
.map(item => String(item.space_code || '').trim())
.filter(Boolean)) ];
const existingLocationCodes = new Set();
if (spaceCodes.length > 0) {
const existingRows = await ctx.model.StockCheckDetail.findAll({
where: {
check_id: checkId,
location_code: { [Op.in]: spaceCodes },
},
attributes: [ 'location_code' ],
raw: true,
});
for (const row of existingRows) {
const code = String(row.location_code || '').trim();
if (code) {
existingLocationCodes.add(code);
}
}
}
for (const locationId of numericLocationIds) {
const space = spaceById.get(locationId);
if (!space) {
invalidLocationIds.push(locationId);
continue;
}
const spaceCode = String(space.space_code || '').trim();
// 库位编码为空(脏数据)或已存在同库位明细行:跳过,避免撞 uk_check_location
if (!spaceCode || existingLocationCodes.has(spaceCode)) {
skippedItems.push(locationId);
continue;
}
existingLocationCodes.add(spaceCode);
toCreate.push({
check_id: checkId,
warehouse_id: Number(warehouseId),
scope_type: 'location',
stock_id: null,
item_code: null,
item_name: null,
spec: null,
batch_no: null,
system_quantity: 0,
location_id: Number(space.id),
location_code: spaceCode,
});
}
}
/**
* 删除盘点明细(批量:从任务中移除一个或多个商品/库位范围行)。
* 仅主表状态 created/rejected(ADD_DETAIL_ALLOWED_STATUSES)允许删除;
* 明细存在作业记录(wms_stock_check_record)时一并防御性删除(正常流程该状态不应有记录);
* 查不到的明细 ID 计入 skipped_ids 不报错;删除后重算主表 total_items。
* 注意:响应结构由旧版 { detail_id, deleted, total_items } 变更为
* { deleted_count, deleted_ids, skipped_ids, total_items }。
*
* @param {Object} params 删除参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {Array<number>|number} params.detailIds 盘点明细ID数组(单值自动转数组,单次上限 200)。
* @return {Promise<Object>} { deleted_count, deleted_ids, skipped_ids, total_items };
* deleted_ids/skipped_ids 均保持入参顺序。
* @throws {Error} 参数非法、任务不存在、状态不允许或明细为空/超限时抛出业务错误(错误码 400)。
*/
async detailDelete(params = {}) {
const { warehouseId, id, detailIds } = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!ADD_DETAIL_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${check.status})不允许删除明细`);
}
const numericDetailIds = this._normalizeIdList(detailIds);
if (numericDetailIds.length === 0) {
throw this.createBusinessError('请至少选择一个明细');
}
if (numericDetailIds.length > 200) {
throw this.createBusinessError('单次最多删除 200 条明细');
}
// 仓库隔离查询明细:id in ids + check_id + warehouse_id;查不到的 ID 计入 skipped_ids(不报错)
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: {
id: { [Op.in]: numericDetailIds },
check_id: checkId,
warehouse_id: Number(warehouseId),
},
attributes: [ 'id' ],
raw: true,
});
const foundIdSet = new Set(detailRows.map(row => Number(row.id)));
const deletedIds = [];
const skippedIds = [];
for (const detailId of numericDetailIds) {
if (foundIdSet.has(detailId)) {
deletedIds.push(detailId);
} else {
skippedIds.push(detailId);
}
}
if (deletedIds.length > 0) {
await ctx.model.StockCheckDetail.destroy({
where: { id: { [Op.in]: deletedIds } },
});
// 防御性处理:若这些明细存在作业记录(正常流程 created/rejected 不应有记录),一并删除
await ctx.model.StockCheckRecord.destroy({
where: {
detail_id: { [Op.in]: deletedIds },
check_id: checkId,
warehouse_id: Number(warehouseId),
},
});
}
// 删除明细后重算主表 total_items(商品范围按商品计数,库位范围按明细行计数)
const scopeSummary = await this._countScopeSummary(checkId);
const totalItems = scopeSummary.total_items;
await check.update({ total_items: totalItems });
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_DELETE_DETAIL',
operationAction: 'UPDATE',
changeSummary: `删除盘点明细:单号 ${check.check_no},删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(warehouseId),
checkNo: check.check_no,
detailIds: deletedIds,
skippedIds,
deletedCount: deletedIds.length,
skippedCount: skippedIds.length,
message: `删除盘点明细:单号 ${check.check_no},删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`,
},
});
return {
deleted_count: deletedIds.length,
deleted_ids: deletedIds,
skipped_ids: skippedIds,
total_items: totalItems,
};
}
/**
* 拉取盘点任务详情(只返回任务本身信息)。
* 不返回明细范围行与盘点作业聚合(明细范围行/盘点结果请调用 result,
* 作业记录明细请调用 recordList,盘点作业数据请调用 workData)。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @return {Promise<Object>} { check },check 为盘点主表信息(_formatCheckRow 口径),
* 并附 profit_total(盘盈合计数量)/loss_total(盘亏合计数量,正数口径,与 finish 一致)。
* @throws {Error} 任务不存在时抛出业务错误(错误码 400)。
*/
async detail(params = {}) {
const { warehouseId, id } = params;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
// 数量差异汇总(盘盈/盘亏数量,口径与 finish 一致;无作业记录时均为 0)
const diffSummary = await this._calcQuantityDiffSummary(checkId);
return {
check: {
...this._formatCheckRow(check.get({ plain: true })),
profit_total: diffSummary.profit_total,
loss_total: diffSummary.loss_total,
},
};
}
/**
* 构建静态盘点锁定缓存键(按仓库维度)。
*
* @param {number} warehouseId 仓库ID。
* @return {string} 缓存键。
*/
_staticLockCacheKey(warehouseId) {
return `${STATIC_LOCK_CACHE_KEY_PREFIX}${Number(warehouseId) || 0}`;
}
/**
* 查询「静态盘点锁定中」的库存商品列表(公共查询,供库存操作前判断是否可动)。
*
* 口径:主表 is_static=1 且状态为 approved(审核完成)/checking(盘点作业中)的任务,
* 取其商品范围明细(scope_type=goods)的 stock_id 去重集合——即这些商品的库位正在静态盘点,
* 出入库/移库等库存操作应被限制;任务提交审核前(created/submitted/rejected)与
* 已完成(completed)/已取消(cancelled)不锁定。
*
* 缓存:结果按仓库维度缓存在 `stock_check:static_lock:{warehouseId}`(TTL 300 秒兜底,
* Redis 优先、不可用时降级进程内缓存);审核/完成/取消/批量删除等状态流转时**立即重建缓存**
* (不是简单删除再等下次回源),空集合也会被缓存(不会因「当前没有锁定商品」反复回源)。
* 同一进程内并发未命中用 singleflight 去重,只回源一次。返回 cached 标识本次是否命中缓存。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {boolean} [params.forceRefresh] 跳过缓存强制回源重建(内部/排障用)。
* @return {Promise<Object>} { warehouse_id, stock_ids, rows, total, cached, updated_at };
* rows 每个 stock_id 一条:{ stock_id, item_code, item_name, check_ids, check_nos, location_codes }。
*/
async staticLockList(params = {}) {
const { warehouseId, forceRefresh } = params;
const normalizedWarehouseId = Number(warehouseId);
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
throw this.createBusinessError('无法获取当前仓库上下文');
}
const cacheKey = this._staticLockCacheKey(normalizedWarehouseId);
if (forceRefresh !== true && forceRefresh !== 'true' && forceRefresh !== 1) {
const cachedPayload = await this._readStaticLockCache(cacheKey);
if (cachedPayload) {
return cachedPayload;
}
}
const payload = await this._loadStaticLockCache(normalizedWarehouseId);
return payload;
}
/**
* 读取锁定缓存(命中时补齐 cached=true)。
*
* @param {string} cacheKey 缓存键。
* @return {Promise<Object|null>} 缓存载荷(已格式化)或 null。
*/
async _readStaticLockCache(cacheKey) {
const { ctx } = this;
const cachedPayload = await ctx.app.getCacheAsync(cacheKey);
if (!cachedPayload || !Array.isArray(cachedPayload.rows)) {
return null;
}
return {
warehouse_id: Number(cachedPayload.warehouse_id) || 0,
stock_ids: cachedPayload.stock_ids || [],
rows: cachedPayload.rows,
total: cachedPayload.rows.length,
cached: true,
updated_at: cachedPayload.updated_at || null,
};
}
/**
* 回源数据库并写入缓存(进程内 singleflight:同仓库并发未命中只回源一次)。
*
* 防脏读(写缓存乐观锁):回源前后各读一次「锁定代次」(状态流转时由
* refreshStaticLockCache 递增),两次不一致说明查询期间有并发状态流转,
* 本次结果可能是旧快照 → **放弃写入缓存**(删除缓存,交给下一次查询/该次流转的重建),
* 避免用旧快照覆盖新缓存。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object>} 格式化后的载荷(cached=false;未写缓存时同样带 skipped_write 标识)。
*/
async _loadStaticLockCache(warehouseId) {
const { ctx } = this;
const cacheKey = this._staticLockCacheKey(warehouseId);
const inflight = STATIC_LOCK_INFLIGHT.get(cacheKey);
if (inflight) {
return inflight;
}
const task = (async () => {
const generationBefore = await this._readStaticLockGeneration(warehouseId);
const rows = await this._queryStaticLockRows(warehouseId);
const generationAfter = await this._readStaticLockGeneration(warehouseId);
const payload = {
warehouse_id: Number(warehouseId),
stock_ids: rows.map(row => row.stock_id),
rows,
updated_at: new Date().toISOString(),
};
if (generationBefore !== generationAfter) {
// 查询期间有状态流转:不写入旧快照,删掉缓存让下一次读取回源
ctx.logger.warn(`[StockCheckStaticLock] 回源期间发生状态流转,跳过写缓存 warehouse=${warehouseId}(gen ${generationBefore} → ${generationAfter})`);
await this.clearStaticLockCache(warehouseId);
return {
...payload,
total: rows.length,
cached: false,
cache_skipped: true,
};
}
await ctx.app.setCacheAsync(cacheKey, payload, STATIC_LOCK_CACHE_TTL_SECONDS);
return {
...payload,
total: rows.length,
cached: false,
};
})();
STATIC_LOCK_INFLIGHT.set(cacheKey, task);
try {
return await task;
} finally {
STATIC_LOCK_INFLIGHT.delete(cacheKey);
}
}
/**
* 查询静态锁定商品行(数据库口径,无缓存):is_static=1 且 approved/checking 任务的商品明细。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<Array<Object>>} 按 stock_id 升序的聚合行。
*/
async _queryStaticLockRows(warehouseId) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const checkRows = await ctx.model.StockCheck.findAll({
where: {
warehouse_id: Number(warehouseId),
is_static: 1,
status: { [Op.in]: STATIC_LOCK_ALLOWED_STATUSES },
},
attributes: [ 'id', 'check_no' ],
raw: true,
});
if (checkRows.length === 0) {
return [];
}
const checkNoById = new Map(checkRows.map(row => [ Number(row.id), String(row.check_no || '') ]));
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: {
check_id: { [Op.in]: [ ...checkNoById.keys() ] },
scope_type: 'goods',
},
attributes: [ 'check_id', 'stock_id', 'item_code', 'item_name', 'location_code' ],
raw: true,
});
const aggByStock = new Map();
for (const detailRow of detailRows) {
const stockId = Number(detailRow.stock_id);
if (!Number.isInteger(stockId) || stockId <= 0) {
continue;
}
const agg = aggByStock.get(stockId) || {
stock_id: stockId,
item_code: detailRow.item_code || null,
item_name: detailRow.item_name || null,
check_ids: [],
check_nos: [],
location_codes: [],
};
const detailCheckId = Number(detailRow.check_id);
if (!agg.check_ids.includes(detailCheckId)) {
agg.check_ids.push(detailCheckId);
agg.check_nos.push(checkNoById.get(detailCheckId) || '');
}
const locationCode = String(detailRow.location_code || '').trim();
if (locationCode && !agg.location_codes.includes(locationCode)) {
agg.location_codes.push(locationCode);
}
aggByStock.set(stockId, agg);
}
return [ ...aggByStock.values() ].sort((left, right) => left.stock_id - right.stock_id);
}
/**
* 重建静态盘点锁定缓存(状态流转后立即同步,避免「删除缓存 → 下次查询才回源」的空窗)。
* 顺序:先递增锁定代次(使并发回源中的旧快照自动作废)→ 回源 → 写回缓存;
* 重建失败时降级为删除缓存(下次查询回源),并记录 warn 日志,不影响主流程。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<void>} 无返回值。
*/
async refreshStaticLockCache(warehouseId) {
const { ctx } = this;
const normalizedWarehouseId = Number(warehouseId);
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return;
}
try {
// 代次必须在回源查询之前递增:并发中的旧回源读到代次变化会放弃写缓存
await this._bumpStaticLockGeneration(normalizedWarehouseId);
await this._loadStaticLockCache(normalizedWarehouseId);
} catch (error) {
ctx.logger.warn(`[StockCheckStaticLock] 重建静态锁定缓存失败 warehouse=${normalizedWarehouseId}: ${error && error.message}`);
await this.clearStaticLockCache(normalizedWarehouseId);
}
}
/**
* 构建锁定代次缓存键(状态流转时递增,用于回源前后一致性校验)。
*
* @param {number} warehouseId 仓库ID。
* @return {string} 代次键。
*/
_staticLockGenerationKey(warehouseId) {
return `${STATIC_LOCK_GENERATION_KEY_PREFIX}${Number(warehouseId) || 0}`;
}
/**
* 读取锁定代次(Redis 不可用时回退进程内计数)。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<number>} 代次值(无记录为 0)。
*/
async _readStaticLockGeneration(warehouseId) {
const { ctx } = this;
const normalizedWarehouseId = Number(warehouseId);
const redis = ctx.app.redis && typeof ctx.app.redis.get === 'function' ? ctx.app.redis.get('cache') : null;
if (redis && typeof redis.get === 'function') {
try {
const value = await redis.get(this._staticLockGenerationKey(normalizedWarehouseId));
if (value !== null && value !== undefined) {
return Number(value) || 0;
}
} catch (error) {
ctx.logger.warn(`[StockCheckStaticLock] 读取锁定代次失败,回退进程内计数 warehouse=${normalizedWarehouseId}: ${error && error.message}`);
}
}
return STATIC_LOCK_GENERATION_LOCAL.get(normalizedWarehouseId) || 0;
}
/**
* 递增锁定代次(Redis INCR 原子递增;不可用时退化为进程内计数)。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<number>} 递增后的代次值。
*/
async _bumpStaticLockGeneration(warehouseId) {
const { ctx } = this;
const normalizedWarehouseId = Number(warehouseId);
const redis = ctx.app.redis && typeof ctx.app.redis.get === 'function' ? ctx.app.redis.get('cache') : null;
if (redis && typeof redis.incr === 'function') {
try {
const value = await redis.incr(this._staticLockGenerationKey(normalizedWarehouseId));
return Number(value) || 0;
} catch (error) {
ctx.logger.warn(`[StockCheckStaticLock] 递增锁定代次失败,回退进程内计数 warehouse=${normalizedWarehouseId}: ${error && error.message}`);
}
}
const nextValue = (STATIC_LOCK_GENERATION_LOCAL.get(normalizedWarehouseId) || 0) + 1;
STATIC_LOCK_GENERATION_LOCAL.set(normalizedWarehouseId, nextValue);
return nextValue;
}
/**
* 删除静态盘点锁定缓存(Redis 与进程内缓存同时清理;下次查询回源重建)。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<void>} 无返回值。
*/
async clearStaticLockCache(warehouseId) {
const { ctx } = this;
const normalizedWarehouseId = Number(warehouseId);
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return;
}
try {
await ctx.app.delCacheAsync(this._staticLockCacheKey(normalizedWarehouseId));
} catch (error) {
ctx.logger.warn(`[StockCheckStaticLock] 清除静态锁定缓存失败 warehouse=${normalizedWarehouseId}: ${error && error.message}`);
}
}
/**
* 判断指定商品当前是否处于静态盘点锁定中(供库存操作前置校验,读缓存)。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number|Array<number>} params.stockId 商品库存ID(单值或数组)。
* @return {Promise<Object>} { locked, locked_stock_ids, rows, cached };
* locked=true 表示至少有一个商品在锁定集合中;rows 仅返回命中的商品行。
*/
async isStockStaticLocked(params = {}) {
const { warehouseId, stockId } = params;
const stockIds = this._normalizeIdList(stockId);
if (stockIds.length === 0) {
throw this.createBusinessError('商品ID不能为空');
}
const lockList = await this.staticLockList({ warehouseId });
const stockIdSet = new Set(stockIds.map(id => Number(id)));
const hitRows = lockList.rows.filter(row => stockIdSet.has(Number(row.stock_id)));
return {
locked: hitRows.length > 0,
locked_stock_ids: hitRows.map(row => Number(row.stock_id)),
rows: hitRows,
cached: lockList.cached,
};
}
/**
* 查询商品是否被静态盘点锁定,并生成可直接返回/抛出的冲突文案(供库存操作前置拦截)。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID。
* @param {number|Array<number>} params.stockIds 商品库存ID(单值或数组)。
* @param {string} [params.actionLabel] 被禁止的操作名(用于文案,如「移库」「分配储位」)。
* @return {Promise<Object>} { locked, rows, message };locked=false 时 rows 为空数组、message 为空串。
*/
async getStaticLockConflict(params = {}) {
const { warehouseId, stockIds, actionLabel } = params;
const normalizedStockIds = this._normalizeIdList(stockIds);
if (normalizedStockIds.length === 0) {
return { locked: false, rows: [], message: '' };
}
const result = await this.isStockStaticLocked({ warehouseId, stockId: normalizedStockIds });
if (!result.locked) {
return { locked: false, rows: [], message: '' };
}
const actionText = String(actionLabel || '该操作').trim() || '该操作';
const detailText = result.rows
.map(row => {
const stockText = row.item_code ? `${row.item_code}(${row.stock_id})` : String(row.stock_id);
const checkNos = (Array.isArray(row.check_nos) ? row.check_nos : []).filter(Boolean).join('/');
return checkNos ? `${stockText} 盘点单 ${checkNos}` : stockText;
})
.join(';');
return {
locked: true,
rows: result.rows,
message: `商品正在静态盘点中,禁止${actionText}:${detailText}`,
};
}
/**
* 收集任务商品范围明细覆盖的商品ID(去重升序),用于完成/释放锁定追溯。
*
* @param {number} checkId 盘点任务ID。
* @return {Promise<Array<number>>} 商品库存ID列表(升序;库位任务为空数组)。
*/
async _collectGoodsStockIds(checkId) {
const { ctx } = this;
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { check_id: Number(checkId), scope_type: 'goods' },
attributes: [ 'stock_id' ],
raw: true,
});
return [ ...new Set(detailRows
.map(row => Number(row.stock_id))
.filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]
.sort((left, right) => left - right);
}
/**
* 拉取盘点明细结果(后台查看明细口径,仅展示盘点前/盘点后明细使用)。
* 任务尚无作业记录(盘点前,如 created/rejected/submitted 待提交状态)时,rows 直接返回
* wms_stock_check_detail 明细范围行原始数据(商品/库位/商品快照/账面快照),供后台查看盘点范围;
* 存在作业记录后,商品范围(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 };无作业记录时 rows=wms_stock_check_detail 明细范围行
* (id/check_id/warehouse_id/scope_type/stock_id/location_id/location_code/item_code/item_name/spec/
* batch_no/system_quantity/remark/created_at/updated_at,total=明细行数,check 为主表信息);
* 有作业记录时:商品范围按商品聚合(一个商品一行):
* 行含商品快照(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)(=可用数量,不含锁定待出库),行级 checked_quantity 为行内合计、
* diff_quantity 为行内各商品差异代数和;
* 未知商品单独输出行级 unknown_items [{ barcode, item_name, checked_quantity }]
* (无账面,差异 = 实盘 - 0 = 盘盈,已计入行级 checked_quantity/diff_quantity/is_diff)。
* @throws {Error} 任务不存在时抛出业务错误(错误码 400)。
*/
async result(params = {}) {
const { warehouseId, id } = params;
const { ctx } = this;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { check_id: checkId, warehouse_id: Number(warehouseId) },
order: [[ 'id', 'ASC' ]],
raw: true,
});
const records = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkId, warehouse_id: Number(warehouseId) },
order: [[ 'id', 'ASC' ]],
raw: true,
});
// 盘点前(尚无作业记录,如待提交状态):直接返回明细范围行(wms_stock_check_detail),
// 供后台查看盘点范围明细(本接口不再作为盘点作业数据提供)
if (records.length === 0) {
return {
check: this._formatCheckRow(check.get({ plain: true })),
rows: detailRows,
total: detailRows.length,
};
}
// 挂载作业记录图片(FileReference business_type=stock_check_record,与收货 receivingItem 口径一致)
await this._attachRecordImages(records);
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: formattedCheck,
rows,
total: rows.length,
};
}
/**
* 为盘点作业记录挂载图片列表(图片独立维护,仿收货 receivingItem 口径)。
* 查询 wms_file_reference(business_type=stock_check_record,business_id in 记录ID)并关联
* wms_file 取 file_url,每条记录挂载 images: [{ id: file_id, url }],无图片返回空数组;
* 直接修改传入记录对象的 images 字段,无返回值。
*
* @param {Array<Object>} records 作业记录原始行(每条需含 id 字段)。
* @return {Promise<void>} 无返回值。
*/
async _attachRecordImages(records = []) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const normalizedRecords = Array.isArray(records) ? records : [];
const recordIds = [ ...new Set(normalizedRecords
.map(record => Number(record && record.id))
.filter(recordId => Number.isInteger(recordId) && recordId > 0)) ];
if (recordIds.length === 0) {
return;
}
const imageRefs = await ctx.model.FileReference.findAll({
where: {
business_type: 'stock_check_record',
business_id: { [Op.in]: recordIds.map(String) },
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
}],
order: [[ 'display_order', 'ASC' ], [ 'id', 'ASC' ]],
});
const imageMap = new Map();
for (const ref of imageRefs) {
const businessId = String(ref.business_id);
if (!imageMap.has(businessId)) {
imageMap.set(businessId, []);
}
imageMap.get(businessId).push({
id: ref.file_id,
url: ref.file ? ref.file.file_url : null,
});
}
for (const record of normalizedRecords) {
record.images = imageMap.get(String(record.id)) || [];
}
}
/**
* 构建盘点明细聚合行。
* 商品范围(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>>} 格式化后的聚合行列表(按首条明细 id 升序)。
*/
async _buildDetailAggregations(params = {}) {
const { detailRows, recordRows } = params;
const { ctx } = this;
const { Op, literal } = ctx.app.Sequelize;
// 按明细聚合作业记录
const recordsByDetail = new Map();
for (const record of recordRows) {
const detailRowId = Number(record.detail_id);
if (!recordsByDetail.has(detailRowId)) {
recordsByDetail.set(detailRowId, []);
}
recordsByDetail.get(detailRowId).push(record);
}
// 分拣:商品范围行按 stock_id 分组合并(按商品盘点一行一商品),库位范围行按明细行处理
const locationRows = [];
const goodsGroups = new Map();
for (const detailRow of detailRows) {
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
if (scopeType === 'location') {
locationRows.push(detailRow);
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));
}
}
}
let stockMap = new Map();
if (stockIds.size > 0) {
const stockRows = await ctx.model.StockWarehouse.findAll({
where: { id: { [Op.in]: [ ...stockIds ] } },
attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ],
raw: true,
});
stockMap = new Map(stockRows.map(item => [ Number(item.id), item ]));
}
// 库位行账面:wms_storage 按 (space_id, stock_id) SUM(可用数量)
const storageQuantityMap = new Map();
if (locationRows.length > 0 && stockIds.size > 0) {
const locationIds = [ ...new Set(locationRows
.filter(row => row.location_id)
.map(row => Number(row.location_id))) ];
if (locationIds.length > 0) {
const storageRows = await ctx.model.Storage.findAll({
where: {
space_id: { [Op.in]: locationIds },
stock_id: { [Op.in]: [ ...stockIds ] },
},
attributes: [
'space_id',
'stock_id',
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
group: [ 'space_id', 'stock_id' ],
raw: true,
});
for (const storageRow of storageRows) {
storageQuantityMap.set(
`${Number(storageRow.space_id)}_${Number(storageRow.stock_id)}`,
Number(storageRow.totalQuantity) || 0
);
}
}
}
// 商品范围:按商品合并输出(账面快照按库位明细行汇总,实盘按作业记录聚合)
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);
}
/**
* 将同商品的多个库位明细行合并格式化为一条商品聚合输出行(按商品盘点一行一商品)。
* 行含商品快照 + 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 保持只输出已知商品。
*
* @param {Object} params 格式化参数。
* @param {Object} params.detailRow 明细原始行。
* @param {Map<number, Array<Object>>} params.recordsByDetail 按明细ID分组的作业记录。
* @param {Map<number, Object>} params.stockMap 商品快照映射。
* @param {Map<string, number>} params.storageQuantityMap 库位商品账面数量映射(键 `${space_id}_${stock_id}`)。
* @return {Object} 格式化后的明细行。
*/
async _formatDetailAggregationRow(params = {}) {
const { detailRow, recordsByDetail, stockMap, storageQuantityMap } = params;
const { ctx } = this;
const { literal } = ctx.app.Sequelize;
const detailRowId = Number(detailRow.id);
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
const detailRecords = recordsByDetail.get(detailRowId) || [];
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;
// 按库位聚合作业记录(库位为空归入"无库位"分组,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;
}
const locations = [ ...locationGroups.values() ]
.sort((left, right) => left.first_record_id - right.first_record_id)
.map(locationGroup => ({
location_id: locationGroup.location_id,
location_code: locationGroup.location_code,
quantity: locationGroup.quantity,
}));
// 未知商品(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,
}));
const base = {
...detailRow,
scope_type: scopeType,
location_codes: locationCodes,
checkers,
last_checked_at: lastCheckedAt,
records: detailRecords,
locations,
};
// 库位范围行:按商品聚合记录,账面从 wms_storage 取(location_id 为空时账面按 0);
// 空库位标记:无商品聚合,账面有库存即盘亏(差异 = -账面总量)
const isEmptyLocation = detailRecords.some(record => record.is_empty);
const locationId = detailRow.location_id !== null && detailRow.location_id !== undefined
? Number(detailRow.location_id)
: 0;
let locationSystemTotal = 0;
if (isEmptyLocation && locationId > 0) {
const emptyStorageRows = await ctx.model.Storage.findAll({
where: { space_id: locationId },
attributes: [[ literal('SUM(available_quantity)'), 'totalQuantity' ]],
raw: true,
});
locationSystemTotal = Number(emptyStorageRows[0] && emptyStorageRows[0].totalQuantity) || 0;
}
if (isEmptyLocation) {
return {
...base,
is_empty: true,
checked_quantity: 0,
diff_quantity: locationSystemTotal > 0 ? -locationSystemTotal : 0,
is_diff: locationSystemTotal > 0 ? 1 : 0,
status: 'checked',
stocks: [],
unknown_items: unknownItems,
};
}
const quantityByStock = new Map();
for (const record of detailRecords) {
const stockId = Number(record.stock_id);
if (!Number.isInteger(stockId) || stockId <= 0) {
continue;
}
const agg = quantityByStock.get(stockId) || { checked: 0 };
agg.checked += Number(record.quantity) || 0;
quantityByStock.set(stockId, agg);
}
let checkedQuantity = 0;
let diffQuantitySum = 0;
let hasDiff = false;
const stocks = [ ...quantityByStock.keys() ]
.sort((left, right) => left - right)
.map(stockId => {
const agg = quantityByStock.get(stockId);
const stock = stockMap.get(stockId) || {};
const systemQuantity = locationId > 0
? (storageQuantityMap.get(`${locationId}_${stockId}`) || 0)
: 0;
const diffQuantity = agg.checked - systemQuantity;
checkedQuantity += agg.checked;
diffQuantitySum += diffQuantity;
if (diffQuantity !== 0) {
hasDiff = true;
}
return {
stock_id: stockId,
item_code: stock.item_code || null,
item_name: stock.item_name || null,
system_quantity: systemQuantity,
checked_quantity: agg.checked,
diff_quantity: diffQuantity,
};
});
// 未知商品无账面:实盘全部计入行级已盘数量与盘盈差异(必然差异)
for (const agg of unknownByBarcode.values()) {
checkedQuantity += agg.checked;
diffQuantitySum += agg.checked;
if (agg.checked > 0) {
hasDiff = true;
}
}
return {
...base,
is_empty: false,
stocks,
unknown_items: unknownItems,
checked_quantity: detailRecords.length > 0 ? checkedQuantity : null,
diff_quantity: detailRecords.length > 0 ? diffQuantitySum : null,
is_diff: hasDiff ? 1 : 0,
status: detailRecords.length > 0 ? 'checked' : 'unchecked',
};
}
/**
* 按条码解析系统商品ID(未知商品上报回填用)。
* 查询 wms_stock_barcodes 按 barcode + warehouse_id 匹配条码,再校验 wms_stock_warehouse
* 中该商品确实属于本仓库(StockBarcode 关联 StockWarehouse),命中返回 stock_id,未命中返回 0。
*
* @param {string} barcodeValue 扫描到的条码/编码。
* @param {number} warehouseId 仓库ID。
* @return {Promise<number>} 命中的库存商品ID(wms_stock_warehouse.id),未命中返回 0。
*/
async _resolveStockIdByBarcode(barcodeValue, warehouseId) {
const { ctx } = this;
const normalizedBarcode = String(barcodeValue || '').trim();
if (!normalizedBarcode) {
return 0;
}
const barcodeRow = await ctx.model.StockBarcode.findOne({
where: { barcode: normalizedBarcode, warehouse_id: Number(warehouseId) },
attributes: [ 'stock_id' ],
raw: true,
});
const matchedStockId = barcodeRow ? Number(barcodeRow.stock_id) : 0;
if (!Number.isInteger(matchedStockId) || matchedStockId <= 0) {
return 0;
}
const stockRow = await ctx.model.StockWarehouse.findOne({
where: { id: matchedStockId, warehouse_id: Number(warehouseId) },
attributes: [ 'id' ],
raw: true,
});
return stockRow ? matchedStockId : 0;
}
/**
* 按库位编码解析库位ID(仅命中分区存在且未删除的有效库位行)。
* 同仓库同编码可能同时存在多条库位(历史重复库位、分区已删除的无头库位,
* 唯一索引含 deleted_at 且 NULL 不去重),此处取稳定口径:
* 优先该商品有启用库存的库位行,其次 ID 最小的有效行。
*
* @param {number} warehouseId 仓库ID。
* @param {string} locationCode 库位编码。
* @param {number} [stockId] 商品库存ID(wms_stock_warehouse.id,用于优先命中库存所在库位)。
* @return {Promise<number>} 库位ID,未命中返回 0。
*/
async _resolveLocationIdByCode(warehouseId, locationCode, stockId) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const normalizedCode = String(locationCode || '').trim();
if (!normalizedCode) {
return 0;
}
const spaceRows = await ctx.model.LocationSpace.findAll({
where: {
warehouse_id: Number(warehouseId),
space_code: normalizedCode,
},
attributes: [ 'id' ],
// 库位有效性:zone 必须存在且未删除(无头库位不参与匹配)
include: [{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [],
required: true,
}],
order: [[ 'id', 'ASC' ]],
raw: true,
});
const candidateIds = (Array.isArray(spaceRows) ? spaceRows : [])
.map(row => Number(row && row.id))
.filter(id => Number.isInteger(id) && id > 0);
if (candidateIds.length === 0) {
return 0;
}
if (candidateIds.length === 1 || !(Number(stockId) > 0)) {
return candidateIds[0];
}
const storageRow = await ctx.model.Storage.findOne({
where: {
warehouse_id: Number(warehouseId),
stock_id: Number(stockId),
space_id: { [Op.in]: candidateIds },
is_enabled: 1,
},
attributes: [ 'space_id' ],
raw: true,
});
const storageSpaceId = storageRow ? Number(storageRow.space_id) : 0;
return storageSpaceId > 0 ? storageSpaceId : candidateIds[0];
}
/**
* 盘点作业上报(覆盖式)。
* 仅 approved/checking 状态允许;商品明细行固定上报明细商品(入参商品不一致报错),
* 库位明细行必须指定商品且商品必须属于本仓库,库位以明细库位为准(入参库位不一致报错);
* 同明细 + 同商品 + 同库位编码重复上报时更新已有记录的
* quantity/checker_id/checker_name/checked_at(保留原 location_id,若本次新匹配到 location_id 则回填),
* 不再新增;未传库位编码时以 space_id 对应库位的编码落库;
* **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 至少传一项):
* - 传了 stock_id:按已知商品走现有逻辑(本仓库校验等);
* - 未传 stock_id 但传了 barcode:先按条码匹配系统商品(wms_stock_barcodes 按
* barcode + 本仓库,关联 StockWarehouse 校验),命中则回填 stock_id 按已知商品处理;
* 未命中则记录 stock_id=NULL + barcode + item_name(item_name 缺省为 barcode);
* - 都未传:沿用现有报错口径(商品行缺商品信息报 400 / 库位行缺商品报 400)。
* 覆盖式查重:已知商品 where { detail_id, stock_id, location_code } 不变;
* 未知商品 where { detail_id, stock_id: null, barcode, location_code }(应用层查重,
* 唯一索引不约束 NULL 行,并发兜底逻辑对未知商品同样降级更新)。
*
* @param {Object} params 上报参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {number} params.detailId 明细ID。
* @param {string} [params.location] 库位编码(可选,仅做一致性校验;库位以 spaceId 为准)。
* @param {number} params.spaceId 库位ID(wms_location_space.id,必传):必须属于本仓库且分区有效,
* 缺失报 400「缺少库位ID(space_id)」;与 location 编码不一致或(库位明细行)与明细库位不一致同样 400。
* @param {number} params.quantity 实盘数量(>=0 且 <= 2147483647)。
* @param {number} [params.stockId] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。
* @param {string} [params.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品,
* 未命中记为未知商品)。
* @param {string} [params.itemName] 未知商品名称(缺省为 barcode;已知商品忽略)。
* @param {boolean} [params.is_empty] 空库位标记(仅库位盘点明细支持;标记空时商品/条码/数量均不参与)。
* @param {number} [params.checkerId] 盘点人账户ID(由方法层从上下文注入)。
* @param {string} [params.checkerName] 盘点人名称快照(由方法层从上下文注入)。
* @return {Promise<Object>} { record, detail_id, mode, total_items, checked_items, diff_items, detail_status };
* record 为作业记录全字段(含 barcode/item_name)。
* @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。
*/
/**
* 标记库位为空(库位盘点模式专属,转调 report 的空库位标记口径)。
* 仅任务范围为库位(type=location)时允许:非库位任务报 400;
* 状态仅 approved/checking;明细必须属于本任务且为库位范围行(scope_type=location)。
* 行为与 report(is_empty=true) 完全一致:写/更新空标记记录(stock_id/barcode/item_name 为空、
* quantity=0、is_empty=1)、清除该明细商品记录、主表 approved→checking、
* 重算 checked_items/diff_items/detail_status、写入操作日志。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {number} params.detailId 库位明细ID。
* @param {number} [params.checkerId] 盘点人账户ID(由方法层从上下文注入)。
* @param {string} [params.checkerName] 盘点人名称快照(由方法层从上下文注入)。
* @return {Promise<Object>} 与 report 一致:{ record, detail_id, mode, total_items, checked_items, diff_items, detail_status }。
* @throws {Error} 任务不存在、状态不允许、非库位任务、明细不存在或明细非库位行时抛出业务错误(错误码 400)。
*/
async markEmpty(params = {}) {
const { warehouseId, id, detailId, checkerId, checkerName } = params;
const checkId = Number(id);
const detailRowId = Number(detailId);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
if (!Number.isInteger(detailRowId) || detailRowId <= 0) {
throw this.createBusinessError('盘点明细ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!REPORT_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${check.status})不允许盘点作业`);
}
const normalizedType = String(check.type || '').trim();
if (normalizedType !== 'location') {
throw this.createBusinessError('仅库位盘点任务支持空库位标记');
}
// 明细必须属于本任务且为库位范围行(scope_type=location)
const detail = await this.ctx.model.StockCheckDetail.findOne({
where: { id: detailRowId, check_id: checkId, warehouse_id: Number(warehouseId) },
});
if (!detail) {
throw this.createBusinessError('盘点明细不存在');
}
if ((detail.scope_type || 'goods') !== 'location') {
throw this.createBusinessError('仅库位盘点明细支持空库位标记');
}
// 转调 report 空库位标记口径(查重/互斥/汇总/日志统一);
// report 要求必传 space_id,这里按明细库位编码解析有效库位(明细库位可能指向无头库位)
const resolvedSpaceId = await this._resolveLocationIdByCode(
Number(warehouseId),
String(detail.location_code || '').trim()
);
if (resolvedSpaceId <= 0) {
throw this.createBusinessError('盘点明细库位无效(库位不存在或所属分区已删除)');
}
return this.report({
warehouseId,
id: checkId,
detailId: detailRowId,
spaceId: resolvedSpaceId,
is_empty: true,
checkerId,
checkerName,
});
}
async report(params = {}) {
const {
warehouseId,
id,
detailId,
location,
spaceId: spaceIdInput,
quantity,
stockId,
barcode,
itemName,
is_empty: isEmptyInput,
checkerId,
checkerName,
} = params;
const { ctx } = this;
// 空库位标记:仅库位明细行支持;标记空时商品/条码/数量均不参与(数量恒为 0)
const normalizedIsEmpty = isEmptyInput === true || isEmptyInput === 'true' || isEmptyInput === 1;
const checkId = Number(id);
const detailRowId = Number(detailId);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
// detail_id 可选:goods 汇总视图行不再带明细ID,允许按 id + stock_id + space_id 反查该商品明细
let resolvedDetailRowId = Number.isInteger(detailRowId) && detailRowId > 0 ? detailRowId : 0;
const inputStockIdRaw = stockId !== undefined && stockId !== null && stockId !== ''
? Number(stockId)
: 0;
if (resolvedDetailRowId === 0 && !(Number.isInteger(inputStockIdRaw) && inputStockIdRaw > 0)) {
throw this.createBusinessError('盘点明细ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!REPORT_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${check.status})不允许盘点作业`);
}
const quantityValue = normalizedIsEmpty ? 0 : Number(quantity);
if (!normalizedIsEmpty && (!Number.isInteger(quantityValue) || quantityValue < 0)) {
throw this.createBusinessError('实盘数量必须为不小于0的整数');
}
if (!normalizedIsEmpty && quantityValue > REPORT_MAX_QUANTITY) {
throw this.createBusinessError(`实盘数量不能超过 ${REPORT_MAX_QUANTITY}`);
}
// 明细定位:传了 detail_id 直接用;未传时按 id + stock_id + space_id 反查该商品的库位明细
// (goods 汇总视图行不再输出明细ID,前端可只回传商品与库位)
let detail = null;
if (resolvedDetailRowId > 0) {
detail = await ctx.model.StockCheckDetail.findOne({
where: { id: resolvedDetailRowId, check_id: checkId, warehouse_id: Number(warehouseId) },
});
if (!detail) {
throw this.createBusinessError('盘点明细不存在');
}
} else {
const candidateSpaceId = Number(spaceIdInput);
const detailScope = {
check_id: checkId,
warehouse_id: Number(warehouseId),
stock_id: inputStockIdRaw,
};
if (Number.isInteger(candidateSpaceId) && candidateSpaceId > 0) {
detail = await ctx.model.StockCheckDetail.findOne({
where: { ...detailScope, location_id: candidateSpaceId },
});
}
if (!detail) {
detail = await ctx.model.StockCheckDetail.findOne({
where: detailScope,
order: [[ 'id', 'ASC' ]],
});
}
if (!detail) {
throw this.createBusinessError('盘点明细不存在(该商品不在本任务盘点范围内,或库位盘点任务需传 detail_id)');
}
resolvedDetailRowId = Number(detail.id);
}
const scopeType = (detail.scope_type || 'goods') === 'location' ? 'location' : 'goods';
if (normalizedIsEmpty && scopeType !== 'location') {
throw this.createBusinessError('仅库位盘点明细支持空库位标记');
}
const inputStockId = stockId !== undefined && stockId !== null && stockId !== ''
? Number(stockId)
: 0;
const inputBarcode = barcode !== undefined && barcode !== null && String(barcode).trim() !== ''
? String(barcode).trim()
: '';
// 未知商品名称:仅未知商品记录落库,缺省为条码
const inputItemName = itemName !== undefined && itemName !== null && String(itemName).trim() !== ''
? String(itemName).trim()
: '';
// 必填库位ID(wms_location_space.id):必须属于本仓库且所属分区有效。
// 不允许按编码猜库位(同仓库同编码可能有多条历史重复/无头库位),缺失即 400 由调用方补传
const inputSpaceId = spaceIdInput !== undefined && spaceIdInput !== null && spaceIdInput !== ''
? Number(spaceIdInput)
: 0;
if (!Number.isInteger(inputSpaceId) || inputSpaceId <= 0) {
throw this.createBusinessError('缺少库位ID(space_id),请传取回数据中的 space_id');
}
const inputLocationRow = await ctx.model.LocationSpace.findOne({
where: { id: inputSpaceId, warehouse_id: Number(warehouseId) },
attributes: [ 'id', 'space_code' ],
include: [{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [],
required: true,
}],
raw: true,
});
if (!inputLocationRow) {
throw this.createBusinessError('上报库位不存在、不属于当前仓库或所属分区已删除');
}
const inputLocationCode = String(inputLocationRow.space_code || '').trim();
if (!inputLocationCode) {
throw this.createBusinessError('上报库位的库位编码为空,无法上报');
}
// 入参库位编码(可选):仅做一致性校验,库位以 space_id 对应的库位行为准
const inputLocationCodeParam = location !== undefined && location !== null && String(location).trim() !== ''
? String(location).trim()
: '';
let normalizedStockId = 0;
let normalizedBarcode = null;
let normalizedItemName = null;
let isUnknownGoods = false;
let locationCode = '';
let locationId = null;
if (scopeType === 'goods') {
// 商品行:商品固定为明细商品,入参传了不同商品直接报错
normalizedStockId = Number(detail.stock_id);
if (!Number.isInteger(normalizedStockId) || normalizedStockId <= 0) {
throw this.createBusinessError('盘点明细缺少商品信息');
}
if (inputStockId > 0 && inputStockId !== normalizedStockId) {
throw this.createBusinessError('上报商品与盘点明细商品不一致');
}
if (inputStockId <= 0 && inputBarcode) {
// 仅传条码:先尝试回填系统商品;命中且与明细商品一致按已知商品处理,未命中记为未知商品
const matchedStockId = await this._resolveStockIdByBarcode(inputBarcode, Number(warehouseId));
if (matchedStockId > 0) {
if (matchedStockId !== normalizedStockId) {
throw this.createBusinessError('上报商品与盘点明细商品不一致');
}
normalizedBarcode = inputBarcode;
} else {
isUnknownGoods = true;
normalizedStockId = 0;
normalizedBarcode = inputBarcode;
normalizedItemName = inputItemName || inputBarcode;
}
} else if (inputBarcode) {
normalizedBarcode = inputBarcode;
}
// 库位以 space_id 对应的库位行为准(必填);location 编码仅做一致性校验
if (inputLocationCodeParam && inputLocationCodeParam !== inputLocationCode) {
throw this.createBusinessError('上报库位编码与库位ID不一致');
}
locationCode = inputLocationCode;
locationId = Number(inputLocationRow.id);
} else {
// 库位行:以明细库位为准
locationCode = String(detail.location_code || '').trim();
if (!locationCode) {
throw this.createBusinessError('盘点明细缺少库位信息');
}
if (inputLocationCodeParam && inputLocationCodeParam !== locationCode) {
throw this.createBusinessError('上报库位与盘点明细库位不一致');
}
if (inputLocationCode !== locationCode) {
throw this.createBusinessError('上报库位与盘点明细库位不一致');
}
locationId = Number(inputLocationRow.id);
if (normalizedIsEmpty) {
// 空库位标记:不要求商品,stock_id/barcode/item_name 均为空、quantity=0
normalizedStockId = 0;
normalizedBarcode = null;
normalizedItemName = null;
isUnknownGoods = false;
} else if (inputStockId <= 0 && !inputBarcode) {
throw this.createBusinessError('按库位盘点时必须指定商品');
} else if (inputStockId <= 0 && inputBarcode) {
// 仅传条码:先尝试回填系统商品;命中按已知商品处理,未命中记为未知商品
const matchedStockId = await this._resolveStockIdByBarcode(inputBarcode, Number(warehouseId));
if (matchedStockId > 0) {
normalizedStockId = matchedStockId;
normalizedBarcode = inputBarcode;
} else {
isUnknownGoods = true;
normalizedStockId = 0;
normalizedBarcode = inputBarcode;
normalizedItemName = inputItemName || inputBarcode;
}
} else {
// 传了 stock_id:现有校验口径(商品必须属于本仓库)
const stock = await ctx.model.StockWarehouse.findOne({
where: {
id: inputStockId,
warehouse_id: Number(warehouseId),
},
attributes: [ 'id' ],
raw: true,
});
if (!stock) {
throw this.createBusinessError('上报商品不属于本仓库');
}
normalizedStockId = inputStockId;
if (inputBarcode) {
normalizedBarcode = inputBarcode;
}
}
}
// 静态盘点要求「该商品已完全拣货」:商品仍有锁定量说明存在已分配储位但尚未拣出的在途出库,
// 此时上报的实盘数与账面快照之间会夹着这批货,差异不可信,直接拒绝上报
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 对应库位)更新已有记录,
// 依赖唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全;
// 未知商品唯一索引不约束 NULL 行,按同明细 + 同条码 + 同库位编码在应用层查重;
// 空库位标记按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新
const existingRecordWhere = normalizedIsEmpty
? {
detail_id: resolvedDetailRowId,
is_empty: true,
location_code: locationCode,
}
: (isUnknownGoods
? {
detail_id: resolvedDetailRowId,
stock_id: null,
barcode: normalizedBarcode,
location_code: locationCode,
}
: {
detail_id: resolvedDetailRowId,
stock_id: normalizedStockId,
location_code: locationCode,
});
const existingRecord = await ctx.model.StockCheckRecord.findOne({
where: existingRecordWhere,
});
const normalizedCheckerId = checkerId ? Number(checkerId) : null;
const normalizedCheckerName = checkerName || null;
let record = null;
let mode = 'created';
if (existingRecord) {
// 保留原 location_id,若本次新匹配到 location_id 则回填
const resolvedLocationId = locationId !== null && locationId !== undefined
? locationId
: existingRecord.location_id;
const updatePatch = {
quantity: quantityValue,
checker_id: normalizedCheckerId,
checker_name: normalizedCheckerName,
checked_at: now,
location_id: resolvedLocationId,
};
if (normalizedBarcode !== null) {
updatePatch.barcode = normalizedBarcode;
}
if (normalizedItemName !== null) {
updatePatch.item_name = normalizedItemName;
}
await existingRecord.update(updatePatch);
record = existingRecord.get({ plain: true });
mode = 'updated';
} else {
try {
const createdRecord = await ctx.model.StockCheckRecord.create({
check_id: checkId,
warehouse_id: Number(warehouseId),
detail_id: resolvedDetailRowId,
stock_id: (isUnknownGoods || normalizedIsEmpty) ? null : normalizedStockId,
barcode: normalizedBarcode,
item_name: normalizedItemName,
is_empty: normalizedIsEmpty,
location_id: locationId,
location_code: locationCode,
quantity: quantityValue,
checker_id: normalizedCheckerId,
checker_name: normalizedCheckerName,
checked_at: now,
});
record = createdRecord.get({ plain: true });
} catch (error) {
// 并发下撞唯一索引 uk_detail_stock_location(已知商品):降级为更新已有记录,避免调用方收到 500;
// 未知商品唯一索引不约束 NULL 行,同样按查重条件降级更新兜底
const isDuplicate = (error && error.name === 'SequelizeUniqueConstraintError')
|| (error && error.original && error.original.code === 'ER_DUP_ENTRY');
if (!isDuplicate) {
throw error;
}
const latestRecord = await ctx.model.StockCheckRecord.findOne({
where: existingRecordWhere,
});
if (!latestRecord) {
throw error;
}
const resolvedLocationId = locationId !== null && locationId !== undefined
? locationId
: latestRecord.location_id;
const updatePatch = {
quantity: quantityValue,
checker_id: normalizedCheckerId,
checker_name: normalizedCheckerName,
checked_at: now,
location_id: resolvedLocationId,
};
if (normalizedBarcode !== null) {
updatePatch.barcode = normalizedBarcode;
}
if (normalizedItemName !== null) {
updatePatch.item_name = normalizedItemName;
}
await latestRecord.update(updatePatch);
record = latestRecord.get({ plain: true });
mode = 'updated';
}
}
// 空库位标记与商品记录互斥:确认库位为空后清除该明细下商品记录;上报商品后清除该明细下空标记
if (normalizedIsEmpty) {
await ctx.model.StockCheckRecord.destroy({
where: { detail_id: resolvedDetailRowId, is_empty: false },
});
} else {
await ctx.model.StockCheckRecord.destroy({
where: { detail_id: resolvedDetailRowId, is_empty: true },
});
}
// 主表 approved → checking 自动转移;盘点开始时间=第一个盘点明细写入的时间
// (start_time 为空则补写,保证任何状态下首个明细落盘时间都被记录)
const checkPatch = {};
if (check.status === 'approved') {
checkPatch.status = 'checking';
}
if (!check.start_time) {
checkPatch.start_time = now;
}
if (Object.keys(checkPatch).length > 0) {
await check.update(checkPatch);
}
// 重算 checked_items / diff_items / detail_status
const summary = await this._recalcCheckSummary(checkId);
// 写入操作日志(失败不影响主流程)
// message 补充库位编码/库位ID(原 message 只有明细与数量,事后无法定位是哪个库位被上报),
// before_changes 落明细快照与本次上报字段,供追溯
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_REPORT',
operationAction: 'UPDATE',
changeSummary: normalizedIsEmpty
? `盘点作业上报:明细 ${resolvedDetailRowId} 确认库位 ${locationCode || '未指定'} 为空`
: `盘点作业上报:明细 ${resolvedDetailRowId},库位 ${locationCode || '未指定'},实盘 ${quantityValue}${normalizedBarcode ? `,条码 ${normalizedBarcode}` : ''}(${mode === 'created' ? '新增' : '更新'})`,
beforeChanges: {
check_no: check.check_no,
detail_id: resolvedDetailRowId,
scope_type: scopeType,
stock_id: normalizedStockId > 0 ? normalizedStockId : null,
location_code: locationCode || '',
location_id: locationId !== null && locationId !== undefined ? Number(locationId) : null,
detail_location_code: String(detail.location_code || '').trim() || null,
detail_location_id: detail.location_id !== null && detail.location_id !== undefined
? Number(detail.location_id)
: null,
quantity: quantityValue,
barcode: normalizedBarcode,
is_unknown_goods: isUnknownGoods,
is_empty: normalizedIsEmpty,
mode,
record_id: Number(record && record.id) || null,
},
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
checkNo: check.check_no,
detailId: resolvedDetailRowId,
locationCode,
locationId: locationId !== null && locationId !== undefined ? Number(locationId) : null,
quantity: quantityValue,
barcode: normalizedBarcode,
isUnknownGoods,
is_empty: normalizedIsEmpty,
mode,
message: normalizedIsEmpty
? `盘点作业上报:明细 ${resolvedDetailRowId} 确认库位 ${locationCode || '未指定'}${locationId ? `(#${locationId})` : ''} 为空`
: `盘点作业上报:明细 ${resolvedDetailRowId},库位 ${locationCode || '未指定'}${locationId ? `(#${locationId})` : ''},实盘 ${quantityValue}`,
},
});
return {
record,
detail_id: resolvedDetailRowId,
mode,
total_items: summary.total_items,
checked_items: summary.checked_items,
diff_items: summary.diff_items,
detail_status: summary.detail_status,
};
}
/**
* 拉取盘点作业记录列表。
* 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;rows 每条为作业记录全字段 +
* 商品快照列(item_code/item_name,从明细表查得)按记录 id 倒序;
* 未知商品(stock_id 为空)商品编码列显示扫描条码(barcode)、名称列显示上报名称快照(item_name);
* 每条记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径)。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} [params.id] 盘点任务ID(可选)。
* @param {number} [params.detailId] 明细ID(可选)。
* @param {Object} [params.pagination] 分页参数。
* @return {Promise<Object>} { rows, total, page, pageSize };rows 每条含 barcode/item_name 与
* images: [{ id: file_id, url }]。
* @throws {Error} 未传任务ID或明细ID时抛出业务错误(错误码 400)。
*/
async recordList(params = {}) {
const { warehouseId, id, detailId, pagination = {} } = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const checkId = id !== undefined && id !== null && id !== '' ? Number(id) : 0;
const normalizedDetailId = detailId !== undefined && detailId !== null && detailId !== '' ? Number(detailId) : 0;
const hasCheckId = Number.isInteger(checkId) && checkId > 0;
const hasDetailId = Number.isInteger(normalizedDetailId) && normalizedDetailId > 0;
if (!hasCheckId && !hasDetailId) {
throw this.createBusinessError('请至少提供盘点任务ID或明细ID');
}
const page = Math.max(1, Number(pagination.page) || 1);
const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20));
const where = { warehouse_id: Number(warehouseId) };
if (hasCheckId) {
where.check_id = checkId;
}
if (hasDetailId) {
where.detail_id = normalizedDetailId;
}
const { count, rows } = await ctx.model.StockCheckRecord.findAndCountAll({
where,
order: [[ 'id', 'DESC' ]],
offset: (page - 1) * pageSize,
limit: pageSize,
raw: true,
});
// 挂载作业记录图片(FileReference business_type=stock_check_record,与收货 receivingItem 口径一致)
await this._attachRecordImages(rows);
// 商品快照列从明细表补齐(未命中 getStockDetails 时兜底)
const detailIds = [ ...new Set(rows.map(row => Number(row.detail_id))) ];
let itemByDetailId = new Map();
if (detailIds.length > 0) {
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { id: { [Op.in]: detailIds } },
attributes: [ 'id', 'item_code', 'item_name', 'spec' ],
raw: true,
});
itemByDetailId = new Map(detailRows.map(item => [ Number(item.id), item ]));
}
// 商品基础信息批量取(与 workData 口径一致:getStockDetails 带缓存)+ 货主名映射
const stockIds = [ ...new Set(rows
.map(row => Number(row.stock_id))
.filter(stockId => Number.isInteger(stockId) && stockId > 0)) ];
let stockDetailMap = new Map();
if (stockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, {
warehouseId: Number(warehouseId),
});
stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ]));
}
const storeIds = [ ...stockDetailMap.values() ]
.map(item => Number(item.store_id))
.filter(storeId => Number.isInteger(storeId) && storeId > 0);
const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId);
const formattedRows = rows.map(row => {
const item = itemByDetailId.get(Number(row.detail_id)) || {};
const recordStockId = Number(row.stock_id);
const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0;
const stockDetail = isUnknownGoods ? {} : (stockDetailMap.get(recordStockId) || {});
const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : [];
const storeId = !isUnknownGoods && stockDetail.store_id != null ? Number(stockDetail.store_id) : null;
return {
...row,
// 空串表示"无库位"分组,接口返回口径统一为 null
location_code: String(row.location_code || '').trim() !== '' ? row.location_code : null,
// 未知商品(stock_id 为空):商品编码列显示扫描条码、名称列显示上报名称快照,无商品/货主信息;
// 已知商品按 workData 口径:商品信息批量取自 getStockDetails(未命中回退明细商品快照),
// 货主名经 _resolveStoreNameMap 解析
item_code: isUnknownGoods
? (String(row.barcode || '').trim() || null)
: (stockDetail.item_code || item.item_code || null),
item_name: isUnknownGoods
? (String(row.item_name || row.barcode || '').trim() || null)
: (stockDetail.item_name || item.item_name || null),
spec: isUnknownGoods ? null : (stockDetail.sku_property || item.spec || null),
store_id: storeId,
store_name: storeId ? (storeNameMap.get(storeId) || null) : null,
barcode: isUnknownGoods
? (String(row.barcode || '').trim() || null)
: ((barcodes[0] && barcodes[0].barcode) || (String(row.barcode || '').trim() || null)),
};
});
return { rows: formattedRows, total: count, page, pageSize };
}
/**
* 拉取盘点作业数据(视图由任务类型与 is_goods 驱动,view 入参已废弃忽略)。
* 视图解析规则:
* - 任务范围为库位(type=location):一律按库位视图(location)返回,无视 view/is_goods 入参;
* - 任务范围为商品(type=goods/store):默认聚合库位视图(space);仅 is_goods=true 时按商品视图(goods)返回。
* 三视图行结构:
* location=库位结构,以任务库位范围行(scope_type=location)为列表,
* 行内挂该库位的盘点作业记录 goods 子列表(已知商品与未知商品均入内,
* has_unknown 标记是否含未知商品);
* goods=商品结构,按商品(stock_id)汇总,一个商品一行——同商品的多个库位明细行
* (scope_type=goods,按「商品+库位」拆行)合并:行内挂跨明细按库位合并的作业记录
* (locations 每项含该库位明细ID detail_id),明盘(mode=open)返回账面快照合计/已盘合计/差异,
* 盲盘(mode=blind)不返回任何数量字段;逐库位明细/汇总请调用 workDataDetail(id + stock_id);
* space=聚合库位列表,以任务商品所在库位为列表(仅按库位拣货顺序 pick_sequence 升序
* 排序,pick_priority/库位 id 不参与,同值保持库位查询顺序),行内挂该库位的任务商品与账面/实盘数量,盲盘不返回数量字段;
* 若任务无对应范围行(如 location 视图无库位范围行),rows 返回空数组。
* 分页:pagination.{page,pageSize}(与 stock_check.list 口径一致;未传或非法时默认 page=1、
* pageSize=20,上限 200),先构建全量行再按页切片;rows 为当前页行、total 为全部行数,
* 并返回 page/pageSize。
*
* 不返回任务主表信息(check)——任务信息请调用 detail;
* 响应返回 view(服务端实际解析出的视图类型 location/goods/space),供调用方判断 rows 行结构。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {boolean} [params.isGoods] 商品任务是否按商品视图返回(true=goods 视图);
* 缺省为 false(聚合库位 space 视图);库位任务无视该参数。
* @param {string} [params.keyword] 关键字(仅库位任务 location 视图生效):按行
* location_code/location_name 模糊匹配(不区分大小写)过滤后返回;非库位任务忽略。
* @param {boolean} [params.onlyAbnormal] 只看未盘和差异(可选,向后兼容):过滤在 keyword 之后、
* 分页切片之前完成,三视图均生效——location 视图仅保留 status=unchecked 或 has_unknown=true 的行;
* goods 视图仅保留未盘行(locations 均无 record_ids)或明盘差异行(is_diff=1);
* space 视图按行内 goods 子项过滤(status=unchecked 或明盘 checked_quantity≠system_quantity),
* 过滤后 goods 为空的行整体移除;盲盘无数量字段仅按未盘过滤;total 为过滤后行数。
* @param {Object} [params.pagination] 分页配置 { page, pageSize }。
* @return {Promise<Object>} { view, rows, total, page, pageSize };view 为解析后的视图类型
* (location=库位结构/goods=商品结构/space=聚合库位结构);rows 结构按解析后的视图不同:
* 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;
* 静态盘点另含 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 = {}) {
const { warehouseId, id, isGoods, keyword, pagination = {}, onlyAbnormal } = params;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!REPORT_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${STOCK_CHECK_STATUS_LABELS[check.status] || check.status})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取`);
}
// 视图解析:库位范围任务一律 location 视图(无视 view/is_goods);
// 商品范围任务默认 space(聚合库位),仅 is_goods=true 时 goods 视图
const normalizedType = String(check.type || '').trim();
const goodsViewRequested = isGoods === true || isGoods === 'true' || isGoods === 1;
const resolvedView = normalizedType === 'location'
? 'location'
: (goodsViewRequested ? 'goods' : 'space');
// 静态盘点(is_static=1)账面取明细快照,非静态取当前 wms_storage 账面
const isStatic = Number(check.is_static) === 1;
const allRows = resolvedView === 'location'
? await this._buildLocationWorkRows(warehouseId, checkId)
: (resolvedView === 'goods'
? await this._buildGoodsWorkRows(warehouseId, checkId, check.mode, isStatic)
: await this._buildSpaceWorkRows(warehouseId, checkId, check.mode, isStatic));
// keyword 过滤:仅库位任务(location 视图)启用,按行 location_code/location_name
// 模糊匹配(不区分大小写)过滤任务明细后再分页;非库位任务忽略该参数
const normalizedKeyword = String(keyword || '').trim().toLowerCase();
const keywordFilteredRows = resolvedView === 'location' && normalizedKeyword
? allRows.filter(row =>
String(row.location_code || '').toLowerCase().includes(normalizedKeyword)
|| String(row.location_name || '').toLowerCase().includes(normalizedKeyword))
: allRows;
// only_abnormal 过滤:仅保留"未盘或有差异"的行(与 keyword 过滤叠加,三视图均生效);
// 未传/非 true(false/0/空串/缺省)不过滤
const abnormalRequested = onlyAbnormal === true || onlyAbnormal === 'true' || onlyAbnormal === 1;
const filteredRows = abnormalRequested
? this._filterAbnormalWorkRows(resolvedView, keywordFilteredRows, check.mode !== 'blind')
: keywordFilteredRows;
// 分页切片:page 默认 1、pageSize 默认 20(上限 200),非法值回退默认
const page = Math.max(1, Number(pagination.page) || 1);
const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20));
const offset = (page - 1) * pageSize;
return {
view: resolvedView,
rows: filteredRows.slice(offset, offset + pageSize),
total: filteredRows.length,
page,
pageSize,
};
}
/**
* only_abnormal 过滤:仅保留"未盘或有差异"的行(workData 专用,过滤在分页切片之前完成)。
* 语义按视图区分:
* - location 视图:保留 status=unchecked(未盘)或 has_unknown=true(含未知商品记录,未知商品无账面、
* 差异=实盘-0=盘盈,视为差异)的行;空库位标记(is_empty)后 status=checked 视为已盘点、不保留;
* - goods 视图:未盘口径为 locations 均无 record_ids(无任何作业记录);差异口径为明盘 is_diff=1;
* 盲盘(isOpen=false)无数量字段,仅按未盘过滤(已盘行全部移除);
* - space 视图:按行内 goods 子项过滤——保留 status=unchecked 的子项,明盘另保留
* checked_quantity≠system_quantity(数量差异)的子项;过滤后 goods 为空的行整体移除。
*
* @param {string} view 服务端解析出的视图类型(location/goods/space)。
* @param {Array<Object>} rows 待过滤的作业数据行(keyword 过滤之后的全量行)。
* @param {boolean} isOpen 是否明盘(true=明盘含数量字段,false=盲盘无数量字段)。
* @return {Array<Object>} 过滤后的行列表。
*/
_filterAbnormalWorkRows(view, rows, isOpen) {
if (view === 'location') {
return rows.filter(row => row.status === 'unchecked' || row.has_unknown === true);
}
if (view === 'goods') {
return rows.filter(row => {
const hasRecords = Array.isArray(row.locations)
&& row.locations.some(location => location
&& Array.isArray(location.record_ids)
&& location.record_ids.length > 0);
if (!hasRecords) {
return true;
}
return isOpen && row.is_diff === 1;
});
}
// space 视图:按行内 goods 子项过滤,过滤后 goods 为空的行整体移除
return rows
.map(row => ({
...row,
goods: (Array.isArray(row.goods) ? row.goods : []).filter(item => {
if (!item) {
return false;
}
if (item.status === 'unchecked') {
return true;
}
return isOpen && Number(item.checked_quantity) !== Number(item.system_quantity);
}),
}))
.filter(row => Array.isArray(row.goods) && row.goods.length > 0);
}
/**
* 拉取盘点作业数据(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(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {number|string} [params.locationId] 库位ID(wms_location_space.id),
* 传入时只返回该库位行(兼容 location_id 写法)。
* @param {Object} [params.pagination] 分页配置 { page, pageSize }。
* @return {Promise<Object>} { view:'space', rows, total, page, pageSize }。
* @throws {Error} 任务不存在或任务状态非 approved/checking 时抛出业务错误(错误码 400)。
*/
async workDataSpaceDetails(params = {}) {
const { warehouseId, id, locationId, pagination = {} } = params;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!REPORT_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${STOCK_CHECK_STATUS_LABELS[check.status] || check.status})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取`);
}
const normalizedLocationId = Number(locationId);
const hasLocationFilter = Number.isInteger(normalizedLocationId) && normalizedLocationId > 0;
const allRows = await this._buildSpaceWorkRows(
warehouseId,
checkId,
check.mode,
Number(check.is_static) === 1
);
// 库位过滤:传入 location_id 时只保留该库位行
const filteredRows = hasLocationFilter
? allRows.filter(row => Number(row.id) === normalizedLocationId)
: allRows;
// 分页切片:page 默认 1、pageSize 默认 20(上限 200),非法值回退默认
const page = Math.max(1, Number(pagination.page) || 1);
const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20));
const offset = (page - 1) * pageSize;
return {
view: 'space',
rows: filteredRows.slice(offset, offset + pageSize),
total: filteredRows.length,
page,
pageSize,
};
}
/**
* 拉取盘点作业数据明细(单行/商品钻取版)。
*
* 两种入参与返回:
* - 库位明细(detail_id,scope_type=location):返回单行,结构与 workData location 视图单行一致
* (detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/
* checked_at/checkers/goods),便于作业端按明细ID刷新单行数据;
* - 商品(id=盘点任务ID + stock_id,或 detail_id 指向商品范围行):返回该商品的库位分行数据 +
* 汇总数据 { check_id, stock_id, 商品信息, summary, rows }:
* summary 为商品级汇总(明盘含 system_quantity 账面快照合计/checked_quantity 实盘合计/
* diff_quantity/is_diff;盲盘不含数量字段);
* rows 为该商品每个库位一行(detail_id 该库位明细ID/location_id 与同义 space_id 库位ID/
* location_code 库位编码,明盘另含 system_quantity 该库位当前账面(可用数量)/
* snapshot_quantity 该库位账面快照/locked_quantity 锁定数量/checked_quantity 该库位实盘/
* 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(由方法层从上下文注入)。
* @param {number} [params.id] 盘点任务ID(商品钻取必传,与 stockId 搭配)。
* @param {number} [params.stockId] 商品库存ID(wms_stock_warehouse.id,商品钻取必传)。
* @param {number} [params.detailId] 盘点明细ID(库位明细必传;商品明细可只传本参数,按明细商品钻取)。
* @return {Promise<Object>} 库位明细返回 location 单行;商品返回 { check_id, stock_id, 商品信息, summary, rows }。
* @throws {Error} 明细/商品不在任务范围内、任务状态非 approved/checking 时抛业务错误(错误码 400)。
*/
async workDataDetail(params = {}) {
const { ctx } = this;
const { warehouseId, detailId, id: checkIdInput, stockId } = params;
const normalizedDetailId = Number(detailId);
const normalizedCheckId = Number(checkIdInput);
const normalizedStockId = Number(stockId);
const hasDetailId = Number.isInteger(normalizedDetailId) && normalizedDetailId > 0;
const hasStockScope = Number.isInteger(normalizedCheckId) && normalizedCheckId > 0
&& Number.isInteger(normalizedStockId) && normalizedStockId > 0;
if (!hasDetailId && !hasStockScope) {
throw this.createBusinessError('请提供盘点明细ID(detail_id),或盘点任务ID(id)+商品ID(stock_id)');
}
let detailRow = null;
if (hasDetailId) {
detailRow = await ctx.model.StockCheckDetail.findOne({
where: { id: normalizedDetailId, warehouse_id: Number(warehouseId) },
raw: true,
});
if (!detailRow) {
throw this.createBusinessError('盘点明细不存在');
}
} else {
// 商品钻取:任务 + 商品 → 该商品的库位明细行(取明细 id 最小的一条定位商品与任务)
detailRow = await ctx.model.StockCheckDetail.findOne({
where: {
check_id: normalizedCheckId,
warehouse_id: Number(warehouseId),
stock_id: normalizedStockId,
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
if (!detailRow) {
throw this.createBusinessError('盘点明细不存在(该商品不在本任务盘点范围内)');
}
}
const check = await this._findCheck(warehouseId, Number(detailRow.check_id));
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!REPORT_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${STOCK_CHECK_STATUS_LABELS[check.status] || check.status})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取`);
}
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
// 商品(scope_type=goods):返回该商品的库位分行数据 + 汇总数据
if (scopeType === 'goods') {
const isStatic = Number(check.is_static) === 1;
const goodsRows = await this._buildGoodsWorkRows(
warehouseId,
Number(detailRow.check_id),
check.mode,
isStatic
);
const goodsRow = goodsRows.find(item => Number(item.stock_id) === Number(detailRow.stock_id));
if (!goodsRow) {
throw this.createBusinessError('盘点明细不存在');
}
return this._formatGoodsWorkDetail(goodsRow, check.mode, Number(detailRow.check_id));
}
// 库位明细:返回 location 视图单行
const rows = await this._buildLocationWorkRows(warehouseId, Number(detailRow.check_id));
const row = rows.find(item => Number(item.detail_id) === normalizedDetailId);
if (!row) {
throw this.createBusinessError('盘点明细不存在');
}
return row;
}
/**
* 将 goods 视图聚合行格式化为商品钻取结果:汇总数据(summary)+ 按库位分行数据(rows)。
* open(明盘)输出数量字段;blind(盲盘)不返回任何数量字段(仅库位与作业记录信息)。
*
* @param {Object} goodsRow goods 视图单行(_buildGoodsWorkRows 输出)。
* @param {string} mode 盘点方式:open=明盘/blind=盲盘。
* @param {number} checkId 盘点任务ID。
* @return {Object} { check_id, stock_id, 商品信息, summary, rows }。
*/
_formatGoodsWorkDetail(goodsRow, mode, checkId) {
const isOpen = mode !== 'blind';
const locations = Array.isArray(goodsRow.locations) ? goodsRow.locations : [];
const rows = locations.map(location => {
const detailRowId = location && location.detail_id !== undefined ? location.detail_id : null;
const row = {
// 该库位对应的盘点明细ID(商品按库位拆行,可为 null:库位已无明细但有作业记录)
detail_id: detailRowId,
// 库位ID(wms_location_space.id):location_id 与 space_id 同值,可直接回传 stock.check.report
location_id: location ? location.location_id : null,
space_id: location ? location.space_id : null,
location_code: location ? location.location_code : null,
checked_at: location ? location.checked_at : null,
checker_name: location ? location.checker_name : null,
record_ids: location && Array.isArray(location.record_ids) ? location.record_ids : [],
images: location && Array.isArray(location.images) ? location.images : [],
};
if (isOpen) {
const checkedQuantity = Number(location && location.quantity) || 0;
const snapshotQuantity = Number(location && location.snapshot_quantity) || 0;
// system_quantity 为本次参与差异计算的账面(静态=快照,非静态=当前 storage)
const bookQuantity = Number(location && location.system_quantity) || 0;
row.system_quantity = bookQuantity;
row.storage_quantity = Number(location && location.storage_quantity) || 0;
row.locked_quantity = Number(location && location.locked_quantity) || 0;
row.snapshot_quantity = snapshotQuantity;
row.checked_quantity = checkedQuantity;
row.diff_quantity = checkedQuantity - bookQuantity;
}
return row;
});
const detail = {
check_id: Number(checkId) || null,
stock_id: Number(goodsRow.stock_id) || null,
item_code: goodsRow.item_code || null,
item_name: goodsRow.item_name || null,
spec: goodsRow.spec || null,
store_id: goodsRow.store_id !== undefined ? goodsRow.store_id : null,
store_name: goodsRow.store_name || null,
barcode: goodsRow.barcode || null,
images: Array.isArray(goodsRow.images) ? goodsRow.images : [],
// 账面取值来源:静态盘点=明细快照(盘点基准冻结),非静态=当前 wms_storage 账面
is_static: Number(goodsRow.is_static) === 1 ? 1 : 0,
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,
checked_quantity: Number(goodsRow.checked_quantity) || 0,
diff_quantity: Number(goodsRow.diff_quantity) || 0,
is_diff: Number(goodsRow.is_diff) || 0,
};
}
return detail;
}
/**
* 构建 location 视图行:以任务库位范围行为列表,行内挂该库位的盘点作业记录。
* 已知商品子列表 goods 的商品基础信息(item_code/item_name/条码/图片/货主)批量取自
* stockWarehouse.getStockDetails,货主名经 _resolveStoreNameMap 解析;
* 未知商品子列表 unknown 输出记录快照字段(barcode/item_name/images,图片经 _attachRecordImages 挂载);
* 库位名称 custom_name 兜底 space_code,库位编码优先明细快照、缺失时回退库位表。
*
* @param {number} warehouseId 仓库ID。
* @param {number} checkId 盘点任务ID。
* @return {Promise<Array<Object>>} 库位视图行列表(按明细 id 升序)。
*/
async _buildLocationWorkRows(warehouseId, checkId) {
const { ctx } = this;
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'location' },
order: [[ 'id', 'ASC' ]],
raw: true,
});
const records = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkId, warehouse_id: Number(warehouseId) },
order: [[ 'id', 'ASC' ]],
raw: true,
});
// 挂载作业记录图片(FileReference business_type=stock_check_record,与 result 口径一致)
await this._attachRecordImages(records);
// 库位名称(custom_name 兜底 space_code),库位编码优先明细快照、缺失时回退库位表
const locationIds = [ ...new Set(detailRows
.map(row => Number(row.location_id))
.filter(locationId => Number.isInteger(locationId) && locationId > 0)) ];
let locationMap = new Map();
if (locationIds.length > 0) {
const locationRows = await ctx.model.LocationSpace.findAll({
where: { id: { [ctx.app.Sequelize.Op.in]: locationIds } },
attributes: [ 'id', 'space_code', 'custom_name' ],
raw: true,
});
locationMap = new Map(locationRows.map(row => [ Number(row.id), row ]));
}
// 按明细聚合作业记录
const recordsByDetail = new Map();
for (const record of records) {
const detailId = Number(record.detail_id);
if (!recordsByDetail.has(detailId)) {
recordsByDetail.set(detailId, []);
}
recordsByDetail.get(detailId).push(record);
}
// 已知商品基础信息批量取(getStockDetails 带缓存)与货主名映射
const stockIds = [ ...new Set(records
.map(record => Number(record.stock_id))
.filter(stockId => Number.isInteger(stockId) && stockId > 0)) ];
let stockDetailMap = new Map();
if (stockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, {
warehouseId: Number(warehouseId),
});
stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ]));
}
const storeIds = [ ...stockDetailMap.values() ]
.map(item => Number(item.store_id))
.filter(storeId => Number.isInteger(storeId) && storeId > 0);
const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId);
return detailRows.map(detailRow => {
const detailId = Number(detailRow.id);
const detailRecords = recordsByDetail.get(detailId) || [];
const locationRow = locationMap.get(Number(detailRow.location_id) || 0);
const locationCode = String(
detailRow.location_code || (locationRow && locationRow.space_code) || ''
).trim() || null;
const locationName = locationCode
? ((locationRow && (locationRow.custom_name || locationRow.space_code)) || locationCode)
: null;
const goods = [];
const checkerSet = new Set();
let lastCheckedAt = null;
let hasUnknown = false;
let isEmptyLocation = false;
for (const record of detailRecords) {
const checkerName = String(record.checker_name || '').trim();
if (checkerName) {
checkerSet.add(checkerName);
}
if (record.checked_at && (!lastCheckedAt || new Date(record.checked_at) > new Date(lastCheckedAt))) {
lastCheckedAt = record.checked_at;
}
// 空库位标记记录:不计入 goods 子列表,行级输出 is_empty 标记
if (record.is_empty) {
isEmptyLocation = true;
continue;
}
const stockId = Number(record.stock_id);
if (Number.isInteger(stockId) && stockId > 0) {
const stockDetail = stockDetailMap.get(stockId) || {};
const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : [];
const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null;
goods.push({
record_id: record.id,
stock_id: stockId,
item_code: stockDetail.item_code || null,
item_name: stockDetail.item_name || null,
barcode: (barcodes[0] && barcodes[0].barcode) || null,
images: Array.isArray(record.images) ? record.images : [],
store_id: storeId,
store_name: storeNameMap.get(storeId) || null,
quantity: Number(record.quantity) || 0,
checked_at: record.checked_at || null,
checker_name: checkerName || null,
});
} else {
// 未知商品(stock_id 为空)同样进入 goods 子列表,输出记录快照字段
hasUnknown = true;
goods.push({
record_id: record.id,
stock_id: null,
item_code: String(record.barcode || '').trim() || null,
item_name: String(record.item_name || record.barcode || '').trim() || null,
barcode: String(record.barcode || '').trim() || null,
images: Array.isArray(record.images) ? record.images : [],
store_id: null,
store_name: null,
quantity: Number(record.quantity) || 0,
checked_at: record.checked_at || null,
checker_name: checkerName || null,
});
}
}
const rowLocationId = detailRow.location_id !== null && detailRow.location_id !== undefined
? Number(detailRow.location_id)
: null;
return {
detail_id: detailId,
location_id: rowLocationId,
// space_id 为 location_id 的同义字段,供调用方直接回传 stock.check.report
space_id: rowLocationId,
location_code: locationCode,
location_name: locationName,
status: detailRecords.length > 0 ? 'checked' : 'unchecked',
has_unknown: hasUnknown,
is_empty: isEmptyLocation,
checked_at: lastCheckedAt,
checkers: [ ...checkerSet ],
goods,
};
});
}
/**
* 构建 goods 视图行:按商品(stock_id)汇总输出,一个商品一行;
* 同商品的库位明细行(scope_type=goods,按「商品+库位」拆行、唯一键 check_id+stock_id+location_id)
* 合并为一行:行级数量跨明细合计(账面快照合计、作业记录按库位合并),
* locations 每项带该库位明细行ID(detail_id)与账面快照(snapshot_quantity,明盘)供逐库位上报/钻取;
* stock_id 为空/异常的明细行无法按商品归并,各自成行。
* locations 为商品所在全部库位(wms_storage 中该商品的 space_id 集合,按拣货路径排序):
* 明盘(mode=open)每库位含 system_quantity(该库位账面数量,wms_storage space+stock
* 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 解析。
*
* @param {number} warehouseId 仓库ID。
* @param {number} checkId 盘点任务ID。
* @param {string} mode 盘点方式:open=明盘/blind=盲盘。
* @param {boolean} [isStatic=false] 是否静态盘点(is_static=1):true=账面取明细快照,
* false=账面取当前 wms_storage(可用数量)。
* @return {Promise<Array<Object>>} 商品视图行列表(按商品首个明细 id 升序)。
*/
async _buildGoodsWorkRows(warehouseId, checkId, mode, isStatic = false) {
const { ctx } = this;
const { Op, fn, col, literal } = ctx.app.Sequelize;
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'goods' },
order: [[ 'id', 'ASC' ]],
raw: true,
});
const records = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkId, warehouse_id: Number(warehouseId) },
order: [[ 'id', 'ASC' ]],
raw: true,
});
// 挂载作业记录图片(FileReference business_type=stock_check_record,与 result 口径一致)
await this._attachRecordImages(records);
const isOpen = mode !== 'blind';
// 商品基础信息批量取(getStockDetails 带缓存,未命中回退明细商品快照)与货主名映射
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, {
warehouseId: Number(warehouseId),
});
stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ]));
}
const storeIds = [ ...stockDetailMap.values() ]
.map(item => Number(item.store_id))
.filter(storeId => Number.isInteger(storeId) && storeId > 0);
const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId);
// 商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id
// 同时按 stock+space 汇总账面数量(该库位系统库存,口径=可用数量)与锁定数量,
// 供明盘 locations.system_quantity / locked_quantity 使用
const stockSpaceIdsMap = new Map();
const stockSpaceQuantityMap = new Map();
const allSpaceIds = new Set();
if (stockIds.length > 0) {
const storageRows = await ctx.model.Storage.findAll({
where: {
warehouse_id: Number(warehouseId),
stock_id: { [Op.in]: stockIds },
is_enabled: 1,
// 排除无头库位(与明细生成口径一致)
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
},
attributes: [
'stock_id',
'space_id',
[ literal('SUM(available_quantity)'), 'system_quantity' ],
[ fn('SUM', col('locked_quantity')), 'locked_quantity' ],
],
group: [ 'stock_id', 'space_id' ],
raw: true,
});
for (const storageRow of storageRows) {
const stockId = Number(storageRow.stock_id);
if (!stockSpaceIdsMap.has(stockId)) {
stockSpaceIdsMap.set(stockId, []);
stockSpaceQuantityMap.set(stockId, new Map());
}
const spaceId = Number(storageRow.space_id);
stockSpaceIdsMap.get(stockId).push(spaceId);
stockSpaceQuantityMap.get(stockId).set(spaceId, {
system_quantity: Number(storageRow.system_quantity) || 0,
locked_quantity: Number(storageRow.locked_quantity) || 0,
});
allSpaceIds.add(spaceId);
}
}
// 库位表(space_code + 拣货路径),按拣货路径排序:pick_sequence 升序、pick_priority 降序(同值按 id 升序兜底)
let sortedSpaceRows = [];
if (allSpaceIds.size > 0) {
const locationRows = await ctx.model.LocationSpace.findAll({
where: { id: { [Op.in]: [ ...allSpaceIds ] } },
attributes: [ 'id', 'space_code', 'pick_sequence', 'pick_priority' ],
raw: true,
});
sortedSpaceRows = locationRows.sort((left, right) => {
const sequenceDiff = Number(left.pick_sequence || 0) - Number(right.pick_sequence || 0);
if (sequenceDiff !== 0) {
return sequenceDiff;
}
const priorityDiff = Number(right.pick_priority || 0) - Number(left.pick_priority || 0);
if (priorityDiff !== 0) {
return priorityDiff;
}
return Number(left.id) - Number(right.id);
});
}
const spaceCodeByStockMap = new Map();
const spaceQuantityByStockMap = new Map();
// 库位编码 → 有效库位ID(同编码多条时取拣货顺序第一条):供 goods 视图 locations[] 回传 location_id,
// 让调用方能直接把库位ID回传 stock.check.report(否则只有编码,服务端只能按编码猜库位)
const spaceIdByCodeMap = new Map();
for (const row of sortedSpaceRows) {
const spaceCode = String(row.space_code || '').trim();
if (spaceCode && !spaceIdByCodeMap.has(spaceCode)) {
spaceIdByCodeMap.set(spaceCode, Number(row.id));
}
}
// 已盘库位(当前库存已无该商品)补查有效库位ID,口径与 workData space 视图一致(zone 存在未删除)
const uncoveredRecordCodes = [ ...new Set(records
.map(record => String(record.location_code || '').trim())
.filter(code => code && !spaceIdByCodeMap.has(code))) ];
if (uncoveredRecordCodes.length > 0) {
const uncoveredRows = await ctx.model.LocationSpace.findAll({
where: {
warehouse_id: Number(warehouseId),
space_code: { [Op.in]: uncoveredRecordCodes },
},
attributes: [ 'id', 'space_code' ],
include: [{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [],
required: true,
}],
order: [[ 'id', 'ASC' ]],
raw: true,
});
for (const row of uncoveredRows) {
const spaceCode = String(row.space_code || '').trim();
if (spaceCode && !spaceIdByCodeMap.has(spaceCode)) {
spaceIdByCodeMap.set(spaceCode, Number(row.id));
}
}
}
for (const [ stockId, spaceIds ] of stockSpaceIdsMap.entries()) {
const spaceRowMap = new Map(sortedSpaceRows.map(row => [ Number(row.id), row ]));
const orderedRows = spaceIds
.map(spaceId => spaceRowMap.get(spaceId))
.filter(Boolean)
.sort((left, right) => sortedSpaceRows.indexOf(left) - sortedSpaceRows.indexOf(right));
spaceCodeByStockMap.set(
stockId,
orderedRows.map(row => String(row.space_code || '').trim())
);
const quantityByCode = new Map();
for (const row of orderedRows) {
const spaceCode = String(row.space_code || '').trim();
const spaceQuantity = (stockSpaceQuantityMap.get(stockId) || new Map()).get(Number(row.id)) || {};
quantityByCode.set(spaceCode, {
system_quantity: Number(spaceQuantity.system_quantity) || 0,
locked_quantity: Number(spaceQuantity.locked_quantity) || 0,
});
}
spaceQuantityByStockMap.set(stockId, quantityByCode);
}
// 按明细聚合作业记录
const recordsByDetail = new Map();
for (const record of records) {
const detailId = Number(record.detail_id);
if (!recordsByDetail.has(detailId)) {
recordsByDetail.set(detailId, []);
}
recordsByDetail.get(detailId).push(record);
}
// 按商品汇总:同商品的库位明细行合并为一组(分组顺序沿用明细 id 升序);
// stock_id 为空/异常的明细行无法按商品归并,各自成组(保持单行输出)
const detailGroups = [];
const groupIndexByStock = new Map();
for (const detailRow of detailRows) {
const detailStockId = Number(detailRow.stock_id);
const groupKey = Number.isInteger(detailStockId) && detailStockId > 0
? `stock_${detailStockId}`
: `detail_${Number(detailRow.id)}`;
if (!groupIndexByStock.has(groupKey)) {
groupIndexByStock.set(groupKey, detailGroups.length);
detailGroups.push([]);
}
detailGroups[groupIndexByStock.get(groupKey)].push(detailRow);
}
return detailGroups.map(groupRows => {
const firstDetailRow = groupRows[0];
const stockId = Number(firstDetailRow.stock_id);
// 该商品全部明细的作业记录(明细 id 升序 → 记录 id 升序)
const detailRecords = [];
for (const groupRow of groupRows) {
detailRecords.push(...(recordsByDetail.get(Number(groupRow.id)) || []));
}
// 库位编码 → 该库位明细行(明细ID + 账面快照):供逐库位钻取/上报回传,
// 同编码多条时取明细 id 最小的一行(正常数据唯一键已保证一个商品一个库位一行)
const detailByLocationCode = new Map();
for (const groupRow of groupRows) {
const groupRowCode = String(groupRow.location_code || '').trim();
if (!groupRowCode || detailByLocationCode.has(groupRowCode)) {
continue;
}
detailByLocationCode.set(groupRowCode, {
detail_id: Number(groupRow.id),
snapshot_quantity: Number(groupRow.system_quantity) || 0,
});
}
const stockDetail = stockDetailMap.get(stockId) || {};
const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : [];
const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null;
const row = {
stock_id: stockId,
item_code: stockDetail.item_code || firstDetailRow.item_code || null,
item_name: stockDetail.item_name || firstDetailRow.item_name || null,
spec: stockDetail.sku_property || firstDetailRow.spec || null,
store_id: storeId,
store_name: storeNameMap.get(storeId) || null,
barcode: (barcodes[0] && barcodes[0].barcode) || null,
images: stockDetail.image_url || [],
// 账面取值来源:静态盘点=明细快照(盘点基准冻结),非静态=当前 wms_storage 账面
is_static: isStatic ? 1 : 0,
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;
row.diff_quantity = 0;
row.is_diff = 0;
}
// 按库位聚合该明细的作业记录(库位为空归入"无库位"分组,按首条记录 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_code: recordLocationCode || null,
quantity: 0,
first_record_id: Number(record.id) || 0,
checked_at: null,
checker_name: null,
record_ids: [],
images: [],
});
}
const group = locationGroups.get(recordLocationCode);
group.quantity += Number(record.quantity) || 0;
group.record_ids.push(Number(record.id) || 0);
for (const image of (Array.isArray(record.images) ? record.images : [])) {
if (!group.images.some(item => item && Number(item.id) === Number(image.id))) {
group.images.push(image);
}
}
if (record.checked_at && (!group.checked_at || new Date(record.checked_at) > new Date(group.checked_at))) {
group.checked_at = record.checked_at;
group.checker_name = String(record.checker_name || '').trim() || null;
}
}
// locations:商品所在全部库位(基础列表),已盘库位合并作业信息,未盘库位为空信息;
// 商品库存已无记录但已盘的库位(仅记录库位)追加在末尾
const baseLocationCodes = (spaceCodeByStockMap.get(stockId) || []).filter(code => code !== '');
const mergedLocationCodes = new Set(baseLocationCodes);
const extraGroups = [];
for (const [ code, group ] of locationGroups.entries()) {
if (code && !mergedLocationCodes.has(code)) {
extraGroups.push(group);
}
}
const buildLocationItem = (code, group) => {
const locationIdValue = (code && spaceIdByCodeMap.get(code)) || (group && group.location_id) || null;
const locationDetail = detailByLocationCode.get(code || '') || null;
const locationItem = {
// 库位ID(wms_location_space.id):优先有效库位行,其次作业记录回填值;
// space_id 供调用方直接回传 stock.check.report(location_id 为兼容别名)
location_id: locationIdValue,
space_id: locationIdValue,
location_code: code || null,
// 该库位对应的盘点明细ID(商品按库位拆行);无明细快照的库位为 null
detail_id: locationDetail ? locationDetail.detail_id : null,
checked_at: group ? group.checked_at : null,
checker_name: group ? group.checker_name : null,
record_ids: group ? group.record_ids : [],
images: group ? group.images : [],
};
if (isOpen) {
// 明盘:逐库位账面按任务是否静态取值——静态盘点取该库位明细快照(盘点基准冻结),
// 非静态取当前 wms_storage 账面(可用数量);两者同时输出便于对照,
// system_quantity 始终为「本次参与差异计算的账面」
const spaceQuantity = (spaceQuantityByStockMap.get(stockId) || new Map()).get(code || '') || {};
const storageQuantity = Number(spaceQuantity.system_quantity) || 0;
const snapshotQuantity = locationDetail ? locationDetail.snapshot_quantity : 0;
locationItem.system_quantity = isStatic ? snapshotQuantity : storageQuantity;
locationItem.storage_quantity = storageQuantity;
locationItem.locked_quantity = Number(spaceQuantity.locked_quantity) || 0;
locationItem.snapshot_quantity = snapshotQuantity;
locationItem.quantity = group ? group.quantity : 0;
}
return locationItem;
};
row.locations = [
...baseLocationCodes.map(code => buildLocationItem(code, locationGroups.get(code) || null)),
...extraGroups
.sort((left, right) => left.first_record_id - right.first_record_id)
.map(group => buildLocationItem(group.location_code, group)),
];
// "无库位"分组(记录 location_code 为空)追加在末尾
const emptyLocationGroup = locationGroups.get('');
if (emptyLocationGroup) {
row.locations.push(buildLocationItem(null, emptyLocationGroup));
}
if (isOpen && row.locations.length > 0) {
// 行级账面 = 各库位账面(按静态/非静态口径取值)之和
row.system_quantity = row.locations.reduce(
(sum, item) => sum + (Number(item.system_quantity) || 0),
0
);
row.checked_quantity = row.locations.reduce((sum, item) => sum + (Number(item.quantity) || 0), 0);
// 差异仅对存在作业记录的行计算(未盘行差异保持 0,避免误显盘亏)
if (detailRecords.length > 0) {
row.diff_quantity = row.checked_quantity - row.system_quantity;
row.is_diff = row.diff_quantity !== 0 ? 1 : 0;
}
}
return row;
});
}
/**
* 构建 space 视图行:以任务商品(scope_type=goods 的 stock_id 集合)所在的库位为列表。
* 库位集合取 wms_storage(warehouse_id + stock_id 在集合内 + is_enabled=1 且未删除,DISTINCT space_id)
* ∪ 作业记录库位(上报库位与明细库位编码一致时归并到明细固化 location_id,
* 无头库位归并到同编码有效库位,避免同编码出现重复行),
* 库位仅按拣货顺序排序:pick_sequence 升序(pick_priority/库位 id 不参与排序,
* 同值保持库位查询顺序);
* 行内 goods 为该库位下的任务商品:明盘含 system_quantity(wms_storage space+stock
* 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 有库位的商品不入列表(无库位可聚)。
*
* @param {number} warehouseId 仓库ID。
* @param {number} checkId 盘点任务ID。
* @param {string} mode 盘点方式:open=明盘/blind=盲盘。
* @param {boolean} [isStatic=false] 是否静态盘点(is_static=1):true=账面取明细快照,
* false=账面取当前 wms_storage(可用数量)。
* @return {Promise<Array<Object>>} 聚合库位视图行列表(按拣货路径排序)。
*/
async _buildSpaceWorkRows(warehouseId, checkId, mode, isStatic = false) {
const { ctx } = this;
const { Op, fn, col, literal } = ctx.app.Sequelize;
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'goods' },
order: [[ 'id', 'ASC' ]],
raw: true,
});
const stockIds = [ ...new Set(detailRows
.map(row => Number(row.stock_id))
.filter(stockId => Number.isInteger(stockId) && stockId > 0)) ];
if (stockIds.length === 0) {
return [];
}
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' ]],
raw: true,
});
// 挂载作业记录图片(FileReference business_type=stock_check_record,与 result 口径一致)
await this._attachRecordImages(records);
// 商品基础信息批量取(getStockDetails 带缓存,未命中回退明细商品快照)与货主名映射
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, {
warehouseId: Number(warehouseId),
});
const stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ]));
const storeIds = [ ...stockDetailMap.values() ]
.map(item => Number(item.store_id))
.filter(storeId => Number.isInteger(storeId) && storeId > 0);
const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId);
const detailByStockId = new Map(detailRows.map(row => [ Number(row.stock_id), row ]));
const detailById = new Map(detailRows.map(row => [ Number(row.id), row ]));
// 明细按「库位 + 商品」索引:同一商品分布在多个库位时,库位行应取本库位对应的明细
const detailByStockSpace = new Map(
detailRows.map(row => [ `${Number(row.location_id)}_${Number(row.stock_id)}`, row ])
);
// 任务商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id,
// 同时按 (space_id, stock_id) 汇总账面数量(口径=可用数量)与锁定数量
const storageRows = await ctx.model.Storage.findAll({
where: {
warehouse_id: Number(warehouseId),
stock_id: { [Op.in]: stockIds },
is_enabled: 1,
// 排除无头库位(与明细生成口径一致)
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
},
attributes: [
'space_id',
'stock_id',
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
[ fn('SUM', col('locked_quantity')), 'totalLockedQuantity' ],
],
group: [ 'space_id', 'stock_id' ],
raw: true,
});
// 记录库位归一:上报库位与明细库位编码一致时以明细固化库位为准,
// 避免同仓库同编码存在多条库位(历史重复库位/无头库位)时同一编码在视图里出现两行
const recordSpaceIdMap = new Map();
for (const record of records) {
const recordCode = String(record.location_code || '').trim();
const recordDetail = detailById.get(Number(record.detail_id));
const detailLocationCode = recordDetail ? String(recordDetail.location_code || '').trim() : '';
const detailLocationId = recordDetail ? Number(recordDetail.location_id) || 0 : 0;
const recordSpaceId = recordCode && detailLocationCode === recordCode && detailLocationId > 0
? detailLocationId
: Number(record.location_id) || 0;
recordSpaceIdMap.set(Number(record.id), recordSpaceId);
}
// 无头库位(分区不存在/已删除)不直接入视图:同仓库同编码多条库位时会出现自定义字段为空的幽灵行,
// 统一归并到同编码的有效库位(优先该商品有启用库存的库位,其次 ID 最小)
const recordSpaceIdList = [ ...new Set([ ...recordSpaceIdMap.values() ].filter(spaceId => spaceId > 0)) ];
if (recordSpaceIdList.length > 0) {
const validRecordSpaceRows = await ctx.model.LocationSpace.findAll({
where: { id: { [Op.in]: recordSpaceIdList } },
attributes: [ 'id' ],
include: [{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [],
required: true,
}],
raw: true,
});
const validRecordSpaceIdSet = new Set(validRecordSpaceRows.map(row => Number(row.id)));
const invalidRecordSpaceIds = recordSpaceIdList.filter(spaceId => !validRecordSpaceIdSet.has(spaceId));
if (invalidRecordSpaceIds.length > 0) {
const invalidRows = await ctx.model.LocationSpace.findAll({
where: { id: { [Op.in]: invalidRecordSpaceIds } },
attributes: [ 'id', 'space_code' ],
raw: true,
});
const invalidSpaceCodeMap = new Map(
invalidRows.map(row => [ Number(row.id), String(row.space_code || '').trim() ])
);
const fallbackCodes = [ ...new Set([ ...invalidSpaceCodeMap.values() ].filter(Boolean)) ];
const fallbackRows = fallbackCodes.length === 0 ? [] : await ctx.model.LocationSpace.findAll({
where: {
warehouse_id: Number(warehouseId),
space_code: { [Op.in]: fallbackCodes },
},
attributes: [ 'id', 'space_code' ],
include: [{
model: ctx.model.LocationZone,
as: 'zone',
attributes: [],
required: true,
}],
order: [[ 'id', 'ASC' ]],
raw: true,
});
const fallbackIdsByCode = new Map();
for (const row of fallbackRows) {
const code = String(row.space_code || '').trim();
if (!fallbackIdsByCode.has(code)) {
fallbackIdsByCode.set(code, []);
}
fallbackIdsByCode.get(code).push(Number(row.id));
}
const storageKeySet = new Set(
storageRows.map(row => `${Number(row.space_id)}_${Number(row.stock_id)}`)
);
for (const record of records) {
const recordId = Number(record.id);
const currentSpaceId = recordSpaceIdMap.get(recordId) || 0;
if (!invalidRecordSpaceIds.includes(currentSpaceId)) {
continue;
}
const code = invalidSpaceCodeMap.get(currentSpaceId)
|| String(record.location_code || '').trim();
const candidates = fallbackIdsByCode.get(code) || [];
if (candidates.length === 0) {
continue;
}
const recordStockId = Number(record.stock_id) || 0;
const stockHit = recordStockId > 0
? candidates.find(spaceId => storageKeySet.has(`${spaceId}_${recordStockId}`))
: 0;
recordSpaceIdMap.set(recordId, stockHit || candidates[0]);
}
}
}
// 作业记录库位:优先已回填 location_id;未回填的按库位编码匹配 wms_location_space 补查,
// 保证商品库存已无记录时(如盘点前库存已出空)space 视图仍能展示已盘库位行
// (编码一致时已在上面归并到明细固化库位)。
const recordSpaceIds = [];
const recordLocationCodes = [];
for (const record of records) {
const recordSpaceId = recordSpaceIdMap.get(Number(record.id)) || 0;
if (recordSpaceId > 0) {
if (!recordSpaceIds.includes(recordSpaceId)) {
recordSpaceIds.push(recordSpaceId);
}
} else {
const locationCode = String(record.location_code || '').trim();
if (locationCode && !recordLocationCodes.includes(locationCode)) {
recordLocationCodes.push(locationCode);
}
}
}
let codeMatchedLocationRows = [];
if (recordLocationCodes.length > 0) {
codeMatchedLocationRows = await ctx.model.LocationSpace.findAll({
where: {
warehouse_id: Number(warehouseId),
space_code: { [Op.in]: recordLocationCodes },
},
attributes: [ 'id', 'space_code', 'custom_barcode', 'custom_name', 'pick_sequence' ],
raw: true,
});
for (const row of codeMatchedLocationRows) {
const matchedSpaceId = Number(row.id);
if (!recordSpaceIds.includes(matchedSpaceId)) {
recordSpaceIds.push(matchedSpaceId);
}
}
}
const storageSpaceIds = [ ...new Set(storageRows.map(row => Number(row.space_id))) ];
const spaceIds = [ ...new Set([ ...storageSpaceIds, ...recordSpaceIds ]) ];
if (spaceIds.length === 0) {
return [];
}
const locationRows = await ctx.model.LocationSpace.findAll({
where: { id: { [Op.in]: spaceIds } },
attributes: [ 'id', 'space_code', 'custom_barcode', 'custom_name', 'pick_sequence' ],
raw: true,
});
// 库位仅按拣货顺序排序:pick_sequence 升序(pick_priority/库位 id 不参与排序,
// 同值保持库位查询顺序,依赖 Array.sort 稳定排序)
const sortedLocations = locationRows.sort((left, right) =>
Number(left.pick_sequence || 0) - Number(right.pick_sequence || 0)
);
// 库位商品账面/锁定映射(键 `${space_id}_${stock_id}`)
const storageQuantityMap = new Map();
for (const storageRow of storageRows) {
storageQuantityMap.set(
`${Number(storageRow.space_id)}_${Number(storageRow.stock_id)}`,
{
system_quantity: Number(storageRow.totalQuantity) || 0,
locked_quantity: Number(storageRow.totalLockedQuantity) || 0,
}
);
}
// 按库位归集任务商品存储行
const storageBySpace = new Map();
for (const storageRow of storageRows) {
const spaceId = Number(storageRow.space_id);
if (!storageBySpace.has(spaceId)) {
storageBySpace.set(spaceId, []);
}
storageBySpace.get(spaceId).push(storageRow);
}
// 按 (detail_id, location_code) 聚合作业记录(已盘口径与实盘合计用)
const recordsByDetailLocation = new Map();
for (const record of records) {
const detailId = Number(record.detail_id);
const locationCode = String(record.location_code || '').trim();
const key = `${detailId}_${locationCode}`;
if (!recordsByDetailLocation.has(key)) {
recordsByDetailLocation.set(key, []);
}
recordsByDetailLocation.get(key).push(record);
}
// 按 (detail_id, space_id) 聚合作业记录(库位编码大小写/回填差异时兜底按库位ID命中)
const codeToSpaceIdMap = new Map(
codeMatchedLocationRows.map(row => [ String(row.space_code || '').trim(), Number(row.id) ])
);
const recordsByDetailSpace = new Map();
// 记录按「库位 + 商品」归集:跨明细上报(记录明细与库位不一致)时仍能命中对应库位行
const recordsBySpaceStock = new Map();
// 仅记录库位(当前库存无该商品)按库位归集记录,供 space 视图补行
const recordsBySpace = new Map();
for (const record of records) {
let spaceId = recordSpaceIdMap.get(Number(record.id)) || 0;
if (!spaceId) {
spaceId = codeToSpaceIdMap.get(String(record.location_code || '').trim()) || 0;
}
if (!spaceId) {
continue;
}
const detailId = Number(record.detail_id);
const detailSpaceKey = `${detailId}_${spaceId}`;
if (!recordsByDetailSpace.has(detailSpaceKey)) {
recordsByDetailSpace.set(detailSpaceKey, []);
}
recordsByDetailSpace.get(detailSpaceKey).push(record);
const recordStockId = Number(record.stock_id) || 0;
if (recordStockId > 0) {
const spaceStockKey = `${spaceId}_${recordStockId}`;
if (!recordsBySpaceStock.has(spaceStockKey)) {
recordsBySpaceStock.set(spaceStockKey, []);
}
recordsBySpaceStock.get(spaceStockKey).push(record);
}
if (!recordsBySpace.has(spaceId)) {
recordsBySpace.set(spaceId, []);
}
recordsBySpace.get(spaceId).push(record);
}
return sortedLocations.map(locationRow => {
const spaceId = Number(locationRow.id);
const spaceCode = String(locationRow.space_code || '').trim();
// 库存行 + 仅记录库位(当前库存已无该商品)的已知商品补行
const spaceStorageRows = storageBySpace.get(spaceId) || [];
const knownStorageStockIds = new Set(spaceStorageRows.map(row => Number(row.stock_id)));
const mergedRows = [ ...spaceStorageRows ];
for (const record of recordsBySpace.get(spaceId) || []) {
const recordStockId = Number(record.stock_id) || 0;
if (recordStockId > 0 && !knownStorageStockIds.has(recordStockId)) {
mergedRows.push({ space_id: spaceId, stock_id: recordStockId, totalQuantity: 0, totalLockedQuantity: 0 });
knownStorageStockIds.add(recordStockId);
}
}
const goods = mergedRows
.sort((left, right) => Number(left.stock_id) - Number(right.stock_id))
.map(storageRow => {
const stockId = Number(storageRow.stock_id);
const detailRow = detailByStockSpace.get(`${spaceId}_${stockId}`) || detailByStockId.get(stockId);
if (!detailRow) {
return null;
}
const stockDetail = stockDetailMap.get(stockId) || {};
const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : [];
const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null;
const detailId = Number(detailRow.id);
const locationRecords = recordsBySpaceStock.get(`${spaceId}_${stockId}`)
|| recordsByDetailSpace.get(`${detailId}_${spaceId}`)
|| recordsByDetailLocation.get(`${detailId}_${spaceCode}`)
|| [];
// 作业照片与记录ID(供前端展示与编辑/移除记录)
const recordImages = [];
const recordIds = [];
for (const record of locationRecords) {
recordIds.push(Number(record.id) || 0);
for (const image of (Array.isArray(record.images) ? record.images : [])) {
if (!recordImages.some(item => item && Number(item.id) === Number(image.id))) {
recordImages.push(image);
}
}
}
const item = {
detail_id: detailId,
stock_id: stockId,
item_code: stockDetail.item_code || detailRow.item_code || null,
item_name: stockDetail.item_name || detailRow.item_name || null,
spec: stockDetail.sku_property || detailRow.spec || null,
store_id: storeId,
store_name: storeNameMap.get(storeId) || null,
barcode: (barcodes[0] && barcodes[0].barcode) || null,
images: recordImages,
record_ids: recordIds,
};
if (isOpen) {
const storageQuantity = storageQuantityMap.get(`${spaceId}_${stockId}`) || {};
const liveQuantity = Number(storageQuantity.system_quantity) || 0;
const snapshotQuantity = Number(detailRow.system_quantity) || 0;
// 账面取值:静态盘点=明细快照(盘点基准冻结),非静态=当前 wms_storage 账面
item.system_quantity = isStatic ? snapshotQuantity : liveQuantity;
item.storage_quantity = liveQuantity;
item.locked_quantity = Number(storageQuantity.locked_quantity) || 0;
item.snapshot_quantity = snapshotQuantity;
item.checked_quantity = locationRecords.reduce(
(sum, record) => sum + (Number(record.quantity) || 0),
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;
})
.filter(item => item !== null);
return {
// 库位字段对齐库位查询惯例(index.searchSpace:id/space_code/custom_barcode/custom_name);
// location_id / space_id 均为 id 的同义字段,上报 stock.check.report 时以 space_id 必传
id: spaceId,
location_id: spaceId,
space_id: spaceId,
space_code: spaceCode || null,
custom_barcode: locationRow.custom_barcode != null && String(locationRow.custom_barcode).trim() !== ''
? String(locationRow.custom_barcode).trim()
: null,
custom_name: locationRow.custom_name != null && String(locationRow.custom_name).trim() !== ''
? String(locationRow.custom_name).trim()
: null,
goods,
};
});
}
/**
* 批量删除盘点作业记录(按行清除盘点信息)。
* 仅主表状态 approved/checking 允许删除;记录不存在或不属于该任务/仓库时计入 skipped_ids 不报错;
* 删除后重算 checked_items/diff_items/detail_status(明细记录删光后该明细回到未盘),主表状态不回退;
* 同时清理被删记录的图片引用(FileReference business_type=stock_check_record,失败仅告警不影响主流程)。
* 注意:本接口已由旧版单值删除升级为批量删除,响应结构由旧版 { record_id, deleted, ...summary }
* 变更为 { deleted_count, deleted_ids, skipped_ids, ...summary }。
*
* @param {Object} params 删除参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {Array<number>|number} params.recordIds 作业记录ID数组(单值自动转数组,单次上限 200;
* 方法层已兼容 record_ids/recordIds/record_id 写法)。
* @return {Promise<Object>} { deleted_count, deleted_ids, skipped_ids, total_items, checked_items, diff_items, detail_status };
* deleted_ids/skipped_ids 均保持入参顺序。
* @throws {Error} 参数非法、任务不存在或状态不允许时抛出业务错误(错误码 400)。
*/
async recordDelete(params = {}) {
const { warehouseId, id, recordIds } = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!REPORT_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${check.status})不允许删除作业记录`);
}
const numericRecordIds = this._normalizeIdList(recordIds);
if (numericRecordIds.length === 0) {
throw this.createBusinessError('请至少选择一条作业记录');
}
if (numericRecordIds.length > 200) {
throw this.createBusinessError('单次最多删除 200 条作业记录');
}
// 仓库隔离查询记录:id in ids + check_id + warehouse_id;查不到的 ID 计入 skipped_ids(不报错)
const recordRows = await ctx.model.StockCheckRecord.findAll({
where: {
id: { [Op.in]: numericRecordIds },
check_id: checkId,
warehouse_id: Number(warehouseId),
},
attributes: [ 'id' ],
raw: true,
});
const foundIdSet = new Set(recordRows.map(row => Number(row.id)));
const deletedIds = [];
const skippedIds = [];
for (const recordId of numericRecordIds) {
if (foundIdSet.has(recordId)) {
deletedIds.push(recordId);
} else {
skippedIds.push(recordId);
}
}
if (deletedIds.length > 0) {
await ctx.model.StockCheckRecord.destroy({
where: { id: { [Op.in]: deletedIds } },
});
// 清理被删记录的图片引用(图片独立维护,仿收货口径):失败仅告警,不影响主流程
try {
await ctx.model.FileReference.destroy({
where: {
business_type: 'stock_check_record',
business_id: { [Op.in]: deletedIds.map(String) },
},
});
} catch (error) {
ctx.logger.warn(`[stock.check.recordDelete] 清理作业记录图片引用失败: ${error && error.message ? error.message : error}`);
}
}
// 重算 checked_items / diff_items / detail_status(明细记录删光后该明细回到未盘),主表状态不回退
const summary = await this._recalcCheckSummary(checkId);
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_DELETE_RECORD',
operationAction: 'UPDATE',
changeSummary: `批量删除盘点作业记录 ${deletedIds.length} 条(跳过 ${skippedIds.length} 条)`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
checkNo: check.check_no,
deletedIds,
skippedIds,
message: `批量删除盘点作业记录 ${deletedIds.length} 条`,
},
});
return {
deleted_count: deletedIds.length,
deleted_ids: deletedIds,
skipped_ids: skippedIds,
total_items: summary.total_items,
checked_items: summary.checked_items,
diff_items: summary.diff_items,
detail_status: summary.detail_status,
};
}
/**
* 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。
* 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记),
* 该库位回到未盘状态;仅任务范围为库位(type=location)且状态 approved/checking 时允许;
* 删除后重算 checked_items/diff_items/detail_status,主表状态不回退;
* 同时清理被删记录的图片引用(失败仅告警不影响主流程)。
*
* @param {Object} params 清除参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {number} params.locationId 库位ID(wms_location_space.id)。
* @return {Promise<Object>} { detail_id, location_id, deleted_count, total_items, checked_items, diff_items, detail_status }。
* @throws {Error} 参数非法、任务不存在、状态不允许、非库位任务或库位不在任务范围内时抛出业务错误(错误码 400)。
*/
async recheckClearLocation(params = {}) {
const { warehouseId, id, locationId } = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const checkId = Number(id);
const normalizedLocationId = Number(locationId);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
if (!Number.isInteger(normalizedLocationId) || normalizedLocationId <= 0) {
throw this.createBusinessError('库位ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!REPORT_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${check.status})不允许清除库位盘点信息`);
}
const normalizedType = String(check.type || '').trim();
if (normalizedType !== 'location') {
throw this.createBusinessError('仅库位盘点任务支持重盘清除库位');
}
const detail = await ctx.model.StockCheckDetail.findOne({
where: {
check_id: checkId,
warehouse_id: Number(warehouseId),
location_id: normalizedLocationId,
scope_type: 'location',
},
attributes: [ 'id', 'location_id', 'location_code' ],
});
if (!detail) {
throw this.createBusinessError('该库位不在盘点任务范围内');
}
const detailId = Number(detail.id);
// 删除该明细全部作业记录(含空库位标记)
const recordRows = await ctx.model.StockCheckRecord.findAll({
where: { detail_id: detailId, check_id: checkId },
attributes: [ 'id' ],
raw: true,
});
const deletedCount = recordRows.length;
if (deletedCount > 0) {
await ctx.model.StockCheckRecord.destroy({
where: {
detail_id: detailId,
check_id: checkId,
warehouse_id: Number(warehouseId),
},
});
// 清理被删记录的图片引用:失败仅告警,不影响主流程
try {
await ctx.model.FileReference.destroy({
where: {
business_type: 'stock_check_record',
business_id: { [Op.in]: recordRows.map(row => String(row.id)) },
},
});
} catch (error) {
ctx.logger.warn(`[stock.check.recheckClearLocation] 清理作业记录图片引用失败: ${error && error.message ? error.message : error}`);
}
}
// 重算 checked_items / diff_items / detail_status(该库位回到未盘),主表状态不回退
const summary = await this._recalcCheckSummary(checkId);
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_CLEAR_LOCATION',
operationAction: 'UPDATE',
changeSummary: `重盘清除库位 ${String(detail.location_code || '').trim() || normalizedLocationId}:删除作业记录 ${deletedCount} 条`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
checkNo: check.check_no,
detailId,
locationId: normalizedLocationId,
locationCode: String(detail.location_code || '').trim(),
message: `重盘清除库位:删除作业记录 ${deletedCount} 条`,
},
});
return {
detail_id: detailId,
location_id: normalizedLocationId,
deleted_count: deletedCount,
total_items: summary.total_items,
checked_items: summary.checked_items,
diff_items: summary.diff_items,
detail_status: summary.detail_status,
};
}
/**
* 计算任务数量差异汇总(盘盈/盘亏/差异明细数,纯查询无副作用)。
*
* 口径:
* - 商品范围(scope_type=goods):按商品聚合(一行一商品,多个库位明细行合并)——
* 已盘商品差异 = 商品实盘合计 - 账面快照 system_quantity 合计;未盘商品按实盘 0 处理
* (差异 = -账面快照合计,即盘亏);
* - 库位行(scope_type=location):按商品聚合 vs wms_storage 账面;未盘库位行无法枚举商品,
* 不计差异;
* - 未知商品(记录 stock_id 为空)无账面:实盘 > 0 即盘盈,必然计入差异。
* 盘亏合计以正数返回(loss_total 为正数口径)。
*
* @param {number} checkId 盘点任务ID。
* @return {Promise<Object>} { diff_items, profit_total, loss_total }。
*/
async _calcQuantityDiffSummary(checkId) {
const { ctx } = this;
const summary = await this._recalcCheckSummary(checkId);
const checkedQuantityByDetail = summary.checked_quantity_by_detail || new Map();
const stockQuantityByDetail = summary.stock_quantity_by_detail || new Map();
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', '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 !== 'location') {
continue;
}
// 库位行:按商品聚合 vs wms_storage 账面;未盘库位行无法枚举商品,不计差异
const byStock = stockQuantityByDetail.get(detailId);
const byUnknown = unknownQuantityByDetail.get(detailId);
if ((!byStock || byStock.size === 0) && (!byUnknown || byUnknown.size === 0)) {
continue;
}
let rowDiff = false;
for (const agg of (byStock ? byStock.values() : [])) {
const diffQuantity = agg.checked - (agg.system || 0);
if (diffQuantity !== 0) {
rowDiff = true;
if (diffQuantity > 0) {
profitTotal += diffQuantity;
} else {
lossTotal += Math.abs(diffQuantity);
}
}
}
// 未知商品无账面:实盘 > 0 即盘盈、必然计入差异
for (const agg of (byUnknown ? byUnknown.values() : [])) {
if (agg.checked > 0) {
rowDiff = true;
profitTotal += agg.checked;
}
}
if (rowDiff) {
diffItems++;
}
}
return {
diff_items: diffItems,
profit_total: profitTotal,
loss_total: lossTotal,
};
}
/**
* 完成盘点作业(允许部分未盘完成)。
* 仅 approved/checking 状态允许;未盘商品明细按实盘 0 处理(差异 = -账面快照,计入盘亏与 diff_items);
* 已盘明细按作业记录聚合差异(盘盈合计 / 盘亏合计):商品行聚合 vs system_quantity 快照,
* 库位行按商品聚合 vs wms_storage 账面(space_id 为空时账面按 0,未盘库位行因无法枚举商品不计差异);
* 未知商品(stock_id 为空)无账面:差异 = 实盘 - 0 = 盘盈,计入盘盈合计与 diff_items;
* 完成后主表置 completed、写 end_time、detail_status=all_checked,并返回差异汇总与未盘明细数。
*
* @param {Object} params 完成参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @return {Promise<Object>} { id, status, total_items, checked_items, unchecked_items, diff_items,
* profit_total, loss_total, released_stock_ids }(released_stock_ids=本任务覆盖的商品ID,
* 完成即释放静态锁定;库位任务为空数组)。
* @throws {Error} 状态不允许时抛出业务错误(错误码 400)。
*/
async finish(params = {}) {
const { warehouseId, id } = params;
const { ctx } = this;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!REPORT_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${check.status})不允许完成盘点`);
}
// 范围口径汇总:商品范围按商品计数,库位范围按明细行计数(与 _recalcCheckSummary 一致)
const scopeSummary = await this._countScopeSummary(checkId);
const totalItems = scopeSummary.total_items;
const checkedItems = scopeSummary.checked_items;
const uncheckedItems = totalItems - checkedItems;
// 数量差异汇总(盘盈/盘亏/差异明细数,口径见 _calcQuantityDiffSummary)
const diffSummary = await this._calcQuantityDiffSummary(checkId);
const diffItems = diffSummary.diff_items;
const profitTotal = diffSummary.profit_total;
const lossTotal = diffSummary.loss_total;
// 完成前先记录本任务覆盖的商品(完成=释放锁定,供响应与日志追溯)
const releasedStockIds = await this._collectGoodsStockIds(checkId);
await check.update({
status: 'completed',
end_time: new Date(),
detail_status: 'all_checked',
checked_items: checkedItems,
diff_items: diffItems,
});
// 任务结束:清除静态锁定缓存,释放本任务商品(is_static=1 时其余锁定任务仍保留)
await this.refreshStaticLockCache(warehouseId);
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_FINISH',
operationAction: 'UPDATE',
changeSummary: `完成盘点:差异明细 ${diffItems},盘盈 ${profitTotal},盘亏 ${lossTotal},未盘 ${uncheckedItems}`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
checkNo: check.check_no,
diffItems,
profitTotal,
lossTotal,
checkedItems,
uncheckedItems,
releasedStockIds,
message: `完成盘点:差异 ${diffItems} 项,盘盈 ${profitTotal},盘亏 ${lossTotal}${releasedStockIds.length > 0 ? `,释放静态锁定商品 ${releasedStockIds.length} 个` : ''}`,
},
});
return {
id: checkId,
status: 'completed',
total_items: totalItems,
checked_items: checkedItems,
unchecked_items: uncheckedItems,
diff_items: diffItems,
profit_total: profitTotal,
loss_total: lossTotal,
released_stock_ids: releasedStockIds,
};
}
/**
* 查询商品在仓库内的锁定量合计(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)(= 库存总量 − 锁定数量 − 拦截锁定数量;库存记录不存在时按 0):
* 账面只统计可用数量,不把 locked_quantity(已分配储位、待拣出库)计入:
* 分配储位只搬 available→locked(账面不变),拣货完成同时扣 quantity 与 locked、
* available 不变,因此「可用数量」口径在静态盘点窗口内对拣货动作不敏感。
* - 提交审核时调用(保证 result/差异对比使用提交时点的账面);
* - 审核通过时再次调用(盘点基准以「审核完成=开始盘点」时刻为准,覆盖提交后到达的出入库);
* 库位范围(scope_type=location)账面实时查 wms_storage,不处理。
*
* @param {number} checkId 盘点任务ID。
* @param {number} warehouseId 仓库ID。
* @return {Promise<number>} 刷新(含值变化)的明细行数。
*/
async _refreshGoodsBookSnapshot(checkId, warehouseId) {
const { ctx } = this;
const { Op, literal } = ctx.app.Sequelize;
const checkIdNumber = Number(checkId);
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { check_id: checkIdNumber, scope_type: 'goods' },
raw: true,
});
if (detailRows.length === 0) {
return 0;
}
const stockIds = [ ...new Set(detailRows
.map(row => Number(row.stock_id))
.filter(stockId => Number.isInteger(stockId) && stockId > 0)) ];
// 按 (stock_id, space_id) 聚合当前账面:SUM(可用数量)
const storageQuantityMap = new Map();
if (stockIds.length > 0) {
const storageRows = await ctx.model.Storage.findAll({
where: {
warehouse_id: Number(warehouseId),
stock_id: { [Op.in]: stockIds },
is_enabled: 1,
},
attributes: [
'stock_id',
'space_id',
[ literal('SUM(available_quantity)'), 'totalQuantity' ],
],
group: [ 'stock_id', 'space_id' ],
raw: true,
});
for (const storageRow of storageRows) {
storageQuantityMap.set(
`${Number(storageRow.stock_id)}_${Number(storageRow.space_id)}`,
Number(storageRow.totalQuantity) || 0
);
}
}
// 逐明细行刷新库位级账面快照(刷新时点账面,库存记录不存在时按 0)
let refreshedCount = 0;
for (const detailRow of detailRows) {
const systemQuantity = storageQuantityMap.get(
`${Number(detailRow.stock_id)}_${Number(detailRow.location_id)}`
) || 0;
if (Number(detailRow.system_quantity || 0) === systemQuantity) {
continue;
}
await ctx.model.StockCheckDetail.update(
{ system_quantity: systemQuantity },
{ where: { id: detailRow.id } }
);
refreshedCount++;
}
return refreshedCount;
}
/**
* 完成盘点任务(提交审核)。
* 仅 created/rejected 状态允许;校验 total_items>0 后置为 submitted;
* 库位范围明细(scope_type=location)缺少库位(location_id 为空或 location_code 为空)时不可提交。
*
* @param {Object} params 提交参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @return {Promise<Object>} { id, status }。
* @throws {Error} 状态不允许、没有明细或存在缺少库位的明细时抛出业务错误(错误码 400)。
*/
async submit(params = {}) {
const { warehouseId, id } = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!SUBMIT_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${check.status})不允许提交审核`);
}
if (Number(check.total_items) <= 0) {
throw this.createBusinessError('盘点任务还没有明细行,无法提交审核');
}
// 盘点明细缺库位(location_id 为空或 location_code 为空)不可提交(脏数据防御):
// 库位范围明细天然必须带库位;商品范围明细按「商品 + 库位」拆行后同样必须带库位
const missingLocationCount = await ctx.model.StockCheckDetail.count({
where: {
check_id: checkId,
[Op.or]: [
{ location_id: null },
{ location_code: null },
{ location_code: '' },
],
},
});
if (missingLocationCount > 0) {
throw this.createBusinessError('存在缺少库位的盘点明细,无法提交审核');
}
// 提交审核时刷新商品范围明细行账面快照(提交时点账面=盘点基准,
// 快照失败则提交失败,保证「提交即快照」);审核通过时会再次刷新到「开始盘点」时点
await this._refreshGoodsBookSnapshot(checkId, Number(warehouseId));
await check.update({ status: 'submitted' });
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_SUBMIT',
operationAction: 'UPDATE',
changeSummary: `提交审核盘点任务 ${check.check_no}`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
checkNo: check.check_no,
message: `提交审核盘点任务 ${check.check_no}`,
},
});
return {
id: checkId,
status: 'submitted',
};
}
/**
* 取消盘点任务。
* 仅 created/submitted/rejected 状态允许;取消后置为 cancelled(终态)。
*
* @param {Object} params 取消参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @return {Promise<Object>} { id, status }。
* @throws {Error} 状态不允许时抛出业务错误(错误码 400)。
*/
async cancel(params = {}) {
const { warehouseId, id } = params;
const { ctx } = this;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (!CANCEL_ALLOWED_STATUSES.includes(check.status)) {
throw this.createBusinessError(`当前状态(${check.status})不允许取消`);
}
await check.update({ status: 'cancelled' });
await this.refreshStaticLockCache(warehouseId);
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_CANCEL',
operationAction: 'UPDATE',
changeSummary: `取消盘点任务 ${check.check_no}`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
checkNo: check.check_no,
message: `取消盘点任务 ${check.check_no}`,
},
});
return {
id: checkId,
status: 'cancelled',
};
}
/**
* 审核盘点任务。
* 仅 submitted 状态允许;approve → approved,reject → rejected(reason 可选写入备注)。
*
* @param {Object} params 审核参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {string} params.action 审核动作:approve=通过,reject=驳回。
* @param {string} [params.reason] 驳回原因(写入备注)。
* @return {Promise<Object>} { id, status, snapshot_refreshed }(snapshot_refreshed=本次刷新的商品明细快照行数,驳回为 0)。
* @throws {Error} 状态不允许或动作非法时抛出业务错误(错误码 400)。
*/
async audit(params = {}) {
const { warehouseId, id, action, reason } = params;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const actionValue = action ? String(action).trim() : '';
if (actionValue !== 'approve' && actionValue !== 'reject') {
throw this.createBusinessError('审核动作仅支持 approve/reject');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
if (check.status !== 'submitted') {
throw this.createBusinessError(`当前状态(${check.status})不允许审核`);
}
// 驳回原因:入参优先,为空时回退主表现有备注
const reasonValue = reason !== undefined && reason !== null && String(reason).trim() !== ''
? String(reason).trim()
: check.remark;
if (actionValue === 'approve') {
// 审核完成即开始盘点基准:再次刷新商品范围明细快照(覆盖提交后到达的出入库),
// 并失效静态锁定缓存(is_static=1 的任务此刻起进入锁定集合)
const refreshedCount = await this._refreshGoodsBookSnapshot(checkId, Number(warehouseId));
await check.update({ status: 'approved' });
await this.refreshStaticLockCache(warehouseId);
return await this._writeAuditLogAndResult({
check,
checkId,
warehouseId,
actionValue,
reasonValue,
refreshedCount,
});
}
await check.update({
status: 'rejected',
remark: reasonValue,
});
await this.refreshStaticLockCache(warehouseId);
return await this._writeAuditLogAndResult({
check,
checkId,
warehouseId,
actionValue,
reasonValue,
refreshedCount: 0,
});
}
/**
* 审核完成后写入操作日志并返回审核结果(审计分支共用)。
*
* @param {Object} params 参数。
* @param {Object} params.check 盘点主表模型实例。
* @param {number} params.checkId 盘点任务ID。
* @param {number} params.warehouseId 仓库ID。
* @param {string} params.actionValue 审核动作:approve/reject。
* @param {string} [params.reasonValue] 驳回原因。
* @param {number} params.refreshedCount 刷新快照的明细行数(驳回为 0)。
* @return {Promise<Object>} { id, status, snapshot_refreshed }。
*/
async _writeAuditLogAndResult(params = {}) {
const { check, checkId, warehouseId, actionValue, reasonValue, refreshedCount } = params;
const { ctx } = this;
const refreshedSuffix = actionValue === 'approve' && refreshedCount > 0
? `,刷新账面快照 ${refreshedCount} 行`
: '';
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_AUDIT',
operationAction: 'UPDATE',
changeSummary: actionValue === 'approve'
? `审核通过盘点任务 ${check.check_no}${refreshedSuffix}`
: `审核驳回盘点任务 ${check.check_no}${reasonValue ? `,原因:${reasonValue}` : ''}`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
checkNo: check.check_no,
action: actionValue,
reason: actionValue === 'reject' ? reasonValue : '',
snapshotRefreshed: refreshedCount,
message: actionValue === 'approve'
? `审核通过盘点任务 ${check.check_no}${refreshedSuffix}`
: `审核驳回盘点任务 ${check.check_no}${reasonValue ? `,原因:${reasonValue}` : ''}`,
},
});
return {
id: checkId,
status: actionValue === 'approve' ? 'approved' : 'rejected',
snapshot_refreshed: refreshedCount,
};
}
/**
* 批量删除盘点任务(仅删除已作废任务,非作废或查不到的任务跳过)。
* 入参 ids 归一化为去重后的正整数(单次上限 200);
* 按 id in ids + warehouse_id 查询主表做仓库隔离;
* 状态分流:status=cancelled 的任务级联删除,其他状态及查不到的任务计入 skipped_ids;
* 删除级联顺序(事务内):先删作业记录(StockCheckRecord where check_id in 删除集),
* 再删明细(StockCheckDetail where check_id in 删除集),最后删主表(StockCheck where id in 删除集)。
*
* @param {Object} params 批量删除参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {Array<number>|number} params.ids 盘点任务ID(数组或单个数值)。
* @return {Promise<Object>} { total, deleted_count, skipped_count, deleted_ids, skipped_ids };
* total=入参去重后数量,deleted_ids/skipped_ids 均保持入参顺序。
* @throws {Error} 缺少仓库上下文、ids 为空或超过单次上限时抛出业务错误(错误码 400)。
*/
async batchDelete(params = {}) {
const { warehouseId, ids } = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const normalizedWarehouseId = Number(warehouseId);
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
throw this.createBusinessError('无法获取当前仓库上下文');
}
const numericIds = this._normalizeIdList(ids);
if (numericIds.length === 0) {
throw this.createBusinessError('ids 不能为空');
}
if (numericIds.length > 200) {
throw this.createBusinessError('单次最多删除 200 个盘点任务');
}
// 仓库隔离查询主表:id in ids + warehouse_id
const checkRows = await ctx.model.StockCheck.findAll({
where: {
id: { [Op.in]: numericIds },
warehouse_id: normalizedWarehouseId,
},
attributes: [ 'id', 'status' ],
raw: true,
});
const checkMap = new Map(checkRows.map(row => [ Number(row.id), row ]));
// 状态分流:仅 cancelled 删除;其他状态及查不到的任务计入 skipped_ids(保持入参顺序)
const deletedIds = [];
const skippedIds = [];
for (const checkId of numericIds) {
const row = checkMap.get(checkId);
if (row && row.status === 'cancelled') {
deletedIds.push(checkId);
} else {
skippedIds.push(checkId);
}
}
// 级联删除(事务):作业记录 → 明细 → 主表
if (deletedIds.length > 0) {
await ctx.model.transaction(async transaction => {
await ctx.model.StockCheckRecord.destroy({
where: { check_id: { [Op.in]: deletedIds } },
transaction,
});
await ctx.model.StockCheckDetail.destroy({
where: { check_id: { [Op.in]: deletedIds } },
transaction,
});
await ctx.model.StockCheck.destroy({
where: { id: { [Op.in]: deletedIds } },
transaction,
});
});
await this.refreshStaticLockCache(normalizedWarehouseId);
}
// 事务提交后写入操作日志(不随事务回滚残留,失败不影响主流程)
if (deletedIds.length > 0) {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: deletedIds[0],
operationCode: 'STOCK_CHECK_BATCH_DELETE',
operationAction: 'DELETE',
changeSummary: `批量删除盘点任务:删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: normalizedWarehouseId,
deletedIds,
skippedIds,
deletedCount: deletedIds.length,
skippedCount: skippedIds.length,
message: `批量删除盘点任务:删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`,
},
});
}
return {
total: numericIds.length,
deleted_count: deletedIds.length,
skipped_count: skippedIds.length,
deleted_ids: deletedIds,
skipped_ids: skippedIds,
};
}
/**
* 盘点任务导出:查询任务与作业记录 → Sheet1「盘点单」一行一个盘点任务、
* Sheet2「盘点明细」一行一条实际盘点记录(商品/库位/实盘数量/盘点人/时间,
* 不导出未盘的任务范围行)→ 流式生成 Excel → COS 上传。
* 未知商品(stock_id 为空)商品编码列显示扫描条码(barcode)、商品名称列显示上报名称快照
* (item_name);已知商品维持现有口径。通过 onProgress 回调实时推送进度。
*
* @param {Object} params 导出参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {Array<number>} params.ids 盘点任务ID数组。
* @param {Function} [params.onProgress] 进度回调。
* @return {Promise<Object>} 导出结果,包含文件下载信息与数量统计。
* @throws {Error} 没有可导出的任务时抛出业务错误(错误码 400)。
*/
async exportStockChecks(params = {}) {
const { warehouseId, ids, onProgress } = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const reportProgress = async (status, progress, message, extra = {}) => {
if (typeof onProgress === 'function') {
await onProgress({ status, progress, message, ...extra });
}
};
await reportProgress('running', 5, '正在准备导出数据...');
const numericIds = this._normalizeIdList(ids);
if (numericIds.length === 0) {
throw this.createBusinessError('请至少选择一个盘点任务');
}
const checks = await ctx.model.StockCheck.findAll({
where: {
id: { [Op.in]: numericIds },
warehouse_id: Number(warehouseId),
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
if (checks.length === 0) {
throw this.createBusinessError('未找到可导出的盘点任务');
}
// 盘点明细导出:直接拉作业记录(实际盘过的库位+数量),不按任务范围行展开(任务明细不导出)
const recordRows = await ctx.model.StockCheckRecord.findAll({
where: { check_id: { [Op.in]: numericIds } },
order: [[ 'check_id', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
});
// 商品快照(item_code/item_name)从 wms_stock_warehouse 补齐(库位行的记录没有商品快照)
const stockIds = [ ...new Set(recordRows.map(row => Number(row.stock_id)).filter(id => Number.isInteger(id) && id > 0)) ];
let stockMap = new Map();
if (stockIds.length > 0) {
const stockRows = await ctx.model.StockWarehouse.findAll({
where: { id: { [Op.in]: stockIds } },
attributes: [ 'id', 'item_code', 'item_name' ],
raw: true,
});
stockMap = new Map(stockRows.map(item => [ Number(item.id), item ]));
}
const recordsGrouped = new Map();
for (const row of recordRows) {
const recordStockId = Number(row.stock_id);
const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0;
const stock = stockMap.get(recordStockId) || {};
const checkId = Number(row.check_id);
if (!recordsGrouped.has(checkId)) {
recordsGrouped.set(checkId, []);
}
recordsGrouped.get(checkId).push({
...row,
// 未知商品(stock_id 为空):商品编码列显示扫描条码、商品名称列显示上报名称快照;
// 已知商品维持现有口径(wms_stock_warehouse 商品快照)
item_code: isUnknownGoods ? (String(row.barcode || '').trim() || null) : (stock.item_code || null),
item_name: isUnknownGoods ? (String(row.item_name || row.barcode || '').trim() || null) : (stock.item_name || null),
});
}
const totalCount = recordRows.length;
await reportProgress('running', 10, `共 ${checks.length} 个盘点任务、${totalCount} 条盘点明细,开始导出...`, {
totalCount,
currentCount: 0,
});
const exportResult = await this._generateAndUploadStockCheckExcel(checks, recordsGrouped, {
totalCount,
onProgress,
});
await reportProgress('success', 100, '导出完成', {
totalCount,
currentCount: totalCount,
result: exportResult,
});
return {
...exportResult,
total_count: totalCount,
current_count: totalCount,
};
}
/**
* 生成盘点导出 Excel(Sheet1=盘点单行,Sheet2=盘点明细(作业记录:库位+数量+盘点人+时间))
* 并上传 COS,返回下载信息。
* 与售后/退回拆包导出口径一致:流式写临时文件 → uploadFile → uploadSuccessNotify。
*
* @param {Array<Object>} checks 盘点任务主表行。
* @param {Map<number, Array<Object>>} recordsGrouped 按 check_id 分组的作业记录行(含 item_code/item_name 快照)。
* @param {Object} [options] 附加选项。
* @param {number} [options.totalCount] 作业记录总行数(用于进度计算)。
* @param {Function} [options.onProgress] 进度回调。
* @return {Promise<Object>} { filename, fileKey, url, cdnUrl, cosUrl }。
*/
async _generateAndUploadStockCheckExcel(checks = [], recordsGrouped = new Map(), options = {}) {
const { totalCount = 0, onProgress } = options;
const { ctx } = this;
const reportProgress = async (status, progress, message, extra = {}) => {
if (typeof onProgress === 'function') {
await onProgress({ status, progress, message, ...extra });
}
};
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-stock-check-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `库存盘点导出_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
try {
// ---- Sheet1:盘点单行(一行一个盘点任务) ----
const checksSheet = workbook.addWorksheet('盘点单');
checksSheet.addRow([
'盘点单号',
'盘点名称',
'盘点范围',
'盘点方式',
'盘点状态',
'盘点进度',
'货主ID',
'创建人',
'明细行数',
'已盘行数',
'差异行数',
'开始时间',
'结束时间',
'备注',
]).commit();
for (const check of checks) {
checksSheet.addRow([
check.check_no || '',
check.title || '',
STOCK_CHECK_TYPE_LABELS[check.type] || check.type || '',
STOCK_CHECK_MODE_LABELS[check.mode] || check.mode || '',
STOCK_CHECK_STATUS_LABELS[check.status] || check.status || '',
STOCK_CHECK_DETAIL_PROGRESS_LABELS[check.detail_status] || check.detail_status || '',
check.store_id === null || check.store_id === undefined ? '' : Number(check.store_id),
check.creator_name || '',
Number(check.total_items) || 0,
Number(check.checked_items) || 0,
Number(check.diff_items) || 0,
this._formatLocalDateTime(check.start_time),
this._formatLocalDateTime(check.end_time),
check.remark || '',
]).commit();
}
checksSheet.commit();
// ---- Sheet2:盘点明细(作业记录:一行一条实际盘点记录,不含未盘的任务范围行) ----
const detailsSheet = workbook.addWorksheet('盘点明细');
detailsSheet.addRow([
'盘点单号',
'商品编码',
'商品名称',
'库位编码',
'实盘数量',
'盘点人',
'盘点时间',
]).commit();
let currentCount = 0;
for (const check of checks) {
const checkId = Number(check.id);
const rows = recordsGrouped.get(checkId) || [];
for (const row of rows) {
detailsSheet.addRow([
check.check_no || '',
row.is_empty ? '(空库位)' : (row.item_code || ''),
row.is_empty ? '' : (row.item_name || ''),
String(row.location_code || '').trim() !== '' ? row.location_code : '',
row.is_empty ? 0 : (Number(row.quantity) || 0),
row.checker_name || '',
this._formatLocalDateTime(row.checked_at),
]).commit();
currentCount++;
// 每 200 行汇报一次进度
if (currentCount % 200 === 0 || currentCount === totalCount) {
const progress = 10 + Math.floor((currentCount / Math.max(1, totalCount)) * 80);
await reportProgress('running', progress, `正在导出... (${currentCount}/${totalCount})`, {
totalCount,
currentCount,
});
}
}
}
detailsSheet.commit();
await workbook.commit();
await reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: totalCount });
// ---- 上传文件(与 afterSale/return_unpack 导出口径一致)----
const uploadInfo = await this._uploadExportExcelFile(filePath, filename, {
businessType: 'stockCheckExport',
description: `库存盘点导出,共 ${checks.length} 个盘点任务、${totalCount} 条盘点明细`,
});
return uploadInfo;
} catch (error) {
const workbookStream = workbook.stream;
if (workbookStream && typeof workbookStream.destroy === 'function') {
workbookStream.destroy();
}
ctx.logger.error(`[stock.check.export] 生成/上传 Excel 失败: ${error.message}`);
throw error;
} finally {
await fsp.rm(tempDir, { recursive: true, force: true });
}
}
/**
* 上传导出的 Excel 文件(与 afterSale/return_unpack 导出口径一致):
* 流式上传 → uploadFile → uploadSuccessNotify 落库,返回下载信息。
*
* @param {string} filePath 本地临时文件路径。
* @param {string} filename 文件名。
* @param {Object} [options] 附加选项。
* @param {string} [options.businessType] 业务类型(默认 stockCheckExport)。
* @param {string} [options.description] 文件描述。
* @return {Promise<Object>} { filename, fileKey, url, cdnUrl, cosUrl }。
*/
async _uploadExportExcelFile(filePath, filename, options = {}) {
const { ctx } = this;
const businessType = options.businessType || 'stockCheckExport';
const description = options.description || '';
const uploadService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.upload;
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
throw new Error('上传服务不可用');
}
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/stock_check/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
let fileRecord = null;
if (typeof uploadService.uploadSuccessNotify === 'function') {
fileRecord = await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
category: 'document',
businessType,
description,
});
}
// 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录,最后回退 COS key
const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {};
const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null;
const fileUrlFromRecord = resolvedFileRecord
? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '')
: '';
const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || '';
return {
filename,
fileKey: safeUploadResult.fileName || uploadKey,
url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey,
cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '',
cosUrl: safeUploadResult.cosUrl || '',
};
}
/**
* 盘点明细导出(单任务,按盘点范围分流):
* - 商品范围(scope_type=goods)固定两个 sheet:
* Sheet1「汇总和差异」——每商品一行(盘点单号/商品编码/条码(wms_stock_barcodes 第一条)/
* 商品名称/规格/账面数量(快照合计)/盘点数量/差异数量/差异类型(盘盈|盘亏,未盘留空);
* 未知商品(条码维度,无账面、差异=实盘=盘盈)追加在末尾;
* Sheet2「库位明细」——直接按作业记录(wms_stock_check_record)一行一条实际盘点记录
* (库位编码/数量(实盘)/条码/商品名称;未知商品条码=扫描条码)。
* - 库位范围(scope_type=location):Sheet「盘点明细」——库位编码/商品编码/商品名称/盘点数量
* (作业记录口径,未知商品编码=扫描条码,空库位标记商品为空、数量 0)。
* 流式生成 Excel → COS 上传;通过 onProgress 回调实时推送进度。
*
* @param {Object} params 导出参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @param {Function} [params.onProgress] 进度回调。
* @return {Promise<Object>} 导出结果,包含文件下载信息与 total_count。
* @throws {Error} 任务不存在或参数非法时抛出业务错误(错误码 400)。
*/
async exportCheckDetail(params = {}) {
const { warehouseId, id, onProgress } = params;
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const reportProgress = async (status, progress, message, extra = {}) => {
if (typeof onProgress === 'function') {
await onProgress({ status, progress, message, ...extra });
}
};
await reportProgress('running', 5, '正在准备导出数据...');
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
throw this.createBusinessError('盘点任务ID不能为空');
}
const check = await this._findCheck(warehouseId, checkId);
if (!check) {
throw this.createBusinessError('盘点任务不存在');
}
const detailRows = await ctx.model.StockCheckDetail.findAll({
where: { check_id: checkId, warehouse_id: Number(warehouseId) },
order: [[ 'id', 'ASC' ]],
raw: true,
});
const records = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkId, warehouse_id: Number(warehouseId) },
order: [[ 'id', 'ASC' ]],
raw: true,
});
const isLocationScope = detailRows.length > 0
&& detailRows.every(row => (row.scope_type || 'goods') === 'location');
// 商品范围:复用 result 的商品合并聚合(账面=快照、实盘=作业记录聚合)
let goodsRows = [];
if (!isLocationScope) {
goodsRows = (await this._buildDetailAggregations({ detailRows, recordRows: records }))
.filter(row => row.scope_type === 'goods');
}
// 库位范围商品快照(库位行的作业记录不带商品快照列)
const stockIds = [ ...new Set(records
.map(row => Number(row.stock_id))
.filter(stockId => Number.isInteger(stockId) && stockId > 0)) ];
let stockMap = new Map();
if (stockIds.length > 0) {
const stockRows = await ctx.model.StockWarehouse.findAll({
where: { id: { [Op.in]: stockIds } },
attributes: [ 'id', 'item_code', 'item_name' ],
raw: true,
});
stockMap = new Map(stockRows.map(item => [ Number(item.id), item ]));
}
// 商品范围:商品条码(wms_stock_barcodes 按 stock_id 取第一条,库位明细 sheet 的条码列)
const barcodeMap = new Map();
if (!isLocationScope) {
const goodsStockIds = [ ...new Set(goodsRows
.map(row => Number(row.stock_id))
.filter(stockId => Number.isInteger(stockId) && stockId > 0)) ];
if (goodsStockIds.length > 0) {
const barcodeRows = await ctx.model.StockBarcode.findAll({
where: {
warehouse_id: Number(warehouseId),
stock_id: { [Op.in]: goodsStockIds },
},
attributes: [ 'stock_id', 'barcode' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
for (const barcodeRow of barcodeRows) {
const barcodeStockId = Number(barcodeRow.stock_id);
if (!barcodeMap.has(barcodeStockId)) {
barcodeMap.set(barcodeStockId, String(barcodeRow.barcode || '').trim());
}
}
}
}
// 库位显示覆盖:自定义名称优先 → 自定义编码次之 → 最后才显示库位编码
const locationDisplayMap = new Map();
const recordLocationCodes = [ ...new Set(records
.map(record => String(record.location_code || '').trim())
.filter(Boolean)) ];
if (recordLocationCodes.length > 0) {
const spaceRows = await ctx.model.LocationSpace.findAll({
where: {
warehouse_id: Number(warehouseId),
space_code: { [Op.in]: recordLocationCodes },
},
attributes: [ 'space_code', 'custom_name', 'custom_barcode' ],
raw: true,
});
for (const spaceRow of spaceRows) {
const code = String(spaceRow.space_code || '').trim();
if (!code) {
continue;
}
const candidate = {
custom_name: String(spaceRow.custom_name || '').trim(),
custom_barcode: String(spaceRow.custom_barcode || '').trim(),
};
// 同仓库同编码可能有多条库位(历史重复/无头库位):优先保留有自定义名称的行,
// 避免空值行后写覆盖,导致导出回退成库位编码
const existing = locationDisplayMap.get(code);
const shouldReplace = !existing
|| (!existing.custom_name && candidate.custom_name)
|| (!existing.custom_name && !candidate.custom_name && candidate.custom_barcode);
if (shouldReplace) {
locationDisplayMap.set(code, candidate);
}
}
}
const totalCount = isLocationScope
? records.length
: goodsRows.reduce(
(sum, row) => sum + 1 + (Array.isArray(row.unknown_items) ? row.unknown_items.length : 0),
0
) + records.length;
await reportProgress('running', 10, `正在导出盘点明细(共 ${totalCount} 行)...`, {
totalCount,
currentCount: 0,
});
const exportResult = await this._generateAndUploadCheckDetailExcel({
check: check.get({ plain: true }),
isLocationScope,
goodsRows,
records,
stockMap,
barcodeMap,
locationDisplayMap,
totalCount,
onProgress,
});
await reportProgress('success', 100, '导出完成', {
totalCount,
currentCount: totalCount,
result: exportResult,
});
return {
...exportResult,
total_count: totalCount,
current_count: totalCount,
};
}
/**
* 库位编码显示覆盖:自定义名称优先 → 自定义编码(custom_barcode)次之 → 库位编码(space_code)兜底;
* 库位编码为空或无匹配库位时返回空/库位编码。
*
* @param {string} locationCode 作业记录库位编码。
* @param {Map<string, Object>} locationDisplayMap 库位编码 → { custom_name, custom_barcode } 映射。
* @return {string} 显示用的库位文本。
*/
_resolveLocationDisplayCode(locationCode, locationDisplayMap = new Map()) {
const code = String(locationCode || '').trim();
if (!code) {
return '';
}
const space = locationDisplayMap.get(code);
if (!space) {
return code;
}
return space.custom_name || space.custom_barcode || code;
}
/**
* 生成盘点明细导出 Excel 并上传 COS(Sheet 结构随盘点范围变化,见 exportCheckDetail)。
*
* @param {Object} params 生成参数。
* @param {Object} params.check 盘点主表行。
* @param {boolean} params.isLocationScope 是否库位范围盘点。
* @param {Array<Object>} params.goodsRows 商品范围聚合行(result 口径)。
* @param {Array<Object>} params.records 作业记录原始行。
* @param {Map<number, Object>} params.stockMap 商品快照映射(库位范围用)。
* @param {Map<number, string>} params.barcodeMap 商品条码映射(商品范围库位明细 sheet 用)。
* @param {Map<string, Object>} params.locationDisplayMap 库位显示覆盖映射(库位编码 → { custom_name, custom_barcode })。
* @param {number} params.totalCount 总行数(进度计算用)。
* @param {Function} [params.onProgress] 进度回调。
* @return {Promise<Object>} { filename, fileKey, url, cdnUrl, cosUrl }。
*/
async _generateAndUploadCheckDetailExcel(params = {}) {
const {
check,
isLocationScope,
goodsRows = [],
records = [],
stockMap = new Map(),
barcodeMap = new Map(),
locationDisplayMap = new Map(),
totalCount = 0,
onProgress,
} = params;
const { ctx } = this;
const reportProgress = async (status, progress, message, extra = {}) => {
if (typeof onProgress === 'function') {
await onProgress({ status, progress, message, ...extra });
}
};
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-stock-check-detail-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `盘点明细导出_${check.check_no || check.id}_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
try {
const checkNo = String(check.check_no || '');
let currentCount = 0;
const reportRowProgress = async () => {
currentCount++;
if (currentCount % 200 === 0 || currentCount === totalCount) {
const progress = 10 + Math.floor((currentCount / Math.max(1, totalCount)) * 80);
await reportProgress('running', progress, `正在导出... (${currentCount}/${totalCount})`, {
totalCount,
currentCount,
});
}
};
if (isLocationScope) {
// ---- 库位范围:库位 / 商品 / 盘点数量 ----
const sheet = workbook.addWorksheet('盘点明细');
sheet.addRow([ '库位编码', '商品编码', '商品名称', '盘点数量' ]).commit();
for (const record of records) {
const recordStockId = Number(record.stock_id);
const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0;
const stock = stockMap.get(recordStockId) || {};
sheet.addRow([
this._resolveLocationDisplayCode(record.location_code, locationDisplayMap),
record.is_empty ? '' : (isUnknownGoods ? String(record.barcode || '').trim() : (stock.item_code || '')),
record.is_empty ? '' : (isUnknownGoods ? String(record.item_name || record.barcode || '').trim() : (stock.item_name || '')),
record.is_empty ? 0 : (Number(record.quantity) || 0),
]).commit();
await reportRowProgress();
}
sheet.commit();
} else {
// ---- 商品范围:汇总和差异 + 库位明细 两个 sheet ----
const summarySheet = workbook.addWorksheet('汇总和差异');
summarySheet.addRow([
'盘点单号',
'商品编码',
'条码',
'商品名称',
'规格',
'账面数量',
'盘点数量',
'差异数量',
'差异类型',
]).commit();
const locationSheet = workbook.addWorksheet('库位明细');
locationSheet.addRow([ '库位编码', '数量', '条码', '商品名称' ]).commit();
for (const row of goodsRows) {
const hasRecords = Array.isArray(row.records) && row.records.length > 0;
const diffQuantity = hasRecords ? (Number(row.diff_quantity) || 0) : 0;
summarySheet.addRow([
checkNo,
row.item_code || '',
barcodeMap.get(Number(row.stock_id)) || '',
row.item_name || '',
row.spec || '',
Number(row.system_quantity) || 0,
hasRecords ? (Number(row.checked_quantity) || 0) : '',
hasRecords ? diffQuantity : '',
!hasRecords ? '' : (diffQuantity > 0 ? '盘盈' : (diffQuantity < 0 ? '盘亏' : '')),
]).commit();
await reportRowProgress();
// 未知商品(条码维度,无账面,差异=实盘=盘盈;商品编码列即扫描条码,条码列留空避免重复)
for (const unknownItem of (Array.isArray(row.unknown_items) ? row.unknown_items : [])) {
const checkedQuantity = Number(unknownItem.checked_quantity) || 0;
summarySheet.addRow([
checkNo,
unknownItem.barcode || '',
'',
unknownItem.item_name || '',
'',
0,
checkedQuantity,
checkedQuantity,
'盘盈',
]).commit();
await reportRowProgress();
}
}
// 库位明细:直接按作业记录(wms_stock_check_record)一行一条实际盘点记录
const itemNameByStock = new Map(goodsRows
.filter(row => row.stock_id)
.map(row => [ Number(row.stock_id), row.item_name || '' ]));
for (const record of records) {
const recordStockId = Number(record.stock_id);
const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0;
locationSheet.addRow([
this._resolveLocationDisplayCode(record.location_code, locationDisplayMap),
record.is_empty ? 0 : (Number(record.quantity) || 0),
record.is_empty ? '' : (isUnknownGoods ? String(record.barcode || '').trim() : (barcodeMap.get(recordStockId) || '')),
record.is_empty ? '' : (isUnknownGoods ? String(record.item_name || record.barcode || '').trim() : (itemNameByStock.get(recordStockId) || '')),
]).commit();
await reportRowProgress();
}
summarySheet.commit();
locationSheet.commit();
}
await workbook.commit();
await reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: totalCount });
const uploadInfo = await this._uploadExportExcelFile(filePath, filename, {
businessType: 'stockCheckDetailExport',
description: `盘点明细导出 ${check.check_no || check.id},共 ${totalCount} 行`,
});
return uploadInfo;
} catch (error) {
const workbookStream = workbook.stream;
if (workbookStream && typeof workbookStream.destroy === 'function') {
workbookStream.destroy();
}
ctx.logger.error(`[stock.check.exportDetail] 生成/上传 Excel 失败: ${error.message}`);
throw error;
} finally {
await fsp.rm(tempDir, { recursive: true, force: true });
}
}
}
module.exports = StockCheckService;