'use strict'; const Service = require('egg').Service; class LocationService extends Service { /** * 创建货架并自动生成仓位 * @param {Object} params 货架基础参数 */ async createRackWithSpaces(params) { const { ctx } = this; const { app } = ctx; // 开启事务 return await app.model.transaction(async transaction => { // 1. 创建货架 const rack = await app.model.LocationZone.create({ ...params, zone_type: 'rack', is_active: true, }, { transaction }); // 2. 自动生成仓位 await this._generateSpacesForRack(rack.id, rack, transaction); // 3. 计算库区内的货架排序 if (rack.parent_id) { await this._calculateAreaRackOrder(rack.warehouse_id, rack.parent_id, transaction); } // 4. 计算拣货路径 await this._calculatePickPathForWarehouse(rack.warehouse_id, transaction); return rack; }); } /** * 为货架生成仓位 * @param {number|string} rackId 货架ID * @param {Object} rack 货架信息 * @param {Object} transaction 事务对象 */ async _generateSpacesForRack(rackId, rack, transaction) { const { app } = this; const { rack_columns, rack_rows, rack_levels } = rack; const spaces = []; // 计算每个仓位的尺寸 const cellLength = rack.length / rack_columns / 10; // mm转cm const cellWidth = rack.width / rack_levels / 10; // mm转cm const cellHeight = rack.height / rack_rows / 10; // mm转cm // 生成所有仓位 for (let row = 1; row <= rack_rows; row++) { for (let column = 1; column <= rack_columns; column++) { for (let level = 1; level <= rack_levels; level++) { const spaceCode = `${rack.zone_code}-${column.toString().padStart(2, '0')}-${row.toString().padStart(2, '0')}-${level.toString().padStart(2, '0')}`; // 计算相对坐标 const relativeX = (column - 1) * cellLength; const relativeY = (row - 1) * cellHeight; const relativeZ = (level - 1) * cellWidth; spaces.push({ warehouse_id: rack.warehouse_id, zone_id: rackId, location_type_id: 1, // 默认仓位类型 space_code: spaceCode, row_no: row.toString(), column_no: column.toString(), level_no: level.toString(), cell_no: `${column}-${row}-${level}`, length: cellLength, width: cellWidth, height: cellHeight, volume: cellLength * cellWidth * cellHeight / 1000000, // cm³转m³ max_weight: 100, // 默认100kg space_status: 'AVAILABLE', is_enabled: true, relative_x: relativeX, relative_y: relativeY, relative_z: relativeZ, }); } } } // 批量插入仓位 if (spaces.length > 0) { await app.model.LocationSpace.bulkCreate(spaces, { transaction }); } this.ctx.logger.info(`为货架 ${rack.zone_code} 生成了 ${spaces.length} 个仓位`); } /** * 计算库区内货架的排序(按X坐标排序) * @param {number|string} warehouseId 仓库ID * @param {number|string} areaId 库区ID * @param {Object} transaction 事务对象 */ async _calculateAreaRackOrder(warehouseId, areaId, transaction) { const { app } = this; // 获取库区内的所有货架,按X坐标排序 const racks = await app.model.LocationZone.findAll({ where: { warehouse_id: warehouseId, parent_id: areaId, zone_type: 'rack', is_active: true, deleted_at: null, }, order: [[ 'x', 'ASC' ]], transaction, }); // 更新排序序号 for (let i = 0; i < racks.length; i++) { await racks[i].update({ path_sequence: i + 1, }, { transaction }); } this.ctx.logger.info(`更新库区 ${areaId} 内 ${racks.length} 个货架的排序`); } /** * 计算仓库的拣货路径 * @param {number|string} warehouseId 仓库ID * @param {Object} transaction 事务对象 */ async _calculatePickPathForWarehouse(warehouseId, transaction) { const { app } = this; // 1. 获取起始拣货点 const pickStart = await app.model.LocationZone.findOne({ where: { warehouse_id: warehouseId, zone_type: 'pick_start', is_active: true, deleted_at: null, }, transaction, }); if (!pickStart) { this.ctx.logger.warn(`仓库 ${warehouseId} 没有设置起始拣货点`); return; } // 2. 获取所有货架,按距离排序 const racks = await app.model.LocationZone.findAll({ where: { warehouse_id: warehouseId, zone_type: 'rack', is_active: true, deleted_at: null, }, transaction, }); // 3. 计算距离并排序(曼哈顿距离) const sortedRacks = racks.map(rack => { const distance = Math.abs(rack.x - pickStart.x) + Math.abs(rack.y - pickStart.y); return { rack, distance, }; }).sort((a, b) => a.distance - b.distance); // 4. 更新货架的拣货顺序和距离 for (let i = 0; i < sortedRacks.length; i++) { const { rack, distance } = sortedRacks[i]; await rack.update({ path_sequence: i + 1, pick_distance: distance, }, { transaction }); // 5. 更新该货架下所有仓位的拣货顺序 await this._updateSpacePickSequence(rack.id, i + 1, distance, transaction); } this.ctx.logger.info(`为仓库 ${warehouseId} 计算了 ${sortedRacks.length} 个货架的拣货路径`); } /** * 更新货架下仓位的拣货顺序 * @param {number|string} rackId 货架ID * @param {number} rackSequence 货架拣货顺序 * @param {number} rackDistance 起始点距离 * @param {Object} transaction 事务对象 */ async _updateSpacePickSequence(rackId, rackSequence, rackDistance, transaction) { const { app } = this; // 获取货架信息 const rack = await app.model.LocationZone.findByPk(rackId, { transaction }); if (!rack) return; // 获取货架的所有仓位 const spaces = await app.model.LocationSpace.findAll({ where: { zone_id: rackId, is_enabled: true, deleted_at: null, }, order: [ [ 'row_no', 'ASC' ], // 从下层开始 [ 'column_no', 'ASC' ], // 从左到右 [ 'level_no', 'ASC' ], // 从外到内 ], transaction, }); // 更新每个仓位的拣货顺序 for (let i = 0; i < spaces.length; i++) { const space = spaces[i]; const spaceSequence = rackSequence * 1000 + i + 1; // 货架顺序 + 仓位顺序 // 计算预估拣货时间(基于层数) const row = parseInt(space.row_no) || 1; let pickTimeEstimate = 30; // 默认30秒 if (row <= 2) pickTimeEstimate = 25; // 下层快 else if (row <= 4) pickTimeEstimate = 40; // 中层需要梯子 else pickTimeEstimate = 60; // 上层需要设备 await space.update({ pick_sequence: spaceSequence, distance_from_start: rackDistance, pick_time_estimate: pickTimeEstimate, pick_priority: this._calculatePickPriority(row, rackDistance), }, { transaction }); } this.ctx.logger.info(`更新货架 ${rack.zone_code} 下 ${spaces.length} 个仓位的拣货顺序`); } /** * 计算拣货优先级 * @param {number} row 层数 * @param {number} distance 距离 */ _calculatePickPriority(row, distance) { // 行数越小(下层)优先级越高 const rowPriority = Math.max(1, 10 - (row || 1)); // 距离越近优先级越高 const distancePriority = Math.max(1, 10 - Math.floor(distance / 1000)); // 综合优先级(1-100) return Math.min(100, Math.max(1, rowPriority * 5 + distancePriority * 5)); } /** * 更新货架位置后重新计算路径 * @param {number|string} rackId 货架ID * @param {Object} newPosition 新坐标 */ async updateRackPosition(rackId, newPosition) { const { ctx, app } = this; return await app.model.transaction(async transaction => { // 1. 检查货架是否有占用仓位 const occupiedSpaces = await app.model.LocationSpace.count({ where: { zone_id: rackId, space_status: [ 'OCCUPIED', 'RESERVED' ], is_enabled: true, deleted_at: null, }, transaction, }); if (occupiedSpaces > 0) { ctx.throw(400, `货架有 ${occupiedSpaces} 个占用或预留仓位,不能修改位置`); } // 2. 更新货架位置 const rack = await app.model.LocationZone.findByPk(rackId, { transaction }); if (!rack) { ctx.throw(404, '货架不存在'); } await rack.update({ x: newPosition.x, y: newPosition.y, z: newPosition.z || rack.z, }, { transaction }); // 3. 重新计算库区内货架排序 if (rack.parent_id) { await this._calculateAreaRackOrder(rack.warehouse_id, rack.parent_id, transaction); } // 4. 重新计算拣货路径 await this._calculatePickPathForWarehouse(rack.warehouse_id, transaction); return rack; }); } /** * 获取拣货路径 * @param {number|string} warehouseId 仓库ID * @param {Object} options 查询选项 */ async getPickPath(warehouseId, options = {}) { const { app } = this; const { includeSpaces = false, limit = 50, sortBy = 'path_sequence', } = options; // 获取货架的拣货路径 const racks = await app.model.LocationZone.findAll({ where: { warehouse_id: warehouseId, zone_type: 'rack', is_active: true, deleted_at: null, }, order: [[ sortBy, 'ASC' ]], limit, include: includeSpaces ? [{ model: app.model.LocationSpace, as: 'spaces', where: { is_enabled: true, deleted_at: null, space_status: [ 'AVAILABLE', 'OCCUPIED' ], }, required: false, order: [[ 'pick_sequence', 'ASC' ]], }] : [], }); // 计算总距离和时间 let totalDistance = 0; let totalTime = 0; racks.forEach(rack => { if (rack.pick_distance) totalDistance += rack.pick_distance; if (rack.spaces) { rack.spaces.forEach(space => { if (space.pick_time_estimate) totalTime += space.pick_time_estimate; }); } }); return { racks, summary: { totalRacks: racks.length, totalDistance: `${(totalDistance / 1000).toFixed(2)}米`, estimatedTotalTime: `${Math.ceil(totalTime / 60)}分钟`, }, }; } /** * 批量更新邻居关系 * @param {number|string} warehouseId 仓库ID */ async updateNeighborRelations(warehouseId) { const { app } = this; // 获取所有货架 const racks = await app.model.LocationZone.findAll({ where: { warehouse_id: warehouseId, zone_type: 'rack', is_active: true, deleted_at: null, }, }); // 为每个货架计算邻居 for (const rack of racks) { const neighbors = await this._findNeighborRacks(rack, racks); await rack.update({ neighbor_zone_ids: neighbors.map(n => n.id), }); } this.ctx.logger.info(`为仓库 ${warehouseId} 更新了 ${racks.length} 个货架的邻居关系`); } /** * 查找相邻货架 * @param {Object} currentRack 当前货架 * @param {Array} allRacks 所有货架 */ async _findNeighborRacks(currentRack, allRacks) { const NEIGHBOR_DISTANCE = 2000; // 2米内视为邻居 return allRacks.filter(rack => { if (rack.id === currentRack.id) return false; // 计算两个货架中心点的距离 const currentCenterX = currentRack.x + currentRack.length / 2; const currentCenterY = currentRack.y + currentRack.width / 2; const rackCenterX = rack.x + rack.length / 2; const rackCenterY = rack.y + rack.width / 2; const distance = Math.sqrt( Math.pow(currentCenterX - rackCenterX, 2) + Math.pow(currentCenterY - rackCenterY, 2) ); return distance <= NEIGHBOR_DISTANCE; }); } } module.exports = LocationService;