WMS_MAIN/app/service/systems/stock_store.js
2026-03-25 23:26:10 +08:00

2660 lines
76 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 {
constructor(ctx) {
super(ctx);
}
async create(stockData) {
const {
app,
ctx,
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 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 ? new Date(stockData.create_time).format() : '',
},
};
return result;
}
async getItemInfoWithCache(itemId) {
const {
ctx,
app,
} = this; // 使用 ctx.model 而非 app.model
const cacheKey = `item:info:${itemId}`;
try {
// 1. 尝试从缓存获取
const cached = await app.getCacheAsync(cacheKey);
console.log('缓存》》》》', cached);
if (cached !== null && cached !== undefined) {
app.logger.debug('[ItemCacheHit]', itemId);
// 处理空值标记
if (cached.__isNull) {
return null; // 明确返回 null 表示商品不存在
}
// 返回缓存的对象
return cached;
}
// 2. 缓存未命中,查询数据库
app.logger.debug('[ItemCacheMiss]', itemId);
console.log('缓存》》》》', 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}`);
}
throw error;
}
}
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) {
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', '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 = Math.max(0, quantity - lockedQuantity);
const grossWeight = parseInt(stockWarehouse.gross_weight) || 0;
storage = {
id: stockWarehouse.id,
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,
warehouse_code: itemInfo.warehouse_code,
item_code: itemInfo.item_code,
},
storage,
},
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 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 itemId
*/
async clearItemStorageCache(itemId) {
const {
app,
} = this;
const cacheKey = `storages:${itemId}`;
try {
await app.delCacheAsync(cacheKey);
app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`);
} catch (error) {
app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message);
}
}
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 {
// 1. 查询并锁定记录(悲观锁)
const stockRecord = await ctx.model.StockWarehouse.findOne({
where: {
id: stockWarehouseId,
is_valid: 'Y',
deleted_at: null,
},
transaction,
lock: transaction.LOCK.UPDATE, // 行级锁
raw: false, // 需要实例以使用方法
});
// 检查记录是否存在
if (!stockRecord) {
return {
success: false,
error: `库存记录不存在或已失效 (ID: ${stockWarehouseId})`,
data: null,
};
}
// 2. 业务规则校验
if (isLocking) {
// 加锁操作:检查可用库存是否足够
const availableQty = stockRecord.quantity - stockRecord.locked_quantity;
if (availableQty < absQty) {
return {
success: false,
error: `库存不足,可用 ${availableQty},需求 ${absQty}`,
data: {
available: availableQty,
required: absQty,
recordId: stockWarehouseId,
},
};
}
// 检查锁定后是否会导致超卖
const newLocked = stockRecord.locked_quantity + absQty;
if (newLocked > stockRecord.quantity) {
return {
success: false,
error: `锁定后会导致超卖,总库存 ${stockRecord.quantity},锁定后 ${newLocked}`,
data: null,
};
}
} 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,
};
}
}
// 3. 执行锁定/释放操作
let updateResult;
if (isLocking) {
// 加锁:增加 locked_quantity
updateResult = await stockRecord.increment('locked_quantity', {
by: absQty,
transaction,
silent: true,
});
app.logger.info(
`[库存锁定] ID: ${stockWarehouseId}, 增加锁定: +${absQty}, 锁定后: ${stockRecord.locked_quantity + absQty}`
);
} else {
// 减锁:减少 locked_quantity(确保不小于0)
updateResult = await stockRecord.decrement('locked_quantity', {
by: absQty,
transaction,
silent: true,
});
app.logger.info(
`[库存释放] ID: ${stockWarehouseId}, 减少锁定: -${absQty}, 锁定后: ${stockRecord.locked_quantity - absQty}`
);
}
// 4. 获取更新后的数据(可选)
await stockRecord.reload({
transaction,
});
// 5. 返回成功结果
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 {
// 2. 获取商品和库存信息(复用)
const stockResult = await this.getItemStorages(itemId, transaction);
if (!stockResult.success) {
// 入库失败:商品不存在或未绑定
return stockResult;
}
const {
stock,
storage,
} = stockResult.data;
// 3. 执行库存增加
let result;
if (storage.exists) {
// 非首次入库:更新现有记录(只增加quantity)
result = await ctx.model.StockWarehouse.increment('quantity', {
by: inboundQty,
where: {
id: storage.id,
is_valid: 'Y',
deleted_at: null,
},
transaction,
});
app.logger.info('[入库] 更新现有库存', {
itemId,
stockId: storage.id,
quantity: inboundQty,
before: storage.quantity,
after: storage.quantity + inboundQty,
});
} else {
// 首次入库:需要创建库存记录(stock_id应该已存在)
// 注意:这里需要更多信息,如warehouse_id等,实际场景可能需要额外参数
return {
success: false,
error: '库存记录不存在,首次入库需要完整参数',
data: null,
};
}
// 4. 获取更新后的数据
const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, {
transaction,
raw: true,
});
return {
success: true,
data: {
itemId,
stockId: storage.id,
action: 'inbound',
quantity: inboundQty,
beforeQuantity: storage.quantity,
afterQuantity: updatedRecord.quantity,
beforeLocked: storage.lockedQuantity,
afterLocked: updatedRecord.locked_quantity,
available: updatedRecord.quantity - updatedRecord.locked_quantity,
updatedAt: updatedRecord.update_at,
},
error: null,
};
} catch (error) {
app.logger.error('[inbound] 入库失败', {
itemId,
quantity,
error: error.message,
stack: error.stack,
});
return {
success: false,
error: `入库系统错误: ${error.message}`,
data: null,
};
}
}
/**
* 商品出库服务
* @param {number} itemId 商品ID (StockStore.id)
* @param {number} quantity 出库数量(正数)
* @param {Object} transaction 数据库事务
*/
async outbound(itemId, quantity, transaction) {
const {
ctx,
app,
} = this;
// 1. 参数验证
const outboundQty = parseInt(quantity);
if (!itemId || outboundQty <= 0) {
return {
success: false,
error: `出库参数无效: itemId=${itemId}, quantity=${quantity}`,
data: null,
};
}
try {
// 2. 获取商品和库存信息(复用)
const stockResult = await this.getItemStorages(itemId, transaction);
if (!stockResult.success) {
return stockResult;
}
const {
stock,
storage,
} = stockResult.data;
// 3. 检查库存是否足够出库
if (!storage.exists) {
return {
success: false,
error: '库存记录不存在,无法出库',
data: null,
};
}
// 关键检查:总库存是否足够
if (storage.quantity < outboundQty) {
return {
success: false,
error: `总库存不足,当前 ${storage.quantity},需求 ${outboundQty}`,
data: null,
};
}
// 关键检查:锁定库存是否足够扣减
if (storage.lockedQuantity < outboundQty) {
return {
success: false,
error: `锁定库存不足,已锁定 ${storage.lockedQuantity},需求 ${outboundQty}`,
data: null,
};
}
// 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,
// 乐观锁条件:确保更新时库存仍然足够
quantity: {
[app.Sequelize.Op.gte]: outboundQty,
},
locked_quantity: {
[app.Sequelize.Op.gte]: outboundQty,
},
},
transaction,
});
if (result[0] === 0) {
return {
success: false,
error: '出库失败:库存已被其他操作修改',
data: null,
};
}
// 5. 获取更新后的数据
const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, {
transaction,
raw: true,
});
app.logger.info('[出库] 成功', {
itemId,
stockId: storage.id,
quantity: outboundQty,
beforeQuantity: storage.quantity,
afterQuantity: updatedRecord.quantity,
beforeLocked: storage.lockedQuantity,
afterLocked: updatedRecord.locked_quantity,
});
return {
success: true,
data: {
itemId,
stockId: storage.id,
action: 'outbound',
quantity: outboundQty,
beforeQuantity: storage.quantity,
afterQuantity: updatedRecord.quantity,
beforeLocked: storage.lockedQuantity,
afterLocked: updatedRecord.locked_quantity,
available: updatedRecord.quantity - updatedRecord.locked_quantity,
updatedAt: updatedRecord.update_at,
},
error: null,
};
} catch (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,
config,
} = 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 {
cos,
} = config;
const {
cdnurl,
} = cos;
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, service, 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;
console.log('批量修改参数', 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;
console.log('条码修改提交', data);
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;
console.log(data);
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;
console.log(stock_id);
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,
}),
]);
}
console.log('barcodes>>>>', barcodes);
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,
};
});
console.log('warehouseStock>>>', warehouseStock);
const get_store_id = warehouseStock ? warehouseStock.store_id : barcodes[0]['warehouse_stock.store_id'];
console.log('get_store_id>>>', get_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) {
console.log(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) {
console.log(e);
throw e;
}
}
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',
'store_id',
],
raw: true,
});
stock.enable_box_spec = !!stock.enable_box_spec;
return stock;
}
async saveWarehouseStock(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, id,
} = data;
const prohibited_id_tmp = !prohibited_id ? null : parseInt(prohibited_id);
// 1. 参数验证
this.validateSaveParams(data);
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('商品不存在');
}
// 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,
updated_at: new Date(),
};
console.log('更新数据', updateData);
// 5. 清除空值
Object.keys(updateData).forEach(key => {
if (key != 'prohibited_id' && (updateData[key] === undefined || updateData[key] === null)) {
delete updateData[key];
}
});
// 6. 执行更新
const [affectedRows] = 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, id, barcode,
} = data;
// 1. 参数验证
this.validateSaveParams(data, false);
let checkItemCodeUnique = {};
try {
checkItemCodeUnique = await this.checkItemCodeUnique(null, item_code, store_id, warehouseId);
} catch (e) {
console.log(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 = [];
console.log('createdRecord', createdRecord.id);
if (toCreate.length > 0) {
const refData = toCreate.map(item => ({
stock_id: createdRecord.id,
barcode: item,
warehouse_id: warehouseId,
created_at: new Date(),
}));
console.log('refData', refData);
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) {
console.log(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() {
}
async checkItemCodeUnique(id, item_code, store_id, warehouse_id) {
const { ctx } = this;
const { Op } = this.app.Sequelize || app.Sequelize;
try {
// 检查条码是否被其他仓位使用(排除当前仓位)
let whereId = null;
if (id) {
whereId = {
id: {
[Op.ne]: id, // 排除当前仓位ID
},
};
}
const where = {
[Op.and]: [
whereId,
{ item_code },
{ store_id },
{ warehouse_id },
{ deleted_at: null }, // 未删除的记录
],
};
const space = await ctx.model.StockWarehouse.findOne({
where,
attributes: ['id'],
});
// 如果没有找到重复的条码,返回唯一
if (!space) {
return { isUnique: true };
}
return { isUnique: false, message: '商品编码已被使用' };
} catch (error) {
ctx.logger.error('检查商品编码唯一性失败:', error);
return { isUnique: false, message: '商品编码检测失败' };
}
}
async handleBatchDelete(data) {
const { ctx } = 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'],
});
console.log('查询到的商品资料:', JSON.stringify(products, null, 2));
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);
}
});
console.log('可以删除的商品:', deletableProducts);
console.log('不能删除的商品:', undeletableProducts);
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, app } = 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, app } = 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 };
}
async search(data) {
const { keyword, store_id = null } = 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'],
}));
// 执行查询
console.log('查询商品===》');
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',
],
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) || [];
return result;
});
return {
code: 200,
data: formattedResults,
total: formattedResults.length,
};
} catch (error) {
ctx.logger.error('搜索仓库商品失败:', error);
return {
code: 0,
message: '搜索失败,请稍后重试',
};
}
}
}
module.exports = stockStoreService;