const mongoose = require('mongoose'); const fs = require('fs'); const path = require('path'); const connectDB = require('../config/db'); const User = require('../models/User'); const Asset = require('../models/Asset'); /** * Hàm định dạng dung lượng file */ function formatBytes(bytes, decimals = 2) { if (bytes === 0) return '0 Bytes'; const k = 1024; const dm = decimals < 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } /** * Script thống kê dung lượng lưu trữ theo từng người dùng */ const getStorageStats = async () => { try { console.log('=== ĐANG TRUY XUẤT THỐNG KÊ DUNG LƯỢNG LƯU TRỮ ==='); await connectDB(); // 1. Lấy tất cả user để map tên const users = await User.find().select('username email').lean(); const userMap = {}; const stats = {}; users.forEach(u => { userMap[u._id.toString()] = u.username; stats[u._id.toString()] = { username: u.username, email: u.email, fileCount: 0, totalBytes: 0 }; }); // Thêm mục cho các asset không có chủ sở hữu (nếu có) stats['unknown'] = { username: 'Không xác định', email: 'N/A', fileCount: 0, totalBytes: 0 }; // 2. Lấy tất cả Asset const assets = await Asset.find().lean(); console.log(`- Đang kiểm tra ${assets.length} tệp tin trong hệ thống...`); for (const asset of assets) { const userId = asset.uploadedBy ? asset.uploadedBy.toString() : 'unknown'; if (asset.filePath && fs.existsSync(asset.filePath)) { const fileStat = fs.statSync(asset.filePath); if (stats[userId]) { stats[userId].totalBytes += fileStat.size; stats[userId].fileCount += 1; } else { stats['unknown'].totalBytes += fileStat.size; stats['unknown'].fileCount += 1; } } } // 3. Hiển thị kết quả console.log('\nKết quả thống kê:'); console.log(''.padEnd(60, '-')); console.log(`${'Username'.padEnd(20)} | ${'Số file'.padEnd(10)} | ${'Dung lượng'}`); console.log(''.padEnd(60, '-')); Object.values(stats).forEach(userStat => { if (userStat.fileCount > 0) { console.log(`${userStat.username.padEnd(20)} | ${userStat.fileCount.toString().padEnd(10)} | ${formatBytes(userStat.totalBytes)}`); } }); console.log(''.padEnd(60, '-')); mongoose.connection.close(); } catch (err) { console.error('Lỗi khi thống kê:', err.message); if (mongoose.connection) mongoose.connection.close(); process.exit(1); } }; getStorageStats();