WMS_MAIN/app/service/systems/stock_transaction.js

558 lines
18 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(),
};
return ctx.model.StockTransaction.create(payload, options);
}
async list(pageParams = {}, sortParams = {}, groupByBatch = false) {
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 },
],
};
// 动态 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),
},
};
}
/**
* 查询商品出入库流水列表(原始记录,不做聚合)。
* 仓库侧:按 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.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] 分页参数
* @return {Promise<Object>} { list, pagination }
*/
async queryList(options = {}) {
const { ctx, app } = this;
const {
warehouseId,
storeId,
startTime,
endTime,
storeIds,
warehouseIds,
stockIds,
transactionType,
orderType,
orderNo,
batchNo,
entryOrderId,
receivingId,
orderId,
sort = {},
pagination = {},
} = options;
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 = Array.isArray(stockIds)
? stockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
if (normalizedStockIds.length > 0) {
whereClauses.push('t.stock_id IN (:stockIds)');
replacements.stockIds = normalizedStockIds;
}
// 流水类型
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),
},
};
}
}
module.exports = StockTransactionService;