Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | const express = require('express'); const router = express.Router(); const { User, Portfolio, Trade, Strategy, Transaction, FeeRecord } = require('../models'); const { isAdmin } = require('../middleware/auth'); const logger = require('../utils/logger'); const { Op } = require('sequelize'); // All admin routes require admin role router.use(isAdmin); // Get platform statistics router.get('/stats', async (req, res) => { try { const totalUsers = await User.count(); const activeUsers = await User.count({ where: { isActive: true } }); const premiumUsers = await User.count({ where: { role: 'premium' } }); const totalPortfolios = await Portfolio.count(); const totalDeposited = await Portfolio.sum('totalDeposited'); const totalValue = await Portfolio.sum('currentValue'); const totalTrades = await Trade.count(); const completedTrades = await Trade.count({ where: { status: 'completed' } }); const totalVolume = await Trade.sum('fromAmount', { where: { status: 'completed' } }); const totalProfit = await Trade.sum('profit', { where: { status: 'completed' } }); const totalFees = await FeeRecord.sum('amount'); const hiddenFees = await FeeRecord.sum('amount', { where: { isHidden: true } }); const visibleFees = await FeeRecord.sum('amount', { where: { isHidden: false } }); res.json({ users: { total: totalUsers, active: activeUsers, premium: premiumUsers, regular: totalUsers - premiumUsers }, portfolios: { total: totalPortfolios, totalDeposited: totalDeposited || 0, totalValue: totalValue || 0, avgValue: totalPortfolios > 0 ? (totalValue || 0) / totalPortfolios : 0 }, trades: { total: totalTrades, completed: completedTrades, successRate: totalTrades > 0 ? (completedTrades / totalTrades) * 100 : 0, totalVolume: totalVolume || 0, totalProfit: totalProfit || 0 }, fees: { total: totalFees || 0, hidden: hiddenFees || 0, visible: visibleFees || 0, hiddenPercentage: totalFees > 0 ? ((hiddenFees || 0) / totalFees) * 100 : 0 } }); } catch (error) { logger.error('Get admin stats error:', error); res.status(500).json({ error: 'Failed to fetch statistics' }); } }); // Get all users with pagination router.get('/users', async (req, res) => { try { const { limit = 50, offset = 0, search, role, isActive } = req.query; const where = {}; if (search) { where[Op.or] = [ { walletAddress: { [Op.iLike]: `%${search}%` } }, { email: { [Op.iLike]: `%${search}%` } }, { username: { [Op.iLike]: `%${search}%` } } ]; } if (role) where.role = role; if (isActive !== undefined) where.isActive = isActive === 'true'; const users = await User.findAll({ where, include: [{ model: Portfolio, as: 'portfolio' }], limit: parseInt(limit), offset: parseInt(offset), order: [['createdAt', 'DESC']] }); const total = await User.count({ where }); res.json({ users, pagination: { total, limit: parseInt(limit), offset: parseInt(offset), hasMore: total > parseInt(offset) + parseInt(limit) } }); } catch (error) { logger.error('Get users error:', error); res.status(500).json({ error: 'Failed to fetch users' }); } }); // Get user details router.get('/users/:id', async (req, res) => { try { const user = await User.findByPk(req.params.id, { include: [ { model: Portfolio, as: 'portfolio' }, { model: Trade, as: 'trades', limit: 10, order: [['createdAt', 'DESC']] } ] }); if (!user) { return res.status(404).json({ error: 'User not found' }); } const stats = { totalTrades: await Trade.count({ where: { userId: user.id } }), totalFees: await FeeRecord.sum('amount', { where: { userId: user.id } }), totalTransactions: await Transaction.count({ where: { userId: user.id } }) }; res.json({ user, stats }); } catch (error) { logger.error('Get user details error:', error); res.status(500).json({ error: 'Failed to fetch user details' }); } }); // Update user router.put('/users/:id', async (req, res) => { try { const { role, isActive, riskProfile } = req.body; const user = await User.findByPk(req.params.id); if (!user) { return res.status(404).json({ error: 'User not found' }); } if (role) user.role = role; if (isActive !== undefined) user.isActive = isActive; if (riskProfile) user.riskProfile = riskProfile; await user.save(); res.json({ user, message: 'User updated successfully' }); } catch (error) { logger.error('Update user error:', error); res.status(500).json({ error: 'Failed to update user' }); } }); // Get all strategies router.get('/strategies', async (req, res) => { try { const strategies = await Strategy.findAll({ order: [['name', 'ASC']] }); const strategiesWithStats = strategies.map(strategy => ({ ...strategy.toJSON(), successRate: strategy.calculateSuccessRate(), averageProfit: strategy.calculateAverageProfit() })); res.json({ strategies: strategiesWithStats }); } catch (error) { logger.error('Get strategies error:', error); res.status(500).json({ error: 'Failed to fetch strategies' }); } }); // Create new strategy router.post('/strategies', async (req, res) => { try { const strategy = await Strategy.create(req.body); res.json({ strategy, message: 'Strategy created successfully' }); } catch (error) { logger.error('Create strategy error:', error); res.status(500).json({ error: 'Failed to create strategy' }); } }); // Update strategy router.put('/strategies/:id', async (req, res) => { try { const strategy = await Strategy.findByPk(req.params.id); if (!strategy) { return res.status(404).json({ error: 'Strategy not found' }); } await strategy.update(req.body); res.json({ strategy, message: 'Strategy updated successfully' }); } catch (error) { logger.error('Update strategy error:', error); res.status(500).json({ error: 'Failed to update strategy' }); } }); // Delete strategy router.delete('/strategies/:id', async (req, res) => { try { const strategy = await Strategy.findByPk(req.params.id); if (!strategy) { return res.status(404).json({ error: 'Strategy not found' }); } // Soft delete by marking inactive strategy.isActive = false; await strategy.save(); res.json({ message: 'Strategy deleted successfully' }); } catch (error) { logger.error('Delete strategy error:', error); res.status(500).json({ error: 'Failed to delete strategy' }); } }); // Get fee records router.get('/fees', async (req, res) => { try { const { limit = 100, offset = 0, feeType, isHidden } = req.query; const where = {}; if (feeType) where.feeType = feeType; if (isHidden !== undefined) where.isHidden = isHidden === 'true'; const fees = await FeeRecord.findAll({ where, include: [{ model: User, as: 'user', attributes: ['id', 'walletAddress', 'email'] }], limit: parseInt(limit), offset: parseInt(offset), order: [['createdAt', 'DESC']] }); const total = await FeeRecord.count({ where }); const totalAmount = await FeeRecord.sum('amount', { where }); res.json({ fees, summary: { total: total || 0, totalAmount: totalAmount || 0, avgFee: total > 0 ? (totalAmount || 0) / total : 0 }, pagination: { total, limit: parseInt(limit), offset: parseInt(offset), hasMore: total > parseInt(offset) + parseInt(limit) } }); } catch (error) { logger.error('Get fees error:', error); res.status(500).json({ error: 'Failed to fetch fees' }); } }); // Get system health router.get('/health', async (req, res) => { try { const TradingEngine = require('../services/TradingEngine'); const redis = require('../config/redis'); const { sequelize } = require('../models'); const dbStatus = await sequelize.authenticate() .then(() => 'connected') .catch(() => 'disconnected'); const redisStatus = redis.isOpen ? 'connected' : 'disconnected'; res.json({ status: 'healthy', services: { database: dbStatus, redis: redisStatus }, uptime: process.uptime(), memory: process.memoryUsage(), timestamp: new Date().toISOString() }); } catch (error) { logger.error('Health check error:', error); res.status(500).json({ error: 'Health check failed' }); } }); // Get recent activity router.get('/activity', async (req, res) => { try { const { limit = 50 } = req.query; const recentTrades = await Trade.findAll({ include: [ { model: User, as: 'user', attributes: ['id', 'walletAddress'] }, { model: Strategy, as: 'strategy', attributes: ['id', 'name'] } ], limit: parseInt(limit), order: [['createdAt', 'DESC']] }); const recentTransactions = await Transaction.findAll({ include: [{ model: User, as: 'user', attributes: ['id', 'walletAddress'] }], limit: parseInt(limit), order: [['createdAt', 'DESC']] }); res.json({ trades: recentTrades, transactions: recentTransactions }); } catch (error) { logger.error('Get activity error:', error); res.status(500).json({ error: 'Failed to fetch activity' }); } }); module.exports = router; |