Newer
Older
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')
Matthew Mongeau
committed
class CourseEnrollment(models.Model):
David Ormsbee
committed
"""
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.
"""
Calen Pennington
committed
MODEL_TAGS = ['course', 'is_active', 'mode']
Calen Pennington
committed
Bridger Maxwell
committed
user = models.ForeignKey(User)
Calen Pennington
committed
course = models.ForeignKey(
CourseOverview,
db_constraint=False,
)
Calen Pennington
committed
@property
def course_id(self):
return self._course_id
@course_id.setter
def course_id(self, value):
if isinstance(value, basestring):
self._course_id = CourseKey.from_string(value)
else:
self._course_id = value
created = models.DateTimeField(auto_now_add=True, null=True, db_index=True)
David Ormsbee
committed
# 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.DEFAULT_MODE_SLUG, max_length=100)
David Ormsbee
committed
objects = CourseEnrollmentManager()
# cache key format e.g enrollment.<username>.<course_key>.mode = 'honor'
COURSE_ENROLLMENT_CACHE_KEY = u"enrollment.{}.{}.mode" # TODO Can this be removed? It doesn't seem to be used.
MODE_CACHE_NAMESPACE = u'CourseEnrollment.mode_and_active'
Calen Pennington
committed
unique_together = (('user', 'course'),)
ordering = ('user', 'course')
def __init__(self, *args, **kwargs):
super(CourseEnrollment, self).__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 __unicode__(self):
David Ormsbee
committed
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(CourseEnrollment, self).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))
David Ormsbee
committed
@classmethod
def get_or_create_enrollment(cls, user, course_key):
David Ormsbee
committed
"""
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.
Jesse Shapiro
committed
Returns a CourseEnrollment object.
David Ormsbee
committed
`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.
Jesse Shapiro
committed
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.
David Ormsbee
committed
"""
# 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)
David Ormsbee
committed
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
}
)
Jesse Shapiro
committed
# 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)
Jesse Shapiro
committed
"""Returns a CourseEnrollment object.
Args:
user (User): The user associated with the enrollment.
course_id (CourseKey): The key of the course associated with the enrollment.
Returns:
Course enrollment object or None
"""
assert user
if user.is_anonymous():
return None
return cls.objects.get(
user=user,
course_id=course_key
)
except cls.DoesNotExist:
return None
Muhammad Shoaib
committed
@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.
"""
# Disable the pylint error here, as per ormsbee. This local import was previously
# in CourseEnrollment.enroll
from courseware.access import has_access # pylint: disable=import-error
return not has_access(user, 'enroll', course)
def update_enrollment(self, mode=None, is_active=None, skip_refund=False):
"""
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.
# 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
if self.mode != mode and mode is not None:
self.mode = mode
mode_changed = True
if activation_changed or mode_changed:
self._update_enrollment_in_request_cache(
self.user,
self.course_id,
CourseEnrollmentState(self.mode, self.is_active),
)
Renzo Lucioni
committed
if activation_changed:
if self.is_active:
self.emit_event(EVENT_NAME_ENROLLMENT_ACTIVATED)
Calen Pennington
committed
dog_stats_api.increment(
"common.student.enrollment",
tags=[u"org:{}".format(self.course_id.org),
u"offering:{}".format(self.course_id.offering),
Calen Pennington
committed
u"mode:{}".format(self.mode)]
)
else:
UNENROLL_DONE.send(sender=None, course_enrollment=self, skip_refund=skip_refund)
self.send_signal(EnrollStatusChange.unenroll)
David Ormsbee
committed
Calen Pennington
committed
dog_stats_api.increment(
"common.student.unenrollment",
tags=[u"org:{}".format(self.course_id.org),
u"offering:{}".format(self.course_id.offering),
Calen Pennington
committed
u"mode:{}".format(self.mode)]
)
# 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)
ENROLLMENT_TRACK_UPDATED.send(sender=None, user=self.user, course_key=self.course_id)
Calen Pennington
committed
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
Calen Pennington
committed
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):
"""
Emits an event to explicitly track course enrollment and unenrollment.
"""
try:
context = contexts.course_context_from_course_id(self.course_id)
assert isinstance(self.course_id, CourseKey)
'course_id': text_type(self.course_id),
'mode': self.mode,
}
with tracker.get_tracker().context(event_name, context):
Renzo Lucioni
committed
if hasattr(settings, 'LMS_SEGMENT_KEY') and settings.LMS_SEGMENT_KEY:
tracking_context = tracker.get_tracker().resolve_context()
Renzo Lucioni
committed
analytics.track(self.user_id, event_name, {
'category': 'conversion',
'label': text_type(self.course_id),
Renzo Lucioni
committed
'org': self.course_id.org,
'course': self.course_id.course,
'run': self.course_id.run,
'mode': self.mode,
}, context={
'ip': tracking_context.get('ip'),
'Google Analytics': {
'clientId': tracking_context.get('client_id')
}
Renzo Lucioni
committed
})
except: # pylint: disable=bare-except
if event_name and self.course_id:
log.exception(
u'Unable to emit event %s for user %s and course %s',
event_name,
self.course_id,
)
David Ormsbee
committed
@classmethod
def enroll(cls, user, course_key, mode=None, check_access=False):
David Ormsbee
committed
"""
Enroll a user in a course. This saves immediately.
Jesse Shapiro
committed
Returns a CourseEnrollment object.
David Ormsbee
committed
`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)
David Ormsbee
committed
`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',
Afzal Wali
committed
'no-id-professional' and 'credit'.
See CourseMode in common/djangoapps/course_modes/models.py.
David Ormsbee
committed
`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.
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.
David Ormsbee
committed
It is expected that this method is called from a method which has already
verified the user authentication.
Renzo Lucioni
committed
Also emits relevant events for analytics purposes.
David Ormsbee
committed
"""
if mode is None:
mode = _default_course_mode(unicode(course_key))
# All the server-side checks for whether a user is allowed to enroll.
try:
course = CourseOverview.get_from_id(course_key)
except CourseOverview.DoesNotExist:
# This is here to preserve legacy behavior which allowed enrollment in courses
# announced before the start of content creation.
if check_access:
log.warning(u"User %s failed to enroll in non-existent course %s", user.username, unicode(course_key))
raise NonExistentCourseError
if cls.is_enrollment_closed(user, course):
u"User %s failed to enroll in course %s because enrollment is closed",
user.username,
if cls.objects.is_course_full(course):
u"Course %s has reached its maximum enrollment of %d learners. User %s failed to enroll.",
course.max_student_enrollments_allowed,
user.username,
if cls.is_enrolled(user, course_key):
u"User %s attempted to enroll in %s, but they were already enrolled",
user.username,
# 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)
enrollment.send_signal(EnrollStatusChange.enroll)
David Ormsbee
committed
@classmethod
def enroll_by_email(cls, email, course_id, mode=None, ignore_errors=True):
David Ormsbee
committed
"""
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.
Jesse Shapiro
committed
Returns a CourseEnrollment object. If the User does not exist and
David Ormsbee
committed
`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.
David Ormsbee
committed
`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 = u"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):
David Ormsbee
committed
"""
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.
David Ormsbee
committed
"""
try:
record = cls.objects.get(user=user, course_id=course_id)
record.update_enrollment(is_active=False, skip_refund=skip_refund)
David Ormsbee
committed
except cls.DoesNotExist:
log.error(
u"Tried to unenroll student %s from %s but they were not enrolled",
user,
course_id
)
David Ormsbee
committed
@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)
"""
try:
user = User.objects.get(email=email)
return cls.unenroll(user, course_id)
except User.DoesNotExist:
log.error(
u"Tried to unenroll email %s from course %s, but user not found",
email,
course_id
)
David Ormsbee
committed
@classmethod
def is_enrolled(cls, user, course_key):
David Ormsbee
committed
"""
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
David Ormsbee
committed
@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 = unicode(course_key)
return cls.objects.filter(
Calen Pennington
committed
course__id__startswith=querystring,
except cls.DoesNotExist:
return False
Diana Huang
committed
@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)
Calen Pennington
committed
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.
Diana Huang
committed
"""
enrollment_state = cls._get_enrollment_state(user, course_id)
return enrollment_state.mode, enrollment_state.is_active
Diana Huang
committed
David Ormsbee
committed
@classmethod
def enrollments_for_user(cls, user):
return cls.objects.filter(user=user, is_active=1).select_related('user')
David Ormsbee
committed
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
@classmethod
def enrollments_for_user_with_overviews_preload(cls, user): # 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 = list(cls.enrollments_for_user(user))
overviews = CourseOverview.get_from_ids_if_exists(
enrollment.course_id for enrollment in enrollments
)
for enrollment in enrollments:
enrollment._course_overview = overviews.get(enrollment.course_id) # pylint: disable=protected-access
return enrollments
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
@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 = [(six.text_type(e[0]).lower(), e[1].lower()) for e in enrollments]
enrollments = sorted(enrollments, key=lambda e: e[0])
hash_elements = [user.username]
hash_elements += ['{course_id}={mode}'.format(course_id=e[0], mode=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
David Ormsbee
committed
def activate(self):
"""Makes this `CourseEnrollment` record active. Saves immediately."""
David Ormsbee
committed
def deactivate(self):
"""Makes this `CourseEnrollment` record inactive. Saves immediately. An
inactive record means that the student is not enrolled in this course.
"""
def change_mode(self, mode):
"""Changes this `CourseEnrollment` record's mode to `mode`. Saves immediately."""
def refundable(self, user_already_has_certs_for=None):
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.
Arguments:
`user_already_has_certs_for` (set of `CourseKey`):
An optional param that is a set of `CourseKeys` that the user
has already been issued certificates in.
Returns:
bool: Whether is CourseEnrollment can be refunded.
# In order to support manual refunds past the deadline, set can_refund on this object.
# On unenrolling, the "UNENROLL_DONE" signal calls CertificateItem.refund_cert_callback(),
# which calls this method to determine whether to refund the order.
# This can't be set directly because refunds currently happen as a side-effect of unenrolling.
# (side-effects are bad)
if getattr(self, 'can_refund', None) is not None:
return True
# If the student has already been given a certificate they should not be refunded
if user_already_has_certs_for is not None:
if self.course_id in user_already_has_certs_for:
return False
else:
if GeneratedCertificate.certificate_for_student(self.user, self.course_id) is not None:
return False
# If it is after the refundable cutoff date they should not be refunded.
refund_cutoff_date = self.refund_cutoff_date()
# `refund_cuttoff_date` will be `None` if there is no order. If there is no order return `False`.
if refund_cutoff_date is None:
return False
if datetime.now(UTC) > refund_cutoff_date:
course_mode = CourseMode.mode_for_course(self.course_id, 'verified', include_expired=True)
if course_mode is None:
return False
else:
return True
def refund_cutoff_date(self):
""" Calculate and return the refund window end date. """
# NOTE: This is here to avoid circular references
from openedx.core.djangoapps.commerce.utils import ecommerce_api_client, ECOMMERCE_DATE_FORMAT
attribute = self.attributes.get(namespace='order', name='order_number')
except ObjectDoesNotExist:
return None
except MultipleObjectsReturned:
# If there are multiple attributes then return the last one.
enrollment_id = self.get_enrollment(self.user, self.course_id).id
log.warning(
u"Multiple CourseEnrollmentAttributes found for user %s with enrollment-ID %s",
self.user.id,
enrollment_id
)
attribute = self.attributes.filter(namespace='order', name='order_number').last()
try:
order = ecommerce_api_client(self.user).orders(order_number).get()
except HttpClientError:
log.warning(
u"Encountered HttpClientError while getting order details from ecommerce. "
u"Order={number} and user {user}".format(number=order_number, user=self.user.id))
return None
except HttpServerError:
log.warning(
u"Encountered HttpServerError while getting order details from ecommerce. "
u"Order={number} and user {user}".format(number=order_number, user=self.user.id))
return None
except SlumberBaseException:
log.warning(
u"Encountered an error while getting order details from ecommerce. "
u"Order={number} and user {user}".format(number=order_number, user=self.user.id))
refund_window_start_date = max(
datetime.strptime(order['date_placed'], ECOMMERCE_DATE_FORMAT),
self.course_overview.start.replace(tzinfo=None)
)
return refund_window_start_date.replace(tzinfo=UTC) + EnrollmentRefundConfiguration.current().refund_window
@property
def username(self):
return self.user.username
@property
def course_overview(self):
"""
Returns a CourseOverview of the course to which this enrollment refers.
Returns None if an error occurred while trying to load the course.
Note:
If the course is re-published within the lifetime of this
CourseEnrollment object, then the value of this property will
become stale.
Calen Pennington
committed
"""
if not self._course_overview:
try:
self._course_overview = self.course
except CourseOverview.DoesNotExist:
log.info('Course Overviews: unable to find course overview for enrollment, loading from modulestore.')
try:
self._course_overview = CourseOverview.get_from_id(self.course_id)
except (CourseOverview.DoesNotExist, IOError):
self._course_overview = None
return self._course_overview
@cached_property
def verified_mode(self):
return CourseMode.verified_mode_for_course(self.course_id)
def upgrade_deadline(self):
"""
Returns the upgrade deadline for this enrollment, if it is upgradeable.
If the seat cannot be upgraded, None is returned.
Note:
When loading this model, use `select_related` to retrieve the associated schedule object.
Returns:
datetime|None
"""
log.debug('Schedules: Determining upgrade deadline for CourseEnrollment %d...', self.id)
if not CourseMode.is_mode_upgradeable(self.mode):
log.debug(
'Schedules: %s mode of %s is not upgradeable. Returning None for upgrade deadline.',
self.mode, self.course_id
)
return None
if self.dynamic_upgrade_deadline is not None:
Gabe Mulley
committed
# When course modes expire they aren't found any more and None would be returned.
# Replicate that behavior here by returning None if the personalized deadline is in the past.
if datetime.now(UTC) >= self.dynamic_upgrade_deadline:
log.debug('Schedules: Returning None since dynamic upgrade deadline has already passed.')
Gabe Mulley
committed
return None
if self.verified_mode is None or CourseMode.is_professional_mode(self.verified_mode):
log.debug('Schedules: Returning None for dynamic upgrade deadline since the course does not have a '
'verified mode.')
return None
return self.dynamic_upgrade_deadline
return self.course_upgrade_deadline
@cached_property
def dynamic_upgrade_deadline(self):
Gabe Mulley
committed
"""
Returns the learner's personalized upgrade deadline if one exists, otherwise it returns None.
Gabe Mulley
committed
Note that this will return a value even if the deadline is in the past. This property can be used
to modify behavior for users with personalized deadlines by checking if it's None or not.
Returns:
datetime|None
"""
if not self.course_overview.self_paced:
return None
if not DynamicUpgradeDeadlineConfiguration.is_enabled():
return None
course_config = CourseDynamicUpgradeDeadlineConfiguration.current(self.course_id)
if course_config.opted_out():
# Course-level config should be checked first since it overrides the org-level config
return None
org_config = OrgDynamicUpgradeDeadlineConfiguration.current(self.course_id.org)
if org_config.opted_out() and not course_config.opted_in():
return None
try:
if not self.schedule or not self.schedule.active: # pylint: disable=no-member
return None
log.debug(
'Schedules: Pulling upgrade deadline for CourseEnrollment %d from Schedule %d.',
self.id, self.schedule.id
upgrade_deadline = self.schedule.upgrade_deadline
except ObjectDoesNotExist:
# NOTE: Schedule has a one-to-one mapping with CourseEnrollment. If no schedule is associated
# with this enrollment, Django will raise an exception rather than return None.
log.debug('Schedules: No schedule exists for CourseEnrollment %d.', self.id)
return None
return upgrade_deadline
@cached_property
def course_upgrade_deadline(self):
Gabe Mulley
committed
"""
Returns the expiration datetime for the verified course mode.
If the mode is already expired, return None. Also return None if the course does not have a verified
course mode.
Returns:
datetime|None
"""
if self.verified_mode:
log.debug('Schedules: Defaulting to verified mode expiration date-time for %s.', self.course_id)
return self.verified_mode.expiration_datetime
else:
log.debug('Schedules: No verified mode located for %s.', self.course_id)
except CourseMode.DoesNotExist:
log.debug('Schedules: %s has no verified mode.', self.course_id)
def is_verified_enrollment(self):
"""
Check the course enrollment mode is verified or not
"""
return CourseMode.is_verified_slug(self.mode)
def is_professional_enrollment(self):
"""
Check the course enrollment mode is professional or not
"""
return CourseMode.is_professional_slug(self.mode)
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
@classmethod
def is_enrolled_as_verified(cls, user, course_key):
"""
Check whether the course enrollment is for a verified mode.
Arguments:
user (User): The user object.
course_key (CourseKey): The identifier for the course.
Returns: bool
"""
enrollment = cls.get_enrollment(user, course_key)
return (
enrollment is not None and
enrollment.is_active and
enrollment.is_verified_enrollment()
)
@classmethod
def cache_key_name(cls, user_id, course_key):
"""Return cache key name to be used to cache current configuration.
Args:
user_id(int): Id of user.
course_key(unicode): Unicode of course key
Returns:
Unicode cache key
"""
return cls.COURSE_ENROLLMENT_CACHE_KEY.format(user_id, unicode(course_key))
@classmethod
def _get_enrollment_state(cls, user, course_key):
"""
Returns the CourseEnrollmentState for the given user
and course_key, caching the result for later retrieval.
"""
assert user
if user.is_anonymous():
return CourseEnrollmentState(None, None)
enrollment_state = cls._get_enrollment_in_request_cache(user, course_key)
if not enrollment_state:
try:
record = cls.objects.get(user=user, course_id=course_key)
enrollment_state = CourseEnrollmentState(record.mode, record.is_active)
except cls.DoesNotExist:
enrollment_state = CourseEnrollmentState(None, None)
cls._update_enrollment_in_request_cache(user, course_key, enrollment_state)
return enrollment_state
@classmethod
def bulk_fetch_enrollment_states(cls, users, course_key):
"""
Bulk pre-fetches the enrollment states for the given users
for the given course.
"""
# before populating the cache with another bulk set of data,
# remove previously cached entries to keep memory usage low.
clear_cache(cls.MODE_CACHE_NAMESPACE)
records = cls.objects.filter(user__in=users, course_id=course_key).select_related('user')
cache = cls._get_mode_active_request_cache()
for record in records:
enrollment_state = CourseEnrollmentState(record.mode, record.is_active)
cls._update_enrollment(cache, record.user.id, course_key, enrollment_state)
@classmethod
def _get_mode_active_request_cache(cls):
"""
Returns the request-specific cache for CourseEnrollment
"""
return get_cache(cls.MODE_CACHE_NAMESPACE)
@classmethod
def _get_enrollment_in_request_cache(cls, user, course_key):
"""
Returns the cached value (CourseEnrollmentState) for the user's
enrollment in the request cache. If not cached, returns None.
"""
return cls._get_mode_active_request_cache().get((user.id, course_key))
@classmethod
def _update_enrollment_in_request_cache(cls, user, course_key, enrollment_state):
"""
Updates the cached value for the user's enrollment in the
request cache.
"""
cls._update_enrollment(cls._get_mode_active_request_cache(), user.id, course_key, enrollment_state)
@classmethod
def _update_enrollment(cls, cache, user_id, course_key, enrollment_state):
"""
Updates the cached value for the user's enrollment in the
given cache.
"""
cache[(user_id, course_key)] = enrollment_state
@receiver(models.signals.post_save, sender=CourseEnrollment)
@receiver(models.signals.post_delete, sender=CourseEnrollment)
def invalidate_enrollment_mode_cache(sender, instance, **kwargs): # pylint: disable=unused-argument, invalid-name
"""Invalidate the cache of CourseEnrollment model. """
cache_key = CourseEnrollment.cache_key_name(
instance.user.id,
unicode(instance.course_id)
)
cache.delete(cache_key)
class ManualEnrollmentAudit(models.Model):
"""
Table for tracking which enrollments were performed through manual enrollment.
"""
enrollment = models.ForeignKey(CourseEnrollment, null=True)
enrolled_by = models.ForeignKey(User, null=True)
enrolled_email = models.CharField(max_length=255, db_index=True)
time_stamp = models.DateTimeField(auto_now_add=True, null=True)
state_transition = models.CharField(max_length=255, choices=TRANSITION_STATES)
reason = models.TextField(null=True)
role = models.CharField(blank=True, null=True, max_length=64)
def create_manual_enrollment_audit(cls, user, email, state_transition, reason, enrollment=None, role=None):
"""
saves the student manual enrollment information
"""
enrolled_by=user,
enrolled_email=email,
state_transition=state_transition,
reason=reason,
enrollment=enrollment,
role=role,
)
@classmethod
def get_manual_enrollment_by_email(cls, email):
"""
if matches returns the most recent entry in the table filtered by email else returns None.
"""
try:
manual_enrollment = cls.objects.filter(enrolled_email=email).latest('time_stamp')
except cls.DoesNotExist:
manual_enrollment = None