feat(机柜管理): 添加机柜导入导出功能并优化分页查询

- 添加xlsx依赖支持Excel文件处理
- 实现机柜数据的导入导出功能,包括模板下载
- 优化机柜列表的分页查询接口
- 修复机柜可视化页面U位标记位置计算问题
- 更新背景设置和渐变颜色样式
This commit is contained in:
zhang1106
2025-12-22 08:59:44 +08:00
parent 130b2ad5f7
commit c60d13a0df
11 changed files with 726 additions and 38 deletions
+2 -2
View File
@@ -1,5 +1,5 @@
{
"type": "image",
"image": "/uploads/1766210792626_生成情侣图片.png",
"size": "cover"
"image": "/uploads/1766291127756_生成情侣图片.png",
"size": "contain"
}
+105 -1
View File
@@ -18,7 +18,8 @@
"mysql2": "^3.16.0",
"sequelize": "^6.32.1",
"sqlite3": "^5.1.6",
"three": "^0.182.0"
"three": "^0.182.0",
"xlsx": "^0.18.5"
},
"devDependencies": {
"nodemon": "^3.0.1"
@@ -117,6 +118,15 @@
"node": ">= 0.6"
}
},
"node_modules/adler-32": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz",
"integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
@@ -466,6 +476,19 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/cfb": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz",
"integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"crc-32": "~1.2.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
@@ -510,6 +533,15 @@
"node": ">=6"
}
},
"node_modules/codepage": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz",
"integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/color-support": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz",
@@ -583,6 +615,18 @@
"node": ">= 0.10"
}
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
"license": "Apache-2.0",
"bin": {
"crc32": "bin/crc32.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/csv-parser": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/csv-parser/-/csv-parser-3.2.0.tgz",
@@ -926,6 +970,15 @@
"node": ">= 0.6"
}
},
"node_modules/frac": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz",
"integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
@@ -2712,6 +2765,18 @@
"node": ">= 0.6"
}
},
"node_modules/ssf": {
"version": "0.11.2",
"resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz",
"integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
"license": "Apache-2.0",
"dependencies": {
"frac": "~1.1.2"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/ssri": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/ssri/-/ssri-8.0.1.tgz",
@@ -3049,12 +3114,51 @@
"@types/node": "*"
}
},
"node_modules/wmf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz",
"integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz",
"integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
"node_modules/xlsx": {
"version": "0.18.5",
"resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz",
"integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"cfb": "~1.2.1",
"codepage": "~1.15.0",
"crc-32": "~1.2.1",
"ssf": "~0.11.2",
"wmf": "~1.0.1",
"word": "~0.3.0"
},
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
+2 -1
View File
@@ -17,7 +17,8 @@
"mysql2": "^3.16.0",
"sequelize": "^6.32.1",
"sqlite3": "^5.1.6",
"three": "^0.182.0"
"three": "^0.182.0",
"xlsx": "^0.18.5"
},
"devDependencies": {
"nodemon": "^3.0.1"
+280 -2
View File
@@ -3,17 +3,36 @@ const router = express.Router();
const Rack = require('../models/Rack');
const Device = require('../models/Device');
const Room = require('../models/Room');
const XLSX = require('xlsx');
const fs = require('fs');
const path = require('path');
// 获取所有机柜
router.get('/', async (req, res) => {
try {
// 分页参数
const page = parseInt(req.query.page) || 1;
const pageSize = parseInt(req.query.pageSize) || 10;
const offset = (page - 1) * pageSize;
// 获取总记录数
const total = await Rack.count();
// 获取分页数据
const racks = await Rack.findAll({
include: [
{ model: Room },
{ model: Device }
]
],
limit: pageSize,
offset: offset
});
// 返回带分页信息的响应
res.json({
racks,
total
});
res.json(racks);
} catch (error) {
res.status(500).json({ error: error.message });
}
@@ -91,5 +110,264 @@ router.delete('/:rackId', async (req, res) => {
}
});
// 导出机柜导入模板
router.get('/import-template', async (req, res) => {
try {
// 准备模板数据
const templateData = [
{
'机柜ID': 'RACK001',
'机柜名称': '测试机柜1',
'所属机房名称': '测试机房1',
'高度(U)': 42,
'最大功率(W)': 5000,
'状态': 'active'
},
{
'机柜ID': 'RACK002',
'机柜名称': '测试机柜2',
'所属机房名称': '测试机房1',
'高度(U)': 42,
'最大功率(W)': 3000,
'状态': 'maintenance'
}
];
// 设置CSV标题(包含格式说明)
const headers = [
{ id: '机柜ID', title: '机柜ID' },
{ id: '机柜名称', title: '机柜名称' },
{ id: '所属机房名称', title: '所属机房名称' },
{ id: '高度(U)', title: '高度(U)' },
{ id: '最大功率(W)', title: '最大功率(W)' },
{ id: '状态', title: '状态(active/maintenance/inactive)' }
];
// 使用xlsx创建工作簿
const wb = XLSX.utils.book_new();
// 将数据转换为工作表
const ws = XLSX.utils.json_to_sheet(templateData);
// 设置列宽
ws['!cols'] = [
{ wch: 15 },
{ wch: 20 },
{ wch: 15 },
{ wch: 10 },
{ wch: 15 },
{ wch: 15 }
];
// 添加工作表到工作簿
XLSX.utils.book_append_sheet(wb, ws, '机柜模板');
// 生成Excel文件的Buffer
const excelBuffer = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });
// 设置响应头
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent('机柜导入模板.xlsx')}`);
// 发送文件
res.send(excelBuffer);
} catch (error) {
console.error('生成导入模板失败:', error);
res.status(500).json({ error: '生成导入模板失败' });
}
});
// 导入机柜数据
router.post('/import', async (req, res) => {
try {
// 检查是否有上传文件
if (!req.files || !req.files.file) {
return res.status(400).json({
success: false,
message: '没有上传文件',
error: '没有找到有效的上传文件,请选择一个Excel文件后重试'
});
}
const file = req.files.file;
// 保存临时文件
const tempFilePath = path.join(__dirname, '../temp', `${Date.now()}_${file.name}`);
try {
await file.mv(tempFilePath);
} catch (saveError) {
return res.status(500).json({
success: false,
message: '文件保存失败',
error: `无法保存上传的文件: ${saveError.message}`
});
}
try {
// 读取Excel文件
let workbook;
try {
workbook = XLSX.readFile(tempFilePath);
} catch (readError) {
return res.status(400).json({
success: false,
message: '文件解析失败',
error: `无法解析Excel文件: ${readError.message}`
});
}
// 获取第一个工作表
if (!workbook.SheetNames.length) {
return res.status(400).json({
success: false,
message: '文件格式错误',
error: 'Excel文件中没有找到工作表'
});
}
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
// 转换为JSON格式
const jsonData = XLSX.utils.sheet_to_json(worksheet, {
header: ['rackId', 'name', 'roomName', 'height', 'maxPower', 'status'],
range: 1, // 从第2行开始读取数据
blankrows: false // 跳过空行
});
if (jsonData.length === 0) {
return res.status(400).json({
success: false,
message: '没有找到有效数据',
error: 'Excel文件中没有找到可导入的数据行'
});
}
// 验证数据
const validStatuses = ['active', 'maintenance', 'inactive'];
const validationResults = [];
// 获取所有有效的机房信息(名称到ID的映射)
const allRooms = await Room.findAll();
const roomNameToIdMap = new Map(allRooms.map(room => [room.name, room.roomId]));
const validRoomNames = new Set(roomNameToIdMap.keys());
jsonData.forEach((item, index) => {
const rowNumber = index + 2; // 实际行号(加1是因为从0开始,加1是因为跳过了标题行)
const errors = [];
if (!item.rackId || item.rackId.trim() === '') {
errors.push('机柜ID不能为空');
}
if (!item.name || item.name.trim() === '') {
errors.push('机柜名称不能为空');
}
if (!item.roomName || item.roomName.trim() === '') {
errors.push('所属机房名称不能为空');
} else if (!validRoomNames.has(item.roomName.trim())) {
errors.push(`所属机房名称不存在: ${item.roomName}`);
}
if (typeof item.height !== 'number' || item.height <= 0) {
errors.push('高度必须是大于0的数字');
}
if (typeof item.maxPower !== 'number' || item.maxPower < 0) {
errors.push('最大功率必须是大于等于0的数字');
}
if (!item.status || !validStatuses.includes(item.status)) {
errors.push(`状态必须是以下值之一: ${validStatuses.join(', ')}`);
}
if (errors.length > 0) {
validationResults.push({
row: rowNumber,
data: item,
errors: errors
});
}
});
if (validationResults.length > 0) {
return res.status(400).json({
success: false,
message: '数据验证失败',
error: `${validationResults.length} 行数据格式错误`,
details: validationResults
});
}
// 批量创建机柜
let createdCount = 0;
let duplicateCount = 0;
try {
// 检查重复的机柜ID
const existingRacks = await Rack.findAll({
where: {
rackId: jsonData.map(item => item.rackId)
}
});
const existingIds = new Set(existingRacks.map(rack => rack.rackId));
const newData = jsonData.filter(item => !existingIds.has(item.rackId));
const duplicateData = jsonData.filter(item => existingIds.has(item.rackId));
duplicateCount = duplicateData.length;
// 将roomName转换为roomId
const dataWithRoomId = jsonData.map(item => {
const trimmedRoomName = item.roomName.trim();
return {
...item,
roomId: roomNameToIdMap.get(trimmedRoomName),
roomName: undefined // 移除不需要的字段
};
});
// 只创建新的机柜
if (newData.length > 0) {
const dataToCreate = dataWithRoomId.filter(item =>
jsonData.map(d => d.rackId).includes(item.rackId) &&
!existingIds.has(item.rackId)
);
const result = await Rack.bulkCreate(dataToCreate, {
ignoreDuplicates: true // 忽略重复的机柜ID
});
createdCount = result.length;
}
} catch (dbError) {
return res.status(500).json({
success: false,
message: '数据库操作失败',
error: `保存机柜数据失败: ${dbError.message}`
});
}
res.status(200).json({
success: true,
message: '机柜导入完成',
imported: createdCount,
duplicates: duplicateCount,
total: jsonData.length
});
} finally {
// 删除临时文件
if (fs.existsSync(tempFilePath)) {
fs.unlinkSync(tempFilePath);
}
}
} catch (error) {
res.status(500).json({
success: false,
message: '服务器内部错误',
error: `导入过程中发生未知错误: ${error.message}`
});
}
});
module.exports = router;
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 MiB

+105 -1
View File
@@ -14,7 +14,8 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.15.0",
"three": "^0.160.0"
"three": "^0.160.0",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.0.3",
@@ -1106,6 +1107,15 @@
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
}
},
"node_modules/adler-32": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz",
"integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/antd": {
"version": "5.29.2",
"resolved": "https://registry.npmjs.org/antd/-/antd-5.29.2.tgz",
@@ -1287,6 +1297,19 @@
],
"license": "CC-BY-4.0"
},
"node_modules/cfb": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz",
"integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"crc-32": "~1.2.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/classnames": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz",
@@ -1302,6 +1325,15 @@
"node": ">=6"
}
},
"node_modules/codepage": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz",
"integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -1336,6 +1368,18 @@
"toggle-selection": "^1.0.6"
}
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
"license": "Apache-2.0",
"bin": {
"crc32": "bin/crc32.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -1526,6 +1570,15 @@
"node": ">= 6"
}
},
"node_modules/frac": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz",
"integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -2564,6 +2617,18 @@
"node": ">=0.10.0"
}
},
"node_modules/ssf": {
"version": "0.11.2",
"resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz",
"integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
"license": "Apache-2.0",
"dependencies": {
"frac": "~1.1.2"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/string-convert": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/string-convert/-/string-convert-0.2.1.tgz",
@@ -2685,6 +2750,45 @@
}
}
},
"node_modules/wmf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz",
"integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz",
"integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/xlsx": {
"version": "0.18.5",
"resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz",
"integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"cfb": "~1.2.1",
"codepage": "~1.15.0",
"crc-32": "~1.2.1",
"ssf": "~0.11.2",
"wmf": "~1.0.1",
"word": "~0.3.0"
},
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
+2 -1
View File
@@ -15,7 +15,8 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.15.0",
"three": "^0.160.0"
"three": "^0.160.0",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.0.3",
+3 -2
View File
@@ -43,8 +43,9 @@ function Dashboard() {
// 获取所有机柜
const racksRes = await axios.get('/api/racks');
const racks = racksRes.data;
const totalRacks = racks.length;
// 机柜API返回的是包含total和racks数组的对象
const totalRacks = racksRes.data.total;
const racks = racksRes.data.racks || [];
// 获取所有机房
const roomsRes = await axios.get('/api/rooms');
+4 -3
View File
@@ -195,7 +195,8 @@ function DeviceManagement() {
const fetchRacks = async () => {
try {
const response = await axios.get('/api/racks');
setRacks(response.data);
// 现在API返回的格式是 { racks: [], total: number }
setRacks(response.data.racks || []);
} catch (error) {
message.error('获取机柜列表失败');
console.error('获取机柜列表失败:', error);
@@ -1006,7 +1007,7 @@ function DeviceManagement() {
}}
footer={null}
width={600}
destroyOnClose
destroyOnHidden
>
{!isImporting && !importResult ? (
<div>
@@ -1131,7 +1132,7 @@ function DeviceManagement() {
</Button>
]}
width={800}
destroyOnClose
destroyOnHidden
>
{selectedDevice && (
<div>
+210 -9
View File
@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, message, Card, Space, InputNumber, Upload, Progress } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import axios from 'axios';
import * as XLSX from 'xlsx';
const { Option } = Select;
@@ -12,15 +13,38 @@ function RackManagement() {
const [modalVisible, setModalVisible] = useState(false);
const [editingRack, setEditingRack] = useState(null);
const [form] = Form.useForm();
// 分页状态
const [pagination, setPagination] = useState({
current: 1,
pageSize: 10,
total: 0,
pageSizeOptions: ['10', '20', '30', '50', '100'],
showSizeChanger: true,
showTotal: (total) => `${total} 条记录`
});
// 导入模态框状态
const [importModalVisible, setImportModalVisible] = useState(false);
const [importProgress, setImportProgress] = useState(0);
const [isImporting, setIsImporting] = useState(false);
const [importResult, setImportResult] = useState(null);
// 获取所有机柜
const fetchRacks = async () => {
const fetchRacks = async (page = 1, pageSize = 10) => {
try {
setLoading(true);
const response = await axios.get('/api/racks');
setRacks(response.data);
const response = await axios.get('/api/racks', {
params: {
page,
pageSize
}
});
// 假设API返回格式为 { racks: [], total: number }
const { racks: data, total } = response.data;
setRacks(data);
// 更新分页状态
setPagination(prev => ({ ...prev, current: page, pageSize, total }));
} catch (error) {
message.error('获取机柜列表失败');
console.error('获取机柜列表失败:', error);
@@ -40,8 +64,13 @@ function RackManagement() {
}
};
// 处理表格分页变化
const handleTableChange = (pagination) => {
fetchRacks(pagination.current, pagination.pageSize);
};
useEffect(() => {
fetchRacks();
fetchRacks(pagination.current, pagination.pageSize);
fetchRooms();
}, []);
@@ -105,11 +134,86 @@ function RackManagement() {
});
};
// 下载导入模板
const handleDownloadTemplate = () => {
// 调用后端API下载模板
window.open('/api/racks/import-template', '_blank');
message.success('模板下载成功');
};
// 导入机柜数据
const handleImport = async (file) => {
try {
setIsImporting(true);
setImportProgress(0);
setImportResult(null);
const formData = new FormData();
formData.append('file', file);
// 模拟进度
const progressInterval = setInterval(() => {
setImportProgress(prev => {
if (prev >= 90) {
clearInterval(progressInterval);
return prev;
}
return prev + 10;
});
}, 500);
// 发送文件到后端处理
const response = await axios.post('/api/racks/import', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
clearInterval(progressInterval);
setImportProgress(100);
setImportResult(response.data);
setIsImporting(false);
// 根据导入结果显示不同的消息
if (response.data.success) {
const { imported, duplicates, total } = response.data;
if (duplicates > 0) {
message.warning(`导入完成,但有 ${duplicates} 条重复记录被跳过`);
} else {
message.success('所有记录导入成功');
}
} else {
message.error(response.data.message || '导入失败');
}
// 阻止自动上传
return false;
} catch (error) {
setIsImporting(false);
let errorMessage = '机柜导入失败';
let errorDetails = null;
if (error.response) {
// 服务器返回了错误响应
errorMessage = error.response.data.message || error.response.data.error || errorMessage;
errorDetails = error.response.data.details;
} else if (error.request) {
// 请求已发送但没有收到响应
errorMessage = '网络错误,服务器没有响应';
} else {
// 请求配置错误
errorMessage = `请求错误: ${error.message}`;
}
setImportResult({ success: false, message: errorMessage, details: errorDetails });
message.error(errorMessage);
console.error('机柜导入失败:', error);
// 阻止自动上传
return false;
}
};
// 状态标签映射
const statusMap = {
@@ -195,6 +299,9 @@ function RackManagement() {
<Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
添加机柜
</Button>
<Button icon={<UploadOutlined />} onClick={() => setImportModalVisible(true)}>
导入机柜
</Button>
</Space>
}>
<Table
@@ -202,7 +309,9 @@ function RackManagement() {
dataSource={racks}
rowKey="rackId"
loading={loading}
pagination={{ pageSize: 10 }}
pagination={pagination}
onChange={handleTableChange}
scroll={{ x: 'max-content' }}
/>
</Card>
@@ -287,6 +396,98 @@ function RackManagement() {
</Form>
</Modal>
{/* 导入机柜模态框 */}
<Modal
title="导入机柜"
open={importModalVisible}
onCancel={() => {
setImportModalVisible(false);
setImportProgress(0);
setImportResult(null);
setIsImporting(false);
}}
footer={null}
width={600}
destroyOnClose
>
{!isImporting && !importResult ? (
<div>
<p>请上传XLSX格式的机柜数据文件</p>
<p style={{ color: '#999', fontSize: '12px', marginBottom: 20 }}>支持的编码格式UTF-8</p>
<div style={{ marginBottom: 20 }}>
<p style={{ fontWeight: 'bold', marginBottom: 8 }}>Excel文件格式要求</p>
<ul style={{ paddingLeft: 20, marginBottom: 10 }}>
<li>必填字段机柜ID机柜名称所属机房名称高度(U)最大功率(W)状态</li>
<li>状态值active(在用)maintenance(维护中)inactive(停用)</li>
<li>高度和功率必须是数字格式</li>
</ul>
</div>
<div style={{ marginBottom: 20 }}>
<Button icon={<DownloadOutlined />} onClick={handleDownloadTemplate} style={{ marginRight: 10 }}>
下载导入模板
</Button>
<span style={{ color: '#999', fontSize: '12px' }}>包含示例数据的XLSX模板文件</span>
</div>
<Upload
name="file"
accept=".xlsx, .xls"
showUploadList={false}
beforeUpload={handleImport}
maxCount={1}
>
<Button type="primary" icon={<UploadOutlined />} block>
选择Excel文件
</Button>
</Upload>
</div>
) : (
<div>
<p>正在导入数据...</p>
<Progress percent={importProgress} status="active" style={{ marginBottom: 20 }} />
{importResult && (
<div>
<p style={{ marginBottom: 10 }}>导入完成</p>
<p>总记录数{importResult.total || 0}</p>
<p>成功{importResult.imported || 0}</p>
<p>重复{importResult.duplicates || 0}</p>
{importResult.details && importResult.details.length > 0 && (
<div>
<p style={{ marginTop: 20, fontWeight: 'bold' }}>导入失败记录</p>
<ul style={{ maxHeight: '300px', overflowY: 'auto', textAlign: 'left' }}>
{importResult.details.map((item, index) => (
<li key={index} style={{ marginBottom: '8px' }}>
<strong> {item.row} </strong>
<ul style={{ margin: '4px 0 0 20px' }}>
{item.errors.map((err, errIndex) => (
<li key={errIndex} style={{ color: '#ff4d4f' }}>{err}</li>
))}
</ul>
</li>
))}
</ul>
</div>
)}
<Button
type="primary"
onClick={() => {
setImportModalVisible(false);
setImportProgress(0);
setImportResult(null);
setIsImporting(false);
fetchRacks();
}}
style={{ marginTop: 20 }}
>
确定
</Button>
</div>
)}
</div>
)}
</Modal>
</div>
);
+13 -16
View File
@@ -152,10 +152,13 @@ function RackVisualization() {
try {
setLoading(true);
setError(null);
const response = await axios.get('/api/racks');
// 为机柜可视化页面传递较大的pageSize以获取所有机柜
const response = await axios.get('/api/racks', { params: { pageSize: 1000 } });
// 验证数据结构并过滤有效机柜
const validRacks = response.data.filter(rack =>
// 机柜API返回的是包含total和racks数组的对象
const racksArray = response.data.racks || [];
const validRacks = racksArray.filter(rack =>
rack &&
typeof rack === 'object' &&
rack.rackId &&
@@ -439,7 +442,7 @@ function RackVisualization() {
key={i}
className="u-mark"
style={{
top: `${(height - i) * uHeight + 1}px`,
top: `${(height - i) * uHeight}px`,
height: '1px',
backgroundColor: i % 5 === 0 ? '#1890ff' : '#999',
width: '100%',
@@ -469,14 +472,11 @@ function RackVisualization() {
const generateLeftUMarks = (height) => {
const marks = [];
const uHeight = 18;
const rackContentHeight = height * uHeight; // 机柜内容总高度
const containerPadding = 6; // 前面板上下padding总和
for (let u = 1; u <= height; u++) {
// 计算从上到下的位置,考虑前面板的padding
// U1在最底部,所以从底部开始计算
const bottomToTop = (u - 1) * uHeight;
const topPosition = rackContentHeight - bottomToTop - uHeight + containerPadding / 2;
// 使用与设备位置计算一致的逻辑
// U1在最底部,计算U位标记的顶部位置(从机柜顶部算起)
const topPosition = (height - u) * uHeight;
marks.push(
<div key={`left-${u}`}>
@@ -515,14 +515,11 @@ function RackVisualization() {
const generateRightUMarks = (height) => {
const marks = [];
const uHeight = 18;
const rackContentHeight = height * uHeight; // 机柜内容总高度
const containerPadding = 6; // 前面板上下padding总和
for (let u = 1; u <= height; u++) {
// 计算从上到下的位置,考虑前面板的padding
// U1在最底部,所以从底部开始计算
const bottomToTop = (u - 1) * uHeight;
const topPosition = rackContentHeight - bottomToTop - uHeight + containerPadding / 2;
// 使用与设备位置计算一致的逻辑
// U1在最底部,计算U位标记的顶部位置(从机柜顶部算起)
const topPosition = (height - u) * uHeight;
marks.push(
<div key={`right-${u}`}>
@@ -834,7 +831,7 @@ function RackVisualization() {
backgroundColor: '#f0f2f5',
background: backgroundType === 'image' && backgroundImage
? `url(${backgroundImage})`
: 'linear-gradient(135deg, #ff0000 0%, #ff7f00 14%, #ffff00 28%, #00ff00 42%, #0000ff 57%, #4b0082 71%, #8b00ff 100%)',
: 'linear-gradient(135deg, #ffcccc 0%, #ffd6b3 14%, #ffffcc 28%, #ccffcc 42%, #cce6ff 57%, #d6ccff 71%, #e6ccff 100%)',
backgroundSize: backgroundType === 'image' ? backgroundSize : 'auto',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',