'use strict'; const Service = require('egg').Service; class entryOrderService extends Service { async addOrder(data, info, fromCode) { const { storeId, warehouseId, appKey, customerId, warehouseCode } = info; const { app } = this; const transaction = await app.model.transaction(); // 开启事务 try { console.log('入库单开始接收处理'); let totalOrderLines = data.request.entryOrder.totalOrderLines || 0; let orderLine = data.request.orderLines.orderLine; if (orderLine.itemCode) { orderLine = [ orderLine ]; } console.log('orderLine', orderLine); const isSingle = totalOrderLines ? 0 : 1; totalOrderLines = totalOrderLines || orderLine.length; let errors = []; const items = []; console.log('循环开始'); // 验证商品 for (var i = 0; i < orderLine.length; i++) { let wms_stock = null; // ERP不处理WMS的外部商品编码 if (!orderLine[i].itemId) { console.log('ERP不处理WMS的外部商品编码'); // 查找唯一键 wms_stock = await app.model.StockStore.findOne({ where: { item_code: orderLine[i].itemCode, app_key: appKey, warehouse_id: warehouseId, store_id: storeId, }, transaction }); } else { wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId, { transaction }); } if (!wms_stock) { errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`); continue; } if (!wms_stock.stock_id) { errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》wms无对应关系\n请联系仓库关联创建商品`); continue; } wms_stock.inventory_type = orderLine[i].inventoryType || 'ZP'; wms_stock.order_line_no = orderLine[i].orderLineNo || i + 1; wms_stock.count = orderLine[i].planQty; wms_stock.item_id = orderLine[i].itemId || wms_stock.id; items.push(wms_stock); } console.log('items>>>>>', items); if (errors.length > 0) { await transaction.rollback(); // 验证失败,回滚事务 return { success: false, message: '创建入库单失败,失败原因:\n' + errors.join('\n'), data: { createTime: new Date(), }, }; } // 创建入库单(内部也使用事务) const order = await this.tryCreateEntryOrder( data.request.entryOrder, appKey, storeId, warehouseId, totalOrderLines, fromCode, customerId, warehouseCode, transaction // 传递事务 ); console.log('入库单参数', order); if (!order.success) { await transaction.rollback(); return { success: false, message: '创建入库单失败,失败原因:\n' + order.error, data: { createTime: new Date(), }, }; } const orderId = order.entryOrderId; const orderCode = order.entryOrderCode || data.request.entryOrder.entryOrderCode; errors = []; // 重置错误数组 // 添加商品明细 for (var i = 0; i < items.length; i++) { const item = items[i]; const res = await this.addItems(item, orderId, transaction); console.log('添加商品返回信息', res); if (!res.success) { errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); } } if (errors.length > 0) { await transaction.rollback(); // 商品添加失败,回滚整个事务 return { success: false, message: '创建入库单失败,失败原因:\n' + errors.join('\n'), data: { createTime: new Date(), }, }; } // 获取接收行数并处理状态 const lineCount = await this.getLineCount(orderId, transaction); if (lineCount == totalOrderLines) { // 所有行数接收完成 await this.received(orderId, warehouseId, storeId, transaction); } // 提交事务 await transaction.commit(); if (lineCount == totalOrderLines) { return { success: true, message: '入库单接收完毕', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, status: 'COMPLETED', }, }; } // 部分接收或等待接收 return { success: true, message: '入库单接收中', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, status: 'PARTIAL_RECEIVED', }, }; } catch (error) { // 发生异常,回滚事务 await transaction.rollback().catch(e => console.error('回滚事务失败:', e)); console.error('addOrder 事务异常:', error); return { success: false, message: `系统异常: ${error.message}`, data: { createTime: new Date(), }, }; } } // 辅助函数:获取行数(支持事务) async getLineCount(orderId, transaction = null) { const { app } = this; const options = { where: { order_id: orderId }, }; if (transaction) { options.transaction = transaction; } const count = await app.model.EntryItems.count(options); return count; } // 辅助函数:标记为已接收(支持事务) async received(orderId, warehouseId, storeId, transaction = null) { const { app } = this; const updateData = { order_status: 'COMPLETED', updated_at: new Date(), }; const where = { id: orderId, warehouse_id: warehouseId, store_id: storeId, }; if (transaction) { await app.model.EntryOrder.update(updateData, { where, transaction, }); } else { await app.model.EntryOrder.update(updateData, { where }); } } // 辅助函数:统一返回格式 success(message, data = {}) { return { success: true, message, data: { ...data, createTime: new Date(), }, }; } fail(message, data = {}) { return { success: false, message, data: { ...data, createTime: new Date(), }, }; } async findByOrderCode(entryOrderCode, warehouseId, storeId) { const { ctx } = this; return await ctx.model.EntryOrder.findOne({ where: { entry_order_code: entryOrderCode, warehouse_id: warehouseId, store_id: storeId, is_enabled: 1, deleted_at: null, }, include: [ { model: ctx.model.Store, as: 'warehouse', attributes: [[ 'company_name', 'store_name' ]], }, { model: ctx.model.Store, as: 'store', attributes: [[ 'company_name', 'store_name' ]], }, { model: ctx.model.EntryItems, as: 'items', include: [ { model: ctx.model.StockWarehouse, as: 'stock', attributes: [ 'product_code', 'product_name' ], }, ], }, ], }); } async findByStatus(status, params = {}) { const { ctx, app } = this; const { warehouse_id, store_id, start_date, end_date, page = 1, pageSize = 20 } = params; const where = { order_status: status, is_enabled: 1, deleted_at: null, }; if (warehouse_id) { where.warehouse_id = warehouse_id; } if (store_id) { where.store_id = store_id; } if (start_date || end_date) { where.created_at = {}; if (start_date) { where.created_at[app.Sequelize.Op.gte] = start_date; } if (end_date) { where.created_at[app.Sequelize.Op.lte] = end_date; } } const currentPage = Math.max(Number(page) || 1, 1); const currentPageSize = Math.max(Number(pageSize) || 20, 1); const { count, rows } = await ctx.model.EntryOrder.findAndCountAll({ where, include: [ { model: ctx.model.Store, as: 'warehouse', attributes: [[ 'company_name', 'store_name' ]], }, { model: ctx.model.Store, as: 'store', attributes: [[ 'company_name', 'store_name' ]], }, ], order: [[ 'created_at', 'DESC' ]], offset: (currentPage - 1) * currentPageSize, limit: currentPageSize, distinct: true, }); return { list: rows, pagination: { page: currentPage, pageSize: currentPageSize, total: count, totalPages: Math.ceil(count / currentPageSize), }, }; } async getStatsByWarehouse(warehouseId, startDate, endDate) { const { ctx, app } = this; const where = { warehouse_id: warehouseId, is_enabled: 1, deleted_at: null, }; if (startDate || endDate) { where.created_at = {}; if (startDate) { where.created_at[app.Sequelize.Op.gte] = startDate; } if (endDate) { where.created_at[app.Sequelize.Op.lte] = endDate; } } const result = await ctx.model.EntryOrder.findAll({ attributes: [ 'order_status', [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'count' ], [ app.Sequelize.fn('SUM', app.Sequelize.col('total_order_lines')), 'total_lines' ], ], where, group: [ 'order_status' ], raw: true, }); const stats = { pending: 0, confirmed: 0, partial_received: 0, completed: 0, cancelled: 0, total: 0, total_lines: 0, }; result.forEach(item => { const status = String(item.order_status || '').toLowerCase(); const count = parseInt(item.count, 10) || 0; const totalLines = parseInt(item.total_lines, 10) || 0; if (stats[status] !== undefined) { stats[status] = count; } stats.total += count; stats.total_lines += totalLines; }); return stats; } async updateSyncStatus(orderId, status, message = null, options = {}) { const { ctx } = this; const order = await ctx.model.EntryOrder.findByPk(orderId, { transaction: options.transaction, }); if (!order) { throw new Error('入库单不存在'); } const updateData = { sync_status: status, }; if (message !== null) { updateData.sync_message = message; } return await order.update(updateData, { transaction: options.transaction, }); } async updateOrderStatus(orderId, status, options = {}) { const { ctx } = this; const order = await ctx.model.EntryOrder.findByPk(orderId, { transaction: options.transaction, }); if (!order) { throw new Error('入库单不存在'); } const validTransitions = { PENDING: [ 'CONFIRMED', 'CANCELLED' ], CONFIRMED: [ 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED' ], PARTIAL_RECEIVED: [ 'COMPLETED', 'CANCELLED' ], CREATED: [ 'PENDING', 'CANCELLED' ], CREATING: [ 'PENDING', 'CANCELLED' ], }; const allowedTransitions = validTransitions[order.order_status]; if (!allowedTransitions || !allowedTransitions.includes(status)) { throw new Error(`状态从${order.order_status}转换到${status}不被允许`); } return await order.update({ order_status: status }, { transaction: options.transaction, }); } async calculateReceivedQuantities(orderId) { const { ctx, app } = this; const order = await ctx.model.EntryOrder.findByPk(orderId, { attributes: [ 'id', 'entry_order_code' ], raw: true, }); if (!order) { throw new Error('入库单不存在'); } const items = await ctx.model.EntryItems.findAll({ where: { order_id: orderId }, attributes: [ 'id', 'count', 'item_id' ], raw: true, }); const itemIds = [ ...new Set(items.map(item => item.item_id).filter(Boolean)) ]; const receivedRows = itemIds.length > 0 ? await ctx.model.Storage.findAll({ where: { inbound_order_no: order.entry_order_code, item_id: itemIds, }, attributes: [ 'item_id', [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'received' ], ], group: [ 'item_id' ], raw: true, }) : []; const receivedMap = new Map( receivedRows.map(row => [ Number(row.item_id), Number(row.received) || 0 ]) ); let totalExpected = 0; let totalReceived = 0; let allReceived = items.length > 0; let anyReceived = false; items.forEach(item => { const expected = Number(item.count) || 0; const received = receivedMap.get(Number(item.item_id)) || 0; totalExpected += expected; totalReceived += received; if (expected > 0 && received < expected) { allReceived = false; } if (received > 0) { anyReceived = true; } }); return { total_expected: totalExpected, total_received: totalReceived, all_received: allReceived, any_received: anyReceived, percentage: totalExpected > 0 ? Math.round((totalReceived / totalExpected) * 100) : 0, }; } async batchUpdateReceived(updates, options = {}) { const { ctx } = this; const externalTransaction = options.transaction || null; const transaction = externalTransaction || await ctx.model.transaction(); try { const pendingUpdates = []; for (const update of updates) { const { id, quantity } = update; const item = await ctx.model.EntryItems.findByPk(id, { transaction }); if (!item) { throw new Error(`入库明细 ${id} 不存在`); } item.validateReceiveQuantity(quantity); pendingUpdates.push({ item, quantity, }); } for (const pending of pendingUpdates) { const newReceived = (pending.item.received_quantity || 0) + pending.quantity; await pending.item.update({ received_quantity: newReceived, }, { transaction }); } if (!externalTransaction) { await transaction.commit(); } return { success: true }; } catch (error) { if (!externalTransaction) { await transaction.rollback(); } throw error; } } async getOrderProgress(orderId) { const { ctx, app } = this; const items = await ctx.model.EntryItems.findAll({ where: { order_id: orderId }, attributes: [ [ app.Sequelize.fn('SUM', app.Sequelize.col('count')), 'total_plan' ], [ app.Sequelize.fn('SUM', app.Sequelize.col('received_quantity')), 'total_received' ], [ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'item_count' ], ], raw: true, }); const result = items[0] || {}; const totalPlan = parseInt(result.total_plan, 10) || 0; const totalReceived = parseInt(result.total_received, 10) || 0; return { total_plan: totalPlan, total_received: totalReceived, total_remaining: Math.max(0, totalPlan - totalReceived), item_count: parseInt(result.item_count, 10) || 0, progress_percent: totalPlan > 0 ? Math.min(100, Math.round((totalReceived / totalPlan) * 100)) : 0, is_completed: totalReceived >= totalPlan, }; } async tryCreateEntryOrder(order, appKey, storeId, warehouseId, totalOrderLines, sourceType, qimenOwnerCode, qimenWarehouseCode, transaction = null) { const { app } = this; const { ctx } = this; console.log('创建入库单信息', order, appKey, storeId, warehouseId); try { const options = transaction ? { transaction } : {}; // 1. 检查入库单是否已存在 const existingOrder = await ctx.model.EntryOrder.findOne({ where: { entry_order_code: order.entryOrderCode, warehouse_id: warehouseId, store_id: storeId, }, ...options, }); // 2. 如果入库单已存在 if (existingOrder) { const allowedStatuses = [ 'CREATING' ]; if (allowedStatuses.includes(existingOrder.order_status)) { // 状态在允许范围内,更新为接收中状态 await existingOrder.update({ order_status: 'CREATING', updated_at: new Date(), }, options); console.log(`入库单 ${order.entryOrderCode} 已存在,状态更新为接收中`); return { success: true, code: 1, message: '入库单已存在,状态已更新为接收中', entryOrderId: existingOrder.id, entryOrderCode: existingOrder.entry_order_code, orderStatus: 'CREATING', items: existingOrder.items || [], data: { entryOrder: { id: existingOrder.id, entryOrderCode: existingOrder.entry_order_code, orderType: existingOrder.order_type, orderStatus: existingOrder.order_status, totalOrderLines, }, }, }; } // 其他状态返回错误 const statusName = existingOrder.getOrderStatusName ? existingOrder.getOrderStatusName() : existingOrder.order_status; return { success: false, code: 0, message: `入库单已存在,当前状态为${statusName},无法重复创建`, entryOrderId: existingOrder.id, entryOrderCode: existingOrder.entry_order_code, orderStatus: existingOrder.order_status, error: `入库单已存在,状态: ${statusName}`, }; } // 3. 入库单不存在,创建新的入库单 // 如果外部传入了事务,使用外部事务;否则创建新事务 const internalTransaction = transaction ? null : await ctx.model.transaction(); const currentTransaction = transaction || internalTransaction; try { const warehouse_data = await this.ctx.service.systems.store.getStoreName(warehouseId); let store_name = null; let warehouse_name = null; if (warehouse_data.code == 200) { warehouse_name = warehouse_data.data.company_name; } const store_data = await this.ctx.service.systems.store.getStoreName(storeId); if (store_data.code == 200) { store_name = store_data.data.company_name; } const contract_data = await this.ctx.service.systems.store.getStoreRemaskName(storeId, warehouseId); let contract = null; if (contract_data.code == 200) { contract = contract_data.data; } // 构建入库单数据 const entryOrderData = { entry_order_code: order.entryOrderCode, order_type: order.orderType, purchase_order_code: order.relatedOrders?.relatedOrder?.orderCode || '', total_order_lines: totalOrderLines, order_create_time: order.orderCreateTime ? new Date(order.orderCreateTime) : new Date(), expect_start_time: order.expectStartTime ? new Date(order.expectStartTime) : new Date(), expect_end_time: order.expectStartTime ? new Date(order.expectStartTime) : new Date(), logistics_code: order.logisticsCode || '', logistics_name: order.logisticsName || '', express_code: order.expressCode || '', supplier_code: order.supplierCode || '', supplier_name: order.supplierName || '', source_type: sourceType, order_status: 'CREATING', sync_status: 'PENDING', sync_message: '', is_enabled: 1, warehouse_id: warehouseId, store_id: storeId, store_name: contract.store_remask || store_name, warehouse_name: contract.warehouse_remask || warehouse_name, remark: order.remark || '', qimen_owner_code: qimenOwnerCode || '', qimen_warehouse_code: qimenWarehouseCode || '', }; // 创建入库单 const newEntryOrder = await ctx.model.EntryOrder.create(entryOrderData, { transaction: currentTransaction, }); // 如果这是内部创建的事务,提交它 if (internalTransaction) { await internalTransaction.commit(); } console.log(`成功创建入库单: ${order.entryOrderCode}, ID: ${newEntryOrder.id}`); return { success: true, code: 1, message: '入库单创建成功,状态设置为接收中', entryOrderId: newEntryOrder.id, entryOrderCode: newEntryOrder.entry_order_code, }; } catch (error) { console.log('创建入库单失败', error); // 如果这是内部创建的事务,回滚它 if (internalTransaction) { await internalTransaction.rollback(); } throw error; } } catch (error) { console.error('创建入库单失败:', error); return { success: false, code: 0, message: `创建入库单异常: ${error.message}`, entryOrderId: null, entryOrderCode: null, orderStatus: null, error: error.message, }; } } async addItems(item, orderId, transaction = null) { const { app } = this; const { ctx } = this; console.log('添加入库单商品'); try { const options = transaction ? { transaction } : {}; // 检查商品是否已存在 const existingOrderItem = await ctx.model.EntryItems.findOne({ where: { order_id: orderId, order_line_no: item.order_line_no, }, ...options, }); if (!existingOrderItem) { try { // 构建入库明细数据 const entryItemsData = { order_id: orderId, out_biz_code: item.out_biz_code || '', order_line_no: item.order_line_no || '', owner_code: item.owner_code || '', item_code: item.item_code || '', item_id: item.item_id || 0, count: item.count || 0, inventory_type: item.inventory_type || '', stock_id: item.stock_id || '', }; // 创建入库明细 await ctx.model.EntryItems.create(entryItemsData, { transaction, }); return { success: true, code: 1, }; } catch (error) { console.log('添加商品明细出错', error); throw error; } } return { success: true, code: 1, message: '商品已存在,跳过重复添加', }; } catch (error) { console.error('添加入库单商品失败:', error); return { success: false, code: 0, message: `添加商品失败: ${error.message}`, error: error.message, }; } } async received(orderId, warehouseId, storeId, transaction = null) { console.log('完结传参', orderId, warehouseId, storeId); const { app } = this; const { ctx } = this; const options = transaction ? { transaction } : {}; const existingOrder = await ctx.model.EntryOrder.findOne({ where: { warehouse_id: warehouseId, store_id: storeId, id: orderId, }, ...options, }); if (!existingOrder) { return { success: false, code: 0, message: '入库单不存在', entryOrderId: null, orderStatus: null, error: '入库单不存在', }; } const allowedStatuses = [ 'CREATING' ]; if (allowedStatuses.includes(existingOrder.order_status)) { await existingOrder.update({ order_status: 'CREATED', updated_at: new Date(), }, options); } return { success: true, code: 1, message: '完成', }; } async qimenEntryorderConfirm(entryOrder, orderLines, isFin, outBizCode) { if (orderLines.length < 1) { throw new Error('行不能为空'); } console.log('isFin:', isFin); const queryData = { request: { entryOrder: { entryOrderCode: entryOrder.entry_order_code, ownerCode: entryOrder.qimen_owner_code, warehouseCode: entryOrder.qimen_warehouse_code, entryOrderId: entryOrder.id, entryOrderType: entryOrder.order_type, outBizCode, confirmType: isFin ? 0 : 1, status: isFin ? 'FULFILLED' : 'PARTFULFILLED', freight: 0, operateTime: new Date().format(), remark: entryOrder.remark, }, orderLines, }, }; const Result = await this.ctx.service.systems.qimenQuery.send('taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, queryData); return Result; } async entryorderConfirm(orderId, isCompleted) { const { app, ctx } = this; const transaction = await app.model.transaction(); try { // 锁定数据 const entryOrder = await app.model.EntryOrder.findOne({ where: { id: orderId, is_enabled: 1, deleted_at: null, }, include: [ { model: app.model.EntryItems, as: 'items', lock: transaction.LOCK.UPDATE, }, ], lock: transaction.LOCK.UPDATE, transaction, }); if (!entryOrder) { await transaction.rollback(); return { success: false, message: '入库单不存在' }; } // 状态检查 const allowedStatuses = [ 'CREATED', 'PARTIAL_RECEIVED', 'CONFIRMED' ]; if (!allowedStatuses.includes(entryOrder.order_status)) { await transaction.rollback(); return { success: false, code: 'INVALID_STATUS', message: `入库单状态[${entryOrder.order_status}]不允许确认`, }; } const orderLines = []; let totalPlanQty = 0; let totalReceivedQty = 0; let totalConfirmIncrement = 0; let hasItemsToConfirm = false; // 第一阶段:计算和验证,不执行更新 const pendingUpdates = []; for (let i = 0; i < entryOrder.items.length; i++) { const item = entryOrder.items[i]; const planQty = item.count || 0; const receivedQty = item.received_quantity || 0; const confirmedQty = item.confirm_quantity || 0; // 计算本次确认的增量 const confirmIncrement = Math.max(0, receivedQty - confirmedQty); if (confirmIncrement > 0) { hasItemsToConfirm = true; // 奇门需要的是本次确认的数量(actualQty) const orderLine = { orderLineNo: i + 1, ownerCode: item.owner_code, itemCode: item.item_code, itemId: item.item_id, inventoryType: item.inventory_type, planQty, actualQty: confirmIncrement, // 传本次增量 }; orderLines.push(orderLine); totalConfirmIncrement += confirmIncrement; // 记录待更新数据(不执行) pendingUpdates.push({ id: item.id, item_id: item.item_id, new_confirm_quantity: confirmedQty + confirmIncrement, old_confirm_quantity: confirmedQty, received_quantity: receivedQty, confirm_increment: confirmIncrement, }); } totalPlanQty += planQty; totalReceivedQty += receivedQty; } // 没有需要确认的数量 if (!hasItemsToConfirm) { await transaction.rollback(); return { success: false, message: '没有需要确认的收货数量' }; } // 判断是否最终完成 const isFin = isCompleted ? true : (totalReceivedQty >= totalPlanQty); let qimenResult = {}; let queryId = null; // 奇门入库单,数据同步到奇门 if (entryOrder.source_type == 'QM') { // 第二阶段:调用奇门接口 const Result = await this.qimenEntryorderConfirm( entryOrder, orderLines, isFin, Math.round(new Date() / 1000) ); console.log(Result); queryId = Result.queryId; qimenResult = Result.xmlArray.response; // 奇门调用失败,回滚事务 if (!qimenResult || qimenResult.flag != 'success') { await transaction.rollback(); console.error('奇门接口调用失败:', qimenResult); return { success: false, code: 'QIMEN_FAILED', message: '奇门接口调用失败', detail: qimenResult?.message || '未知错误', }; } } // 第三阶段:奇门成功,执行数据库更新 // 1. 更新确认数量 for (const update of pendingUpdates) { const result = await app.model.EntryItems.update({ confirm_quantity: update.new_confirm_quantity, updated_at: new Date(), }, { where: { id: update.id, confirm_quantity: update.old_confirm_quantity, // 乐观锁,防止并发 }, transaction, }); const res = await ctx.service.systems.stockStore.inbound(update.item_id, update.confirm_increment, transaction); console.log('增加库存返回', res); if (result[0] === 0) { // 更新失败,可能被并发修改了 console.warn(`更新入库明细失败,可能已被修改: id=${update.id}`); // 可以选择重试或抛出异常 } } // 2. 更新入库单状态 let newOrderStatus = entryOrder.order_status; if (isFin) { newOrderStatus = 'COMPLETED'; } else if (totalConfirmIncrement > 0) { if (entryOrder.order_status === 'CREATED') { newOrderStatus = 'CONFIRMED'; } else { newOrderStatus = 'PARTIAL_RECEIVED'; } } const updateResult = await app.model.EntryOrder.update({ order_status: newOrderStatus, sync_status: 'SUCCESS', sync_message: JSON.stringify({ confirmTime: new Date(), totalPlan: totalPlanQty, totalReceived: totalReceivedQty, totalConfirmIncrement, isFin, pendingUpdatesCount: pendingUpdates.length, qimenResult: qimenResult?.data || {}, }), updated_at: new Date(), }, { where: { id: entryOrder.id, order_status: entryOrder.order_status, // 乐观锁 }, transaction, }); if (updateResult[0] === 0) { // 入库单状态已被修改,回滚 await transaction.rollback(); return { success: false, code: 'CONCURRENT_MODIFICATION', message: '入库单已被修改,请刷新后重试', }; } // 4. 提交事务 await transaction.commit(); console.log(`入库单确认成功: id=${entryOrder.id}, 确认增量=${totalConfirmIncrement}, 状态=${newOrderStatus}`); return { success: true, message: isFin ? '入库单完成确认' : '入库单增量确认成功', data: { entryOrderId: entryOrder.id, entryOrderCode: entryOrder.entry_order_code, orderStatus: newOrderStatus, totalPlan: totalPlanQty, totalReceived: totalReceivedQty, totalConfirmIncrement, isFin, updatedItemsCount: pendingUpdates.length, orderLinesCount: orderLines.length, }, }; } catch (error) { // 发生异常,回滚事务 await transaction.rollback().catch(e => { console.error('回滚事务失败:', e); }); console.error('确认入库单失败:', error); return { success: false, code: 'SYSTEM_ERROR', message: `系统异常: ${error.message}`, stack: process.env.NODE_ENV === 'development' ? error.stack : undefined, }; } } } module.exports = entryOrderService;