WMS_MAIN/app/service/systems/stock_check.js
liufumingren 9743416187 feat: 盘点作业数据接口改造与账面口径全量统一(可用+锁定)
- workData 三视图:goods 视图 locations=商品所在全部库位列表(明盘每库位 system_quantity 账面/quantity 盘点、盲盘只显示库位);space 视图同口径;新增 workDataSpaceDetails 分页版
- workDataDetail 增加 goods 分支(单行结构,复用视图构建器);detail 补 profit_total/loss_total 差异汇总
- 库位账面全量统一为 SUM(available_quantity+locked_quantity)(可用+锁定)并标记 locked_quantity:result/report/finish/detail/addDetail 拆行快照与作业视图一致
- 未盘行不误显盘亏:diff/is_diff 仅存在作业记录时计算
- 文档 methods/system.json 0.3.249 + changes 变更记录,开发/生产库已回填
2026-10-06 03:24:41 +08:00

4529 lines
185 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([ 'all', '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' ]);
/** 允许提交审核的主表状态 */
const SUBMIT_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]);
/** 允许取消的主表状态 */
const CANCEL_ALLOWED_STATUSES = Object.freeze([ 'created', 'submitted', 'rejected' ]);
/** 盘点范围类型中文标签 */
const STOCK_CHECK_TYPE_LABELS = Object.freeze({
all: '全盘',
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 || 'all',
mode: row.mode || 'open',
store_id: row.store_id || null,
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) },
});
}
/**
* 重算盘点主表的盘点进度汇总(checked_items / diff_items / detail_status)。
* 明细已盘口径:该明细存在盘点作业记录(wms_stock_check_record);
* 差异口径:明细行内任一商品「实盘合计 ≠ 账面」即该行有差异,按明细去重计数;
* 商品行账面 = system_quantity 快照,库位行账面 = 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 { fn, col, Op, literal } = ctx.app.Sequelize;
const checkIdNumber = Number(checkId);
const detailWhere = { check_id: checkIdNumber };
const totalItems = await ctx.model.StockCheckDetail.count({ where: detailWhere });
// 有作业记录的明细数(DISTINCT detail_id)
const checkedCountRows = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkIdNumber },
attributes: [[ fn('COUNT', fn('DISTINCT', col('detail_id'))), 'checkedCount' ]],
raw: true,
});
const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0;
// 明细与作业记录
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');
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 + locked_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 + locked_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 即盘盈、必然计入差异;
// 空库位标记明细:账面有库存即盘亏差异(标记空与实际不符)
let diffItems = 0;
for (const detailRow of detailRows) {
const detailId = Number(detailRow.id);
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
if (scopeType === 'location' && 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;
if (scopeType === 'goods') {
const systemQuantity = Number(detailRow.system_quantity || 0);
hasDiff = (checkedQuantityByDetail.get(detailId) || 0) !== systemQuantity;
} else {
for (const agg of (byStock ? byStock.values() : [])) {
if (agg.checked !== (agg.system || 0)) {
hasDiff = true;
break;
}
}
if (!hasDiff && byUnknown) {
for (const agg of byUnknown.values()) {
if (agg.checked > 0) {
hasDiff = true;
break;
}
}
}
}
if (hasDiff) {
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='all'] 盘点范围类型:all/store/goods/location。
* @param {string} [params.mode='open'] 盘点方式:open=明盘/blind=盲盘;
* 按库位盘点(all/location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
* @param {number} [params.storeId] 货主ID(按货主盘点时必填)。
* @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,
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() : 'all';
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('/')}`);
}
// 按库位盘点(all/location)一律盲盘,不管前端传入什么;
// 按商品盘点(store/goods)按传入值(默认明盘)
if (normalizedType === 'all' || 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('按货主盘点时必须指定货主');
}
// 创建盘点任务(并发下撞 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,
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]}`,
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,
message: `创建盘点任务 ${plainRecord.check_no}(${STOCK_CHECK_TYPE_LABELS[normalizedType]}/${STOCK_CHECK_MODE_LABELS[normalizedMode]})`,
},
});
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';
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,
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 totalItems = await ctx.model.StockCheckDetail.count({
where: { check_id: record.id },
});
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]}`,
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 添加商品行(商品必须属于
* 任务货主);all/location 类型按 locations(库位编码,兼容旧调用)或 location_ids
* (库位ID,直接查库校验,不再解析编码)添加库位行,两者都传时 location_ids 优先、
* locations 忽略;all 未传库位且未传库位ID时自动拉取全仓库启用库位;
* 兼容历史任务:type=all 且已存在商品明细行(改造前创建)时继续按商品模式接受 stock_ids;
* 已存在的同盘点项跳过(幂等),重算主表 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 || 'all').trim();
let isGoodsScope = checkType === 'store' || checkType === 'goods';
let isLocationScope = checkType === 'all' || checkType === 'location';
const numericStockIds = this._normalizeIdList(stockIds);
const locationCodes = this._normalizeCodeList(locations);
const numericLocationIds = this._normalizeIdList(locationIds);
// 兼容历史任务:改造前 type=all 的任务按商品添加明细(明细行 scope_type='goods')。
// 这类任务已存在商品明细行时,继续按商品模式接受 stock_ids,避免旧调用被 400 拒绝;
// 全新 type=all 任务(无任何商品明细行)维持新语义:按库位盘点,只能传 locations。
if (checkType === 'all' && isLocationScope) {
const goodsScopeCount = await ctx.model.StockCheckDetail.count({
where: { check_id: checkId, scope_type: 'goods' },
});
if (goodsScopeCount > 0) {
isGoodsScope = true;
isLocationScope = false;
}
}
// 按盘点类型校验入参维度(商品与库位互斥)
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;
// 全盘:未显式传库位时自动拉取全仓库启用库位
if (checkType === 'all' && codes.length === 0) {
const enabledSpaces = await ctx.model.LocationSpace.findAll({
where: { warehouse_id: Number(warehouseId), is_enabled: true },
attributes: [ 'space_code' ],
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('当前仓库没有启用库位,无法按全盘自动生成盘点范围');
}
}
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 totalItems = await ctx.model.StockCheckDetail.count({
where: { check_id: checkId },
});
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(可用+锁定);无库存库位商品不可盘点)
const storageRows = await ctx.model.Storage.findAll({
where: {
warehouse_id: Number(warehouseId),
stock_id: { [Op.in]: numericStockIds },
is_enabled: 1,
},
attributes: [
'stock_id',
'space_id',
[ literal('SUM(available_quantity + locked_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,
});
}
}
}
/**
* 生成按库位盘点明细的待创建行(all/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' ],
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直查路径,all/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(不报错)
const spaceRows = await ctx.model.LocationSpace.findAll({
where: {
id: { [Op.in]: numericLocationIds },
warehouse_id: Number(warehouseId),
},
attributes: [ 'id', 'space_code' ],
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 totalItems = await ctx.model.StockCheckDetail.count({
where: { check_id: checkId },
});
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,
},
};
}
/**
* 拉取盘点明细结果(按范围行聚合作业记录)。
* 商品行聚合其库位作业记录,库位行按商品聚合作业记录并从 wms_storage 补齐账面数量。
* 未知商品(记录 stock_id 为空)按 barcode 维度归组,行级额外输出 unknown_items;
* 每条作业记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径)。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.id 盘点任务ID。
* @return {Promise<Object>} { check, rows, total };商品行含商品快照 + 已盘聚合
* (checked_quantity=记录数量合计、diff_quantity=实盘-账面、is_diff、status、location_codes、
* checkers、last_checked_at)、records(该明细全部作业记录,每条含 barcode/item_name/images)与 locations
* (按库位聚合 [{ location_id, location_code, quantity }],按首条记录 id 升序);
* 库位行输出 { ...row, scope_type: 'location', stocks },stocks 按商品聚合该明细下记录
* [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],
* 账面数量查 wms_storage SUM(available_quantity+locked_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,
});
// 挂载作业记录图片(FileReference business_type=stock_check_record,与收货 receivingItem 口径一致)
await this._attachRecordImages(records);
const rows = await this._buildDetailAggregations({ detailRows, recordRows: records });
return {
check: this._formatCheckRow(check.get({ plain: true })),
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)) || [];
}
}
/**
* 构建盘点明细聚合行(商品行聚合其库位作业记录;库位行按商品聚合作业记录,
* 并从 wms_storage 补齐各商品账面数量;未知商品按 barcode 维度归组输出 unknown_items)。
*
* @param {Object} params 聚合参数。
* @param {Array<Object>} params.detailRows 明细原始行。
* @param {Array<Object>} params.recordRows 作业记录原始行。
* @return {Promise<Array<Object>>} 格式化后的明细行列表。
*/
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);
}
// 收集商品 ID 集合:商品行取明细 stock_id,库位行取记录 stock_id
const stockIds = new Set();
const locationRows = [];
for (const detailRow of detailRows) {
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
if (scopeType === 'goods') {
if (detailRow.stock_id) {
stockIds.add(Number(detailRow.stock_id));
}
} else {
locationRows.push(detailRow);
const detailRecords = recordsByDetail.get(Number(detailRow.id)) || [];
for (const record of detailRecords) {
if (record.stock_id) {
stockIds.add(Number(record.stock_id));
}
}
}
}
// 商品快照(item_code/item_name)从 wms_stock_warehouse 补齐
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 + locked_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
);
}
}
}
return Promise.all(detailRows.map(detailRow => this._formatDetailAggregationRow({
detailRow,
recordsByDetail,
stockMap,
storageQuantityMap,
})));
}
/**
* 将单条盘点明细格式化为聚合输出行。
* 商品行:聚合作业记录输出已盘数量/差异/库位列表等;
* 库位行:按商品聚合作业记录输出 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,
};
if (scopeType === 'goods') {
const checkedQuantity = detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0);
const diffQuantity = checkedQuantity - Number(detailRow.system_quantity || 0);
return {
...base,
checked_quantity: detailRecords.length > 0 ? checkedQuantity : null,
diff_quantity: detailRecords.length > 0 ? diffQuantity : null,
is_diff: detailRecords.length > 0 && diffQuantity !== 0 ? 1 : 0,
status: detailRecords.length > 0 ? 'checked' : 'unchecked',
unknown_items: unknownItems,
};
}
// 库位行:按商品聚合记录,账面从 wms_storage 取(location_id 为空时账面按 0);
// 空库位标记:无商品聚合,账面有库存即盘亏(差异 = -账面总量)
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 + locked_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;
}
/**
* 盘点作业上报(覆盖式)。
* 仅 approved/checking 状态允许;商品明细行固定上报明细商品(入参商品不一致报错),
* 库位明细行必须指定商品且商品必须属于本仓库,库位以明细库位为准(入参库位不一致报错);
* 同明细 + 同商品 + 同库位编码重复上报时更新已有记录的
* quantity/checker_id/checker_name/checked_at(保留原 location_id,若本次新匹配到 location_id 则回填),
* 不再新增;未传库位归入"无库位"分组(location_code 存空串);
* 库位编码匹配 wms_location_space.space_code 时回填 location_id;
* 主表 approved 自动转 checking;重算 checked_items / diff_items / detail_status。
* 数据库层由唯一索引 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] 库位编码(可空;库位明细行以明细库位为准)。
* @param {number} params.quantity 实盘数量(>=0)。
* @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/all)时允许:非库位任务报 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' && normalizedType !== 'all') {
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 空库位标记口径(查重/互斥/汇总/日志统一)
return this.report({
warehouseId,
id: checkId,
detailId: detailRowId,
is_empty: true,
checkerId,
checkerName,
});
}
async report(params = {}) {
const {
warehouseId,
id,
detailId,
location,
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不能为空');
}
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 quantityValue = normalizedIsEmpty ? 0 : Number(quantity);
if (!normalizedIsEmpty && (!Number.isInteger(quantityValue) || quantityValue < 0)) {
throw this.createBusinessError('实盘数量必须为不小于0的整数');
}
const detail = await ctx.model.StockCheckDetail.findOne({
where: { id: detailRowId, check_id: checkId, warehouse_id: Number(warehouseId) },
});
if (!detail) {
throw this.createBusinessError('盘点明细不存在');
}
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()
: '';
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;
}
// 库位编码匹配 wms_location_space.space_code 时回填 location_id;
// 未传库位归一为空串("无库位"分组,配合 uk_detail_stock_location 唯一索引)
locationCode = location !== undefined && location !== null && String(location).trim() !== ''
? String(location).trim()
: '';
if (locationCode) {
const space = await ctx.model.LocationSpace.findOne({
where: {
warehouse_id: Number(warehouseId),
space_code: locationCode,
},
attributes: [ 'id' ],
raw: true,
});
if (space) {
locationId = space.id;
}
}
} else {
// 库位行:以明细库位为准
locationCode = String(detail.location_code || '').trim();
if (!locationCode) {
throw this.createBusinessError('盘点明细缺少库位信息');
}
const inputLocation = location !== undefined && location !== null && String(location).trim() !== ''
? String(location).trim()
: '';
if (inputLocation && inputLocation !== locationCode) {
throw this.createBusinessError('上报库位与盘点明细库位不一致');
}
locationId = detail.location_id !== null && detail.location_id !== undefined
? Number(detail.location_id)
: null;
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;
}
}
}
const now = new Date();
// 覆盖式上报:已知商品按同明细 + 同商品 + 同库位编码(未传库位为空串"无库位"分组)更新已有记录,
// 依赖唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全;
// 未知商品唯一索引不约束 NULL 行,按同明细 + 同条码 + 同库位编码在应用层查重;
// 空库位标记按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新
const existingRecordWhere = normalizedIsEmpty
? {
detail_id: detailRowId,
is_empty: true,
location_code: locationCode,
}
: (isUnknownGoods
? {
detail_id: detailRowId,
stock_id: null,
barcode: normalizedBarcode,
location_code: locationCode,
}
: {
detail_id: detailRowId,
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: detailRowId,
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: detailRowId, is_empty: false },
});
} else {
await ctx.model.StockCheckRecord.destroy({
where: { detail_id: detailRowId, 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);
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_REPORT',
operationAction: 'UPDATE',
changeSummary: normalizedIsEmpty
? `盘点作业上报:明细 ${detailRowId} 确认库位 ${locationCode || '未指定'} 为空`
: `盘点作业上报:明细 ${detailRowId},库位 ${locationCode || '未指定'},实盘 ${quantityValue}${normalizedBarcode ? `,条码 ${normalizedBarcode}` : ''}(${mode === 'created' ? '新增' : '更新'})`,
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
checkNo: check.check_no,
detailId: detailRowId,
locationCode,
quantity: quantityValue,
barcode: normalizedBarcode,
isUnknownGoods,
is_empty: normalizedIsEmpty,
mode,
message: normalizedIsEmpty
? `盘点作业上报:明细 ${detailRowId} 确认库位为空`
: `盘点作业上报:明细 ${detailRowId} 实盘 ${quantityValue}`,
},
});
return {
record,
detail_id: detailRowId,
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/all):一律按库位视图(location)返回,无视 view/is_goods 入参;
* - 任务范围为商品(type=goods/store):默认聚合库位视图(space);仅 is_goods=true 时按商品视图(goods)返回。
* 三视图行结构:
* location=库位结构,以任务库位范围行(scope_type=location)为列表,
* 行内挂该库位的盘点作业记录 goods 子列表(已知商品与未知商品均入内,
* has_unknown 标记是否含未知商品);
* goods=商品结构,以任务商品范围行(scope_type=goods)为列表,行内挂按库位聚合的作业记录,
* 明盘(mode=open)返回账面快照/已盘合计/差异,盲盘(mode=blind)不返回任何数量字段;
* space=聚合库位列表,以任务商品所在库位为列表(按拣货路径 pick_sequence 升序、
* pick_priority 降序排序),行内挂该库位的任务商品与账面/实盘数量,盲盘不返回数量字段;
* 若任务无对应范围行(如 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 {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 行含 detail_id/stock_id/item_code/item_name/spec/
* store_id/store_name/barcode/images/locations(明盘另含 system_quantity/checked_quantity/
* diff_quantity/is_diff);space 行含 id/space_code/custom_barcode/custom_name/goods。
* @throws {Error} 任务不存在或任务状态非 approved/checking 时抛出业务错误(错误码 400)。
*/
async workData(params = {}) {
const { warehouseId, id, isGoods, keyword, 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)的任务可拉取`);
}
// 视图解析:库位范围任务一律 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' || normalizedType === 'all'
? 'location'
: (goodsViewRequested ? 'goods' : 'space');
const allRows = resolvedView === 'location'
? await this._buildLocationWorkRows(warehouseId, checkId)
: (resolvedView === 'goods'
? await this._buildGoodsWorkRows(warehouseId, checkId, check.mode)
: await this._buildSpaceWorkRows(warehouseId, checkId, check.mode));
// keyword 过滤:仅库位任务(location 视图)启用,按行 location_code/location_name
// 模糊匹配(不区分大小写)过滤任务明细后再分页;非库位任务忽略该参数
const normalizedKeyword = String(keyword || '').trim().toLowerCase();
const filteredRows = resolvedView === 'location' && normalizedKeyword
? allRows.filter(row =>
String(row.location_code || '').toLowerCase().includes(normalizedKeyword)
|| String(row.location_name || '').toLowerCase().includes(normalizedKeyword))
: 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: resolvedView,
rows: filteredRows.slice(offset, offset + pageSize),
total: filteredRows.length,
page,
pageSize,
};
}
/**
* 拉取盘点作业数据(space 视图分页版)。
* 行结构与 workData space 视图行一致(id=库位ID/space_code/custom_barcode/custom_name/goods),
* 商品任务(scope_type=goods)按库位聚合;传入 location_id 时只返回该库位行(total=1),
* 不传时按分页返回全部库位行。
*
* @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);
// 库位过滤:传入 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,
};
}
/**
* 拉取单条盘点明细的作业数据(workData 单行版)。
*
* 按明细范围类型分流,均返回单行对象(与对应视图单行结构一致):
* - 库位明细(scope_type=location):行结构与 workData location 视图单行一致
* (detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/
* checked_at/checkers/goods),便于作业端按明细ID刷新单行数据;
* - 商品明细(scope_type=goods):行结构与 workData goods 视图行一致(detail_id/stock_id/
* item_code/item_name/spec/store_id/store_name/barcode/images/locations;
* 明盘另含 system_quantity/checked_quantity/diff_quantity/is_diff,盲盘不含数量字段)。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
* @param {number} params.detailId 盘点明细ID(库位范围行或商品范围行)。
* @return {Promise<Object>} 单行作业数据(结构随明细范围类型与 workData 对应视图单行一致)。
* @throws {Error} 明细不存在或任务状态非 approved/checking 时抛业务错误(错误码 400)。
*/
async workDataDetail(params = {}) {
const { ctx } = this;
const { warehouseId, detailId } = params;
const normalizedDetailId = Number(detailId);
if (!Number.isInteger(normalizedDetailId) || normalizedDetailId <= 0) {
throw this.createBusinessError('盘点明细ID不能为空');
}
const detailRow = await ctx.model.StockCheckDetail.findOne({
where: { id: normalizedDetailId, warehouse_id: Number(warehouseId) },
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';
// 商品明细:返回 goods 视图单行(与 location 分支结构对称)
if (scopeType === 'goods') {
const goodsRows = await this._buildGoodsWorkRows(warehouseId, Number(detailRow.check_id), check.mode);
const goodsRow = goodsRows.find(item => Number(item.detail_id) === normalizedDetailId);
if (!goodsRow) {
throw this.createBusinessError('盘点明细不存在');
}
return goodsRow;
}
// 库位明细:返回 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;
}
/**
* 构建 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,
});
}
}
return {
detail_id: detailId,
location_id: detailRow.location_id !== null && detailRow.location_id !== undefined
? detailRow.location_id
: null,
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 视图行:以任务商品范围行为列表,行内挂商品所在库位列表(locations)。
* locations 为商品所在全部库位(wms_storage 中该商品的 space_id 集合,按拣货路径排序):
* 明盘(mode=open)每库位含 system_quantity(该库位账面数量,wms_storage space+stock
* SUM(available_quantity+locked_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;
* 商品基础信息批量取自 stockWarehouse.getStockDetails(未命中回退明细商品快照),
* 货主名经 _resolveStoreNameMap 解析。
*
* @param {number} warehouseId 仓库ID。
* @param {number} checkId 盘点任务ID。
* @param {string} mode 盘点方式:open=明盘/blind=盲盘。
* @return {Promise<Array<Object>>} 商品视图行列表(按明细 id 升序)。
*/
async _buildGoodsWorkRows(warehouseId, checkId, mode) {
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)) ];
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,
},
attributes: [
'stock_id',
'space_id',
[ literal('SUM(available_quantity + locked_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();
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);
}
return detailRows.map(detailRow => {
const detailId = Number(detailRow.id);
const stockId = Number(detailRow.stock_id);
const detailRecords = recordsByDetail.get(detailId) || [];
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 = {
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: stockDetail.image_url || [],
locations: [],
};
if (isOpen) {
row.system_quantity = Number(detailRow.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 locationItem = {
location_code: code || 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) {
// 明盘:库位账面数量(可用+锁定)、库位锁定数量与库位盘点数量(实盘合计)区分输出
const spaceQuantity = (spaceQuantityByStockMap.get(stockId) || new Map()).get(code || '') || {};
locationItem.system_quantity = Number(spaceQuantity.system_quantity) || 0;
locationItem.locked_quantity = Number(spaceQuantity.locked_quantity) || 0;
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.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),
* 库位按拣货路径排序:pick_sequence 升序、pick_priority 降序(同值按库位 id 升序兜底);
* 行内 goods 为该库位下的任务商品:明盘含 system_quantity(wms_storage space+stock
* SUM(available_quantity+locked_quantity))、locked_quantity(wms_storage space+stock SUM(locked_quantity))
* 与 checked_quantity(该商品在该库位的实盘合计),盲盘不返回任何数量字段;
* status 已盘口径:该 (detail_id, location_code) 存在作业记录;
* 未在 wms_storage 有库位的商品不入列表(无库位可聚)。
*
* @param {number} warehouseId 仓库ID。
* @param {number} checkId 盘点任务ID。
* @param {string} mode 盘点方式:open=明盘/blind=盲盘。
* @return {Promise<Array<Object>>} 聚合库位视图行列表(按拣货路径排序)。
*/
async _buildSpaceWorkRows(warehouseId, checkId, mode) {
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';
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 ]));
// 任务商品所在库位: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,
},
attributes: [
'space_id',
'stock_id',
[ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ],
[ fn('SUM', col('locked_quantity')), 'totalLockedQuantity' ],
],
group: [ 'space_id', 'stock_id' ],
raw: true,
});
// 作业记录库位:优先已回填 location_id;未回填的按库位编码匹配 wms_location_space 补查,
// 保证商品库存已无记录时(如盘点前库存已出空)space 视图仍能展示已盘库位行。
const recordSpaceIds = [];
const recordLocationCodes = [];
for (const record of records) {
const recordSpaceId = Number(record.location_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', 'pick_priority' ],
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', 'pick_priority' ],
raw: true,
});
// 库位按拣货路径排序:pick_sequence 升序、pick_priority 降序(同值按库位 id 升序兜底)
const sortedLocations = 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);
});
// 库位商品账面/锁定映射(键 `${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();
// 仅记录库位(当前库存无该商品)按库位归集记录,供 space 视图补行
const recordsBySpace = new Map();
for (const record of records) {
let spaceId = Number(record.location_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);
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 = 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 = 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}`) || {};
item.system_quantity = Number(storageQuantity.system_quantity) || 0;
item.locked_quantity = Number(storageQuantity.locked_quantity) || 0;
item.checked_quantity = locationRecords.reduce(
(sum, record) => sum + (Number(record.quantity) || 0),
0
);
}
item.status = locationRecords.length > 0 ? 'checked' : 'unchecked';
return item;
})
.filter(item => item !== null);
return {
// 库位字段对齐库位查询惯例(index.searchSpace:id/space_code/custom_barcode/custom_name)
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/all)且状态 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' && normalizedType !== 'all') {
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):聚合 vs 账面快照 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', 'system_quantity' ],
raw: true,
});
let profitTotal = 0;
let lossTotal = 0;
let diffItems = 0;
for (const detailRow of detailRows) {
const detailId = Number(detailRow.id);
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
if (scopeType === 'goods') {
const systemQuantity = Number(detailRow.system_quantity || 0);
const checkedQuantity = checkedQuantityByDetail.get(detailId);
// 已盘商品行按记录聚合差异;未盘商品行按实盘 0 处理(差异 = -账面快照,即盘亏)
const diffQuantity = checkedQuantity === undefined
? -systemQuantity
: checkedQuantity - systemQuantity;
if (diffQuantity !== 0) {
diffItems++;
if (diffQuantity > 0) {
profitTotal += diffQuantity;
} else {
lossTotal += Math.abs(diffQuantity);
}
}
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 }。
* @throws {Error} 状态不允许时抛出业务错误(错误码 400)。
*/
async finish(params = {}) {
const { warehouseId, id } = params;
const { ctx } = this;
const { fn, col } = ctx.app.Sequelize;
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
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 totalItems = await ctx.model.StockCheckDetail.count({
where: { check_id: checkId },
});
// 已盘明细数:存在作业记录(wms_stock_check_record)的明细数
const checkedCountRows = await ctx.model.StockCheckRecord.findAll({
where: { check_id: checkId },
attributes: [[ fn('COUNT', fn('DISTINCT', col('detail_id'))), 'checkedCount' ]],
raw: true,
});
const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0;
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;
await check.update({
status: 'completed',
end_time: new Date(),
detail_status: 'all_checked',
checked_items: checkedItems,
diff_items: diffItems,
});
// 写入操作日志(失败不影响主流程)
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,
message: `完成盘点:差异 ${diffItems} 项,盘盈 ${profitTotal},盘亏 ${lossTotal}`,
},
});
return {
id: checkId,
status: 'completed',
total_items: totalItems,
checked_items: checkedItems,
unchecked_items: uncheckedItems,
diff_items: diffItems,
profit_total: profitTotal,
loss_total: lossTotal,
};
}
/**
* 完成盘点任务(提交审核)。
* 仅 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 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 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 }。
* @throws {Error} 状态不允许或动作非法时抛出业务错误(错误码 400)。
*/
async audit(params = {}) {
const { warehouseId, id, action, reason } = params;
const { ctx } = this;
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') {
await check.update({ status: 'approved' });
} else {
await check.update({
status: 'rejected',
remark: reasonValue,
});
}
// 写入操作日志(失败不影响主流程)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'stock_check',
businessId: checkId,
operationCode: 'STOCK_CHECK_AUDIT',
operationAction: 'UPDATE',
changeSummary: actionValue === 'approve'
? `审核通过盘点任务 ${check.check_no}`
: `审核驳回盘点任务 ${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 : '',
message: actionValue === 'approve'
? `审核通过盘点任务 ${check.check_no}`
: `审核驳回盘点任务 ${check.check_no}${reasonValue ? `,原因:${reasonValue}` : ''}`,
},
});
return {
id: checkId,
status: actionValue === 'approve' ? 'approved' : 'rejected',
};
}
/**
* 批量删除盘点任务(仅删除已作废任务,非作废或查不到的任务跳过)。
* 入参 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,
});
});
}
// 事务提交后写入操作日志(不随事务回滚残留,失败不影响主流程)
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 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: 'stockCheckExport',
description: `库存盘点导出,共 ${checks.length} 个盘点任务、${totalCount} 条盘点明细`,
});
}
// 优先取 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 || '',
};
} 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 });
}
}
}
module.exports = StockCheckService;