from django.db.models import Prefetch from rest_framework import routers, serializers, viewsets from rest_framework.decorators import action from rest_framework.response import Response from membershipworks.models import Member from .models import ( Department, Certification, CertificationDefinition, CertificationVersion, ) class DepartmentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Department fields = ["name", "parent", "list_moderator_flag", "list_reply_to_address"] class DepartmentViewSet(viewsets.ModelViewSet): queryset = Department.objects.all() serializer_class = DepartmentSerializer class CertificationDefinitionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CertificationDefinition fields = ["certification_name", "department", "mailing_list"] class CertificationDefinitionViewSet(viewsets.ModelViewSet): queryset = CertificationDefinition.objects.all() serializer_class = CertificationDefinitionSerializer @action(detail=False, methods=["get"]) def mailing_lists(self, request, format=None): """ Generate a mailing list for each certification definition, containing all certified users for that tool """ lists = {} for definition in self.queryset.exclude(mailing_list="").prefetch_related( Prefetch( "certificationversion_set__certification_set__member", queryset=Member.objects.with_is_active(), ), ): if definition.mailing_list not in lists: lists[definition.mailing_list] = set() # TODO: this could be done in sql instead; was planning to # maybe also filter to only active certs for version in definition.certificationversion_set.all(): for cert in version.certification_set.all(): if cert.member and cert.member.is_active: lists[definition.mailing_list].add( cert.member.sanitized_mailbox ) return Response(lists) class CertificationVersionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CertificationVersion fields = ["definition", "version"] class CertificationVersionViewSet(viewsets.ModelViewSet): queryset = CertificationVersion.objects.all() serializer_class = CertificationVersionSerializer class CertificationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Certification fields = [ "name", "member", "certification_version", "certified_by", "date", "shop_lead_notified", "notes", ] class CertificationViewSet(viewsets.ModelViewSet): queryset = Certification.objects.all() serializer_class = CertificationSerializer router = routers.DefaultRouter() router.register(r"paperwork/department", DepartmentViewSet) router.register(r"paperwork/certification_definition", CertificationDefinitionViewSet) router.register(r"paperwork/certification_version", CertificationVersionViewSet) router.register(r"paperwork/certification", CertificationViewSet)