from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, IsAdminUser from django.utils import timezone from datetime import timedelta from django.db.models import Count from apps.account.models import User from apps.course.models import Course, Participant from apps.blog.models import Blog from apps.certificate.models import Certificate # Import your Transaction model here class AdminDashboardStatsView(APIView): permission_classes = [IsAuthenticated, IsAdminUser] def get(self, request): now = timezone.now() thirty_days_ago = now - timedelta(days=30) # 1. Basic Counts active_students = User.objects.filter(groups__name="Student Group", is_active=True).count() professors = User.objects.filter(groups__name="Professor Group", is_active=True).count() active_courses = Course.objects.filter(status=Course.StatusChoices.ONGOING).count() total_blogs = Blog.objects.count() pending_certificates = Certificate.objects.filter(status='pending').count() # 2. Revenue (Mocked - replace with your actual Transaction logic) # revenue_30d = Transaction.objects.filter(status='success', created_at__gte=thirty_days_ago).aggregate(Sum('amount'))['amount__sum'] or 0 revenue_30d = 12500.00 # Dummy data # 3. Transaction Chart Data (Mocked - replace with actual grouped query) transactions_data = [ {"name": "Success", "value": 450, "fill": "var(--color-success)"}, {"name": "Pending", "value": 85, "fill": "var(--color-pending)"}, {"name": "Waiting", "value": 40, "fill": "var(--color-waiting)"}, {"name": "Failed", "value": 25, "fill": "var(--color-failed)"}, ] # 4. Top 5 Popular Courses top_courses = Course.objects.annotate( participant_count=Count('participants') ).order_by('-participant_count')[:5] top_courses_data = [ { "id": c.id, "title": c.title, "professor": c.professor.fullname if c.professor else "Unknown", "participants": c.participant_count } for c in top_courses ] return Response({ "cards": { "active_students": active_students, "professors": professors, "active_courses": active_courses, "total_blogs": total_blogs, "revenue_30d": revenue_30d, "pending_certificates": pending_certificates }, "transactions_chart": transactions_data, "top_courses": top_courses_data })