WMS_MAIN/app/service/systems/stock_transaction.js
liufumingren 190d3cf9e5 feat(stock.check): 盘点模块功能扩展并同步接口文档(0.3.227)
- 盘点明细/记录支持未知商品(stock_id 可空)与库位范围,模式/状态口径修正
- 新增静态盘点任务、公告相关模型与迁移,stock_warehouse 增加预警数量
- methods/system.json 同步盘点接口文档;headers platform 微信端取值 wx 修正为 miniprogram
2026-10-02 15:43:49 +08:00

1373 lines
48 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 Service = require('egg').Service;
class StockTransactionService extends Service {
/**
* 规范化入库流水的单据字段。
*
* 约束:
* 1) transaction_type=INBOUND 时,order_id 必须写 null;
* 2) 其他类型保持上游值不变。
*
* @param {Object} data 流水数据。
* @param {number|null|undefined} orderId 候选单据ID。
* @return {number|null} 规范化后的单据ID。
*/
normalizeInboundOrderId(data = {}, orderId) {
if (data.transaction_type === 'INBOUND') {
return null;
}
return orderId ?? null;
}
/**
* 判断当前流水是否属于订单出库链路。
*
* 说明:
* 1) 仅 OUTBOUND 才可能是订单出库;
* 2) 允许上游传入多种 order_type,只要具备订单出库特征均视为订单出库;
* 3) 订单ID合法性由 resolveOutboundOrderReference 统一校验。
*
* @param {Object} data 流水数据。
* @return {boolean} 是否为订单出库流水。
*/
isOrderOutboundTransaction(data = {}) {
if (data.transaction_type !== 'OUTBOUND') {
return false;
}
const normalizedOrderType = String(data.order_type || '').trim();
const sourceOrderCodes = String(data.source_order_codes || '').trim();
const remark = String(data.remark || '').trim();
return Boolean(
sourceOrderCodes
|| normalizedOrderType === 'STOCK_STORE_OUTBOUND'
|| normalizedOrderType === 'ORDER'
|| remark === '订单出库'
);
}
/**
* 规范化订单出库流水的单据字段。
*
* 约束:
* 1) order_id 必须是订单主键 ID;
* 2) order_no 必须写订单 source_order_codes。
* 3) batch_no 必须以订单 wave_no 为准(无 wave_no 时写 null)。
*
* @param {Object} data 流水数据。
* @param {Object} options 写入选项。
* @return {Promise<{orderId: number|null, orderNo: string|null, batchNo: string|null}>} 规范化后的单据字段。
*/
async resolveOutboundOrderReference(data = {}, options = {}) {
const { ctx } = this;
const isOrderOutbound = this.isOrderOutboundTransaction(data);
if (!isOrderOutbound) {
return {
orderId: data.order_id ?? null,
orderNo: data.order_no ?? null,
batchNo: data.batch_no ?? null,
};
}
const orderId = Number(data.order_id);
if (!Number.isFinite(orderId) || orderId <= 0) {
throw new Error('订单出库流水 order_id 必须为订单主键 id');
}
let sourceOrderCodes = String(data.source_order_codes || '').trim();
// 兜底查询 source_order_codes(仅当调用方未传入时),用 try-catch 防止拖垮事务
const orderDeliveryModel = ctx.model && ctx.model.OrderDelivery;
if (!sourceOrderCodes && orderDeliveryModel && typeof orderDeliveryModel.findOne === 'function') {
try {
const orderRow = await orderDeliveryModel.findOne({
where: { id: orderId },
attributes: [ 'id', 'source_order_codes' ],
raw: true,
transaction: options.transaction,
});
if (orderRow) {
sourceOrderCodes = String(orderRow.source_order_codes || '').trim();
}
} catch (error) {
ctx.logger.warn(`[resolveOutboundOrderReference] 查询订单 source_order_codes 失败,降级跳过: ${error.message}`);
}
}
if (!sourceOrderCodes) {
throw new Error(`订单出库流水 order_no 必须使用 source_order_codes,订单ID: ${orderId}`);
}
return {
orderId,
orderNo: sourceOrderCodes,
batchNo: data.batch_no ?? null,
};
}
/**
* 统一写入库存流水记录。
*
* @param {Object} data 流水数据
* @param {string} data.transaction_type 出入库类型
* @param {number} data.warehouse_id 仓库ID
* @param {number} data.store_id 货主ID
* @param {number} data.stock_id 商品库存ID
* @param {number} data.quantity 变动数量
* @param {string} [data.batch_no] 批次号
* @param {string} [data.order_type] 关联单据类型
* @param {string} [data.order_no] 关联单据号
* @param {number} [data.order_id] 关联单据ID
* @param {number} [data.receiving_id] 关联收货单ID
* @param {number} [data.entry_order_id] 关联入库单ID
* @param {string} [data.operator_id] 操作人ID
* @param {string} [data.operator_name] 操作人名称
* @param {string} [data.remark] 备注
* @param {number} [data.before_quantity] 变更前总库存数量
* @param {number} [data.after_quantity] 变更后总库存数量
* @param {number} [data.before_locked_quantity] 变更前锁定数量
* @param {number} [data.after_locked_quantity] 变更后锁定数量
* @param {Date} [data.created_at] 创建时间
* @param {Object} [options] 写入选项
* @param {Object} [options.transaction] 数据库事务
* @return {Promise<Object>} 新增的流水记录
*/
async create(data = {}, options = {}) {
const { ctx } = this;
if (!options.transaction) {
throw new Error('stockTransaction.create 缺少 transaction,库存流水写入必须在事务中执行');
}
const quantity = Number(data.quantity);
if (!data.transaction_type) {
throw new Error('transaction_type 必填');
}
if (!data.warehouse_id) {
throw new Error('warehouse_id 必填');
}
if (!data.store_id) {
throw new Error('store_id 必填');
}
if (!data.stock_id) {
throw new Error('stock_id 必填');
}
if (!Number.isFinite(quantity) || quantity <= 0) {
throw new Error('quantity 必须为正数');
}
const isOrderOutbound = this.isOrderOutboundTransaction(data);
const normalizedOrderReference = await this.resolveOutboundOrderReference(data, options);
const normalizedOrderType = isOrderOutbound ? 'ORDER' : (data.order_type ?? null);
const normalizedBatchNo = isOrderOutbound ? normalizedOrderReference.batchNo : (data.batch_no ?? null);
const normalizedOrderId = this.normalizeInboundOrderId(data, normalizedOrderReference.orderId);
const payload = {
transaction_type: data.transaction_type,
warehouse_id: data.warehouse_id,
store_id: data.store_id,
stock_id: data.stock_id,
quantity,
batch_no: normalizedBatchNo,
order_type: normalizedOrderType,
order_no: normalizedOrderReference.orderNo,
order_id: normalizedOrderId,
receiving_id: data.receiving_id ?? null,
entry_order_id: data.entry_order_id ?? null,
operator_id: data.operator_id ?? null,
operator_name: data.operator_name ?? null,
remark: data.remark ?? null,
before_quantity: data.before_quantity ?? null,
after_quantity: data.after_quantity ?? null,
before_locked_quantity: data.before_locked_quantity ?? null,
after_locked_quantity: data.after_locked_quantity ?? null,
created_at: data.created_at || new Date(),
};
const row = await ctx.model.StockTransaction.create(payload, options);
// 订单出入库(收/发)后商品离开静态状态:硬删除静态通知/盘点任务关联记录(失败不影响主流程)
if (data.transaction_type === 'INBOUND' || data.transaction_type === 'OUTBOUND') {
await Promise.all([
this.clearStaticNoticeByStockId(data.stock_id, options),
this.clearStaticCheckTaskByStockId(data.stock_id, options),
]);
}
return row;
}
/**
* 硬删除指定商品的静态通知记录。
*
* 商品一旦有新的收/发流水即离开静态状态,历史通知记录不再有意义,
* 因此在流水写入成功后直接物理删除(不走软删)。
* 清理失败不影响出入库主流程(仅记录 warn)。
*
* @param {number} stockId 商品库存ID
* @param {Object} [options] 写入选项
* @param {Object} [options.transaction] 数据库事务(建议与流水写入同一事务)
* @return {Promise<number>} 删除行数(异常时返回 0)
*/
async clearStaticNoticeByStockId(stockId, options = {}) {
const { ctx } = this;
const numericStockId = Number(stockId);
if (!Number.isFinite(numericStockId) || numericStockId <= 0) {
return 0;
}
try {
const noticeModel = ctx.model && ctx.model.StockStaticNotice;
if (!noticeModel) {
return 0;
}
return await noticeModel.destroy({
where: { stock_id: numericStockId },
force: true, // 硬删除(paranoid 表需 force 才能物理删除)
...(options && options.transaction ? { transaction: options.transaction } : {}),
});
} catch (err) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[stockTransaction.clearStaticNoticeByStockId] 清理静态通知记录失败 stockId=${numericStockId}: ${err && err.message}`
);
return 0;
}
}
/**
* 硬删除指定商品的静态盘点任务关联记录。
*
* 商品一旦有新的收/发流水即离开静态状态,已创建的盘点任务关联不再有意义,
* 因此在流水写入成功后直接物理删除(不走软删)。
* 清理失败不影响出入库主流程(仅记录 warn)。
*
* @param {number} stockId 商品库存ID
* @param {Object} [options] 写入选项
* @param {Object} [options.transaction] 数据库事务(建议与流水写入同一事务)
* @return {Promise<number>} 删除行数(异常时返回 0)
*/
async clearStaticCheckTaskByStockId(stockId, options = {}) {
const { ctx } = this;
const numericStockId = Number(stockId);
if (!Number.isFinite(numericStockId) || numericStockId <= 0) {
return 0;
}
try {
const taskModel = ctx.model && ctx.model.StockStaticCheckTask;
if (!taskModel) {
return 0;
}
return await taskModel.destroy({
where: { stock_id: numericStockId },
force: true, // 硬删除(paranoid 表需 force 才能物理删除)
...(options && options.transaction ? { transaction: options.transaction } : {}),
});
} catch (err) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[stockTransaction.clearStaticCheckTaskByStockId] 清理静态盘点任务关联记录失败 stockId=${numericStockId}: ${err && err.message}`
);
return 0;
}
}
/**
* 查询库位维度出入库流水逐条明细(wms_storage_transaction)。
* 与 stock.transaction.list 形态一致:裸 SQL 列白名单 + COUNT 分页 + 排序白名单,
* 不做聚合,仅查询当前仓库数据,并关联商品信息(stockItem)。
* @param {Object} [options] 查询选项
* @param {number} options.warehouseId 仓库ID(必填,由 method 层从当前上下文注入)
* @param {string|Date|null} [options.startTime] 开始时间(闭区间下限,created_at >= startTime)
* @param {string|Date|null} [options.endTime] 结束时间(闭区间上限,created_at <= endTime)
* @param {Array<number|string>} [options.storeIds] 货主ID数组
* @param {Array<number|string>} [options.stockIds] 商品库存ID数组
* @param {number} [options.spaceId] 库位ID
* @param {string} [options.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode/SKU ID 模糊匹配)
* @param {string} [options.transactionType] 流水类型(INBOUND/OUTBOUND/TRANSFER_OUT/TRANSFER_IN/LOCK/UNLOCK)
* @param {string} [options.orderType] 单据类型
* @param {string} [options.orderNo] 单据号(模糊匹配)
* @param {string} [options.batchNo] 批次号
* @param {string} [options.inventoryType] 库存类型(ZP/CC/JS/XS/ZT/DJ/FP)
* @param {string} [options.operatorName] 操作人姓名(模糊匹配)
* @param {number} [options.orderId] 发货单ID
* @param {Object} [options.sort] 排序参数 { sortField, sortOrder }
* @param {Object} [options.pagination] 分页参数 { page, pageSize }
* @return {Promise<Object>} { list, pagination }
*/
async list(options = {}) {
const { ctx, app } = this;
const {
warehouseId,
startTime,
endTime,
storeIds: rawStoreIds,
stockIds: rawStockIds,
spaceId,
keyword,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
sort = {},
pagination = {},
} = options;
if (!warehouseId) {
return {
list: [],
pagination: { page: 1, pageSize: 20, total: 0, totalPages: 0 },
};
}
// keyword 快捷搜索:解析为 stock_id IN 条件,无匹配时直接返回空列表
let stockIds = Array.isArray(rawStockIds)
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
const normalizedKeyword = String(keyword || '').trim();
if (normalizedKeyword && stockIds.length === 0) {
stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', Number(warehouseId));
if (stockIds.length === 0) {
return {
list: [],
pagination: { page: 1, pageSize: 20, total: 0, totalPages: 0 },
};
}
}
const { whereSQL, replacements } = this._buildStorageTransactionWhere({
warehouseId,
startTime,
endTime,
storeIds: rawStoreIds,
stockIds,
spaceId,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
});
// 排序白名单,非法字段回退默认排序(created_at DESC)
const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id', 'space_id' ]);
const sortFieldRaw = String(sort.sortField || 'created_at').trim();
const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at';
const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase();
const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC';
// 分页
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;
// 查询总数
const countResult = await ctx.model.query(
`SELECT COUNT(*) AS total FROM wms_storage_transaction t ${whereSQL}`,
{
replacements,
type: app.Sequelize.QueryTypes.SELECT,
}
);
const total = countResult && countResult[0] ? Number(countResult[0].total) : 0;
// 明细白名单:显式列出列名,避免模型整行序列化引入未预期字段
const rows = await ctx.model.query(`
SELECT
t.id,
t.created_at,
t.transaction_type,
t.warehouse_id,
t.store_id,
t.stock_id,
t.storage_id,
t.space_id,
t.quantity,
t.before_quantity,
t.after_quantity,
t.before_locked_quantity,
t.after_locked_quantity,
t.before_intercept_locked_quantity,
t.after_intercept_locked_quantity,
t.batch_no,
t.inventory_type,
t.order_type,
t.order_no,
t.order_id,
t.source_order_codes,
t.operator_id,
t.operator_name,
t.remark,
sw.id AS sw_id,
sw.item_code AS sw_item_code,
sw.item_name AS sw_item_name,
sw.sku_property AS sw_sku_property,
sw.stock_unit AS sw_stock_unit
FROM wms_storage_transaction t
LEFT JOIN wms_stock_warehouse sw ON sw.id = t.stock_id
${whereSQL}
ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder}
LIMIT :limit OFFSET :offset
`, {
replacements: { ...replacements, limit: pageSize, offset },
type: app.Sequelize.QueryTypes.SELECT,
});
const safeRows = Array.isArray(rows) ? rows : [];
const list = safeRows.map(item => ({
id: Number(item.id),
created_at: item.created_at ? app.formatDate(item.created_at) : '',
transaction_type: item.transaction_type || '',
warehouse_id: Number(item.warehouse_id) || 0,
store_id: Number(item.store_id) || 0,
stock_id: Number(item.stock_id) || 0,
storage_id: Number(item.storage_id) || 0,
space_id: Number(item.space_id) || 0,
quantity: Number(item.quantity) || 0,
before_quantity: Number(item.before_quantity) || 0,
after_quantity: Number(item.after_quantity) || 0,
before_locked_quantity: Number(item.before_locked_quantity) || 0,
after_locked_quantity: Number(item.after_locked_quantity) || 0,
before_intercept_locked_quantity: Number(item.before_intercept_locked_quantity) || 0,
after_intercept_locked_quantity: Number(item.after_intercept_locked_quantity) || 0,
batch_no: item.batch_no || '',
inventory_type: item.inventory_type || '',
order_type: item.order_type || '',
order_no: item.order_no || '',
order_id: Number(item.order_id) || 0,
source_order_codes: item.source_order_codes || '',
operator_id: item.operator_id || '',
operator_name: item.operator_name || '',
remark: item.remark || '',
stockItem: item.sw_id !== null && item.sw_id !== undefined
? {
id: Number(item.sw_id) || 0,
item_code: item.sw_item_code || '',
item_name: item.sw_item_name || '',
sku_property: item.sw_sku_property || '',
stock_unit: item.sw_stock_unit || '',
}
: null,
}));
return {
list,
pagination: {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
},
};
}
/**
* 组装库位维度流水查询条件白名单(wms_storage_transaction)。
* 所有条件显式拼装,避免动态 where 注入未知字段;list 与导出共用。
* @param {Object} params 归一化后的查询参数
* @param {number} params.warehouseId 仓库ID
* @param {string|Date|null} [params.startTime] 开始时间
* @param {string|Date|null} [params.endTime] 结束时间
* @param {Array<number|string>} [params.storeIds] 货主ID数组
* @param {Array<number>} [params.stockIds] 商品库存ID数组
* @param {number} [params.spaceId] 库位ID
* @param {string} [params.transactionType] 流水类型
* @param {string} [params.orderType] 单据类型
* @param {string} [params.orderNo] 单据号(模糊)
* @param {string} [params.batchNo] 批次号
* @param {string} [params.inventoryType] 库存类型
* @param {string} [params.operatorName] 操作人(模糊)
* @param {number} [params.orderId] 发货单ID
* @return {{whereSQL: string, replacements: Object}} WHERE 子句与查询参数
*/
_buildStorageTransactionWhere({
warehouseId,
startTime,
endTime,
storeIds: rawStoreIds,
stockIds,
spaceId,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
} = {}) {
const whereClauses = [ 't.warehouse_id = :warehouseId' ];
const replacements = { warehouseId: Number(warehouseId) };
if (startTime !== undefined && startTime !== null && startTime !== '') {
const startMs = new Date(startTime).getTime();
if (!Number.isNaN(startMs)) {
whereClauses.push('t.created_at >= :startTime');
replacements.startTime = startTime;
}
}
if (endTime !== undefined && endTime !== null && endTime !== '') {
const endMs = new Date(endTime).getTime();
if (!Number.isNaN(endMs)) {
whereClauses.push('t.created_at <= :endTime');
replacements.endTime = endTime;
}
}
const storeIds = Array.isArray(rawStoreIds)
? rawStoreIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
if (storeIds.length > 0) {
whereClauses.push('t.store_id IN (:storeIds)');
replacements.storeIds = storeIds;
}
const normalizedStockIds = Array.isArray(stockIds) ? stockIds : [];
if (normalizedStockIds.length > 0) {
whereClauses.push('t.stock_id IN (:stockIds)');
replacements.stockIds = normalizedStockIds;
}
const normalizedSpaceId = Number(spaceId);
if (Number.isInteger(normalizedSpaceId) && normalizedSpaceId > 0) {
whereClauses.push('t.space_id = :spaceId');
replacements.spaceId = normalizedSpaceId;
}
if (transactionType) {
whereClauses.push('t.transaction_type = :transactionType');
replacements.transactionType = String(transactionType).trim();
}
if (orderType) {
whereClauses.push('t.order_type = :orderType');
replacements.orderType = String(orderType).trim();
}
if (orderNo) {
whereClauses.push('t.order_no LIKE :orderNo');
replacements.orderNo = `%${String(orderNo).trim()}%`;
}
if (batchNo) {
whereClauses.push('t.batch_no = :batchNo');
replacements.batchNo = String(batchNo).trim();
}
if (inventoryType) {
whereClauses.push('t.inventory_type = :inventoryType');
replacements.inventoryType = String(inventoryType).trim();
}
if (operatorName) {
whereClauses.push('t.operator_name LIKE :operatorName');
replacements.operatorName = `%${String(operatorName).trim()}%`;
}
const normalizedOrderId = Number(orderId);
if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) {
whereClauses.push('t.order_id = :orderId');
replacements.orderId = normalizedOrderId;
}
return {
whereSQL: `WHERE ${whereClauses.join(' AND ')}`,
replacements,
};
}
/**
* 根据关键字解析匹配的 stock_id 列表。
* 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。
* @param {string} keyword 搜索关键字
* @param {string} primaryDimCol 主维度列名(warehouse_id 或 store_id)
* @param {number} primaryDimVal 主维度值
* @return {Promise<number[]>} 匹配的 stock_id 列表
*/
async _resolveKeywordToStockIds(keyword, primaryDimCol, primaryDimVal) {
const { ctx, app } = this;
const normalizedKeyword = String(keyword || '').trim();
if (!normalizedKeyword) {
return [];
}
const likePattern = `%${normalizedKeyword}%`;
const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null;
const extraIdCondition = exactStockId !== null ? 'OR sw.id = :exactStockId' : '';
const stockRows = await ctx.model.query(`
SELECT DISTINCT sw.id AS stock_id
FROM wms_stock_warehouse sw
WHERE sw.${primaryDimCol} = :primaryDimVal
AND (
sw.item_code LIKE :keyword
OR sw.item_name LIKE :keyword
OR sw.goods_code LIKE :keyword
${extraIdCondition}
)
`, {
replacements: { primaryDimVal, keyword: likePattern, exactStockId },
type: app.Sequelize.QueryTypes.SELECT,
});
const barcodeRows = await ctx.model.query(`
SELECT DISTINCT sb.stock_id
FROM wms_stock_barcodes sb
INNER JOIN wms_stock_warehouse sw ON sw.id = sb.stock_id AND sw.${primaryDimCol} = :primaryDimVal
WHERE sb.barcode LIKE :keyword
`, {
replacements: { primaryDimVal, keyword: likePattern },
type: app.Sequelize.QueryTypes.SELECT,
});
const stockIdSet = new Set();
for (const row of stockRows) {
const sid = Number(row.stock_id);
if (sid > 0) stockIdSet.add(sid);
}
for (const row of barcodeRows) {
const sid = Number(row.stock_id);
if (sid > 0) stockIdSet.add(sid);
}
return [ ...stockIdSet ];
}
/**
* 查询商品出入库流水列表(原始记录,不做聚合)。
* 仓库侧:按 warehouseId 限定;货主侧:按 storeId 限定。
* @param {Object} options 查询参数
* @param {number} [options.warehouseId] 仓库ID(仓库侧必传)
* @param {number} [options.storeId] 货主ID(货主侧必传)
* @param {string|Date|null} [options.startTime] 开始时间
* @param {string|Date|null} [options.endTime] 结束时间
* @param {Array<number|string>} [options.storeIds] 货主ID数组(仓库侧筛选)
* @param {Array<number|string>} [options.warehouseIds] 仓库ID数组(货主侧筛选)
* @param {Array<number|string>} [options.stockIds] 商品库存ID数组
* @param {string} [options.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode/SKU ID 模糊匹配)
* @param {string} [options.transactionType] 流水类型
* @param {string} [options.orderType] 单据类型
* @param {string} [options.orderNo] 单据号
* @param {string} [options.batchNo] 批次号
* @param {number} [options.entryOrderId] 入库单ID
* @param {number} [options.receivingId] 收货单ID
* @param {number} [options.orderId] 发货单ID
* @param {Object} [options.sort] 排序参数
* @param {Object} [options.pagination] 分页参数
* @param {string} [options.mode] 模式 'warehouse'/'store',用于 keyword 解析时决定主维度
* @return {Promise<Object>} { list, pagination }
*/
async queryList(options = {}) {
const { ctx, app } = this;
const {
warehouseId,
storeId,
startTime,
endTime,
storeIds,
warehouseIds,
stockIds: rawStockIds,
keyword,
ids,
transactionType,
orderType,
orderNo,
batchNo,
entryOrderId,
receivingId,
orderId,
sort = {},
pagination = {},
mode = 'warehouse',
} = options;
// keyword 解析为 stock_ids
let resolvedStockIds = Array.isArray(rawStockIds)
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
const normalizedKeyword = String(keyword || '').trim();
let keywordResolvedEmpty = false;
if (normalizedKeyword && resolvedStockIds.length === 0) {
const isStoreMode = mode === 'store';
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
const primaryDimVal = isStoreMode ? Number(storeId) : Number(warehouseId);
if (primaryDimVal > 0) {
resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal);
if (resolvedStockIds.length === 0) {
// keyword 无匹配商品,避免退化为查询全部流水
keywordResolvedEmpty = true;
}
}
}
const whereClauses = [];
const replacements = {};
if (keywordResolvedEmpty) {
whereClauses.push('1 = 0');
}
// 数据范围限定:仓库侧或货主侧
if (warehouseId !== undefined && warehouseId !== null) {
whereClauses.push('t.warehouse_id = :warehouseId');
replacements.warehouseId = Number(warehouseId);
}
if (storeId !== undefined && storeId !== null) {
whereClauses.push('t.store_id = :storeId');
replacements.storeId = Number(storeId);
}
// 时间范围
if (startTime !== undefined && startTime !== null && startTime !== '') {
const startMs = new Date(startTime).getTime();
if (!Number.isNaN(startMs)) {
whereClauses.push('t.created_at >= :startTime');
replacements.startTime = startTime;
}
}
if (endTime !== undefined && endTime !== null && endTime !== '') {
const endMs = new Date(endTime).getTime();
if (!Number.isNaN(endMs)) {
whereClauses.push('t.created_at <= :endTime');
replacements.endTime = endTime;
}
}
// 货主筛选(仓库侧)
const normalizedStoreIds = Array.isArray(storeIds)
? storeIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
if (normalizedStoreIds.length > 0) {
whereClauses.push('t.store_id IN (:storeIds)');
replacements.storeIds = normalizedStoreIds;
}
// 仓库筛选(货主侧)
const normalizedWarehouseIds = Array.isArray(warehouseIds)
? warehouseIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
if (normalizedWarehouseIds.length > 0) {
whereClauses.push('t.warehouse_id IN (:warehouseIds)');
replacements.warehouseIds = normalizedWarehouseIds;
}
// 商品筛选
const normalizedStockIds = resolvedStockIds;
if (normalizedStockIds.length > 0) {
whereClauses.push('t.stock_id IN (:stockIds)');
replacements.stockIds = normalizedStockIds;
}
// 记录ID筛选(精确导出选中记录)
const normalizedIds = Array.isArray(ids)
? ids.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
if (normalizedIds.length > 0) {
whereClauses.push('t.id IN (:ids)');
replacements.ids = normalizedIds;
}
// 流水类型
if (transactionType) {
whereClauses.push('t.transaction_type = :transactionType');
replacements.transactionType = String(transactionType).trim();
}
// 单据类型
if (orderType) {
whereClauses.push('t.order_type = :orderType');
replacements.orderType = String(orderType).trim();
}
// 单据号(模糊匹配)
if (orderNo) {
whereClauses.push('t.order_no LIKE :orderNo');
replacements.orderNo = `%${String(orderNo).trim()}%`;
}
// 批次号
if (batchNo) {
whereClauses.push('t.batch_no = :batchNo');
replacements.batchNo = String(batchNo).trim();
}
// 入库单ID
if (entryOrderId !== undefined && entryOrderId !== null) {
const eid = Number(entryOrderId);
if (Number.isInteger(eid) && eid > 0) {
whereClauses.push('t.entry_order_id = :entryOrderId');
replacements.entryOrderId = eid;
}
}
// 收货单ID
if (receivingId !== undefined && receivingId !== null) {
const rid = Number(receivingId);
if (Number.isInteger(rid) && rid > 0) {
whereClauses.push('t.receiving_id = :receivingId');
replacements.receivingId = rid;
}
}
// 发货单ID
if (orderId !== undefined && orderId !== null) {
const oid = Number(orderId);
if (Number.isInteger(oid) && oid > 0) {
whereClauses.push('t.order_id = :orderId');
replacements.orderId = oid;
}
}
const whereSQL = whereClauses.length > 0
? `WHERE ${whereClauses.join(' AND ')}`
: '';
// 排序
const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id' ]);
const sortFieldRaw = String(sort.sortField || 'created_at').trim();
const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at';
const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase();
const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC';
// 分页
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;
// 查询总数
const countResult = await ctx.model.query(
`SELECT COUNT(*) AS total FROM wms_stock_transaction t ${whereSQL}`,
{
replacements,
type: app.Sequelize.QueryTypes.SELECT,
}
);
const total = countResult && countResult[0] ? Number(countResult[0].total) : 0;
// 查询列表
const rows = await ctx.model.query(
`SELECT
t.id,
t.created_at,
t.transaction_type,
t.warehouse_id,
t.store_id,
t.stock_id,
t.quantity,
t.before_quantity,
t.after_quantity,
t.before_locked_quantity,
t.after_locked_quantity,
t.batch_no,
t.order_type,
t.order_no,
t.order_id,
t.receiving_id,
t.entry_order_id,
t.operator_name,
t.remark
FROM wms_stock_transaction t
${whereSQL}
ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder}
LIMIT :limit OFFSET :offset
`,
{
replacements: { ...replacements, limit: pageSize, offset },
type: app.Sequelize.QueryTypes.SELECT,
}
);
const safeRows = Array.isArray(rows) ? rows : [];
const list = safeRows.map(item => ({
id: Number(item.id),
created_at: item.created_at ? app.formatDate(item.created_at) : '',
transaction_type: item.transaction_type || '',
warehouse_id: Number(item.warehouse_id) || 0,
store_id: Number(item.store_id) || 0,
stock_id: Number(item.stock_id) || 0,
quantity: Number(item.quantity) || 0,
before_quantity: Number(item.before_quantity) || 0,
after_quantity: Number(item.after_quantity) || 0,
before_locked_quantity: Number(item.before_locked_quantity) || 0,
after_locked_quantity: Number(item.after_locked_quantity) || 0,
batch_no: item.batch_no || '',
order_type: item.order_type || '',
order_no: item.order_no || '',
order_id: Number(item.order_id) || 0,
receiving_id: Number(item.receiving_id) || 0,
entry_order_id: Number(item.entry_order_id) || 0,
operator_name: item.operator_name || '',
remark: item.remark || '',
}));
return {
list,
pagination: {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
},
};
}
/**
* 导出商品出入库流水列表为 Excel。
* 与 queryList 使用相同的查询条件,但不分页(导出上限 50000 条)。
* @param {Object} options 查询参数(与 queryList 一致,忽略 pagination)
* @param {string} [options.mode] 导出模式:'warehouse' 仓库侧 / 'store' 货主侧
* @return {Promise<Object>} Excel 导出结果 { url, filename }
*/
async exportList(options = {}) {
const { ctx, app } = this;
const {
warehouseId,
storeId,
startTime,
endTime,
storeIds,
warehouseIds,
stockIds: rawStockIds,
keyword,
ids,
transactionType,
orderType,
orderNo,
batchNo,
entryOrderId,
receivingId,
orderId,
sort = {},
mode = 'warehouse',
} = options;
// keyword 解析为 stock_ids
let resolvedStockIds = Array.isArray(rawStockIds)
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
const normalizedKeyword = String(keyword || '').trim();
let keywordResolvedEmpty = false;
if (normalizedKeyword && resolvedStockIds.length === 0) {
const isStoreMode = mode === 'store';
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
const primaryDimVal = isStoreMode ? Number(storeId) : Number(warehouseId);
if (primaryDimVal > 0) {
resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal);
if (resolvedStockIds.length === 0) {
// keyword 无匹配商品,避免退化为导出全部流水
keywordResolvedEmpty = true;
}
}
}
const isStoreMode = mode === 'store';
const whereClauses = [];
const replacements = {};
if (keywordResolvedEmpty) {
whereClauses.push('1 = 0');
}
// 数据范围限定
if (warehouseId !== undefined && warehouseId !== null) {
whereClauses.push('t.warehouse_id = :warehouseId');
replacements.warehouseId = Number(warehouseId);
}
if (storeId !== undefined && storeId !== null) {
whereClauses.push('t.store_id = :storeId');
replacements.storeId = Number(storeId);
}
if (startTime !== undefined && startTime !== null && startTime !== '') {
const startMs = new Date(startTime).getTime();
if (!Number.isNaN(startMs)) {
whereClauses.push('t.created_at >= :startTime');
replacements.startTime = startTime;
}
}
if (endTime !== undefined && endTime !== null && endTime !== '') {
const endMs = new Date(endTime).getTime();
if (!Number.isNaN(endMs)) {
whereClauses.push('t.created_at <= :endTime');
replacements.endTime = endTime;
}
}
const normalizedStoreIds = Array.isArray(storeIds)
? storeIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
if (normalizedStoreIds.length > 0) {
whereClauses.push('t.store_id IN (:storeIds)');
replacements.storeIds = normalizedStoreIds;
}
const normalizedWarehouseIds = Array.isArray(warehouseIds)
? warehouseIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
if (normalizedWarehouseIds.length > 0) {
whereClauses.push('t.warehouse_id IN (:warehouseIds)');
replacements.warehouseIds = normalizedWarehouseIds;
}
const normalizedStockIds = resolvedStockIds;
if (normalizedStockIds.length > 0) {
whereClauses.push('t.stock_id IN (:stockIds)');
replacements.stockIds = normalizedStockIds;
}
// 记录ID筛选(精确导出选中记录)
const normalizedIds = Array.isArray(ids)
? ids.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
if (normalizedIds.length > 0) {
whereClauses.push('t.id IN (:ids)');
replacements.ids = normalizedIds;
}
if (transactionType) {
whereClauses.push('t.transaction_type = :transactionType');
replacements.transactionType = String(transactionType).trim();
}
if (orderType) {
whereClauses.push('t.order_type = :orderType');
replacements.orderType = String(orderType).trim();
}
if (orderNo) {
whereClauses.push('t.order_no LIKE :orderNo');
replacements.orderNo = `%${String(orderNo).trim()}%`;
}
if (batchNo) {
whereClauses.push('t.batch_no = :batchNo');
replacements.batchNo = String(batchNo).trim();
}
if (entryOrderId !== undefined && entryOrderId !== null) {
const eid = Number(entryOrderId);
if (Number.isInteger(eid) && eid > 0) {
whereClauses.push('t.entry_order_id = :entryOrderId');
replacements.entryOrderId = eid;
}
}
if (receivingId !== undefined && receivingId !== null) {
const rid = Number(receivingId);
if (Number.isInteger(rid) && rid > 0) {
whereClauses.push('t.receiving_id = :receivingId');
replacements.receivingId = rid;
}
}
if (orderId !== undefined && orderId !== null) {
const oid = Number(orderId);
if (Number.isInteger(oid) && oid > 0) {
whereClauses.push('t.order_id = :orderId');
replacements.orderId = oid;
}
}
const whereSQL = whereClauses.length > 0
? `WHERE ${whereClauses.join(' AND ')}`
: '';
const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id' ]);
const sortFieldRaw = String(sort.sortField || 'created_at').trim();
const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at';
const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase();
const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC';
const EXPORT_MAX = 50000;
const rows = await ctx.model.query(
`SELECT
t.id,
t.created_at,
t.transaction_type,
t.warehouse_id,
t.store_id,
t.stock_id,
t.quantity,
t.before_quantity,
t.after_quantity,
t.before_locked_quantity,
t.after_locked_quantity,
t.batch_no,
t.order_type,
t.order_no,
t.order_id,
t.receiving_id,
t.entry_order_id,
t.operator_name,
t.remark
FROM wms_stock_transaction t
${whereSQL}
ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder}
LIMIT ${EXPORT_MAX}
`,
{
replacements,
type: app.Sequelize.QueryTypes.SELECT,
}
);
const safeRows = Array.isArray(rows) ? rows : [];
const excelRows = safeRows.map((item, index) => {
const qty = Number(item.quantity) || 0;
const beforeQty = Number(item.before_quantity) || 0;
const afterQty = Number(item.after_quantity) || 0;
const beforeLocked = Number(item.before_locked_quantity) || 0;
const afterLocked = Number(item.after_locked_quantity) || 0;
const lockedChange = afterLocked - beforeLocked;
return {
序号: index + 1,
创建时间: item.created_at ? app.formatDate(item.created_at) : '',
流水类型: item.transaction_type || '',
仓库ID: Number(item.warehouse_id) || 0,
货主ID: Number(item.store_id) || 0,
商品ID: Number(item.stock_id) || 0,
库存变动量: qty,
库存变更前: beforeQty,
库存变更后: afterQty,
锁定变动量: lockedChange,
锁定变更前: beforeLocked,
锁定变更后: afterLocked,
批次号: item.batch_no || '',
单据类型: item.order_type || '',
单据号: item.order_no || '',
收货单ID: Number(item.receiving_id) || 0,
入库单ID: Number(item.entry_order_id) || 0,
发货单ID: Number(item.order_id) || 0,
操作人: item.operator_name || '',
备注: item.remark || '',
};
});
const titleSuffix = isStoreMode ? '货主侧' : '仓库侧';
const warehouseIdForPath = warehouseId || storeId || 'unknown';
return await ctx.service.systems.excel.generateAndUpload({
filename: `商品流水_${titleSuffix}_${warehouseIdForPath}_${Date.now()}.xlsx`,
dir: `exports/stock/transaction/${warehouseIdForPath}`,
category: 'document',
sheets: [
{
name: '商品流水',
columns: [
{ header: '序号', key: '序号' },
{ header: '创建时间', key: '创建时间' },
{ header: '流水类型', key: '流水类型' },
{ header: '仓库ID', key: '仓库ID' },
{ header: '货主ID', key: '货主ID' },
{ header: '商品ID', key: '商品ID' },
{ header: '库存变动量', key: '库存变动量' },
{ header: '库存变更前', key: '库存变更前' },
{ header: '库存变更后', key: '库存变更后' },
{ header: '锁定变动量', key: '锁定变动量' },
{ header: '锁定变更前', key: '锁定变更前' },
{ header: '锁定变更后', key: '锁定变更后' },
{ header: '批次号', key: '批次号' },
{ header: '单据类型', key: '单据类型' },
{ header: '单据号', key: '单据号' },
{ header: '收货单ID', key: '收货单ID' },
{ header: '入库单ID', key: '入库单ID' },
{ header: '发货单ID', key: '发货单ID' },
{ header: '操作人', key: '操作人' },
{ header: '备注', key: '备注' },
],
rows: excelRows,
},
],
});
}
/**
* 导出库位维度出入库流水明细为 Excel(wms_storage_transaction)。
* 与 list 使用相同查询条件,但不分页(导出上限 50000 条)。
* @param {Object} options 查询参数(与 list 一致,忽略 pagination)
* @return {Promise<Object>} Excel 导出结果 { url, filename }
*/
async exportStorageList(options = {}) {
const { ctx, app } = this;
const {
warehouseId,
startTime,
endTime,
storeIds: rawStoreIds,
stockIds: rawStockIds,
spaceId,
keyword,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
sort = {},
} = options;
// keyword 快捷搜索:解析为 stock_id IN 条件,无匹配时导出空表
let stockIds = Array.isArray(rawStockIds)
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
const normalizedKeyword = String(keyword || '').trim();
let keywordResolvedEmpty = false;
if (normalizedKeyword && stockIds.length === 0) {
stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', Number(warehouseId));
if (stockIds.length === 0) {
keywordResolvedEmpty = true;
}
}
let whereSQL;
let replacements;
if (keywordResolvedEmpty) {
whereSQL = 'WHERE 1 = 0';
replacements = {};
} else {
({ whereSQL, replacements } = this._buildStorageTransactionWhere({
warehouseId,
startTime,
endTime,
storeIds: rawStoreIds,
stockIds,
spaceId,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
}));
}
// 排序白名单,与 list 一致
const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id', 'space_id' ]);
const sortFieldRaw = String(sort.sortField || 'created_at').trim();
const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at';
const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase();
const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC';
const EXPORT_MAX = 50000;
const rows = await ctx.model.query(`
SELECT
t.id,
t.created_at,
t.transaction_type,
t.warehouse_id,
t.store_id,
t.stock_id,
t.storage_id,
t.space_id,
t.quantity,
t.before_quantity,
t.after_quantity,
t.before_locked_quantity,
t.after_locked_quantity,
t.before_intercept_locked_quantity,
t.after_intercept_locked_quantity,
t.batch_no,
t.inventory_type,
t.order_type,
t.order_no,
t.order_id,
t.source_order_codes,
t.operator_id,
t.operator_name,
t.remark
FROM wms_storage_transaction t
${whereSQL}
ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder}
LIMIT ${EXPORT_MAX}
`, {
replacements,
type: app.Sequelize.QueryTypes.SELECT,
});
const safeRows = Array.isArray(rows) ? rows : [];
const excelRows = safeRows.map((item, index) => ({
序号: index + 1,
创建时间: item.created_at ? app.formatDate(item.created_at) : '',
流水类型: item.transaction_type || '',
仓库ID: Number(item.warehouse_id) || 0,
货主ID: Number(item.store_id) || 0,
商品ID: Number(item.stock_id) || 0,
库位库存ID: Number(item.storage_id) || 0,
库位ID: Number(item.space_id) || 0,
库存变动量: Number(item.quantity) || 0,
库存变更前: Number(item.before_quantity) || 0,
库存变更后: Number(item.after_quantity) || 0,
锁定变更前: Number(item.before_locked_quantity) || 0,
锁定变更后: Number(item.after_locked_quantity) || 0,
拦截锁定变更前: Number(item.before_intercept_locked_quantity) || 0,
拦截锁定变更后: Number(item.after_intercept_locked_quantity) || 0,
批次号: item.batch_no || '',
库存类型: item.inventory_type || '',
单据类型: item.order_type || '',
单据号: item.order_no || '',
发货单ID: Number(item.order_id) || 0,
来源订单号: item.source_order_codes || '',
操作人ID: item.operator_id || '',
操作人: item.operator_name || '',
备注: item.remark || '',
}));
const warehouseIdForPath = Number(warehouseId) || 'unknown';
return await ctx.service.systems.excel.generateAndUpload({
filename: `库位流水_${warehouseIdForPath}_${Date.now()}.xlsx`,
dir: `exports/storage/transaction/${warehouseIdForPath}`,
category: 'document',
sheets: [
{
name: '库位流水',
columns: [
{ header: '序号', key: '序号' },
{ header: '创建时间', key: '创建时间' },
{ header: '流水类型', key: '流水类型' },
{ header: '仓库ID', key: '仓库ID' },
{ header: '货主ID', key: '货主ID' },
{ header: '商品ID', key: '商品ID' },
{ header: '库位库存ID', key: '库位库存ID' },
{ header: '库位ID', key: '库位ID' },
{ header: '库存变动量', key: '库存变动量' },
{ header: '库存变更前', key: '库存变更前' },
{ header: '库存变更后', key: '库存变更后' },
{ header: '锁定变更前', key: '锁定变更前' },
{ header: '锁定变更后', key: '锁定变更后' },
{ header: '拦截锁定变更前', key: '拦截锁定变更前' },
{ header: '拦截锁定变更后', key: '拦截锁定变更后' },
{ header: '批次号', key: '批次号' },
{ header: '库存类型', key: '库存类型' },
{ header: '单据类型', key: '单据类型' },
{ header: '单据号', key: '单据号' },
{ header: '发货单ID', key: '发货单ID' },
{ header: '来源订单号', key: '来源订单号' },
{ header: '操作人ID', key: '操作人ID' },
{ header: '操作人', key: '操作人' },
{ header: '备注', key: '备注' },
],
rows: excelRows,
},
],
});
}
}
module.exports = StockTransactionService;