WMS_MAIN/app/service/systems/stock_store.js
liufumingren adb1a16599 1
2026-05-16 23:00:49 +08:00

3311 lines
99 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
const {
parseWhereConditions,
buildSequelizeCondition: buildSequelizeConditionUtil,
processConditionValue: processConditionValueUtil,
isEmptyValue: isEmptyValueUtil,
normalizeDate: normalizeDateUtil,
} = require('../../lib/query_condition_parser');
class stockStoreService extends Service {
async create(stockData) {
const {
app,
service,
} = this;
const warehouseId = stockData.warehouse_id;
// 设置创建时间
if (!stockData.create_time) {
stockData.create_time = new Date();
}
// 检查唯一约束
const existing = await app.model.StockStore.findOne({
where: {
item_code: stockData.item_code,
app_key: stockData.app_key,
warehouse_id: warehouseId,
store_id: stockData.store_id,
},
});
let result;
if (existing) {
// 更新现有记录
await app.model.StockStore.update(stockData, {
where: {
id: existing.id,
},
});
const updatedRow = await app.model.StockStore.findByPk(existing.id);
result = updatedRow;
} else {
// 创建新记录
result = await app.model.StockStore.create(stockData);
}
try {
// 创建/更新成功后,同步到库存表
// 注意:这里需要传入warehouseId作为第二个参数
const warehouseResult = await this.checkAndCreateWarehouseStock(
stockData,
warehouseId // 传入warehouse_id
);
// 如果库存表操作成功,更新 stock_id
if (warehouseResult.success) {
await app.model.StockStore.update({
stock_id: warehouseResult.id,
}, {
where: {
id: result.id,
},
silent: true, // 不触发钩子,避免循环
});
await service.systems.operationLog.createOperationLog({
businessType: 'stock',
businessId: warehouseResult.id,
operationCode: 'BIND',
operator: {
id: null,
name: '奇门',
},
extras: {
warehouseId,
externalLogType: 'QIMEN',
externalLogId: this.ctx.qimenLogId,
},
beforeChanges: null,
});
result.stock_id = warehouseResult.id;
app.logger.debug(`[库存同步成功] StockStore ID: ${result.id}, StockWarehouse ID: ${warehouseResult.id}`);
} else {
app.logger.warn(`[库存同步失败] StockStore ID: ${result.id}, 原因: ${warehouseResult.message}`);
}
} catch (error) {
// 库存同步失败不影响主流程,但记录日志
app.logger.error(`[库存同步异常] StockStore ID: ${result.id}`, {
error: error.message,
stack: error.stack,
});
}
return result;
}
async initQimenStockData(data, appKey, storeId, warehouseId) {
const item_data = data.item ? data.item : {};
const result = {
warehouse_code: data.warehouseCode || '',
owner_code: data.ownerCode || '',
is_area_sale: item_data.isAreaSale || 'N',
item_code: item_data.itemCode || '',
app_key: appKey || '',
goods_code: item_data.goodsCode || '',
item_name: item_data.itemName || '',
sku_property: item_data.skuProperty || '',
stock_unit: item_data.stockUnit || '',
length: parseFloat(item_data.length) || 0,
width: parseFloat(item_data.width) || 0,
height: parseFloat(item_data.height) || 0,
volume: parseFloat(item_data.volume) || 0,
gross_weight: parseFloat(item_data.grossWeight) || 0,
net_weight: parseFloat(item_data.netWeight) || 0,
category_id: parseInt(item_data.categoryId) || 0,
category_name: item_data.categoryName || '',
item_type: item_data.itemType || '',
tag_price: parseFloat(item_data.tagPrice) || 0,
retail_price: parseFloat(item_data.retailPrice) || 0,
brand_name: item_data.brandName || null,
is_sn_mgmt: item_data.isSNMgmt || 'N',
is_shelf_life_mgmt: item_data.isShelfLifeMgmt || 'N',
is_batch_mgmt: item_data.isBatchMgmt || 'N',
create_time: item_data.createTime || new Date(),
update_time: new Date(),
is_valid: item_data.isValid || 'Y',
warehouse_id: warehouseId,
barcode: item_data.barCode || '',
store_id: storeId,
create_from: 'qimen',
};
return result;
}
async convertToQimenFormat(stockData) {
const { app } = this;
const result = {
// 商品信息
item: {
itemId: stockData.id, // 数据库主键作为奇门的itemId
itemCode: stockData.item_code || '',
goodsCode: stockData.goods_code || '',
itemName: stockData.item_name || '',
skuProperty: stockData.sku_property || '',
stockUnit: stockData.stock_unit || '',
// 尺寸重量信息
length: parseFloat(stockData.length) || 0,
width: parseFloat(stockData.width) || 0,
height: parseFloat(stockData.height) || 0,
volume: parseFloat(stockData.volume) || 0,
grossWeight: parseFloat(stockData.gross_weight) || 0,
netWeight: parseFloat(stockData.net_weight) || 0,
// 分类信息
categoryId: stockData.category_id || 0,
categoryName: stockData.category_name || '',
itemType: stockData.item_type || '',
// 价格信息
tagPrice: parseFloat(stockData.tag_price) || 0,
retailPrice: parseFloat(stockData.retail_price) || 0,
// 管理标志
isAreaSale: stockData.is_area_sale === 'Y' ? 'Y' : 'N',
isSNMgmt: stockData.is_sn_mgmt === 'Y' ? 'Y' : 'N',
isShelfLifeMgmt: stockData.is_shelf_life_mgmt === 'Y' ? 'Y' : 'N',
isBatchMgmt: stockData.is_batch_mgmt === 'Y' ? 'Y' : 'N',
// 其他信息
barCode: stockData.barcode || '',
isValid: stockData.is_valid === 'Y' ? 'Y' : 'N',
createTime: stockData.create_time ? app.formatDate(stockData.create_time) : '',
},
};
return result;
}
async getItemInfoWithCache(itemId) {
const {
app, ctx,
} = this;
const cacheKey = `item:info:${itemId}`;
try {
// 1. 尝试从缓存获取
const cached = await app.getCacheAsync(cacheKey);
if (cached !== null && cached !== undefined) {
app.logger.debug('[ItemCacheHit]', itemId);
// 处理空值标记
if (cached.__isNull) {
return null; // 明确返回 null 表示商品不存在
}
// 返回缓存的对象
return cached;
}
// 2. 缓存未命中,查询数据库
app.logger.debug('[ItemCacheMiss]', itemId);
// ⭐ 关键修复:使用 raw: true 获取纯对象
const itemInfo = await ctx.model.StockStore.findByPk(itemId, {
attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ], // 按需增加字段
raw: true, // ⭐ 必须:转换为纯 JavaScript 对象
});
// 3. 处理查询结果并缓存
if (itemInfo) {
// 缓存有效数据,设置合理过期时间(如5分钟)
await app.setCacheAsync(cacheKey, itemInfo, 300);
return itemInfo;
}
// ⭐ 关键:缓存空值,防止缓存穿透
// 使用特定标记,并设置较短过期时间(如1-2分钟)
const nullMarker = {
__isNull: true,
};
await app.setCacheAsync(cacheKey, nullMarker, 120);
return null; // 明确返回 null
} catch (error) {
app.logger.error('[getItemInfoWithCache] 查询失败', {
itemId,
error: error.message,
stack: error.stack,
});
// 根据错误类型处理
if (error.name && error.name.includes('Sequelize')) {
// 数据库错误,抛出系统异常
throw new Error('商品信息查询服务暂时不可用');
}
// Redis 等缓存错误,降级直接查数据库
// 这里简单重试一次数据库查询
app.logger.warn('缓存服务异常,降级直接查询数据库', itemId);
try {
const itemInfo = await ctx.model.StockStore.findByPk(itemId, {
attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ],
raw: true,
});
return itemInfo || null;
} catch (dbError) {
// 数据库也失败,向上抛出
throw new Error(`查询商品信息失败: ${dbError.message}`);
}
}
}
/**
* 查询商品对应的库存记录与可用量。
*
* @param {number|string} itemId 商品 ID。
* @param {Object|null} transaction 数据库事务。
* @return {Promise<Object>} 库存查询结果。
*/
async getItemStorages(itemId, transaction) {
const {
ctx,
app,
} = this;
const cacheKey = `storages:${itemId}`;
try {
// 1. 获取商品信息
const itemInfo = await this.getItemInfoWithCache(itemId);
// 情况A:商品不存在
if (!itemInfo || itemInfo.__isEmpty) {
return {
success: false,
error: '已更改未同步推送到仓库',
data: null,
};
}
// 情况B:商品存在但未绑定库存记录
if (!itemInfo.stock_id) {
return {
success: false,
error: '仓库已解绑,请联系仓库关联绑定',
data: null,
};
}
// 2. 检查缓存
let storage = null;
let fromCache = false;
const cached = await app.getCacheAsync(cacheKey);
if (cached) {
storage = cached;
fromCache = true;
if (storage && storage.canUse <= 0) {
const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(itemInfo.stock_id, transaction);
if (!policyConfig.allowOversell) {
app.logger.debug(`[缓存快速失败] 商品 ${itemId} 可用库存为0`);
return {
success: false,
error: '库存不足',
data: null,
_fromCache: true,
};
}
}
}
// 3. 查询数据库(缓存未命中或事务场景)
if (!storage || transaction) {
const stockWarehouse = await ctx.model.StockWarehouse.findOne({
where: {
id: itemInfo.stock_id,
is_valid: 'Y',
deleted_at: null,
},
attributes: [
'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight',
],
transaction,
lock: transaction?.LOCK?.UPDATE,
raw: true,
});
if (stockWarehouse) {
const quantity = parseInt(stockWarehouse.quantity) || 0;
const lockedQuantity = parseInt(stockWarehouse.locked_quantity) || 0;
const canUse = quantity - lockedQuantity;
const grossWeight = parseInt(stockWarehouse.gross_weight) || 0;
storage = {
id: stockWarehouse.id,
storeId: Number(stockWarehouse.store_id) || 0,
warehouseId: Number(stockWarehouse.warehouse_id) || 0,
quantity,
lockedQuantity,
canUse,
grossWeight,
_updatedAt: Date.now(),
exists: true,
};
} else {
// 库存记录不存在
app.logger.warn(`[库存记录缺失] 商品 ${itemId} 的 stock_id ${itemInfo.stock_id} 不存在`);
storage = {
id: null,
quantity: 0,
lockedQuantity: 0,
canUse: 0,
_updatedAt: Date.now(),
exists: false,
};
}
// 4. 异步更新缓存(不加await,不阻塞主流程)
const ttl = this._calculateCacheTTL(storage);
if (!cached) {
app.setCacheAsync(cacheKey, storage, ttl);
}
}
// 5. 返回结果
return {
success: true,
data: {
stock: {
id: itemInfo.id,
stock_id: itemInfo.stock_id,
store_id: storage && storage.storeId ? storage.storeId : undefined,
warehouse_id: storage && storage.warehouseId ? storage.warehouseId : undefined,
warehouse_code: itemInfo.warehouse_code,
item_code: itemInfo.item_code,
},
storage,
allow_oversell: storage && storage.canUse <= 0
? (await this.getStoreWarehousePolicyConfigByStockId(itemInfo.stock_id, transaction)).allowOversell
: undefined,
},
error: null,
_fromCache: fromCache,
};
} catch (error) {
app.logger.error(`[getItemStorages] 系统异常, itemId: ${itemId}`, {
error: error.message,
stack: error.stack,
});
return {
success: false,
error: `库存查询系统错误: ${error.message}`,
data: null,
};
}
}
/**
* 计算缓存时间
* @param {Object} storage - 库存对象
*/
_calculateCacheTTL(storage) {
if (!storage || !storage._exists || !storage._isValid) {
return 5; // 无效库存缓存5秒
}
if (storage.canUse <= 0) {
return 10; // 无库存缓存10秒
}
if (storage.canUse <= 10) {
return 15; // 低库存缓存15秒
}
return 60; // 正常库存缓存60秒
}
/**
* 清理缓存
* @param {number|string} itemId - 商品ID
*/
async clearItemStorageCache(itemId) {
const {
app,
} = this;
const cacheKey = `storages:${itemId}`;
if (app && typeof app.delCacheAsync === 'function') {
try {
await app.delCacheAsync(cacheKey);
app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`);
} catch (error) {
app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message);
}
return;
}
if (app && typeof app.setCacheAsync === 'function') {
try {
await app.setCacheAsync(cacheKey, null, 0);
app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`);
} catch (error) {
app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message);
}
}
}
/**
* 在给定事务中执行库存写操作,未传入事务时自动创建并提交回滚。
*
* @param {Object} externalTransaction 外部传入的数据库事务
* @param {Function} handler 业务处理函数
* @return {Promise<*>} 业务处理结果
*/
async _runWithTransaction(externalTransaction, handler) {
const { ctx } = this;
if (externalTransaction) {
return handler(externalTransaction, true);
}
const internalTransaction = await ctx.model.transaction();
try {
const result = await handler(internalTransaction, false);
await internalTransaction.commit();
return result;
} catch (error) {
await internalTransaction.rollback();
throw error;
}
}
/**
* 获取库存对应的货主-仓库签约策略配置。
*
* @param {number|Object} stockWarehouseId 库存 ID 或库存记录。
* @param {Object|null} [transaction=null] 事务对象。
* @return {Promise<Object>} 策略配置对象,包含 relation、policyConfig、allowOversell。
*/
async getStoreWarehousePolicyConfigByStockId(stockWarehouseId, transaction = null) {
const { ctx } = this;
const stockRecord = stockWarehouseId && typeof stockWarehouseId === 'object'
? stockWarehouseId
: await ctx.model.StockWarehouse.findOne({
where: {
id: Number(stockWarehouseId || 0),
is_valid: 'Y',
deleted_at: null,
},
attributes: [ 'id', 'store_id', 'warehouse_id' ],
transaction,
raw: true,
});
const storeId = Number(stockRecord && stockRecord.store_id) || 0;
const warehouseId = Number(stockRecord && stockRecord.warehouse_id) || 0;
if (storeId <= 0 || warehouseId <= 0) {
return {
relation: null,
policyConfig: null,
allowOversell: false,
};
}
const relation = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: storeId,
warehouse_id: warehouseId,
auth_status: 2,
use_status: 1,
},
attributes: [ 'id', 'policy_config', 'auth_status', 'use_status' ],
transaction,
raw: true,
});
if (!relation) {
return {
relation: null,
policyConfig: null,
allowOversell: false,
};
}
const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse;
const policyConfig = storeWarehouseService && typeof storeWarehouseService.getEffectivePolicyConfigByContractId === 'function'
? await storeWarehouseService.getEffectivePolicyConfigByContractId(relation.id, transaction)
: null;
return {
relation,
policyConfig,
allowOversell: Number(policyConfig && policyConfig.allow_oversell) === 1,
};
}
/**
* 锁定或释放库存。
*
* @param {number|string} stockWarehouseId 库存主键。
* @param {number} quantity 锁定数量,负数表示释放。
* @param {Object|null} transaction 数据库事务。
* @return {Promise<Object>} 锁定结果。
*/
async lockItemStorages(stockWarehouseId, quantity, transaction) {
const {
ctx,
app,
} = this;
// 输入验证
const lockQty = parseInt(quantity);
if (!stockWarehouseId || isNaN(lockQty) || lockQty === 0) {
return {
success: false,
error: `参数错误:库存ID无效或数量为0 (ID: ${stockWarehouseId}, Qty: ${quantity})`,
data: null,
};
}
const isLocking = lockQty > 0; // true=加锁,false=减锁
const absQty = Math.abs(lockQty);
try {
return await this._runWithTransaction(transaction, async currentTransaction => {
// 1. 查询并锁定记录(悲观锁)
const stockRecord = await ctx.model.StockWarehouse.findOne({
where: {
id: stockWarehouseId,
is_valid: 'Y',
deleted_at: null,
},
transaction: currentTransaction,
lock: currentTransaction.LOCK.UPDATE,
attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight' ],
raw: false,
});
if (!stockRecord) {
return {
success: false,
error: `库存记录不存在或已失效 (ID: ${stockWarehouseId})`,
data: null,
};
}
if (isLocking) {
const availableQty = stockRecord.quantity - stockRecord.locked_quantity;
if (availableQty < absQty) {
const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(stockRecord, currentTransaction);
if (!policyConfig.allowOversell) {
return {
success: false,
error: `库存不足,可用 ${availableQty},需求 ${absQty}`,
data: {
available: availableQty,
required: absQty,
recordId: stockWarehouseId,
},
};
}
}
} else {
if (stockRecord.locked_quantity < absQty) {
return {
success: false,
error: `释放数量超过已锁定库存,已锁 ${stockRecord.locked_quantity},尝试释放 ${absQty}`,
data: null,
};
}
const newLocked = stockRecord.locked_quantity - absQty;
if (newLocked < 0) {
return {
success: false,
error: `释放后锁定库存为负值: ${newLocked}`,
data: null,
};
}
}
if (isLocking) {
await stockRecord.increment('locked_quantity', {
by: absQty,
transaction: currentTransaction,
silent: true,
});
app.logger.info(
`[库存锁定] ID: ${stockWarehouseId}, 增加锁定: +${absQty}, 锁定后: ${stockRecord.locked_quantity + absQty}`
);
} else {
await stockRecord.decrement('locked_quantity', {
by: absQty,
transaction: currentTransaction,
silent: true,
});
app.logger.info(
`[库存释放] ID: ${stockWarehouseId}, 减少锁定: -${absQty}, 锁定后: ${stockRecord.locked_quantity - absQty}`
);
}
await stockRecord.reload({
transaction: currentTransaction,
});
return {
success: true,
data: {
id: stockWarehouseId,
action: isLocking ? 'lock' : 'unlock',
quantity: absQty,
beforeLocked: isLocking ? stockRecord.locked_quantity - absQty : stockRecord.locked_quantity +
absQty,
afterLocked: stockRecord.locked_quantity,
totalQuantity: stockRecord.quantity,
available: stockRecord.quantity - stockRecord.locked_quantity,
updatedAt: stockRecord.update_at,
},
error: null,
};
});
} catch (error) {
app.logger.error('[lockItemStorages] 系统异常', {
stockWarehouseId,
quantity,
isLocking,
error: error.message,
stack: error.stack,
});
// 根据错误类型返回
if (error.name && error.name.includes('Sequelize')) {
return {
success: false,
error: `数据库操作失败: ${error.message}`,
data: null,
};
}
return {
success: false,
error: `系统错误: ${error.message}`,
data: null,
};
}
}
/**
* 商品入库服务
* @param {number} itemId 商品ID (StockStore.id)
* @param {number} quantity 入库数量(正数)
* @param {Object} transaction 数据库事务
*/
async inbound(itemId, quantity, transaction) {
const {
ctx,
app,
} = this;
// 1. 参数验证
const inboundQty = parseInt(quantity);
if (!itemId || inboundQty <= 0) {
return {
success: false,
error: `入库参数无效: itemId=${itemId}, quantity=${quantity}`,
data: null,
};
}
try {
return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => {
// 2. 获取商品和库存信息(复用)
const stockResult = await this.getItemStorages(itemId, currentTransaction);
if (!stockResult.success) {
if (hasExternalTransaction) {
throw new Error(stockResult.error);
}
return stockResult;
}
const { storage } = stockResult.data;
// 3. 执行库存增加
if (!storage.exists) {
const failureResult = {
success: false,
error: '库存记录不存在,首次入库需要完整参数',
data: null,
};
if (hasExternalTransaction) {
throw new Error(failureResult.error);
}
return failureResult;
}
const beforeQuantity = Number(storage.quantity) || 0;
const beforeLockedQuantity = Number(storage.lockedQuantity) || 0;
// 非首次入库:更新现有记录(只增加quantity)
await ctx.model.StockWarehouse.increment('quantity', {
by: inboundQty,
where: {
id: storage.id,
is_valid: 'Y',
deleted_at: null,
},
transaction: currentTransaction,
});
const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, {
transaction: currentTransaction,
raw: true,
});
const afterQuantity = Number(updatedRecord.quantity) || 0;
const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0;
await ctx.service.systems.stockTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id,
store_id: ctx.user.store_id,
stock_id: storage.id,
storage_id: null,
space_id: null,
quantity: inboundQty,
batch_no: null,
inventory_type: 'ZP',
order_type: 'STOCK_STORE_INBOUND',
order_no: null,
order_id: null,
receiving_id: null,
entry_order_id: null,
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: currentTransaction,
});
await ctx.model.StorageTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id,
store_id: ctx.user.store_id,
stock_id: storage.id,
storage_id: null,
space_id: null,
quantity: inboundQty,
before_quantity: beforeQuantity,
after_quantity: afterQuantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: afterLockedQuantity,
batch_no: null,
inventory_type: 'ZP',
order_type: 'STOCK_STORE_INBOUND',
order_no: null,
order_id: null,
source_order_codes: null,
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
operator_name: ctx.user?.employees_name || '',
remark: '商品入库',
created_at: new Date(),
}, {
transaction: currentTransaction,
});
app.logger.info('[入库] 更新现有库存', {
itemId,
stockId: storage.id,
quantity: inboundQty,
before: beforeQuantity,
after: afterQuantity,
});
await this.clearItemStorageCache(itemId);
return {
success: true,
data: {
itemId,
stockId: storage.id,
action: 'inbound',
quantity: inboundQty,
beforeQuantity,
afterQuantity,
beforeLocked: beforeLockedQuantity,
afterLocked: afterLockedQuantity,
available: afterQuantity - afterLockedQuantity,
updatedAt: updatedRecord.update_at,
},
error: null,
};
});
} catch (error) {
if (transaction) {
throw error;
}
app.logger.error('[inbound] 入库失败', {
itemId,
quantity,
error: error.message,
stack: error.stack,
});
return {
success: false,
error: `入库系统错误: ${error.message}`,
data: null,
};
}
}
/**
* 规范化出库元信息,兼容驼峰与下划线字段。
*
* @param {Object} meta 出库元信息。
* @return {Object} 规范化后的订单上下文。
*/
normalizeOutboundMeta(meta = {}) {
const normalized = meta && typeof meta === 'object' ? meta : {};
const orderIdRaw = normalized.orderId
?? normalized.order_id
?? normalized.deliveryOrderId
?? normalized.delivery_order_id
?? normalized.id;
const orderItemIdRaw = normalized.orderItemId ?? normalized.order_item_id;
const sourceOrderCodesRaw = normalized.sourceOrderCodes ?? normalized.source_order_codes;
const orderNoRaw = normalized.orderNo
?? sourceOrderCodesRaw
?? normalized.order_no
?? normalized.deliveryOrderCode
?? normalized.delivery_order_code;
const orderId = Number(orderIdRaw);
const orderItemId = Number(orderItemIdRaw);
const orderNo = String(orderNoRaw || '').trim();
const sourceOrderCodes = String(sourceOrderCodesRaw || '').trim();
return {
orderId: Number.isFinite(orderId) && orderId > 0 ? orderId : null,
orderItemId: Number.isFinite(orderItemId) && orderItemId > 0 ? orderItemId : null,
orderNo: orderNo || null,
sourceOrderCodes: sourceOrderCodes || null,
};
}
/**
* 查询订单明细对应的拣货分配记录。
*
* @param {number|null} orderId 订单 ID。
* @param {number|null} orderItemId 订单明细 ID。
* @param {Object|null} transaction 事务对象。
* @return {Promise<Array<Object>>} 拣货分配列表。
*/
async getPickingRowsForOutbound(orderId, orderItemId, transaction) {
const { ctx } = this;
const pickingModel = ctx.model && ctx.model.Picking;
if (!pickingModel || typeof pickingModel.findAll !== 'function') {
return [];
}
if (!orderId || !orderItemId) {
return [];
}
const rows = await pickingModel.findAll({
where: {
order_id: orderId,
order_item_id: orderItemId,
},
attributes: [ 'storage_id', 'space_id', 'quantity' ],
order: [[ 'id', 'ASC' ]],
raw: true,
transaction,
});
return Array.isArray(rows) ? rows : [];
}
/**
* 生成出库流水写入明细,优先按拣货分配逐条记录。
*
* @param {Object} options 参数集合。
* @param {number} options.outboundQty 本次出库总数量。
* @param {Array<Object>} options.pickingRows 拣货分配记录。
* @param {Object} options.basePayload 流水公共字段。
* @return {Array<Object>} 待写入的出库流水列表。
*/
buildOutboundTransactionPayloads({ outboundQty, pickingRows, basePayload }) {
const payloads = [];
const normalizedRows = Array.isArray(pickingRows) ? pickingRows : [];
let consumedQty = 0;
for (const pickingRow of normalizedRows) {
const remainingQty = outboundQty - consumedQty;
if (remainingQty <= 0) {
break;
}
const pickingQty = Number(pickingRow && pickingRow.quantity) || 0;
if (pickingQty <= 0) {
continue;
}
const transactionQty = Math.min(pickingQty, remainingQty);
payloads.push({
...basePayload,
storage_id: pickingRow && pickingRow.storage_id ? Number(pickingRow.storage_id) : null,
space_id: pickingRow && pickingRow.space_id ? Number(pickingRow.space_id) : null,
quantity: transactionQty,
});
consumedQty += transactionQty;
}
if (payloads.length === 0) {
return [{
...basePayload,
storage_id: null,
space_id: null,
quantity: outboundQty,
}];
}
if (consumedQty < outboundQty) {
payloads.push({
...basePayload,
storage_id: null,
space_id: null,
quantity: outboundQty - consumedQty,
});
}
return payloads;
}
/**
* 商品出库服务
* @param {number} itemId 商品ID (StockStore.id)
* @param {number} quantity 出库数量(正数)
* @param {Object} transaction 数据库事务
* @param {Object} meta 出库元信息(订单、明细等)
*/
async outbound(itemId, quantity, transaction, meta = {}) {
const {
ctx,
app,
} = this;
const outboundMeta = this.normalizeOutboundMeta(meta);
// 1. 参数验证
const outboundQty = parseInt(quantity);
if (!itemId || outboundQty <= 0) {
return {
success: false,
error: `出库参数无效: itemId=${itemId}, quantity=${quantity}`,
data: null,
};
}
try {
return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => {
// 2. 获取商品和库存信息(复用)
const stockResult = await this.getItemStorages(itemId, currentTransaction);
if (!stockResult.success) {
if (hasExternalTransaction) {
throw new Error(stockResult.error);
}
return stockResult;
}
const { storage } = stockResult.data;
// 3. 检查库存是否足够出库
if (!storage.exists) {
const failureResult = {
success: false,
error: '库存记录不存在,无法出库',
data: null,
};
if (hasExternalTransaction) {
throw new Error(failureResult.error);
}
return failureResult;
}
const beforeQuantity = Number(storage.quantity) || 0;
const beforeLockedQuantity = Number(storage.lockedQuantity) || 0;
const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(storage.id, currentTransaction);
const allowOversell = policyConfig.allowOversell === true;
// 关键检查:总库存是否足够,启用超卖时放行负库存结果
if (beforeQuantity < outboundQty && !allowOversell) {
const failureResult = {
success: false,
error: `总库存不足,当前 ${beforeQuantity},需求 ${outboundQty}`,
data: null,
};
if (hasExternalTransaction) {
throw new Error(failureResult.error);
}
return failureResult;
}
// 关键检查:锁定库存是否足够扣减
if (beforeLockedQuantity < outboundQty) {
const failureResult = {
success: false,
error: `锁定库存不足,已锁定 ${beforeLockedQuantity},需求 ${outboundQty}`,
data: null,
};
if (hasExternalTransaction) {
throw new Error(failureResult.error);
}
return failureResult;
}
// 4. 执行出库扣减(同时减少quantity和locked_quantity)
const result = await ctx.model.StockWarehouse.update({
quantity: app.Sequelize.literal(`quantity - ${outboundQty}`),
locked_quantity: app.Sequelize.literal(`locked_quantity - ${outboundQty}`),
update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'),
}, {
where: {
id: storage.id,
is_valid: 'Y',
deleted_at: null,
locked_quantity: {
[app.Sequelize.Op.gte]: outboundQty,
},
},
transaction: currentTransaction,
});
if (result[0] === 0) {
const failureResult = {
success: false,
error: '出库失败:库存已被其他操作修改',
data: null,
};
if (hasExternalTransaction) {
throw new Error(failureResult.error);
}
return failureResult;
}
// 5. 获取更新后的数据
const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, {
transaction: currentTransaction,
raw: true,
});
const afterQuantity = Number(updatedRecord.quantity) || 0;
const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0;
let pickingRows = [];
if (outboundMeta.orderId && outboundMeta.orderItemId) {
try {
pickingRows = await this.getPickingRowsForOutbound(outboundMeta.orderId, outboundMeta.orderItemId, currentTransaction);
} catch (error) {
app.logger.warn(`[outbound] 读取拣货分配失败,降级为单条出库流水: ${error.message}`);
}
}
const baseTransactionPayload = {
transaction_type: 'OUTBOUND',
warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id,
store_id: storage.storeId || updatedRecord.store_id || ctx.user.store_id,
stock_id: storage.id,
batch_no: null,
inventory_type: 'ZP',
order_type: 'STOCK_STORE_OUTBOUND',
order_no: outboundMeta.orderNo,
order_id: outboundMeta.orderId,
source_order_codes: outboundMeta.sourceOrderCodes,
receiving_id: null,
entry_order_id: null,
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(),
};
const transactionPayloads = this.buildOutboundTransactionPayloads({
outboundQty,
pickingRows,
basePayload: baseTransactionPayload,
});
for (const payload of transactionPayloads) {
await ctx.service.systems.stockTransaction.create(payload, {
transaction: currentTransaction,
});
}
app.logger.info('[出库] 成功', {
itemId,
stockId: storage.id,
quantity: outboundQty,
beforeQuantity,
afterQuantity,
beforeLocked: beforeLockedQuantity,
afterLocked: afterLockedQuantity,
});
await this.clearItemStorageCache(itemId);
return {
success: true,
data: {
itemId,
stockId: storage.id,
action: 'outbound',
quantity: outboundQty,
beforeQuantity,
afterQuantity,
beforeLocked: beforeLockedQuantity,
afterLocked: afterLockedQuantity,
available: afterQuantity - afterLockedQuantity,
updatedAt: updatedRecord.update_at,
},
error: null,
};
});
} catch (error) {
if (transaction) {
throw error;
}
app.logger.error('[outbound] 出库失败', {
itemId,
quantity,
error: error.message,
stack: error.stack,
});
return {
success: false,
error: `出库系统错误: ${error.message}`,
data: null,
};
}
}
async checkAndCreateWarehouseStock(sourceData, warehouseId) {
const {
ctx,
app,
service,
} = this;
try {
// 1. 参数验证
if (!sourceData || !sourceData.item_code) {
return {
success: false,
id: null,
message: '缺少必要参数: item_code',
};
}
if (!warehouseId) {
return {
success: false,
id: null,
message: '缺少必要参数: warehouseId',
};
}
// 2. 检查记录是否存在
const existingRecord = await ctx.model.StockWarehouse.findOne({
where: {
item_code: sourceData.item_code,
warehouse_id: warehouseId,
store_id: sourceData.store_id,
deleted_at: null,
},
attributes: [ 'id' ],
raw: true,
});
// 3. 如果存在,直接返回ID
if (existingRecord) {
app.logger.debug(
`[库存记录已存在] item_code: ${sourceData.item_code}, warehouse_id: ${warehouseId}`
);
return {
success: true,
id: existingRecord.id,
message: '库存记录已存在',
exists: true,
};
}
// 4. 准备创建数据
const now = new Date();
const stockData = {
// 唯一约束字段
item_code: sourceData.item_code,
goods_code: sourceData.goods_code,
warehouse_id: warehouseId,
// 商品基本信息
store_id: sourceData.store_id || 0,
item_name: sourceData.item_name || '',
sku_property: sourceData.sku_property || '',
stock_unit: sourceData.stock_unit || '个', // 提供默认值
item_type: sourceData.item_type || 'ZC',
// 规格信息
length: parseFloat(sourceData.length) || 0,
width: parseFloat(sourceData.width) || 0,
height: parseFloat(sourceData.height) || 0,
volume: parseFloat(sourceData.volume) || 0,
gross_weight: parseFloat(sourceData.gross_weight) || 0,
net_weight: parseFloat(sourceData.net_weight) || 0,
// 价格信息
tag_price: parseFloat(sourceData.tag_price) || 0,
retail_price: parseFloat(sourceData.retail_price) || 0,
brand_name: sourceData.brand_name || null,
// 管理属性
is_sn_mgmt: sourceData.is_sn_mgmt === 'Y' ? 'Y' : 'N',
is_shelf_life_mgmt: sourceData.is_shelf_life_mgmt === 'Y' ? 'Y' : 'N',
is_batch_mgmt: sourceData.is_batch_mgmt === 'Y' ? 'Y' : 'N',
// 其他字段
packing_requirements: sourceData.packing_requirements || '',
create_at: now,
update_at: now,
is_valid: 'Y',
level: 'C',
quantity: parseInt(sourceData.quantity) || 0,
locked_quantity: parseInt(sourceData.locked_quantity) || 0,
deleted_at: null,
};
// 5. 创建记录(处理可能的重复插入)
let createdRecord;
try {
createdRecord = await ctx.model.StockWarehouse.create(stockData);
const barcodes = sourceData.barcode.split(';');
const existingFileIds = [];
const toCreate = barcodes.filter(item => !existingFileIds.includes(item));
// 批量操作
const promises = [];
if (toCreate.length > 0) {
const refData = toCreate.map(item => ({
stock_id: createdRecord.id,
barcode: item,
warehouse_id: warehouseId,
created_at: new Date(),
}));
promises.push(ctx.model.StockBarcode.bulkCreate(refData));
await Promise.all(promises);
}
await service.systems.operationLog.createOperationLog({
businessType: 'stock',
businessId: createdRecord.id,
operationCode: 'CREATE',
operator: {
id: null,
name: '奇门',
},
extras: {
warehouseId,
externalLogType: 'QIMEN',
externalLogId: this.ctx.qimenLogId,
},
beforeChanges: null,
});
} catch (createError) {
// 如果是唯一约束冲突,说明在创建过程中其他请求已经创建了
if (createError.name === 'SequelizeUniqueConstraintError') {
app.logger.warn(
`[库存记录并发创建] item_code: ${sourceData.item_code}, warehouse_id: ${warehouseId}`
);
// 重新查询一次
const retryRecord = await ctx.model.StockWarehouse.findOne({
where: {
item_code: sourceData.item_code,
goods_code: sourceData.goods_code,
warehouse_id: warehouseId,
is_valid: 'Y',
},
attributes: [ 'id' ],
raw: true,
});
if (retryRecord) {
return {
success: true,
id: retryRecord.id,
message: '库存记录并发创建成功',
exists: true,
};
}
}
throw createError;
}
app.logger.debug(`[库存记录创建成功] id: ${createdRecord.id}, item_code: ${sourceData.item_code}`);
return {
success: true,
id: createdRecord.id,
message: '库存记录创建成功',
exists: false,
};
} catch (error) {
app.logger.error('[checkAndCreateStock] 系统异常', {
sourceData,
warehouseId,
error: error.message,
stack: error.stack,
});
return {
success: false,
id: null,
message: `库存记录操作失败: ${error.message}`,
error,
};
}
}
/**
* 获取仓库库存列表(支持分页和动态查询条件)
* @param {Object} where - 查询条件对象
* @param {Object} pageParams - 分页参数
* @param {number} pageParams.page - 当前页码,默认1
* @param {number} pageParams.pageSize - 每页条数,默认20
* @param {Object} sortParams - 排序参数
* @param {string} sortParams.sortField - 排序字段,默认'create_at'
* @param {string} sortParams.sortOrder - 排序方式,默认'DESC'
* @return {Promise<Object>} 返回查询结果
*/
async getWarehouseStock(where, pageParams = {}, sortParams = {}) {
const {
ctx,
app,
} = this;
const {
Sequelize,
} = app;
const {
Op,
} = Sequelize;
try {
// 设置默认参数
const {
page = 1,
pageSize = 20,
} = pageParams;
const {
sortField = 'id',
sortOrder = 'DESC',
} = sortParams;
// 构建基础查询条件
const queryOptions = {
where: {},
order: [],
attributes: {
exclude: [ 'deleted_at' ],
},
};
const barcodeQueryOptions = {
where: {},
};
const prohibitedQueryOptions = {
where: {},
};
// 添加默认条件
queryOptions.where[Op.and] = [{
warehouse_id: ctx.user.store_id,
},
{
is_valid: 'Y',
},
{
deleted_at: null,
},
];
barcodeQueryOptions.where[Op.and] = [];
prohibitedQueryOptions.where[Op.and] = [];
// 检测并处理条码查询条件
let hasBarcodeCondition = false;
let hasProhibitedCondition = false;
let barcodeCondition = null;
let parsedBarcodeInput = null;
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
? ctx.where
: (where && typeof where === 'object' ? where : {});
// 处理动态查询条件
if (normalizedWhere && Object.keys(normalizedWhere).length > 0) {
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
barcode: {
bucket: 'barcode',
},
prohibited_type: {
bucket: 'prohibited',
field: 'id',
},
},
});
if (!parsed.ok) {
return {
code: 400,
data: {
list: [],
pagination: {
page: parseInt(page),
pageSize: parseInt(pageSize),
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total_quantity: 0,
total_locked: 0,
total_available: 0,
total_items: 0,
},
},
message: `筛选条件解析失败: ${parsed.reason}`,
};
}
parsedResult = parsed.result;
}
const {
dynamicConditions,
bucketConditions,
bucketFlags,
rawConditionsByField,
} = parsedResult;
const barcodeDynamicConditions = bucketConditions.barcode || [];
const prohibitedConditions = bucketConditions.prohibited || [];
hasBarcodeCondition = Boolean(bucketFlags.barcode);
hasProhibitedCondition = Boolean(bucketFlags.prohibited);
barcodeCondition = barcodeDynamicConditions[0] || null;
parsedBarcodeInput = rawConditionsByField.barcode || null;
if (dynamicConditions.length > 0) {
queryOptions.where[Op.and].push({
[Op.and]: dynamicConditions,
});
}
if (barcodeDynamicConditions.length > 0) {
barcodeQueryOptions.where[Op.and].push({
[Op.and]: barcodeDynamicConditions,
});
}
if (prohibitedConditions.length > 0) {
prohibitedQueryOptions.where[Op.and].push({
[Op.and]: prohibitedConditions,
});
}
}
// 如果有条码查询条件,先查询匹配的库存ID
let matchedStockIds = [];
if (hasBarcodeCondition && barcodeCondition) {
// 从条码条件中提取条码值,构建条码查询
let barcodeValues = [];
// 根据不同的条件格式提取条码值
if (parsedBarcodeInput && parsedBarcodeInput.value) {
if (Array.isArray(parsedBarcodeInput.value)) {
barcodeValues = parsedBarcodeInput.value;
} else if (typeof parsedBarcodeInput.value === 'string') {
barcodeValues = [ parsedBarcodeInput.value ];
}
}
if (barcodeValues.length > 0) {
// 构建条码查询条件
const barcodeWhere = {};
const barcodeOperator = String(parsedBarcodeInput.operator || 'like').toLowerCase();
if (barcodeOperator === 'eq') {
// 精确查询
if (barcodeValues.length === 1) {
barcodeWhere.barcode = barcodeValues[0];
} else {
barcodeWhere.barcode = {
[Op.in]: barcodeValues,
};
}
} else if (barcodeOperator === 'like') {
// 模糊查询
if (barcodeValues.length === 1) {
barcodeWhere.barcode = {
[Op.like]: `%${barcodeValues[0]}%`,
};
} else {
const likeConditions = barcodeValues.map(value => ({
barcode: {
[Op.like]: `%${value}%`,
},
}));
barcodeWhere[Op.or] = likeConditions;
}
} else {
// 默认模糊查询
barcodeWhere.barcode = {
[Op.like]: `%${barcodeValues[0]}%`,
};
}
// 查询匹配的条码,获取库存ID
const matchedBarcodes = await ctx.model.StockBarcode.findAll({
...barcodeQueryOptions,
attributes: [ 'stock_id' ],
group: [ 'stock_id' ], // 使用 GROUP BY 去重
raw: true,
});
matchedStockIds = matchedBarcodes.map(b => b.stock_id);
// 如果没有匹配的条码,直接返回空结果
if (matchedStockIds.length === 0) {
return {
code: 200,
data: {
list: [],
pagination: {
page: parseInt(page),
pageSize: parseInt(pageSize),
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total_quantity: 0,
total_locked: 0,
total_available: 0,
total_items: 0,
},
},
message: '查询成功',
};
}
// 将库存ID条件合并到主查询条件中
queryOptions.where[Op.and].push({
id: {
[Op.in]: matchedStockIds,
},
});
}
}
// 处理排序
const validSortFields = [
'id', 'item_code', 'item_name', 'quantity', 'locked_quantity',
'tag_price', 'retail_price', 'create_at', 'update_at',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at';
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
queryOptions.order.push([ actualSortField, actualSortOrder ]);
// 计算分页偏移量
const offset = (page - 1) * pageSize;
// 执行查询:获取总数和数据
const [ total, data ] = await Promise.all([
// 获取总数
ctx.model.StockWarehouse.count({
where: queryOptions.where,
include: [ ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId: ctx.user.store_id,
required: true,
attributes: [ 'store_remask' ],
}), {
...prohibitedQueryOptions,
model: ctx.model.ProhibitedType,
as: 'prohibited',
attributes: [ 'type_name' ],
required: hasProhibitedCondition,
}],
distinct: true,
}),
// 获取分页数据
ctx.model.StockWarehouse.findAll({
...queryOptions,
include: [ ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId: ctx.user.store_id,
required: true,
attributes: [ 'store_remask' ],
}), {
...prohibitedQueryOptions,
model: ctx.model.ProhibitedType,
as: 'prohibited',
attributes: [ 'type_name' ],
required: hasProhibitedCondition,
}],
limit: parseInt(pageSize),
offset: parseInt(offset),
distinct: true, // 确保去重
raw: true,
}),
]);
// 计算分页信息
const totalPages = Math.ceil(total / pageSize);
const hasPrevious = page > 1;
const hasNext = page < totalPages;
// 批量查询条码信息
const stockIds = data.map(item => item.id);
let barcodes = [];
let images = [];
if (stockIds.length > 0) {
barcodes = await ctx.model.StockBarcode.findAll({
where: {
stock_id: {
[Op.in]: stockIds,
},
},
raw: true,
});
images = await ctx.model.FileReference.findAll({
where: {
business_type: 'stock',
business_id: {
[Op.in]: stockIds,
},
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
}],
});
}
// 处理数据,添加一些计算字段
const processedData = data.map(item => {
const availableQuantity = Math.max(0, item.quantity - item.locked_quantity);
const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed(
2) : 0;
// 过滤该商品的条码
const itemBarcodes = barcodes
.filter(barcode => barcode.stock_id === item.id)
.map(barcode => barcode.barcode);
const itemImages = images
.filter(images => parseInt(images.business_id) === item.id)
.map(images => images.file.file_url);
return {
...item,
barcodes: itemBarcodes,
images: itemImages,
available_quantity: availableQuantity,
lock_rate: parseFloat(lockRate),
lock_rate_display: `${lockRate}%`,
create_at_display: item.create_at ? this.formatDate(item.create_at) : '',
update_at_display: item.update_at ? this.formatDate(item.update_at) : '',
// 标记是否通过条码查询匹配
is_barcode_matched: hasBarcodeCondition && matchedStockIds.includes(item.id),
};
});
// 添加汇总信息
const summary = {
total_quantity: data.reduce((sum, item) => sum + item.quantity, 0),
total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0),
total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item
.locked_quantity), 0),
total_items: data.length,
// 如果有条码查询,添加匹配统计
...(hasBarcodeCondition && {
barcode_matched_count: matchedStockIds.length,
barcode_search_value: parsedBarcodeInput ? parsedBarcodeInput.value : null,
}),
};
return {
code: 200,
data: {
list: processedData,
pagination: {
page: parseInt(page),
pageSize: parseInt(pageSize),
total,
totalPages,
hasPrevious,
hasNext,
},
summary,
queryInfo: {
conditions: normalizedWhere,
sortField: actualSortField,
sortOrder: actualSortOrder,
hasBarcodeSearch: hasBarcodeCondition,
},
},
message: '查询成功',
};
} catch (error) {
ctx.logger.error('[StockService.getWarehouseStock] 查询失败:', error);
return {
code: 500,
data: {
list: [],
pagination: {
page: parseInt(pageParams.page || 1),
pageSize: parseInt(pageParams.pageSize || 20),
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total_quantity: 0,
total_locked: 0,
total_available: 0,
total_items: 0,
},
},
message: `查询失败: ${error.message}`,
};
}
}
/**
* 构建Sequelize查询条件
* @param {string} fieldKey - 字段键名
* @param {Object} condition - 条件对象
* @param {Object} app - Egg应用实例
* @return {Object|null} Sequelize条件对象
*/
buildSequelizeCondition(fieldKey, condition, app) {
const parsed = buildSequelizeConditionUtil(fieldKey, condition, app);
if (!parsed.ok) {
return null;
}
return parsed.condition;
}
/**
* 处理条件值
* @param {any} value - 原始值
* @param {string} type - 字段类型
* @return {any} 处理后的值
*/
processConditionValue(value, type) {
return processConditionValueUtil(value, type);
}
normalizeDate(value) {
return normalizeDateUtil(value);
}
/**
* 格式化日期显示
* @param {string} dateString - 日期字符串
* @return {string} 格式化后的日期
*/
formatDate(dateString) {
if (!dateString) return '';
const date = new Date(dateString);
if (isNaN(date.getTime())) return dateString;
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
});
}
/**
* 判断值是否为空
* @param {any} value - 要判断的值
* @return {boolean} 是否为空
*/
isEmptyValue(value) {
return isEmptyValueUtil(value);
}
async getProhibitedType() {
const {
ctx,
app,
} = this;
const {
Op,
} = app.Sequelize;
// 从用户信息获取仓库ID
const warehouseId = ctx.user.store_id;
// 查询系统预设分类和当前仓库专有分类
const types = await ctx.model.ProhibitedType.findAll({
where: {
[Op.or]: [{
warehouse_id: null,
}, // 系统预设
{
warehouse_id: warehouseId,
}, // 当前仓库专有
],
},
order: [
[ 'warehouse_id', 'ASC' ], // 系统预设在前(warehouse_id为null)
[ 'sort_order', 'ASC' ], // 按排序字段
[ 'created_at', 'ASC' ], // 按创建时间
],
attributes: [
'id',
'type_name',
'warehouse_id',
'is_system_preset',
'sort_order',
],
});
// 转换为前端需要的格式 {value: id, label: type_name}
const result = types.map(item => ({
value: item.id,
label: item.type_name,
warehouse_id: item.warehouse_id,
is_system_preset: item.is_system_preset,
sort_order: item.sort_order,
}));
return result;
}
async getBarcodes(data) {
const {
ctx,
} = this;
const {
id,
} = data;
const warehouseId = ctx.user.store_id;
const barcodes = await ctx.model.StockBarcode.findAll({
where: {
stock_id: id,
},
attributes: [
'barcode',
],
include: [{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'id' ],
where: {
warehouse_id: warehouseId,
},
required: true,
}],
raw: true,
});
return barcodes;
}
async handleBatchChange() {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit' ];
const { ids, method, value } = ctx.request.body;
try {
// 1. 参数验证
if (!ids || !Array.isArray(ids) || ids.length === 0) {
return { message: '请选择要修改的商品', code: 405 };
}
if (!method || !canChangeFlide.includes(method)) {
return { message: `不支持修改的字段: ${method}`, code: 405 };
}
if (value === undefined || value === null) {
return { message: '修改值不能为空', code: 405 };
}
// 2. 获取仓库ID
const warehouseId = ctx.user.store_id;
if (!warehouseId) {
return { message: '缺少仓库信息', code: 405 };
}
// 3. 验证要修改的记录是否存在且属于当前仓库
const existingRefs = await ctx.model.StockWarehouse.findAll({
where: {
id: { [Op.in]: ids },
warehouse_id: warehouseId,
delete_at: null,
},
attributes: [ 'id' ],
});
if (existingRefs.length !== ids.length) {
const existingIds = existingRefs.map(item => item.id);
const notExistIds = ids.filter(id => !existingIds.includes(id));
return {
message: `部分商品不存在或无权修改: ${notExistIds.join(',')}`,
code: 405,
};
}
// 4. 根据字段类型处理值
let updateData = {};
if (method === 'prohibited_id') {
// 违禁品类型应该是数字
const updateValue = parseInt(value, 10);
if (isNaN(updateValue)) {
return { message: '违禁品类型必须是数字', code: 405 };
}
updateData = {
prohibited_id: updateValue,
update_at: new Date(),
update_by: ctx.user.id || ctx.user.username,
};
} else if (method === 'gross_weight') {
// 毛重应该是数字
const updateValue = parseFloat(value);
if (isNaN(updateValue) || updateValue < 0) {
return { message: '毛重必须是有效的正数', code: 405 };
}
updateData = {
gross_weight: updateValue,
update_at: new Date(),
update_by: ctx.user.id || ctx.user.username,
};
} else if (method === 'managementFlags') {
// 管理标识是对象格式,需要更新三个独立字段
if (typeof value !== 'object') {
return { message: '管理标识必须是对象格式', code: 405 };
}
// 验证三个管理标识字段
const managementFields = [ 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt' ];
updateData = {
update_at: new Date(),
update_by: ctx.user.id || ctx.user.username,
};
for (const field of managementFields) {
if (value[field] === undefined) {
return { message: `管理标识缺少 ${field} 字段`, code: 405 };
}
if (![ 'Y', 'N' ].includes(value[field])) {
return { message: `管理标识 ${field} 的值必须是 Y 或 N`, code: 405 };
}
updateData[field] = value[field];
}
} else {
// 品牌名称和打包要求验证
if (typeof value !== 'string') {
return { message: `${method} 必须是字符串`, code: 405 };
}
if (value.length > 255) {
return { message: `${method} 不能超过255个字符`, code: 405 };
}
updateData = {
[method]: value,
update_at: new Date(),
update_by: ctx.user.id || ctx.user.username,
};
}
// 5. 执行批量更新
const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, {
where: {
id: { [Op.in]: ids },
warehouse_id: warehouseId,
delete_at: null,
},
});
return {
message: `成功修改 ${affectedRows} 条记录`,
code: 200,
data: {
affectedRows,
ids,
},
};
} catch (error) {
ctx.logger.error('批量修改失败:', error);
console.error('批量修改错误:', error);
return {
message: error.message || '批量修改失败',
code: 500,
};
}
}
async saveWarehouseStockBarcode(data) {
const {
ctx, service,
} = this;
const {
id,
barcodes,
} = data;
const warehouseId = ctx.user.store_id;
// 获取现有的file_id
const existingRefs = await ctx.model.StockBarcode.findAll({
where: {
stock_id: id,
warehouse_id: warehouseId,
},
});
const existingFileIds = existingRefs.map(item => item.barcode);
const newFileIds = barcodes.map(item => item);
// 需要删除的ID
const toDeleteIds = existingFileIds.filter(barcode => !newFileIds.includes(barcode));
// 需要创建的记录
const toCreate = barcodes.filter(item => !existingFileIds.includes(item));
// 批量操作
const promises = [];
if (toDeleteIds.length > 0) {
promises.push(
ctx.model.StockBarcode.destroy({
where: {
stock_id: id,
barcode: toDeleteIds,
warehouse_id: warehouseId,
},
})
);
}
if (toCreate.length > 0) {
const refData = toCreate.map(item => ({
stock_id: id,
barcode: item,
warehouse_id: warehouseId,
created_at: new Date(),
}));
promises.push(ctx.model.StockBarcode.bulkCreate(refData));
}
await Promise.all(promises);
await service.systems.operationLog.createOperationLog({
businessType: 'stock',
businessId: id,
operationCode: 'UPDATE_BARCODE',
operator: {
id: ctx.user.id,
name: ctx.user.employees_name,
},
beforeChanges: null,
extras: {
warehouseId,
},
});
return {
success: true,
};
}
async getStoreStocks(data) {
const {
app,
} = this;
const {
Sequelize,
} = app;
const {
Op,
} = Sequelize;
const {
ctx,
} = this;
const {
stock_id = null, store_id = null, page = 1, pageSize = 20, item_code = '', item_name = '',
} = data || {};
const warehouseId = ctx.user.store_id;
let barcodes = [];
let warehouseStock = null;
let total = 0;
if (stock_id) {
barcodes = await ctx.model.StockStore.findAll({
where: {
stock_id,
},
attributes: [
'item_code', 'item_name', 'app_key', 'create_from', 'id',
],
include: [{
model: ctx.model.StockWarehouse,
as: 'warehouse_stock',
attributes: [ 'id', 'store_id' ],
where: {
warehouse_id: warehouseId,
},
required: true,
}],
raw: true,
});
warehouseStock = await ctx.model.StockWarehouse.findOne({
where: {
id: stock_id,
},
attributes: [
'store_id',
],
});
} else {
const StockWarehouseWhere = {
warehouse_id: warehouseId,
};
const StockStoreWhere = {};
if (store_id) {
StockWarehouseWhere.store_id = store_id;
}
if (item_code) {
const processedValue = item_code.split(',');
const likeConditions = processedValue.map(value => ({
item_code: {
[Op.like]: `%${value}%`,
},
}));
StockStoreWhere[Op.or] = likeConditions;
}
if (item_name) {
const processedValue = item_name.split(',');
const likeConditions = processedValue.map(value => ({
item_name: {
[Op.like]: `%${value}%`,
},
}));
StockStoreWhere[Op.or] = likeConditions;
}
const offset = (page - 1) * pageSize;
[ total, barcodes ] = await Promise.all([
ctx.model.StockStore.count({
where: StockStoreWhere,
attributes: [
'item_code', 'item_name', 'app_key', 'create_from', 'id', 'stock_id',
],
include: [{
model: ctx.model.StockWarehouse,
as: 'warehouse_stock',
attributes: [ 'id' ],
where: StockWarehouseWhere,
required: false,
}],
limit: parseInt(pageSize),
offset: parseInt(offset),
raw: true,
}),
ctx.model.StockStore.findAll({
where: StockStoreWhere,
attributes: [
'item_code', 'item_name', 'app_key', 'create_from', 'id', 'stock_id',
],
include: [{
model: ctx.model.StockWarehouse,
as: 'warehouse_stock',
attributes: [ 'id' ],
where: StockWarehouseWhere,
required: false,
}],
limit: parseInt(pageSize),
offset: parseInt(offset),
raw: true,
}),
]);
}
const results = barcodes.map(item => {
return {
app_key: item.app_key,
create_from: item.create_from === 'qimen' ? '奇门' : 'API',
id: item.id,
app_name: item.app_key,
item_code: item.item_code,
stock_id: item['warehouse_stock.id'],
hasBind: !!item.stock_id,
item_name: item.item_name,
};
});
const get_store_id = warehouseStock ? warehouseStock.store_id : barcodes[0]['warehouse_stock.store_id'];
return {
rows: results,
store_id: get_store_id,
total,
};
}
async bindItem(data) {
const {
ctx,
app,
} = this;
const {
id,
warehouse_stock,
} = data;
const warehouseId = ctx.user.store_id;
try {
const storeStock = await ctx.model.StockStore.findOne({
where: {
warehouse_id: warehouseId,
deleted_at: null,
id,
},
attributes: [
'stock_id',
'store_id',
],
});
if (!storeStock) {
throw new Error('外部商品不存在');
}
const warehouseStock = await ctx.model.StockWarehouse.findOne({
where: {
warehouse_id: warehouseId,
deleted_at: null,
id: warehouse_stock,
},
attributes: [
'store_id',
],
});
if (!warehouseStock) {
throw new Error('仓库商品不存在');
}
if (warehouseStock.store_id !== storeStock.store_id) {
throw new Error('仓库商品和外部商品不是同一个货主,刷新再试');
}
await app.model.StockStore.update({
stock_id: warehouse_stock,
}, {
where: {
id,
},
});
return 1;
} catch (e) {
throw e;
}
}
async unbindItem(data) {
const {
ctx,
app,
} = this;
const {
id,
} = data;
const warehouseId = ctx.user.store_id;
try {
const storeStock = await ctx.model.StockStore.findOne({
where: {
warehouse_id: warehouseId,
deleted_at: null,
id,
},
attributes: [
'stock_id',
'store_id',
],
});
if (!storeStock) {
throw new Error('外部商品不存在');
}
await app.model.StockStore.update({
stock_id: null,
}, {
where: {
id,
},
});
return 1;
} catch (e) {
throw e;
}
}
/**
* 获取仓库商品详情。
*
* @param {object} data - 查询参数。
* @param {number|string} data.id - 商品 ID。
* @return {Promise<object|null>} 商品详情。
*/
/**
* 查询库存商品详情。
*
* @param {Object} data 请求参数。
* @param {number|string} data.id 库存商品 ID。
* @return {Promise<Object|null>} 库存商品详情。
*/
async getInfo(data) {
const {
ctx,
} = this;
const {
id,
} = data;
const warehouseId = ctx.user.store_id;
const stock = await ctx.model.StockWarehouse.findOne({
where: {
warehouse_id: warehouseId,
deleted_at: null,
id,
},
attributes: [
'gross_weight',
'height',
'id',
'is_batch_mgmt',
'is_shelf_life_mgmt',
'is_sn_mgmt',
'item_code',
'item_name',
'length',
'net_weight',
'packing_requirements',
'prohibited_id',
'retail_price',
'sku_property',
'stock_unit',
'tag_price',
'brand_name',
'volume',
'width',
'enable_box_spec',
'quantity_per_box',
'box_gross_weight',
'box_net_weight',
'box_length',
'box_width',
'box_height',
'box_volume',
'inbound_min_days',
'outbound_min_days',
'remaining_threshold_days',
'shelf_life_days',
'store_id',
],
raw: true,
});
stock.enable_box_spec = !!stock.enable_box_spec;
return stock;
}
/**
* 更新仓库商品资料,并在启用保质期管理时校验保质期相关字段。
*
* @param {Object} data 请求体,包含商品主键及待更新字段。
* @return {Promise<Object>} 返回更新后的商品详情。
*/
async saveWarehouseStock(data) {
const { ctx, service } = this;
const warehouseId = ctx.user.store_id;
const {
item_code, item_name, sku_property, stock_unit,
packing_requirements, length, width, height, volume,
gross_weight, net_weight, tag_price, retail_price,
is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt,
prohibited_id, brand_name, managementFlags,
enable_box_spec, box_unit, quantity_per_box,
box_gross_weight, box_net_weight, box_length,
box_width, box_height, box_volume, box_remark, id,
shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days,
} = data;
const prohibited_id_tmp = !prohibited_id ? null : parseInt(prohibited_id);
// 1. 参数验证
this.validateSaveParams(data);
if (is_shelf_life_mgmt === 'Y') {
const shelfLifeFields = [
[ 'shelf_life_days', shelf_life_days ],
[ 'inbound_min_days', inbound_min_days ],
[ 'outbound_min_days', outbound_min_days ],
[ 'remaining_threshold_days', remaining_threshold_days ],
];
const invalidShelfLifeFields = shelfLifeFields.filter(item => Number(item[1]) <= 0);
if (invalidShelfLifeFields.length > 0) {
throw new Error('启用保质期管理时,shelf_life_days、inbound_min_days、outbound_min_days、remaining_threshold_days 都必须存在且大于 0');
}
}
let transaction;
try {
// 2. 开启事务
transaction = await ctx.model.transaction();
// 3. 查询商品是否存在
const stock_info = await ctx.model.StockWarehouse.findOne({
where: {
id,
deleted_at: null,
warehouse_id: ctx.user.store_id,
},
transaction,
});
if (!stock_info) {
throw new Error('商品不存在');
}
const hasInputItemCode = Object.prototype.hasOwnProperty.call(data, 'item_code');
if (hasInputItemCode) {
const itemCodeUniqueResult = await this.checkItemCodeUnique(
id,
item_code,
stock_info.store_id,
stock_info.warehouse_id
);
if (!itemCodeUniqueResult || !itemCodeUniqueResult.isUnique) {
throw new Error('商品编码已存在,请检查后重试');
}
}
// 4. 准备更新数据
const updateData = {
item_code,
item_name,
sku_property,
stock_unit,
packing_requirements,
length,
width,
height,
volume,
gross_weight,
net_weight,
tag_price,
retail_price,
enable_box_spec: enable_box_spec ? 1 : 0,
is_sn_mgmt: is_sn_mgmt || false,
is_shelf_life_mgmt: is_shelf_life_mgmt || false,
is_batch_mgmt: is_batch_mgmt || false,
prohibited_id: prohibited_id_tmp,
brand_name,
...(managementFlags && { management_flags: managementFlags }),
box_unit,
quantity_per_box,
box_gross_weight,
box_net_weight,
box_length,
box_width,
box_height,
box_volume,
box_remark,
shelf_life_days,
inbound_min_days,
outbound_min_days,
remaining_threshold_days,
updated_at: new Date(),
};
// 5. 清除空值
Object.keys(updateData).forEach(key => {
if (key !== 'prohibited_id' && (updateData[key] === undefined || updateData[key] === null)) {
delete updateData[key];
}
});
// 6. 执行更新
await ctx.model.StockWarehouse.update(updateData, {
where: {
id,
warehouse_id: ctx.user.store_id,
deleted_at: null,
},
transaction,
});
await service.systems.operationLog.createOperationLog({
businessType: 'stock',
businessId: id,
operationCode: 'UPDATE',
operator: {
id: ctx.user.id,
name: ctx.user.employees_name,
},
beforeChanges: stock_info,
extras: {
warehouseId,
},
});
// 7. 提交事务
await transaction.commit();
// 8. 返回更新后的数据
return await this.getInfo({ id });
} catch (error) {
// 9. 回滚事务
if (transaction) {
await transaction.rollback();
}
ctx.logger.error('saveWarehouseStock error:', error);
// 根据错误类型返回更友好的错误信息
if (error.name === 'SequelizeValidationError') {
throw new Error(`数据验证失败: ${error.errors.map(e => e.message).join(', ')}`);
}
throw error;
}
}
async createWarehouseStock(data) {
const { ctx, service } = this;
const warehouseId = ctx.user.store_id;
const {
item_code, store_id, item_name, sku_property, stock_unit,
packing_requirements, length, width, height, volume,
gross_weight, net_weight, tag_price, retail_price,
is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt,
prohibited_id, brand_name, managementFlags,
enable_box_spec, box_unit, quantity_per_box,
box_gross_weight, box_net_weight, box_length,
box_width, box_height, box_volume, box_remark, barcode,
} = data;
// 1. 参数验证
this.validateSaveParams(data, false);
let checkItemCodeUnique = {};
try {
checkItemCodeUnique = await this.checkItemCodeUnique(null, item_code, store_id, warehouseId);
} catch (e) {
throw (e);
}
if (checkItemCodeUnique && !checkItemCodeUnique.isUnique) {
throw (new Error('创建失败,商品编码已被使用'));
}
const insertData = {
item_code,
item_name,
sku_property,
stock_unit,
packing_requirements,
length,
width,
height,
volume,
gross_weight,
net_weight,
tag_price,
retail_price,
warehouse_id: warehouseId,
enable_box_spec: enable_box_spec ? 1 : 0,
is_sn_mgmt: is_sn_mgmt || false,
is_shelf_life_mgmt: is_shelf_life_mgmt || false,
is_batch_mgmt: is_batch_mgmt || false,
prohibited_id,
brand_name,
...(managementFlags && { management_flags: managementFlags }),
box_unit,
quantity_per_box,
box_gross_weight,
box_net_weight,
item_type: 'ZC',
level: 'C',
store_id,
box_length,
create_at: new Date(),
box_width,
box_height,
box_volume,
box_remark,
updated_at: new Date(),
};
const transaction = await ctx.model.transaction();
try {
// 2. 开启事务
const createdRecord = await ctx.model.StockWarehouse.create(insertData, transaction);
const barcodes_arr = barcode.split(';');
const existingFileIds = [];
const toCreate = barcodes_arr.filter(item => !existingFileIds.includes(item));
// 批量操作
const promises = [];
if (toCreate.length > 0) {
const refData = toCreate.map(item => ({
stock_id: createdRecord.id,
barcode: item,
warehouse_id: warehouseId,
created_at: new Date(),
}));
promises.push(ctx.model.StockBarcode.bulkCreate(refData, { transaction }));
await Promise.all(promises);
}
await service.systems.operationLog.createOperationLog({
businessType: 'stock',
businessId: createdRecord.id,
operationCode: 'CREATE',
operator: {
id: ctx.user.id,
name: ctx.user.employees_name,
},
extras: {
warehouseId,
},
});
await transaction.commit();
return await this.getInfo({ id: createdRecord.id });
} catch (e) {
if (transaction) {
await transaction.rollback();
}
throw (new Error(`创建失败,${e.message}`));
}
}
validateSaveParams(data, isEdit = true) {
const requiredFields = [ 'item_code', 'item_name', 'stock_unit', 'gross_weight' ];
if (!data.id && isEdit) {
throw new Error('缺失必要参数: id');
}
for (const field of requiredFields) {
if (!data[field]) {
throw new Error(`缺失必要参数: ${field}`);
}
}
if (data.enable_box_spec && (!data.quantity_per_box || data.quantity_per_box <= 0)) {
throw new Error('启用箱规时,每箱数量必须大于0');
}
// 数值类型验证
const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ];
for (const field of numericFields) {
if (data[field] && isNaN(Number(data[field]))) {
throw new Error(`${field} 必须是有效的数字`);
}
}
}
async stockLog() {
return undefined;
}
/**
* 校验商品编码在指定仓库与货主维度下是否唯一。
* @param {number|null} item_id 商品ID(编辑场景用于排除自身)
* @param {string} item_code 商品编码
* @param {number} owner_id 货主ID
* @param {number} warehouse_id 仓库ID
* @return {Promise<{unique:boolean,isUnique:boolean,message?:string}>} 唯一性校验结果
*/
async checkItemCodeUnique(item_id, item_code, owner_id, warehouse_id) {
const { ctx, app } = this;
const { Op } = this.app.Sequelize || app.Sequelize;
try {
const normalizedItemCode = String(item_code || '').trim();
const where = {
item_code: normalizedItemCode,
store_id: owner_id,
warehouse_id,
deleted_at: null,
};
if (item_id) {
where.id = {
[Op.ne]: item_id,
};
}
const space = await ctx.model.StockWarehouse.findOne({
where,
attributes: [ 'id' ],
});
if (!space) {
return { unique: true, isUnique: true };
}
return { unique: false, isUnique: false, message: '商品编码已存在' };
} catch (error) {
ctx.logger.error('检查商品编码唯一性失败:', error);
return { unique: false, isUnique: false, message: '商品编码检测失败' };
}
}
async handleBatchDelete(data) {
const { ctx, app } = this;
const { Op } = this.app.Sequelize || app.Sequelize;
const { ids } = data;
if (!ids || !Array.isArray(ids) || ids.length === 0) {
return { code: 405, message: '请选择要删除的商品' };
}
try {
const where = {
[Op.and]: [
{ id: { [Op.in]: ids } },
{ deleted_at: null },
],
};
// 1. 查询商品资料及其库存情况
const products = await ctx.model.StockWarehouse.findAll({
where,
include: [
{
model: ctx.model.Storage,
as: 'storage',
attributes: [ 'id', 'quantity' ],
required: false, // 使用left join,因为可能没有库存记录
},
],
attributes: [ 'id', 'item_name', 'quantity', 'return_quantity' ],
});
if (products.length === 0) {
return { code: 200, message: '未找到对应的商品资料或已删除', data: [] };
}
// 2. 分析哪些商品可以删除(没有库存或库存为0)
const deletableProducts = [];
const undeletableProducts = [];
products.forEach(product => {
const productInfo = {
id: product.id,
name: product.item_name,
hasStock: false,
stockQuantity: 0,
};
// 检查库存情况
if (product.storage) {
if (Array.isArray(product.storage)) {
// 如果有多个库存记录
const totalStock = product.storage.reduce((sum, storage) => {
return sum + (storage.quantity || 0);
}, 0);
productInfo.stockQuantity = totalStock;
productInfo.hasStock = totalStock > 0;
} else {
// 如果只有一个库存记录
productInfo.stockQuantity = product.storage.quantity || 0;
productInfo.hasStock = productInfo.stockQuantity > 0;
}
}
if (product.quantity > 0 || product.return_quantity > 0) {
productInfo.hasStock = true;
}
if (productInfo.hasStock) {
undeletableProducts.push(productInfo);
} else {
deletableProducts.push(productInfo);
}
});
if (deletableProducts.length === 0) {
return {
code: 405,
message: '所有选中的商品都有库存,无法删除',
data: {
undeletableProducts,
message: `以下商品存在库存无法删除:${undeletableProducts.map(p => p.name).join('、')}`,
},
};
}
// 3. 执行删除(软删除)
const deletableIds = deletableProducts.map(p => p.id);
const result = await ctx.model.transaction(async t => {
// 软删除商品资料
const [ affectedCount ] = await ctx.model.StockWarehouse.update(
{
deleted_at: new Date(),
updated_at: new Date(),
// 如果需要记录删除人
// deleted_by: ctx.user.user_id
},
{
where: {
id: { [Op.in]: deletableIds },
},
transaction: t,
// 如果要检查行锁
// lock: t.LOCK.UPDATE
}
);
return {
deletedCount: affectedCount,
deletedIds: deletableIds,
};
});
// 4. 如果需要同时清理关联数据
if (deletableIds.length > 0) {
// 例如:清理商品分类关联、商品标签关联等
// await this.cleanRelatedData(deletableIds);
}
return {
code: 200,
message: `删除成功,共删除 ${result.deletedCount} 个商品资料`,
data: {
deletedCount: result.deletedCount,
deletedProducts: deletableProducts,
undeletableProducts,
failedIds: ids.filter(id => !deletableIds.includes(id)),
summary: {
totalSelected: ids.length,
deleted: deletableProducts.length,
failed: undeletableProducts.length,
},
},
};
} catch (error) {
console.error('批量删除商品资料失败:', error);
ctx.logger.error('批量删除商品资料失败:', error);
// 根据错误类型返回不同的提示
let errorMessage = '删除失败,请稍后重试';
if (error.name === 'SequelizeForeignKeyConstraintError') {
errorMessage = '删除失败,存在关联数据,请先处理相关数据';
} else if (error.name === 'SequelizeDatabaseError') {
errorMessage = '数据库操作失败';
}
return {
code: 500,
message: errorMessage,
error: process.env.NODE_ENV === 'development' ? {
message: error.message,
stack: error.stack,
} : undefined,
};
}
}
async deleteUnit(data) {
const { id } = data;
const { ctx } = this;
const unitExit = await ctx.model.StockUnit.findOne({
where: {
id,
warehouse_id: ctx.user.store_id,
},
});
if (!unitExit) {
throw new Error('库存单位不存在');
}
ctx.model.StockUnit.destroy({
where: {
id,
warehouse_id: ctx.user.store_id,
},
});
return { message: '删除成功', code: 200 };
}
async deleteProhibited(data) {
const { id } = data;
const { ctx } = this;
const unitExit = await ctx.model.ProhibitedType.findOne({
where: {
id,
warehouse_id: ctx.user.store_id,
},
});
if (!unitExit) {
throw new Error('违禁品类型不存在');
}
ctx.model.ProhibitedType.destroy({
where: {
id,
warehouse_id: ctx.user.store_id,
},
});
return { message: '删除成功', code: 200 };
}
/**
* 快捷搜索仓库商品并补全库存管理标记。
* @param {Object} data 请求体
* @param {string} [data.keyword] 搜索关键字
* @param {number|string} [data.store_id] 货主ID
* @param {boolean} [data.with_stock=false] 是否返回关联库存数据
* @param {boolean} [data.is_batch=false] with_stock=true 时是否按批次返回
* @return {Promise<Object>} 搜索结果,data 为商品数组
*/
async search(data) {
const { keyword, store_id = null, with_stock = false, is_batch = false } = data;
const { ctx, app } = this;
const { Op } = app.Sequelize;
const warehouseId = ctx.user.store_id;
try {
const whereCondition = {
warehouse_id: warehouseId,
deleted_at: null,
};
// 如果有传入store_id,则添加store_id条件
if (store_id) {
whereCondition.store_id = store_id;
}
// 准备关联查询的条件
const includeConditions = [];
// 如果有搜索关键词,创建搜索条件
if (keyword && keyword.trim()) {
const searchKeyword = `%${keyword.trim()}%`;
// 先构建主表的搜索条件
const stockWarehouseConditions = {
[Op.or]: [
{ item_code: { [Op.like]: searchKeyword } },
{ item_name: { [Op.like]: searchKeyword } },
{ goods_code: { [Op.like]: searchKeyword } },
],
};
// 添加条形码关联查询条件
includeConditions.push({
model: app.model.StockBarcode,
as: 'barcodes',
attributes: [ 'barcode' ],
required: false, // 使用LEFT JOIN
where: {
barcode: { [Op.like]: searchKeyword },
},
});
// 合并搜索条件
whereCondition[Op.or] = [
stockWarehouseConditions,
// 如果barcodes表有匹配的记录,则也返回该商品
{
'$barcodes.barcode$': { [Op.like]: searchKeyword },
},
];
} else {
// 如果没有关键词,也包含barcodes关联(但不需要where条件)
includeConditions.push({
model: app.model.StockBarcode,
as: 'barcodes',
attributes: [ 'barcode' ],
required: false,
});
}
includeConditions.push(app.model.StoreWarehouse.buildStoreStockInclude({
warehouseId,
required: false,
attributes: [ 'store_id', 'store_remask' ],
}));
// 执行查询
const results = await app.model.StockWarehouse.findAll({
where: whereCondition,
attributes: [
'id', 'item_code', 'goods_code', 'item_name',
'sku_property', 'stock_unit', 'quantity',
'locked_quantity', 'brand_name', 'item_type',
'inbound_min_days', 'outbound_min_days',
'shelf_life_days', 'remaining_threshold_days',
'is_batch_mgmt',
'is_shelf_life_mgmt',
'gross_weight',
],
order: [[ 'create_at', 'DESC' ]],
limit: 50,
include: includeConditions,
subQuery: false, // 避免子查询,提高性能
});
// 格式化返回数据
const formattedResults = results.map(item => {
const result = item.toJSON();
// 提取所有条形码
result.barcodes = result.barcodes?.map(b => b.barcode) || [];
const batchMgmtValue = result.is_batch_mgmt;
result.is_batch_mgmt_enabled = typeof batchMgmtValue === 'boolean'
? batchMgmtValue
: [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(String(batchMgmtValue).trim().toUpperCase());
delete result.is_batch_mgmt;
const shelfLifeMgmtValue = result.is_shelf_life_mgmt;
result.is_shelf_life_mgmt = typeof shelfLifeMgmtValue === 'boolean'
? shelfLifeMgmtValue
: [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(String(shelfLifeMgmtValue).trim().toUpperCase());
return result;
});
// with_stock=true 时关联查询库存数据
if (with_stock && formattedResults.length > 0) {
const stockIds = formattedResults.map(r => r.id);
const storageWhere = {
stock_id: { [Op.in]: stockIds },
warehouse_id: warehouseId,
is_enabled: 1,
delete_at: null,
};
const storageRows = await app.model.Storage.findAll({
where: storageWhere,
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', 'created_at',
],
include: [{
model: app.model.LocationSpace,
as: 'space',
attributes: [ 'id', 'space_code', 'custom_name' ],
required: false,
}],
order: [[ 'created_at', 'DESC' ]],
});
// 按 stock_id 分组
const storageMap = new Map();
for (const row of storageRows) {
const plain = row.get({ plain: true });
const key = plain.stock_id;
if (!storageMap.has(key)) {
storageMap.set(key, []);
}
storageMap.get(key).push(plain);
}
for (const item of formattedResults) {
const storageList = storageMap.get(item.id) || [];
if (is_batch) {
// is_batch=true:逐条批次明细返回,不分组
item.storage = storageList;
} else {
// is_batch=false(默认):按库位分组汇总
const mergedMap = new Map();
for (const s of storageList) {
const spaceKey = s.space_id;
if (mergedMap.has(spaceKey)) {
const existing = mergedMap.get(spaceKey);
existing.quantity += Number(s.quantity) || 0;
existing.locked_quantity += Number(s.locked_quantity) || 0;
existing.available_quantity = existing.quantity - existing.locked_quantity;
} else {
const quantity = Number(s.quantity) || 0;
const lockedQuantity = Number(s.locked_quantity) || 0;
mergedMap.set(spaceKey, {
space_id: s.space_id,
inventory_type: s.inventory_type,
quantity,
locked_quantity: lockedQuantity,
available_quantity: quantity - lockedQuantity,
space: s.space,
});
}
}
item.storage = Array.from(mergedMap.values());
}
}
}
return {
code: 200,
data: formattedResults,
total: formattedResults.length,
};
} catch (error) {
ctx.logger.error('搜索仓库商品失败:', error);
return {
code: 0,
message: '搜索失败,请稍后重试',
};
}
}
/**
* 查询商品的库存明细(storage 表)。
* @param {Object} data 请求体
* @param {number} data.stock_id 商品库存ID(stock_warehouse.id)
* @param {Object} [data.pagination] 分页参数
* @return {Promise<Object>} 库存明细分页结果
*/
async getStockDetail(data) {
const { ctx, app } = this;
const warehouseId = ctx.user.store_id;
const { stock_id, pagination = {}, group_by_batch = false } = data;
if (!stock_id) {
return { code: 0, message: '参数 stock_id 不能为空' };
}
try {
// 校验商品归属当前仓库
const stockItem = await app.model.StockWarehouse.findOne({
where: {
id: stock_id,
warehouse_id: warehouseId,
deleted_at: null,
},
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'quantity', 'locked_quantity' ],
raw: true,
});
if (!stockItem) {
return { code: 0, message: '商品不存在或不属于当前仓库' };
}
const { page = 1, pageSize = 20 } = pagination;
const offset = (page - 1) * pageSize;
const storageWhere = {
stock_id,
warehouse_id: warehouseId,
is_enabled: 1,
delete_at: null,
};
if (group_by_batch) {
// 区分批次:按原逻辑返回每一条库存明细
const { count, rows } = await app.model.Storage.findAndCountAll({
where: storageWhere,
attributes: [
'id', 'space_id', 'batch_no', 'inventory_type',
'quantity', 'locked_quantity', 'available_quantity',
'production_date', 'expiry_date', 'inbound_time',
'inbound_order_no', 'supplier_batch_no', 'created_at',
],
include: [{
model: app.model.LocationSpace,
as: 'space',
attributes: [ 'id', 'space_code', 'custom_name' ],
required: false,
}],
order: [[ 'created_at', 'DESC' ]],
offset,
limit: pageSize,
});
return {
code: 200,
data: {
stockItem,
storageList: rows,
pagination: {
page,
pageSize,
total: count,
},
},
};
}
// 不区分批次:按 space_id 合并库存数据
const allRows = await app.model.Storage.findAll({
where: storageWhere,
attributes: [
'id', 'space_id', 'inventory_type',
'quantity', 'locked_quantity', 'created_at',
],
include: [{
model: app.model.LocationSpace,
as: 'space',
attributes: [
'id',
'space_code',
'custom_name',
],
required: false,
}],
order: [
[
'created_at',
'DESC',
],
],
});
// 按 space_id 合并
const mergedMap = new Map();
for (const row of allRows) {
const plain = row.get({ plain: true });
const key = plain.space_id;
if (mergedMap.has(key)) {
const existing = mergedMap.get(key);
existing.quantity += Number(plain.quantity) || 0;
existing.locked_quantity += Number(plain.locked_quantity) || 0;
existing.available_quantity = existing.quantity - existing.locked_quantity;
} else {
const quantity = Number(plain.quantity) || 0;
const lockedQuantity = Number(plain.locked_quantity) || 0;
mergedMap.set(key, {
id: plain.id,
space_id: plain.space_id,
batch_no: null,
inventory_type: plain.inventory_type,
quantity,
locked_quantity: lockedQuantity,
available_quantity: quantity - lockedQuantity,
production_date: null,
expiry_date: null,
inbound_time: null,
inbound_order_no: null,
supplier_batch_no: null,
created_at: plain.created_at,
space: plain.space,
});
}
}
const mergedList = Array.from(mergedMap.values());
const total = mergedList.length;
const storageList = mergedList.slice(offset, offset + pageSize);
return {
code: 200,
data: {
stockItem,
storageList,
pagination: {
page,
pageSize,
total,
},
},
};
} catch (error) {
ctx.logger.error(`查询商品库存明细失败, stock_id: ${stock_id}`, error);
return { code: 0, message: '查询库存明细失败,请稍后重试' };
}
}
}
module.exports = stockStoreService;