paperwork: Add certification_definition/mailing_lists API endpoint

This commit is contained in:
Adam Goldsmith 2022-12-25 01:22:21 -05:00
parent 48cad701e8
commit a9dcda9508

View File

@ -1,5 +1,9 @@
from django.db.models import Prefetch
from rest_framework import routers, serializers, viewsets 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 from .models import Certification, CertificationDefinition, CertificationVersion
@ -13,6 +17,32 @@ class CertificationDefinitionViewSet(viewsets.ModelViewSet):
queryset = CertificationDefinition.objects.all() queryset = CertificationDefinition.objects.all()
serializer_class = CertificationDefinitionSerializer 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 CertificationVersionSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta: