- warehouseNotify: 按固定群订阅经 wms_api_app 回调推送(MD5 验签),消息表登记+失败重试 - notice: 货主群缺失时降级发仓库异常群(前缀标记失败),合约停用/已解除货主不发货主群也不降级 - order_async: 订单同步通知 3 分钟去抖合并,Redis 队列+定时冲刷+失败重试 - receiving: 收货完成/驳回/审核通知走仓库通道,仓库/货主侧文案分离 - storage/inventory: 移除移库完成群通知(事件码保留,库存余量提醒仍复用) - 新增 debug:warehouse:push-receiver 调试接收服务与文档/变更记录
1974 lines
72 KiB
JavaScript
1974 lines
72 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||
|
||
/**
|
||
* 计算库存批次的保质期预警状态。
|
||
*
|
||
* @param {Object} stock 商品库存资料
|
||
* @param {string|Date|null} expiryDate 批次到期日期
|
||
* @param {number} [nowMs=Date.now()] 当前时间戳
|
||
* @return {{remainingDays: (number|null), isTriggered: boolean}} 预警信息
|
||
*/
|
||
function getShelfLifeWarningState(stock = {}, expiryDate = null, nowMs = Date.now()) {
|
||
const expiryTime = expiryDate ? new Date(expiryDate).getTime() : null;
|
||
const remainingDays = expiryTime === null || Number.isNaN(expiryTime)
|
||
? null
|
||
: Math.max(0, Math.ceil((expiryTime - nowMs) / DAY_MS));
|
||
const isShelfLifeMgmt = stock.is_shelf_life_mgmt === 'Y' || stock.is_shelf_life_mgmt === true;
|
||
const thresholdDays = Number(stock.remaining_threshold_days) || 0;
|
||
|
||
return {
|
||
remainingDays,
|
||
isTriggered: Boolean(isShelfLifeMgmt && thresholdDays > 0 && remainingDays !== null && remainingDays <= thresholdDays),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 将库存预警规则转换为按到期天数递增的区间配置。
|
||
*
|
||
* @param {Array<Object>} warningRules 库存预警规则
|
||
* @return {Array<{name: string, key: string, tip_text: string, min_days: number, max_days: number}>} 规则区间列表
|
||
*/
|
||
function buildInventoryWarningRanges(warningRules = []) {
|
||
if (!Array.isArray(warningRules) || !warningRules.length) {
|
||
return [];
|
||
}
|
||
|
||
const sortedRules = warningRules
|
||
.filter(rule => rule && typeof rule === 'object')
|
||
.map(rule => ({
|
||
name: rule.name,
|
||
key: rule.key,
|
||
tip_text: rule.tip_text === undefined || rule.tip_text === null ? '' : String(rule.tip_text),
|
||
expire_days: Number(rule.expire_days),
|
||
}))
|
||
.filter(rule => Number.isInteger(rule.expire_days) && rule.expire_days >= 0)
|
||
.sort((a, b) => a.expire_days - b.expire_days);
|
||
|
||
let previousMax = null;
|
||
return sortedRules.map(rule => {
|
||
const minDays = previousMax === null ? 0 : previousMax + 1;
|
||
const maxDays = rule.expire_days;
|
||
previousMax = maxDays;
|
||
return {
|
||
name: rule.name,
|
||
key: rule.key,
|
||
tip_text: rule.tip_text,
|
||
min_days: minDays,
|
||
max_days: maxDays,
|
||
};
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 根据剩余天数命中库存预警规则并返回响应字段。
|
||
*
|
||
* @param {number|null} remainingDays 到期剩余天数
|
||
* @param {Array<Object>} warningRanges 预警规则区间
|
||
* @return {{expiry_remaining_days: (number|null), inventory_warning_level: (string|null), inventory_warning_color: (string|null), inventory_warning_range: ({min_days: number, max_days: number}|null), inventory_warning_tip_text: (string|null)}} 预警输出字段
|
||
*/
|
||
function getInventoryWarningPayload(remainingDays, warningRanges = []) {
|
||
if (!Number.isInteger(remainingDays) || !Array.isArray(warningRanges) || !warningRanges.length) {
|
||
return {
|
||
expiry_remaining_days: null,
|
||
inventory_warning_level: null,
|
||
inventory_warning_color: null,
|
||
inventory_warning_range: null,
|
||
inventory_warning_tip_text: null,
|
||
};
|
||
}
|
||
|
||
const matchedRange = warningRanges.find(rule => (
|
||
remainingDays >= rule.min_days && remainingDays <= rule.max_days
|
||
));
|
||
|
||
if (!matchedRange) {
|
||
return {
|
||
expiry_remaining_days: remainingDays,
|
||
inventory_warning_level: null,
|
||
inventory_warning_color: null,
|
||
inventory_warning_range: null,
|
||
inventory_warning_tip_text: null,
|
||
};
|
||
}
|
||
|
||
return {
|
||
expiry_remaining_days: remainingDays,
|
||
inventory_warning_level: matchedRange.name || null,
|
||
inventory_warning_color: matchedRange.key || null,
|
||
inventory_warning_range: {
|
||
min_days: matchedRange.min_days,
|
||
max_days: matchedRange.max_days,
|
||
},
|
||
inventory_warning_tip_text: matchedRange.tip_text,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 将库存商品上的标记值规范化为布尔值。
|
||
*
|
||
* @param {unknown} value 待转换的标记值
|
||
* @return {boolean} 是否为真值
|
||
*/
|
||
function toBooleanFlag(value) {
|
||
if (typeof value === 'boolean') {
|
||
return value;
|
||
}
|
||
|
||
if (typeof value === 'number') {
|
||
return value === 1;
|
||
}
|
||
|
||
if (typeof value === 'string') {
|
||
return [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(value.trim().toUpperCase());
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* 批量加载库存商品的条码与图片附属信息。
|
||
* 复用 stock_warehouse.getStockDetails 缓存查询。
|
||
*
|
||
* @param {Object} ctx 当前请求上下文
|
||
* @param {number[]} stockIds 商品ID列表
|
||
* @return {Promise<{barcodesByStockId: Map<number, string[]>, imagesByStockId: Map<number, string[]>}>} 附属信息映射
|
||
*/
|
||
async function loadStockAttachments(ctx, stockIds = []) {
|
||
const uniqueStockIds = [ ...new Set(
|
||
Array.isArray(stockIds)
|
||
? stockIds.map(item => Number(item)).filter(Boolean)
|
||
: []
|
||
) ];
|
||
|
||
const barcodesByStockId = new Map();
|
||
const imagesByStockId = new Map();
|
||
|
||
if (!uniqueStockIds.length) {
|
||
return { barcodesByStockId, imagesByStockId };
|
||
}
|
||
|
||
try {
|
||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||
uniqueStockIds,
|
||
{}
|
||
);
|
||
for (const detail of stockDetails) {
|
||
const stockId = Number(detail.id);
|
||
if (!stockId) {
|
||
continue;
|
||
}
|
||
|
||
// 提取条码
|
||
if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
|
||
const barcodes = detail.barcodes
|
||
.map(bc => String(bc.barcode || '').trim())
|
||
.filter(Boolean);
|
||
if (barcodes.length > 0) {
|
||
barcodesByStockId.set(stockId, barcodes);
|
||
}
|
||
}
|
||
|
||
// 提取图片(兼容数组/字符串格式)
|
||
const imageUrls = Array.isArray(detail.image_url)
|
||
? detail.image_url.map(u => String(u || '').trim()).filter(Boolean)
|
||
: (detail.image_url ? [ String(detail.image_url).trim() ] : []);
|
||
if (imageUrls.length > 0) {
|
||
imagesByStockId.set(stockId, imageUrls);
|
||
}
|
||
}
|
||
} catch (error) {
|
||
ctx.logger?.warn?.('[storage.inventory] 查询商品附属信息失败,已降级为空数组', {
|
||
error: error.message,
|
||
});
|
||
}
|
||
|
||
return {
|
||
barcodesByStockId,
|
||
imagesByStockId,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 为库存列表补充商品附属信息。
|
||
*
|
||
* @param {Object} ctx 当前请求上下文
|
||
* @param {Object[]} list 库存列表
|
||
* @return {Promise<void>}
|
||
*/
|
||
async function enrichInventoryStockAttachments(ctx, list = []) {
|
||
const stockIds = list.map(item => Number(item?.stock?.id || item?.stock_id || 0)).filter(Boolean);
|
||
const { barcodesByStockId, imagesByStockId } = await loadStockAttachments(ctx, stockIds);
|
||
|
||
for (const item of list) {
|
||
const stockId = Number(item?.stock?.id || item?.stock_id || 0);
|
||
if (!stockId) {
|
||
continue;
|
||
}
|
||
|
||
if (!item.stock) {
|
||
item.stock = {};
|
||
}
|
||
|
||
item.stock.barcodes = barcodesByStockId.get(stockId) || [];
|
||
item.stock.images = imagesByStockId.get(stockId) || [];
|
||
}
|
||
}
|
||
|
||
class InventoryService extends Service {
|
||
|
||
/**
|
||
* 写入移库双向库位流水(移库出/移库入)。
|
||
*
|
||
* 说明:
|
||
* 1) before/after 与锁定字段均写同值快照,避免被识别为普通出入库数量变化;
|
||
* 2) 仅记录移库行为本身,不绑定订单字段。
|
||
*
|
||
* @param {Object} data 入参
|
||
* @param {Object} data.transaction 数据库事务
|
||
* @param {Object} data.srcRecord 源库存记录
|
||
* @param {number} data.transferQuantity 移库数量
|
||
* @param {number} data.sourceSpaceId 源库位ID
|
||
* @param {number} data.targetSpaceId 目标库位ID
|
||
* @param {number|null} data.targetStorageId 目标库存记录ID
|
||
* @param {number} data.totalSnapshotQuantity stock_id 总库存快照数量
|
||
* @param {number} data.totalSnapshotLockedQuantity stock_id 总锁定快照数量
|
||
* @return {Promise<void>} 无返回值
|
||
*/
|
||
async createTransferStockTransactions(data = {}) {
|
||
const { ctx } = this;
|
||
|
||
const operatorId = ctx.user?.employees_id || ctx.user?.id || null;
|
||
const operatorName = ctx.user?.employees_name || '';
|
||
|
||
const totalSnapshotQuantity = Number(data.totalSnapshotQuantity) || 0;
|
||
const totalSnapshotLockedQuantity = Number(data.totalSnapshotLockedQuantity) || 0;
|
||
|
||
await ctx.model.StorageTransaction.create({
|
||
transaction_type: 'TRANSFER_OUT',
|
||
warehouse_id: data.srcRecord.warehouse_id,
|
||
store_id: data.srcRecord.store_id,
|
||
stock_id: data.srcRecord.stock_id,
|
||
storage_id: data.srcRecord.id,
|
||
space_id: data.sourceSpaceId,
|
||
quantity: data.transferQuantity,
|
||
batch_no: data.srcRecord.batch_no,
|
||
inventory_type: data.srcRecord.inventory_type,
|
||
order_type: null,
|
||
order_no: null,
|
||
order_id: null,
|
||
operator_id: operatorId,
|
||
operator_name: operatorName,
|
||
remark: '移库出',
|
||
before_quantity: totalSnapshotQuantity,
|
||
after_quantity: totalSnapshotQuantity,
|
||
before_locked_quantity: totalSnapshotLockedQuantity,
|
||
after_locked_quantity: totalSnapshotLockedQuantity,
|
||
source_order_codes: null,
|
||
created_at: new Date(),
|
||
}, {
|
||
transaction: data.transaction,
|
||
});
|
||
|
||
await ctx.model.StorageTransaction.create({
|
||
transaction_type: 'TRANSFER_IN',
|
||
warehouse_id: data.srcRecord.warehouse_id,
|
||
store_id: data.srcRecord.store_id,
|
||
stock_id: data.srcRecord.stock_id,
|
||
storage_id: data.targetStorageId,
|
||
space_id: data.targetSpaceId,
|
||
quantity: data.transferQuantity,
|
||
batch_no: data.srcRecord.batch_no,
|
||
inventory_type: data.srcRecord.inventory_type,
|
||
order_type: null,
|
||
order_no: null,
|
||
order_id: null,
|
||
operator_id: operatorId,
|
||
operator_name: operatorName,
|
||
remark: '移库入',
|
||
before_quantity: totalSnapshotQuantity,
|
||
after_quantity: totalSnapshotQuantity,
|
||
before_locked_quantity: totalSnapshotLockedQuantity,
|
||
after_locked_quantity: totalSnapshotLockedQuantity,
|
||
source_order_codes: null,
|
||
created_at: new Date(),
|
||
}, {
|
||
transaction: data.transaction,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 移库(库位转移):将单条库存从一个库位移动到另一个库位。
|
||
* 支持部分/全量移库、目标库位合并。
|
||
*
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.storage_id 库存记录ID(必填)
|
||
* @param {number} data.target_space_id 目标库位ID(必填)
|
||
* @param {number} [data.quantity] 移库数量(可选,默认全部移动)
|
||
* @return {Promise<Object>} code/data/message 结构
|
||
*/
|
||
async transferLocation(data = {}) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
|
||
// ────────── 1. 参数校验 ──────────
|
||
const storageId = Number(data.storage_id || 0);
|
||
if (!storageId) {
|
||
return { code: 400, message: 'storage_id 必填', data: null };
|
||
}
|
||
|
||
const targetSpaceId = Number(data.target_space_id || 0);
|
||
if (!targetSpaceId) {
|
||
return { code: 400, message: 'target_space_id 必填', data: null };
|
||
}
|
||
|
||
if (data.quantity !== undefined && data.quantity !== null) {
|
||
const qty = Number(data.quantity);
|
||
if (!Number.isFinite(qty) || qty <= 0) {
|
||
return { code: 400, message: 'quantity 必须为正数', data: null };
|
||
}
|
||
}
|
||
|
||
// ────────── 2. 开事务 ──────────
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// ────────── 3. 锁定并校验原库存记录 ──────────
|
||
const srcRecord = await ctx.model.Storage.findOne({
|
||
where: {
|
||
id: storageId,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
},
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
if (!srcRecord) {
|
||
await transaction.rollback();
|
||
return { code: 404, message: `库存记录不存在: storage_id=${storageId}`, data: null };
|
||
}
|
||
|
||
const warehouseId = srcRecord.warehouse_id;
|
||
|
||
const stockWarehouseSnapshot = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: srcRecord.stock_id },
|
||
attributes: [ 'id', 'quantity', 'locked_quantity' ],
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
if (!stockWarehouseSnapshot) {
|
||
await transaction.rollback();
|
||
return { code: 404, message: `商品SKU不存在: stock_id=${srcRecord.stock_id}`, data: null };
|
||
}
|
||
|
||
// ────────── 4. 校验目标库位 ──────────
|
||
const targetSpace = await ctx.model.LocationSpace.findOne({
|
||
where: {
|
||
id: targetSpaceId,
|
||
is_enabled: true,
|
||
},
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
if (!targetSpace) {
|
||
await transaction.rollback();
|
||
return { code: 404, message: `目标库位不存在或未启用: space_id=${targetSpaceId}`, data: null };
|
||
}
|
||
if (targetSpace.warehouse_id !== warehouseId) {
|
||
await transaction.rollback();
|
||
return { code: 400, message: `目标库位 ${targetSpaceId} 不属于仓库 ${warehouseId}`, data: null };
|
||
}
|
||
if (![ 'AVAILABLE', 'OCCUPIED' ].includes(targetSpace.space_status)) {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 400,
|
||
message: `目标库位 ${targetSpace.space_code} 状态为 ${targetSpace.space_status},不可移入`,
|
||
data: null,
|
||
};
|
||
}
|
||
|
||
// ────────── 5. 处理移库 ──────────
|
||
const availableQty = srcRecord.quantity - srcRecord.locked_quantity;
|
||
const transferQty = (data.quantity !== undefined && data.quantity !== null)
|
||
? Number(data.quantity)
|
||
: availableQty;
|
||
|
||
// 校验移库数量
|
||
if (transferQty > availableQty) {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 400,
|
||
message: `库存记录 ${storageId} 可用数量不足:可用 ${availableQty},请求移库 ${transferQty}`,
|
||
data: null,
|
||
};
|
||
}
|
||
|
||
// 原库位与目标库位相同则直接返回
|
||
if (srcRecord.space_id === targetSpaceId) {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 200,
|
||
message: '原库位与目标库位相同,无需移库',
|
||
data: {
|
||
storage_id: storageId,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: 0,
|
||
status: 'skipped',
|
||
},
|
||
};
|
||
}
|
||
|
||
const beforeSnapshot = {
|
||
storage_id: storageId,
|
||
space_id: srcRecord.space_id,
|
||
quantity: srcRecord.quantity,
|
||
available_quantity: srcRecord.available_quantity,
|
||
};
|
||
|
||
const isFullTransfer = (transferQty === srcRecord.quantity);
|
||
|
||
// 查找目标库位是否已有相同 stock_id + batch_no + inventory_type 的记录
|
||
const existingTarget = await ctx.model.Storage.findOne({
|
||
where: {
|
||
space_id: targetSpaceId,
|
||
stock_id: srcRecord.stock_id,
|
||
batch_no: srcRecord.batch_no,
|
||
inventory_type: srcRecord.inventory_type,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
id: { [Op.ne]: storageId }, // 排除自身(全量移库时直接改 space_id 的情况)
|
||
},
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
let afterSnapshot;
|
||
let targetStorageId = null;
|
||
// 原库位统计变化
|
||
const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 };
|
||
// 目标库位统计变化
|
||
const tgtSpaceDelta = { skuDelta: 0, qtyDelta: 0 };
|
||
|
||
if (existingTarget) {
|
||
// ── 目标库位已有同规格记录:合并数量 ──
|
||
await ctx.model.Storage.update({
|
||
quantity: app.Sequelize.literal(`quantity + ${transferQty}`),
|
||
available_quantity: app.Sequelize.literal(`available_quantity + ${transferQty}`),
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: existingTarget.id },
|
||
transaction,
|
||
});
|
||
|
||
if (isFullTransfer) {
|
||
// 全量移库且合并:硬删除原记录,释放唯一键
|
||
await ctx.model.Storage.destroy({
|
||
where: { id: storageId },
|
||
force: true,
|
||
transaction,
|
||
});
|
||
srcSpaceDelta.qtyDelta -= srcRecord.quantity;
|
||
// 检查原库位该 SKU 是否还有其他记录
|
||
const remainingSku = await ctx.model.Storage.count({
|
||
where: {
|
||
space_id: srcRecord.space_id,
|
||
stock_id: srcRecord.stock_id,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
id: { [Op.ne]: storageId },
|
||
},
|
||
transaction,
|
||
});
|
||
if (remainingSku === 0) {
|
||
srcSpaceDelta.skuDelta -= 1;
|
||
}
|
||
} else {
|
||
// 部分移库:减少原记录数量
|
||
await ctx.model.Storage.update({
|
||
quantity: app.Sequelize.literal(`quantity - ${transferQty}`),
|
||
available_quantity: app.Sequelize.literal(`available_quantity - ${transferQty}`),
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: storageId },
|
||
transaction,
|
||
});
|
||
srcSpaceDelta.qtyDelta -= transferQty;
|
||
}
|
||
|
||
// 目标库位数量增加
|
||
tgtSpaceDelta.qtyDelta += transferQty;
|
||
// 目标库位该 SKU 之前已有记录,skuDelta 不变
|
||
|
||
targetStorageId = existingTarget.id;
|
||
afterSnapshot = {
|
||
merged_into: existingTarget.id,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: transferQty,
|
||
source_deleted: isFullTransfer,
|
||
};
|
||
} else if (isFullTransfer) {
|
||
// ── 全量移库 & 目标无同规格记录:直接修改 space_id ──
|
||
await ctx.model.Storage.update({
|
||
space_id: targetSpaceId,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: storageId },
|
||
transaction,
|
||
});
|
||
|
||
srcSpaceDelta.qtyDelta -= srcRecord.quantity;
|
||
// 检查原库位该 SKU 是否还有其他记录
|
||
const remainingSku = await ctx.model.Storage.count({
|
||
where: {
|
||
space_id: srcRecord.space_id,
|
||
stock_id: srcRecord.stock_id,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
id: { [Op.ne]: storageId },
|
||
},
|
||
transaction,
|
||
});
|
||
if (remainingSku === 0) {
|
||
srcSpaceDelta.skuDelta -= 1;
|
||
}
|
||
|
||
// 目标库位新增一个 SKU
|
||
const existingSkuInTarget = await ctx.model.Storage.count({
|
||
where: {
|
||
space_id: targetSpaceId,
|
||
stock_id: srcRecord.stock_id,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
id: { [Op.ne]: storageId }, // 排掉自身(此时 space_id 已更新,但事务内逻辑用旧值)
|
||
},
|
||
transaction,
|
||
});
|
||
if (existingSkuInTarget === 0) {
|
||
tgtSpaceDelta.skuDelta += 1;
|
||
}
|
||
tgtSpaceDelta.qtyDelta += srcRecord.quantity;
|
||
|
||
targetStorageId = storageId;
|
||
afterSnapshot = {
|
||
storage_id: storageId,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: transferQty,
|
||
source_deleted: false,
|
||
};
|
||
} else {
|
||
// ── 部分移库 & 目标无同规格记录:减少原记录数量,新建目标记录 ──
|
||
await ctx.model.Storage.update({
|
||
quantity: app.Sequelize.literal(`quantity - ${transferQty}`),
|
||
available_quantity: app.Sequelize.literal(`available_quantity - ${transferQty}`),
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: storageId },
|
||
transaction,
|
||
});
|
||
|
||
const newRecord = await ctx.model.Storage.create({
|
||
warehouse_id: srcRecord.warehouse_id,
|
||
store_id: srcRecord.store_id,
|
||
space_id: targetSpaceId,
|
||
stock_id: srcRecord.stock_id,
|
||
batch_no: srcRecord.batch_no,
|
||
inventory_type: srcRecord.inventory_type,
|
||
quantity: transferQty,
|
||
locked_quantity: 0,
|
||
available_quantity: transferQty,
|
||
production_date: srcRecord.production_date,
|
||
expiry_date: srcRecord.expiry_date,
|
||
inbound_time: srcRecord.inbound_time,
|
||
inbound_order_no: srcRecord.inbound_order_no,
|
||
receiving_id: srcRecord.receiving_id,
|
||
entry_order_id: srcRecord.entry_order_id,
|
||
supplier_id: srcRecord.supplier_id,
|
||
supplier_batch_no: srcRecord.supplier_batch_no,
|
||
is_enabled: 1,
|
||
created_at: new Date(),
|
||
updated_at: new Date(),
|
||
}, { transaction });
|
||
|
||
srcSpaceDelta.qtyDelta -= transferQty;
|
||
// 原库位 SKU 数不变(原记录仍在)
|
||
|
||
// 目标库位:新增 SKU
|
||
const existingSkuInTarget = await ctx.model.Storage.count({
|
||
where: {
|
||
space_id: targetSpaceId,
|
||
stock_id: srcRecord.stock_id,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
},
|
||
transaction,
|
||
});
|
||
// count 包含刚 create 的记录,如果只有 1 条说明之前没有
|
||
if (existingSkuInTarget <= 1) {
|
||
tgtSpaceDelta.skuDelta += 1;
|
||
}
|
||
tgtSpaceDelta.qtyDelta += transferQty;
|
||
|
||
targetStorageId = newRecord.id;
|
||
afterSnapshot = {
|
||
new_storage_id: newRecord.id,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: transferQty,
|
||
source_deleted: false,
|
||
};
|
||
}
|
||
|
||
await this.createTransferStockTransactions({
|
||
transaction,
|
||
srcRecord,
|
||
transferQuantity: transferQty,
|
||
sourceSpaceId: srcRecord.space_id,
|
||
targetSpaceId,
|
||
targetStorageId,
|
||
totalSnapshotQuantity: Number(stockWarehouseSnapshot.quantity) || 0,
|
||
totalSnapshotLockedQuantity: Number(stockWarehouseSnapshot.locked_quantity) || 0,
|
||
});
|
||
|
||
// ────────── 记录操作日志(事务内) ──────────
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'storage',
|
||
businessId: storageId,
|
||
operationCode: 'STORAGE_TRANSFER_LOCATION',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: transferQty,
|
||
},
|
||
beforeChanges: beforeSnapshot,
|
||
afterChanges: afterSnapshot,
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[inventory.transferLocation] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
// ────────── 6. 更新库位统计 ──────────
|
||
const updateSpaceStats = async (spaceId, delta) => {
|
||
if (delta.qtyDelta === 0 && delta.skuDelta === 0) return;
|
||
const updateFields = {};
|
||
if (delta.qtyDelta !== 0) {
|
||
updateFields.current_quantity = app.Sequelize.literal(
|
||
`GREATEST(COALESCE(current_quantity, 0) + (${delta.qtyDelta}), 0)`
|
||
);
|
||
}
|
||
if (delta.skuDelta !== 0) {
|
||
updateFields.current_sku_count = app.Sequelize.literal(
|
||
`GREATEST(COALESCE(current_sku_count, 0) + (${delta.skuDelta}), 0)`
|
||
);
|
||
}
|
||
await ctx.model.LocationSpace.update(updateFields, {
|
||
where: { id: spaceId },
|
||
transaction,
|
||
});
|
||
};
|
||
|
||
await updateSpaceStats(srcRecord.space_id, srcSpaceDelta);
|
||
await updateSpaceStats(targetSpaceId, tgtSpaceDelta);
|
||
|
||
// ────────── 7. 提交事务 ──────────
|
||
await transaction.commit();
|
||
|
||
ctx.logger.info('[inventory.transferLocation] 移库完成', {
|
||
warehouse_id: warehouseId,
|
||
storage_id: storageId,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: transferQty,
|
||
});
|
||
|
||
return {
|
||
code: 200,
|
||
message: '移库完成',
|
||
data: {
|
||
storage_id: storageId,
|
||
stock_id: srcRecord.stock_id,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: transferQty,
|
||
status: 'success',
|
||
},
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
ctx.logger.error('[inventory.transferLocation] 移库异常', {
|
||
storage_id: storageId,
|
||
target_space_id: targetSpaceId,
|
||
error: error.message,
|
||
stack: error.stack,
|
||
});
|
||
|
||
if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) {
|
||
return { code: 409, message: '库存记录被锁定,请稍后重试', data: null };
|
||
}
|
||
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按库位+商品维度移库。
|
||
* 自动查找该库位下该商品的所有 storage 记录,按 quantity ASC 逐条扣减并合并移动到目标库位。
|
||
*
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.space_id 原库位ID(必填)
|
||
* @param {number} data.stock_id 商品SKU ID(必填,对应 wms_stock_warehouse.id)
|
||
* @param {number} data.target_space_id 目标库位ID(必填)
|
||
* @param {number} data.quantity 移库数量(必填)
|
||
* @return {Promise<Object>} code/data/message 结构
|
||
*/
|
||
async transferByProduct(data = {}) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
|
||
// ────────── 1. 参数校验 ──────────
|
||
const spaceId = Number(data.space_id || 0);
|
||
const stockId = Number(data.stock_id || 0);
|
||
const targetSpaceId = Number(data.target_space_id || 0);
|
||
const quantity = Number(data.quantity || 0);
|
||
|
||
if (!spaceId) {
|
||
return { code: 400, message: 'space_id 必填', data: null };
|
||
}
|
||
if (!stockId) {
|
||
return { code: 400, message: 'stock_id 必填', data: null };
|
||
}
|
||
if (!targetSpaceId) {
|
||
return { code: 400, message: 'target_space_id 必填', data: null };
|
||
}
|
||
if (!Number.isFinite(quantity) || quantity <= 0) {
|
||
return { code: 400, message: 'quantity 必须为正数', data: null };
|
||
}
|
||
|
||
// ────────── 2. 批次管理校验 ──────────
|
||
const stockWarehouse = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: stockId },
|
||
attributes: [ 'id', 'is_batch_mgmt' ],
|
||
});
|
||
if (!stockWarehouse) {
|
||
return { code: 404, message: `商品SKU不存在: stock_id=${stockId}`, data: null };
|
||
}
|
||
if (stockWarehouse.is_batch_mgmt === 'Y') {
|
||
return {
|
||
code: 400,
|
||
message: '该商品已开启批次管理,请使用按库存记录移库(transferLocation)',
|
||
data: null,
|
||
};
|
||
}
|
||
|
||
// ────────── 3. 原库位与目标库位相同 ──────────
|
||
if (spaceId === targetSpaceId) {
|
||
return {
|
||
code: 200,
|
||
message: '原库位与目标库位相同,无需移库',
|
||
data: {
|
||
space_id: spaceId,
|
||
stock_id: stockId,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: 0,
|
||
affected_storage_count: 0,
|
||
status: 'skipped',
|
||
},
|
||
};
|
||
}
|
||
|
||
// ────────── 4. 开事务 ──────────
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// ────────── 5. 查找并锁定原库存记录 ──────────
|
||
const srcRecords = await ctx.model.Storage.findAll({
|
||
where: {
|
||
space_id: spaceId,
|
||
stock_id: stockId,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
},
|
||
order: [[ 'quantity', 'ASC' ]],
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
if (!srcRecords.length) {
|
||
await transaction.rollback();
|
||
return { code: 404, message: `原库位 ${spaceId} 下未找到商品 ${stockId} 的库存记录`, data: null };
|
||
}
|
||
|
||
const totalAvailable = srcRecords.reduce((sum, r) => sum + (r.quantity - r.locked_quantity), 0);
|
||
if (quantity > totalAvailable) {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 400,
|
||
message: `可用数量不足:可用 ${totalAvailable},请求移库 ${quantity}`,
|
||
data: null,
|
||
};
|
||
}
|
||
|
||
const warehouseId = srcRecords[0].warehouse_id;
|
||
|
||
const stockWarehouseSnapshot = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: stockId },
|
||
attributes: [ 'id', 'quantity', 'locked_quantity' ],
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
if (!stockWarehouseSnapshot) {
|
||
await transaction.rollback();
|
||
return { code: 404, message: `商品SKU不存在: stock_id=${stockId}`, data: null };
|
||
}
|
||
|
||
// ────────── 6. 校验目标库位 ──────────
|
||
const targetSpace = await ctx.model.LocationSpace.findOne({
|
||
where: {
|
||
id: targetSpaceId,
|
||
is_enabled: true,
|
||
},
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
if (!targetSpace) {
|
||
await transaction.rollback();
|
||
return { code: 404, message: `目标库位不存在或未启用: space_id=${targetSpaceId}`, data: null };
|
||
}
|
||
if (targetSpace.warehouse_id !== warehouseId) {
|
||
await transaction.rollback();
|
||
return { code: 400, message: `目标库位 ${targetSpaceId} 不属于仓库 ${warehouseId}`, data: null };
|
||
}
|
||
if (![ 'AVAILABLE', 'OCCUPIED' ].includes(targetSpace.space_status)) {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 400,
|
||
message: `目标库位 ${targetSpace.space_code} 状态为 ${targetSpace.space_status},不可移入`,
|
||
data: null,
|
||
};
|
||
}
|
||
|
||
// ────────── 7. 逐条扣减并移库 ──────────
|
||
let remainingQty = quantity;
|
||
let affectedCount = 0;
|
||
const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 };
|
||
const tgtSpaceDelta = { skuDelta: 0, qtyDelta: 0 };
|
||
|
||
// 预先记录目标库位是否已有该 SKU(用于事后计算 skuDelta)
|
||
const tgtSkuCountBefore = await ctx.model.Storage.count({
|
||
where: {
|
||
space_id: targetSpaceId,
|
||
stock_id: stockId,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
for (const srcRecord of srcRecords) {
|
||
if (remainingQty <= 0) break;
|
||
|
||
const available = srcRecord.quantity - srcRecord.locked_quantity;
|
||
const toTransfer = Math.min(available, remainingQty);
|
||
if (toTransfer <= 0) continue;
|
||
|
||
affectedCount++;
|
||
const isFullTransfer = (toTransfer === srcRecord.quantity);
|
||
let targetStorageId = null;
|
||
|
||
// ── 在目标库位查找同 stock_id + batch_no + inventory_type 的记录 ──
|
||
const existingTarget = await ctx.model.Storage.findOne({
|
||
where: {
|
||
space_id: targetSpaceId,
|
||
stock_id: srcRecord.stock_id,
|
||
batch_no: srcRecord.batch_no,
|
||
inventory_type: srcRecord.inventory_type,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
id: { [Op.ne]: srcRecord.id },
|
||
},
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
if (existingTarget) {
|
||
// 目标已有同规格记录:合并数量
|
||
await ctx.model.Storage.update({
|
||
quantity: app.Sequelize.literal(`quantity + ${toTransfer}`),
|
||
available_quantity: app.Sequelize.literal(`available_quantity + ${toTransfer}`),
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: existingTarget.id },
|
||
transaction,
|
||
});
|
||
|
||
if (isFullTransfer) {
|
||
// 全量:硬删除原记录,释放唯一键
|
||
await ctx.model.Storage.destroy({
|
||
where: { id: srcRecord.id },
|
||
force: true,
|
||
transaction,
|
||
});
|
||
} else {
|
||
// 部分:减少原记录
|
||
await ctx.model.Storage.update({
|
||
quantity: app.Sequelize.literal(`quantity - ${toTransfer}`),
|
||
available_quantity: app.Sequelize.literal(`available_quantity - ${toTransfer}`),
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: srcRecord.id },
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
targetStorageId = existingTarget.id;
|
||
} else if (isFullTransfer) {
|
||
// 全量移库 & 目标无同规格记录:直接改 space_id
|
||
await ctx.model.Storage.update({
|
||
space_id: targetSpaceId,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: srcRecord.id },
|
||
transaction,
|
||
});
|
||
|
||
targetStorageId = srcRecord.id;
|
||
} else {
|
||
// 部分移库 & 目标无同规格记录:减少原记录,新建目标记录
|
||
await ctx.model.Storage.update({
|
||
quantity: app.Sequelize.literal(`quantity - ${toTransfer}`),
|
||
available_quantity: app.Sequelize.literal(`available_quantity - ${toTransfer}`),
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: srcRecord.id },
|
||
transaction,
|
||
});
|
||
|
||
const newRecord = await ctx.model.Storage.create({
|
||
warehouse_id: srcRecord.warehouse_id,
|
||
store_id: srcRecord.store_id,
|
||
space_id: targetSpaceId,
|
||
stock_id: srcRecord.stock_id,
|
||
batch_no: srcRecord.batch_no,
|
||
inventory_type: srcRecord.inventory_type,
|
||
quantity: toTransfer,
|
||
locked_quantity: 0,
|
||
available_quantity: toTransfer,
|
||
production_date: srcRecord.production_date,
|
||
expiry_date: srcRecord.expiry_date,
|
||
inbound_time: srcRecord.inbound_time,
|
||
inbound_order_no: srcRecord.inbound_order_no,
|
||
receiving_id: srcRecord.receiving_id,
|
||
entry_order_id: srcRecord.entry_order_id,
|
||
supplier_id: srcRecord.supplier_id,
|
||
supplier_batch_no: srcRecord.supplier_batch_no,
|
||
is_enabled: 1,
|
||
created_at: new Date(),
|
||
updated_at: new Date(),
|
||
}, { transaction });
|
||
|
||
targetStorageId = newRecord.id;
|
||
}
|
||
|
||
await this.createTransferStockTransactions({
|
||
transaction,
|
||
srcRecord,
|
||
transferQuantity: toTransfer,
|
||
sourceSpaceId: srcRecord.space_id,
|
||
targetSpaceId,
|
||
targetStorageId,
|
||
totalSnapshotQuantity: Number(stockWarehouseSnapshot.quantity) || 0,
|
||
totalSnapshotLockedQuantity: Number(stockWarehouseSnapshot.locked_quantity) || 0,
|
||
});
|
||
|
||
srcSpaceDelta.qtyDelta -= toTransfer;
|
||
tgtSpaceDelta.qtyDelta += toTransfer;
|
||
remainingQty -= toTransfer;
|
||
}
|
||
|
||
// ── 计算 SKU 维度统计变化 ──
|
||
const remainingSrcSku = await ctx.model.Storage.count({
|
||
where: {
|
||
space_id: spaceId,
|
||
stock_id: stockId,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
},
|
||
transaction,
|
||
});
|
||
if (remainingSrcSku === 0) {
|
||
srcSpaceDelta.skuDelta -= 1;
|
||
}
|
||
|
||
if (tgtSkuCountBefore === 0) {
|
||
// 操作前目标库位没有该 SKU,现在有了
|
||
tgtSpaceDelta.skuDelta += 1;
|
||
}
|
||
|
||
// ────────── 8. 操作日志 ──────────
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'storage',
|
||
businessId: spaceId,
|
||
operationCode: 'STORAGE_TRANSFER_BY_PRODUCT',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
space_id: spaceId,
|
||
stock_id: stockId,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: quantity,
|
||
affected_storage_count: affectedCount,
|
||
},
|
||
beforeChanges: {
|
||
space_id: spaceId,
|
||
stock_id: stockId,
|
||
total_available: totalAvailable,
|
||
source_record_count: srcRecords.length,
|
||
},
|
||
afterChanges: {
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: quantity,
|
||
affected_storage_count: affectedCount,
|
||
},
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[inventory.transferByProduct] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
// ────────── 9. 更新库位统计 ──────────
|
||
const updateSpaceStats = async (updateSpaceId, delta) => {
|
||
if (delta.qtyDelta === 0 && delta.skuDelta === 0) return;
|
||
const updateFields = {};
|
||
if (delta.qtyDelta !== 0) {
|
||
updateFields.current_quantity = app.Sequelize.literal(
|
||
`GREATEST(COALESCE(current_quantity, 0) + (${delta.qtyDelta}), 0)`
|
||
);
|
||
}
|
||
if (delta.skuDelta !== 0) {
|
||
updateFields.current_sku_count = app.Sequelize.literal(
|
||
`GREATEST(COALESCE(current_sku_count, 0) + (${delta.skuDelta}), 0)`
|
||
);
|
||
}
|
||
await ctx.model.LocationSpace.update(updateFields, {
|
||
where: { id: updateSpaceId },
|
||
transaction,
|
||
});
|
||
};
|
||
|
||
await updateSpaceStats(spaceId, srcSpaceDelta);
|
||
await updateSpaceStats(targetSpaceId, tgtSpaceDelta);
|
||
|
||
// ────────── 10. 提交事务 ──────────
|
||
await transaction.commit();
|
||
|
||
ctx.logger.info('[inventory.transferByProduct] 按商品移库完成', {
|
||
warehouse_id: warehouseId,
|
||
space_id: spaceId,
|
||
stock_id: stockId,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: quantity,
|
||
affected_storage_count: affectedCount,
|
||
});
|
||
|
||
return {
|
||
code: 200,
|
||
message: '按商品移库完成',
|
||
data: {
|
||
space_id: spaceId,
|
||
stock_id: stockId,
|
||
target_space_id: targetSpaceId,
|
||
transfer_quantity: quantity,
|
||
affected_storage_count: affectedCount,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
ctx.logger.error('[inventory.transferByProduct] 按商品移库异常', {
|
||
space_id: spaceId,
|
||
stock_id: stockId,
|
||
target_space_id: targetSpaceId,
|
||
quantity,
|
||
error: error.message,
|
||
stack: error.stack,
|
||
});
|
||
|
||
if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) {
|
||
return { code: 409, message: '库存记录被锁定,请稍后重试', data: null };
|
||
}
|
||
|
||
if (error.name === 'SequelizeUniqueConstraintError') {
|
||
return {
|
||
code: 409,
|
||
message: '目标库位已存在该商品同批次同类型的库存记录,合并移库失败,请稍后重试或使用 transferLocation 逐条移库',
|
||
data: null,
|
||
};
|
||
}
|
||
|
||
if (error.name === 'SequelizeValidationError') {
|
||
ctx.logger.error('[inventory.transferByProduct] Sequelize 校验失败', {
|
||
errors: error.errors?.map(e => ({ path: e.path, message: e.message, value: e.value })),
|
||
});
|
||
return { code: 400, message: `数据校验失败: ${error.errors?.map(e => e.message).join('; ') || error.message}`, data: null };
|
||
}
|
||
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 查询库存列表。
|
||
*
|
||
* 支持按批次明细或合并模式返回库存,并补充商品条码、图片附件、保质期预警和货主名称。
|
||
* 货主名称来源于货主签约表的 store_remask 字段,最终以 stock.store_name 输出。
|
||
*
|
||
* @param {Object} [pageParams={}] 分页参数
|
||
* @param {number} [pageParams.page=1] 页码
|
||
* @param {number} [pageParams.pageSize=20] 每页数量
|
||
* @param {Object} [sortParams={}] 排序参数
|
||
* @param {string} [sortParams.sortField='created_at'] 排序字段
|
||
* @param {string} [sortParams.sortOrder='DESC'] 排序方向
|
||
* @param {boolean} [groupByBatch=false] 是否按批次明细返回
|
||
* @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果
|
||
*/
|
||
async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false) {
|
||
const { ctx, app } = this;
|
||
const { Op, fn, col, literal } = app.Sequelize;
|
||
const nowMs = Date.now();
|
||
|
||
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 },
|
||
{ is_enabled: 1 },
|
||
{ delete_at: null },
|
||
],
|
||
};
|
||
|
||
// 动态 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) {
|
||
let inventoryWarningRanges = [];
|
||
try {
|
||
const store = await ctx.model.Store.findByPk(warehouseId, {
|
||
attributes: [ 'id', 'subject_config' ],
|
||
});
|
||
const normalizedSubjectConfig = ctx.model.Store.normalizeSubjectConfig(
|
||
store ? store.subject_config : null
|
||
);
|
||
inventoryWarningRanges = buildInventoryWarningRanges(
|
||
normalizedSubjectConfig && Array.isArray(normalizedSubjectConfig.inventory_warning_rules)
|
||
? normalizedSubjectConfig.inventory_warning_rules
|
||
: []
|
||
);
|
||
} catch (error) {
|
||
ctx.logger.warn(`[getInventoryList] 库存预警规则读取失败: ${error.message}`);
|
||
}
|
||
|
||
// 按批次明细:逐条返回
|
||
const { count: total, rows } = await ctx.model.Storage.findAndCountAll({
|
||
where: baseWhere,
|
||
order: [[ sortField, sortOrder ]],
|
||
offset,
|
||
limit,
|
||
include: [
|
||
{
|
||
model: ctx.model.StockWarehouse,
|
||
as: 'stock',
|
||
attributes: [
|
||
'id',
|
||
'item_code',
|
||
'item_name',
|
||
'sku_property',
|
||
'stock_unit',
|
||
'is_batch_mgmt',
|
||
'is_shelf_life_mgmt',
|
||
'remaining_threshold_days',
|
||
],
|
||
include: [
|
||
{
|
||
model: ctx.model.StoreWarehouse,
|
||
as: 'store_stock',
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
required: false,
|
||
},
|
||
],
|
||
required: false,
|
||
},
|
||
{
|
||
model: ctx.model.LocationSpace,
|
||
as: 'space',
|
||
attributes: [ 'id', 'space_code', 'custom_name' ],
|
||
required: false,
|
||
},
|
||
],
|
||
});
|
||
|
||
const list = rows.map(item => {
|
||
const row = item.get({ plain: true });
|
||
const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs);
|
||
const inventoryWarningPayload = getInventoryWarningPayload(
|
||
shelfLifeWarningState.remainingDays,
|
||
inventoryWarningRanges
|
||
);
|
||
if (row.stock) {
|
||
row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt);
|
||
row.stock.store_name = row.stock.store_stock?.store_remask || null;
|
||
delete row.stock.store_stock;
|
||
delete row.stock.is_batch_mgmt;
|
||
}
|
||
// 货主名称提升到根层级,便于前端直接使用
|
||
row.store_name = row.stock?.store_name || null;
|
||
row.created_at = row.created_at ? app.formatDate(row.created_at) : '';
|
||
row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : '';
|
||
row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : '';
|
||
row.production_date = row.production_date ? app.formatDate(row.production_date) : '';
|
||
row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : '';
|
||
row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered;
|
||
row.expiry_remaining_days = inventoryWarningPayload.expiry_remaining_days;
|
||
row.inventory_warning_level = inventoryWarningPayload.inventory_warning_level;
|
||
row.inventory_warning_color = inventoryWarningPayload.inventory_warning_color;
|
||
row.inventory_warning_range = inventoryWarningPayload.inventory_warning_range;
|
||
row.inventory_warning_tip_text = inventoryWarningPayload.inventory_warning_tip_text;
|
||
return row;
|
||
});
|
||
|
||
await enrichInventoryStockAttachments(ctx, list);
|
||
|
||
return {
|
||
list,
|
||
pagination: {
|
||
page,
|
||
pageSize,
|
||
total,
|
||
totalPages: Math.ceil(total / pageSize),
|
||
},
|
||
};
|
||
}
|
||
|
||
// 不按批次:仅按 stock_id 合并(跨库位、跨库存类型汇总)
|
||
const groupFields = [ 'stock_id' ];
|
||
|
||
const countResult = await ctx.model.Storage.count({
|
||
where: baseWhere,
|
||
group: groupFields,
|
||
});
|
||
const total = Array.isArray(countResult) ? countResult.length : countResult;
|
||
|
||
const rows = await ctx.model.Storage.findAll({
|
||
where: baseWhere,
|
||
attributes: [
|
||
'stock_id',
|
||
[ fn('MIN', col('wms_storage.warehouse_id')), 'warehouse_id' ],
|
||
[ fn('MIN', col('wms_storage.store_id')), 'store_id' ],
|
||
[ fn('MIN', col('wms_storage.production_date')), 'production_date' ],
|
||
[ fn('MIN', col('wms_storage.expiry_date')), 'expiry_date' ],
|
||
[ fn('SUM', col('wms_storage.quantity')), 'quantity' ],
|
||
[ fn('SUM', col('wms_storage.locked_quantity')), 'locked_quantity' ],
|
||
[ fn('SUM', col('wms_storage.available_quantity')), 'available_quantity' ],
|
||
[ fn('MIN', col('wms_storage.inbound_time')), 'first_inbound_time' ],
|
||
[ fn('MAX', col('wms_storage.inbound_time')), 'last_inbound_time' ],
|
||
[ fn('COUNT', col('wms_storage.id')), 'batch_count' ],
|
||
],
|
||
group: groupFields,
|
||
order: [[ literal('last_inbound_time'), sortOrder ]],
|
||
offset,
|
||
limit,
|
||
include: [
|
||
{
|
||
model: ctx.model.StockWarehouse,
|
||
as: 'stock',
|
||
attributes: [
|
||
'id',
|
||
'item_code',
|
||
'item_name',
|
||
'sku_property',
|
||
'stock_unit',
|
||
'is_batch_mgmt',
|
||
'is_shelf_life_mgmt',
|
||
'remaining_threshold_days',
|
||
],
|
||
include: [
|
||
{
|
||
model: ctx.model.StoreWarehouse,
|
||
as: 'store_stock',
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
required: false,
|
||
},
|
||
],
|
||
required: false,
|
||
},
|
||
],
|
||
raw: true,
|
||
nest: true,
|
||
});
|
||
|
||
const list = rows.map(row => {
|
||
const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs);
|
||
if (row.stock) {
|
||
row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt);
|
||
row.stock.store_name = row.stock.store_stock?.store_remask || null;
|
||
delete row.stock.store_stock;
|
||
delete row.stock.is_batch_mgmt;
|
||
}
|
||
// 货主名称提升到根层级,便于前端直接使用
|
||
row.store_name = row.stock?.store_name || null;
|
||
row.first_inbound_time = row.first_inbound_time ? app.formatDate(row.first_inbound_time) : '';
|
||
row.last_inbound_time = row.last_inbound_time ? app.formatDate(row.last_inbound_time) : '';
|
||
row.production_date = row.production_date ? app.formatDate(row.production_date) : '';
|
||
row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : '';
|
||
row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered;
|
||
return row;
|
||
});
|
||
|
||
await enrichInventoryStockAttachments(ctx, list);
|
||
|
||
return {
|
||
list,
|
||
pagination: {
|
||
page,
|
||
pageSize,
|
||
total,
|
||
totalPages: Math.ceil(total / pageSize),
|
||
},
|
||
};
|
||
}
|
||
/**
|
||
* 收货单快捷入库:判断货主配置是否允许收货单快捷入库,不允许直接返回失败;
|
||
* 允许的话使用收货单的明细创建入库单,相同 stock_id 的合并为一条,汇集总数。
|
||
* 在 wms_entry_order_receiving 表建立绑定关系,入库单自动审批到 PENDING 状态。
|
||
*
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.receiving_id 收货单ID(必填)
|
||
* @return {Promise<Object>} code/data/message 结构,data 中包含创建的入库单信息
|
||
*/
|
||
async quickPutaway(data = {}) {
|
||
const { ctx, app } = this;
|
||
const receivingId = Number(data.receiving_id || 0);
|
||
|
||
// ────────── 1. 参数校验 ──────────
|
||
if (!receivingId) {
|
||
return { code: 400, message: 'receiving_id 必填', data: null };
|
||
}
|
||
|
||
const warehouseId = ctx.user.store_id;
|
||
if (!warehouseId) {
|
||
return { code: 400, message: '无法获取当前仓库信息', data: null };
|
||
}
|
||
|
||
// ────────── 2. 加载收货单主表及明细 ──────────
|
||
const receiving = await ctx.model.Receiving.findOne({
|
||
where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false },
|
||
});
|
||
|
||
if (!receiving) {
|
||
return { code: 404, message: `收货单不存在或无权访问: receiving_id=${receivingId}`, data: null };
|
||
}
|
||
|
||
if (receiving.status === 'cancelled') {
|
||
return { code: 400, message: '收货单已作废,不允许快捷入库', data: null };
|
||
}
|
||
|
||
if (receiving.status !== 'completed') {
|
||
return { code: 400, message: `收货单状态不允许快捷入库,当前状态: ${receiving.status},仅 completed 状态可操作`, data: null };
|
||
}
|
||
|
||
if (!receiving.is_review) {
|
||
return { code: 400, message: '收货单未审核,不允许快捷入库', data: null };
|
||
}
|
||
|
||
const storeId = receiving.store_id;
|
||
|
||
// ────────── 3. 检查货主配置:是否允许收货单快捷入库 ──────────
|
||
const storeWarehouse = await ctx.model.StoreWarehouse.findOne({
|
||
where: { store_id: storeId, warehouse_id: warehouseId, warehouse_use_status: 1 },
|
||
attributes: [ 'id', 'policy_config' ],
|
||
});
|
||
|
||
if (!storeWarehouse) {
|
||
return { code: 400, message: '货主仓库签约关系不存在', data: null };
|
||
}
|
||
|
||
const policyConfig = storeWarehouse.policy_config || {};
|
||
const allowQuickPutaway = Number(policyConfig.allow_receiving_quick_putaway) === 1;
|
||
|
||
if (!allowQuickPutaway) {
|
||
return { code: 400, message: '货主未开启收货单快捷入库功能,请联系管理员开启', data: null };
|
||
}
|
||
|
||
// ────────── 4. 加载收货单明细 ──────────
|
||
const receivingDetails = await ctx.model.ReceivingDetail.findAll({
|
||
where: { receiving_id: receivingId },
|
||
attributes: [
|
||
'id', 'system_product_id', 'actual_quantity', 'product_name',
|
||
'batch_number', 'production_date', 'expiry_date',
|
||
'storage_status', 'stored_quantity',
|
||
],
|
||
});
|
||
|
||
if (!receivingDetails || receivingDetails.length === 0) {
|
||
return { code: 400, message: '收货单无明细,无法创建入库单', data: null };
|
||
}
|
||
|
||
// ────────── 5. 按 stock_id(system_product_id)分组,合并数量 ──────────
|
||
/** @type {Map<number, {system_product_id: number, total_quantity: number, product_name: string, batch_number: string, production_date: string|null, expiry_date: string|null, detail_ids: number[]}>} */
|
||
const groupedMap = new Map();
|
||
|
||
for (const detail of receivingDetails) {
|
||
const stockId = Number(detail.system_product_id);
|
||
if (!stockId) {
|
||
// 跳过未匹配系统商品的明细
|
||
continue;
|
||
}
|
||
|
||
const qty = Number(detail.actual_quantity) || 0;
|
||
if (qty <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const existing = groupedMap.get(stockId);
|
||
if (existing) {
|
||
existing.total_quantity += qty;
|
||
existing.detail_ids.push(detail.id);
|
||
} else {
|
||
groupedMap.set(stockId, {
|
||
system_product_id: stockId,
|
||
total_quantity: qty,
|
||
product_name: detail.product_name || '',
|
||
batch_number: detail.batch_number || '',
|
||
production_date: detail.production_date || null,
|
||
expiry_date: detail.expiry_date || null,
|
||
detail_ids: [ detail.id ],
|
||
});
|
||
}
|
||
}
|
||
|
||
if (groupedMap.size === 0) {
|
||
return { code: 400, message: '收货单中所有明细均未关联系统商品,无法创建入库单', data: null };
|
||
}
|
||
|
||
const groupedItems = Array.from(groupedMap.values());
|
||
|
||
// ────────── 6. 批量查询 stock_warehouse 获取 stock_id 对应的商品信息 ──────────
|
||
const stockIds = groupedItems.map(item => item.system_product_id);
|
||
const stockRows = await ctx.model.StockWarehouse.findAll({
|
||
where: { id: { [app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId },
|
||
attributes: [ 'id', 'item_code', 'item_name', 'stock_unit', 'is_valid' ],
|
||
raw: true,
|
||
});
|
||
const stockMap = new Map();
|
||
for (const row of stockRows) {
|
||
stockMap.set(Number(row.id), row);
|
||
}
|
||
|
||
// 校验所有 stock_id 是否存在且有效
|
||
const missingStockIds = stockIds.filter(sid => !stockMap.has(sid));
|
||
if (missingStockIds.length > 0) {
|
||
return {
|
||
code: 400,
|
||
message: `以下商品在当前仓库中不存在或已失效: stock_id=${missingStockIds.join(',')}`,
|
||
data: null,
|
||
};
|
||
}
|
||
|
||
// ────────── 7. 开事务,创建入库单及明细 ──────────
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// 获取货主和仓库名称快照
|
||
const storeData = await ctx.service.systems.store.getStoreName(storeId);
|
||
const storeName = (storeData.code === 200 && storeData.data) ? storeData.data.company_name : '';
|
||
const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId);
|
||
const warehouseName = (warehouseData.code === 200 && warehouseData.data) ? warehouseData.data.company_name : '';
|
||
|
||
// 生成入库单号
|
||
const entryOrderCode = await this._generateEntryOrderCode(warehouseId, storeId, transaction);
|
||
|
||
// 创建入库单主表(状态直接设为 PENDING)
|
||
const entryOrder = await ctx.model.EntryOrder.create({
|
||
entry_order_code: entryOrderCode,
|
||
order_type: 'SCRK',
|
||
total_order_lines: groupedItems.length,
|
||
order_create_time: new Date(),
|
||
source_type: 'WMS',
|
||
order_status: 'PENDING',
|
||
sync_status: 'PENDING',
|
||
is_enabled: 1,
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
store_name: storeName,
|
||
warehouse_name: warehouseName,
|
||
remark: `收货单${receiving.receiving_number}快捷入库`,
|
||
expense_record: 0,
|
||
}, { transaction });
|
||
|
||
const entryOrderId = entryOrder.id;
|
||
|
||
// 创建入库单明细(按合并后的分组)
|
||
for (let i = 0; i < groupedItems.length; i++) {
|
||
const group = groupedItems[i];
|
||
const stockInfo = stockMap.get(group.system_product_id);
|
||
|
||
await ctx.model.EntryItems.create({
|
||
order_id: entryOrderId,
|
||
out_biz_code: '',
|
||
order_line_no: i + 1,
|
||
owner_code: '',
|
||
item_code: stockInfo ? stockInfo.item_code : '',
|
||
item_id: 0,
|
||
count: group.total_quantity,
|
||
inventory_type: 'ZP',
|
||
stock_id: group.system_product_id,
|
||
received_quantity: 0,
|
||
confirm_quantity: 0,
|
||
}, { transaction });
|
||
}
|
||
|
||
// ────────── 8. 写入 wms_entry_order_receiving 绑定关系 ──────────
|
||
await ctx.model.EntryOrderReceiving.create({
|
||
entry_order_id: entryOrderId,
|
||
receiving_id: receivingId,
|
||
}, { transaction });
|
||
|
||
// ────────── 9. 更新收货单主表 storage_status ──────────
|
||
// 快捷入库后收货单进入"等待入库"状态(后续可通过 matchPutaway 补全)
|
||
const [ affectedRows ] = await ctx.model.Receiving.update({
|
||
storage_status: 'waiting',
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: receivingId, storage_status: 'none' },
|
||
transaction,
|
||
});
|
||
|
||
if (affectedRows === 0) {
|
||
await transaction.rollback();
|
||
return { code: 400, message: '收货单入库状态已变更,可能已被其他操作处理,禁止重复快捷入库', data: null };
|
||
}
|
||
|
||
// ────────── 10. 更新收货单明细的 storage_status 为 waiting,stored_quantity 为对应用量 ──────────
|
||
for (const group of groupedItems) {
|
||
for (const detailId of group.detail_ids) {
|
||
const detailRow = receivingDetails.find(d => d.id === detailId);
|
||
if (!detailRow) continue;
|
||
|
||
// 该明细的总量和已入库量
|
||
const detailTotalQty = Number(detailRow.actual_quantity) || 0;
|
||
// 该明细在本次合并中的贡献量按比例计入(简化:按该明细数量在合并总量中的占比)
|
||
const detailRatio = group.total_quantity > 0 ? detailTotalQty / group.total_quantity : 0;
|
||
const thisStoredQty = Math.round(detailRatio * group.total_quantity);
|
||
|
||
const newStoredQty = Math.min(detailTotalQty, (Number(detailRow.stored_quantity) || 0) + thisStoredQty);
|
||
// 明细实际数量表示的是该明细的收货量,合并后该 SKU 的明细可能有多条
|
||
// 简化:如果该明细被完全用完则设为 all,否则 waiting(等待手工上架)
|
||
const newStorageStatus = newStoredQty >= detailTotalQty ? 'all' : 'waiting';
|
||
|
||
await ctx.model.ReceivingDetail.update({
|
||
storage_status: newStorageStatus,
|
||
stored_quantity: newStoredQty,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: detailId },
|
||
transaction,
|
||
});
|
||
}
|
||
}
|
||
|
||
// ────────── 11. 操作日志 ──────────
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'entry_order',
|
||
businessId: entryOrderId,
|
||
operationCode: 'ENTRY_ORDER_QUICK_PUTAWAY',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
storeId,
|
||
receivingId,
|
||
entryOrderCode,
|
||
receivingNumber: receiving.receiving_number,
|
||
totalLines: groupedItems.length,
|
||
},
|
||
transaction,
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[inventory.quickPutaway] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
// ────────── 12. 提交事务 ──────────
|
||
await transaction.commit();
|
||
|
||
ctx.logger.info(`[inventory.quickPutaway] 快捷入库完成 entryOrderId=${entryOrderId} receivingId=${receivingId} lines=${groupedItems.length}`);
|
||
|
||
return {
|
||
code: 200,
|
||
message: '快捷入库成功',
|
||
data: {
|
||
entry_order_id: entryOrderId,
|
||
entry_order_code: entryOrderCode,
|
||
order_status: 'PENDING',
|
||
receiving_id: receivingId,
|
||
total_lines: groupedItems.length,
|
||
total_quantity: groupedItems.reduce((sum, g) => sum + g.total_quantity, 0),
|
||
},
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
ctx.logger.error(`[inventory.quickPutaway] 快捷入库异常 receivingId=${receivingId}: ${error.message}`, error.stack);
|
||
return { code: 500, message: `系统异常: ${error.message}`, data: null };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 导出库存列表(异步任务内部调用,生成 Excel 并上传)。
|
||
*
|
||
* where 条件通过 ctx.whereParsed 读取(与 getInventoryList 完全一致),
|
||
* 调用方需先执行 prepareWhereContext 设置 ctx.whereParsed。
|
||
*
|
||
* 支持两种导出模式:
|
||
* - stock_location:按 stock_id + space_id(库位)聚合,汇总数量
|
||
* - storage:按 storage_id 逐条导出明细
|
||
*
|
||
* @param {Object} sortParams 排序参数 { sortField, sortOrder }
|
||
* @param {boolean} groupByBatch 是否按批次导出(false=聚合,true=逐条明细)
|
||
* @return {Promise<Object>} 导出上传结果(含 url/fileKey 等)
|
||
*/
|
||
async exportInventoryList(sortParams = {}, groupByBatch = false) {
|
||
const { ctx, app } = this;
|
||
const { Op, fn, col, literal } = app.Sequelize;
|
||
const warehouseId = ctx.user.store_id;
|
||
const { sortField = 'id', sortOrder = 'DESC' } = sortParams;
|
||
const pageSize = 500;
|
||
let page = 1;
|
||
let hasNext = true;
|
||
const rows = [];
|
||
|
||
// 构建基础 where 条件(与 getInventoryList 完全一致)
|
||
const baseWhere = {
|
||
[Op.and]: [
|
||
{ warehouse_id: warehouseId },
|
||
{ is_enabled: 1 },
|
||
{ delete_at: null },
|
||
],
|
||
};
|
||
|
||
// 动态 where 条件(与 getInventoryList 一致:从 ctx.whereParsed 读取)
|
||
const parsed = ctx.whereParsed;
|
||
if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) {
|
||
baseWhere[Op.and].push(...parsed.dynamicConditions);
|
||
}
|
||
|
||
if (groupByBatch) {
|
||
// ────── group_by_batch=true:按 storage_id 逐条导出明细 ──────
|
||
while (hasNext) {
|
||
const { rows: pageRows } = await ctx.model.Storage.findAndCountAll({
|
||
where: baseWhere,
|
||
attributes: [
|
||
'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type',
|
||
'quantity', 'locked_quantity', 'available_quantity',
|
||
'production_date', 'expiry_date', 'inbound_time', 'inbound_order_no',
|
||
'supplier_batch_no', 'store_id', 'warehouse_id',
|
||
'created_at', 'updated_at',
|
||
],
|
||
order: [[ sortField, sortOrder ]],
|
||
offset: (page - 1) * pageSize,
|
||
limit: pageSize,
|
||
include: [
|
||
{
|
||
model: ctx.model.StockWarehouse,
|
||
as: 'stock',
|
||
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
|
||
required: false,
|
||
},
|
||
{
|
||
model: ctx.model.LocationSpace,
|
||
as: 'space',
|
||
attributes: [ 'id', 'space_code', 'custom_name' ],
|
||
required: false,
|
||
},
|
||
],
|
||
raw: true,
|
||
nest: true,
|
||
});
|
||
|
||
if (pageRows.length === 0) {
|
||
hasNext = false;
|
||
break;
|
||
}
|
||
|
||
// 收集 store_id 批量查询货主名称
|
||
const storeIds = [ ...new Set(pageRows.map(r => Number(r.store_id)).filter(Boolean)) ];
|
||
const storeMap = new Map();
|
||
if (storeIds.length > 0) {
|
||
try {
|
||
const storeRows = await ctx.model.StoreWarehouse.findAll({
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
where: { store_id: { [Op.in]: storeIds }, warehouse_id: warehouseId },
|
||
raw: true,
|
||
});
|
||
for (const sr of storeRows) {
|
||
storeMap.set(Number(sr.store_id), sr.store_remask || '');
|
||
}
|
||
} catch (_e) { /* ignore */ }
|
||
}
|
||
|
||
for (const row of pageRows) {
|
||
rows.push({
|
||
storage_id: row.id,
|
||
stock_id: row.stock_id,
|
||
item_code: row.stock?.item_code || '',
|
||
item_name: row.stock?.item_name || '',
|
||
sku_property: row.stock?.sku_property || '',
|
||
stock_unit: row.stock?.stock_unit || '',
|
||
store_name: storeMap.get(Number(row.store_id)) || '',
|
||
space_code: row.space?.space_code || '',
|
||
space_name: row.space?.custom_name || '',
|
||
batch_no: row.batch_no || '',
|
||
inventory_type: row.inventory_type || '',
|
||
quantity: row.quantity,
|
||
locked_quantity: row.locked_quantity,
|
||
available_quantity: row.available_quantity,
|
||
production_date: row.production_date ? app.formatDate(row.production_date) : '',
|
||
expiry_date: row.expiry_date ? app.formatDate(row.expiry_date) : '',
|
||
inbound_time: row.inbound_time ? app.formatDate(row.inbound_time) : '',
|
||
inbound_order_no: row.inbound_order_no || '',
|
||
supplier_batch_no: row.supplier_batch_no || '',
|
||
created_at: row.created_at ? app.formatDate(row.created_at) : '',
|
||
updated_at: row.updated_at ? app.formatDate(row.updated_at) : '',
|
||
});
|
||
}
|
||
|
||
hasNext = pageRows.length >= pageSize;
|
||
page += 1;
|
||
}
|
||
} else {
|
||
// ────── group_by_batch=false(默认):按 stock_id + space_id 聚合 ──────
|
||
const groupFields = [ 'stock_id', 'space_id' ];
|
||
|
||
while (hasNext) {
|
||
const pageRows = await ctx.model.Storage.findAll({
|
||
where: baseWhere,
|
||
attributes: [
|
||
'stock_id',
|
||
'space_id',
|
||
[ fn('MIN', col('wms_storage.store_id')), 'store_id' ],
|
||
[ fn('SUM', col('wms_storage.quantity')), 'quantity' ],
|
||
[ fn('SUM', col('wms_storage.locked_quantity')), 'locked_quantity' ],
|
||
[ fn('SUM', col('wms_storage.available_quantity')), 'available_quantity' ],
|
||
[ fn('COUNT', col('wms_storage.id')), 'batch_count' ],
|
||
[ fn('MAX', col('wms_storage.inbound_time')), 'last_inbound_time' ],
|
||
[ fn('MIN', col('wms_storage.created_at')), 'first_created_at' ],
|
||
[ fn('MAX', col('wms_storage.updated_at')), 'last_updated_at' ],
|
||
],
|
||
group: groupFields,
|
||
order: [[ literal('last_inbound_time'), sortOrder ]],
|
||
offset: (page - 1) * pageSize,
|
||
limit: pageSize,
|
||
include: [
|
||
{
|
||
model: ctx.model.StockWarehouse,
|
||
as: 'stock',
|
||
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
|
||
required: false,
|
||
},
|
||
{
|
||
model: ctx.model.LocationSpace,
|
||
as: 'space',
|
||
attributes: [ 'id', 'space_code', 'custom_name' ],
|
||
required: false,
|
||
},
|
||
],
|
||
raw: true,
|
||
nest: true,
|
||
});
|
||
|
||
if (pageRows.length === 0) {
|
||
hasNext = false;
|
||
break;
|
||
}
|
||
|
||
// 收集 store_id 批量查询货主名称
|
||
const storeIds = [ ...new Set(pageRows.map(r => Number(r.store_id)).filter(Boolean)) ];
|
||
const storeMap = new Map();
|
||
if (storeIds.length > 0) {
|
||
try {
|
||
const storeRows = await ctx.model.StoreWarehouse.findAll({
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
where: { store_id: { [Op.in]: storeIds }, warehouse_id: warehouseId },
|
||
raw: true,
|
||
});
|
||
for (const sr of storeRows) {
|
||
storeMap.set(Number(sr.store_id), sr.store_remask || '');
|
||
}
|
||
} catch (_e) { /* ignore */ }
|
||
}
|
||
|
||
for (const row of pageRows) {
|
||
rows.push({
|
||
stock_id: row.stock_id,
|
||
space_id: row.space_id,
|
||
item_code: row.stock?.item_code || '',
|
||
item_name: row.stock?.item_name || '',
|
||
sku_property: row.stock?.sku_property || '',
|
||
stock_unit: row.stock?.stock_unit || '',
|
||
store_name: storeMap.get(Number(row.store_id)) || '',
|
||
space_code: row.space?.space_code || '',
|
||
space_name: row.space?.custom_name || '',
|
||
quantity: row.quantity,
|
||
locked_quantity: row.locked_quantity,
|
||
available_quantity: row.available_quantity,
|
||
batch_count: row.batch_count,
|
||
last_inbound_time: row.last_inbound_time ? app.formatDate(row.last_inbound_time) : '',
|
||
created_at: row.first_created_at ? app.formatDate(row.first_created_at) : '',
|
||
updated_at: row.last_updated_at ? app.formatDate(row.last_updated_at) : '',
|
||
});
|
||
}
|
||
|
||
hasNext = pageRows.length >= pageSize;
|
||
page += 1;
|
||
}
|
||
}
|
||
|
||
// ── 批量填充商品条码和图片(复用 loadStockAttachments 缓存查询)──
|
||
if (rows.length > 0) {
|
||
const stockIds = [ ...new Set(
|
||
rows.map(r => Number(r.stock_id || 0)).filter(Boolean)
|
||
) ];
|
||
const { barcodesByStockId, imagesByStockId } = await loadStockAttachments(ctx, stockIds);
|
||
|
||
for (const row of rows) {
|
||
const sid = Number(row.stock_id || 0);
|
||
row.barcodes = sid ? (barcodesByStockId.get(sid) || []).join(', ') : '';
|
||
row.image_url = sid ? ((imagesByStockId.get(sid) || [])[0] || '') : '';
|
||
}
|
||
}
|
||
|
||
// 生成 Excel
|
||
const now = new Date();
|
||
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`;
|
||
|
||
const modeLabel = groupByBatch ? '库存明细' : '库存汇总';
|
||
const sheetName = groupByBatch ? '库存明细' : '库存汇总(按商品+库位)';
|
||
|
||
const columns = groupByBatch
|
||
? [
|
||
{ header: '库存记录ID', key: 'storage_id' },
|
||
{ header: '商品编码', key: 'item_code' },
|
||
{ header: '商品名称', key: 'item_name' },
|
||
{ header: '规格', key: 'sku_property' },
|
||
{ header: '库存单位', key: 'stock_unit' },
|
||
{ header: '货主', key: 'store_name' },
|
||
{ header: '库位编码', key: 'space_code' },
|
||
{ header: '库位名称', key: 'space_name' },
|
||
{ header: '条码', key: 'barcodes' },
|
||
{ header: '图片', key: 'image_url' },
|
||
{ header: '批次号', key: 'batch_no' },
|
||
{ header: '库存类型', key: 'inventory_type' },
|
||
{ header: '数量', key: 'quantity' },
|
||
{ header: '锁定数量', key: 'locked_quantity' },
|
||
{ header: '可用数量', key: 'available_quantity' },
|
||
{ header: '生产日期', key: 'production_date' },
|
||
{ header: '过期日期', key: 'expiry_date' },
|
||
{ header: '入库时间', key: 'inbound_time' },
|
||
{ header: '入库单号', key: 'inbound_order_no' },
|
||
{ header: '供应商批次号', key: 'supplier_batch_no' },
|
||
{ header: '创建时间', key: 'created_at' },
|
||
{ header: '更新时间', key: 'updated_at' },
|
||
]
|
||
: [
|
||
{ header: '商品编码', key: 'item_code' },
|
||
{ header: '商品名称', key: 'item_name' },
|
||
{ header: '规格', key: 'sku_property' },
|
||
{ header: '库存单位', key: 'stock_unit' },
|
||
{ header: '货主', key: 'store_name' },
|
||
{ header: '条码', key: 'barcodes' },
|
||
{ header: '图片', key: 'image_url' },
|
||
{ header: '库位编码', key: 'space_code' },
|
||
{ header: '库位名称', key: 'space_name' },
|
||
{ header: '总库存', key: 'quantity' },
|
||
{ header: '锁定库存', key: 'locked_quantity' },
|
||
{ header: '可用库存', key: 'available_quantity' },
|
||
{ header: '批次数', key: 'batch_count' },
|
||
{ header: '最近入库时间', key: 'last_inbound_time' },
|
||
{ header: '创建时间', key: 'created_at' },
|
||
{ header: '更新时间', key: 'updated_at' },
|
||
];
|
||
|
||
return await ctx.service.systems.excel.generateAndUpload({
|
||
filename: `${modeLabel}导出_${dateToken}.xlsx`,
|
||
dir: `exports/storage/inventory/${warehouseId}`,
|
||
category: 'document',
|
||
sheets: [{
|
||
name: sheetName,
|
||
columns,
|
||
rows,
|
||
}],
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 生成入库单号。
|
||
* 格式:SCRK + 年月日 + 4位流水号
|
||
*
|
||
* @param {number} warehouseId 仓库ID
|
||
* @param {number} storeId 货主ID
|
||
* @param {Object} transaction 数据库事务
|
||
* @return {Promise<string>} 生成的入库单号
|
||
*/
|
||
async _generateEntryOrderCode(warehouseId, storeId, transaction) {
|
||
const { ctx, app } = this;
|
||
const now = new Date();
|
||
const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
|
||
const prefix = `SCRK${dateStr}`;
|
||
|
||
// 查询当天该仓库下已有的最大入库单号(全局唯一,不区分货主,避免多货主场景下重复)
|
||
const lastOrder = await ctx.model.EntryOrder.findOne({
|
||
where: {
|
||
entry_order_code: { [app.Sequelize.Op.like]: `${prefix}%` },
|
||
warehouse_id: warehouseId,
|
||
},
|
||
order: [[ 'entry_order_code', 'DESC' ]],
|
||
attributes: [ 'entry_order_code' ],
|
||
transaction,
|
||
raw: true,
|
||
paranoid: false,
|
||
lock: transaction.LOCK.UPDATE,
|
||
});
|
||
|
||
let seq = 1;
|
||
if (lastOrder && lastOrder.entry_order_code) {
|
||
const seqPart = lastOrder.entry_order_code.slice(prefix.length);
|
||
const seqNum = parseInt(seqPart, 10);
|
||
if (!Number.isNaN(seqNum)) {
|
||
seq = seqNum + 1;
|
||
}
|
||
}
|
||
|
||
return `${prefix}${String(seq).padStart(4, '0')}`;
|
||
}
|
||
}
|
||
|
||
module.exports = InventoryService;
|