/
course_enrollment.py
1780 lines (1483 loc) · 71.5 KB
/
course_enrollment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
110
111
112
113
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
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
809
810
811
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Models for course enrollment"""
import hashlib # lint-amnesty, pylint: disable=wrong-import-order
import logging # lint-amnesty, pylint: disable=wrong-import-order
import uuid # lint-amnesty, pylint: disable=wrong-import-order
from collections import defaultdict, namedtuple # lint-amnesty, pylint: disable=wrong-import-order
from datetime import date, datetime, timedelta # lint-amnesty, pylint: disable=wrong-import-order
from urllib.parse import urljoin
from config_models.models import ConfigurationModel
from django.conf import settings
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.cache import cache
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.core.validators import FileExtensionValidator
from django.db import models
from django.db.models import Count, Index, Q
from django.dispatch import receiver
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from edx_django_utils.cache import RequestCache, TieredCache, get_cache_key
from eventtracking import tracker
from model_utils.models import TimeStampedModel
from opaque_keys.edx.django.models import CourseKeyField
from opaque_keys.edx.keys import CourseKey
from openedx_events.learning.data import CourseData, CourseEnrollmentData, UserData, UserPersonalData
from openedx_events.learning.signals import (
COURSE_ENROLLMENT_CHANGED,
COURSE_ENROLLMENT_CREATED,
COURSE_UNENROLLMENT_COMPLETED,
)
from openedx_filters.learning.filters import CourseEnrollmentStarted, CourseUnenrollmentStarted
from pytz import UTC
from requests.exceptions import HTTPError, RequestException
from simple_history.models import HistoricalRecords
from common.djangoapps.course_modes.models import CourseMode, get_cosmetic_verified_display_price
from common.djangoapps.student.signals import ENROLL_STATUS_CHANGE, ENROLLMENT_TRACK_UPDATED, UNENROLL_DONE
from common.djangoapps.track import contexts, segment
from common.djangoapps.util.query import use_read_replica_if_available
from lms.djangoapps.certificates.data import CertificateStatuses
from lms.djangoapps.courseware.models import (
CourseDynamicUpgradeDeadlineConfiguration,
DynamicUpgradeDeadlineConfiguration,
OrgDynamicUpgradeDeadlineConfiguration,
)
from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.enrollments.api import (
_default_course_mode,
get_enrollment_attributes,
set_enrollment_attributes,
)
from openedx.core.djangolib.model_mixins import DeletableByUserValue
log = logging.getLogger(__name__)
AUDIT_LOG = logging.getLogger("audit")
# ENROLL signal used for free enrollment only
class EnrollStatusChange:
"""
Possible event types for ENROLL_STATUS_CHANGE signal
"""
# enroll for a course
enroll = 'enroll'
# unenroll for a course
unenroll = 'unenroll'
# add an upgrade to cart
upgrade_start = 'upgrade_start'
# complete an upgrade purchase
upgrade_complete = 'upgrade_complete'
# add a paid course to the cart
paid_start = 'paid_start'
# complete a paid course purchase
paid_complete = 'paid_complete'
UNENROLLED_TO_ALLOWEDTOENROLL = 'from unenrolled to allowed to enroll'
ALLOWEDTOENROLL_TO_ENROLLED = 'from allowed to enroll to enrolled'
ENROLLED_TO_ENROLLED = 'from enrolled to enrolled'
ENROLLED_TO_UNENROLLED = 'from enrolled to unenrolled'
UNENROLLED_TO_ENROLLED = 'from unenrolled to enrolled'
ALLOWEDTOENROLL_TO_UNENROLLED = 'from allowed to enroll to enrolled'
UNENROLLED_TO_UNENROLLED = 'from unenrolled to unenrolled'
DEFAULT_TRANSITION_STATE = 'N/A'
SCORE_RECALCULATION_DELAY_ON_ENROLLMENT_UPDATE = 30
TRANSITION_STATES = (
(UNENROLLED_TO_ALLOWEDTOENROLL, UNENROLLED_TO_ALLOWEDTOENROLL),
(ALLOWEDTOENROLL_TO_ENROLLED, ALLOWEDTOENROLL_TO_ENROLLED),
(ENROLLED_TO_ENROLLED, ENROLLED_TO_ENROLLED),
(ENROLLED_TO_UNENROLLED, ENROLLED_TO_UNENROLLED),
(UNENROLLED_TO_ENROLLED, UNENROLLED_TO_ENROLLED),
(ALLOWEDTOENROLL_TO_UNENROLLED, ALLOWEDTOENROLL_TO_UNENROLLED),
(UNENROLLED_TO_UNENROLLED, UNENROLLED_TO_UNENROLLED),
(DEFAULT_TRANSITION_STATE, DEFAULT_TRANSITION_STATE)
)
EVENT_NAME_ENROLLMENT_ACTIVATED = 'edx.course.enrollment.activated'
EVENT_NAME_ENROLLMENT_DEACTIVATED = 'edx.course.enrollment.deactivated'
EVENT_NAME_ENROLLMENT_MODE_CHANGED = 'edx.course.enrollment.mode_changed'
class CourseEnrollmentException(Exception):
pass
class NonExistentCourseError(CourseEnrollmentException):
pass
class EnrollmentClosedError(CourseEnrollmentException):
pass
class CourseFullError(CourseEnrollmentException):
pass
class AlreadyEnrolledError(CourseEnrollmentException):
pass
class EnrollmentNotAllowed(CourseEnrollmentException):
pass
class UnenrollmentNotAllowed(CourseEnrollmentException):
pass
class CourseEnrollmentManager(models.Manager):
"""
Custom manager for CourseEnrollment with Table-level filter methods.
"""
def is_small_course(self, course_id):
"""
Returns false if the number of enrollments are one greater than 'max_enrollments' else true
'course_id' is the course_id to return enrollments
"""
max_enrollments = settings.FEATURES.get("MAX_ENROLLMENT_INSTR_BUTTONS")
enrollment_number = super().get_queryset().filter(
course_id=course_id,
is_active=1
)[:max_enrollments + 1].count()
return enrollment_number <= max_enrollments
def num_enrolled_in_exclude_admins(self, course_id):
"""
Returns the count of active enrollments in a course excluding instructors, staff and CCX coaches.
Arguments:
course_id (CourseLocator): course_id to return enrollments (count).
Returns:
int: Count of enrollments excluding staff, instructors and CCX coaches.
"""
# To avoid circular imports.
from common.djangoapps.student.roles import CourseCcxCoachRole, CourseInstructorRole, CourseStaffRole
course_locator = course_id
if getattr(course_id, 'ccx', None):
course_locator = course_id.to_course_locator()
staff = CourseStaffRole(course_locator).users_with_role()
admins = CourseInstructorRole(course_locator).users_with_role()
coaches = CourseCcxCoachRole(course_locator).users_with_role()
return super().get_queryset().filter(
course_id=course_id,
is_active=1,
).exclude(user__in=staff).exclude(user__in=admins).exclude(user__in=coaches).count()
def is_course_full(self, course):
"""
Returns a boolean value regarding whether a course has already reached it's max enrollment
capacity
"""
is_course_full = False
if course.max_student_enrollments_allowed is not None:
is_course_full = self.num_enrolled_in_exclude_admins(course.id) >= course.max_student_enrollments_allowed
return is_course_full
def users_enrolled_in(self, course_id, include_inactive=False, verified_only=False):
"""
Return a queryset of User for every user enrolled in the course.
Arguments:
course_id (CourseLocator): course_id to return enrollees for.
include_inactive (boolean): is a boolean when True, returns both active and inactive enrollees
verified_only (boolean): is a boolean when True, returns only verified enrollees.
Returns:
Returns a User queryset.
"""
filter_kwargs = {
'courseenrollment__course_id': course_id,
}
if not include_inactive:
filter_kwargs['courseenrollment__is_active'] = True
if verified_only:
filter_kwargs['courseenrollment__mode'] = CourseMode.VERIFIED
return User.objects.filter(**filter_kwargs)
def enrollment_counts(self, course_id):
"""
Returns a dictionary that stores the total enrollment count for a course, as well as the
enrollment count for each individual mode.
"""
# Unfortunately, Django's "group by"-style queries look super-awkward
query = use_read_replica_if_available(
super().get_queryset().filter(course_id=course_id, is_active=True).values(
'mode').order_by().annotate(Count('mode')))
total = 0
enroll_dict = defaultdict(int)
for item in query:
enroll_dict[item['mode']] = item['mode__count']
total += item['mode__count']
enroll_dict['total'] = total
return enroll_dict
def enrolled_and_dropped_out_users(self, course_id):
"""Return a queryset of Users in the course."""
return User.objects.filter(
courseenrollment__course_id=course_id
)
# Named tuple for fields pertaining to the state of
# CourseEnrollment for a user in a course. This type
# is used to cache the state in the request cache.
CourseEnrollmentState = namedtuple('CourseEnrollmentState', 'mode, is_active')
class CourseEnrollment(models.Model):
"""
Represents a Student's Enrollment record for a single Course. You should
generally not manipulate CourseEnrollment objects directly, but use the
classmethods provided to enroll, unenroll, or check on the enrollment status
of a given student.
We're starting to consolidate course enrollment logic in this class, but
more should be brought in (such as checking against CourseEnrollmentAllowed,
checking course dates, user permissions, etc.) This logic is currently
scattered across our views.
.. no_pii:
"""
MODEL_TAGS = ['course', 'is_active', 'mode']
user = models.ForeignKey(User, on_delete=models.CASCADE)
course = models.ForeignKey(
CourseOverview,
db_constraint=False,
on_delete=models.DO_NOTHING,
)
@property
def course_price(self):
return get_cosmetic_verified_display_price(self.course)
created = models.DateTimeField(auto_now_add=True, null=True, db_index=True)
# If is_active is False, then the student is not considered to be enrolled
# in the course (is_enrolled() will return False)
is_active = models.BooleanField(default=True)
# Represents the modes that are possible. We'll update this later with a
# list of possible values.
mode = models.CharField(default=CourseMode.get_default_mode_slug, max_length=100)
# An audit row will be created for every change to a CourseEnrollment. This
# will create a new model behind the scenes - HistoricalCourseEnrollment and a
# table named 'student_courseenrollment_history'.
history = HistoricalRecords(
history_id_field=models.UUIDField(default=uuid.uuid4),
table_name='student_courseenrollment_history'
)
objects = CourseEnrollmentManager()
# cache key format e.g enrollment.<username>.<course_key>.mode = 'honor'
COURSE_ENROLLMENT_CACHE_KEY = "enrollment.{}.{}.mode" # TODO Can this be removed? It doesn't seem to be used.
MODE_CACHE_NAMESPACE = 'CourseEnrollment.mode_and_active'
class Meta:
unique_together = (('user', 'course'), )
indexes = [Index(fields=['user', '-created'])]
ordering = ('user', 'course')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Private variable for storing course_overview to minimize calls to the database.
# When the property .course_overview is accessed for the first time, this variable will be set.
self._course_overview = None
def __str__(self):
return (
"[CourseEnrollment] {}: {} ({}); active: ({})"
).format(self.user, self.course_id, self.created, self.is_active)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
super().save(
force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields
)
# Delete the cached status hash, forcing the value to be recalculated the next time it is needed.
cache.delete(self.enrollment_status_hash_cache_key(self.user))
@classmethod
def get_or_create_enrollment(cls, user, course_key):
"""
Create an enrollment for a user in a class. By default *this enrollment
is not active*. This is useful for when an enrollment needs to go
through some sort of approval process before being activated. If you
don't need this functionality, just call `enroll()` instead.
Returns a CourseEnrollment object.
`user` is a Django User object. If it hasn't been saved yet (no `.id`
attribute), this method will automatically save it before
adding an enrollment for it.
`course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
It is expected that this method is called from a method which has already
verified the user authentication and access.
If the enrollment is done due to a CourseEnrollmentAllowed, the CEA will be
linked to the user being enrolled so that it can't be used by other users.
"""
# If we're passing in a newly constructed (i.e. not yet persisted) User,
# save it to the database so that it can have an ID that we can throw
# into our CourseEnrollment object. Otherwise, we'll get an
# IntegrityError for having a null user_id.
assert isinstance(course_key, CourseKey)
if user.id is None:
user.save()
enrollment, __ = cls.objects.get_or_create(
user=user,
course_id=course_key,
defaults={
'mode': CourseMode.DEFAULT_MODE_SLUG,
'is_active': False
}
)
# If there was an unlinked CEA, it becomes linked now
CourseEnrollmentAllowed.objects.filter(
email=user.email,
course_id=course_key,
user__isnull=True
).update(user=user)
return enrollment
@classmethod
def get_enrollment(cls, user, course_key, select_related=None):
"""Returns a CourseEnrollment object.
Args:
user (User): The user associated with the enrollment.
course_key (CourseKey): The key of the course associated with the enrollment.
Returns:
Course enrollment object or None
"""
assert user
if user.is_anonymous:
return None
try:
request_cache = RequestCache('get_enrollment')
if select_related:
cache_key = (user.id, course_key, ','.join(select_related))
else:
cache_key = (user.id, course_key)
cache_response = request_cache.get_cached_response(cache_key)
if cache_response.is_found:
return cache_response.value
query = cls.objects
if select_related is not None:
query = query.select_related(*select_related)
enrollment = query.get(
user=user,
course_id=course_key
)
request_cache.set(cache_key, enrollment)
return enrollment
except cls.DoesNotExist:
return None
@classmethod
def is_enrollment_closed(cls, user, course):
"""
Returns a boolean value regarding whether the user has access to enroll in the course. Returns False if the
enrollment has been closed.
"""
from openedx.core.djangoapps.enrollments.permissions import ENROLL_IN_COURSE
return not user.has_perm(ENROLL_IN_COURSE, course)
def update_enrollment(self, mode=None, is_active=None, skip_refund=False, enterprise_uuid=None):
"""
Updates an enrollment for a user in a class. This includes options
like changing the mode, toggling is_active True/False, etc.
Also emits relevant events for analytics purposes.
This saves immediately.
"""
RequestCache('get_enrollment').clear()
activation_changed = False
# if is_active is None, then the call to update_enrollment didn't specify
# any value, so just leave is_active as it is
if self.is_active != is_active and is_active is not None:
self.is_active = is_active
activation_changed = True
mode_changed = False
# if mode is None, the call to update_enrollment didn't specify a new
# mode, so leave as-is
if self.mode != mode and mode is not None:
self.mode = mode
mode_changed = True
try:
course_data = CourseData(
course_key=self.course_id,
display_name=self.course.display_name,
)
except CourseOverview.DoesNotExist:
course_data = CourseData(
course_key=self.course_id,
)
if activation_changed or mode_changed:
self.save()
self._update_enrollment_in_request_cache(
self.user,
self.course_id,
CourseEnrollmentState(self.mode, self.is_active),
)
# .. event_implemented_name: COURSE_ENROLLMENT_CHANGED
COURSE_ENROLLMENT_CHANGED.send_event(
enrollment=CourseEnrollmentData(
user=UserData(
pii=UserPersonalData(
username=self.user.username,
email=self.user.email,
name=self.user.profile.name,
),
id=self.user.id,
is_active=self.user.is_active,
),
course=course_data,
mode=self.mode,
is_active=self.is_active,
creation_date=self.created,
)
)
if activation_changed:
if self.is_active:
self.emit_event(EVENT_NAME_ENROLLMENT_ACTIVATED, enterprise_uuid=enterprise_uuid)
else:
UNENROLL_DONE.send(sender=None, course_enrollment=self, skip_refund=skip_refund)
self.emit_event(EVENT_NAME_ENROLLMENT_DEACTIVATED, enterprise_uuid=enterprise_uuid)
self.send_signal(EnrollStatusChange.unenroll)
# .. event_implemented_name: COURSE_UNENROLLMENT_COMPLETED
COURSE_UNENROLLMENT_COMPLETED.send_event(
enrollment=CourseEnrollmentData(
user=UserData(
pii=UserPersonalData(
username=self.user.username,
email=self.user.email,
name=self.user.profile.name,
),
id=self.user.id,
is_active=self.user.is_active,
),
course=course_data,
mode=self.mode,
is_active=self.is_active,
creation_date=self.created,
)
)
if mode_changed:
from common.djangoapps.student.email_helpers import (
generate_proctoring_requirements_email_context,
should_send_proctoring_requirements_email,
)
from common.djangoapps.student.emails import send_proctoring_requirements_email
# If mode changed to one that requires proctoring, send proctoring requirements email
if should_send_proctoring_requirements_email(self.user.username, self.course_id):
email_context = generate_proctoring_requirements_email_context(self.user, self.course_id)
send_proctoring_requirements_email(context=email_context)
# Only emit mode change events when the user's enrollment
# mode has changed from its previous setting
self.emit_event(EVENT_NAME_ENROLLMENT_MODE_CHANGED)
# this signal is meant to trigger a score recalculation celery task,
# `countdown` is added to celery task as delay so that cohort is duly updated
# before starting score recalculation
ENROLLMENT_TRACK_UPDATED.send(
sender=None,
user=self.user,
course_key=self.course_id,
mode=self.mode,
countdown=SCORE_RECALCULATION_DELAY_ON_ENROLLMENT_UPDATE,
)
def send_signal(self, event, cost=None, currency=None):
"""
Sends a signal announcing changes in course enrollment status.
"""
ENROLL_STATUS_CHANGE.send(sender=None, event=event, user=self.user,
mode=self.mode, course_id=self.course_id,
cost=cost, currency=currency)
@classmethod
def send_signal_full(cls, event, user=user, mode=mode, course_id=None, cost=None, currency=None):
"""
Sends a signal announcing changes in course enrollment status.
This version should be used if you don't already have a CourseEnrollment object
"""
ENROLL_STATUS_CHANGE.send(sender=None, event=event, user=user,
mode=mode, course_id=course_id,
cost=cost, currency=currency)
def emit_event(self, event_name, enterprise_uuid=None):
"""
Emits an event to explicitly track course enrollment and unenrollment.
"""
from openedx.core.djangoapps.schedules.config import set_up_external_updates_for_enrollment
from common.djangoapps.student.toggles import should_send_enrollment_email
from common.djangoapps.student.tasks import send_course_enrollment_email
segment_properties = {
'category': 'conversion',
'label': str(self.course_id),
'org': self.course_id.org,
'course': self.course_id.course,
'run': self.course_id.run,
'mode': self.mode,
}
try:
context = contexts.course_context_from_course_id(self.course_id)
if enterprise_uuid:
context["enterprise_uuid"] = enterprise_uuid
context["enterprise_enrollment"] = True
segment_properties["enterprise_uuid"] = enterprise_uuid
segment_properties["enterprise_enrollment"] = True
assert isinstance(self.course_id, CourseKey)
data = {
'user_id': self.user.id,
'course_id': str(self.course_id),
'mode': self.mode,
}
if enterprise_uuid and 'username' not in context:
data['username'] = self.user.username
# DENG-803: For segment events forwarded along to Hubspot, duplicate the `properties`
# section of the event payload into the `traits` section so that they can be received.
# This is a temporary fix until we implement this behavior outside of the LMS.
# TODO: DENG-804: remove the properties duplication in the event traits.
segment_traits = dict(segment_properties)
# Add course_title to the traits, as it is used by Hubspot filters
segment_traits['course_title'] = self.course_overview.display_name if self.course_overview else None
# Hubspot requires all incoming events have an email address to link it
# to a Contact object.
segment_traits['email'] = self.user.email
if event_name == EVENT_NAME_ENROLLMENT_ACTIVATED:
if should_send_enrollment_email():
course_pacing_type = 'self-paced' if self.course_overview.self_paced else 'instructor-paced'
send_course_enrollment_email.apply_async((self.user.id, str(self.course_id),
self.course_overview.display_name,
self.course_overview.short_description,
self.course_overview.has_ended(),
course_pacing_type,
self.mode))
segment_properties['email'] = self.user.email
# This next property is for an experiment, see method's comments for more information
segment_properties['external_course_updates'] = set_up_external_updates_for_enrollment(self.user,
self.course_id)
segment_properties['course_start'] = self.course.start
segment_properties['course_pacing'] = self.course.pacing
with tracker.get_tracker().context(event_name, context):
tracker.emit(event_name, data)
segment.track(self.user_id, event_name, segment_properties, traits=segment_traits)
except Exception: # pylint: disable=broad-except
if event_name and self.course_id:
log.exception(
'Unable to emit event %s for user %s and course %s',
event_name,
self.user.username,
self.course_id,
)
@classmethod
def enroll(cls, user, course_key, mode=None, check_access=False, can_upgrade=False, enterprise_uuid=None):
"""
Enroll a user in a course. This saves immediately.
Returns a CourseEnrollment object.
`user` is a Django User object. If it hasn't been saved yet (no `.id`
attribute), this method will automatically save it before
adding an enrollment for it.
`course_key` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
`mode` is a string specifying what kind of enrollment this is. The
default is the default course mode, 'audit'. Other options
include 'professional', 'verified', 'honor',
'no-id-professional' and 'credit'.
See CourseMode in common/djangoapps/course_modes/models.py.
`check_access`: if True, we check that an accessible course actually
exists for the given course_key before we enroll the student.
The default is set to False to avoid breaking legacy code or
code with non-standard flows (ex. beta tester invitations), but
for any standard enrollment flow you probably want this to be True.
`can_upgrade`: if course is upgradeable, alow learners to enroll even
if enrollment is closed. This is a special case for entitlements
while selecting a session. The default is set to False to avoid
breaking the orignal course enroll code.
enterprise_uuid (str): Add course enterprise uuid
Exceptions that can be raised: NonExistentCourseError,
EnrollmentClosedError, CourseFullError, AlreadyEnrolledError. All these
are subclasses of CourseEnrollmentException if you want to catch all of
them in the same way.
It is expected that this method is called from a method which has already
verified the user authentication.
Also emits relevant events for analytics purposes.
"""
try:
user, course_key, mode = CourseEnrollmentStarted.run_filter(
user=user, course_key=course_key, mode=mode,
)
except CourseEnrollmentStarted.PreventEnrollment as exc:
raise EnrollmentNotAllowed(str(exc)) from exc
if mode is None:
mode = _default_course_mode(str(course_key))
# All the server-side checks for whether a user is allowed to enroll.
try:
course = CourseOverview.get_from_id(course_key)
course_data = CourseData(
course_key=course.id,
display_name=course.display_name,
)
except CourseOverview.DoesNotExist:
# This is here to preserve legacy behavior which allowed enrollment in courses
# announced before the start of content creation.
course_data = CourseData(
course_key=course_key,
)
if check_access:
log.warning("User %s failed to enroll in non-existent course %s", user.username, str(course_key))
raise NonExistentCourseError # lint-amnesty, pylint: disable=raise-missing-from
if check_access:
if cls.is_enrollment_closed(user, course) and not can_upgrade:
log.warning(
"User %s failed to enroll in course %s because enrollment is closed",
user.username,
str(course_key)
)
raise EnrollmentClosedError
if cls.objects.is_course_full(course):
log.warning(
"Course %s has reached its maximum enrollment of %d learners. User %s failed to enroll.",
str(course_key),
course.max_student_enrollments_allowed,
user.username,
)
raise CourseFullError
if cls.is_enrolled(user, course_key):
log.warning(
"User %s attempted to enroll in %s, but they were already enrolled",
user.username,
str(course_key)
)
if check_access:
raise AlreadyEnrolledError
# User is allowed to enroll if they've reached this point.
enrollment = cls.get_or_create_enrollment(user, course_key)
enrollment.update_enrollment(is_active=True, mode=mode, enterprise_uuid=enterprise_uuid)
enrollment.send_signal(EnrollStatusChange.enroll)
# .. event_implemented_name: COURSE_ENROLLMENT_CREATED
COURSE_ENROLLMENT_CREATED.send_event(
enrollment=CourseEnrollmentData(
user=UserData(
pii=UserPersonalData(
username=user.username,
email=user.email,
name=user.profile.name,
),
id=user.id,
is_active=user.is_active,
),
course=course_data,
mode=enrollment.mode,
is_active=enrollment.is_active,
creation_date=enrollment.created,
)
)
return enrollment
@classmethod
def enroll_by_email(cls, email, course_id, mode=None, ignore_errors=True):
"""
Enroll a user in a course given their email. This saves immediately.
Note that enrolling by email is generally done in big batches and the
error rate is high. For that reason, we supress User lookup errors by
default.
Returns a CourseEnrollment object. If the User does not exist and
`ignore_errors` is set to `True`, it will return None.
`email` Email address of the User to add to enroll in the course.
`course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
`mode` is a string specifying what kind of enrollment this is. The
default is the default course mode, 'audit'. Other options
include 'professional', 'verified', 'honor',
'no-id-professional' and 'credit'.
See CourseMode in common/djangoapps/course_modes/models.py.
`ignore_errors` is a boolean indicating whether we should suppress
`User.DoesNotExist` errors (returning None) or let it
bubble up.
It is expected that this method is called from a method which has already
verified the user authentication and access.
"""
try:
user = User.objects.get(email=email)
return cls.enroll(user, course_id, mode)
except User.DoesNotExist:
err_msg = "Tried to enroll email {} into course {}, but user not found"
log.error(err_msg.format(email, course_id))
if ignore_errors:
return None
raise
@classmethod
def unenroll(cls, user, course_id, skip_refund=False):
"""
Remove the user from a given course. If the relevant `CourseEnrollment`
object doesn't exist, we log an error but don't throw an exception.
`user` is a Django User object. If it hasn't been saved yet (no `.id`
attribute), this method will automatically save it before
adding an enrollment for it.
`course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
`skip_refund` can be set to True to avoid the refund process.
"""
RequestCache('get_enrollment').clear()
try:
record = cls.objects.get(user=user, course_id=course_id)
try:
# .. filter_implemented_name: CourseUnenrollmentStarted
# .. filter_type: org.openedx.learning.course.unenrollment.started.v1
record = CourseUnenrollmentStarted.run_filter(enrollment=record)
except CourseUnenrollmentStarted.PreventUnenrollment as exc:
raise UnenrollmentNotAllowed(str(exc)) from exc
record.update_enrollment(is_active=False, skip_refund=skip_refund)
except cls.DoesNotExist:
log.error(
"Tried to unenroll student %s from %s but they were not enrolled",
user,
course_id
)
@classmethod
def unenroll_by_email(cls, email, course_id):
"""
Unenroll a user from a course given their email. This saves immediately.
User lookup errors are logged but will not throw an exception.
`email` Email address of the User to unenroll from the course.
`course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
"""
RequestCache('get_enrollment').clear()
try:
user = User.objects.get(email=email)
return cls.unenroll(user, course_id)
except User.DoesNotExist:
log.error(
"Tried to unenroll email %s from course %s, but user not found",
email,
course_id
)
@classmethod
def is_enrolled(cls, user, course_key):
"""
Returns True if the user is enrolled in the course (the entry must exist
and it must have `is_active=True`). Otherwise, returns False.
`user` is a Django User object. If it hasn't been saved yet (no `.id`
attribute), this method will automatically save it before
adding an enrollment for it.
`course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
"""
enrollment_state = cls._get_enrollment_state(user, course_key)
return enrollment_state.is_active or False
@classmethod
def is_enrolled_by_partial(cls, user, course_id_partial):
"""
Returns `True` if the user is enrolled in a course that starts with
`course_id_partial`. Otherwise, returns False.
Can be used to determine whether a student is enrolled in a course
whose run name is unknown.
`user` is a Django User object. If it hasn't been saved yet (no `.id`
attribute), this method will automatically save it before
adding an enrollment for it.
`course_id_partial` (CourseKey) is missing the run component
"""
assert isinstance(course_id_partial, CourseKey)
assert not course_id_partial.run # None or empty string
course_key = CourseKey.from_string('/'.join([course_id_partial.org, course_id_partial.course, '']))
querystring = str(course_key)
try:
return cls.objects.filter(
user=user,
course__id__startswith=querystring,
is_active=1
).exists()
except cls.DoesNotExist:
return False
@classmethod
def enrollment_mode_for_user(cls, user, course_id):
"""
Returns the enrollment mode for the given user for the given course
`user` is a Django User object
`course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
Returns (mode, is_active) where mode is the enrollment mode of the student
and is_active is whether the enrollment is active.
Returns (None, None) if the courseenrollment record does not exist.
"""
enrollment_state = cls._get_enrollment_state(user, course_id)
return enrollment_state.mode, enrollment_state.is_active
@classmethod
def enrollments_for_user(cls, user):
return cls.objects.filter(user=user, is_active=1).select_related('user')
@classmethod
def enrollments_for_user_with_overviews_preload(cls, user, courses_limit=None): # pylint: disable=invalid-name
"""
List of user's CourseEnrollments, CourseOverviews preloaded if possible.
We try to preload all CourseOverviews, which are usually lazily loaded
as the .course_overview property. This is to avoid making an extra
query for every enrollment when displaying something like the student
dashboard. If some of the CourseOverviews are not found, we make no
attempt to initialize them -- we just fall back to existing lazy-load
behavior. The goal is to optimize the most common case as simply as
possible, without changing any of the existing contracts.
The name of this method is long, but was the end result of hashing out a
number of alternatives, so pylint can stuff it (disable=invalid-name)
"""
enrollments = cls.enrollments_for_user(user).select_related('schedule', 'course', 'course__image_set')
if courses_limit:
return enrollments.order_by('-created')[:courses_limit]
else:
return enrollments
@classmethod
def enrollment_status_hash_cache_key(cls, user):
""" Returns the cache key for the cached enrollment status hash.
Args:
user (User): User whose cache key should be returned.
Returns:
str: Cache key.
"""
return 'enrollment_status_hash_' + user.username
@classmethod
def generate_enrollment_status_hash(cls, user):
""" Generates a hash encoding the given user's *active* enrollments.
Args:
user (User): User whose enrollments should be hashed.
Returns:
str: Hash of the user's active enrollments. If the user is anonymous, `None` is returned.
"""
assert user
if user.is_anonymous:
return None
cache_key = cls.enrollment_status_hash_cache_key(user)
status_hash = cache.get(cache_key)
if not status_hash:
enrollments = cls.enrollments_for_user(user).values_list('course_id', 'mode')
enrollments = [(str(e[0]).lower(), e[1].lower()) for e in enrollments]
enrollments = sorted(enrollments, key=lambda e: e[0])
hash_elements = [user.username]
hash_elements += [f'{e[0]}={e[1]}' for e in enrollments]
status_hash = hashlib.md5('&'.join(hash_elements).encode('utf-8')).hexdigest()
# The hash is cached indefinitely. It will be invalidated when the user enrolls/unenrolls.
cache.set(cache_key, status_hash, None)
return status_hash
def is_paid_course(self):
"""
Returns True, if course is paid
"""
paid_course = CourseMode.is_white_label(self.course_id)
if paid_course or CourseMode.is_professional_slug(self.mode):
return True
return False
def activate(self):
"""Makes this `CourseEnrollment` record active. Saves immediately."""
self.update_enrollment(is_active=True)
def deactivate(self):
"""Makes this `CourseEnrollment` record inactive. Saves immediately. An
inactive record means that the student is not enrolled in this course.
"""
self.update_enrollment(is_active=False)
def change_mode(self, mode):
"""Changes this `CourseEnrollment` record's mode to `mode`. Saves immediately."""
self.update_enrollment(mode=mode)
def refundable(self):
"""
For paid/verified certificates, students may always receive a refund if
this CourseEnrollment's `can_refund` attribute is not `None` (that
overrides all other rules).
If the `.can_refund` attribute is `None` or doesn't exist, then ALL of
the following must be true for this enrollment to be refundable:
* The user does not have a certificate issued for this course.
* We are not past the refund cutoff date
* There exists a 'verified' CourseMode for this course.