views.py 7.78 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from rest_framework import viewsets, permissions, status
from rest_framework.response import Response
from rest_framework.decorators import action

from django.views.generic import DetailView
from django.urls import resolve
from django.http import Http404

from courses.permissions import IsProfessorCoordinatorOrAdminPermissionOrReadOnly

from courses.certification.serializers import (
    CertificationProcessSerializer,
    CourseCertificationSerializer,
    CertificateTemplateSerializer,
15
    CertificateTemplateCreateSerializer,
16 17 18 19 20 21 22 23 24
    CertificateTemplateImageSerializer,
)

from courses.certification.models import (
    CertificationProcess,
    CourseCertification,
    CertificateTemplate,
)

25 26 27
from courses.models import Course
from courses.workspaces.models import Workspace

28 29 30

class CertificateDataMixin(viewsets.ModelViewSet):
     def get_queryset(self):
31
        queryset = CertificateTemplate.objects.all()
32 33
        course = self.request.query_params.get('course', None)
        if course:
34
            queryset = queryset.filter(course=course)
35

36
        workspace = self.request.query_params.get('workspace', None)
37 38
        if workspace:
            queryset = queryset.filter(workspace=workspace)
39 40 41 42 43

        return queryset


class CertificateDataViewSet(CertificateDataMixin, viewsets.ModelViewSet):
44
    model = CertificateTemplate
45 46
    permission_classes = (IsProfessorCoordinatorOrAdminPermissionOrReadOnly, )

47 48 49 50 51
    def get_serializer_class(self):
        if self.action == 'create':
            return CertificateTemplateCreateSerializer
        return CertificateTemplateSerializer

52 53 54 55 56 57
    @action(detail=True, methods=['get', 'post'])
    def images(self, request, pk=None):
        obj = self.get_object()
        errors = []

        clear_logos = (
58
            ('cert_logo', request.data.get('cert_logo_clear', None)),
59 60
            ('base_logo', request.data.get('base_logo_clear', None)),
            ('signature', request.data.get('signature_clear', None)),
61
            ('site_logo', request.data.get('site_logo_clear', None)),
62 63 64
        )
        for cl in clear_logos:
            if(cl[1]):
65
                setattr(obj, cl[0], None)
66

67
        serializer = CertificateTemplateImageSerializer(obj, request.FILES)
68 69
        if serializer.is_valid():
            serializer.save()
70 71
            return Response(CertificateTemplateSerializer(obj).data,
                            status=status.HTTP_200_OK)
72
        else:
73
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

class CertificationProcessViewSet(viewsets.ModelViewSet):
    model = CertificationProcess
    filter_fields = ('student',)
    serializer_class = CertificationProcessSerializer

    permission_classes = []

    def get_queryset(self):
        queryset = super().get_queryset()

        klass = self.request.query_params.get('klass')
        if klass:
            queryset = queryset.filter(klass=klass)

        return queryset


class CourseCertificationViewSet(viewsets.ModelViewSet):
    queryset = CourseCertification.objects.all()
    model = CourseCertification
    lookup_field = 'link_hash'
    filter_fields = ('course_student',)
    serializer_class = CourseCertificationSerializer

    def get_queryset(self):
        queryset = super(CourseCertificationViewSet, self).get_queryset()
        if not self.request.GET.get('user', False):
            queryset = queryset.filter(course_student__user=self.request.user)

        return queryset


class CertificateTemplateViewSet(viewsets.ModelViewSet):
    model = CertificateTemplate
    queryset = CertificateTemplate.objects.all()
110 111
    # lookup_field = 'course'
    permission_classes = (IsProfessorCoordinatorOrAdminPermissionOrReadOnly, )
112 113
    serializer_class = CertificateTemplateSerializer

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    def get_serializer_class(self):
        if self.action == 'create':
            return CertificateTemplateCreateSerializer
        return CertificateTemplateSerializer

    @action(detail=True, methods=['get', 'post'])
    def images(self, request, pk=None):
        obj = self.get_object()
        errors = []

        clear_logos = (
            ('cert_logo', request.data.get('cert_logo_clear', None)),
            ('base_logo', request.data.get('base_logo_clear', None)),
            ('signature', request.data.get('signature_clear', None)),
            ('site_logo', request.data.get('site_logo_clear', None)),
        )
        for cl in clear_logos:
            if(cl[1]):
                setattr(obj, cl[0], None)

        serializer = CertificateTemplateImageSerializer(obj, request.FILES)
        if serializer.is_valid():
            serializer.save()
            return Response(CertificateTemplateSerializer(obj).data,
                            status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    def update(self, request, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data)
        if serializer.is_valid():
            serializer.save()
        return Response(serializer.data)


class CertificateTemplateImageViewSet(viewsets.ModelViewSet):
    queryset = CertificateTemplate.objects.all()
    model = CertificateTemplate
    lookup_field = 'course'
    serializer_class = CertificateTemplateImageSerializer
    permission_classes = (IsProfessorCoordinatorOrAdminPermissionOrReadOnly, )

    def post(self, request, **kwargs):
        certificate_template = self.get_object()
159 160
        serializer = CertificateTemplateImageSerializer(certificate_template,
                                                        request.FILES)
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184

        if serializer.is_valid():
            serializer.save()
            return Response(status=200)
        else:
            return Response(serializer.errors, status=400)


class CourseCertificationDetailView(DetailView):
    model = CourseCertification
    template_name = 'certificate.html'
    slug_field = "link_hash"
    serializer_class = CourseCertificationSerializer

    def render_to_response(self, context, **response_kwargs):

        certificate = context.get('object')
        workspace = certificate.course_student\
            .get_current_class().contract.first()

        if not certificate.course_student.can_emmit_receipt():
            raise Http404

        if certificate:
185 186
            context['cert_template'] = CertificateTemplate.objects.get(
                course=certificate.course_student.course,
187
                document_type=certificate.type,
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
            )
            # Interpolate data into text string
            # {Nome} : certificate.student (name)
            # {CPF} : certificate.student.cpf)
            # {MODULO} : certificate.course.name)
            # {CONTRATO} : context['cert_template'].workspace.name)
            # {NUM_UNIDADES} : str(certificate.course_total_units))
            # {TURMA} : certificate.course_student.get_current_class().name)

            if '{MODULO}' in context['cert_template'].text:
                context['cert_template'].text = context['cert_template'].text.replace(
                    '{MODULO}',
                    certificate.course.name,
                )

            if '{CPF}' in context['cert_template'].text:
                context['cert_template'].text = context['cert_template'].text.replace(
                    '{CPF}',
                    certificate.student.cpf,
                )

            context['cert_template'].text = context['cert_template'].text\
                .replace('{NOME}', certificate.student.get_full_name())\
                .replace('{CONTRATO}', context['cert_template'].workspace.name)\
                .replace('{NUM_UNIDADES}', str(certificate.course_total_units))\
                .replace('{TURMA}', certificate.course_student.get_current_class().name)\

        url_name = resolve(self.request.path_info).url_name

        return super().render_to_response(context, **response_kwargs)