|
| 1 | +"""Django Signal handlers.""" |
| 2 | + |
| 3 | +import logging |
| 4 | + |
| 5 | +from common.djangoapps.course_modes import api as modes_api |
| 6 | +from common.djangoapps.student.models import CourseEnrollment |
| 7 | +from openedx.core.djangoapps.content.course_overviews.models import CourseOverview |
| 8 | +from xmodule.data import CertificatesDisplayBehaviors |
| 9 | + |
| 10 | +from ol_openedx_events_handler.tasks.certificate_passing import ( |
| 11 | + create_certificate_for_passing_grade, |
| 12 | +) |
| 13 | +from ol_openedx_events_handler.utils import validate_certificate_webhook |
| 14 | + |
| 15 | +log = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +def _is_eligible_for_certificate(user, course_id): |
| 19 | + """ |
| 20 | + Determine whether certificate generation should be triggered. |
| 21 | + """ |
| 22 | + enrollment_mode, is_active = CourseEnrollment.enrollment_mode_for_user( |
| 23 | + user, course_id |
| 24 | + ) |
| 25 | + |
| 26 | + if not is_active: |
| 27 | + return False |
| 28 | + |
| 29 | + is_mode_eligible_for_cert = modes_api.is_eligible_for_certificate(enrollment_mode) |
| 30 | + course_overview = CourseOverview.get_from_id(course_id) |
| 31 | + certificate_display_behavior = course_overview.certificates_display_behavior |
| 32 | + |
| 33 | + return is_mode_eligible_for_cert and ( |
| 34 | + course_overview.self_paced |
| 35 | + or certificate_display_behavior == CertificatesDisplayBehaviors.EARLY_NO_INFO |
| 36 | + ) |
| 37 | + |
| 38 | + |
| 39 | +def listen_for_passing_grade(sender, user, course_id, **kwargs): # noqa: ARG001 |
| 40 | + """ |
| 41 | + Automatically create a certificate in the relevant MIT application when a user |
| 42 | + completes a course and gets a passing grade. |
| 43 | + """ |
| 44 | + |
| 45 | + if not _is_eligible_for_certificate(user, course_id): |
| 46 | + return |
| 47 | + |
| 48 | + if not validate_certificate_webhook(): |
| 49 | + return |
| 50 | + |
| 51 | + course_key = str(course_id) |
| 52 | + user_email = getattr(user, "email", None) |
| 53 | + if not user_email and getattr(user, "pii", None): |
| 54 | + user_email = getattr(user.pii, "email", None) |
| 55 | + if not user_email: |
| 56 | + log.error( |
| 57 | + "Cannot dispatch certificate webhook without user email for course '%s'.", |
| 58 | + course_key, |
| 59 | + ) |
| 60 | + return |
| 61 | + |
| 62 | + log.info( |
| 63 | + "User '%s' passed course '%s'. Dispatching certificate webhook.", |
| 64 | + user_email, |
| 65 | + course_key, |
| 66 | + ) |
| 67 | + create_certificate_for_passing_grade.delay( |
| 68 | + user_email=user_email, |
| 69 | + course_key=course_key, |
| 70 | + ) |
0 commit comments