from decimal import Decimal
from django.db.models import Sum,Q,Count,DecimalField,Value
from django.db.models.functions import Coalesce
from rest_framework.views import APIView
from rest_framework.response import Response
from apps.accounts.models import User
from apps.core.models import Campus
from apps.activities.models import ActivityReport
from apps.finance.models import FinanceEntry
class DashboardSummary(APIView):
 def get(self,request):
  money=DecimalField(max_digits=14,decimal_places=2)
  finance=FinanceEntry.objects.filter(approved=True).aggregate(income=Coalesce(Sum('amount',filter=Q(direction='INCOME')),Value(Decimal('0.00')),output_field=money),expenses=Coalesce(Sum('amount',filter=Q(direction='EXPENSE')),Value(Decimal('0.00')),output_field=money))
  activities=ActivityReport.objects.filter(approved=True).aggregate(events=Count('id'),attendance=Coalesce(Sum('attendance'),0),souls_won=Coalesce(Sum('souls_won'),0),followed_up=Coalesce(Sum('converts_followed_up'),0))
  return Response({'members':User.objects.filter(is_active=True).count(),'alumni':User.objects.filter(member_type='ALUMNI').count(),'current_students':User.objects.filter(member_type='CURRENT').count(),'campuses':Campus.objects.filter(active=True).count(),'finance':{**finance,'balance':finance['income']-finance['expenses']},'activities':activities})
class CampusRollup(APIView):
 def get(self,request):
  rows=[]
  for c in Campus.objects.filter(active=True):
   money=DecimalField(max_digits=14,decimal_places=2)
   f=FinanceEntry.objects.filter(campus=c,approved=True).aggregate(income=Coalesce(Sum('amount',filter=Q(direction='INCOME')),Value(Decimal('0.00')),output_field=money),expenses=Coalesce(Sum('amount',filter=Q(direction='EXPENSE')),Value(Decimal('0.00')),output_field=money))
   a=ActivityReport.objects.filter(campus=c,approved=True).aggregate(events=Count('id'),attendance=Coalesce(Sum('attendance'),0),souls_won=Coalesce(Sum('souls_won'),0))
   rows.append({'campus_id':c.id,'campus':c.name,**a,**f,'balance':f['income']-f['expenses']})
  return Response(rows)
