已完成设备管理页面的基本功能,包括设备导入导出,字段自定义,字段是否显示等功能,目前处于资产管理已基本完善
This commit is contained in:
Generated
+81
-17
@@ -9,7 +9,11 @@
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"cors": "^2.8.5",
|
||||
"csv-parser": "^3.2.0",
|
||||
"csv-writer": "^1.6.0",
|
||||
"express": "^4.18.2",
|
||||
"express-fileupload": "^1.5.2",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"sequelize": "^6.32.1",
|
||||
"sqlite3": "^5.1.6"
|
||||
},
|
||||
@@ -311,6 +315,18 @@
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "1.1.12",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
|
||||
@@ -359,6 +375,17 @@
|
||||
"ieee754": "^1.1.13"
|
||||
}
|
||||
},
|
||||
"node_modules/busboy": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
|
||||
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
|
||||
"dependencies": {
|
||||
"streamsearch": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
@@ -544,6 +571,24 @@
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/csv-parser": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/csv-parser/-/csv-parser-3.2.0.tgz",
|
||||
"integrity": "sha512-fgKbp+AJbn1h2dcAHKIdKNSSjfp43BZZykXsCjzALjKy80VXQNHPFJ6T9Afwdzoj24aMkq8GwDS7KGcDPpejrA==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"csv-parser": "bin/csv-parser"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/csv-writer": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/csv-writer/-/csv-writer-1.6.0.tgz",
|
||||
"integrity": "sha512-NOx7YDFWEsM/fTRAJjRpPp8t+MKRVvniAg9wQlUKx20MFrPs73WLJhFf5iteqrxNYnsy924K3Iroh3yNHeYd2g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "2.6.9",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
|
||||
@@ -664,19 +709,6 @@
|
||||
"iconv-lite": "^0.6.2"
|
||||
}
|
||||
},
|
||||
"node_modules/encoding/node_modules/iconv-lite": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
|
||||
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/end-of-stream": {
|
||||
"version": "1.4.5",
|
||||
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
|
||||
@@ -803,6 +835,18 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/express-fileupload": {
|
||||
"version": "1.5.2",
|
||||
"resolved": "https://registry.npmjs.org/express-fileupload/-/express-fileupload-1.5.2.tgz",
|
||||
"integrity": "sha512-wxUJn2vTHvj/kZCVmc5/bJO15C7aSMyHeuXYY3geKpeKibaAoQGcEv5+sM6nHS2T7VF+QHS4hTWPiY2mKofEdg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"busboy": "^1.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/file-uri-to-path": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
|
||||
@@ -1183,12 +1227,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
|
||||
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
@@ -2033,6 +2077,18 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/raw-body/node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/rc": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
|
||||
@@ -2547,6 +2603,14 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/streamsearch": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
|
||||
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/string_decoder": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
|
||||
|
||||
@@ -7,12 +7,16 @@
|
||||
"dev": "nodemon server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"cors": "^2.8.5",
|
||||
"csv-parser": "^3.2.0",
|
||||
"csv-writer": "^1.6.0",
|
||||
"express": "^4.18.2",
|
||||
"express-fileupload": "^1.5.2",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"sequelize": "^6.32.1",
|
||||
"sqlite3": "^5.1.6",
|
||||
"cors": "^2.8.5"
|
||||
"sqlite3": "^5.1.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.0.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,4 +70,35 @@ router.delete('/:fieldId', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 批量更新字段配置
|
||||
router.post('/config', async (req, res) => {
|
||||
try {
|
||||
const fieldConfigs = req.body;
|
||||
|
||||
// 验证输入
|
||||
if (!Array.isArray(fieldConfigs)) {
|
||||
return res.status(400).json({ error: '输入必须是数组' });
|
||||
}
|
||||
|
||||
// 批量更新字段配置
|
||||
const updatedFields = [];
|
||||
for (const config of fieldConfigs) {
|
||||
// 使用fieldName作为更新条件,因为这是唯一的
|
||||
const [updated] = await DeviceField.update(
|
||||
{ visible: config.visible },
|
||||
{ where: { fieldName: config.fieldName } }
|
||||
);
|
||||
|
||||
if (updated) {
|
||||
const updatedField = await DeviceField.findOne({ where: { fieldName: config.fieldName } });
|
||||
updatedFields.push(updatedField);
|
||||
}
|
||||
}
|
||||
|
||||
res.json(updatedFields);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
+527
-19
@@ -1,8 +1,15 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { Op } = require('sequelize');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const csv = require('csv-parser');
|
||||
const { createObjectCsvWriter } = require('csv-writer');
|
||||
const iconv = require('iconv-lite');
|
||||
const Device = require('../models/Device');
|
||||
const Rack = require('../models/Rack');
|
||||
const Room = require('../models/Room');
|
||||
const DeviceField = require('../models/DeviceField');
|
||||
|
||||
// 获取所有设备(支持搜索和筛选)
|
||||
router.get('/', async (req, res) => {
|
||||
@@ -41,7 +48,12 @@ router.get('/', async (req, res) => {
|
||||
const { count, rows } = await Device.findAndCountAll({
|
||||
where,
|
||||
include: [
|
||||
{ model: Rack }
|
||||
{
|
||||
model: Rack,
|
||||
include: [
|
||||
{ model: Room }
|
||||
]
|
||||
}
|
||||
],
|
||||
offset,
|
||||
limit: parseInt(pageSize)
|
||||
@@ -58,23 +70,6 @@ router.get('/', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 获取单个设备
|
||||
router.get('/:deviceId', async (req, res) => {
|
||||
try {
|
||||
const device = await Device.findByPk(req.params.deviceId, {
|
||||
include: [
|
||||
{ model: Rack }
|
||||
]
|
||||
});
|
||||
if (!device) {
|
||||
return res.status(404).json({ error: '设备不存在' });
|
||||
}
|
||||
res.json(device);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 创建设备
|
||||
router.post('/', async (req, res) => {
|
||||
try {
|
||||
@@ -94,6 +89,458 @@ router.post('/', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 设备导入模板下载
|
||||
router.get('/import-template', async (req, res) => {
|
||||
try {
|
||||
// 查询设备字段配置
|
||||
const deviceFields = await DeviceField.findAll({
|
||||
order: [['order', 'ASC']]
|
||||
});
|
||||
|
||||
// 准备模板数据
|
||||
const templateData = [
|
||||
{
|
||||
'设备ID': 'DEV001',
|
||||
'设备名称': '测试服务器001',
|
||||
'设备类型': 'server',
|
||||
'型号': 'DELL R740',
|
||||
'序列号': 'SN1234567890',
|
||||
'所在机柜ID': 'A01',
|
||||
'位置(U)': '1',
|
||||
'高度(U)': '2',
|
||||
'功率(W)': '500',
|
||||
'状态': 'running',
|
||||
'购买日期': '2023-01-01',
|
||||
'保修到期': '2026-12-31',
|
||||
'IP地址': '192.168.1.100',
|
||||
'描述': '测试用服务器'
|
||||
}
|
||||
];
|
||||
|
||||
// 设置基础CSV标题(包含格式说明)
|
||||
const baseHeaders = [
|
||||
{ id: '设备ID', title: '设备ID' },
|
||||
{ id: '设备名称', title: '设备名称' },
|
||||
{ id: '设备类型', title: '设备类型(server/switch/router/storage)' },
|
||||
{ id: '型号', title: '型号' },
|
||||
{ id: '序列号', title: '序列号' },
|
||||
{ id: '所在机柜ID', title: '所在机柜ID' },
|
||||
{ id: '位置(U)', title: '位置(U)' },
|
||||
{ id: '高度(U)', title: '高度(U)' },
|
||||
{ id: '功率(W)', title: '功率(W)' },
|
||||
{ id: '状态', title: '状态(running/maintenance/offline/fault)' },
|
||||
{ id: '购买日期', title: '购买日期(YYYY-MM-DD)' },
|
||||
{ id: '保修到期', title: '保修到期(YYYY-MM-DD)' },
|
||||
{ id: 'IP地址', title: 'IP地址(可选)' },
|
||||
{ id: '描述', title: '描述(可选)' }
|
||||
];
|
||||
|
||||
// 添加自定义字段标题(排除与基础字段重复的字段)
|
||||
const baseFieldTitles = baseHeaders.map(header => header.id);
|
||||
const customHeaders = deviceFields
|
||||
.filter(field => field.visible && !baseFieldTitles.includes(field.displayName))
|
||||
.map(field => ({
|
||||
id: field.displayName,
|
||||
title: `${field.displayName}(${field.required ? '必填' : '可选'})`
|
||||
}));
|
||||
|
||||
const csvWriter = createObjectCsvWriter({
|
||||
path: path.join(__dirname, '../temp/import_template.csv'),
|
||||
header: [...baseHeaders, ...customHeaders]
|
||||
});
|
||||
|
||||
// 写入CSV文件
|
||||
await csvWriter.writeRecords(templateData);
|
||||
|
||||
// 设置响应头
|
||||
res.setHeader('Content-Type', 'text/csv; charset=gbk');
|
||||
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent('设备导入模板.csv')}`);
|
||||
|
||||
// 发送文件
|
||||
const fileStream = fs.createReadStream(path.join(__dirname, '../temp/import_template.csv'));
|
||||
fileStream.pipe(res);
|
||||
|
||||
// 删除临时文件
|
||||
fileStream.on('end', () => {
|
||||
fs.unlinkSync(path.join(__dirname, '../temp/import_template.csv'));
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('生成导入模板失败:', error);
|
||||
res.status(500).json({ error: '生成导入模板失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 导出设备数据为CSV
|
||||
router.get('/export', async (req, res) => {
|
||||
try {
|
||||
const { deviceIds } = req.query;
|
||||
|
||||
// 查询条件
|
||||
const where = {};
|
||||
if (deviceIds) {
|
||||
// 支持多个设备ID,使用数组格式
|
||||
const ids = Array.isArray(deviceIds) ? deviceIds : [deviceIds];
|
||||
where.deviceId = { [Op.in]: ids };
|
||||
}
|
||||
|
||||
// 查询设备字段配置
|
||||
const deviceFields = await DeviceField.findAll({
|
||||
order: [['order', 'ASC']]
|
||||
});
|
||||
|
||||
// 查询设备数据
|
||||
const devices = await Device.findAll({
|
||||
where,
|
||||
include: [
|
||||
{
|
||||
model: Rack,
|
||||
include: [
|
||||
{ model: Room }
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
// 如果没有找到设备
|
||||
if (devices.length === 0) {
|
||||
return res.status(404).json({ error: '未找到指定的设备' });
|
||||
}
|
||||
|
||||
// 准备CSV数据
|
||||
const csvData = devices.map(device => {
|
||||
// 创建基础数据对象
|
||||
const deviceData = {
|
||||
'设备ID': device.deviceId,
|
||||
'设备名称': device.name,
|
||||
'设备类型': device.type,
|
||||
'型号': device.model,
|
||||
'序列号': device.serialNumber,
|
||||
'所在机房ID': device.Rack?.Room?.roomId || '',
|
||||
'所在机房名称': device.Rack?.Room?.name || '',
|
||||
'所在机柜ID': device.rackId,
|
||||
'所在机柜名称': device.Rack?.name || '',
|
||||
'位置(U)': device.position,
|
||||
'高度(U)': device.height,
|
||||
'功率(W)': device.powerConsumption,
|
||||
'IP地址': device.ipAddress,
|
||||
'状态': device.status,
|
||||
'购买日期': device.purchaseDate ? new Date(device.purchaseDate).toLocaleDateString() : '',
|
||||
'保修到期': device.warrantyExpiry ? new Date(device.warrantyExpiry).toLocaleDateString() : '',
|
||||
'描述': device.description,
|
||||
'创建时间': device.createdAt ? new Date(device.createdAt).toLocaleString() : ''
|
||||
};
|
||||
|
||||
// 添加自定义字段(排除基础字段)
|
||||
if (device.customFields) {
|
||||
// 定义基础字段的显示名称
|
||||
const baseFieldDisplayNames = [
|
||||
'设备ID', '设备名称', '设备类型', '型号', '序列号',
|
||||
'所在机房ID', '所在机房名称', '所在机柜ID', '所在机柜名称', '位置(U)', '高度(U)',
|
||||
'功率(W)', 'IP地址', '状态', '购买日期', '保修到期', '描述', '创建时间'
|
||||
];
|
||||
|
||||
deviceFields.forEach(field => {
|
||||
// 只添加未在基础字段中出现的自定义字段
|
||||
if (field.visible &&
|
||||
device.customFields[field.fieldName] &&
|
||||
!baseFieldDisplayNames.includes(field.displayName)) {
|
||||
deviceData[field.displayName] = device.customFields[field.fieldName];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return deviceData;
|
||||
});
|
||||
|
||||
// 设置CSV标题(包含自定义字段)
|
||||
const baseHeaders = [
|
||||
{ id: '设备ID', title: '设备ID' },
|
||||
{ id: '设备名称', title: '设备名称' },
|
||||
{ id: '设备类型', title: '设备类型' },
|
||||
{ id: '型号', title: '型号' },
|
||||
{ id: '序列号', title: '序列号' },
|
||||
{ id: '所在机房ID', title: '所在机房ID' },
|
||||
{ id: '所在机房名称', title: '所在机房名称' },
|
||||
{ id: '所在机柜ID', title: '所在机柜ID' },
|
||||
{ id: '所在机柜名称', title: '所在机柜名称' },
|
||||
{ id: '位置(U)', title: '位置(U)' },
|
||||
{ id: '高度(U)', title: '高度(U)' },
|
||||
{ id: '功率(W)', title: '功率(W)' },
|
||||
{ id: 'IP地址', title: 'IP地址' },
|
||||
{ id: '状态', title: '状态' },
|
||||
{ id: '购买日期', title: '购买日期' },
|
||||
{ id: '保修到期', title: '保修到期' },
|
||||
{ id: '描述', title: '描述' },
|
||||
{ id: '创建时间', title: '创建时间' }
|
||||
];
|
||||
|
||||
// 添加自定义字段标题(排除与基础字段重复的字段)
|
||||
const baseFieldTitles = baseHeaders.map(header => header.id);
|
||||
const customHeaders = deviceFields
|
||||
.filter(field => field.visible && !baseFieldTitles.includes(field.displayName))
|
||||
.map(field => ({ id: field.displayName, title: field.displayName }));
|
||||
|
||||
const csvWriter = createObjectCsvWriter({
|
||||
path: path.join(__dirname, '../temp/devices.csv'),
|
||||
header: [...baseHeaders, ...customHeaders],
|
||||
encoding: 'utf8'
|
||||
});
|
||||
|
||||
// 确保temp目录存在
|
||||
if (!fs.existsSync(path.join(__dirname, '../temp'))) {
|
||||
fs.mkdirSync(path.join(__dirname, '../temp'));
|
||||
}
|
||||
|
||||
// 写入CSV文件
|
||||
await csvWriter.writeRecords(csvData);
|
||||
|
||||
// 读取文件并转换为GBK编码
|
||||
const csvContent = fs.readFileSync(path.join(__dirname, '../temp/devices.csv'), 'utf8');
|
||||
const gbkContent = iconv.encode(csvContent, 'gbk');
|
||||
|
||||
// 设置响应头
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=devices.csv');
|
||||
|
||||
// 发送CSV数据
|
||||
res.send(gbkContent);
|
||||
|
||||
// 删除临时文件
|
||||
fs.unlinkSync(path.join(__dirname, '../temp/devices.csv'));
|
||||
} catch (error) {
|
||||
console.error('导出设备数据失败:', error);
|
||||
res.status(500).json({ error: '导出设备数据失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 导入设备数据从CSV
|
||||
router.post('/import', async (req, res) => {
|
||||
try {
|
||||
if (!req.files || !req.files.csvFile) {
|
||||
return res.status(400).json({ error: '请上传CSV文件' });
|
||||
}
|
||||
|
||||
const csvFile = req.files.csvFile;
|
||||
const stats = { total: 0, success: 0, failed: 0, errors: [] };
|
||||
|
||||
// 确保temp目录存在
|
||||
if (!fs.existsSync(path.join(__dirname, '../temp'))) {
|
||||
fs.mkdirSync(path.join(__dirname, '../temp'));
|
||||
}
|
||||
|
||||
// 保存上传的文件
|
||||
const filePath = path.join(__dirname, '../temp', csvFile.name);
|
||||
await csvFile.mv(filePath);
|
||||
|
||||
// 读取并解析CSV文件(GBK编码)
|
||||
const results = [];
|
||||
const stream = fs.createReadStream(filePath)
|
||||
.pipe(iconv.decodeStream('gbk'))
|
||||
.pipe(csv());
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
stream.on('data', (data) => {
|
||||
stats.total++;
|
||||
results.push(data);
|
||||
})
|
||||
.on('end', resolve)
|
||||
.on('error', reject);
|
||||
});
|
||||
|
||||
// 获取所有机柜信息用于验证
|
||||
const racks = await Rack.findAll();
|
||||
const rackIds = racks.map(rack => rack.rackId);
|
||||
|
||||
// 获取所有机房信息,用于自动创建机柜时的默认机房
|
||||
let rooms = await Room.findAll();
|
||||
let defaultRoomId;
|
||||
|
||||
// 如果没有机房,创建一个默认机房
|
||||
if (rooms.length === 0) {
|
||||
const defaultRoom = await Room.create({
|
||||
roomId: 'ROOM001',
|
||||
name: '默认机房',
|
||||
location: '默认位置',
|
||||
area: 100,
|
||||
capacity: 100
|
||||
});
|
||||
defaultRoomId = defaultRoom.roomId;
|
||||
} else {
|
||||
// 使用第一个机房作为默认机房
|
||||
defaultRoomId = rooms[0].roomId;
|
||||
}
|
||||
|
||||
// 获取设备字段配置
|
||||
const deviceFields = await DeviceField.findAll();
|
||||
|
||||
// 创建字段映射:displayName -> fieldName
|
||||
const fieldMapping = {};
|
||||
deviceFields.forEach(field => {
|
||||
fieldMapping[field.displayName] = field;
|
||||
});
|
||||
|
||||
// 处理导入数据
|
||||
for (let i = 0; i < results.length; i++) {
|
||||
const row = results[i];
|
||||
const rowNum = i + 2; // CSV行号(第一行是标题)
|
||||
|
||||
// 辅助函数:从带格式说明的字段名中提取原始字段名(如从"设备类型(server/switch/router/storage)"提取"设备类型")
|
||||
const extractFieldName = (fieldNameWithFormat) => {
|
||||
const match = fieldNameWithFormat.match(/^([^\(]+)/);
|
||||
return match ? match[1].trim() : fieldNameWithFormat;
|
||||
};
|
||||
|
||||
// 创建一个映射,将原始字段名映射到CSV中的值
|
||||
const fieldValueMap = {};
|
||||
Object.entries(row).forEach(([displayName, value]) => {
|
||||
const originalFieldName = extractFieldName(displayName);
|
||||
fieldValueMap[originalFieldName] = value;
|
||||
// 同时保留原始字段名的映射,以便兼容不同格式
|
||||
fieldValueMap[displayName] = value;
|
||||
});
|
||||
|
||||
try {
|
||||
// 验证必填字段
|
||||
if (!fieldValueMap['设备ID'] || !fieldValueMap['设备名称'] || !fieldValueMap['设备类型'] || !fieldValueMap['型号'] || !fieldValueMap['序列号'] || !fieldValueMap['所在机柜ID'] || !fieldValueMap['位置(U)'] || !fieldValueMap['高度(U)'] || !fieldValueMap['功率(W)'] || !fieldValueMap['状态'] || !fieldValueMap['购买日期'] || !fieldValueMap['保修到期']) {
|
||||
throw new Error('缺少必填字段');
|
||||
}
|
||||
|
||||
// 验证设备ID是否已存在
|
||||
const existingDevice = await Device.findByPk(fieldValueMap['设备ID']);
|
||||
if (existingDevice) {
|
||||
throw new Error('设备ID已存在');
|
||||
}
|
||||
|
||||
// 验证机柜是否存在,如果不存在则自动创建
|
||||
if (!rackIds.includes(fieldValueMap['所在机柜ID'])) {
|
||||
// 自动创建机柜
|
||||
const newRack = await Rack.create({
|
||||
rackId: fieldValueMap['所在机柜ID'],
|
||||
name: fieldValueMap['所在机柜ID'], // 使用机柜ID作为默认名称
|
||||
height: 42, // 默认42U高度
|
||||
maxPower: 10000, // 默认最大功耗10000W
|
||||
currentPower: 0,
|
||||
status: 'active',
|
||||
roomId: defaultRoomId
|
||||
});
|
||||
|
||||
// 更新机柜列表和ID列表
|
||||
racks.push(newRack);
|
||||
rackIds.push(newRack.rackId);
|
||||
}
|
||||
|
||||
// 验证状态值
|
||||
const validStatus = ['running', 'maintenance', 'offline', 'fault'];
|
||||
if (!validStatus.includes(fieldValueMap['状态'])) {
|
||||
throw new Error('状态值无效,有效值为:running, maintenance, offline, fault');
|
||||
}
|
||||
|
||||
// 验证日期格式并解析日期
|
||||
const purchaseDate = new Date(fieldValueMap['购买日期']);
|
||||
const warrantyExpiry = new Date(fieldValueMap['保修到期']);
|
||||
if (isNaN(purchaseDate.getTime()) || isNaN(warrantyExpiry.getTime())) {
|
||||
throw new Error('日期格式无效,请使用有效的日期格式');
|
||||
}
|
||||
|
||||
// 构建设备数据
|
||||
const deviceData = {
|
||||
deviceId: fieldValueMap['设备ID'],
|
||||
name: fieldValueMap['设备名称'],
|
||||
type: fieldValueMap['设备类型'],
|
||||
model: fieldValueMap['型号'],
|
||||
serialNumber: fieldValueMap['序列号'],
|
||||
rackId: fieldValueMap['所在机柜ID'],
|
||||
position: parseInt(fieldValueMap['位置(U)']),
|
||||
height: parseInt(fieldValueMap['高度(U)']),
|
||||
powerConsumption: parseFloat(fieldValueMap['功率(W)']),
|
||||
ipAddress: fieldValueMap['IP地址'] || '',
|
||||
status: fieldValueMap['状态'],
|
||||
purchaseDate: purchaseDate,
|
||||
warrantyExpiry: warrantyExpiry,
|
||||
description: fieldValueMap['描述'] || ''
|
||||
};
|
||||
|
||||
// 处理自定义字段
|
||||
const customFields = {};
|
||||
Object.entries(row).forEach(([displayName, value]) => {
|
||||
// 跳过基础字段
|
||||
const originalFieldName = extractFieldName(displayName);
|
||||
const baseFields = ['设备ID', '设备名称', '设备类型', '型号', '序列号', '所在机柜ID', '位置(U)', '高度(U)', '功率(W)', '状态', '购买日期', '保修到期', 'IP地址', '描述'];
|
||||
if (!baseFields.includes(originalFieldName)) {
|
||||
// 查找对应的字段配置(同时尝试原始字段名和带格式的字段名)
|
||||
const fieldConfig = fieldMapping[displayName] || fieldMapping[originalFieldName];
|
||||
if (fieldConfig) {
|
||||
// 根据字段类型处理值
|
||||
let processedValue = value;
|
||||
if (fieldConfig.fieldType === 'number') {
|
||||
processedValue = parseFloat(value);
|
||||
} else if (fieldConfig.fieldType === 'boolean') {
|
||||
processedValue = value.toLowerCase() === 'true' || value === '1' || value.toLowerCase() === '是';
|
||||
} else if (fieldConfig.fieldType === 'date') {
|
||||
processedValue = new Date(value);
|
||||
}
|
||||
|
||||
customFields[fieldConfig.fieldName] = processedValue;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 如果有自定义字段,添加到设备数据中
|
||||
if (Object.keys(customFields).length > 0) {
|
||||
deviceData.customFields = customFields;
|
||||
}
|
||||
|
||||
// 创建设备
|
||||
const device = await Device.create(deviceData);
|
||||
|
||||
// 更新机柜当前功率
|
||||
const rack = await Rack.findByPk(row['所在机柜ID']);
|
||||
if (rack) {
|
||||
await rack.update({
|
||||
currentPower: rack.currentPower + device.powerConsumption
|
||||
});
|
||||
}
|
||||
|
||||
stats.success++;
|
||||
} catch (error) {
|
||||
stats.failed++;
|
||||
stats.errors.push({ row: rowNum, error: error.message, data: row });
|
||||
}
|
||||
}
|
||||
|
||||
// 删除临时文件
|
||||
fs.unlinkSync(filePath);
|
||||
|
||||
res.json({ statistics: stats });
|
||||
} catch (error) {
|
||||
console.error('导入设备数据失败:', error);
|
||||
res.status(500).json({ error: '导入设备数据失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// 获取单个设备
|
||||
router.get('/:deviceId', async (req, res) => {
|
||||
try {
|
||||
const device = await Device.findByPk(req.params.deviceId, {
|
||||
include: [
|
||||
{
|
||||
model: Rack,
|
||||
include: [
|
||||
{ model: Room }
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
if (!device) {
|
||||
return res.status(404).json({ error: '设备不存在' });
|
||||
}
|
||||
res.json(device);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 更新设备
|
||||
router.put('/:deviceId', async (req, res) => {
|
||||
try {
|
||||
@@ -119,7 +566,12 @@ router.put('/:deviceId', async (req, res) => {
|
||||
|
||||
const updatedDevice = await Device.findByPk(req.params.deviceId, {
|
||||
include: [
|
||||
{ model: Rack }
|
||||
{
|
||||
model: Rack,
|
||||
include: [
|
||||
{ model: Room }
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
res.json(updatedDevice);
|
||||
@@ -131,6 +583,62 @@ router.put('/:deviceId', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 批量下线设备
|
||||
router.put('/batch-offline', async (req, res) => {
|
||||
try {
|
||||
const { deviceIds } = req.body;
|
||||
|
||||
if (!deviceIds || !Array.isArray(deviceIds)) {
|
||||
return res.status(400).json({ error: '无效的设备ID列表' });
|
||||
}
|
||||
|
||||
// 更新设备状态为离线
|
||||
const updated = await Device.update(
|
||||
{ status: 'offline' },
|
||||
{ where: { deviceId: deviceIds } }
|
||||
);
|
||||
|
||||
res.json({ message: `成功下线 ${updated[0]} 个设备` });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 批量删除设备
|
||||
router.delete('/batch-delete', async (req, res) => {
|
||||
try {
|
||||
const { deviceIds } = req.body;
|
||||
|
||||
if (!deviceIds || !Array.isArray(deviceIds)) {
|
||||
return res.status(400).json({ error: '无效的设备ID列表' });
|
||||
}
|
||||
|
||||
// 先获取所有设备的功率信息
|
||||
const devices = await Device.findAll({
|
||||
where: { deviceId: deviceIds }
|
||||
});
|
||||
|
||||
// 更新机柜功率
|
||||
for (const device of devices) {
|
||||
const rack = await Rack.findByPk(device.rackId);
|
||||
if (rack) {
|
||||
await rack.update({
|
||||
currentPower: Math.max(0, rack.currentPower - device.powerConsumption)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 删除设备
|
||||
const deleted = await Device.destroy({
|
||||
where: { deviceId: deviceIds }
|
||||
});
|
||||
|
||||
res.json({ message: `成功删除 ${deleted} 个设备` });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 删除设备
|
||||
router.delete('/:deviceId', async (req, res) => {
|
||||
try {
|
||||
|
||||
@@ -91,4 +91,5 @@ router.delete('/:rackId', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,5 +1,6 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const fileUpload = require('express-fileupload');
|
||||
const { sequelize } = require('./db');
|
||||
|
||||
// 创建Express应用
|
||||
@@ -9,6 +10,8 @@ const PORT = process.env.PORT || 3001;
|
||||
// 中间件
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(fileUpload({ limits: { fileSize: 50 * 1024 * 1024 } }));
|
||||
app.use('/temp', express.static('temp'));
|
||||
|
||||
// 数据库连接已从db.js导入
|
||||
|
||||
|
||||
@@ -20,10 +20,12 @@ function Dashboard() {
|
||||
|
||||
// 获取所有设备
|
||||
const devicesRes = await axios.get('/api/devices');
|
||||
// 设备API返回的是包含devices数组的对象
|
||||
const devices = devicesRes.data.devices || devicesRes.data;
|
||||
const totalDevices = devices.length;
|
||||
const faultDevices = devices.filter(device => device.status === 'fault').length;
|
||||
// 设备API返回的是包含total和devices数组的对象
|
||||
const totalDevices = devicesRes.data.total;
|
||||
// 获取所有设备以统计故障设备数量
|
||||
const allDevicesRes = await axios.get('/api/devices', { params: { pageSize: totalDevices } });
|
||||
const allDevices = allDevicesRes.data.devices || allDevicesRes.data;
|
||||
const faultDevices = allDevices.filter(device => device.status === 'fault').length;
|
||||
|
||||
// 获取所有机柜
|
||||
const racksRes = await axios.get('/api/racks');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Table, Button, Modal, Form, Input, Select, DatePicker, message, Card, Space, InputNumber, Switch } from 'antd';
|
||||
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { Table, Button, Modal, Form, Input, Select, DatePicker, message, Card, Space, InputNumber, Switch, Upload, Progress, Checkbox } from 'antd';
|
||||
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, UploadOutlined, DownloadOutlined, SettingOutlined } from '@ant-design/icons';
|
||||
import axios from 'axios';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
@@ -20,13 +20,29 @@ function DeviceManagement() {
|
||||
const [type, setType] = useState('all');
|
||||
const [searchForm] = Form.useForm();
|
||||
// 分页状态
|
||||
const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
|
||||
const [pagination, setPagination] = useState({
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
pageSizeOptions: ['10', '20', '30', '50', '100'],
|
||||
showSizeChanger: true,
|
||||
showTotal: (total) => `共 ${total} 条记录`
|
||||
});
|
||||
// 自定义字段状态
|
||||
const [customFieldName, setCustomFieldName] = useState('');
|
||||
const [customFieldValue, setCustomFieldValue] = useState('');
|
||||
// 设备字段配置
|
||||
const [deviceFields, setDeviceFields] = useState([]);
|
||||
const [loadingFields, setLoadingFields] = useState(true);
|
||||
// 导入导出状态
|
||||
const [importModalVisible, setImportModalVisible] = useState(false);
|
||||
const [importProgress, setImportProgress] = useState(0);
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [importResult, setImportResult] = useState(null);
|
||||
const [selectedDevices, setSelectedDevices] = useState([]);
|
||||
const [selectAll, setSelectAll] = useState(false);
|
||||
// 字段配置模态框
|
||||
const [fieldConfigModalVisible, setFieldConfigModalVisible] = useState(false);
|
||||
|
||||
// 获取所有设备(支持搜索、筛选和分页)
|
||||
const fetchDevices = async (page = 1, pageSize = 10, searchParams = {}) => {
|
||||
@@ -219,7 +235,7 @@ function DeviceManagement() {
|
||||
setStatus('all');
|
||||
setType('all');
|
||||
searchForm.resetFields();
|
||||
fetchDevices(1, 10, { keyword: '', status: 'all', type: 'all' });
|
||||
fetchDevices(1, pagination.pageSize, { keyword: '', status: 'all', type: 'all' });
|
||||
};
|
||||
|
||||
// 表格分页变化处理
|
||||
@@ -228,6 +244,56 @@ function DeviceManagement() {
|
||||
fetchDevices(pagination.current, pagination.pageSize);
|
||||
};
|
||||
|
||||
// 批量下线设备
|
||||
const handleBatchOffline = async () => {
|
||||
Modal.confirm({
|
||||
title: '批量下线确认',
|
||||
content: `确定要将选中的 ${selectedDevices.length} 个设备下线吗?`,
|
||||
okText: '确认下线',
|
||||
okType: 'primary',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
try {
|
||||
const response = await axios.put('/api/devices/batch-offline', {
|
||||
deviceIds: selectedDevices
|
||||
});
|
||||
message.success(response.data.message || '批量下线成功');
|
||||
setSelectedDevices([]);
|
||||
setSelectAll(false);
|
||||
fetchDevices();
|
||||
} catch (error) {
|
||||
message.error('批量下线失败');
|
||||
console.error('批量下线设备失败:', error);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 批量删除设备
|
||||
const handleBatchDelete = async () => {
|
||||
Modal.confirm({
|
||||
title: '批量删除确认',
|
||||
content: `确定要删除选中的 ${selectedDevices.length} 个设备吗?此操作不可恢复!`,
|
||||
okText: '确认删除',
|
||||
okType: 'danger',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
try {
|
||||
const response = await axios.delete('/api/devices/batch-delete', {
|
||||
data: { deviceIds: selectedDevices }
|
||||
});
|
||||
message.success(response.data.message || '批量删除成功');
|
||||
setSelectedDevices([]);
|
||||
setSelectAll(false);
|
||||
fetchDevices();
|
||||
} catch (error) {
|
||||
message.error('批量删除失败');
|
||||
console.error('批量删除设备失败:', error);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 删除设备
|
||||
const handleDelete = async (deviceId) => {
|
||||
Modal.confirm({
|
||||
@@ -249,6 +315,105 @@ function DeviceManagement() {
|
||||
});
|
||||
};
|
||||
|
||||
// 导出设备数据
|
||||
const handleExport = async () => {
|
||||
try {
|
||||
if (selectedDevices.length === 0) {
|
||||
message.warning('请先选择要导出的设备');
|
||||
return;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams();
|
||||
selectedDevices.forEach(id => params.append('deviceIds', id));
|
||||
|
||||
const response = await axios.get(`/api/devices/export?${params.toString()}`, { responseType: 'blob' });
|
||||
const blob = new Blob([response.data], { type: 'text/csv; charset=gbk' });
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `devices_export_${new Date().toISOString().split('T')[0]}.csv`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(url);
|
||||
message.success('导出成功');
|
||||
} catch (error) {
|
||||
message.error('导出失败');
|
||||
console.error('导出设备失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理单个设备选择
|
||||
const handleDeviceSelect = (deviceId) => {
|
||||
setSelectedDevices(prev => {
|
||||
if (prev.includes(deviceId)) {
|
||||
return prev.filter(id => id !== deviceId);
|
||||
} else {
|
||||
return [...prev, deviceId];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 处理全选/取消全选
|
||||
const handleSelectAll = (e) => {
|
||||
setSelectAll(e.target.checked);
|
||||
if (e.target.checked) {
|
||||
setSelectedDevices(devices.map(device => device.deviceId));
|
||||
} else {
|
||||
setSelectedDevices([]);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
// 导入设备数据
|
||||
const handleImport = async (file) => {
|
||||
try {
|
||||
setIsImporting(true);
|
||||
setImportProgress(0);
|
||||
setImportResult(null);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('csvFile', file);
|
||||
|
||||
// 模拟进度
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => {
|
||||
if (prev >= 90) {
|
||||
clearInterval(progressInterval);
|
||||
return prev;
|
||||
}
|
||||
return prev + 10;
|
||||
});
|
||||
}, 500);
|
||||
|
||||
const response = await axios.post('/api/devices/import', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
});
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
setImportResult(response.data);
|
||||
setIsImporting(false);
|
||||
message.success('导入完成');
|
||||
|
||||
// 重新加载设备列表
|
||||
setTimeout(() => {
|
||||
fetchDevices();
|
||||
}, 1000);
|
||||
|
||||
} catch (error) {
|
||||
setIsImporting(false);
|
||||
message.error('导入失败');
|
||||
console.error('导入设备失败:', error);
|
||||
}
|
||||
|
||||
// 阻止默认上传行为
|
||||
return false;
|
||||
};
|
||||
|
||||
// 状态标签映射
|
||||
const statusMap = {
|
||||
running: { text: '运行中', color: 'green' },
|
||||
@@ -270,10 +435,20 @@ function DeviceManagement() {
|
||||
const columns = React.useMemo(() => {
|
||||
const generatedColumns = [];
|
||||
|
||||
// 根据字段配置动态生成列
|
||||
// 根据字段配置动态生成列,只显示visible为true的字段
|
||||
deviceFields.forEach(field => {
|
||||
// 只处理可见字段
|
||||
if (!field.visible) return;
|
||||
|
||||
// 特殊处理机柜字段
|
||||
if (field.fieldName === 'rackId') {
|
||||
// 添加机房信息列
|
||||
generatedColumns.push({
|
||||
title: '所在机房',
|
||||
dataIndex: ['Rack', 'Room', 'name'],
|
||||
key: 'roomName',
|
||||
});
|
||||
// 添加机柜信息列
|
||||
generatedColumns.push({
|
||||
title: field.displayName,
|
||||
dataIndex: ['Rack', 'name'],
|
||||
@@ -340,13 +515,46 @@ function DeviceManagement() {
|
||||
return generatedColumns;
|
||||
}, [deviceFields]);
|
||||
|
||||
// 保存字段配置
|
||||
const handleSaveFieldConfig = async (values) => {
|
||||
try {
|
||||
// 更新设备字段配置的可见性
|
||||
const updatedFields = deviceFields.map(field => ({
|
||||
...field,
|
||||
visible: values[field.fieldName]
|
||||
}));
|
||||
|
||||
// 保存到后端
|
||||
await axios.post('/api/deviceFields/config', updatedFields);
|
||||
|
||||
// 更新本地状态
|
||||
setDeviceFields(updatedFields);
|
||||
message.success('字段配置保存成功');
|
||||
setFieldConfigModalVisible(false);
|
||||
} catch (error) {
|
||||
message.error('字段配置保存失败');
|
||||
console.error('保存字段配置失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 重置字段配置为默认值
|
||||
const handleResetFieldConfig = () => {
|
||||
const defaultFields = defaultDeviceFields;
|
||||
setDeviceFields(defaultFields);
|
||||
message.success('字段配置已重置为默认值');
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Card title="设备管理" extra={
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
|
||||
添加设备
|
||||
</Button>
|
||||
<Space>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>添加设备</Button>
|
||||
<Button icon={<DownloadOutlined />} onClick={handleExport}>导出设备</Button>
|
||||
<Button icon={<UploadOutlined />} onClick={() => setImportModalVisible(true)}>导入设备</Button>
|
||||
<Button icon={<SettingOutlined />} onClick={() => setFieldConfigModalVisible(true)}>字段配置</Button>
|
||||
</Space>
|
||||
}>
|
||||
|
||||
{/* 搜索和筛选区域 */}
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Form
|
||||
@@ -407,8 +615,29 @@ function DeviceManagement() {
|
||||
</Form>
|
||||
</Card>
|
||||
|
||||
|
||||
|
||||
<Table
|
||||
columns={columns}
|
||||
columns={[
|
||||
{
|
||||
title: (
|
||||
<Checkbox
|
||||
checked={selectAll && devices.length > 0}
|
||||
onChange={handleSelectAll}
|
||||
indeterminate={selectedDevices.length > 0 && selectedDevices.length < devices.length}
|
||||
/>
|
||||
),
|
||||
key: 'selection',
|
||||
width: 60,
|
||||
render: (_, record) => (
|
||||
<Checkbox
|
||||
checked={selectedDevices.includes(record.deviceId)}
|
||||
onChange={() => handleDeviceSelect(record.deviceId)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
...columns
|
||||
]}
|
||||
dataSource={devices}
|
||||
rowKey="deviceId"
|
||||
loading={loading}
|
||||
@@ -422,7 +651,7 @@ function DeviceManagement() {
|
||||
open={modalVisible}
|
||||
onCancel={handleCancel}
|
||||
footer={null}
|
||||
width={700}
|
||||
width={800}
|
||||
>
|
||||
<Form
|
||||
form={form}
|
||||
@@ -559,6 +788,138 @@ function DeviceManagement() {
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{/* 导入设备模态框 */}
|
||||
{/* 字段配置模态框 */}
|
||||
<Modal
|
||||
title="字段配置"
|
||||
open={fieldConfigModalVisible}
|
||||
onCancel={() => setFieldConfigModalVisible(false)}
|
||||
footer={null}
|
||||
width={600}
|
||||
>
|
||||
<Form
|
||||
layout="vertical"
|
||||
onFinish={handleSaveFieldConfig}
|
||||
initialValues={deviceFields.reduce((acc, field) => ({
|
||||
...acc,
|
||||
[field.fieldName]: field.visible
|
||||
}), {})}
|
||||
>
|
||||
<div style={{ maxHeight: 400, overflowY: 'auto' }}>
|
||||
{/* 将字段分为多列显示 */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
|
||||
{deviceFields.map(field => (
|
||||
<Form.Item
|
||||
key={field.fieldName}
|
||||
name={field.fieldName}
|
||||
valuePropName="checked"
|
||||
noStyle
|
||||
>
|
||||
<Checkbox style={{ marginBottom: '8px' }}>
|
||||
{field.displayName}
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Form.Item style={{ textAlign: 'right', marginTop: '20px' }}>
|
||||
<Space>
|
||||
<Button onClick={() => setFieldConfigModalVisible(false)}>取消</Button>
|
||||
<Button onClick={handleResetFieldConfig}>重置默认</Button>
|
||||
<Button type="primary" htmlType="submit">保存</Button>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="导入设备"
|
||||
open={importModalVisible}
|
||||
onCancel={() => {
|
||||
setImportModalVisible(false);
|
||||
setImportProgress(0);
|
||||
setImportResult(null);
|
||||
setIsImporting(false);
|
||||
}}
|
||||
footer={null}
|
||||
width={600}
|
||||
destroyOnClose
|
||||
>
|
||||
{!isImporting ? (
|
||||
<div>
|
||||
<p>请上传CSV格式的设备数据文件</p>
|
||||
<p style={{ color: '#999', fontSize: '12px', marginBottom: 20 }}>支持的编码格式:GBK</p>
|
||||
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<p style={{ fontWeight: 'bold', marginBottom: 8 }}>CSV文件格式要求:</p>
|
||||
<ul style={{ paddingLeft: 20, marginBottom: 10 }}>
|
||||
<li>必填字段:设备ID、设备名称、设备类型、型号、序列号、所在机柜ID、位置(U)、高度(U)、功率(W)、状态、购买日期、保修到期</li>
|
||||
<li>可选字段:IP地址、描述</li>
|
||||
<li>设备类型:server(服务器)、switch(交换机)、router(路由器)、storage(存储设备)</li>
|
||||
<li>状态值:running(运行中)、maintenance(维护中)、offline(离线)、fault(故障)</li>
|
||||
<li>日期格式:YYYY-MM-DD (例如:2023-01-01)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<a href="/api/devices/import-template" download="设备导入模板.csv">
|
||||
<Button icon={<DownloadOutlined />} style={{ marginRight: 10 }}>
|
||||
下载导入模板
|
||||
</Button>
|
||||
</a>
|
||||
<span style={{ color: '#999', fontSize: '12px' }}>包含示例数据的CSV模板文件</span>
|
||||
</div>
|
||||
|
||||
<Upload
|
||||
name="csvFile"
|
||||
accept=".csv"
|
||||
showUploadList={false}
|
||||
beforeUpload={handleImport}
|
||||
maxCount={1}
|
||||
>
|
||||
<Button type="primary" icon={<UploadOutlined />} block>
|
||||
选择CSV文件
|
||||
</Button>
|
||||
</Upload>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<p>正在导入数据...</p>
|
||||
<Progress percent={importProgress} status="active" style={{ marginBottom: 20 }} />
|
||||
{importResult && (
|
||||
<div>
|
||||
<p style={{ marginBottom: 10 }}>导入完成:</p>
|
||||
<p>总记录数:{importResult.statistics.total}</p>
|
||||
<p>成功:{importResult.statistics.success}</p>
|
||||
<p>失败:{importResult.statistics.failed}</p>
|
||||
{importResult.statistics.errors.length > 0 && (
|
||||
<div style={{ marginTop: 20, maxHeight: 300, overflowY: 'auto' }}>
|
||||
<h4>失败记录:</h4>
|
||||
<ul>
|
||||
{importResult.statistics.errors.map((item, index) => (
|
||||
<li key={index} style={{ color: 'red', fontSize: '12px', marginBottom: 5 }}>
|
||||
行{item.row}:{item.error}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<Button type="primary" onClick={() => {
|
||||
setImportModalVisible(false);
|
||||
setImportProgress(0);
|
||||
setImportResult(null);
|
||||
setIsImporting(false);
|
||||
fetchDevices();
|
||||
}} style={{ marginTop: 20 }}>
|
||||
确定
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Table, Button, Modal, Form, Input, Select, message, Card, Space, InputNumber } from 'antd';
|
||||
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||
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';
|
||||
|
||||
const { Option } = Select;
|
||||
@@ -13,6 +13,8 @@ function RackManagement() {
|
||||
const [editingRack, setEditingRack] = useState(null);
|
||||
const [form] = Form.useForm();
|
||||
|
||||
|
||||
|
||||
// 获取所有机柜
|
||||
const fetchRacks = async () => {
|
||||
try {
|
||||
@@ -103,6 +105,12 @@ function RackManagement() {
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// 状态标签映射
|
||||
const statusMap = {
|
||||
active: { text: '在用', color: 'green' },
|
||||
@@ -183,9 +191,11 @@ function RackManagement() {
|
||||
return (
|
||||
<div>
|
||||
<Card title="机柜管理" extra={
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
|
||||
添加机柜
|
||||
</Button>
|
||||
<Space>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
|
||||
添加机柜
|
||||
</Button>
|
||||
</Space>
|
||||
}>
|
||||
<Table
|
||||
columns={columns}
|
||||
@@ -276,6 +286,8 @@ function RackManagement() {
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Table, Button, Modal, Form, Input, Select, message, Card, Space, InputNumber } from 'antd';
|
||||
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||
import { Table, Button, Modal, Form, Input, Select, message, Card, Space, InputNumber, Upload, Progress, Alert } from 'antd';
|
||||
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
import axios from 'axios';
|
||||
|
||||
const { Option } = Select;
|
||||
@@ -12,6 +12,8 @@ function RoomManagement() {
|
||||
const [editingRoom, setEditingRoom] = useState(null);
|
||||
const [form] = Form.useForm();
|
||||
|
||||
|
||||
|
||||
// 获取所有机房
|
||||
const fetchRooms = async () => {
|
||||
try {
|
||||
@@ -90,6 +92,12 @@ function RoomManagement() {
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// 状态标签映射
|
||||
const statusMap = {
|
||||
active: { text: '在用', color: 'green' },
|
||||
@@ -171,9 +179,11 @@ function RoomManagement() {
|
||||
return (
|
||||
<div>
|
||||
<Card title="机房管理" extra={
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
|
||||
添加机房
|
||||
</Button>
|
||||
<Space>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
|
||||
添加机房
|
||||
</Button>
|
||||
</Space>
|
||||
}>
|
||||
<Table
|
||||
columns={columns}
|
||||
@@ -265,6 +275,10 @@ function RoomManagement() {
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user