api.py 17.2 KB
Newer Older
1 2 3 4 5
"""
Enrollment API for creating, updating, and deleting enrollments. Also provides access to enrollment information at a
course level, such as available course modes.

"""
6
import importlib
7
import logging
8

9
from django.conf import settings
10
from django.core.cache import cache
11 12
from opaque_keys.edx.keys import CourseKey

13
from course_modes.models import CourseMode
14
from enrollment import errors
15 16

log = logging.getLogger(__name__)
17

18 19
DEFAULT_DATA_API = 'enrollment.data'

20

21 22
def get_enrollments(user_id):
    """Retrieves all the courses a user is enrolled in.
23

24
    Takes a user and retrieves all relative enrollments. Includes information regarding how the user is enrolled
25 26 27
    in the the course.

    Args:
28
        user_id (str): The username of the user we want to retrieve course enrollment information for.
29 30

    Returns:
31
        A list of enrollment information for the given user.
32 33 34 35 36

    Examples:
        >>> get_enrollments("Bob")
        [
            {
37 38 39
                "created": "2014-10-20T20:18:00Z",
                "mode": "honor",
                "is_active": True,
40
                "user": "Bob",
41
                "course_details": {
42
                    "course_id": "edX/DemoX/2014T2",
43
                    "course_name": "edX Demonstration Course",
44 45 46 47
                    "enrollment_end": "2014-12-20T20:18:00Z",
                    "enrollment_start": "2014-10-15T20:18:00Z",
                    "course_start": "2015-02-03T00:00:00Z",
                    "course_end": "2015-05-06T00:00:00Z",
48 49 50 51 52 53 54 55
                    "course_modes": [
                        {
                            "slug": "honor",
                            "name": "Honor Code Certificate",
                            "min_price": 0,
                            "suggested_prices": "",
                            "currency": "usd",
                            "expiration_datetime": null,
Diana Huang committed
56
                            "description": null,
57 58
                            "sku": null,
                            "bulk_sku": null
59 60 61 62
                        }
                    ],
                    "invite_only": False
                }
63 64
            },
            {
65 66 67
                "created": "2014-10-25T20:18:00Z",
                "mode": "verified",
                "is_active": True,
68
                "user": "Bob",
69
                "course_details": {
70
                    "course_id": "edX/edX-Insider/2014T2",
71
                    "course_name": "edX Insider Course",
72 73 74 75
                    "enrollment_end": "2014-12-20T20:18:00Z",
                    "enrollment_start": "2014-10-15T20:18:00Z",
                    "course_start": "2015-02-03T00:00:00Z",
                    "course_end": "2015-05-06T00:00:00Z",
76 77 78 79 80 81 82 83
                    "course_modes": [
                        {
                            "slug": "honor",
                            "name": "Honor Code Certificate",
                            "min_price": 0,
                            "suggested_prices": "",
                            "currency": "usd",
                            "expiration_datetime": null,
Diana Huang committed
84
                            "description": null,
85 86
                            "sku": null,
                            "bulk_sku": null
87 88 89 90 91
                        }
                    ],
                    "invite_only": True
                }
            }
92 93 94
        ]

    """
95
    return _data_api().get_course_enrollments(user_id)
96 97


98 99
def get_enrollment(user_id, course_id):
    """Retrieves all enrollment information for the user in respect to a specific course.
100

101
    Gets all the course enrollment information specific to a user in a course.
102 103

    Args:
104
        user_id (str): The user to get course enrollment information for.
105 106 107 108 109 110
        course_id (str): The course to get enrollment information for.

    Returns:
        A serializable dictionary of the course enrollment.

    Example:
111
        >>> get_enrollment("Bob", "edX/DemoX/2014T2")
112
        {
113 114 115
            "created": "2014-10-20T20:18:00Z",
            "mode": "honor",
            "is_active": True,
116
            "user": "Bob",
117
            "course_details": {
118
                "course_id": "edX/DemoX/2014T2",
119
                "course_name": "edX Demonstration Course",
120 121 122 123
                "enrollment_end": "2014-12-20T20:18:00Z",
                "enrollment_start": "2014-10-15T20:18:00Z",
                "course_start": "2015-02-03T00:00:00Z",
                "course_end": "2015-05-06T00:00:00Z",
124 125 126 127 128 129 130 131
                "course_modes": [
                    {
                        "slug": "honor",
                        "name": "Honor Code Certificate",
                        "min_price": 0,
                        "suggested_prices": "",
                        "currency": "usd",
                        "expiration_datetime": null,
Diana Huang committed
132
                        "description": null,
133 134
                        "sku": null,
                        "bulk_sku": null
135 136 137 138
                    }
                ],
                "invite_only": False
            }
139 140 141
        }

    """
142
    return _data_api().get_course_enrollment(user_id, course_id)
143 144


145
def add_enrollment(user_id, course_id, mode=None, is_active=True, enrollment_attributes=None):
146
    """Enrolls a user in a course.
147

148
    Enrolls a user in a course. If the mode is not specified, this will default to `CourseMode.DEFAULT_MODE_SLUG`.
149

150
    Arguments:
151 152
        user_id (str): The user to enroll.
        course_id (str): The course to enroll the user in.
153
        mode (str): Optional argument for the type of enrollment to create. Ex. 'audit', 'honor', 'verified',
154
            'professional'. If not specified, this defaults to the default course mode.
155 156
        is_active (boolean): Optional argument for making the new enrollment inactive. If not specified, is_active
            defaults to True.
157
        enrollment_attributes (list): Attributes to be set the enrollment.
158 159 160 161 162 163 164

    Returns:
        A serializable dictionary of the new course enrollment.

    Example:
        >>> add_enrollment("Bob", "edX/DemoX/2014T2", mode="audit")
        {
165
            "created": "2014-10-20T20:18:00Z",
166
            "mode": "audit",
167
            "is_active": True,
168
            "user": "Bob",
169
            "course_details": {
170
                "course_id": "edX/DemoX/2014T2",
171
                "course_name": "edX Demonstration Course",
172 173 174 175
                "enrollment_end": "2014-12-20T20:18:00Z",
                "enrollment_start": "2014-10-15T20:18:00Z",
                "course_start": "2015-02-03T00:00:00Z",
                "course_end": "2015-05-06T00:00:00Z",
176 177
                "course_modes": [
                    {
178 179
                        "slug": "audit",
                        "name": "Audit",
180 181 182 183
                        "min_price": 0,
                        "suggested_prices": "",
                        "currency": "usd",
                        "expiration_datetime": null,
Diana Huang committed
184
                        "description": null,
185 186
                        "sku": null,
                        "bulk_sku": null
187 188 189 190
                    }
                ],
                "invite_only": False
            }
191 192
        }
    """
193 194
    if mode is None:
        mode = _default_course_mode(course_id)
195
    validate_course_mode(course_id, mode, is_active=is_active)
196 197 198 199 200 201
    enrollment = _data_api().create_course_enrollment(user_id, course_id, mode, is_active)

    if enrollment_attributes is not None:
        set_enrollment_attributes(user_id, course_id, enrollment_attributes)

    return enrollment
202 203


Tasawer committed
204
def update_enrollment(user_id, course_id, mode=None, is_active=None, enrollment_attributes=None, include_expired=False):
205
    """Updates the course mode for the enrolled user.
206

207
    Update a course enrollment for the given user and course.
208

209
    Arguments:
210
        user_id (str): The user associated with the updated enrollment.
211
        course_id (str): The course associated with the updated enrollment.
212 213

    Keyword Arguments:
214
        mode (str): The new course mode for this enrollment.
215
        is_active (bool): Sets whether the enrollment is active or not.
216
        enrollment_attributes (list): Attributes to be set the enrollment.
Tasawer committed
217
        include_expired (bool): Boolean denoting whether expired course modes should be included.
218 219 220 221 222 223 224

    Returns:
        A serializable dictionary representing the updated enrollment.

    Example:
        >>> update_enrollment("Bob", "edX/DemoX/2014T2", "honor")
        {
225 226 227
            "created": "2014-10-20T20:18:00Z",
            "mode": "honor",
            "is_active": True,
228
            "user": "Bob",
229
            "course_details": {
230
                "course_id": "edX/DemoX/2014T2",
231
                "course_name": "edX Demonstration Course",
232 233 234 235
                "enrollment_end": "2014-12-20T20:18:00Z",
                "enrollment_start": "2014-10-15T20:18:00Z",
                "course_start": "2015-02-03T00:00:00Z",
                "course_end": "2015-05-06T00:00:00Z",
236 237 238 239 240 241 242 243
                "course_modes": [
                    {
                        "slug": "honor",
                        "name": "Honor Code Certificate",
                        "min_price": 0,
                        "suggested_prices": "",
                        "currency": "usd",
                        "expiration_datetime": null,
Diana Huang committed
244
                        "description": null,
245 246
                        "sku": null,
                        "bulk_sku": null
247 248 249 250
                    }
                ],
                "invite_only": False
            }
251 252 253
        }

    """
Ayub-Khan committed
254 255 256 257 258
    log.info(u'Starting Update Enrollment process for user {user} in course {course} to mode {mode}'.format(
        user=user_id,
        course=course_id,
        mode=mode,
    ))
259
    if mode is not None:
260
        validate_course_mode(course_id, mode, is_active=is_active, include_expired=include_expired)
261 262 263 264 265
    enrollment = _data_api().update_course_enrollment(user_id, course_id, mode=mode, is_active=is_active)
    if enrollment is None:
        msg = u"Course Enrollment not found for user {user} in course {course}".format(user=user_id, course=course_id)
        log.warn(msg)
        raise errors.EnrollmentNotFoundError(msg)
266 267 268
    else:
        if enrollment_attributes is not None:
            set_enrollment_attributes(user_id, course_id, enrollment_attributes)
Ayub-Khan committed
269 270 271 272 273
    log.info(u'Course Enrollment updated for user {user} in course {course} to mode {mode}'.format(
        user=user_id,
        course=course_id,
        mode=mode
    ))
274
    return enrollment
275 276


277
def get_course_enrollment_details(course_id, include_expired=False):
278
    """Get the course modes for course. Also get enrollment start and end date, invite only, etc.
279 280 281 282 283 284

    Given a course_id, return a serializable dictionary of properties describing course enrollment information.

    Args:
        course_id (str): The Course to get enrollment information for.

285 286 287
        include_expired (bool): Boolean denoting whether expired course modes
        should be included in the returned JSON data.

288 289 290 291 292 293
    Returns:
        A serializable dictionary of course enrollment information.

    Example:
        >>> get_course_enrollment_details("edX/DemoX/2014T2")
        {
294
            "course_id": "edX/DemoX/2014T2",
295
            "course_name": "edX Demonstration Course",
296 297 298 299
            "enrollment_end": "2014-12-20T20:18:00Z",
            "enrollment_start": "2014-10-15T20:18:00Z",
            "course_start": "2015-02-03T00:00:00Z",
            "course_end": "2015-05-06T00:00:00Z",
300 301 302 303 304 305 306 307
            "course_modes": [
                {
                    "slug": "honor",
                    "name": "Honor Code Certificate",
                    "min_price": 0,
                    "suggested_prices": "",
                    "currency": "usd",
                    "expiration_datetime": null,
Diana Huang committed
308
                    "description": null,
309 310
                    "sku": null,
                    "bulk_sku": null
311
                }
312
            ],
313
            "invite_only": False
314 315 316
        }

    """
317 318 319 320
    cache_key = u'enrollment.course.details.{course_id}.{include_expired}'.format(
        course_id=course_id,
        include_expired=include_expired
    )
321 322 323 324 325 326 327 328 329 330 331
    cached_enrollment_data = None
    try:
        cached_enrollment_data = cache.get(cache_key)
    except Exception:
        # The cache backend could raise an exception (for example, memcache keys that contain spaces)
        log.exception(u"Error occurred while retrieving course enrollment details from the cache")

    if cached_enrollment_data:
        log.info(u"Get enrollment data for course %s (cached)", course_id)
        return cached_enrollment_data

332
    course_enrollment_details = _data_api().get_course_enrollment_info(course_id, include_expired)
333 334 335 336 337 338 339 340 341 342 343

    try:
        cache_time_out = getattr(settings, 'ENROLLMENT_COURSE_DETAILS_CACHE_TIMEOUT', 60)
        cache.set(cache_key, course_enrollment_details, cache_time_out)
    except Exception:
        # Catch any unexpected errors during caching.
        log.exception(u"Error occurred while caching course enrollment details for course %s", course_id)
        raise errors.CourseEnrollmentError(u"An unexpected error occurred while retrieving course enrollment details.")

    log.info(u"Get enrollment data for course %s", course_id)
    return course_enrollment_details
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
def set_enrollment_attributes(user_id, course_id, attributes):
    """Set enrollment attributes for the enrollment of given user in the
    course provided.

    Args:
        course_id (str): The Course to set enrollment attributes for.
        user_id (str): The User to set enrollment attributes for.
        attributes (list): Attributes to be set.

    Example:
        >>>set_enrollment_attributes(
            "Bob",
            "course-v1-edX-DemoX-1T2015",
            [
                {
                    "namespace": "credit",
                    "name": "provider_id",
                    "value": "hogwarts",
                },
            ]
        )
    """
    _data_api().add_or_update_enrollment_attr(user_id, course_id, attributes)


def get_enrollment_attributes(user_id, course_id):
    """Retrieve enrollment attributes for given user for provided course.

    Args:
        user_id: The User to get enrollment attributes for
        course_id (str): The Course to get enrollment attributes for.

    Example:
        >>>get_enrollment_attributes("Bob", "course-v1-edX-DemoX-1T2015")
        [
            {
                "namespace": "credit",
                "name": "provider_id",
                "value": "hogwarts",
            },
        ]

    Returns: list
    """
    return _data_api().get_enrollment_attributes(user_id, course_id)


393 394 395 396 397 398 399 400 401 402 403
def _default_course_mode(course_id):
    """Return the default enrollment for a course.

    Special case the default enrollment to return if nothing else is found.

    Arguments:
        course_id (str): The course to check against for available course modes.

    Returns:
        str
    """
404 405
    course_modes = CourseMode.modes_for_course(CourseKey.from_string(course_id))
    available_modes = [m.slug for m in course_modes]
406 407 408 409 410 411 412 413 414 415 416

    if CourseMode.DEFAULT_MODE_SLUG in available_modes:
        return CourseMode.DEFAULT_MODE_SLUG
    elif 'audit' in available_modes:
        return 'audit'
    elif 'honor' in available_modes:
        return 'honor'

    return CourseMode.DEFAULT_MODE_SLUG


417
def validate_course_mode(course_id, mode, is_active=None, include_expired=False):
418 419 420 421 422
    """Checks to see if the specified course mode is valid for the course.

    If the requested course mode is not available for the course, raise an error with corresponding
    course enrollment information.

423
    Arguments:
424 425 426
        course_id (str): The course to check against for available course modes.
        mode (str): The slug for the course mode specified in the enrollment.

427 428
    Keyword Arguments:
        is_active (bool): Whether the enrollment is to be activated or deactivated.
Tasawer committed
429
        include_expired (bool): Boolean denoting whether expired course modes should be included.
430

431 432 433 434 435 436
    Returns:
        None

    Raises:
        CourseModeNotFound: raised if the course mode is not found.
    """
437 438
    # If the client has requested an enrollment deactivation, we want to include expired modes
    # in the set of available modes. This allows us to unenroll users from expired modes.
Tasawer committed
439 440 441
    # If include_expired is set as True we should not redetermine its value.
    if not include_expired:
        include_expired = not is_active if is_active is not None else False
442 443

    course_enrollment_info = _data_api().get_course_enrollment_info(course_id, include_expired=include_expired)
444
    course_modes = course_enrollment_info["course_modes"]
445 446 447 448 449 450 451 452 453 454
    available_modes = [m['slug'] for m in course_modes]
    if mode not in available_modes:
        msg = (
            u"Specified course mode '{mode}' unavailable for course {course_id}.  "
            u"Available modes were: {available}"
        ).format(
            mode=mode,
            course_id=course_id,
            available=", ".join(available_modes)
        )
455
        log.warn(msg)
456
        raise errors.CourseModeNotFoundError(msg, course_enrollment_info)
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471


def _data_api():
    """Returns a Data API.
    This relies on Django settings to find the appropriate data API.

    """
    # We retrieve the settings in-line here (rather than using the
    # top-level constant), so that @override_settings will work
    # in the test suite.
    api_path = getattr(settings, "ENROLLMENT_DATA_API", DEFAULT_DATA_API)

    try:
        return importlib.import_module(api_path)
    except (ImportError, ValueError):
472
        log.exception(u"Could not load module at '{path}'".format(path=api_path))
473
        raise errors.EnrollmentApiLoadError(api_path)