'use strict'; const Service = require('egg').Service; class entryOrderService extends Service { /** * 创建入库单(含明细行校验与插入)。 * @param {Object} data 请求体,包含 request.entryOrder 与 request.orderLines * @param {Object} info 上下文信息 { storeId, warehouseId, appKey, customerId, warehouseCode } * @param {string} fromCode 来源标识(WMS / API / QM) * @param {Object} [options={}] 可选配置 * @param {boolean} [options.autoReview=false] 是否自动审核,true 时入库单创建后状态直接变为 PENDING * @return {Promise} { success, message, data: { entryOrderId, entryOrderCode, createTime, warehouseCode, status } } */ async addOrder(data, info, fromCode, options = {}) { const { autoReview = false } = options; const { storeId, warehouseId, appKey, customerId, warehouseCode } = info; const { app, ctx } = this; const transaction = await app.model.transaction(); // 开启事务 try { let totalOrderLines = data.request.entryOrder.totalOrderLines || 0; let orderLine = data.request.orderLines.orderLine; if (orderLine.itemCode) { orderLine = [ orderLine ]; } totalOrderLines = totalOrderLines || orderLine.length; let errors = []; const items = []; // 验证商品 for (let i = 0; i < orderLine.length; i++) { let wms_stock = null; // ERP不处理WMS的外部商品编码 // 查找唯一键 const findByItemCode = async () => { if (!orderLine[i].itemCode) return null; return await app.model.StockStore.findOne({ where: { item_code: orderLine[i].itemCode, app_key: appKey, warehouse_id: warehouseId, store_id: storeId, }, transaction }); }; if (!orderLine[i].itemId) { wms_stock = await findByItemCode(); } else { wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId, { transaction }); // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 if (wms_stock && Number(wms_stock.store_id) !== Number(storeId)) { wms_stock = null; } // 外部渠道 itemId 可能是平台商品标识或条码而非 WMS 主键, // 主键查不到或跨货主时降级按 item_code 查找,避免误报“未同步推送到仓库” if (!wms_stock) { wms_stock = await findByItemCode(); } } 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); } if (errors.length > 0) { await transaction.rollback(); // 验证失败,回滚事务 return { success: false, message: `创建入库单失败,失败原因:\n${errors.join('\n')}`, data: { createTime: new Date(), }, }; } // 创建入库单(内部也使用事务),autoReview 在 addOrder 层控制最终状态 const order = await this.tryCreateEntryOrder( data.request.entryOrder, appKey, storeId, warehouseId, totalOrderLines, fromCode, customerId, warehouseCode, transaction // 传递事务 ); 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 (let i = 0; i < items.length; i++) { const item = items[i]; const res = await this.addItems(item, orderId, transaction); 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); const expectedTotalOrderLines = Number(totalOrderLines) || 0; // autoReview 决定最终状态:true → PENDING(已审核),false → CREATED(已创建待审核) const finalStatus = autoReview ? 'PENDING' : 'CREATED'; if (lineCount === expectedTotalOrderLines) { // 所有明细行已插入完毕,将状态从 CREATING 更新为目标状态 await app.model.EntryOrder.update( { order_status: finalStatus, updated_at: new Date() }, { where: { id: orderId, warehouse_id: warehouseId, store_id: storeId }, transaction } ); } // 写入操作日志 await ctx.service.systems.operationLog.createOperationLog({ businessType: 'entry_order', businessId: orderId, operationCode: 'ENTRY_ORDER_CREATE', operator: { id: ctx.user?.employees_id || ctx.user?.id || '', name: ctx.user?.employees_name || '', }, extras: { warehouseId, storeId, entryOrderCode: orderCode, sourceType: fromCode, totalOrderLines, finalStatus, }, transaction, }); // 提交事务 await transaction.commit(); // 异步匹配收货单并写入绑定关系(不阻塞 addOrder 返回) if (lineCount === expectedTotalOrderLines) { setImmediate(() => { ctx.service.systems.receivingEntryMatch.matchAfterEntryCompleted(orderId).catch(err => { ctx.logger.error(`[addOrder] 异步匹配收货单异常: ${err.message}`, err.stack); }); }); } if (lineCount === expectedTotalOrderLines) { return { success: true, message: '入库单创建完成', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, status: finalStatus, }, }; } // 部分接收或等待接收 return { success: true, message: '入库单创建中', data: { entryOrderId: orderId, entryOrderCode: orderCode, createTime: new Date(), warehouseCode, status: 'CREATING', }, }; } catch (error) { // 发生异常,回滚事务 await transaction.rollback().catch(e => ctx.logger.error(`回滚事务失败: ${e.message}`, e)); ctx.logger.error(`addOrder 事务异常: ${error.message}`, error); return { success: false, message: `系统异常: ${error.message}`, data: { createTime: new Date(), }, }; } } /** * 获取入库单的明细行数(支持事务)。 * @param {number} orderId 入库单ID * @param {Object|null} [transaction=null] 可选事务对象 * @return {Promise} 明细行数 */ 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; } /** * 标记入库单为已完成(支持事务)。 * @param {number} orderId 入库单ID * @param {number} warehouseId 仓库ID * @param {number} storeId 货主ID * @param {Object|null} [transaction=null] 可选事务对象 * @return {Promise} */ 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: [ 'item_code', 'item_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, 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 = { CREATED: [ 'PENDING', 'CANCELLED' ], PENDING: [ 'COMPLETED', 'CANCELLED' ], CREATING: [ 'CREATED', '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, }; } /** * 尝试创建入库单(含去重与状态校验)。 * 若入库单已存在且状态为 CREATING,则复用该记录;否则新建,初始状态为 CREATING。 * 最终状态(CREATED / PENDING)由调用方 addOrder 根据 autoReview 决定。 * @param {Object} order 入库单基本信息 * @param {string} appKey 应用标识 * @param {number} storeId 货主ID * @param {number} warehouseId 仓库ID * @param {number} totalOrderLines 总行数 * @param {string} sourceType 来源类型(WMS / API / QM) * @param {string|null} qimenOwnerCode 奇门货主编码 * @param {string|null} qimenWarehouseCode 奇门仓库编码 * @param {Object|null} [transaction=null] 外部事务对象 * @return {Promise} { success, code, message, entryOrderId, entryOrderCode, orderStatus, error? } */ async tryCreateEntryOrder(order, appKey, storeId, warehouseId, totalOrderLines, sourceType, qimenOwnerCode, qimenWarehouseCode, transaction = null) { const { ctx } = this; 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); 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.expectEndTime ? new Date(order.expectEndTime) : 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(); } return { success: true, code: 1, message: '入库单创建成功,状态设置为接收中', entryOrderId: newEntryOrder.id, entryOrderCode: newEntryOrder.entry_order_code, }; } catch (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 { ctx } = this; 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) { throw error; } } return { success: true, code: 1, message: '商品已存在,跳过重复添加', }; } catch (error) { console.error('添加入库单商品失败:', error); return { success: false, code: 0, message: `添加商品失败: ${error.message}`, error: error.message, }; } } /** * 审核入库单(CREATED → PENDING)。 * 只允许已绑定收货单的入库单推进状态,未绑定则拒绝。 * * @param {Object} data 请求体 * @param {number} data.id 入库单 ID * @return {Promise} { success, message, data } */ async reviewEntry(data = {}) { const { app, ctx } = this; const orderId = Number(data.id || 0); if (!orderId) { return { success: false, message: 'id 必填' }; } const entryOrder = await app.model.EntryOrder.findOne({ where: { id: orderId, is_enabled: 1, deleted_at: null }, }); if (!entryOrder) { return { success: false, message: '入库单不存在' }; } if (entryOrder.order_status !== 'CREATED') { return { success: false, message: `当前状态[${entryOrder.order_status}]不允许审核,仅 CREATED 可审核`, }; } // 校验:必须有绑定的收货单 const hasReceiving = await ctx.model.EntryOrderReceiving.findOne({ where: { entry_order_id: orderId, deleted_at: null }, }); if (!hasReceiving) { return { success: false, message: '入库单未绑定收货单,请先绑定收货单后再审核', }; } // 推进状态 await entryOrder.update({ order_status: 'PENDING', updated_at: new Date(), }); // 写操作日志 await ctx.service.systems.operationLog.createOperationLog({ businessType: 'entry_order', businessId: entryOrder.id, operationCode: 'ENTRY_ORDER_REVIEW', operator: { id: ctx.user?.employees_id || ctx.user?.id || '', name: ctx.user?.employees_name || '', }, extras: { warehouseId: entryOrder.warehouse_id, message: '入库单审核通过(CREATED → PENDING)', }, }); return { success: true, message: '审核成功', data: { id: entryOrder.id, order_status: 'PENDING' }, }; } } module.exports = entryOrderService;