- systems/storage/inventory.js 新增 updateExpiry:校验 storage_id 为正整数、两个 日期至少传一个、当前仓库上下文(ctx.user.store_id);单事务 + 行锁 (SELECT ... FOR UPDATE)按 id + warehouse_id + is_enabled=1 + delete_at IS NULL 定位库存记录,跨仓库按 404 处理 - 新增模块级 helper parseStorageDateInput:undefined 视为未传、null/空串清空, YYYY-MM-DD / YYYY/MM/DD / YYYY-MM-DD HH:mm:ss / ISO / Date 统一规范化为 YYYY-MM-DD 并校验日期真实存在,其它判非法 - 合并后(未传字段取库内现值)生产日期不能晚于到期日期;两值均与库内一致返回 changed=false,不写库、不记日志 - 成功路径写业务操作日志(operation_code=STORAGE_UPDATE_EXPIRY,记维护前后两个 日期与 storage/space/stock/batch 快照) - systemMethods/storage/inventory.js 新增方法层包装(透传 code/message/data); businessDict 新增 STORAGE_UPDATE_EXPIRY 操作码
3265 lines
124 KiB
JavaScript
3265 lines
124 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||
|
||
/**
|
||
* 库存明细(逐条)模式允许的排序字段白名单(wms_storage 真实列),
|
||
* 防止非法字段进入 ORDER BY 导致 SQL 报错或注入。
|
||
*/
|
||
const STORAGE_BATCH_SORT_FIELD_WHITELIST = new Set([
|
||
'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type',
|
||
'quantity', 'locked_quantity', 'available_quantity',
|
||
'production_date', 'expiry_date', 'inbound_time',
|
||
'created_at', 'updated_at',
|
||
]);
|
||
|
||
/**
|
||
* 库存汇总(按 stock_id 合并)模式允许的排序字段 → 聚合别名映射。
|
||
* 汇总查询中 quantity/locked_quantity/available_quantity 等为 SUM/MIN/MAX 别名,
|
||
* MySQL 支持 ORDER BY 别名,因此直接按别名排序。
|
||
*/
|
||
const STORAGE_AGGREGATE_ORDER_FIELD_MAP = {
|
||
quantity: 'quantity',
|
||
locked_quantity: 'locked_quantity',
|
||
available_quantity: 'available_quantity',
|
||
batch_count: 'batch_count',
|
||
first_inbound_time: 'first_inbound_time',
|
||
last_inbound_time: 'last_inbound_time',
|
||
production_date: 'production_date',
|
||
expiry_date: 'expiry_date',
|
||
};
|
||
|
||
/**
|
||
* 计算库存批次的保质期预警状态。
|
||
*
|
||
* @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) || [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 解析并规范化库存效期维护入参中的日期值(统一输出 'YYYY-MM-DD')。
|
||
*
|
||
* 规则:
|
||
* - `undefined`:未传该字段(不更新,返回 provided=false);
|
||
* - `null` / 空串:清空该字段(provided=true 且 value=null);
|
||
* - `'YYYY-MM-DD'` / `'YYYY/MM/DD'` / `'YYYY-MM-DD HH:mm:ss'` / ISO 字符串 / Date:
|
||
* 仅取日期部分并校验为真实存在的日期,规范化为 'YYYY-MM-DD';
|
||
* - 其它:视为非法(invalid=true),由调用方返回参数错误。
|
||
*
|
||
* @param {unknown} value 待解析的日期值
|
||
* @return {{provided: boolean, value: (string|null), invalid: boolean}} 解析结果
|
||
*/
|
||
function parseStorageDateInput(value) {
|
||
if (value === undefined) {
|
||
return { provided: false, value: null, invalid: false };
|
||
}
|
||
|
||
if (value === null || (typeof value === 'string' && value.trim() === '')) {
|
||
return { provided: true, value: null, invalid: false };
|
||
}
|
||
|
||
let year;
|
||
let month;
|
||
let day;
|
||
|
||
if (value instanceof Date) {
|
||
if (Number.isNaN(value.getTime())) {
|
||
return { provided: true, value: null, invalid: true };
|
||
}
|
||
year = value.getFullYear();
|
||
month = value.getMonth() + 1;
|
||
day = value.getDate();
|
||
} else {
|
||
const matched = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})([T\s].*)?$/.exec(String(value).trim());
|
||
if (!matched) {
|
||
return { provided: true, value: null, invalid: true };
|
||
}
|
||
year = Number(matched[1]);
|
||
month = Number(matched[2]);
|
||
day = Number(matched[3]);
|
||
}
|
||
|
||
const parsed = new Date(year, month - 1, day);
|
||
const isValidDate = parsed.getFullYear() === year
|
||
&& parsed.getMonth() === month - 1
|
||
&& parsed.getDate() === day;
|
||
|
||
if (!isValidDate || year < 1900 || year > 2999) {
|
||
return { provided: true, value: null, invalid: true };
|
||
}
|
||
|
||
return {
|
||
provided: true,
|
||
value: `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`,
|
||
invalid: false,
|
||
};
|
||
}
|
||
|
||
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;
|
||
// 拦截锁定快照:wms_stock_warehouse 层无该字段,取源库位行值(移库不动拦截锁,before=after)
|
||
const sourceInterceptLockedQuantity = Number(data.srcRecord?.intercept_locked_quantity) || 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,
|
||
before_intercept_locked_quantity: sourceInterceptLockedQuantity,
|
||
after_intercept_locked_quantity: sourceInterceptLockedQuantity,
|
||
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,
|
||
before_intercept_locked_quantity: sourceInterceptLockedQuantity,
|
||
after_intercept_locked_quantity: sourceInterceptLockedQuantity,
|
||
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;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 维护当前库存的生产日期与到期日期(wms_storage.production_date / expiry_date)。
|
||
*
|
||
* 口径说明:
|
||
* 1) 按库存记录维度维护(单条 storage_id),仓库上下文来自当前登录用户(ctx.user.store_id),
|
||
* 跨仓库的 storage_id 一律按「不存在」处理;
|
||
* 2) 两个日期字段至少传一个;未传的字段保持库内原值;传 null 或空串表示清空该字段;
|
||
* 3) 日期支持 'YYYY-MM-DD' / 'YYYY/MM/DD' / 'YYYY-MM-DD HH:mm:ss' / ISO 字符串,
|
||
* 内部统一按 'YYYY-MM-DD' 落库;
|
||
* 4) 校验合并后的生产日期不得晚于到期日期(未传字段取库内现值参与比较);
|
||
* 5) 更新前后完全一致时直接返回 changed=false,不写库、不记日志。
|
||
*
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.storage_id 库存记录ID(wms_storage.id,必填)
|
||
* @param {string|Date|null} [data.production_date] 生产日期(传 null/空串表示清空)
|
||
* @param {string|Date|null} [data.expiry_date] 到期日期(传 null/空串表示清空)
|
||
* @return {Promise<{code: number, message: string, data: (Object|null)}>} 统一 code/message/data 结构
|
||
*/
|
||
async updateExpiry(data = {}) {
|
||
const { ctx } = this;
|
||
const requestData = data && typeof data === 'object' ? data : {};
|
||
|
||
// ────────── 1. 参数校验 ──────────
|
||
const storageId = Number(requestData.storage_id || 0);
|
||
if (!Number.isInteger(storageId) || storageId <= 0) {
|
||
return { code: 400, message: 'storage_id 必填且必须为正整数', data: null };
|
||
}
|
||
|
||
const productionDateInput = parseStorageDateInput(requestData.production_date);
|
||
const expiryDateInput = parseStorageDateInput(requestData.expiry_date);
|
||
|
||
if (productionDateInput.invalid) {
|
||
return { code: 400, message: 'production_date 格式非法,须为 YYYY-MM-DD', data: null };
|
||
}
|
||
|
||
if (expiryDateInput.invalid) {
|
||
return { code: 400, message: 'expiry_date 格式非法,须为 YYYY-MM-DD', data: null };
|
||
}
|
||
|
||
if (!productionDateInput.provided && !expiryDateInput.provided) {
|
||
return { code: 400, message: 'production_date 与 expiry_date 至少传入一个', data: null };
|
||
}
|
||
|
||
const warehouseId = Number(ctx.user && (ctx.user.store_id ?? ctx.user.warehouse_id)) || 0;
|
||
if (warehouseId <= 0) {
|
||
return { code: 400, message: '无法获取当前仓库信息', data: null };
|
||
}
|
||
|
||
// ────────── 2. 事务内加锁维护 ──────────
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
const storageRecord = await ctx.model.Storage.findOne({
|
||
where: {
|
||
id: storageId,
|
||
warehouse_id: warehouseId,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
},
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
if (!storageRecord) {
|
||
await transaction.rollback();
|
||
return { code: 404, message: `库存记录不存在或无权访问: storage_id=${storageId}`, data: null };
|
||
}
|
||
|
||
const beforeProductionDate = parseStorageDateInput(storageRecord.production_date).value;
|
||
const beforeExpiryDate = parseStorageDateInput(storageRecord.expiry_date).value;
|
||
|
||
const nextProductionDate = productionDateInput.provided
|
||
? productionDateInput.value
|
||
: beforeProductionDate;
|
||
const nextExpiryDate = expiryDateInput.provided
|
||
? expiryDateInput.value
|
||
: beforeExpiryDate;
|
||
|
||
// 合并后校验:生产日期不能晚于到期日期
|
||
if (nextProductionDate && nextExpiryDate && nextProductionDate > nextExpiryDate) {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 400,
|
||
message: `生产日期(${nextProductionDate})不能晚于到期日期(${nextExpiryDate})`,
|
||
data: null,
|
||
};
|
||
}
|
||
|
||
const baseData = {
|
||
storage_id: storageId,
|
||
warehouse_id: warehouseId,
|
||
store_id: storageRecord.store_id,
|
||
space_id: storageRecord.space_id,
|
||
stock_id: storageRecord.stock_id,
|
||
batch_no: storageRecord.batch_no,
|
||
};
|
||
|
||
if (nextProductionDate === beforeProductionDate && nextExpiryDate === beforeExpiryDate) {
|
||
await transaction.rollback();
|
||
return {
|
||
code: 200,
|
||
message: '生产日期与到期日期均无变化,未做修改',
|
||
data: {
|
||
...baseData,
|
||
production_date: beforeProductionDate,
|
||
expiry_date: beforeExpiryDate,
|
||
changed: false,
|
||
},
|
||
};
|
||
}
|
||
|
||
await ctx.model.Storage.update({
|
||
production_date: nextProductionDate,
|
||
expiry_date: nextExpiryDate,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: storageId },
|
||
transaction,
|
||
});
|
||
|
||
const changeSummary = [];
|
||
if (nextProductionDate !== beforeProductionDate) {
|
||
changeSummary.push(`生产日期 ${beforeProductionDate || '空'} → ${nextProductionDate || '空'}`);
|
||
}
|
||
if (nextExpiryDate !== beforeExpiryDate) {
|
||
changeSummary.push(`到期日期 ${beforeExpiryDate || '空'} → ${nextExpiryDate || '空'}`);
|
||
}
|
||
|
||
// ────────── 3. 记录操作日志(失败仅告警,不影响主流程) ──────────
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'storage',
|
||
businessId: storageId,
|
||
operationCode: 'STORAGE_UPDATE_EXPIRY',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
message: changeSummary.join(';'),
|
||
},
|
||
beforeChanges: {
|
||
...baseData,
|
||
production_date: beforeProductionDate,
|
||
expiry_date: beforeExpiryDate,
|
||
},
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[inventory.updateExpiry] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
await transaction.commit();
|
||
|
||
ctx.logger.info('[inventory.updateExpiry] 库存效期维护完成', {
|
||
warehouse_id: warehouseId,
|
||
storage_id: storageId,
|
||
production_date: nextProductionDate,
|
||
expiry_date: nextExpiryDate,
|
||
});
|
||
|
||
return {
|
||
code: 200,
|
||
message: '更新成功',
|
||
data: {
|
||
...baseData,
|
||
production_date: nextProductionDate,
|
||
expiry_date: nextExpiryDate,
|
||
before_production_date: beforeProductionDate,
|
||
before_expiry_date: beforeExpiryDate,
|
||
changed: true,
|
||
},
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
ctx.logger.error('[inventory.updateExpiry] 库存效期维护异常', {
|
||
storage_id: storageId,
|
||
error: error.message,
|
||
stack: error.stack,
|
||
});
|
||
|
||
if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) {
|
||
return { code: 409, message: '库存记录被锁定,请稍后重试', data: null };
|
||
}
|
||
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 根据商品快捷搜索关键字解析匹配的 stock_id 列表(仓库维度)。
|
||
* 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、
|
||
* 条码(barcode)、SKU ID(纯数字时精确匹配)模糊匹配。
|
||
*
|
||
* @param {string} keyword 搜索关键字
|
||
* @param {number} warehouseId 仓库ID
|
||
* @return {Promise<number[]>} 匹配的 stock_id 列表
|
||
*/
|
||
async resolveStockQueryToStockIds(keyword = '', warehouseId) {
|
||
const { ctx, app } = this;
|
||
const normalizedKeyword = String(keyword || '').trim();
|
||
if (!normalizedKeyword || !warehouseId) {
|
||
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.warehouse_id = :warehouseId
|
||
AND (
|
||
sw.item_code LIKE :keyword
|
||
OR sw.item_name LIKE :keyword
|
||
OR sw.goods_code LIKE :keyword
|
||
${extraIdCondition}
|
||
)
|
||
`, {
|
||
replacements: { warehouseId, 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.warehouse_id = :warehouseId
|
||
WHERE sb.barcode LIKE :keyword
|
||
`, {
|
||
replacements: { warehouseId, 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 ];
|
||
}
|
||
|
||
/**
|
||
* 查询库存列表。
|
||
*
|
||
* 支持按批次明细或合并模式返回库存,并补充商品条码、图片附件、保质期预警和货主名称。
|
||
* 货主名称来源于货主签约表的 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'] 排序字段(明细模式支持 wms_storage 真实列;汇总模式仅支持 quantity/locked_quantity/available_quantity/batch_count/first_inbound_time/last_inbound_time/production_date/expiry_date,其余回退 last_inbound_time)
|
||
* @param {string} [sortParams.sortOrder='DESC'] 排序方向
|
||
* @param {boolean} [groupByBatch=false] 是否按批次明细返回
|
||
* @param {string|string[]} [stockQuery=''] 商品快捷搜索关键字(来自 where.stock_query,按商品编码/名称/货物编码/条码/SKU ID 模糊匹配,解析为 stock_id 过滤;支持数组,多关键字取并集)
|
||
* @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果
|
||
*/
|
||
async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false, stockQuery = '') {
|
||
const { ctx, app } = this;
|
||
const { Op, fn, col, literal } = app.Sequelize;
|
||
const nowMs = Date.now();
|
||
|
||
const warehouseId = ctx.user.store_id;
|
||
const page = Math.max(Number(pageParams.page || pageParams.currentPage || 1) || 1, 1);
|
||
const pageSize = Math.max(Number(pageParams.pageSize || 20) || 20, 1);
|
||
const sortField = sortParams.sortField || sortParams.sort_field || 'created_at';
|
||
const sortOrder = sortParams.sortOrder || sortParams.sort_order || 'DESC';
|
||
const safeSortOrder = String(sortOrder).toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||
// 明细模式按真实列排序;汇总模式按聚合别名排序(默认 last_inbound_time,与历史行为一致)
|
||
const batchSortField = STORAGE_BATCH_SORT_FIELD_WHITELIST.has(sortField) ? sortField : 'created_at';
|
||
const aggregateOrderField = STORAGE_AGGREGATE_ORDER_FIELD_MAP[sortField] || 'last_inbound_time';
|
||
|
||
// 基础条件
|
||
const baseWhere = {
|
||
[Op.and]: [
|
||
{ warehouse_id: warehouseId },
|
||
{ is_enabled: 1 },
|
||
{ delete_at: null },
|
||
// 仅返回有量库存:明细模式过滤 quantity=0 的行,汇总模式过滤总量为 0 的商品
|
||
{ quantity: { [Op.gt]: 0 } },
|
||
],
|
||
};
|
||
|
||
// 动态 where 条件
|
||
const parsed = ctx.whereParsed;
|
||
if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) {
|
||
baseWhere[Op.and].push(...parsed.dynamicConditions);
|
||
}
|
||
|
||
// stock_query 快捷搜索:按商品编码/名称/货物编码/条码/SKU ID 解析为 stock_id IN 条件
|
||
// 兼容单关键字(字符串)与多关键字(数组):多关键字逐项解析后取 stock_id 并集
|
||
const stockQueryKeywords = (Array.isArray(stockQuery) ? stockQuery : [ stockQuery ])
|
||
.map(keyword => String(keyword || '').trim())
|
||
.filter(Boolean);
|
||
if (stockQueryKeywords.length > 0) {
|
||
const stockIdSet = new Set();
|
||
for (const keyword of stockQueryKeywords) {
|
||
const matchedStockIds = await this.resolveStockQueryToStockIds(keyword, warehouseId);
|
||
for (const stockId of matchedStockIds) {
|
||
stockIdSet.add(stockId);
|
||
}
|
||
}
|
||
if (stockIdSet.size > 0) {
|
||
baseWhere[Op.and].push({ stock_id: { [Op.in]: [ ...stockIdSet ] } });
|
||
} else {
|
||
// stock_query 无匹配结果,直接返回空列表
|
||
return {
|
||
list: [],
|
||
pagination: {
|
||
page,
|
||
pageSize,
|
||
total: 0,
|
||
totalPages: 0,
|
||
},
|
||
};
|
||
}
|
||
}
|
||
|
||
const offset = (page - 1) * pageSize;
|
||
const limit = pageSize;
|
||
|
||
if (groupByBatch) {
|
||
const inventoryWarningRanges = await this._loadInventoryWarningRanges(warehouseId, 'getInventoryList');
|
||
|
||
// 按批次明细:逐条返回
|
||
const { count: total, rows } = await ctx.model.Storage.findAndCountAll({
|
||
where: baseWhere,
|
||
order: [[ batchSortField, safeSortOrder ]],
|
||
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: [
|
||
ctx.model.StoreWarehouse.buildStoreStockInclude({
|
||
warehouseId,
|
||
required: false,
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
}),
|
||
],
|
||
required: false,
|
||
},
|
||
{
|
||
model: ctx.model.LocationSpace,
|
||
as: 'space',
|
||
attributes: [ 'id', 'space_code', 'custom_name' ],
|
||
required: false,
|
||
},
|
||
],
|
||
});
|
||
|
||
const list = this._formatBatchStorageRows(rows, inventoryWarningRanges, nowMs);
|
||
|
||
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(aggregateOrderField), safeSortOrder ]],
|
||
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: [
|
||
ctx.model.StoreWarehouse.buildStoreStockInclude({
|
||
warehouseId,
|
||
required: false,
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
}),
|
||
],
|
||
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 下所有数量大于 1 的 storage 行。
|
||
* 支持两种模式:
|
||
* - group_by_space=false(默认,不汇总):逐条返回明细,结构与 storage.inventory.list
|
||
* 明细模式一致(含批次/效期/库存预警字段);
|
||
* - group_by_space=true(按库位汇总):先筛 quantity > 1 的明细行,再按 space_id
|
||
* 汇总数量(quantity/locked_quantity/available_quantity),返回行含库位/商品信息,
|
||
* 不包含批次与效期/预警字段。
|
||
*
|
||
* @param {number} stockId 商品SKU ID(wms_stock_warehouse.id,必填)
|
||
* @param {boolean} [groupBySpace=false] 是否按库位汇总
|
||
* @return {Promise<Object>} code/message/data 结构,data 中为 { list: [...] }
|
||
*/
|
||
async getStorageListByStockId(stockId, groupBySpace = false) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
|
||
// ────────── 1. 参数校验 ──────────
|
||
const normalizedStockId = Number(stockId);
|
||
if (!Number.isInteger(normalizedStockId) || normalizedStockId <= 0) {
|
||
return { code: 400, message: 'stock_id 必填且必须为正整数', data: null };
|
||
}
|
||
|
||
const warehouseId = ctx.user && ctx.user.store_id;
|
||
if (!warehouseId) {
|
||
return { code: 400, message: '无法获取当前仓库信息', data: null };
|
||
}
|
||
|
||
// ────────── 2. 先筛 quantity > 1 的库存明细(两种模式共用同一查询) ──────────
|
||
const nowMs = Date.now();
|
||
const inventoryWarningRanges = await this._loadInventoryWarningRanges(warehouseId, 'getStorageListByStockId');
|
||
|
||
const rows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
stock_id: normalizedStockId,
|
||
quantity: { [Op.gt]: 1 },
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
},
|
||
order: [[ 'id', 'DESC' ]],
|
||
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: [
|
||
ctx.model.StoreWarehouse.buildStoreStockInclude({
|
||
warehouseId,
|
||
required: false,
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
}),
|
||
],
|
||
required: false,
|
||
},
|
||
{
|
||
model: ctx.model.LocationSpace,
|
||
as: 'space',
|
||
attributes: [ 'id', 'space_code', 'custom_name' ],
|
||
required: false,
|
||
},
|
||
],
|
||
});
|
||
|
||
// ────────── 3. 按模式格式化返回 ──────────
|
||
if (groupBySpace) {
|
||
// 按库位汇总:汇总数量,不返回批次/效期/预警字段
|
||
const list = this._aggregateStorageRowsBySpace(rows);
|
||
await enrichInventoryStockAttachments(ctx, list);
|
||
return { code: 200, message: 'ok', data: { list } };
|
||
}
|
||
|
||
// 不汇总:逐条明细(含效期/库存预警字段)
|
||
const list = this._formatBatchStorageRows(rows, inventoryWarningRanges, nowMs);
|
||
await enrichInventoryStockAttachments(ctx, list);
|
||
|
||
return {
|
||
code: 200,
|
||
message: 'ok',
|
||
data: { list },
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按库位查询库存商品列表:传入 space_id,先判断该库位是否为当前仓库的库位,
|
||
* 是则返回该库位下有量库存(quantity > 0)的商品列表,按商品(stock_id)汇总为一条。
|
||
* 商品信息统一走 stock_warehouse 通用链路(getStockDetails),返回 stock_warehouse 通用属性
|
||
* (item_code/item_name/sku_property/stock_unit/is_batch_mgmt/is_shelf_life_mgmt/
|
||
* packing_requirements/need_recheck/barcodes/image_url 等)。
|
||
*
|
||
* @param {number} spaceId 库位ID(wms_location_space.id,必填)
|
||
* @return {Promise<Object>} code/message/data 结构,data 为 { space, list }
|
||
*/
|
||
async getStorageListBySpaceId(spaceId) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
|
||
// ────────── 1. 参数校验 ──────────
|
||
const normalizedSpaceId = Number(spaceId);
|
||
if (!Number.isInteger(normalizedSpaceId) || normalizedSpaceId <= 0) {
|
||
return { code: 400, message: 'space_id 必填且必须为正整数', data: null };
|
||
}
|
||
|
||
const warehouseId = ctx.user && ctx.user.store_id;
|
||
if (!warehouseId) {
|
||
return { code: 400, message: '无法获取当前仓库信息', data: null };
|
||
}
|
||
|
||
// ────────── 2. 判断该库位是否属于当前仓库 ──────────
|
||
const space = await ctx.model.LocationSpace.findOne({
|
||
where: {
|
||
id: normalizedSpaceId,
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
},
|
||
attributes: [ 'id', 'warehouse_id', 'space_code', 'custom_name', 'space_status' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!space) {
|
||
// 区分「库位不存在」与「库位存在但不属于当前仓库」
|
||
const spaceInOtherWarehouse = await ctx.model.LocationSpace.findOne({
|
||
where: { id: normalizedSpaceId, deleted_at: null },
|
||
attributes: [ 'id', 'warehouse_id' ],
|
||
raw: true,
|
||
});
|
||
if (spaceInOtherWarehouse) {
|
||
return { code: 400, message: `库位 ${normalizedSpaceId} 不属于当前仓库`, data: null };
|
||
}
|
||
return { code: 404, message: `库位不存在: space_id=${normalizedSpaceId}`, data: null };
|
||
}
|
||
|
||
const spaceInfo = {
|
||
id: Number(space.id),
|
||
warehouse_id: Number(space.warehouse_id),
|
||
space_code: space.space_code || '',
|
||
custom_name: space.custom_name || '',
|
||
space_status: space.space_status || '',
|
||
};
|
||
|
||
// ────────── 3. 查询该库位下有量库存明细(quantity > 0) ──────────
|
||
const rows = await ctx.model.Storage.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
space_id: normalizedSpaceId,
|
||
quantity: { [Op.gt]: 0 },
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
},
|
||
attributes: [
|
||
'id', 'warehouse_id', 'store_id', 'space_id', 'stock_id',
|
||
'batch_no', 'inventory_type', 'quantity', 'locked_quantity',
|
||
'intercept_locked_quantity', 'available_quantity',
|
||
'production_date', 'expiry_date', 'inbound_time',
|
||
],
|
||
order: [[ 'id', 'DESC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
if (!rows.length) {
|
||
return { code: 200, message: 'ok', data: { space: spaceInfo, list: [] } };
|
||
}
|
||
|
||
// ────────── 4. 商品通用属性:统一走 stock_warehouse 通用链路(getStockDetails) ──────────
|
||
const stockIds = [ ...new Set(rows.map(row => Number(row.stock_id)).filter(Boolean)) ];
|
||
const stockDetailMap = new Map();
|
||
try {
|
||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId });
|
||
for (const detail of (Array.isArray(stockDetails) ? stockDetails : [])) {
|
||
stockDetailMap.set(Number(detail && detail.id || 0), detail);
|
||
}
|
||
} catch (error) {
|
||
ctx.logger?.warn?.('[storage.inventory] getStorageListBySpaceId 查询商品通用属性失败,stock 降级为 null', {
|
||
error: error.message,
|
||
});
|
||
}
|
||
|
||
// ────────── 5. 货主名称:按当前仓库收敛的签约表 store_remask ──────────
|
||
const storeRemarkMap = new Map();
|
||
const storeIds = [ ...new Set(rows.map(row => Number(row.store_id || 0)).filter(Boolean)) ];
|
||
if (storeIds.length > 0) {
|
||
try {
|
||
const storeRows = await ctx.model.StoreWarehouse.findAll({
|
||
where: { warehouse_id: warehouseId, store_id: { [Op.in]: storeIds } },
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
raw: true,
|
||
});
|
||
for (const row of storeRows) {
|
||
storeRemarkMap.set(Number(row.store_id), row.store_remask || '');
|
||
}
|
||
} catch (error) {
|
||
ctx.logger?.warn?.('[storage.inventory] getStorageListBySpaceId 查询货主名称失败,store_name 降级为 null', {
|
||
error: error.message,
|
||
});
|
||
}
|
||
}
|
||
|
||
// ────────── 6. 按商品(stock_id)汇总为一条 ──────────
|
||
const list = this._aggregateStorageRowsByStock(rows, spaceInfo, stockDetailMap, storeRemarkMap);
|
||
|
||
return {
|
||
code: 200,
|
||
message: 'ok',
|
||
data: { space: spaceInfo, list },
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 将同一库位下的库存明细行按商品(stock_id)汇总:汇总数量并统计批次数与最早/最晚入库时间。
|
||
* 商品字段取自 stock_warehouse 通用属性(getStockDetails 返回值,未命中时为 null)。
|
||
*
|
||
* @param {Array<Object>} rows wms_storage 明细行(Sequelize 实例或 plain 对象)
|
||
* @param {Object} [spaceInfo] 库位信息(space_code/custom_name 平铺到每行)
|
||
* @param {Map<number, Object>} [stockDetailMap] stock_id → stock_warehouse 通用属性
|
||
* @param {Map<number, string>} [storeRemarkMap] store_id → 货主名称(store_remask)
|
||
* @return {Array<Object>} 按商品汇总后的列表
|
||
*/
|
||
_aggregateStorageRowsByStock(rows = [], spaceInfo = null, stockDetailMap = null, storeRemarkMap = null) {
|
||
const { app } = this;
|
||
const location = spaceInfo || {};
|
||
const stockMap = stockDetailMap || new Map();
|
||
const storeMap = storeRemarkMap || new Map();
|
||
const groupedMap = new Map();
|
||
|
||
for (const item of rows) {
|
||
const row = item && typeof item.get === 'function' ? item.get({ plain: true }) : item;
|
||
const stockId = Number(row.stock_id || 0);
|
||
if (!stockId) {
|
||
continue;
|
||
}
|
||
|
||
const quantity = Number(row.quantity || 0);
|
||
const lockedQuantity = Number(row.locked_quantity || 0);
|
||
const interceptLockedQuantity = Number(row.intercept_locked_quantity || 0);
|
||
const availableQuantity = Number(row.available_quantity || 0);
|
||
const inboundTimeMs = row.inbound_time ? new Date(row.inbound_time).getTime() : null;
|
||
|
||
const existing = groupedMap.get(stockId);
|
||
if (!existing) {
|
||
groupedMap.set(stockId, {
|
||
warehouse_id: row.warehouse_id,
|
||
store_id: row.store_id,
|
||
space_id: Number(row.space_id || 0),
|
||
stock_id: stockId,
|
||
quantity,
|
||
locked_quantity: lockedQuantity,
|
||
intercept_locked_quantity: interceptLockedQuantity,
|
||
available_quantity: availableQuantity,
|
||
batch_count: 1,
|
||
first_inbound_time: inboundTimeMs,
|
||
last_inbound_time: inboundTimeMs,
|
||
});
|
||
continue;
|
||
}
|
||
|
||
existing.quantity += quantity;
|
||
existing.locked_quantity += lockedQuantity;
|
||
existing.intercept_locked_quantity += interceptLockedQuantity;
|
||
existing.available_quantity += availableQuantity;
|
||
existing.batch_count += 1;
|
||
if (inboundTimeMs !== null && (existing.first_inbound_time === null || inboundTimeMs < existing.first_inbound_time)) {
|
||
existing.first_inbound_time = inboundTimeMs;
|
||
}
|
||
if (inboundTimeMs !== null && (existing.last_inbound_time === null || inboundTimeMs > existing.last_inbound_time)) {
|
||
existing.last_inbound_time = inboundTimeMs;
|
||
}
|
||
}
|
||
|
||
return [ ...groupedMap.values() ].map(row => ({
|
||
...row,
|
||
space_code: location.space_code || '',
|
||
space_name: location.custom_name || location.space_code || '',
|
||
store_name: storeMap.get(Number(row.store_id || 0)) || null,
|
||
stock: stockMap.get(row.stock_id) || null,
|
||
first_inbound_time: row.first_inbound_time ? app.formatDate(row.first_inbound_time) : '',
|
||
last_inbound_time: row.last_inbound_time ? app.formatDate(row.last_inbound_time) : '',
|
||
}));
|
||
}
|
||
|
||
/**
|
||
* 将库存明细行按库位(space_id)汇总:汇总 quantity/locked_quantity/available_quantity,
|
||
* 统计批次数并取最早/最晚入库时间。汇总行不含批次与效期字段,保留商品/库位关联信息。
|
||
*
|
||
* @param {Array<Object>} rows Sequelize 实例数组(或 plain 对象数组)
|
||
* @return {Array<Object>} 按库位汇总后的数组
|
||
*/
|
||
_aggregateStorageRowsBySpace(rows = []) {
|
||
const { app } = this;
|
||
const groupedMap = new Map();
|
||
|
||
for (const item of rows) {
|
||
const row = item && typeof item.get === 'function' ? item.get({ plain: true }) : item;
|
||
const spaceId = Number(row.space_id || 0);
|
||
const quantity = Number(row.quantity || 0);
|
||
const lockedQuantity = Number(row.locked_quantity || 0);
|
||
const availableQuantity = Number(row.available_quantity || 0);
|
||
const inboundTimeMs = row.inbound_time ? new Date(row.inbound_time).getTime() : null;
|
||
|
||
const existing = groupedMap.get(spaceId);
|
||
if (!existing) {
|
||
groupedMap.set(spaceId, {
|
||
warehouse_id: row.warehouse_id,
|
||
store_id: row.store_id,
|
||
space_id: spaceId,
|
||
stock_id: row.stock_id,
|
||
quantity,
|
||
locked_quantity: lockedQuantity,
|
||
available_quantity: availableQuantity,
|
||
batch_count: 1,
|
||
first_inbound_time: inboundTimeMs,
|
||
last_inbound_time: inboundTimeMs,
|
||
stock: row.stock || null,
|
||
space: row.space || null,
|
||
});
|
||
continue;
|
||
}
|
||
|
||
existing.quantity += quantity;
|
||
existing.locked_quantity += lockedQuantity;
|
||
existing.available_quantity += availableQuantity;
|
||
existing.batch_count += 1;
|
||
if (inboundTimeMs !== null && (existing.first_inbound_time === null || inboundTimeMs < existing.first_inbound_time)) {
|
||
existing.first_inbound_time = inboundTimeMs;
|
||
}
|
||
if (inboundTimeMs !== null && (existing.last_inbound_time === null || inboundTimeMs > existing.last_inbound_time)) {
|
||
existing.last_inbound_time = inboundTimeMs;
|
||
}
|
||
}
|
||
|
||
return [ ...groupedMap.values() ].map(row => {
|
||
const formatted = { ...row };
|
||
if (formatted.stock) {
|
||
formatted.stock = {
|
||
...formatted.stock,
|
||
is_batch_mgmt_enabled: toBooleanFlag(formatted.stock.is_batch_mgmt),
|
||
store_name: formatted.stock.store_stock?.store_remask || null,
|
||
};
|
||
delete formatted.stock.store_stock;
|
||
delete formatted.stock.is_batch_mgmt;
|
||
}
|
||
// 货主名称提升到根层级,便于前端直接使用
|
||
formatted.store_name = formatted.stock?.store_name || null;
|
||
formatted.first_inbound_time = formatted.first_inbound_time ? app.formatDate(formatted.first_inbound_time) : '';
|
||
formatted.last_inbound_time = formatted.last_inbound_time ? app.formatDate(formatted.last_inbound_time) : '';
|
||
return formatted;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 读取当前仓库货主配置中的库存预警规则,并转换为按到期天数递增的区间配置。
|
||
*
|
||
* @param {number} warehouseId 仓库ID(货主ID)
|
||
* @param {string} logTag 日志标记
|
||
* @return {Promise<Array<Object>>} 库存预警规则区间列表
|
||
*/
|
||
async _loadInventoryWarningRanges(warehouseId, logTag = 'storage.inventory') {
|
||
const { ctx } = this;
|
||
try {
|
||
const store = await ctx.model.Store.findByPk(warehouseId, {
|
||
attributes: [ 'id', 'subject_config' ],
|
||
});
|
||
const normalizedSubjectConfig = ctx.model.Store.normalizeSubjectConfig(
|
||
store ? store.subject_config : null
|
||
);
|
||
return buildInventoryWarningRanges(
|
||
normalizedSubjectConfig && Array.isArray(normalizedSubjectConfig.inventory_warning_rules)
|
||
? normalizedSubjectConfig.inventory_warning_rules
|
||
: []
|
||
);
|
||
} catch (error) {
|
||
ctx.logger.warn(`[${logTag}] 库存预警规则读取失败: ${error.message}`);
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 将库存批次明细查询结果整理为接口返回格式:
|
||
* 货主名称提升、批次管理标记布尔化、日期格式化、效期与库存预警字段填充。
|
||
*
|
||
* @param {Array<Object>} rows Sequelize 实例数组(或 plain 对象数组)
|
||
* @param {Array<Object>} inventoryWarningRanges 库存预警规则区间
|
||
* @param {number} nowMs 当前时间戳
|
||
* @return {Array<Object>} 格式化后的明细数组
|
||
*/
|
||
_formatBatchStorageRows(rows = [], inventoryWarningRanges = [], nowMs = Date.now()) {
|
||
const { app } = this;
|
||
return rows.map(item => {
|
||
const row = item && typeof item.get === 'function' ? item.get({ plain: true }) : item;
|
||
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;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 收货单快捷入库:判断货主配置是否允许收货单快捷入库,不允许直接返回失败;
|
||
* 允许的话使用收货单的明细创建入库单,相同 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 };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 收货单直入库存(一步完成):直接写入 wms_storage 库位库存并生成入库单。
|
||
*
|
||
* 与 quickPutaway(转入库单,不写库存,明细按 stock_id 合并)的区别:
|
||
* - 入库单明细与收货单明细一一对应(不合并),每行按收货明细的库位 space_id 入库;
|
||
* - 直接写 wms_storage / wms_stock_warehouse 库存并写入出入库流水,入库单一步置为 COMPLETED。
|
||
*
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.receiving_id 收货单ID(必填)
|
||
* @return {Promise<Object>} code/data/message 结构,data 中包含创建的入库单信息
|
||
*/
|
||
async directPutaway(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;
|
||
|
||
// 默认库位:优先使用仓库设置 default_location_id,未设置则兜底库位 1
|
||
let defaultSpaceId = 1;
|
||
try {
|
||
const deliveryOrderService = ctx.service && ctx.service.systems && ctx.service.systems.deliveryOrder;
|
||
const subjectConfig = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function'
|
||
? await deliveryOrderService.getStoreSubjectConfig(warehouseId)
|
||
: null;
|
||
const configuredLocationId = Number(subjectConfig && subjectConfig.default_location_id || 0);
|
||
if (Number.isInteger(configuredLocationId) && configuredLocationId > 0) {
|
||
defaultSpaceId = configuredLocationId;
|
||
}
|
||
} catch (error) {
|
||
ctx.logger.warn('[inventory.directPutaway] 读取仓库默认库位失败,兜底库位 1: %s', error.message);
|
||
}
|
||
|
||
// ────────── 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 allowDirectPutaway = Number(policyConfig.allow_receiving_direct_putaway) === 1;
|
||
|
||
if (!allowDirectPutaway) {
|
||
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',
|
||
'space_id', 'storage_status', 'stored_quantity',
|
||
],
|
||
});
|
||
|
||
if (!receivingDetails || receivingDetails.length === 0) {
|
||
return { code: 400, message: '收货单无明细,无法直入库存', data: null };
|
||
}
|
||
|
||
// 过滤出需要入库的明细(排除已全部入库的)
|
||
const pendingDetails = receivingDetails.filter(
|
||
d => d.storage_status !== 'all' && Number(d.actual_quantity) > 0
|
||
);
|
||
|
||
if (pendingDetails.length === 0) {
|
||
return { code: 400, message: '收货单所有明细均已入库,禁止重复直入库存', data: null };
|
||
}
|
||
|
||
// 待入库明细必须全部已匹配系统商品
|
||
const unmatchedDetails = pendingDetails.filter(d => !d.system_product_id);
|
||
if (unmatchedDetails.length > 0) {
|
||
const names = unmatchedDetails.map(d => d.product_name).join('、');
|
||
return { code: 400, message: `以下商品未匹配系统商品,请先绑定: ${names}`, data: null };
|
||
}
|
||
|
||
// ────────── 5. 批量查询 stock_warehouse 校验商品有效 ──────────
|
||
const stockIds = [ ...new Set(pendingDetails.map(d => Number(d.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);
|
||
}
|
||
|
||
const missingStockIds = stockIds.filter(sid => !stockMap.has(sid));
|
||
if (missingStockIds.length > 0) {
|
||
return {
|
||
code: 400,
|
||
message: `以下商品在当前仓库中不存在或已失效: stock_id=${missingStockIds.join(',')}`,
|
||
data: null,
|
||
};
|
||
}
|
||
|
||
// ────────── 6. 开事务:创建入库单 + 直接写库存 ──────────
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// 锁定收货单行,防止并发重复直入
|
||
const lockedReceiving = await ctx.model.Receiving.findOne({
|
||
where: { id: receivingId },
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
attributes: [ 'id', 'storage_status' ],
|
||
});
|
||
if (!lockedReceiving) {
|
||
await transaction.rollback();
|
||
return { code: 404, message: '收货单不存在', data: null };
|
||
}
|
||
if (lockedReceiving.storage_status === 'all') {
|
||
await transaction.rollback();
|
||
return { code: 400, message: '收货单已全部入库,禁止重复直入库存', data: null };
|
||
}
|
||
|
||
// 获取货主和仓库名称快照
|
||
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 : '';
|
||
|
||
// 生成入库单号(SCRK)
|
||
const entryOrderCode = await this._generateEntryOrderCode(warehouseId, storeId, transaction);
|
||
|
||
// 创建入库单主表(直入:一步完成,直接 COMPLETED)
|
||
const entryOrder = await ctx.model.EntryOrder.create({
|
||
entry_order_code: entryOrderCode,
|
||
order_type: 'SCRK',
|
||
total_order_lines: pendingDetails.length,
|
||
order_create_time: new Date(),
|
||
source_type: 'WMS',
|
||
order_status: 'COMPLETED',
|
||
sync_status: 'SUCCESS',
|
||
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;
|
||
|
||
// ────────── 7. 创建入库单明细:与收货明细一一对应(不合并) ──────────
|
||
// 记录 收货明细ID → 入库明细ID 映射,用于写入 wms_inbound_direct_log
|
||
const entryItemIdByDetailId = new Map();
|
||
for (let i = 0; i < pendingDetails.length; i++) {
|
||
const detail = pendingDetails[i];
|
||
const stockInfo = stockMap.get(Number(detail.system_product_id));
|
||
const detailQty = Number(detail.actual_quantity) || 0;
|
||
|
||
const entryItem = 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: detailQty,
|
||
inventory_type: 'ZP',
|
||
stock_id: Number(detail.system_product_id),
|
||
received_quantity: detailQty,
|
||
confirm_quantity: 0,
|
||
}, { transaction });
|
||
|
||
entryItemIdByDetailId.set(detail.id, entryItem.id);
|
||
}
|
||
|
||
// ────────── 8. 写入 wms_entry_order_receiving 主表级绑定 ──────────
|
||
await ctx.model.EntryOrderReceiving.create({
|
||
entry_order_id: entryOrderId,
|
||
receiving_id: receivingId,
|
||
}, { transaction });
|
||
|
||
// ────────── 9. 更新 StockWarehouse 总库存(按 stock_id 聚合) ──────────
|
||
const stockQtyMap = new Map();
|
||
for (const detail of pendingDetails) {
|
||
const sid = Number(detail.system_product_id);
|
||
const qty = Number(detail.actual_quantity) || 0;
|
||
stockQtyMap.set(sid, (stockQtyMap.get(sid) || 0) + qty);
|
||
}
|
||
|
||
// stock(wms_stock_warehouse)变更摘要,供操作日志记录
|
||
const stockChangeSummaries = [];
|
||
|
||
for (const [ sid, inboundQty ] of stockQtyMap) {
|
||
// 悲观行锁
|
||
const stockRecord = await ctx.model.StockWarehouse.findOne({
|
||
where: { id: sid, is_valid: 'Y', deleted_at: null },
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
if (!stockRecord) {
|
||
throw new Error(`商品库存记录不存在或已失效,无法直入库存: stock_id=${sid}`);
|
||
}
|
||
|
||
const beforeQuantity = Number(stockRecord.quantity) || 0;
|
||
const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||
|
||
await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true });
|
||
await stockRecord.reload({ transaction });
|
||
|
||
const afterQuantity = Number(stockRecord.quantity) || 0;
|
||
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||
|
||
// 商品维度流水(SCRK)
|
||
await ctx.service.systems.stockTransaction.create({
|
||
transaction_type: 'INBOUND',
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
stock_id: sid,
|
||
quantity: inboundQty,
|
||
batch_no: entryOrderCode,
|
||
inventory_type: 'ZP',
|
||
order_type: 'SCRK',
|
||
order_no: entryOrderCode,
|
||
entry_order_id: entryOrderId,
|
||
receiving_id: receivingId,
|
||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||
operator_name: ctx.user?.employees_name || '',
|
||
remark: '收货单直入库存',
|
||
before_quantity: beforeQuantity,
|
||
after_quantity: afterQuantity,
|
||
before_locked_quantity: beforeLockedQuantity,
|
||
after_locked_quantity: afterLockedQuantity,
|
||
created_at: new Date(),
|
||
}, { transaction });
|
||
|
||
// 收集 stock 变更摘要(wms_stock_warehouse 总量变更)
|
||
stockChangeSummaries.push({
|
||
stock_id: sid,
|
||
before_quantity: beforeQuantity,
|
||
after_quantity: afterQuantity,
|
||
change_quantity: inboundQty,
|
||
});
|
||
}
|
||
|
||
// ────────── 10. 写 wms_storage 库位库存(按收货明细库位 space_id 逐明细写入) ──────────
|
||
// storage(wms_storage)变更笔数,供操作日志记录
|
||
let storageWriteCount = 0;
|
||
|
||
for (const detail of pendingDetails) {
|
||
const sid = Number(detail.system_product_id);
|
||
const qty = Number(detail.actual_quantity) || 0;
|
||
if (qty <= 0) continue;
|
||
|
||
// 收货明细有库位则按其库位入库,否则使用仓库默认库位(未设置时兜底库位 1)
|
||
const spaceId = Number(detail.space_id) > 0 ? Number(detail.space_id) : defaultSpaceId;
|
||
const batchNo = detail.batch_number || entryOrderCode;
|
||
const productionDate = detail.production_date || null;
|
||
const expiryDate = detail.expiry_date || null;
|
||
const inventoryType = 'ZP';
|
||
|
||
// 查找 库位+SKU+批次+类型 已有的库存记录(悲观行锁)
|
||
const sRecord = await ctx.model.Storage.findOne({
|
||
where: {
|
||
space_id: spaceId,
|
||
stock_id: sid,
|
||
batch_no: batchNo,
|
||
inventory_type: inventoryType,
|
||
is_enabled: 1,
|
||
delete_at: null,
|
||
},
|
||
lock: transaction.LOCK.UPDATE,
|
||
transaction,
|
||
});
|
||
|
||
let sId = null;
|
||
let sBeforeQty = 0;
|
||
let sAfterQty = 0;
|
||
let sBeforeLockedQty = 0;
|
||
let sAfterLockedQty = 0;
|
||
let sBeforeInterceptQty = 0;
|
||
let sAfterInterceptQty = 0;
|
||
|
||
if (sRecord) {
|
||
if (Number(sRecord.stock_id) !== Number(sid)) {
|
||
throw new Error(
|
||
`直入库存归属冲突: storage_id=${sRecord.id} 当前 stock_id=${sRecord.stock_id}, ` +
|
||
`本次入库 stock_id=${sid}, space_id=${spaceId}, batch_no=${batchNo}`
|
||
);
|
||
}
|
||
sBeforeQty = Number(sRecord.quantity) || 0;
|
||
sAfterQty = sBeforeQty + qty;
|
||
sBeforeLockedQty = Number(sRecord.locked_quantity) || 0;
|
||
sAfterLockedQty = sBeforeLockedQty;
|
||
sBeforeInterceptQty = Number(sRecord.intercept_locked_quantity) || 0;
|
||
sAfterInterceptQty = sBeforeInterceptQty;
|
||
|
||
await ctx.model.Storage.update({
|
||
quantity: app.Sequelize.literal(`quantity + ${qty}`),
|
||
available_quantity: app.Sequelize.literal(`available_quantity + ${qty}`),
|
||
entry_order_id: entryOrderId,
|
||
inbound_time: new Date(),
|
||
inbound_order_no: entryOrderCode,
|
||
production_date: productionDate,
|
||
expiry_date: expiryDate,
|
||
receiving_id: receivingId,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: sRecord.id },
|
||
transaction,
|
||
});
|
||
sId = sRecord.id;
|
||
} else {
|
||
const createdStorage = await ctx.model.Storage.create({
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
space_id: spaceId,
|
||
stock_id: sid,
|
||
batch_no: batchNo,
|
||
inventory_type: inventoryType,
|
||
quantity: qty,
|
||
locked_quantity: 0,
|
||
available_quantity: qty,
|
||
inbound_time: new Date(),
|
||
inbound_order_no: entryOrderCode,
|
||
receiving_id: receivingId,
|
||
entry_order_id: entryOrderId,
|
||
supplier_id: null,
|
||
supplier_batch_no: null,
|
||
production_date: productionDate,
|
||
expiry_date: expiryDate,
|
||
is_enabled: 1,
|
||
created_at: new Date(),
|
||
updated_at: new Date(),
|
||
}, { transaction });
|
||
sId = createdStorage.id;
|
||
sAfterQty = qty;
|
||
sAfterLockedQty = 0;
|
||
}
|
||
|
||
storageWriteCount += 1;
|
||
|
||
// 库位维度流水(order_type 与现有 storage.entry.commit 链路一致:entry_order)
|
||
await ctx.model.StorageTransaction.create({
|
||
transaction_type: 'INBOUND',
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
stock_id: sid,
|
||
storage_id: sId,
|
||
space_id: spaceId,
|
||
quantity: qty,
|
||
before_quantity: sBeforeQty,
|
||
after_quantity: sAfterQty,
|
||
before_locked_quantity: sBeforeLockedQty,
|
||
after_locked_quantity: sAfterLockedQty,
|
||
before_intercept_locked_quantity: sBeforeInterceptQty,
|
||
after_intercept_locked_quantity: sAfterInterceptQty,
|
||
batch_no: batchNo,
|
||
inventory_type: inventoryType,
|
||
order_type: 'entry_order',
|
||
order_no: entryOrderCode,
|
||
order_id: entryOrderId,
|
||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||
operator_name: ctx.user?.employees_name || '',
|
||
remark: '收货单直入库存',
|
||
created_at: new Date(),
|
||
}, { transaction });
|
||
|
||
// 写入导入/PDA 入库记录(status=committed,与 storage.entry.commit 链路一致)。
|
||
// 该表被 storage.receiving.scanDetail、storage.entry.getDirectInboundItems、
|
||
// getReceivingDetailsForBind 的可用数量占用统计等读取,直入也必须写入以保持口径一致。
|
||
await ctx.model.InboundDirectLog.create({
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
stock_id: sid,
|
||
quantity: qty,
|
||
inbound_type: 'import',
|
||
entry_order_id: entryOrderId,
|
||
entry_order_code: entryOrderCode,
|
||
entry_item_id: entryItemIdByDetailId.get(detail.id) || 0,
|
||
receiving_detail_id: detail.id,
|
||
space_id: spaceId,
|
||
status: 'committed',
|
||
remark: '收货单直入库存',
|
||
operator_id: ctx.user?.employees_id || ctx.user?.id || null,
|
||
operator_name: ctx.user?.employees_name || '',
|
||
}, { transaction });
|
||
}
|
||
|
||
// ────────── 11. 回填收货单明细与主表入库状态 ──────────
|
||
for (const detail of pendingDetails) {
|
||
await ctx.model.ReceivingDetail.update({
|
||
stored_quantity: Number(detail.actual_quantity) || 0,
|
||
storage_status: 'all',
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: detail.id },
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
// 收货单主表 storage_status:统计全部明细状态
|
||
const allStatusRows = await ctx.model.ReceivingDetail.findAll({
|
||
where: { receiving_id: receivingId },
|
||
attributes: [ 'storage_status' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
const allStored = allStatusRows.length > 0
|
||
&& allStatusRows.every(d => d.storage_status === 'all');
|
||
await ctx.model.Receiving.update({
|
||
storage_status: allStored ? 'all' : 'partial',
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: receivingId },
|
||
transaction,
|
||
});
|
||
|
||
// ────────── 12. 操作日志(entry_order / storage / stock 三种业务维度全量记录) ──────────
|
||
try {
|
||
const totalDirectQty = pendingDetails.reduce((sum, d) => sum + (Number(d.actual_quantity) || 0), 0);
|
||
await ctx.service.systems.operationLog.createOperationLogs([
|
||
{
|
||
businessType: 'entry_order',
|
||
businessId: entryOrderId,
|
||
operationCode: 'ENTRY_ORDER_DIRECT_PUTAWAY',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
message: `收货单${receiving.receiving_number}直入库存完成,生成入库单${entryOrderCode},共 ${pendingDetails.length} 行明细、${totalDirectQty} 件`,
|
||
},
|
||
},
|
||
{
|
||
businessType: 'storage',
|
||
businessId: entryOrderId,
|
||
operationCode: 'STORAGE_DIRECT_PUTAWAY',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
message: `直入库存写入 wms_storage 库位库存 ${storageWriteCount} 笔(按收货明细库位),共 ${totalDirectQty} 件,入库单号 ${entryOrderCode}`,
|
||
},
|
||
},
|
||
{
|
||
businessType: 'stock',
|
||
businessId: entryOrderId,
|
||
operationCode: 'STOCK_DIRECT_PUTAWAY',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId,
|
||
message: `直入库存更新 wms_stock_warehouse 总库存 ${stockChangeSummaries.length} 个 SKU,共 ${totalDirectQty} 件,变更明细: ${JSON.stringify(stockChangeSummaries)}`,
|
||
},
|
||
},
|
||
], { transaction });
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[inventory.directPutaway] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
// ────────── 13. 提交事务 ──────────
|
||
await transaction.commit();
|
||
|
||
// 入库完成通知货主(失败不影响主流程)
|
||
try {
|
||
await ctx.service.systems.inboundDirectLog.notifyEntryOrderCompleted(entryOrder);
|
||
} catch (noticeErr) {
|
||
ctx.logger.warn('[inventory.directPutaway] 入库完成通知货主失败,不影响业务', noticeErr);
|
||
}
|
||
|
||
ctx.logger.info(`[inventory.directPutaway] 直入库存完成 entryOrderId=${entryOrderId} receivingId=${receivingId} lines=${pendingDetails.length}`);
|
||
|
||
return {
|
||
code: 200,
|
||
message: '直入库存成功',
|
||
data: {
|
||
entry_order_id: entryOrderId,
|
||
entry_order_code: entryOrderCode,
|
||
order_status: 'COMPLETED',
|
||
receiving_id: receivingId,
|
||
total_lines: pendingDetails.length,
|
||
total_quantity: pendingDetails.reduce((sum, d) => sum + (Number(d.actual_quantity) || 0), 0),
|
||
},
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
ctx.logger.error(`[inventory.directPutaway] 直入库存异常 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 safeSortOrder = String(sortOrder).toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||
const batchSortField = STORAGE_BATCH_SORT_FIELD_WHITELIST.has(sortField) ? sortField : 'id';
|
||
const aggregateOrderField = STORAGE_AGGREGATE_ORDER_FIELD_MAP[sortField] || 'last_inbound_time';
|
||
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 },
|
||
// 仅导出有量库存:明细模式过滤 quantity=0 的行,汇总模式过滤总量为 0 的商品
|
||
{ quantity: { [Op.gt]: 0 } },
|
||
],
|
||
};
|
||
|
||
// 动态 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: [[ batchSortField, safeSortOrder ]],
|
||
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(aggregateOrderField), safeSortOrder ]],
|
||
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;
|