models.py 36 KB
Newer Older
1
# -*- coding: utf-8 -*-
Victor Shnayder committed
2
"""
3 4
Certificates are created for a student and an offering of a course.

5
When a certificate is generated, a unique ID is generated so that
6
the certificate can be verified later. The ID is a UUID4, so that
John Jarvis committed
7
it can't be easily guessed and so that it is unique.
8

9 10 11 12
Certificates are generated in batches by a cron job, when a
certificate is available for download the GeneratedCertificate
table is updated with information that will be displayed
on the course overview page.
13

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

State diagram:

[deleted,error,unavailable] [error,downloadable]
            +                +             +
            |                |             |
            |                |             |
         add_cert       regen_cert     del_cert
            |                |             |
            v                v             v
       [generating]    [regenerating]  [deleting]
            +                +             +
            |                |             |
       certificate      certificate    certificate
         created       removed,created   deleted
            +----------------+-------------+------->[error]
            |                |             |
            |                |             |
            v                v             v
      [downloadable]   [downloadable]  [deleted]

35 36 37 38 39 40 41 42 43 44 45 46

Eligibility:

    Students are eligible for a certificate if they pass the course
    with the following exceptions:

       If the student has allow_certificate set to False in the student profile
       he will never be issued a certificate.

       If the user and course is present in the certificate whitelist table
       then the student will be issued a certificate regardless of his grade,
       unless he has allow_certificate set to False.
Victor Shnayder committed
47
"""
48
import json
49
import logging
50
import uuid
John Jarvis committed
51

52 53
import os
from django.conf import settings
54
from django.contrib.auth.models import User
55
from django.core.exceptions import ValidationError
56
from django.db import models, transaction
57
from django.db.models import Count
58
from django.dispatch import receiver
59
from django.utils.translation import ugettext_lazy as _
60
from django_extensions.db.fields import CreationDateTimeField
61
from model_utils import Choices
62
from model_utils.models import TimeStampedModel
63 64
from openedx.core.djangoapps.signals.signals import COURSE_CERT_AWARDED

65

66 67
from badges.events.course_complete import course_badge_check
from badges.events.course_meta import completion_check, course_group_check
68
from config_models.models import ConfigurationModel
69
from instructor_task.models import InstructorTask
70 71
from util.milestones_helpers import fulfill_course_milestone, is_prerequisite_courses_enabled
from xmodule_django.models import CourseKeyField, NoneToEmptyManager
72

73 74
LOGGER = logging.getLogger(__name__)

75

76
class CertificateStatuses(object):
77 78 79
    """
    Enum for certificate statuses
    """
80 81
    deleted = 'deleted'
    deleting = 'deleting'
John Jarvis committed
82
    downloadable = 'downloadable'
83 84 85 86 87
    error = 'error'
    generating = 'generating'
    notpassing = 'notpassing'
    restricted = 'restricted'
    unavailable = 'unavailable'
Bill DeRusha committed
88
    auditing = 'auditing'
89 90
    audit_passing = 'audit_passing'
    audit_notpassing = 'audit_notpassing'
91

92 93 94 95 96 97
    readable_statuses = {
        downloadable: "already received",
        notpassing: "didn't receive",
        error: "error states"
    }

98
    PASSED_STATUSES = (downloadable, generating)
99

100 101 102 103 104 105
    @classmethod
    def is_passing_status(cls, status):
        """
        Given the status of a certificate, return a boolean indicating whether
        the student passed the course.
        """
106
        return status in cls.PASSED_STATUSES
107

John Jarvis committed
108

109 110 111 112 113 114 115 116 117
class CertificateSocialNetworks(object):
    """
    Enum for certificate social networks
    """
    linkedin = 'LinkedIn'
    facebook = 'Facebook'
    twitter = 'Twitter'


118
class CertificateWhitelist(models.Model):
119 120 121 122 123 124 125
    """
    Tracks students who are whitelisted, all users
    in this table will always qualify for a certificate
    regardless of their grade unless they are on the
    embargoed country restriction list
    (allow_certificate set to False in userprofile).
    """
126 127
    class Meta(object):
        app_label = "certificates"
128 129 130

    objects = NoneToEmptyManager()

131
    user = models.ForeignKey(User)
132
    course_id = CourseKeyField(max_length=255, blank=True, default=None)
133
    whitelist = models.BooleanField(default=0)
134 135 136 137
    created = CreationDateTimeField(_('created'))
    notes = models.TextField(default=None, null=True)

    @classmethod
138
    def get_certificate_white_list(cls, course_id, student=None):
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
        """
        Return certificate white list for the given course as dict object,
        returned dictionary will have the following key-value pairs

        [{
            id:         'id (pk) of CertificateWhitelist item'
            user_id:    'User Id of the student'
            user_name:  'name of the student'
            user_email: 'email of the student'
            course_id:  'Course key of the course to whom certificate exception belongs'
            created:    'Creation date of the certificate exception'
            notes:      'Additional notes for the certificate exception'
        }, {...}, ...]

        """
        white_list = cls.objects.filter(course_id=course_id, whitelist=True)
155 156
        if student:
            white_list = white_list.filter(user=student)
157
        result = []
158
        generated_certificates = GeneratedCertificate.eligible_certificates.filter(
159 160 161 162 163 164 165 166
            course_id=course_id,
            user__in=[exception.user for exception in white_list],
            status=CertificateStatuses.downloadable
        )
        generated_certificates = {
            certificate['user']: certificate['created_date']
            for certificate in generated_certificates.values('user', 'created_date')
        }
167 168

        for item in white_list:
169
            certificate_generated = generated_certificates.get(item.user.id, '')
170 171 172 173 174 175
            result.append({
                'id': item.id,
                'user_id': item.user.id,
                'user_name': unicode(item.user.username),
                'user_email': unicode(item.user.email),
                'course_id': unicode(item.course_id),
176 177
                'created': item.created.strftime("%B %d, %Y"),
                'certificate_generated': certificate_generated and certificate_generated.strftime("%B %d, %Y"),
178 179 180
                'notes': unicode(item.notes or ''),
            })
        return result
181

Calen Pennington committed
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
class EligibleCertificateManager(models.Manager):
    """
    A manager for `GeneratedCertificate` models that automatically
    filters out ineligible certs.

    The idea is to prevent accidentally granting certificates to
    students who have not enrolled in a cert-granting mode. The
    alternative is to filter by eligible_for_certificate=True every
    time certs are searched for, which is verbose and likely to be
    forgotten.
    """

    def get_queryset(self):
        """
        Return a queryset for `GeneratedCertificate` models, filtering out
        ineligible certificates.
        """
        return super(EligibleCertificateManager, self).get_queryset().exclude(
            status__in=(CertificateStatuses.audit_passing, CertificateStatuses.audit_notpassing)
        )


205
class GeneratedCertificate(models.Model):
206 207 208
    """
    Base model for generated certificates
    """
209 210 211
    # Import here instead of top of file since this module gets imported before
    # the course_modes app is loaded, resulting in a Django deprecation warning.
    from course_modes.models import CourseMode
212

213 214 215 216 217 218 219 220 221
    # Only returns eligible certificates. This should be used in
    # preference to the default `objects` manager in most cases.
    eligible_certificates = EligibleCertificateManager()

    # Normal object manager, which should only be used when ineligible
    # certificates (i.e. new audit certs) should be included in the
    # results. Django requires us to explicitly declare this.
    objects = models.Manager()

222
    MODES = Choices('verified', 'honor', 'audit', 'professional', 'no-id-professional')
223

224 225
    VERIFIED_CERTS_MODES = [CourseMode.VERIFIED, CourseMode.CREDIT_MODE]

226
    user = models.ForeignKey(User)
227
    course_id = CourseKeyField(max_length=255, blank=True, default=None)
228
    verify_uuid = models.CharField(max_length=32, blank=True, default='', db_index=True)
229
    download_uuid = models.CharField(max_length=32, blank=True, default='')
230
    download_url = models.CharField(max_length=128, blank=True, default='')
231 232 233 234
    grade = models.CharField(max_length=5, blank=True, default='')
    key = models.CharField(max_length=32, blank=True, default='')
    distinction = models.BooleanField(default=False)
    status = models.CharField(max_length=32, default='unavailable')
235
    mode = models.CharField(max_length=32, choices=MODES, default=MODES.honor)
236
    name = models.CharField(blank=True, max_length=255)
237 238
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)
John Jarvis committed
239
    error_reason = models.CharField(max_length=512, blank=True, default='')
240

241
    class Meta(object):
John Jarvis committed
242
        unique_together = (('user', 'course_id'),)
243
        app_label = "certificates"
John Jarvis committed
244

245 246 247 248 249 250 251 252 253 254 255 256
    @classmethod
    def certificate_for_student(cls, student, course_id):
        """
        This returns the certificate for a student for a particular course
        or None if no such certificate exits.
        """
        try:
            return cls.objects.get(user=student, course_id=course_id)
        except cls.DoesNotExist:
            pass

        return None
257

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    @classmethod
    def get_unique_statuses(cls, course_key=None, flat=False):
        """
        1 - Return unique statuses as a list of dictionaries containing the following key value pairs
            [
            {'status': 'status value from db', 'count': 'occurrence count of the status'},
            {...},
            ..., ]

        2 - if flat is 'True' then return unique statuses as a list
        3 - if course_key is given then return unique statuses associated with the given course

        :param course_key: Course Key identifier
        :param flat: boolean showing whether to return statuses as a list of values or a list of dictionaries.
        """
        query = cls.objects

        if course_key:
            query = query.filter(course_id=course_key)

        if flat:
            return query.values_list('status', flat=True).distinct()
        else:
            return query.values('status').annotate(count=Count('status'))

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
    def invalidate(self):
        """
        Invalidate Generated Certificate by  marking it 'unavailable'.

        Following is the list of fields with their defaults
            1 - verify_uuid = '',
            2 - download_uuid = '',
            3 - download_url = '',
            4 - grade = ''
            5 - status = 'unavailable'
        """
        self.verify_uuid = ''
        self.download_uuid = ''
        self.download_url = ''
        self.grade = ''
        self.status = CertificateStatuses.unavailable

        self.save()

302 303 304 305 306 307
    def is_valid(self):
        """
        Return True if certificate is valid else return False.
        """
        return self.status == CertificateStatuses.downloadable

308 309 310
    def save(self, *args, **kwargs):
        """
        After the base save() method finishes, fire the COURSE_CERT_AWARDED
311
        signal iff we are saving a record of a learner passing the course.
312 313
        """
        super(GeneratedCertificate, self).save(*args, **kwargs)
314
        if CertificateStatuses.is_passing_status(self.status):
315 316 317 318 319 320 321 322
            COURSE_CERT_AWARDED.send_robust(
                sender=self.__class__,
                user=self.user,
                course_key=self.course_id,
                mode=self.mode,
                status=self.status,
            )

323

324 325 326 327 328 329 330 331 332 333
class CertificateGenerationHistory(TimeStampedModel):
    """
    Model for storing Certificate Generation History.
    """

    course_id = CourseKeyField(max_length=255)
    generated_by = models.ForeignKey(User)
    instructor_task = models.ForeignKey(InstructorTask)
    is_regeneration = models.BooleanField(default=False)

334 335 336 337
    def get_task_name(self):
        """
        Return "regenerated" if record corresponds to Certificate Regeneration task, otherwise returns 'generated'
        """
Saleem Latif committed
338 339
        # Translators: This is a past-tense verb that is used for task action messages.
        return _("regenerated") if self.is_regeneration else _("generated")
340 341 342 343 344 345 346 347 348 349 350 351

    def get_certificate_generation_candidates(self):
        """
        Return the candidates for certificate generation task. It could either be students or certificate statuses
        depending upon the nature of certificate generation task. Returned value could be one of the following,

        1. "All learners" Certificate Generation task was initiated for all learners of the given course.
        2. Comma separated list of certificate statuses, This usually happens when instructor regenerates certificates.
        3. "for exceptions", This is the case when instructor generates certificates for white-listed
            students.
        """
        task_input = self.instructor_task.task_input
352
        if not task_input.strip():
353
            # if task input is empty, it means certificates were generated for all learners
Saleem Latif committed
354 355
            # Translators: This string represents task was executed for all learners.
            return _("All learners")
356

357 358
        task_input_json = json.loads(task_input)

359 360 361
        # get statuses_to_regenerate from task_input convert statuses to human readable strings and return
        statuses = task_input_json.get('statuses_to_regenerate', None)
        if statuses:
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
            readable_statuses = [
                CertificateStatuses.readable_statuses.get(status) for status in statuses
                if CertificateStatuses.readable_statuses.get(status) is not None
            ]
            return ", ".join(readable_statuses)

        # If "student_set" is present in task_input, then this task only
        # generates certificates for white listed students. Note that
        # this key used to be "students", so we include that in this conditional
        # for backwards compatibility.
        if 'student_set' in task_input_json or 'students' in task_input_json:
            # Translators: This string represents task was executed for students having exceptions.
            return _("For exceptions")
        else:
            return _("All learners")
377

378 379 380 381 382 383 384 385
    class Meta(object):
        app_label = "certificates"

    def __unicode__(self):
        return u"certificates %s by %s on %s for %s" % \
               ("regenerated" if self.is_regeneration else "generated", self.generated_by, self.created, self.course_id)


386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
class CertificateInvalidation(TimeStampedModel):
    """
    Model for storing Certificate Invalidation.
    """
    generated_certificate = models.ForeignKey(GeneratedCertificate)
    invalidated_by = models.ForeignKey(User)
    notes = models.TextField(default=None, null=True)
    active = models.BooleanField(default=True)

    class Meta(object):
        app_label = "certificates"

    def __unicode__(self):
        return u"Certificate %s, invalidated by %s on %s." % \
               (self.generated_certificate, self.invalidated_by, self.created)

    def deactivate(self):
        """
        Deactivate certificate invalidation by setting active to False.
        """
        self.active = False
        self.save()

    @classmethod
    def get_certificate_invalidations(cls, course_key, student=None):
        """
        Return certificate invalidations filtered based on the provided course and student (if provided),

        Returned value is JSON serializable list of dicts, dict element would have the following key-value pairs.
         1. id: certificate invalidation id (primary key)
         2. user: username of the student to whom certificate belongs
         3. invalidated_by: user id of the instructor/support user who invalidated the certificate
         4. created: string containing date of invalidation in the following format "December 29, 2015"
         5. notes: string containing notes regarding certificate invalidation.
        """
        certificate_invalidations = cls.objects.filter(
            generated_certificate__course_id=course_key,
            active=True,
        )
        if student:
            certificate_invalidations = certificate_invalidations.filter(generated_certificate__user=student)
        data = []
        for certificate_invalidation in certificate_invalidations:
            data.append({
                'id': certificate_invalidation.id,
                'user': certificate_invalidation.generated_certificate.user.username,
                'invalidated_by': certificate_invalidation.invalidated_by.username,
                'created': certificate_invalidation.created.strftime("%B %d, %Y"),
                'notes': certificate_invalidation.notes,
            })
        return data


439 440
@receiver(COURSE_CERT_AWARDED, sender=GeneratedCertificate)
def handle_course_cert_awarded(sender, user, course_key, **kwargs):  # pylint: disable=unused-argument
441
    """
442
    Mark a milestone entry if user has passed the course.
443
    """
444 445
    if is_prerequisite_courses_enabled():
        fulfill_course_milestone(course_key, user)
446 447


448
def certificate_status_for_student(student, course_id):
449
    '''
450 451
    This returns a dictionary with a key for status, and other information.
    The status is one of the following:
452

453 454 455
    unavailable  - No entry for this student--if they are actually in
                   the course, they probably have not been graded for
                   certificate generation yet.
456 457 458
    generating   - A request has been made to generate a certificate,
                   but it has not been generated yet.
    regenerating - A request has been made to regenerate a certificate,
John Jarvis committed
459
                   but it has not been generated yet.
460
    deleting     - A request has been made to delete a certificate.
John Jarvis committed
461

462 463
    deleted      - The certificate has been deleted.
    downloadable - The certificate is available for download.
464
    notpassing   - The student was graded but is not passing
465
    restricted   - The student is on the restricted embargo list and
466 467 468
                   should not be issued a certificate. This will
                   be set if allow_certificate is set to False in
                   the userprofile table
469 470 471

    If the status is "downloadable", the dictionary also contains
    "download_url".
472

473
    If the student has been graded, the dictionary also contains their
474
    grade for the course with the key "grade".
475
    '''
476 477 478
    # Import here instead of top of file since this module gets imported before
    # the course_modes app is loaded, resulting in a Django deprecation warning.
    from course_modes.models import CourseMode
479

480
    try:
481
        generated_certificate = GeneratedCertificate.objects.get(  # pylint: disable=no-member
482
            user=student, course_id=course_id)
483 484
        cert_status = {
            'status': generated_certificate.status,
485 486
            'mode': generated_certificate.mode,
            'uuid': generated_certificate.verify_uuid,
487
        }
488
        if generated_certificate.grade:
489
            cert_status['grade'] = generated_certificate.grade
Bill DeRusha committed
490 491 492 493 494 495 496 497 498

        if generated_certificate.mode == 'audit':
            course_mode_slugs = [mode.slug for mode in CourseMode.modes_for_course(course_id)]
            # Short term fix to make sure old audit users with certs still see their certs
            # only do this if there if no honor mode
            if 'honor' not in course_mode_slugs:
                cert_status['status'] = CertificateStatuses.auditing
                return cert_status

499
        if generated_certificate.status == CertificateStatuses.downloadable:
500
            cert_status['download_url'] = generated_certificate.download_url
501

502
        return cert_status
Bill DeRusha committed
503

504 505
    except GeneratedCertificate.DoesNotExist:
        pass
506
    return {'status': CertificateStatuses.unavailable, 'mode': GeneratedCertificate.MODES.honor, 'uuid': None}
507 508


509 510 511 512 513 514 515 516 517
def certificate_info_for_user(user, course_id, grade, user_is_whitelisted=None):
    """
    Returns the certificate info for a user for grade report.
    """
    if user_is_whitelisted is None:
        user_is_whitelisted = CertificateWhitelist.objects.filter(
            user=user, course_id=course_id, whitelist=True
        ).exists()

518 519 520 521 522 523 524 525 526 527 528 529
    certificate_is_delivered = 'N'
    certificate_type = 'N/A'
    eligible_for_certificate = 'Y' if (user_is_whitelisted or grade is not None) and user.profile.allow_certificate \
        else 'N'

    certificate_status = certificate_status_for_student(user, course_id)
    certificate_generated = certificate_status['status'] == CertificateStatuses.downloadable
    if certificate_generated:
        certificate_is_delivered = 'Y'
        certificate_type = certificate_status['mode']

    return [eligible_for_certificate, certificate_is_delivered, certificate_type]
530 531


532 533 534 535 536 537 538 539 540 541 542 543 544
class ExampleCertificateSet(TimeStampedModel):
    """A set of example certificates.

    Example certificates are used to verify that certificate
    generation is working for a particular course.

    A particular course may have several kinds of certificates
    (e.g. honor and verified), in which case we generate
    multiple example certificates for the course.

    """
    course_key = CourseKeyField(max_length=255, db_index=True)

545
    class Meta(object):
546
        get_latest_by = 'created'
547
        app_label = "certificates"
548 549

    @classmethod
550
    @transaction.atomic
551 552 553 554 555 556 557 558 559 560
    def create_example_set(cls, course_key):
        """Create a set of example certificates for a course.

        Arguments:
            course_key (CourseKey)

        Returns:
            ExampleCertificateSet

        """
561 562 563
        # Import here instead of top of file since this module gets imported before
        # the course_modes app is loaded, resulting in a Django deprecation warning.
        from course_modes.models import CourseMode
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
        cert_set = cls.objects.create(course_key=course_key)

        ExampleCertificate.objects.bulk_create([
            ExampleCertificate(
                example_cert_set=cert_set,
                description=mode.slug,
                template=cls._template_for_mode(mode.slug, course_key)
            )
            for mode in CourseMode.modes_for_course(course_key)
        ])

        return cert_set

    @classmethod
    def latest_status(cls, course_key):
        """Summarize the latest status of example certificates for a course.

        Arguments:
            course_key (CourseKey)

        Returns:
            list: List of status dictionaries.  If no example certificates
                have been started yet, returns None.

        """
        try:
            latest = cls.objects.filter(course_key=course_key).latest()
        except cls.DoesNotExist:
            return None

        queryset = ExampleCertificate.objects.filter(example_cert_set=latest).order_by('-created')
        return [cert.status_dict for cert in queryset]

    def __iter__(self):
        """Iterate through example certificates in the set.

        Yields:
            ExampleCertificate

        """
        queryset = (ExampleCertificate.objects).select_related('example_cert_set').filter(example_cert_set=self)
        for cert in queryset:
            yield cert

    @staticmethod
    def _template_for_mode(mode_slug, course_key):
        """Calculate the template PDF based on the course mode. """
        return (
            u"certificate-template-{key.org}-{key.course}-verified.pdf".format(key=course_key)
            if mode_slug == 'verified'
            else u"certificate-template-{key.org}-{key.course}.pdf".format(key=course_key)
        )


def _make_uuid():
    """Return a 32-character UUID. """
    return uuid.uuid4().hex


class ExampleCertificate(TimeStampedModel):
    """Example certificate.

    Example certificates are used to verify that certificate
    generation is working for a particular course.

    An example certificate is similar to an ordinary certificate,
    except that:

    1) Example certificates are not associated with a particular user,
        and are never displayed to students.

    2) We store the "inputs" for generating the example certificate
        to make it easier to debug when certificate generation fails.

    3) We use dummy values.

    """
641 642 643
    class Meta(object):
        app_label = "certificates"

644 645 646 647 648 649 650 651 652 653 654 655
    # Statuses
    STATUS_STARTED = 'started'
    STATUS_SUCCESS = 'success'
    STATUS_ERROR = 'error'

    # Dummy full name for the generated certificate
    EXAMPLE_FULL_NAME = u'John Doë'

    example_cert_set = models.ForeignKey(ExampleCertificateSet)

    description = models.CharField(
        max_length=255,
656
        help_text=_(
657 658 659 660 661 662 663 664 665 666 667 668 669 670
            u"A human-readable description of the example certificate.  "
            u"For example, 'verified' or 'honor' to differentiate between "
            u"two types of certificates."
        )
    )

    # Inputs to certificate generation
    # We store this for auditing purposes if certificate
    # generation fails.
    uuid = models.CharField(
        max_length=255,
        default=_make_uuid,
        db_index=True,
        unique=True,
671
        help_text=_(
672 673 674 675 676 677 678 679 680 681
            u"A unique identifier for the example certificate.  "
            u"This is used when we receive a response from the queue "
            u"to determine which example certificate was processed."
        )
    )

    access_key = models.CharField(
        max_length=255,
        default=_make_uuid,
        db_index=True,
682
        help_text=_(
683 684 685 686 687 688 689 690 691 692
            u"An access key for the example certificate.  "
            u"This is used when we receive a response from the queue "
            u"to validate that the sender is the same entity we asked "
            u"to generate the certificate."
        )
    )

    full_name = models.CharField(
        max_length=255,
        default=EXAMPLE_FULL_NAME,
693
        help_text=_(u"The full name that will appear on the certificate.")
694 695 696 697
    )

    template = models.CharField(
        max_length=255,
698
        help_text=_(u"The template file to use when generating the certificate.")
699 700 701 702 703 704 705 706 707 708 709
    )

    # Outputs from certificate generation
    status = models.CharField(
        max_length=255,
        default=STATUS_STARTED,
        choices=(
            (STATUS_STARTED, 'Started'),
            (STATUS_SUCCESS, 'Success'),
            (STATUS_ERROR, 'Error')
        ),
710
        help_text=_(u"The status of the example certificate.")
711 712 713 714 715
    )

    error_reason = models.TextField(
        null=True,
        default=None,
716
        help_text=_(u"The reason an error occurred during certificate generation.")
717 718 719 720 721 722
    )

    download_url = models.CharField(
        max_length=255,
        null=True,
        default=None,
723
        help_text=_(u"The download URL for the generated certificate.")
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
    )

    def update_status(self, status, error_reason=None, download_url=None):
        """Update the status of the example certificate.

        This will usually be called either:
        1) When an error occurs adding the certificate to the queue.
        2) When we receieve a response from the queue (either error or success).

        If an error occurs, we store the error message;
        if certificate generation is successful, we store the URL
        for the generated certificate.

        Arguments:
            status (str): Either `STATUS_SUCCESS` or `STATUS_ERROR`

        Keyword Arguments:
            error_reason (unicode): A description of the error that occurred.
            download_url (unicode): The URL for the generated certificate.

        Raises:
            ValueError: The status is not a valid value.

        """
        if status not in [self.STATUS_SUCCESS, self.STATUS_ERROR]:
            msg = u"Invalid status: must be either '{success}' or '{error}'.".format(
                success=self.STATUS_SUCCESS,
                error=self.STATUS_ERROR
            )
            raise ValueError(msg)

        self.status = status

        if status == self.STATUS_ERROR and error_reason:
            self.error_reason = error_reason

        if status == self.STATUS_SUCCESS and download_url:
            self.download_url = download_url

        self.save()

    @property
    def status_dict(self):
        """Summarize the status of the example certificate.

        Returns:
            dict

        """
        result = {
            'description': self.description,
            'status': self.status,
        }

        if self.error_reason:
            result['error_reason'] = self.error_reason

        if self.download_url:
            result['download_url'] = self.download_url

        return result

    @property
    def course_key(self):
        """The course key associated with the example certificate. """
        return self.example_cert_set.course_key


class CertificateGenerationCourseSetting(TimeStampedModel):
    """Enable or disable certificate generation for a particular course.

    This controls whether students are allowed to "self-generate"
    certificates for a course.  It does NOT prevent us from
    batch-generating certificates for a course using management
    commands.

    In general, we should only enable self-generated certificates
    for a course once we successfully generate example certificates
    for the course.  This is enforced in the UI layer, but
    not in the data layer.

    """
    course_key = CourseKeyField(max_length=255, db_index=True)
    enabled = models.BooleanField(default=False)

809
    class Meta(object):
810
        get_latest_by = 'created'
811
        app_label = "certificates"
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845

    @classmethod
    def is_enabled_for_course(cls, course_key):
        """Check whether self-generated certificates are enabled for a course.

        Arguments:
            course_key (CourseKey): The identifier for the course.

        Returns:
            boolean

        """
        try:
            latest = cls.objects.filter(course_key=course_key).latest()
        except cls.DoesNotExist:
            return False
        else:
            return latest.enabled

    @classmethod
    def set_enabled_for_course(cls, course_key, is_enabled):
        """Enable or disable self-generated certificates for a course.

        Arguments:
            course_key (CourseKey): The identifier for the course.
            is_enabled (boolean): Whether to enable or disable self-generated certificates.

        """
        CertificateGenerationCourseSetting.objects.create(
            course_key=course_key,
            enabled=is_enabled
        )


846
class CertificateGenerationConfiguration(ConfigurationModel):
847 848 849 850 851 852 853 854 855 856 857
    """Configure certificate generation.

    Enable or disable the self-generated certificates feature.
    When this flag is disabled, the "generate certificate" button
    will be hidden on the progress page.

    When the feature is enabled, the "generate certificate" button
    will appear for courses that have enabled self-generated
    certificates.

    """
858 859
    class Meta(ConfigurationModel.Meta):
        app_label = "certificates"
860 861 862 863 864 865 866 867 868 869 870


class CertificateHtmlViewConfiguration(ConfigurationModel):
    """
    Static values for certificate HTML view context parameters.
    Default values will be applied across all certificate types (course modes)
    Matching 'mode' overrides will be used instead of defaults, where applicable
    Example configuration :
        {
            "default": {
                "url": "http://www.edx.org",
871
                "logo_src": "http://www.edx.org/static/images/logo.png"
872 873
            },
            "honor": {
874
                "logo_src": "http://www.edx.org/static/images/honor-logo.png"
875 876 877
            }
        }
    """
878 879 880
    class Meta(ConfigurationModel.Meta):
        app_label = "certificates"

881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
    configuration = models.TextField(
        help_text="Certificate HTML View Parameters (JSON)"
    )

    def clean(self):
        """
        Ensures configuration field contains valid JSON.
        """
        try:
            json.loads(self.configuration)
        except ValueError:
            raise ValidationError('Must be valid JSON string.')

    @classmethod
    def get_config(cls):
        """
        Retrieves the configuration field value from the database
        """
        instance = cls.current()
        json_data = json.loads(instance.configuration) if instance.enabled else {}
        return json_data
902 903


904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
class CertificateTemplate(TimeStampedModel):
    """A set of custom web certificate templates.

    Web certificate templates are Django web templates
    to replace PDF certificate.

    A particular course may have several kinds of certificate templates
    (e.g. honor and verified).

    """
    name = models.CharField(
        max_length=255,
        help_text=_(u'Name of template.'),
    )
    description = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text=_(u'Description and/or admin notes.'),
    )
    template = models.TextField(
        help_text=_(u'Django template HTML.'),
    )
    organization_id = models.IntegerField(
        null=True,
        blank=True,
        db_index=True,
        help_text=_(u'Organization of template.'),
    )
    course_key = CourseKeyField(
        max_length=255,
        null=True,
        blank=True,
        db_index=True,
    )
    mode = models.CharField(
        max_length=125,
        choices=GeneratedCertificate.MODES,
        default=GeneratedCertificate.MODES.honor,
        null=True,
        blank=True,
        help_text=_(u'The course mode for this template.'),
    )
    is_active = models.BooleanField(
        help_text=_(u'On/Off switch.'),
        default=False,
    )

    def __unicode__(self):
        return u'%s' % (self.name, )

955
    class Meta(object):
956 957
        get_latest_by = 'created'
        unique_together = (('organization_id', 'course_key', 'mode'),)
958
        app_label = "certificates"
959 960


asadiqbal committed
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
def template_assets_path(instance, filename):
    """
    Delete the file if it already exist and returns the certificate template asset file path.

    :param instance: CertificateTemplateAsset object
    :param filename: file to upload
    :return path: path of asset file e.g. certificate_template_assets/1/filename
    """
    name = os.path.join('certificate_template_assets', str(instance.id), filename)
    fullname = os.path.join(settings.MEDIA_ROOT, name)
    if os.path.exists(fullname):
        os.remove(fullname)
    return name


976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
class CertificateTemplateAsset(TimeStampedModel):
    """A set of assets to be used in custom web certificate templates.

    This model stores assets used in custom web certificate templates
    such as image, css files.

    """
    description = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text=_(u'Description of the asset.'),
    )
    asset = models.FileField(
        max_length=255,
asadiqbal committed
991
        upload_to=template_assets_path,
992 993
        help_text=_(u'Asset file. It could be an image or css file.'),
    )
994 995 996 997 998 999
    asset_slug = models.SlugField(
        max_length=255,
        unique=True,
        null=True,
        help_text=_(u'Asset\'s unique slug. We can reference the asset in templates using this value.'),
    )
1000

asadiqbal committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    def save(self, *args, **kwargs):
        """save the certificate template asset """
        if self.pk is None:
            asset_image = self.asset
            self.asset = None
            super(CertificateTemplateAsset, self).save(*args, **kwargs)
            self.asset = asset_image

        super(CertificateTemplateAsset, self).save(*args, **kwargs)

1011
    def __unicode__(self):
1012
        return u'%s' % (self.asset.url, )
1013

1014
    class Meta(object):
1015
        get_latest_by = 'created'
1016
        app_label = "certificates"
1017 1018


1019 1020 1021
@receiver(COURSE_CERT_AWARDED, sender=GeneratedCertificate)
# pylint: disable=unused-argument
def create_course_badge(sender, user, course_key, status, **kwargs):
1022
    """
1023
    Standard signal hook to create course badges when a certificate has been generated.
1024
    """
1025 1026 1027 1028 1029 1030 1031 1032 1033
    course_badge_check(user, course_key)


@receiver(COURSE_CERT_AWARDED, sender=GeneratedCertificate)
def create_completion_badge(sender, user, course_key, status, **kwargs):  # pylint: disable=unused-argument
    """
    Standard signal hook to create 'x courses completed' badges when a certificate has been generated.
    """
    completion_check(user)
1034 1035


1036
@receiver(COURSE_CERT_AWARDED, sender=GeneratedCertificate)
1037
def create_course_group_badge(sender, user, course_key, status, **kwargs):  # pylint: disable=unused-argument
1038
    """
1039
    Standard signal hook to create badges when a user has completed a prespecified set of courses.
1040
    """
1041
    course_group_check(user, course_key)