from rest_framework import generics from rest_framework.exceptions import NotFound from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi from rest_framework.permissions import IsAuthenticated from apps.account.models import StudentUser from apps.course.models import Participant, Course from apps.course.serializers import ParticipantSerializer from apps.account.serializers import UserProfileSerializer from apps.course.doc import * from utils.exceptions import AppAPIException from utils.pagination import StandardResultsSetPagination class CourseParticipantsView(generics.ListAPIView): serializer_class = UserProfileSerializer pagination_class = StandardResultsSetPagination @swagger_auto_schema( operation_description=doc_course_participants(), tags=['Imam-Javad - Course'], ) def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def get_queryset(self): """ Optimized queryset with select_related for course relationship. Filters out guest users (no email) and soft-deleted users (is_active=False). """ course_slug = self.kwargs.get('slug') try: course = Course.objects.get(slug=course_slug) except Course.DoesNotExist: raise AppAPIException({'message': "Course not found"}) # 👇 Apply the strict filters for Normal Users only return StudentUser.objects.select_related().filter( participated_courses__course=course, is_active=True, # Exclude soft-deleted users email__isnull=False # Exclude guest users ).exclude( email__exact='' # Extra safety just in case an email is a blank string ) # class ParticipantCreateView(generics.CreateAPIView): # queryset = StudentUser.objects.all() # serializer_class = ParticipantSerializer # permission_classes = [IsAuthenticated] # def create(self, request, *args, **kwargs): # user = request.user # course_slug = self.kwargs.get('slug') # Get the slug from the URL # try: # course = Course.objects.get(slug=slug) # Retrieve the Course object # except Course.DoesNotExist: # raise AppAPIException({'message': "Course not found"}) # Handle course not found # if request.data.get('email') != request.user: # raise AppAPIException({'message': "The email must be for the requesting user"}) # if user.user_type != User.UserType.STUDENT: # user.change_user_type(User.UserType.STUDENT) # participant, created = Participant.objects.get_or_create( # student=user, # course=course # ) # serializer = self.get_serializer(participant) # return Response(serializer.data, status=status.HTTP_201_CREATED)