cmsmanage/paperwork/api.py

81 lines
2.8 KiB
Python
Raw Normal View History

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
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.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:
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/certification_definition", CertificationDefinitionViewSet)
router.register(r"paperwork/certification_version", CertificationVersionViewSet)
router.register(r"paperwork/certification", CertificationViewSet)