Commit a2500762 authored by Virgilio Santos's avatar Virgilio Santos
Browse files

certificate: remove CertificateData auxiliary model

parent 9dc2f0ab
......@@ -4,12 +4,10 @@ from .models import (
CourseCertification,
CertificateTemplate,
CertificationProcess,
CertificateData,
Evaluation,
)
admin.site.register(CourseCertification)
admin.site.register(CertificateTemplate)
admin.site.register(CertificationProcess)
admin.site.register(CertificateData)
admin.site.register(Evaluation)
# Generated by Django 2.2.13 on 2020-07-03 23:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('courses', '0009_auto_20200609_1453'),
('certification', '0003_auto_20200630_2323'),
]
operations = [
migrations.AddField(
model_name='certificatetemplate',
name='document_type',
field=models.CharField(choices=[('receipt', 'Receipt'), ('certificate', 'Certificate')], default='receipt', max_length=127, verbose_name='Certificate Type'),
),
migrations.AddField(
model_name='certificatetemplate',
name='site_logo',
field=models.ImageField(blank=True, null=True, upload_to='certificates_files', verbose_name='Site Logo'),
),
migrations.AddField(
model_name='certificatetemplate',
name='text',
field=models.TextField(default='', verbose_name='Content'),
),
migrations.AddField(
model_name='certificatetemplate',
name='workspace',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='courses.Workspace'),
),
migrations.AlterUniqueTogether(
name='certificatetemplate',
unique_together={('workspace', 'course', 'document_type')},
),
migrations.DeleteModel(
name='CertificateData',
),
]
......@@ -197,6 +197,10 @@ class CertificationProcess(models.Model):
class CertificateTemplate(models.Model):
TYPES = (
('receipt', _('Receipt')),
('certificate', _('Certificate')),
)
course = models.ForeignKey(
Course,
......@@ -233,15 +237,36 @@ class CertificateTemplate(models.Model):
blank=True,
upload_to=hash_name('signature', 'organization_name'),
)
site_logo = models.ImageField(
_('Site Logo'),
null=True,
blank=True,
upload_to='certificates_files'
)
organization_name = models.CharField(
_('Name'),
max_length=255,
blank=True,
null=True,
)
text = models.TextField(_('Content'), default='')
document_type = models.CharField(
_('Certificate Type'),
choices=TYPES,
max_length=127,
default=TYPES[0][0]
)
workspace = models.ForeignKey(
Workspace,
models.CASCADE,
null=True
)
class Meta:
verbose_name = _('Certificate Template')
unique_together = ('workspace', 'course', 'document_type')
def __unicode__(self):
return '({0})'.format(self.course)
......@@ -267,40 +292,6 @@ class CertificateTemplate(models.Model):
return self.signature.url
return ''
class CertificateData(models.Model):
site_logo = models.ImageField(_('Site Logo'), null=True, blank=True,
upload_to='certificates_files')
text = models.TextField(_('Content'), default='')
TYPES = (
('receipt', _('Receipt')),
('certificate', _('Certificate')),
)
type = models.CharField(
_('Certificate Type'),
choices=TYPES,
max_length=127,
)
workspace = models.ForeignKey(
Workspace,
models.CASCADE,
null=True
)
certificate_template = models.ForeignKey(
CertificateTemplate,
models.CASCADE,
)
class Meta:
verbose_name = _('Certificate Data')
unique_together = ('workspace', 'certificate_template', 'type')
def __str__(self):
return 'Data of {0} ({1})'.format(self.workspace, self.type)
@property
def site_logo_url(self):
if self.site_logo:
......@@ -308,5 +299,5 @@ class CertificateData(models.Model):
return ''
@property
def contrat(self):
def contract(self):
return self.workspace
......@@ -3,7 +3,6 @@ from rest_framework import serializers, status
from courses.workspaces.serializers import SimpleWorkspaceSerializer
from courses.certification.models import (
CertificateData,
CertificateTemplate,
CertificationProcess,
Evaluation,
......@@ -12,71 +11,36 @@ from courses.certification.models import (
class CertificateTemplateSerializer(serializers.ModelSerializer):
course_name = serializers.SerializerMethodField(read_only=True,)
# course = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = CertificateTemplate
fields = (
'id', 'course', 'course_name', 'organization_name',
'base_logo_url', 'cert_logo_url', 'role', 'name',
'signature_url',
)
def get_course_name(self, obj):
return obj.course.name
class CertificateDataSerializer(serializers.ModelSerializer):
workspace = SimpleWorkspaceSerializer(read_only=True)
certificate_template = CertificateTemplateSerializer()
associate = serializers.SerializerMethodField()
course_name = serializers.SerializerMethodField(read_only=True,)
# TODO: Legacy compat field, remove in the future
contract = serializers.SerializerMethodField()
class Meta:
model = CertificateData
fields = (
'id', 'text', 'type', 'site_logo_url',
'certificate_template', 'associate', 'workspace', 'contract',
)
model = CertificateTemplate
fields = ('id', 'text', 'base_logo_url', 'cert_logo_url', 'role', 'name',
'course_name', 'contract', 'associate', 'workspace', 'document_type',
'organization_name', 'site_logo_url', 'signature_url', 'course',)
def get_associate(self, obj):
if obj.type == 'receipt':
type = 'certificate'
else:
type = 'receipt'
a = CertificateData.objects.filter(
type=type,
certificate_template__course=obj.certificate_template.course,
workspace=obj.workspace,
)
if len(a) > 0:
return a[0].id
else:
return None
filters = {
'document_type' : 'certificate' if obj.document_type == 'receipt' else 'receipt',
'course': obj.course,
'workspace': obj.workspace
}
if CertificateTemplate.objects.filter(**filters).exists():
return CertificateTemplate.objects.filter(**filters).first().id
return None
def get_contract(self, obj):
if obj.workspace:
return SimpleWorkspaceSerializer(obj.workspace).data
return None
def update(self, instance, validated_data):
ct = dict(validated_data.pop('certificate_template'))
ct['course'] = ct['course'].id
cts = CertificateTemplateSerializer(instance=instance.certificate_template, data=ct)
cts.is_valid(raise_exception=True)
cts.save()
return super().update(instance, validated_data)
class CertificateImageDataSerializer(serializers.ModelSerializer):
class Meta:
model = CertificateData
fields = ('site_logo',)
def get_course_name(self, obj):
return obj.course.name
class CertificationProcessSerializer(serializers.ModelSerializer):
course_certification = serializers.SlugRelatedField(slug_field="link_hash", read_only=True)
......@@ -127,15 +91,8 @@ class EvaluationSerializer(serializers.ModelSerializer):
model = Evaluation
class CertificateTemplateSerializer(serializers.ModelSerializer):
class Meta:
model = CertificateTemplate
fields = ('id', 'course', 'organization_name', 'base_logo_url', 'cert_logo_url', 'role', 'name', 'signature_url', )
class CertificateTemplateImageSerializer(serializers.ModelSerializer):
class Meta:
model = CertificateTemplate
fields = ('base_logo', 'cert_logo', 'signature', )
fields = ('base_logo', 'cert_logo', 'signature', 'site_logo')
......@@ -6,7 +6,7 @@ from hashlib import sha1
from time import time
from courses.models import Course, CourseStudent
from courses.certification.models import CourseCertification, CertificateTemplate, CertificateData
from courses.certification.models import CourseCertification, CertificateTemplate
@receiver(post_save, sender=CourseStudent)
......@@ -25,8 +25,6 @@ def course_student_created_or_updated(sender, created, instance, **kwargs):
def course_created(sender, created, instance, **kwargs):
if created:
for type_ in CertificateData.TYPES:
ct = CertificateTemplate(course=instance)
for type_ in CertificateTemplate.TYPES:
ct = CertificateTemplate(course=instance, document_type=type_[0])
ct.save()
cd = CertificateData(type=type_[0], certificate_template=ct)
cd.save()
......@@ -9,8 +9,6 @@ from django.http import Http404
from courses.permissions import IsProfessorCoordinatorOrAdminPermissionOrReadOnly
from courses.certification.serializers import (
CertificateDataSerializer,
CertificateImageDataSerializer,
CertificationProcessSerializer,
CourseCertificationSerializer,
CertificateTemplateSerializer,
......@@ -18,7 +16,6 @@ from courses.certification.serializers import (
)
from courses.certification.models import (
CertificateData,
CertificationProcess,
CourseCertification,
CertificateTemplate,
......@@ -30,12 +27,12 @@ from courses.workspaces.models import Workspace
class CertificateDataMixin(viewsets.ModelViewSet):
def get_queryset(self):
queryset = CertificateData.objects.all()
queryset = CertificateTemplate.objects.all()
course = self.request.query_params.get('course', None)
if course:
queryset = queryset.filter(certificate_template__course=course)
queryset = queryset.filter(course=course)
workspace = self.request.query_params.get('contract', None)
workspace = self.request.query_params.get('workspace', None)
if workspace:
queryset = queryset.filter(workspace=workspace)
......@@ -43,79 +40,32 @@ class CertificateDataMixin(viewsets.ModelViewSet):
class CertificateDataViewSet(CertificateDataMixin, viewsets.ModelViewSet):
model = CertificateData
serializer_class = CertificateDataSerializer
model = CertificateTemplate
serializer_class = CertificateTemplateSerializer
permission_classes = (IsProfessorCoordinatorOrAdminPermissionOrReadOnly, )
def create(self, request, *args, **kwargs):
generate = request.data.get('generate', False)
if generate:
data = request.data
current = CertificateData.objects.filter(certificate_template__course__id=data.get('course', None),
workspace__id=data.get('workspace', None))
if len(current) >= 2:
return Response({'error' : 'Os templates já existem'}, status=status.HTTP_400_BAD_REQUEST)
else:
course = Course.objects.get(pk=data.get('course', None))
workspace = Workspace.objects.get(pk=data.get('contract', None))
if len(current) > 0:
ct = CertificateTemplate(course=course)
ct.save()
t = CertificateData.TYPES[0]
if 'receipt' == current[0].type:
t = CertificateData.TYPES[1]
cd = CertificateData(type=t[0], workspace=workspace, certificate_template=ct)
cd.save()
return Response({'message' : 'Os templates foram criados com sucesso'})
else:
for t in CertificateData.TYPES:
ct = CertificateTemplate(course=course)
ct.save()
cd = CertificateData(type=t[0], workspace=workspace, certificate_template=ct)
cd.save()
return Response({'message' : 'Os templates foram criados com sucesso'})
else:
super().create(request, *args, **kwargs)
@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)),
('cert_logo', request.data.get('cert_logo_clear', None)),
('site_logo', request.data.get('site_logo_clear', None)),
)
for cl in clear_logos:
if(cl[1]):
setattr(obj.certificate_template, cl[0], None)
setattr(obj, cl[0], None)
ct_serializer = CertificateTemplateImageSerializer(
obj.certificate_template, request.FILES)
if ct_serializer.is_valid():
ct_serializer.save()
else:
errors += ct_serializer.errors
cl = ('site_logo', request.data.get('site_logo_clear', None))
if(cl[1]):
setattr(obj, cl[0], None)
serializer = CertificateImageDataSerializer(obj, request.FILES)
serializer = CertificateTemplateImageSerializer(obj, request.FILES)
if serializer.is_valid():
serializer.save()
return Response(CertificateTemplateSerializer(obj).data,
status=status.HTTP_200_OK)
else:
errors += serializer.errors
if len(errors) > 0:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
else:
s = CertificateDataSerializer(obj)
return Response(s.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class CertificationProcessViewSet(viewsets.ModelViewSet):
model = CertificationProcess
......@@ -173,8 +123,8 @@ class CertificateTemplateImageViewSet(viewsets.ModelViewSet):
def post(self, request, **kwargs):
certificate_template = self.get_object()
serializer = CertificateTemplateImageSerializer(
certificate_template, request.FILES)
serializer = CertificateTemplateImageSerializer(certificate_template,
request.FILES)
if serializer.is_valid():
serializer.save()
......@@ -199,9 +149,9 @@ class CourseCertificationDetailView(DetailView):
raise Http404
if certificate:
context['cert_template'] = CertificateData.objects.get(
certificate_template__course=certificate.course_student.course,
type=certificate.type,
context['cert_template'] = CertificateTemplate.objects.get(
course=certificate.course_student.course,
document_type=certificate.document_type,
workspace=workspace
)
# Interpolate data into text string
......
......@@ -352,7 +352,7 @@ class CourseStudent(models.Model):
def can_emmit_receipt(self):
if not self.get_current_class().user_can_certificate and not self.course_finished:
return False
if self.get_current_class().user_can_certificate_even_without_progress and self.certificate.type == 'certificate':
if self.get_current_class().user_can_certificate_even_without_progress and self.certificate.document_type == 'certificate':
return True
return self.course_finished
......
......@@ -43,7 +43,7 @@ class UserInDetailSerializer(serializers.ModelSerializer):
'course_finished': x.can_emmit_receipt(),
'course_name': x.course.name,
# FIXME
# 'has_certificate': x.certificate.type == 'certificate',
# 'has_certificate': x.certificate.document_type == 'certificate',
'has_certificate': False,
'class_name': x.get_current_class().name
} for x in obj.coursestudent_set.all()]
......@@ -110,7 +110,7 @@ class UsersByClassSerializer(serializers.Serializer):
return obj.user.last_login
# def get_has_certificate(self, obj):
# return obj.certificate.type == 'certificate'
# return obj.certificate.document_type == 'certificate'
def get_percent_progress_by_lesson(self, obj):
return obj.percent_progress_by_lesson()
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment