Files
nxxmdata/backend/update-device-status.js
2025-08-25 15:00:46 +08:00

88 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 更新设备状态脚本
* 将设备状态更新为online、maintenance、offline三种状态
*/
const { Device } = require('./models');
async function updateDeviceStatus() {
try {
console.log('开始更新设备状态...');
// 获取所有设备
const devices = await Device.findAll();
console.log(`找到 ${devices.length} 个设备`);
// 计算每种状态的设备数量
const totalDevices = devices.length;
const onlineCount = Math.floor(totalDevices * 0.6); // 60% 在线
const maintenanceCount = Math.floor(totalDevices * 0.15); // 15% 维护
const offlineCount = totalDevices - onlineCount - maintenanceCount; // 剩余离线
console.log(`计划分配: ${onlineCount} 在线, ${maintenanceCount} 维护, ${offlineCount} 离线`);
// 随机打乱设备数组
const shuffledDevices = devices.sort(() => Math.random() - 0.5);
// 批量更新设备状态
const updates = [];
// 设置在线设备
for (let i = 0; i < onlineCount; i++) {
updates.push(
Device.update(
{ status: 'online' },
{ where: { id: shuffledDevices[i].id } }
)
);
}
// 设置维护设备
for (let i = onlineCount; i < onlineCount + maintenanceCount; i++) {
updates.push(
Device.update(
{ status: 'maintenance' },
{ where: { id: shuffledDevices[i].id } }
)
);
}
// 设置离线设备
for (let i = onlineCount + maintenanceCount; i < totalDevices; i++) {
updates.push(
Device.update(
{ status: 'offline' },
{ where: { id: shuffledDevices[i].id } }
)
);
}
// 执行所有更新
await Promise.all(updates);
// 验证更新结果
const statusCount = await Device.findAll({
attributes: [
'status',
[Device.sequelize.fn('COUNT', Device.sequelize.col('status')), 'count']
],
group: ['status'],
raw: true
});
console.log('\n更新完成当前设备状态分布:');
statusCount.forEach(item => {
console.log(`${item.status}: ${item.count} 个设备`);
});
console.log('\n设备状态更新成功');
} catch (error) {
console.error('更新设备状态失败:', error);
} finally {
process.exit(0);
}
}
// 执行更新
updateDeviceStatus();