新增: - order.recheckOrder.interceptScan: 拦截扫描接口,入参运单号,查express标记退回,处理工单,更新订单拦截状态 - afterSale.createInterceptWorkOrdersAndNotify: 共享方法,幂等创建工单+通知快递群 修复: - confirmIntercept: 补运单is_back同步(仅限is_intercept=Y),补工单创建+通知 - batchIntercept: 补运单is_intercept同步,补工单创建+通知 - batchUnintercept: 补运单is_intercept/is_back清除 - Qimen/OpenAPI cancel: 补运单is_intercept同步,补工单创建+通知 - interceptScan: 删除死查询,加空指针兜底 文档: - methods/system.json: interceptScan + confirmIntercept 完整API文档 - methods/changes/system.json: 变更记录
920 lines
31 KiB
JavaScript
920 lines
31 KiB
JavaScript
'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(),
|
||
};
|
||
|
||
return ctx.model.StockTransaction.create(payload, options);
|
||
}
|
||
|
||
async list(pageParams = {}, sortParams = {}, groupByBatch = false, keyword = '') {
|
||
const { ctx, app } = this;
|
||
const { Op, fn, col, literal } = app.Sequelize;
|
||
|
||
const warehouseId = ctx.user.store_id;
|
||
const { page = 1, pageSize = 20 } = pageParams;
|
||
const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams;
|
||
|
||
// 基础条件:当前仓库
|
||
const baseWhere = {
|
||
[Op.and]: [
|
||
{ warehouse_id: warehouseId },
|
||
],
|
||
};
|
||
|
||
// keyword 快捷搜索:按 item_code + barcode 匹配,解析为 stock_id IN 条件
|
||
const normalizedKeyword = String(keyword || '').trim();
|
||
if (normalizedKeyword) {
|
||
const stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', warehouseId);
|
||
if (stockIds.length > 0) {
|
||
baseWhere[Op.and].push({ stock_id: { [Op.in]: stockIds } });
|
||
} else {
|
||
// keyword 无匹配结果,直接返回空列表
|
||
return {
|
||
list: [],
|
||
pagination: { page, pageSize, total: 0, totalPages: 0 },
|
||
};
|
||
}
|
||
}
|
||
|
||
// 动态 where 条件
|
||
const parsed = ctx.whereParsed;
|
||
if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) {
|
||
baseWhere[Op.and].push(...parsed.dynamicConditions);
|
||
}
|
||
|
||
const offset = (page - 1) * pageSize;
|
||
const limit = pageSize;
|
||
|
||
if (groupByBatch) {
|
||
// 按批次明细:保持原有逻辑
|
||
const { count: total, rows } = await ctx.model.StockTransaction.findAndCountAll({
|
||
where: baseWhere,
|
||
order: [[ sortField, sortOrder ]],
|
||
offset,
|
||
limit,
|
||
include: [
|
||
{
|
||
model: ctx.model.StockWarehouse,
|
||
as: 'stockItem',
|
||
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
|
||
required: false,
|
||
},
|
||
],
|
||
});
|
||
|
||
const list = rows.map(item => {
|
||
const row = item.get({ plain: true });
|
||
row.created_at = row.created_at ? app.formatDate(row.created_at) : '';
|
||
return row;
|
||
});
|
||
|
||
return {
|
||
list,
|
||
pagination: {
|
||
page,
|
||
pageSize,
|
||
total,
|
||
totalPages: Math.ceil(total / pageSize),
|
||
},
|
||
};
|
||
}
|
||
|
||
// 不按批次:按 stock_id + transaction_type + warehouse/store + order_type 合并
|
||
const groupFields = [ 'stock_id', 'transaction_type', 'warehouse_id', 'store_id', 'order_type' ];
|
||
|
||
// 先查总数(分组后的组数)
|
||
const countResult = await ctx.model.StockTransaction.count({
|
||
where: baseWhere,
|
||
group: groupFields,
|
||
});
|
||
const total = Array.isArray(countResult) ? countResult.length : countResult;
|
||
|
||
// 查分组数据
|
||
const rows = await ctx.model.StockTransaction.findAll({
|
||
where: baseWhere,
|
||
attributes: [
|
||
'stock_id',
|
||
'transaction_type',
|
||
'warehouse_id',
|
||
'store_id',
|
||
'order_type',
|
||
[ fn('SUM', col('stock_transaction.quantity')), 'quantity' ],
|
||
[ fn('MIN', col('stock_transaction.created_at')), 'first_created_at' ],
|
||
[ fn('MAX', col('stock_transaction.created_at')), 'last_created_at' ],
|
||
[ fn('COUNT', col('stock_transaction.id')), 'record_count' ],
|
||
],
|
||
group: groupFields,
|
||
order: [[ literal('last_created_at'), sortOrder ]],
|
||
offset,
|
||
limit,
|
||
include: [
|
||
{
|
||
model: ctx.model.StockWarehouse,
|
||
as: 'stockItem',
|
||
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
|
||
required: false,
|
||
},
|
||
],
|
||
raw: true,
|
||
nest: true,
|
||
});
|
||
|
||
const list = rows.map(row => {
|
||
row.first_created_at = row.first_created_at ? app.formatDate(row.first_created_at) : '';
|
||
row.last_created_at = row.last_created_at ? app.formatDate(row.last_created_at) : '';
|
||
return row;
|
||
});
|
||
|
||
return {
|
||
list,
|
||
pagination: {
|
||
page,
|
||
pageSize,
|
||
total,
|
||
totalPages: Math.ceil(total / pageSize),
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 根据关键字解析匹配的 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();
|
||
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);
|
||
}
|
||
}
|
||
|
||
const whereClauses = [];
|
||
const replacements = {};
|
||
|
||
// 数据范围限定:仓库侧或货主侧
|
||
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();
|
||
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);
|
||
}
|
||
}
|
||
|
||
const isStoreMode = mode === 'store';
|
||
const whereClauses = [];
|
||
const replacements = {};
|
||
|
||
// 数据范围限定
|
||
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,
|
||
},
|
||
],
|
||
});
|
||
}
|
||
}
|
||
|
||
module.exports = StockTransactionService;
|