316 lines
10 KiB
JavaScript
316 lines
10 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();
|
||
let waveNo = null;
|
||
|
||
const orderDeliveryModel = ctx.model && ctx.model.OrderDelivery;
|
||
if (orderDeliveryModel && typeof orderDeliveryModel.findOne === 'function') {
|
||
const orderRow = await orderDeliveryModel.findOne({
|
||
where: {
|
||
id: orderId,
|
||
},
|
||
attributes: [ 'id', 'source_order_codes', 'wave_no' ],
|
||
raw: true,
|
||
transaction: options.transaction,
|
||
});
|
||
|
||
if (orderRow) {
|
||
if (!sourceOrderCodes) {
|
||
sourceOrderCodes = String(orderRow.source_order_codes || '').trim();
|
||
}
|
||
const normalizedWaveNo = String(orderRow.wave_no || '').trim();
|
||
waveNo = normalizedWaveNo || null;
|
||
}
|
||
}
|
||
|
||
if (!sourceOrderCodes) {
|
||
throw new Error(`订单出库流水 order_no 必须使用 source_order_codes,订单ID: ${orderId}`);
|
||
}
|
||
|
||
return {
|
||
orderId,
|
||
orderNo: sourceOrderCodes,
|
||
batchNo: waveNo,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 统一写入库存流水记录。
|
||
*
|
||
* @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),
|
||
},
|
||
};
|
||
}
|
||
}
|
||
|
||
module.exports = StockTransactionService;
|