'use strict'; const Service = require('egg').Service; class DeliveryOrderService extends Service { async addOrder(data, info) { const { ctx } = this; if (!info.warehouseId) { return { success: false, message: '订单创建失败: 非法参数', data: null, }; } const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); const { deliveryOrder, orderLines } = data.request; // 开启事务 const transaction = await ctx.model.transaction(); try { if (!info.storeId) { throw new Error('非法参数'); } if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) { throw new Error('订单信息不完整'); } // 检查订单是否已存在(根据唯一索引) const existingOrder = await DeliveryModel.findOne({ where: { delivery_order_code: deliveryOrder.deliveryOrderCode, store_id: info.storeId, warehouse_id: info.warehouseId, }, attributes: [ 'id' ], transaction, }); if (existingOrder) { await transaction.rollback(); return { success: true, message: '订单已存在', data: { deliveryOrderId: existingOrder.id }, }; } // 准备订单数据 const orderData = await this.prepareOrderData(deliveryOrder, info); // 创建订单 const createdOrder = await DeliveryModel.create(orderData, { transaction }); const orderId = createdOrder.id; let itemsInfo = null; // 添加订单明细 if (orderLines && (orderLines.orderLine)) { itemsInfo = await this.addOrderLines( orderLines.orderLine, orderId, info, transaction ); } else { throw new Error('[订单无明细]'); } // 更新订单统计信息 - 直接使用itemsInfo中的计算结果 if (itemsInfo) { const stats = { items: itemsInfo.items_str || '', // 原始结构字符串 items_count: itemsInfo.stock_count || 0, // 商品种类数 items_total: itemsInfo.item_total_count || 0, // 商品总数(直接使用计算结果) items_weight: itemsInfo.total_weight || 0, // 总重量 items_hash: this.generateItemsHash(itemsInfo), // 哈希值 items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验 updated_at: new Date(), }; await DeliveryModel.update( stats, { where: { id: orderId }, transaction, } ); // 记录详细日志 ctx.logger.info('[订单统计信息已更新]', { orderId, orderCode: deliveryOrder.deliveryOrderCode, stats: { items_count: stats.items_count, items_total: stats.items_total, items_weight: stats.items_weight, items_hash_preview: stats.items_hash?.substring(0, 8) + '...', items_crc: stats.items_crc, }, }); } // 异步处理:订单入队列 this.addOrderToQueue(orderId, info.warehouseId); await transaction.commit(); return { success: true, message: '订单创建成功', data: { orderId, stats: itemsInfo ? { items_count: itemsInfo.stock_count, items_total: itemsInfo.item_total_count, items_weight: itemsInfo.total_weight, } : null, }, }; } catch (error) { console.error('创建订单失败:', error); // 回滚事务 await transaction.rollback(); return { success: false, message: `订单创建失败: ${error.message}`, data: null, }; } } /** * 生成订单结构哈希值 * 直接使用itemsInfo中的items_str * @param itemsInfo */ generateItemsHash(itemsInfo) { const crypto = require('crypto'); if (!itemsInfo || !itemsInfo.items_str) { return ''; } // 生成哈希 return crypto.createHash('md5') .update(itemsInfo.items_str) .digest('hex'); } /** * 计算CRC32校验码 * @param str */ calculateCRC32(str) { if (!str) return 0; try { const crc32 = require('crc-32'); return crc32.str(str) >>> 0; // 转为无符号整数 } catch (error) { // 降级方案:简单校验和 let crc = 0; for (let i = 0; i < str.length; i++) { crc = (crc + str.charCodeAt(i)) & 0xFFFFFFFF; } return crc; } } // 准备订单数据 // 准备订单数据 async prepareOrderData(deliveryOrder, info) { const { ctx, service } = this; const { deliveryOrderCode, preDeliveryOrderCode, preDeliveryOrderId, orderType, warehouseCode, orderFlag, sourcePlatformCode, sourcePlatformName, createTime, placeOrderTime, payTime, payNo, shopNick, sellerNick, buyerNick, operatorName, operateTime, totalAmount, itemAmount, discountAmount, freight, arAmount, gotAmount, logisticsCode, logisticsName, expressCode, logisticsAreaCode, isUrgency, invoiceFlag, senderInfo, receiverInfo, } = deliveryOrder; let platformCode = sourcePlatformCode; let platformName = sourcePlatformName; try { // 验证平台代码是否存在 const platformInfo = await service.systems.platform.checkPlatformExists( sourcePlatformCode, info.warehouseId ); if (platformInfo) { // 平台存在,使用数据库中的平台信息 platformCode = platformInfo.code; platformName = platformInfo.name; ctx.logger.info(`平台验证通过: ${sourcePlatformCode} -> ${platformCode} (${platformName})`); } else { // 平台不存在,抛出错误 throw new Error(`平台代码 ${sourcePlatformCode} 在仓库 ${info.warehouseId} 中不存在`); } } catch (error) { ctx.logger.error(`平台验证失败: ${error.message}`, { platformCode: sourcePlatformCode, warehouseId: info.warehouseId, deliveryOrderCode, }); throw error; // 抛出错误,让上层捕获 } return { delivery_order_code: deliveryOrderCode, pre_delivery_order_code: preDeliveryOrderCode || '', pre_delivery_order_id: preDeliveryOrderId || '', order_type: orderType, warehouse_code: warehouseCode, order_flag: orderFlag || '', // 使用验证后的平台信息 source_platform_code: platformCode, source_platform_name: platformName, create_at: createTime ? new Date(createTime) : new Date(), place_order_time: placeOrderTime ? new Date(placeOrderTime) : null, pay_time: payTime ? new Date(payTime) : null, pay_no: payNo || '', shop_nick: shopNick, seller_nick: sellerNick, buyer_nick: buyerNick, operator_name: operatorName, operate_time: operateTime ? new Date(operateTime) : null, total_amount: totalAmount ? parseFloat(totalAmount) : 0, item_amount: itemAmount ? parseFloat(itemAmount) : 0, discount_amount: discountAmount ? parseFloat(discountAmount) : 0, freight: freight ? parseFloat(freight) : 0, ar_amount: arAmount ? parseFloat(arAmount) : 0, got_amount: gotAmount ? parseFloat(gotAmount) : 0, logistics_code: logisticsCode, logistics_name: logisticsName, express_code: expressCode || '', logistics_area_code: logisticsAreaCode || '', is_urgency: isUrgency || 'N', invoice_flag: invoiceFlag || 'N', status: 'pedding', // 收件人信息 name: receiverInfo?.name || '', tel: receiverInfo?.tel || '', mobile: receiverInfo?.mobile || '', email: receiverInfo?.email || '', country_code: receiverInfo?.countryCode || '', province: receiverInfo?.province || '', city: receiverInfo?.city || '', area: receiverInfo?.area || '', town: receiverInfo?.town || '', detail_address: receiverInfo?.detailAddress || '', zip_code: receiverInfo?.zipCode || '', // 发件人信息(如果需要存储) // 业务关联ID store_id: info.storeId, warehouse_id: info.warehouseId, from_key: info.appKey, }; } // 添加订单明细 async addOrderLines(orderLines, orderId, info, transaction) { const { ctx, app } = this; const { warehouseId, appKey, storeId } = info; let order_items = []; if (orderLines && typeof orderLines === 'object') { if (orderLines.itemCode) { order_items = [ orderLines ]; } else if (Array.isArray(orderLines)) { order_items = orderLines; } else if (orderLines.orderLine && Array.isArray(orderLines.orderLine)) { order_items = orderLines.orderLine; } else if (orderLines.orderLine && typeof orderLines.orderLine === 'object') { order_items = [ orderLines.orderLine ]; } } if (!order_items || !Array.isArray(order_items) || order_items.length === 0) { throw new Error('没有有效的订单明细数据'); } const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); const lineData = []; const errors = []; const stockQuantityMap = new Map(); // stock_id -> 数量 const stockWeightMap = new Map(); // stock_id -> 单件重量(grossWeight) const processedItemIds = new Set(); console.log('order_items', order_items); for (let i = 0; i < order_items.length; i++) { const line = order_items[i]; console.log('line', line); // 跳过空值 if (!line || typeof line !== 'object') { errors.push(`第${i + 1}行: 数据格式无效`); continue; } // 数量验证 const planQty = line.planQty ? parseInt(line.planQty) : 0; if (planQty <= 0) { errors.push(`商品《${line.itemName}》数量必须大于0`); continue; } let wms_stock = null; if (!line.itemId) { console.log('ERP不处理WMS的外部商品编码'); // 查找唯一键 wms_stock = await app.model.StockStore.findOne({ where: { item_code: line.itemCode, app_key: appKey, warehouse_id: warehouseId, store_id: storeId, }, transaction }); } else { wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction }); } // 如果没有itemId,直接记录错误 if (!wms_stock) { errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`); continue; } const itemId = parseInt(wms_stock.id); // ========== 核心库存检查逻辑 ========== const stockResult = await ctx.service.systems.stockStore.getItemStorages(wms_stock.id, transaction); if (!stockResult.success) { errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n${stockResult.error}`); continue; } const { stock, storage } = stockResult.data; const stockId = storage.id; if (!stockId) { errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存记录不存在`); continue; } if (processedItemIds.has(itemId)) { errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》在同一订单中重复出现`); continue; } processedItemIds.add(itemId); const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty; stockQuantityMap.set(stockId, totalQtyForStock); // 记录商品重量(如果storage中有grossWeight) if (storage.grossWeight !== undefined && storage.grossWeight !== null) { const weight = parseFloat(storage.grossWeight) || 0; stockWeightMap.set(stockId, weight); } else { // 如果库存中没有重量信息,记录0 stockWeightMap.set(stockId, 0); } if (storage.canUse < totalQtyForStock) { errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存不足,可用 ${storage.canUse},需求 ${totalQtyForStock}`); stockQuantityMap.set(stockId, totalQtyForStock - planQty); continue; } // 锁定库存 const lockResult = await ctx.service.systems.stockStore.lockItemStorages( storage.id, planQty, transaction ); if (!lockResult.success) { errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`); stockQuantityMap.set(stockId, totalQtyForStock - planQty); continue; } // ========== 库存检查逻辑结束 ========== // 所有检查通过,准备订单行数据 lineData.push({ order_id: orderId, actual_price: this.safeParseFloat(line.actualPrice, 0), retail_price: this.safeParseFloat(line.retailPrice, 0), ext_code: line.extCode || '', inventory_type: line.inventoryType || '', item_code: line.itemCode || '', item_id: line.itemId || null, item_name: line.itemName || '', order_line_no: line.orderLineNo || `${i + 1}`, owner_code: line.ownerCode || '', plan_qty: planQty, source_order_code: line.sourceOrderCode || '', sub_source_order_code: line.subSourceOrderCode || '', extend_props: line.extendProps ? (typeof line.extendProps === 'string' ? line.extendProps : JSON.stringify(line.extendProps)) : null, // 可选:记录重量信息到明细 item_weight: stockWeightMap.get(stockId) || 0, }); } // ========== 计算订单统计信息 ========== let items_str = ''; let total_weight = 0; // 总重量 let stock_count = 0; // stock种类数 let item_total_count = 0; // 商品总数 if (stockQuantityMap.size > 0) { // 生成结构字符串 const sortedStocks = Array.from(stockQuantityMap.entries()) .sort(([ stockIdA ], [ stockIdB ]) => stockIdA - stockIdB) .map(([ stockId, quantity ]) => { // 可选:在字符串中包含重量信息 const weight = stockWeightMap.get(stockId) || 0; return `${stockId}+${quantity}${weight > 0 ? `@${weight}` : ''}`; }); items_str = sortedStocks.join('|'); // 计算统计信息 stock_count = stockQuantityMap.size; // stock种类数 // 计算商品总数 item_total_count = Array.from(stockQuantityMap.values()) .reduce((sum, quantity) => sum + (parseInt(quantity) || 0), 0); // 计算总重量:重量 × 数量 total_weight = Array.from(stockQuantityMap.entries()) .reduce((sum, [ stockId, quantity ]) => { const weight = stockWeightMap.get(stockId) || 0; const qty = parseInt(quantity) || 0; return sum + (weight * qty); }, 0); // 格式化重量(保留2位小数) total_weight = parseFloat(total_weight.toFixed(2)); ctx.logger.debug('[订单统计信息]', { orderId, stock_count, item_total_count, total_weight, items_str_length: items_str.length, items_preview: items_str.substring(0, 100) + (items_str.length > 100 ? '...' : ''), }); } if (errors.length > 0) { throw new Error(`创建订单错误:\n${errors.join('\n')}`); } if (lineData.length === 0) { throw new Error('没有有效的商品明细可以创建'); } // 批量创建订单明细 await OrderItemsModel.bulkCreate(lineData, { transaction }); ctx.logger.info(`成功添加 ${lineData.length} 个订单明细项,订单ID: ${orderId}`); // 返回完整信息 return { length: lineData.length, // 商品种类数(与stock_count相同) items_str, // 结构字符串 stock_count, // stock种类数 item_total_count, // 商品总数 total_weight, // 总重量 stock_quantity_map: Object.fromEntries(stockQuantityMap), // stock_id -> 数量 stock_weight_map: Object.fromEntries(stockWeightMap), // stock_id -> 单件重量 line_data: lineData, // 创建的明细数据 stats: { // 统计信息汇总 unique_items: stock_count, total_items: item_total_count, total_weight, avg_weight_per_item: stock_count > 0 ? (total_weight / item_total_count).toFixed(2) : 0, }, }; } // 添加工具方法 safeParseFloat(value, defaultValue = 0) { if (value === null || value === undefined) return defaultValue; const num = parseFloat(value); return isNaN(num) ? defaultValue : num; } // 订单入队列(异步处理) async addOrderToQueue(orderId, warehouseId) { const { ctx, app } = this; try { const queueData = { orderId, warehouseId, timestamp: Date.now(), action: 'order_created', }; } catch (error) { } } } module.exports = DeliveryOrderService;