diff --git a/paperwork/api.py b/paperwork/api.py index 9689678..e216bb4 100644 --- a/paperwork/api.py +++ b/paperwork/api.py @@ -1,5 +1,9 @@ +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 Certification, CertificationDefinition, CertificationVersion @@ -13,6 +17,32 @@ 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.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( + f"{cert.member.account_name} <{cert.member.email}>" + ) + + return Response(lists) + class CertificationVersionSerializer(serializers.HyperlinkedModelSerializer): class Meta: