import { Request, Response, NextFunction } from 'express'; import userRepository from '../repositories/userRepository'; import licenseRepository from '../repositories/licenseRepository'; import subscriptionRepository from '../repositories/subscriptionRepository'; import scanRepository from '../repositories/scanRepository'; import paymentRepository from '../repositories/paymentRepository'; import licenseService from '../services/licenseService'; import { PAGINATION } from '../utils/constants'; export class AdminController { async getDashboard(_req: Request, res: Response, next: NextFunction) { try { const [totalUsers, roleCount, activeSubscriptions, revenue, totalScans, planCount] = await Promise.all([ userRepository.getTotalCount(), userRepository.countByRole(), subscriptionRepository.getActiveCount(), subscriptionRepository.getRevenueEstimate(), scanRepository.getTotalScans(), licenseRepository.countByPlan(), ]); res.json({ success: true, data: { totalUsers, usersByRole: roleCount, activeSubscriptions, totalRevenue: revenue, totalScans, licensesByPlan: planCount, }, }); } catch (error) { next(error); } } async getUsers(req: Request, res: Response, next: NextFunction) { try { const page = parseInt(req.query.page as string) || PAGINATION.defaultPage; const limit = Math.min( parseInt(req.query.limit as string) || PAGINATION.defaultLimit, PAGINATION.maxLimit ); const search = req.query.search as string | undefined; const result = await userRepository.findAll(page, limit, search); res.json({ success: true, data: result }); } catch (error) { next(error); } } async suspendUser(req: Request, res: Response, next: NextFunction) { try { const { id } = req.params; await userRepository.suspend(id); res.json({ success: true, message: 'User suspended' }); } catch (error) { next(error); } } async activateUser(req: Request, res: Response, next: NextFunction) { try { const { id } = req.params; await userRepository.activate(id); res.json({ success: true, message: 'User activated' }); } catch (error) { next(error); } } async generateLicense(req: Request, res: Response, next: NextFunction) { try { const { userId, plan, durationDays } = req.body; const license = await licenseService.generateLicense(userId, plan, durationDays); res.status(201).json({ success: true, data: license }); } catch (error) { next(error); } } async getRevenue(req: Request, res: Response, next: NextFunction) { try { const months = parseInt(req.query.months as string) || 12; const payments = await paymentRepository.getMonthlyRevenue(months); // Group by month const grouped: Record = {}; payments.forEach((p) => { if (p.paidAt) { const key = `${p.paidAt.getFullYear()}-${String(p.paidAt.getMonth() + 1).padStart(2, '0')}`; grouped[key] = (grouped[key] || 0) + p.amount; } }); res.json({ success: true, data: { monthlyRevenue: grouped, totalRevenue: payments.reduce((sum, p) => sum + p.amount, 0), }, }); } catch (error) { next(error); } } } export default new AdminController();