';
+ for (let i = 0; i < el.rows; i++) {
+
+ headerTds += `| ${el.headers && el.headers[i] ? el.headers[i] : `列${i + 1}`} | `;
+ bodyTds += `]]> | `;
+ }
+ headerTds += '
';
+ bodyTds += '<%}%>';
+ return headerTds + bodyTds;
+ }
+}
+
+module.exports = PrintTemplateService;
diff --git a/app/service/systems/sign.js b/app/service/systems/sign.js
new file mode 100644
index 0000000..2fecd2d
--- /dev/null
+++ b/app/service/systems/sign.js
@@ -0,0 +1,198 @@
+// app/service/sign.js
+const Service = require('egg').Service;
+const crypto = require('crypto');
+
+class SignService extends Service {
+ get Constants() {
+ return {
+ SIGN_METHOD_MD5: 'md5',
+ SIGN_METHOD_HMAC: 'hmac',
+ SIGN_METHOD_HMAC_SHA256: 'hmac_sha256',
+ };
+ }
+ toXml(data) {
+ let xml = '\n';
+ // 添加其他数据字段
+ for (const [ key, value ] of Object.entries(data)) {
+ if (![ 'flag', 'code', 'message' ].includes(key)) {
+ xml += this.ctx.service.qimen.buildXmlNode(key, value, 1);
+ }
+ }
+
+ return xml;
+ }
+
+ signTopRequest(params, body, secret, signMethod) {
+ // 第一步:检查参数是否已经排序
+ const keys = Object.keys(params).sort();
+
+ // 第二步:把所有参数名和参数值串在一起
+ let query = '';
+
+ if (signMethod === this.Constants.SIGN_METHOD_MD5) {
+ query += secret;
+ }
+
+ for (const key of keys) {
+ const value = params[key];
+ if (key && value) {
+ query += key + value;
+ }
+ }
+
+ // 第三步:把请求主体拼接在参数后面
+ if (body) {
+ query += body;
+ }
+
+ // 第四步:使用MD5/HMAC加密
+ let bytes;
+ if (signMethod === this.Constants.SIGN_METHOD_HMAC) {
+ bytes = this.encryptHMAC(query, secret);
+ } else if (signMethod === this.Constants.SIGN_METHOD_HMAC_SHA256) {
+ bytes = this.encryptHMACSHA256(query, secret);
+ } else {
+ query += secret;
+ bytes = this.encryptMD5(query);
+ }
+
+ // 第五步:把二进制转化为大写的十六进制
+ return this.byte2hex(bytes);
+ }
+
+ /**
+ * 验证TOP请求签名
+ * @param {Object} params - 所有字符型的TOP请求参数(包含sign参数)
+ * @param {string} body - 请求主体内容
+ * @param {string} secret - 签名密钥
+ * @param {string} signMethod - 签名方法
+ * @return {boolean} 验证是否通过
+ */
+ verifyTopRequest(params, body, secret, signMethod) {
+ // 复制参数,避免修改原参数
+ const verifyParams = { ...params };
+
+ // 提取签名
+ const receivedSign = verifyParams.sign;
+ if (!receivedSign) {
+ this.ctx.logger.warn('[SignService] Missing sign parameter');
+ return false;
+ }
+
+ // 移除签名参数,不参与签名计算
+ delete verifyParams.sign;
+
+ // 计算签名
+ const calculatedSign = this.signTopRequest(verifyParams, body, secret, signMethod);
+
+ // 比较签名
+ const isValid = receivedSign.toUpperCase() === calculatedSign.toUpperCase();
+
+ if (!isValid) {
+ this.ctx.logger.warn('[SignService] Signature verification failed', {
+ receivedSign: receivedSign.toUpperCase(),
+ calculatedSign: calculatedSign.toUpperCase(),
+ });
+ }
+
+ return isValid;
+ }
+
+ /**
+ * 验证请求并获取参数(移除签名相关参数)
+ * @param {Object} params - 所有请求参数
+ * @param {string} body - 请求主体内容
+ * @param {string} secret - 签名密钥
+ * @param {string} signMethod - 签名方法
+ * @return {Object} { success: boolean, data: Object, message: string }
+ */
+ verifyAndExtractParams(params, body, secret, signMethod) {
+ try {
+ const isValid = this.verifyTopRequest(params, body, secret, signMethod);
+
+ if (!isValid) {
+ return {
+ success: false,
+ data: null,
+ message: 'Signature verification failed',
+ };
+ }
+
+ // 复制参数并移除签名相关字段
+ const cleanParams = { ...params };
+ delete cleanParams.sign;
+ delete cleanParams.sign_method;
+
+ return {
+ success: true,
+ data: cleanParams,
+ message: 'Success',
+ };
+ } catch (error) {
+ this.ctx.logger.error('[SignService] verifyAndExtractParams error:', error);
+ return {
+ success: false,
+ data: null,
+ message: error.message,
+ };
+ }
+ }
+
+ /**
+ * 生成带签名的请求参数
+ * @param {Object} params - 原始参数
+ * @param {string} body - 请求主体内容
+ * @param {string} secret - 签名密钥
+ * @param {string} signMethod - 签名方法
+ * @return {Object} 带签名的参数对象
+ */
+ generateSignedParams(params, body, secret, signMethod) {
+ const sign = this.signTopRequest(params, body, secret, signMethod);
+
+ return {
+ ...params,
+ sign,
+ sign_method: signMethod,
+ };
+ }
+
+ /**
+ * HMAC MD5加密
+ * @param data
+ * @param secret
+ */
+ encryptHMAC(data, secret) {
+ const hmac = crypto.createHmac('md5', secret);
+ hmac.update(data, 'utf8');
+ return hmac.digest();
+ }
+
+ /**
+ * HMAC SHA256加密
+ * @param data
+ * @param secret
+ */
+ encryptHMACSHA256(data, secret) {
+ const hmac = crypto.createHmac('sha256', secret);
+ hmac.update(data, 'utf8');
+ return hmac.digest();
+ }
+
+ /**
+ * MD5加密
+ * @param data
+ */
+ encryptMD5(data) {
+ return crypto.createHash('md5').update(data, 'utf8').digest();
+ }
+
+ /**
+ * 二进制转十六进制字符串(大写)
+ * @param bytes
+ */
+ byte2hex(bytes) {
+ return Buffer.from(bytes).toString('hex').toUpperCase();
+ }
+}
+
+module.exports = SignService;
diff --git a/app/service/systems/space.js b/app/service/systems/space.js
new file mode 100644
index 0000000..7c20188
--- /dev/null
+++ b/app/service/systems/space.js
@@ -0,0 +1,60 @@
+'use strict';
+const Service = require('egg').Service;
+
+class spaceService extends Service {
+ constructor(ctx) {
+ super(ctx);
+ }
+ async searchSpace(data) {
+ const { ctx, app } = this;
+ const { keyword } = data;
+ const warehouseId = ctx.user.store_id;
+
+ // 构建基础查询条件:warehouse_id 为当前仓库或 null
+ const baseWhere = {
+ [app.Sequelize.Op.or]: [
+ { warehouse_id: warehouseId },
+ { warehouse_id: null },
+ ],
+ };
+
+ let whereCondition = baseWhere;
+
+ // 如果有关键词,添加模糊查询
+ if (keyword && keyword.trim()) {
+ const searchKeyword = `%${keyword.trim()}%`;
+ whereCondition = {
+ [app.Sequelize.Op.and]: [
+ baseWhere, // 仓库条件
+ {
+ [app.Sequelize.Op.or]: [
+ {
+ space_code: {
+ [app.Sequelize.Op.like]: searchKeyword,
+ },
+ },
+ {
+ custom_barcode: {
+ [app.Sequelize.Op.like]: searchKeyword,
+ },
+ },
+ ],
+ },
+ ],
+ };
+ }
+
+ const results = await app.model.LocationSpace.findAll({
+ where: whereCondition,
+ attributes: [
+ 'id', 'space_code', 'custom_barcode', 'custom_name',
+ ],
+ order: [[ 'space_code', 'DESC' ]],
+ limit: 50,
+ subQuery: false,
+ });
+
+ return { code: 200, data: results, total: results.length };
+ }
+}
+module.exports = spaceService;
diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js
new file mode 100644
index 0000000..ecb0e04
--- /dev/null
+++ b/app/service/systems/stock_store.js
@@ -0,0 +1,2841 @@
+'use strict';
+const Service = require('egg').Service;
+
+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