api.py 128 KB
Newer Older
1 2 3
"""
Instructor Dashboard API views

4
JSON views which the instructor dashboard requests.
5

Miles Steele committed
6
Many of these GETs may become PUTs in the future.
7
"""
8 9
import csv
import decimal
10
import json
11
import logging
12
import random
13
import re
14 15
import string
import StringIO
16
import time
17 18

import unicodecsv
19
from django.conf import settings
20 21
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied, ValidationError
22
from django.core.mail.message import EmailMessage
23
from django.core.urlresolvers import reverse
24
from django.core.validators import validate_email
25
from django.db import IntegrityError, transaction
26
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound
27
from django.shortcuts import redirect
28 29 30 31 32 33 34
from django.utils.html import strip_tags
from django.utils.translation import ugettext as _
from django.views.decorators.cache import cache_control
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_http_methods, require_POST
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey, UsageKey
35

36 37 38 39 40 41 42 43
import instructor_analytics.basic
import instructor_analytics.csvs
import instructor_analytics.distributions
import lms.djangoapps.instructor.enrollment as enrollment
import lms.djangoapps.instructor_task.api
from bulk_email.models import BulkEmailFlag, CourseEmail
from certificates import api as certs_api
from certificates.models import CertificateInvalidation, CertificateStatuses, CertificateWhitelist, GeneratedCertificate
44
from courseware.access import has_access
45 46
from courseware.courses import get_course_by_id, get_course_with_access
from courseware.models import StudentModule
47 48 49 50 51 52
from django_comment_client.utils import (
    has_forum_access,
    get_course_discussion_settings,
    get_group_name,
    get_group_id_for_user
)
53 54 55 56 57 58 59
from django_comment_common.models import (
    Role,
    FORUM_ROLE_ADMINISTRATOR,
    FORUM_ROLE_MODERATOR,
    FORUM_ROLE_GROUP_MODERATOR,
    FORUM_ROLE_COMMUNITY_TA,
)
Saleem Latif committed
60
from edxmako.shortcuts import render_to_string
61
from lms.djangoapps.instructor.access import ROLES, allow_access, list_with_level, revoke_access, update_forum_role
62
from lms.djangoapps.instructor.enrollment import (
63 64
    enroll_email,
    get_email_params,
65
    get_user_email_language,
66
    send_beta_role_email,
67 68
    send_mail_to_student,
    unenroll_email
69
)
70 71
from lms.djangoapps.instructor.views import INVOICE_KEY
from lms.djangoapps.instructor.views.instructor_task_helpers import extract_email_features, extract_task_features
72
from lms.djangoapps.instructor_task.api import submit_override_score
73
from lms.djangoapps.instructor_task.api_helper import AlreadyRunningError, QueueConnectionError
74 75 76 77
from lms.djangoapps.instructor_task.models import ReportStore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.course_groups.cohorts import is_course_cohorted
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
78
from openedx.core.djangoapps.user_api.preferences.api import get_user_preference, set_user_preference
79
from openedx.core.djangolib.markup import HTML, Text
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
from shoppingcart.models import (
    Coupon,
    CourseMode,
    CourseRegistrationCode,
    CourseRegistrationCodeInvoiceItem,
    Invoice,
    RegistrationCodeRedemption
)
from student import auth
from student.models import (
    ALLOWEDTOENROLL_TO_ENROLLED,
    ALLOWEDTOENROLL_TO_UNENROLLED,
    DEFAULT_TRANSITION_STATE,
    ENROLLED_TO_ENROLLED,
    ENROLLED_TO_UNENROLLED,
    UNENROLLED_TO_ALLOWEDTOENROLL,
    UNENROLLED_TO_ENROLLED,
    UNENROLLED_TO_UNENROLLED,
    CourseEnrollment,
    EntranceExamConfiguration,
    ManualEnrollmentAudit,
    Registration,
    UserProfile,
    anonymous_id_for_user,
    get_user_by_username_or_email,
    unique_id_for_user
)
from student.roles import CourseFinanceAdminRole, CourseSalesAdminRole
108
from submissions import api as sub_api  # installed from the edx-submissions repository
109 110 111 112 113 114 115 116
from util.file import (
    FileValidationException,
    UniversalNewlineIterator,
    course_and_time_based_filename_generator,
    store_uploaded_file
)
from util.json_request import JsonResponse, JsonResponseBadRequest
from util.views import require_global_staff
117
from xmodule.modulestore.django import modulestore
118

119 120
from .tools import (
    dump_module_extensions,
121
    dump_student_extensions,
122 123 124 125
    find_unit,
    get_student_from_identifier,
    handle_dashboard_error,
    parse_datetime,
126
    require_student_from_identifier,
127
    set_due_date_extension,
128
    strip_if_string
129 130
)

131 132
log = logging.getLogger(__name__)

133 134
TASK_SUBMISSION_OK = 'created'

135 136 137
SUCCESS_MESSAGE_TEMPLATE = _("The {report_type} report is being created. "
                             "To view the status of the report, see Pending Tasks below.")

138

139
def common_exceptions_400(func):
140 141 142 143
    """
    Catches common exceptions and renders matching 400 errors.
    (decorator without arguments)
    """
144

145
    def wrapped(request, *args, **kwargs):  # pylint: disable=missing-docstring
146 147
        use_json = (request.is_ajax() or
                    request.META.get("HTTP_ACCEPT", "").startswith("application/json"))
148
        try:
149
            return func(request, *args, **kwargs)
150
        except User.DoesNotExist:
151 152
            message = _('User does not exist.')
        except (AlreadyRunningError, QueueConnectionError) as err:
153
            message = unicode(err)
154 155 156 157 158 159

        if use_json:
            return JsonResponseBadRequest(message)
        else:
            return HttpResponseBadRequest(message)

160 161 162
    return wrapped


163 164
def require_post_params(*args, **kwargs):
    """
165
    Checks for required parameters or renders a 400 error.
166 167
    (decorator with arguments)

168 169 170
    `args` is a *list of required POST parameter names.
    `kwargs` is a **dict of required POST parameter names
        to string explanations of the parameter
171 172 173 174 175 176
    """
    required_params = []
    required_params += [(arg, None) for arg in args]
    required_params += [(key, kwargs[key]) for key in kwargs]
    # required_params = e.g. [('action', 'enroll or unenroll'), ['emails', None]]

177 178
    def decorator(func):  # pylint: disable=missing-docstring
        def wrapped(*args, **kwargs):  # pylint: disable=missing-docstring
179 180 181 182 183 184 185 186 187 188 189
            request = args[0]

            error_response_data = {
                'error': 'Missing required query parameter(s)',
                'parameters': [],
                'info': {},
            }

            for (param, extra) in required_params:
                default = object()
                if request.POST.get(param, default) == default:
190
                    error_response_data['parameters'].append(param)
191 192 193 194 195 196 197 198 199
                    error_response_data['info'][param] = extra

            if len(error_response_data['parameters']) > 0:
                return JsonResponse(error_response_data, status=400)
            else:
                return func(*args, **kwargs)
        return wrapped
    return decorator

200

201 202 203 204 205 206 207 208 209 210 211
def require_level(level):
    """
    Decorator with argument that requires an access level of the requesting
    user. If the requirement is not satisfied, returns an
    HttpResponseForbidden (403).

    Assumes that request is in args[0].
    Assumes that course_id is in kwargs['course_id'].

    `level` is in ['instructor', 'staff']
    if `level` is 'staff', instructors will also be allowed, even
212
        if they are not in the staff group.
213 214 215 216
    """
    if level not in ['instructor', 'staff']:
        raise ValueError("unrecognized level '{}'".format(level))

217 218
    def decorator(func):  # pylint: disable=missing-docstring
        def wrapped(*args, **kwargs):  # pylint: disable=missing-docstring
219
            request = args[0]
stephensanchez committed
220
            course = get_course_by_id(CourseKey.from_string(kwargs['course_id']))
221

222
            if has_access(request.user, level, course):
223 224 225 226 227 228 229
                return func(*args, **kwargs)
            else:
                return HttpResponseForbidden()
        return wrapped
    return decorator


stephensanchez committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
def require_sales_admin(func):
    """
    Decorator for checking sales administrator access before executing an HTTP endpoint. This decorator
    is designed to be used for a request based action on a course. It assumes that there will be a
    request object as well as a course_id attribute to leverage to check course level privileges.

    If the user does not have privileges for this operation, this will return HttpResponseForbidden (403).
    """
    def wrapped(request, course_id):  # pylint: disable=missing-docstring

        try:
            course_key = CourseKey.from_string(course_id)
        except InvalidKeyError:
            log.error(u"Unable to find course with course key %s", course_id)
            return HttpResponseNotFound()

246
        access = auth.user_has_role(request.user, CourseSalesAdminRole(course_key))
stephensanchez committed
247 248 249 250 251 252 253 254

        if access:
            return func(request, course_id)
        else:
            return HttpResponseForbidden()
    return wrapped


255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
def require_finance_admin(func):
    """
    Decorator for checking finance administrator access before executing an HTTP endpoint. This decorator
    is designed to be used for a request based action on a course. It assumes that there will be a
    request object as well as a course_id attribute to leverage to check course level privileges.

    If the user does not have privileges for this operation, this will return HttpResponseForbidden (403).
    """
    def wrapped(request, course_id):  # pylint: disable=missing-docstring

        try:
            course_key = CourseKey.from_string(course_id)
        except InvalidKeyError:
            log.error(u"Unable to find course with course key %s", course_id)
            return HttpResponseNotFound()

271
        access = auth.user_has_role(request.user, CourseFinanceAdminRole(course_key))
272 273 274 275 276 277 278 279

        if access:
            return func(request, course_id)
        else:
            return HttpResponseForbidden()
    return wrapped


asadiqbal08 committed
280 281 282 283 284 285
EMAIL_INDEX = 0
USERNAME_INDEX = 1
NAME_INDEX = 2
COUNTRY_INDEX = 3


286
@require_POST
asadiqbal08 committed
287 288 289
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
290
def register_and_enroll_students(request, course_id):  # pylint: disable=too-many-statements
asadiqbal08 committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    """
    Create new account and Enroll students in this course.
    Passing a csv file that contains a list of students.
    Order in csv should be the following email = 0; username = 1; name = 2; country = 3.
    Requires staff access.

    -If the email address and username already exists and the user is enrolled in the course,
    do nothing (including no email gets sent out)

    -If the email address already exists, but the username is different,
    match on the email address only and continue to enroll the user in the course using the email address
    as the matching criteria. Note the change of username as a warning message (but not a failure). Send a standard enrollment email
    which is the same as the existing manual enrollment

    -If the username already exists (but not the email), assume it is a different user and fail to create the new account.
     The failure will be messaged in a response in the browser.
    """

309 310 311 312
    if not configuration_helpers.get_value(
            'ALLOW_AUTOMATED_SIGNUPS',
            settings.FEATURES.get('ALLOW_AUTOMATED_SIGNUPS', False),
    ):
asadiqbal08 committed
313 314
        return HttpResponseForbidden()

315
    course_id = CourseKey.from_string(course_id)
asadiqbal08 committed
316 317 318 319
    warnings = []
    row_errors = []
    general_errors = []

320 321 322 323 324 325 326
    # for white labels we use 'shopping cart' which uses CourseMode.DEFAULT_SHOPPINGCART_MODE_SLUG as
    # course mode for creating course enrollments.
    if CourseMode.is_white_label(course_id):
        course_mode = CourseMode.DEFAULT_SHOPPINGCART_MODE_SLUG
    else:
        course_mode = None

asadiqbal08 committed
327 328 329 330 331
    if 'students_list' in request.FILES:
        students = []

        try:
            upload_file = request.FILES.get('students_list')
332 333 334 335 336 337 338 339 340
            if upload_file.name.endswith('.csv'):
                students = [row for row in csv.reader(upload_file.read().splitlines())]
                course = get_course_by_id(course_id)
            else:
                general_errors.append({
                    'username': '', 'email': '',
                    'response': _('Make sure that the file you upload is in CSV format with no extraneous characters or rows.')
                })

341
        except Exception:  # pylint: disable=broad-except
asadiqbal08 committed
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
            general_errors.append({
                'username': '', 'email': '', 'response': _('Could not read uploaded file.')
            })
        finally:
            upload_file.close()

        generated_passwords = []
        row_num = 0
        for student in students:
            row_num = row_num + 1

            # verify that we have exactly four columns in every row but allow for blank lines
            if len(student) != 4:
                if len(student) > 0:
                    general_errors.append({
                        'username': '',
                        'email': '',
                        'response': _('Data in row #{row_num} must have exactly four columns: email, username, full name, and country').format(row_num=row_num)
                    })
                continue

            # Iterate each student in the uploaded csv file.
            email = student[EMAIL_INDEX]
            username = student[USERNAME_INDEX]
            name = student[NAME_INDEX]
            country = student[COUNTRY_INDEX][:2]

            email_params = get_email_params(course, True, secure=request.is_secure())
            try:
                validate_email(email)  # Raises ValidationError if invalid
            except ValidationError:
                row_errors.append({
                    'username': username, 'email': email, 'response': _('Invalid email {email_address}.').format(email_address=email)})
            else:
                if User.objects.filter(email=email).exists():
                    # Email address already exists. assume it is the correct user
                    # and just register the user in the course and send an enrollment email.
                    user = User.objects.get(email=email)

                    # see if it is an exact match with email and username
                    # if it's not an exact match then just display a warning message, but continue onwards
                    if not User.objects.filter(email=email, username=username).exists():
                        warning_message = _(
                            'An account with email {email} exists but the provided username {username} '
                            'is different. Enrolling anyway with {email}.'
                        ).format(email=email, username=username)

                        warnings.append({
390 391 392
                            'username': username, 'email': email, 'response': warning_message
                        })
                        log.warning(u'email %s already exist', email)
asadiqbal08 committed
393
                    else:
394 395
                        log.info(
                            u"user already exists with username '%s' and email '%s'",
396 397
                            username,
                            email
398
                        )
asadiqbal08 committed
399

400
                    # enroll a user if it is not already enrolled.
asadiqbal08 committed
401
                    if not CourseEnrollment.is_enrolled(user, course_id):
402 403 404 405 406 407 408 409
                        # Enroll user to the course and add manual enrollment audit trail
                        create_manual_course_enrollment(
                            user=user,
                            course_id=course_id,
                            mode=course_mode,
                            enrolled_by=request.user,
                            reason='Enrolling via csv upload',
                            state_transition=UNENROLLED_TO_ENROLLED,
410
                        )
asadiqbal08 committed
411 412 413 414 415 416
                        enroll_email(course_id=course_id, student_email=email, auto_enroll=True, email_students=True, email_params=email_params)
                else:
                    # This email does not yet exist, so we need to create a new account
                    # If username already exists in the database, then create_and_enroll_user
                    # will raise an IntegrityError exception.
                    password = generate_unique_password(generated_passwords)
417 418 419 420
                    errors = create_and_enroll_user(
                        email, username, name, country, password, course_id, course_mode, request.user, email_params
                    )
                    row_errors.extend(errors)
asadiqbal08 committed
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

    else:
        general_errors.append({
            'username': '', 'email': '', 'response': _('File is not attached.')
        })

    results = {
        'row_errors': row_errors,
        'general_errors': general_errors,
        'warnings': warnings
    }
    return JsonResponse(results)


def generate_random_string(length):
    """
    Create a string of random characters of specified length
    """
    chars = [
        char for char in string.ascii_uppercase + string.digits + string.ascii_lowercase
        if char not in 'aAeEiIoOuU1l'
    ]

    return string.join((random.choice(chars) for __ in range(length)), '')


def generate_unique_password(generated_passwords, password_length=12):
    """
    generate a unique password for each student.
    """

    password = generate_random_string(password_length)
    while password in generated_passwords:
        password = generate_random_string(password_length)

    generated_passwords.append(password)

    return password


461 462 463
def create_user_and_user_profile(email, username, name, country, password):
    """
    Create a new user, add a new Registration instance for letting user verify its identity and create a user profile.
asadiqbal08 committed
464

465 466 467 468 469
    :param email: user's email address
    :param username: user's username
    :param name: user's name
    :param country: user's country
    :param password: user's password
asadiqbal08 committed
470

471 472
    :return: User instance of the new user.
    """
asadiqbal08 committed
473 474 475 476 477 478 479 480 481
    user = User.objects.create_user(username, email, password)
    reg = Registration()
    reg.register(user)

    profile = UserProfile(user=user)
    profile.name = name
    profile.country = country
    profile.save()

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
    return user


def create_manual_course_enrollment(user, course_id, mode, enrolled_by, reason, state_transition):
    """
    Create course enrollment for the given student and create manual enrollment audit trail.

    :param user: User who is to enroll in course
    :param course_id: course identifier of the course in which to enroll the user.
    :param mode: mode for user enrollment, e.g. 'honor', 'audit' etc.
    :param enrolled_by: User who made the manual enrollment entry (usually instructor or support)
    :param reason: Reason behind manual enrollment
    :param state_transition: state transition denoting whether student enrolled from un-enrolled,
            un-enrolled from enrolled etc.
    :return CourseEnrollment instance.
    """
    enrollment_obj = CourseEnrollment.enroll(user, course_id, mode=mode)
    ManualEnrollmentAudit.create_manual_enrollment_audit(
        enrolled_by, user.email, state_transition, reason, enrollment_obj
    )

    log.info(u'user %s enrolled in the course %s', user.username, course_id)
    return enrollment_obj


def create_and_enroll_user(email, username, name, country, password, course_id, course_mode, enrolled_by, email_params):
    """
    Create a new user and enroll him/her to the given course, return list of errors in the following format
        Error format:
            each error is key-value pait dict with following key-value pairs.
            1. username: username of the user to enroll
            1. email: email of the user to enroll
            1. response: readable error message

    :param email: user's email address
    :param username: user's username
    :param name: user's name
    :param country: user's country
    :param password: user's password
    :param course_id: course identifier of the course in which to enroll the user.
    :param course_mode: mode for user enrollment, e.g. 'honor', 'audit' etc.
    :param enrolled_by: User who made the manual enrollment entry (usually instructor or support)
    :param email_params: information to send to the user via email

    :return: list of errors
    """
    errors = list()
    try:
        with transaction.atomic():
            # Create a new user
            user = create_user_and_user_profile(email, username, name, country, password)

            # Enroll user to the course and add manual enrollment audit trail
            create_manual_course_enrollment(
                user=user,
                course_id=course_id,
                mode=course_mode,
                enrolled_by=enrolled_by,
                reason='Enrolling via csv upload',
                state_transition=UNENROLLED_TO_ENROLLED,
            )
    except IntegrityError:
        errors.append({
            'username': username, 'email': email, 'response': _('Username {user} already exists.').format(user=username)
        })
    except Exception as ex:  # pylint: disable=broad-except
        log.exception(type(ex).__name__)
        errors.append({
            'username': username, 'email': email, 'response': type(ex).__name__,
        })
    else:
        try:
            # It's a new user, an email will be sent to each newly created user.
            email_params.update({
                'message': 'account_creation_and_enrollment',
                'email_address': email,
                'password': password,
559
                'platform_name': configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME),
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
            })
            send_mail_to_student(email, email_params)
        except Exception as ex:  # pylint: disable=broad-except
            log.exception(
                "Exception '{exception}' raised while sending email to new user.".format(exception=type(ex).__name__)
            )
            errors.append({
                'username': username,
                'email': email,
                'response':
                    _("Error '{error}' while sending email to new user (user email={email}). "
                      "Without the email student would not be able to login. "
                      "Please contact support for further information.").format(error=type(ex).__name__, email=email),
            })
        else:
            log.info(u'email sent to new created user at %s', email)

    return errors
asadiqbal08 committed
578 579


580
@require_POST
581 582
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
583
@require_level('staff')
584
@require_post_params(action="enroll or unenroll", identifiers="stringified list of emails and/or usernames")
585
def students_update_enrollment(request, course_id):
586 587
    """
    Enroll or unenroll students by email.
588
    Requires staff access.
Miles Steele committed
589 590 591

    Query Parameters:
    - action in ['enroll', 'unenroll']
592
    - identifiers is string containing a list of emails and/or usernames separated by anything split_input_list can handle.
Miles Steele committed
593
    - auto_enroll is a boolean (defaults to false)
594
        If auto_enroll is false, students will be allowed to enroll.
595 596 597 598
        If auto_enroll is true, students will be enrolled as soon as they register.
    - email_students is a boolean (defaults to false)
        If email_students is true, students will be sent email notification
        If email_students is false, students will not be sent email notification
599 600 601

    Returns an analog to this JSON structure: {
        "action": "enroll",
602
        "auto_enroll": false,
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
        "results": [
            {
                "email": "testemail@test.org",
                "before": {
                    "enrollment": false,
                    "auto_enroll": false,
                    "user": true,
                    "allowed": false
                },
                "after": {
                    "enrollment": true,
                    "auto_enroll": false,
                    "user": true,
                    "allowed": false
                }
            }
        ]
    }
621
    """
622
    course_id = CourseKey.from_string(course_id)
623 624
    action = request.POST.get('action')
    identifiers_raw = request.POST.get('identifiers')
625
    identifiers = _split_input_list(identifiers_raw)
626 627
    auto_enroll = _get_boolean_param(request, 'auto_enroll')
    email_students = _get_boolean_param(request, 'email_students')
628 629 630 631 632 633 634 635 636 637 638 639
    is_white_label = CourseMode.is_white_label(course_id)
    reason = request.POST.get('reason')
    if is_white_label:
        if not reason:
            return JsonResponse(
                {
                    'action': action,
                    'results': [{'error': True}],
                    'auto_enroll': auto_enroll,
                }, status=400)
    enrollment_obj = None
    state_transition = DEFAULT_TRANSITION_STATE
640 641 642 643

    email_params = {}
    if email_students:
        course = get_course_by_id(course_id)
644
        email_params = get_email_params(course, auto_enroll, secure=request.is_secure())
645

646
    results = []
647 648 649 650
    for identifier in identifiers:
        # First try to get a user object from the identifer
        user = None
        email = None
651
        language = None
652 653 654 655 656 657
        try:
            user = get_student_from_identifier(identifier)
        except User.DoesNotExist:
            email = identifier
        else:
            email = user.email
658
            language = get_user_email_language(user)
659

660
        try:
661 662 663
            # Use django.core.validators.validate_email to check email address
            # validity (obviously, cannot check if email actually /exists/,
            # simply that it is plausibly valid)
664
            validate_email(email)  # Raises ValidationError if invalid
665
            if action == 'enroll':
666
                before, after, enrollment_obj = enroll_email(
667 668
                    course_id, email, auto_enroll, email_students, email_params, language=language
                )
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
                before_enrollment = before.to_dict()['enrollment']
                before_user_registered = before.to_dict()['user']
                before_allowed = before.to_dict()['allowed']
                after_enrollment = after.to_dict()['enrollment']
                after_allowed = after.to_dict()['allowed']

                if before_user_registered:
                    if after_enrollment:
                        if before_enrollment:
                            state_transition = ENROLLED_TO_ENROLLED
                        else:
                            if before_allowed:
                                state_transition = ALLOWEDTOENROLL_TO_ENROLLED
                            else:
                                state_transition = UNENROLLED_TO_ENROLLED
                else:
                    if after_allowed:
                        state_transition = UNENROLLED_TO_ALLOWEDTOENROLL

688
            elif action == 'unenroll':
689 690 691
                before, after = unenroll_email(
                    course_id, email, email_students, email_params, language=language
                )
692 693
                before_enrollment = before.to_dict()['enrollment']
                before_allowed = before.to_dict()['allowed']
694
                enrollment_obj = CourseEnrollment.get_enrollment(user, course_id) if user else None
695 696 697 698 699 700 701 702 703

                if before_enrollment:
                    state_transition = ENROLLED_TO_UNENROLLED
                else:
                    if before_allowed:
                        state_transition = ALLOWEDTOENROLL_TO_UNENROLLED
                    else:
                        state_transition = UNENROLLED_TO_UNENROLLED

704
            else:
705 706 707
                return HttpResponseBadRequest(strip_tags(
                    "Unrecognized action '{}'".format(action)
                ))
708

709 710 711
        except ValidationError:
            # Flag this email as an error if invalid, but continue checking
            # the remaining in the list
712
            results.append({
713 714
                'identifier': identifier,
                'invalidIdentifier': True,
715
            })
716

717
        except Exception as exc:  # pylint: disable=broad-except
718 719
            # catch and log any exceptions
            # so that one error doesn't cause a 500.
720
            log.exception(u"Error while #{}ing student")
721 722
            log.exception(exc)
            results.append({
723
                'identifier': identifier,
724
                'error': True,
725 726 727
            })

        else:
728 729 730
            ManualEnrollmentAudit.create_manual_enrollment_audit(
                request.user, email, state_transition, reason, enrollment_obj
            )
731 732 733 734
            results.append({
                'identifier': identifier,
                'before': before.to_dict(),
                'after': after.to_dict(),
735
            })
736 737

    response_payload = {
738 739
        'action': action,
        'results': results,
Miles Steele committed
740
        'auto_enroll': auto_enroll,
741
    }
742
    return JsonResponse(response_payload)
743 744


745
@require_POST
746 747
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
748
@require_level('instructor')
749
@common_exceptions_400
750
@require_post_params(
751
    identifiers="stringified list of emails and/or usernames",
752 753
    action="add or remove",
)
754 755 756 757 758
def bulk_beta_modify_access(request, course_id):
    """
    Enroll or unenroll users in beta testing program.

    Query parameters:
759
    - identifiers is string containing a list of emails and/or usernames separated by
760
      anything split_input_list can handle.
761 762
    - action is one of ['add', 'remove']
    """
763
    course_id = CourseKey.from_string(course_id)
764 765
    action = request.POST.get('action')
    identifiers_raw = request.POST.get('identifiers')
766
    identifiers = _split_input_list(identifiers_raw)
767 768
    email_students = _get_boolean_param(request, 'email_students')
    auto_enroll = _get_boolean_param(request, 'auto_enroll')
769 770 771
    results = []
    rolename = 'beta'
    course = get_course_by_id(course_id)
772 773 774

    email_params = {}
    if email_students:
775 776
        secure = request.is_secure()
        email_params = get_email_params(course, auto_enroll=auto_enroll, secure=secure)
777

778
    for identifier in identifiers:
779
        try:
780 781
            error = False
            user_does_not_exist = False
782
            user = get_student_from_identifier(identifier)
783
            user_active = user.is_active
784

785 786 787 788 789 790 791 792
            if action == 'add':
                allow_access(course, user, rolename)
            elif action == 'remove':
                revoke_access(course, user, rolename)
            else:
                return HttpResponseBadRequest(strip_tags(
                    "Unrecognized action '{}'".format(action)
                ))
793 794 795
        except User.DoesNotExist:
            error = True
            user_does_not_exist = True
796
            user_active = None
797
        # catch and log any unexpected exceptions
798
        # so that one error doesn't cause a 500.
799
        except Exception as exc:  # pylint: disable=broad-except
800
            log.exception(u"Error while #{}ing student")
801
            log.exception(exc)
802 803 804 805 806
            error = True
        else:
            # If no exception thrown, see if we should send an email
            if email_students:
                send_beta_role_email(action, user, email_params)
807 808 809 810 811 812
            # See if we should autoenroll the student
            if auto_enroll:
                # Check if student is already enrolled
                if not CourseEnrollment.is_enrolled(user, course_id):
                    CourseEnrollment.enroll(user, course_id)

813 814
        finally:
            # Tabulate the action result of this email address
815
            results.append({
816
                'identifier': identifier,
817
                'error': error,
818 819
                'userDoesNotExist': user_does_not_exist,
                'is_active': user_active
820 821 822 823 824 825 826 827 828
            })

    response_payload = {
        'action': action,
        'results': results,
    }
    return JsonResponse(response_payload)


829
@require_POST
830 831 832
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('instructor')
833
@require_post_params(
834
    unique_student_identifier="email or username of user to change access",
cewing committed
835
    rolename="'instructor', 'staff', 'beta', or 'ccx_coach'",
836
    action="'allow' or 'revoke'"
837
)
838
@common_exceptions_400
839
def modify_access(request, course_id):
840
    """
841
    Modify staff/instructor access of other user.
842
    Requires instructor access.
843

844 845
    NOTE: instructors cannot remove their own instructor access.

846
    Query parameters:
847
    unique_student_identifer is the target user's username or email
cewing committed
848
    rolename is one of ['instructor', 'staff', 'beta', 'ccx_coach']
849
    action is one of ['allow', 'revoke']
850
    """
851
    course_id = CourseKey.from_string(course_id)
852
    course = get_course_with_access(
853
        request.user, 'instructor', course_id, depth=None
854
    )
855
    try:
856
        user = get_student_from_identifier(request.POST.get('unique_student_identifier'))
857 858
    except User.DoesNotExist:
        response_payload = {
859
            'unique_student_identifier': request.POST.get('unique_student_identifier'),
860 861 862 863 864 865 866 867 868 869 870 871 872
            'userDoesNotExist': True,
        }
        return JsonResponse(response_payload)

    # Check that user is active, because add_users
    # in common/djangoapps/student/roles.py fails
    # silently when we try to add an inactive user.
    if not user.is_active:
        response_payload = {
            'unique_student_identifier': user.username,
            'inactiveUser': True,
        }
        return JsonResponse(response_payload)
873

874 875
    rolename = request.POST.get('rolename')
    action = request.POST.get('action')
876

877
    if rolename not in ROLES:
878 879 880
        error = strip_tags("unknown rolename '{}'".format(rolename))
        log.error(error)
        return HttpResponseBadRequest(error)
881

882 883
    # disallow instructors from removing their own instructor access.
    if rolename == 'instructor' and user == request.user and action != 'allow':
884 885 886 887 888 889 890
        response_payload = {
            'unique_student_identifier': user.username,
            'rolename': rolename,
            'action': action,
            'removingSelfAsInstructor': True,
        }
        return JsonResponse(response_payload)
891 892

    if action == 'allow':
893
        allow_access(course, user, rolename)
894
    elif action == 'revoke':
895
        revoke_access(course, user, rolename)
896
    else:
897 898 899
        return HttpResponseBadRequest(strip_tags(
            "unrecognized action '{}'".format(action)
        ))
900 901

    response_payload = {
902
        'unique_student_identifier': user.username,
903
        'rolename': rolename,
904
        'action': action,
905
        'success': 'yes',
906
    }
907
    return JsonResponse(response_payload)
908 909


910
@require_POST
911 912
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
913
@require_level('instructor')
914
@require_post_params(rolename="'instructor', 'staff', or 'beta'")
915
def list_course_role_members(request, course_id):
916 917
    """
    List instructors and staff.
918
    Requires instructor access.
Miles Steele committed
919

cewing committed
920
    rolename is one of ['instructor', 'staff', 'beta', 'ccx_coach']
921 922 923 924 925 926 927 928 929 930 931 932

    Returns JSON of the form {
        "course_id": "some/course/id",
        "staff": [
            {
                "username": "staff1",
                "email": "staff1@example.org",
                "first_name": "Joe",
                "last_name": "Shmoe",
            }
        ]
    }
933
    """
934
    course_id = CourseKey.from_string(course_id)
935
    course = get_course_with_access(
936
        request.user, 'instructor', course_id, depth=None
937
    )
938

939
    rolename = request.POST.get('rolename')
Miles Steele committed
940

941
    if rolename not in ROLES:
Miles Steele committed
942 943 944
        return HttpResponseBadRequest()

    def extract_user_info(user):
945
        """ convert user into dicts for json view """
946

947 948 949 950 951 952 953 954
        return {
            'username': user.username,
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name,
        }

    response_payload = {
955
        'course_id': course_id.to_deprecated_string(),
956
        rolename: map(extract_user_info, list_with_level(
957 958
            course, rolename
        )),
959
    }
960
    return JsonResponse(response_payload)
961 962


963
@transaction.non_atomic_requests
964
@require_POST
965 966
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
967
@require_level('staff')
968
@common_exceptions_400
969 970 971 972 973 974 975 976 977 978 979 980 981
def get_problem_responses(request, course_id):
    """
    Initiate generation of a CSV file containing all student answers
    to a given problem.

    Responds with JSON
        {"status": "... status message ..."}

    if initiation is successful (or generation task is already running).

    Responds with BadRequest if problem location is faulty.
    """
    course_key = CourseKey.from_string(course_id)
982
    problem_location = request.POST.get('problem_location', '')
983
    report_type = _('problem responses')
984 985 986 987

    try:
        problem_key = UsageKey.from_string(problem_location)
        # Are we dealing with an "old-style" problem location?
988
        run = problem_key.run
989
        if not run:
990
            problem_key = UsageKey.from_string(problem_location).map_into_course(course_key)
991 992 993 994 995
        if problem_key.course_key != course_key:
            raise InvalidKeyError(type(problem_key), problem_key)
    except InvalidKeyError:
        return JsonResponseBadRequest(_("Could not find problem with this location."))

996 997 998 999
    lms.djangoapps.instructor_task.api.submit_calculate_problem_responses_csv(request, course_key, problem_location)
    success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)

    return JsonResponse({"status": success_status})
1000 1001


1002
@require_POST
1003 1004 1005
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
1006
def get_grading_config(request, course_id):
1007 1008 1009
    """
    Respond with json which contains a html formatted grade summary.
    """
1010
    course_id = CourseKey.from_string(course_id)
1011
    course = get_course_with_access(
1012
        request.user, 'staff', course_id, depth=None
1013
    )
1014
    grading_config_summary = instructor_analytics.basic.dump_grading_context(course)
1015 1016

    response_payload = {
1017
        'course_id': course_id.to_deprecated_string(),
1018 1019
        'grading_config_summary': grading_config_summary,
    }
1020
    return JsonResponse(response_payload)
1021 1022 1023 1024


@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
1025
@require_level('staff')
1026
def get_sale_records(request, course_id, csv=False):  # pylint: disable=unused-argument, redefined-outer-name
1027 1028 1029
    """
    return the summary of all sales records for a particular course
    """
1030
    course_id = CourseKey.from_string(course_id)
1031 1032
    query_features = [
        'company_name', 'company_contact_name', 'company_contact_email', 'total_codes', 'total_used_codes',
1033
        'total_amount', 'created', 'customer_reference_number', 'recipient_name', 'recipient_email', 'created_by',
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        'internal_reference', 'invoice_number', 'codes', 'course_id'
    ]

    sale_data = instructor_analytics.basic.sale_record_features(course_id, query_features)

    if not csv:
        for item in sale_data:
            item['created_by'] = item['created_by'].username

        response_payload = {
            'course_id': course_id.to_deprecated_string(),
            'sale': sale_data,
            'queried_features': query_features
        }
        return JsonResponse(response_payload)
    else:
        header, datarows = instructor_analytics.csvs.format_dictlist(sale_data, query_features)
1051 1052 1053 1054 1055 1056
        return instructor_analytics.csvs.create_csv_response("e-commerce_sale_invoice_records.csv", header, datarows)


@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
1057
def get_sale_order_records(request, course_id):  # pylint: disable=unused-argument
1058 1059 1060
    """
    return the summary of all sales records for a particular course
    """
1061
    course_id = CourseKey.from_string(course_id)
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    query_features = [
        ('id', 'Order Id'),
        ('company_name', 'Company Name'),
        ('company_contact_name', 'Company Contact Name'),
        ('company_contact_email', 'Company Contact Email'),
        ('logged_in_username', 'Login Username'),
        ('logged_in_email', 'Login User Email'),
        ('purchase_time', 'Date of Sale'),
        ('customer_reference_number', 'Customer Reference Number'),
        ('recipient_name', 'Recipient Name'),
        ('recipient_email', 'Recipient Email'),
        ('bill_to_street1', 'Street 1'),
        ('bill_to_street2', 'Street 2'),
        ('bill_to_city', 'City'),
        ('bill_to_state', 'State'),
        ('bill_to_postalcode', 'Postal Code'),
        ('bill_to_country', 'Country'),
        ('order_type', 'Order Type'),
1080 1081 1082
        ('status', 'Order Item Status'),
        ('coupon_code', 'Coupon Code'),
        ('list_price', 'List Price'),
1083 1084 1085 1086
        ('unit_cost', 'Unit Price'),
        ('quantity', 'Quantity'),
        ('total_discount', 'Total Discount'),
        ('total_amount', 'Total Amount Paid'),
1087 1088 1089 1090 1091
    ]

    db_columns = [x[0] for x in query_features]
    csv_columns = [x[1] for x in query_features]
    sale_data = instructor_analytics.basic.sale_order_record_features(course_id, db_columns)
1092
    __, datarows = instructor_analytics.csvs.format_dictlist(sale_data, db_columns)
1093
    return instructor_analytics.csvs.create_csv_response("e-commerce_sale_order_records.csv", csv_columns, datarows)
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118


@require_level('staff')
@require_POST
def sale_validation(request, course_id):
    """
    This method either invalidate or re validate the sale against the invoice number depending upon the event type
    """
    try:
        invoice_number = request.POST["invoice_number"]
    except KeyError:
        return HttpResponseBadRequest("Missing required invoice_number parameter")
    try:
        invoice_number = int(invoice_number)
    except ValueError:
        return HttpResponseBadRequest(
            "invoice_number must be an integer, {value} provided".format(
                value=invoice_number
            )
        )
    try:
        event_type = request.POST["event_type"]
    except KeyError:
        return HttpResponseBadRequest("Missing required event_type parameter")

1119
    course_id = CourseKey.from_string(course_id)
1120
    try:
1121 1122 1123 1124 1125 1126
        obj_invoice = CourseRegistrationCodeInvoiceItem.objects.select_related('invoice').get(
            invoice_id=invoice_number,
            course_id=course_id
        )
        obj_invoice = obj_invoice.invoice
    except CourseRegistrationCodeInvoiceItem.DoesNotExist:  # Check for old type invoices
1127
        return HttpResponseNotFound(_("Invoice number '{num}' does not exist.").format(num=invoice_number))
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159

    if event_type == "invalidate":
        return invalidate_invoice(obj_invoice)
    else:
        return re_validate_invoice(obj_invoice)


def invalidate_invoice(obj_invoice):
    """
    This method invalidate the sale against the invoice number
    """
    if not obj_invoice.is_valid:
        return HttpResponseBadRequest(_("The sale associated with this invoice has already been invalidated."))
    obj_invoice.is_valid = False
    obj_invoice.save()
    message = _('Invoice number {0} has been invalidated.').format(obj_invoice.id)
    return JsonResponse({'message': message})


def re_validate_invoice(obj_invoice):
    """
    This method re-validate the sale against the invoice number
    """
    if obj_invoice.is_valid:
        return HttpResponseBadRequest(_("This invoice is already active."))

    obj_invoice.is_valid = True
    obj_invoice.save()
    message = _('The registration codes for invoice {0} have been re-activated.').format(obj_invoice.id)
    return JsonResponse({'message': message})


1160
@transaction.non_atomic_requests
1161 1162 1163
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
1164
def get_issued_certificates(request, course_id):
asadiqbal committed
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    """
    Responds with JSON if CSV is not required. contains a list of issued certificates.
    Arguments:
        course_id
    Returns:
        {"certificates": [{course_id: xyz, mode: 'honor'}, ...]}

    """
    course_key = CourseKey.from_string(course_id)
    csv_required = request.GET.get('csv', 'false')

    query_features = ['course_id', 'mode', 'total_issued_certificate', 'report_run_date']
    query_features_names = [
        ('course_id', _('CourseID')),
        ('mode', _('Certificate Type')),
        ('total_issued_certificate', _('Total Certificates Issued')),
        ('report_run_date', _('Date Report Run'))
    ]
    certificates_data = instructor_analytics.basic.issued_certificates(course_key, query_features)
    if csv_required.lower() == 'true':
        __, data_rows = instructor_analytics.csvs.format_dictlist(certificates_data, query_features)
        return instructor_analytics.csvs.create_csv_response(
            'issued_certificates.csv',
            [col_header for __, col_header in query_features_names],
            data_rows
        )
    else:
        response_payload = {
            'certificates': certificates_data,
            'queried_features': query_features,
            'feature_names': dict(query_features_names)
        }
        return JsonResponse(response_payload)


1200
@transaction.non_atomic_requests
1201
@require_POST
asadiqbal committed
1202 1203 1204
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
1205
@common_exceptions_400
1206
def get_students_features(request, course_id, csv=False):  # pylint: disable=redefined-outer-name
1207 1208 1209
    """
    Respond with json which contains a summary of all enrolled students profile information.

1210 1211
    Responds with JSON
        {"students": [{-student-info-}, ...]}
1212

Miles Steele committed
1213
    TO DO accept requests for different attribute sets.
1214
    """
1215 1216
    course_key = CourseKey.from_string(course_id)
    course = get_course_by_id(course_key)
1217
    report_type = _('enrolled learner profile')
1218
    available_features = instructor_analytics.basic.AVAILABLE_FEATURES
1219

1220
    # Allow for sites to be able to define additional columns.
1221 1222 1223 1224 1225 1226 1227
    # Note that adding additional columns has the potential to break
    # the student profile report due to a character limit on the
    # asynchronous job input which in this case is a JSON string
    # containing the list of columns to include in the report.
    # TODO: Refactor the student profile report code to remove the list of columns
    # that should be included in the report from the asynchronous job input.
    # We need to clone the list because we modify it below
1228
    query_features = list(configuration_helpers.get_value('student_profile_download_fields', []))
1229 1230 1231 1232 1233

    if not query_features:
        query_features = [
            'id', 'username', 'name', 'email', 'language', 'location',
            'year_of_birth', 'gender', 'level_of_education', 'mailing_address',
1234
            'goals', 'enrollment_mode', 'verification_status',
1235
        ]
1236

1237 1238 1239
    # Provide human-friendly and translatable names for these features. These names
    # will be displayed in the table generated in data_download.coffee. It is not (yet)
    # used as the header row in the CSV, but could be in the future.
1240
    query_features_names = {
1241
        'id': _('User ID'),
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
        'username': _('Username'),
        'name': _('Name'),
        'email': _('Email'),
        'language': _('Language'),
        'location': _('Location'),
        'year_of_birth': _('Birth Year'),
        'gender': _('Gender'),
        'level_of_education': _('Level of Education'),
        'mailing_address': _('Mailing Address'),
        'goals': _('Goals'),
1252 1253
        'enrollment_mode': _('Enrollment Mode'),
        'verification_status': _('Verification Status'),
1254 1255
    }

1256
    if is_course_cohorted(course.id):
1257 1258 1259 1260
        # Translators: 'Cohort' refers to a group of students within a course.
        query_features.append('cohort')
        query_features_names['cohort'] = _('Cohort')

1261 1262 1263 1264
    if course.teams_enabled:
        query_features.append('team')
        query_features_names['team'] = _('Team')

1265 1266 1267 1268 1269 1270
    # For compatibility reasons, city and country should always appear last.
    query_features.append('city')
    query_features_names['city'] = _('City')
    query_features.append('country')
    query_features_names['country'] = _('Country')

1271
    if not csv:
1272
        student_data = instructor_analytics.basic.enrolled_students_features(course_key, query_features)
1273
        response_payload = {
1274
            'course_id': unicode(course_key),
1275 1276 1277
            'students': student_data,
            'students_count': len(student_data),
            'queried_features': query_features,
1278
            'feature_names': query_features_names,
1279
            'available_features': available_features,
1280
        }
1281
        return JsonResponse(response_payload)
1282

1283
    else:
1284 1285 1286 1287 1288 1289 1290 1291
        lms.djangoapps.instructor_task.api.submit_calculate_students_features_csv(
            request,
            course_key,
            query_features
        )
        success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)

        return JsonResponse({"status": success_status})
1292 1293


1294
@transaction.non_atomic_requests
1295
@require_POST
1296 1297
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
1298
@require_level('staff')
1299
@common_exceptions_400
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
def get_students_who_may_enroll(request, course_id):
    """
    Initiate generation of a CSV file containing information about
    students who may enroll in a course.

    Responds with JSON
        {"status": "... status message ..."}

    """
    course_key = CourseKey.from_string(course_id)
    query_features = ['email']
1311 1312 1313 1314 1315
    report_type = _('enrollment')
    lms.djangoapps.instructor_task.api.submit_calculate_may_enroll_csv(request, course_key, query_features)
    success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)

    return JsonResponse({"status": success_status})
1316 1317


1318
@transaction.non_atomic_requests
1319 1320
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
1321 1322
@require_POST
@require_level('staff')
1323
@common_exceptions_400
1324 1325 1326 1327 1328 1329
def add_users_to_cohorts(request, course_id):
    """
    View method that accepts an uploaded file (using key "uploaded-file")
    containing cohort assignments for users. This method spawns a celery task
    to do the assignments, and a CSV file with results is provided via data downloads.
    """
1330
    course_key = CourseKey.from_string(course_id)
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357

    try:
        def validator(file_storage, file_to_validate):
            """
            Verifies that the expected columns are present.
            """
            with file_storage.open(file_to_validate) as f:
                reader = unicodecsv.reader(UniversalNewlineIterator(f), encoding='utf-8')
                try:
                    fieldnames = next(reader)
                except StopIteration:
                    fieldnames = []
                msg = None
                if "cohort" not in fieldnames:
                    msg = _("The file must contain a 'cohort' column containing cohort names.")
                elif "email" not in fieldnames and "username" not in fieldnames:
                    msg = _("The file must contain a 'username' column, an 'email' column, or both.")
                if msg:
                    raise FileValidationException(msg)

        __, filename = store_uploaded_file(
            request, 'uploaded-file', ['.csv'],
            course_and_time_based_filename_generator(course_key, "cohorts"),
            max_file_size=2000000,  # limit to 2 MB
            validator=validator
        )
        # The task will assume the default file storage.
1358
        lms.djangoapps.instructor_task.api.submit_cohort_students(request, course_key, filename)
1359 1360 1361 1362 1363 1364 1365 1366
    except (FileValidationException, PermissionDenied) as err:
        return JsonResponse({"error": unicode(err)}, status=400)

    return JsonResponse()


@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
1367
@require_level('staff')
1368
def get_coupon_codes(request, course_id):  # pylint: disable=unused-argument
1369 1370 1371
    """
    Respond with csv which contains a summary of all Active Coupons.
    """
1372
    course_id = CourseKey.from_string(course_id)
1373 1374
    coupons = Coupon.objects.filter(course_id=course_id)

1375
    query_features = [
1376 1377 1378 1379 1380 1381 1382 1383 1384
        ('code', _('Coupon Code')),
        ('course_id', _('Course Id')),
        ('percentage_discount', _('% Discount')),
        ('description', _('Description')),
        ('expiration_date', _('Expiration Date')),
        ('is_active', _('Is Active')),
        ('code_redeemed_count', _('Code Redeemed Count')),
        ('total_discounted_seats', _('Total Discounted Seats')),
        ('total_discounted_amount', _('Total Discounted Amount')),
1385
    ]
1386 1387 1388 1389 1390 1391
    db_columns = [x[0] for x in query_features]
    csv_columns = [x[1] for x in query_features]

    coupons_list = instructor_analytics.basic.coupon_codes_features(db_columns, coupons, course_id)
    __, data_rows = instructor_analytics.csvs.format_dictlist(coupons_list, db_columns)
    return instructor_analytics.csvs.create_csv_response('Coupons.csv', csv_columns, data_rows)
1392 1393


1394
@transaction.non_atomic_requests
1395
@require_POST
1396 1397 1398 1399
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
@require_finance_admin
1400
@common_exceptions_400
1401 1402 1403 1404
def get_enrollment_report(request, course_id):
    """
    get the enrollment report for the particular course.
    """
1405
    course_key = CourseKey.from_string(course_id)
1406 1407 1408 1409 1410
    report_type = _('detailed enrollment')
    lms.djangoapps.instructor_task.api.submit_detailed_enrollment_features_csv(request, course_key)
    success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)

    return JsonResponse({"status": success_status})
1411 1412


1413
@transaction.non_atomic_requests
1414
@require_POST
Afzal Wali committed
1415 1416 1417 1418
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
@require_finance_admin
1419
@common_exceptions_400
Afzal Wali committed
1420 1421 1422 1423
def get_exec_summary_report(request, course_id):
    """
    get the executive summary report for the particular course.
    """
1424
    course_key = CourseKey.from_string(course_id)
1425 1426 1427 1428 1429
    report_type = _('executive summary')
    lms.djangoapps.instructor_task.api.submit_executive_summary_report(request, course_key)
    success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)

    return JsonResponse({"status": success_status})
1430 1431


1432
@transaction.non_atomic_requests
1433
@require_POST
1434 1435
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
1436
@require_level('staff')
1437
@common_exceptions_400
1438 1439 1440 1441
def get_course_survey_results(request, course_id):
    """
    get the survey results report for the particular course.
    """
1442
    course_key = CourseKey.from_string(course_id)
1443 1444 1445 1446 1447
    report_type = _('survey')
    lms.djangoapps.instructor_task.api.submit_course_survey_report(request, course_key)
    success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)

    return JsonResponse({"status": success_status})
1448 1449


1450
@transaction.non_atomic_requests
1451
@require_POST
1452 1453
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
1454
@require_level('staff')
1455
@common_exceptions_400
1456 1457 1458 1459 1460
def get_proctored_exam_results(request, course_id):
    """
    get the proctored exam resultsreport for the particular course.
    """
    course_key = CourseKey.from_string(course_id)
1461
    report_type = _('proctored exam results')
1462
    lms.djangoapps.instructor_task.api.submit_proctored_exam_results_report(request, course_key)
1463 1464 1465
    success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)

    return JsonResponse({"status": success_status})
Afzal Wali committed
1466 1467


1468
def save_registration_code(user, course_id, mode_slug, invoice=None, order=None, invoice_item=None):
1469 1470 1471
    """
    recursive function that generate a new code every time and saves in the Course Registration Table
    if validation check passes
stephensanchez committed
1472 1473 1474 1475 1476 1477 1478

    Args:
        user (User): The user creating the course registration codes.
        course_id (str): The string representation of the course ID.
        mode_slug (str): The Course Mode Slug associated with any enrollment made by these codes.
        invoice (Invoice): (Optional) The associated invoice for this code.
        order (Order): (Optional) The associated order for this code.
1479
        invoice_item (CourseRegistrationCodeInvoiceItem) : (Optional) The associated CourseRegistrationCodeInvoiceItem
stephensanchez committed
1480 1481 1482 1483

    Returns:
        The newly created CourseRegistrationCode.

1484 1485 1486 1487 1488 1489
    """
    code = random_code_generator()

    # check if the generated code is in the Coupon Table
    matching_coupons = Coupon.objects.filter(code=code, is_active=True)
    if matching_coupons:
1490 1491 1492
        return save_registration_code(
            user, course_id, mode_slug, invoice=invoice, order=order, invoice_item=invoice_item
        )
1493 1494

    course_registration = CourseRegistrationCode(
1495
        code=code,
stephensanchez committed
1496
        course_id=unicode(course_id),
1497 1498
        created_by=user,
        invoice=invoice,
stephensanchez committed
1499
        order=order,
1500 1501
        mode_slug=mode_slug,
        invoice_item=invoice_item
1502 1503
    )
    try:
1504 1505
        with transaction.atomic():
            course_registration.save()
1506
        return course_registration
1507
    except IntegrityError:
1508 1509 1510
        return save_registration_code(
            user, course_id, mode_slug, invoice=invoice, order=order, invoice_item=invoice_item
        )
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521


def registration_codes_csv(file_name, codes_list, csv_type=None):
    """
    Respond with the csv headers and data rows
    given a dict of codes list
    :param file_name:
    :param codes_list:
    :param csv_type:
    """
    # csv headers
1522
    query_features = [
1523
        'code', 'redeem_code_url', 'course_id', 'company_name', 'created_by',
1524
        'redeemed_by', 'invoice_id', 'purchaser', 'customer_reference_number', 'internal_reference', 'is_valid'
1525
    ]
1526 1527 1528

    registration_codes = instructor_analytics.basic.course_registration_features(query_features, codes_list, csv_type)
    header, data_rows = instructor_analytics.csvs.format_dictlist(registration_codes, query_features)
1529
    return instructor_analytics.csvs.create_csv_response(file_name, header, data_rows)
1530 1531 1532 1533 1534 1535 1536 1537


def random_code_generator():
    """
    generate a random alphanumeric code of length defined in
    REGISTRATION_CODE_LENGTH settings
    """
    code_length = getattr(settings, 'REGISTRATION_CODE_LENGTH', 8)
asadiqbal08 committed
1538
    return generate_random_string(code_length)
1539 1540 1541 1542 1543 1544


@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
@require_POST
1545
def get_registration_codes(request, course_id):
1546 1547 1548
    """
    Respond with csv which contains a summary of all Registration Codes.
    """
1549
    course_id = CourseKey.from_string(course_id)
1550 1551

    #filter all the  course registration codes
1552 1553 1554
    registration_codes = CourseRegistrationCode.objects.filter(
        course_id=course_id
    ).order_by('invoice_item__invoice__company_name')
1555

1556 1557
    company_name = request.POST['download_company_name']
    if company_name:
1558
        registration_codes = registration_codes.filter(invoice_item__invoice__company_name=company_name)
1559 1560 1561 1562 1563 1564 1565

    csv_type = 'download'
    return registration_codes_csv("Registration_Codes.csv", registration_codes, csv_type)


@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
stephensanchez committed
1566
@require_sales_admin
1567 1568 1569 1570 1571
@require_POST
def generate_registration_codes(request, course_id):
    """
    Respond with csv which contains a summary of all Generated Codes.
    """
stephensanchez committed
1572
    course_id = CourseKey.from_string(course_id)
1573
    invoice_copy = False
1574 1575 1576

    # covert the course registration code number into integer
    try:
1577
        course_code_number = int(request.POST['total_registration_codes'])
1578
    except ValueError:
1579 1580 1581 1582 1583
        course_code_number = int(float(request.POST['total_registration_codes']))

    company_name = request.POST['company_name']
    company_contact_name = request.POST['company_contact_name']
    company_contact_email = request.POST['company_contact_email']
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
    unit_price = request.POST['unit_price']

    try:
        unit_price = (
            decimal.Decimal(unit_price)
        ).quantize(
            decimal.Decimal('.01'),
            rounding=decimal.ROUND_DOWN
        )
    except decimal.InvalidOperation:
        return HttpResponse(
            status=400,
            content=_(u"Could not parse amount as a decimal")
        )

1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
    recipient_name = request.POST['recipient_name']
    recipient_email = request.POST['recipient_email']
    address_line_1 = request.POST['address_line_1']
    address_line_2 = request.POST['address_line_2']
    address_line_3 = request.POST['address_line_3']
    city = request.POST['city']
    state = request.POST['state']
    zip_code = request.POST['zip']
    country = request.POST['country']
    internal_reference = request.POST['internal_reference']
    customer_reference_number = request.POST['customer_reference_number']
    recipient_list = [recipient_email]
    if request.POST.get('invoice', False):
        recipient_list.append(request.user.email)
        invoice_copy = True

1615
    sale_price = unit_price * course_code_number
1616
    set_user_preference(request.user, INVOICE_KEY, invoice_copy)
1617
    sale_invoice = Invoice.objects.create(
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
        total_amount=sale_price,
        company_name=company_name,
        company_contact_email=company_contact_email,
        company_contact_name=company_contact_name,
        course_id=course_id,
        recipient_name=recipient_name,
        recipient_email=recipient_email,
        address_line_1=address_line_1,
        address_line_2=address_line_2,
        address_line_3=address_line_3,
        city=city,
        state=state,
        zip=zip_code,
        country=country,
        internal_reference=internal_reference,
        customer_reference_number=customer_reference_number
1634
    )
stephensanchez committed
1635

1636 1637 1638 1639 1640 1641 1642
    invoice_item = CourseRegistrationCodeInvoiceItem.objects.create(
        invoice=sale_invoice,
        qty=course_code_number,
        unit_price=unit_price,
        course_id=course_id
    )

stephensanchez committed
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
    course = get_course_by_id(course_id, depth=0)
    paid_modes = CourseMode.paid_modes_for_course(course_id)

    if len(paid_modes) != 1:
        msg = (
            u"Generating Code Redeem Codes for Course '{course_id}', which must have a single paid course mode. "
            u"This is a configuration issue. Current course modes with payment options: {paid_modes}"
        ).format(course_id=course_id, paid_modes=paid_modes)
        log.error(msg)
        return HttpResponse(
            status=500,
            content=_(u"Unable to generate redeem codes because of course misconfiguration.")
        )

    course_mode = paid_modes[0]
    course_price = course_mode.min_price

1660
    registration_codes = []
1661
    for __ in range(course_code_number):
stephensanchez committed
1662
        generated_registration_code = save_registration_code(
1663
            request.user, course_id, course_mode.slug, invoice=sale_invoice, order=None, invoice_item=invoice_item
stephensanchez committed
1664
        )
1665
        registration_codes.append(generated_registration_code)
1666

1667
    site_name = configuration_helpers.get_value('SITE_NAME', 'localhost')
1668
    quantity = course_code_number
1669
    discount = (float(quantity * course_price) - float(sale_price))
1670
    course_url = '{base_url}{course_about}'.format(
1671
        base_url=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME),
1672 1673
        course_about=reverse('about_course', kwargs={'course_id': course_id.to_deprecated_string()})
    )
1674
    dashboard_url = '{base_url}{dashboard}'.format(
1675
        base_url=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME),
1676 1677 1678
        dashboard=reverse('dashboard')
    )

1679 1680 1681 1682 1683 1684
    try:
        pdf_file = sale_invoice.generate_pdf_invoice(course, course_price, int(quantity), float(sale_price))
    except Exception:  # pylint: disable=broad-except
        log.exception('Exception at creating pdf file.')
        pdf_file = None

1685
    from_address = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)
1686 1687 1688 1689 1690
    context = {
        'invoice': sale_invoice,
        'site_name': site_name,
        'course': course,
        'course_price': course_price,
1691 1692
        'sub_total': course_price * quantity,
        'discount': discount,
1693 1694
        'sale_price': sale_price,
        'quantity': quantity,
1695
        'registration_codes': registration_codes,
1696
        'currency_symbol': settings.PAID_COURSE_REGISTRATION_CURRENCY[1],
1697
        'course_url': course_url,
1698
        'platform_name': configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME),
1699 1700
        'dashboard_url': dashboard_url,
        'contact_email': from_address,
1701 1702 1703 1704 1705
        'corp_address': configuration_helpers.get_value('invoice_corp_address', settings.INVOICE_CORP_ADDRESS),
        'payment_instructions': configuration_helpers.get_value(
            'invoice_payment_instructions',
            settings. INVOICE_PAYMENT_INSTRUCTIONS,
        ),
1706
        'date': time.strftime("%m/%d/%Y")
1707 1708
    }
    # composes registration codes invoice email
1709 1710 1711 1712
    subject = u'Confirmation and Invoice for {course_name}'.format(course_name=course.display_name)
    message = render_to_string('emails/registration_codes_sale_email.txt', context)

    invoice_attachment = render_to_string('emails/registration_codes_sale_invoice_attachment.txt', context)
1713 1714 1715 1716

    #send_mail(subject, message, from_address, recipient_list, fail_silently=False)
    csv_file = StringIO.StringIO()
    csv_writer = csv.writer(csv_file)
1717
    for registration_code in registration_codes:
1718
        full_redeem_code_url = 'http://{base_url}{redeem_code_url}'.format(
1719
            base_url=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME),
1720 1721 1722
            redeem_code_url=reverse('register_code_redemption', kwargs={'registration_code': registration_code.code})
        )
        csv_writer.writerow([registration_code.code, full_redeem_code_url])
1723
    finance_email = configuration_helpers.get_value('finance_email', settings.FINANCE_EMAIL)
1724 1725 1726 1727
    if finance_email:
        # append the finance email into the recipient_list
        recipient_list.append(finance_email)

1728 1729 1730 1731 1732 1733 1734 1735
    # send a unique email for each recipient, don't put all email addresses in a single email
    for recipient in recipient_list:
        email = EmailMessage()
        email.subject = subject
        email.body = message
        email.from_email = from_address
        email.to = [recipient]
        email.attach(u'RegistrationCodes.csv', csv_file.getvalue(), 'text/csv')
1736
        email.attach(u'Invoice.txt', invoice_attachment, 'text/plain')
1737 1738 1739 1740 1741
        if pdf_file is not None:
            email.attach(u'Invoice.pdf', pdf_file.getvalue(), 'application/pdf')
        else:
            file_buffer = StringIO.StringIO(_('pdf download unavailable right now, please contact support.'))
            email.attach(u'pdf_unavailable.txt', file_buffer.getvalue(), 'text/plain')
1742
        email.send()
1743

1744
    return registration_codes_csv("Registration_Codes.csv", registration_codes)
1745 1746 1747 1748 1749 1750


@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
@require_POST
1751
def active_registration_codes(request, course_id):
1752 1753 1754
    """
    Respond with csv which contains a summary of all Active Registration Codes.
    """
1755
    course_id = CourseKey.from_string(course_id)
1756 1757

    # find all the registration codes in this course
1758 1759 1760
    registration_codes_list = CourseRegistrationCode.objects.filter(
        course_id=course_id
    ).order_by('invoice_item__invoice__company_name')
1761

1762 1763
    company_name = request.POST['active_company_name']
    if company_name:
1764
        registration_codes_list = registration_codes_list.filter(invoice_item__invoice__company_name=company_name)
1765
    # find the redeemed registration codes if any exist in the db
1766 1767 1768
    code_redemption_set = RegistrationCodeRedemption.objects.select_related(
        'registration_code', 'registration_code__invoice_item__invoice'
    ).filter(registration_code__course_id=course_id)
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
    if code_redemption_set.exists():
        redeemed_registration_codes = [code.registration_code.code for code in code_redemption_set]
        # exclude the redeemed registration codes from the registration codes list and you will get
        # all the registration codes that are active
        registration_codes_list = registration_codes_list.exclude(code__in=redeemed_registration_codes)

    return registration_codes_csv("Active_Registration_Codes.csv", registration_codes_list)


@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
@require_POST
1782
def spent_registration_codes(request, course_id):
1783 1784 1785
    """
    Respond with csv which contains a summary of all Spent(used) Registration Codes.
    """
1786
    course_id = CourseKey.from_string(course_id)
1787 1788

    # find the redeemed registration codes if any exist in the db
1789 1790 1791
    code_redemption_set = RegistrationCodeRedemption.objects.select_related('registration_code').filter(
        registration_code__course_id=course_id
    )
1792 1793 1794 1795 1796
    spent_codes_list = []
    if code_redemption_set.exists():
        redeemed_registration_codes = [code.registration_code.code for code in code_redemption_set]
        # filter the Registration Codes by course id and the redeemed codes and
        # you will get a list of all the spent(Redeemed) Registration Codes
1797 1798
        spent_codes_list = CourseRegistrationCode.objects.filter(
            course_id=course_id, code__in=redeemed_registration_codes
1799
        ).order_by('invoice_item__invoice__company_name').select_related('invoice_item__invoice')
1800

1801 1802
        company_name = request.POST['spent_company_name']
        if company_name:
1803
            spent_codes_list = spent_codes_list.filter(invoice_item__invoice__company_name=company_name)  # pylint: disable=maybe-no-member
1804 1805 1806 1807 1808

    csv_type = 'spent'
    return registration_codes_csv("Spent_Registration_Codes.csv", spent_codes_list, csv_type)


1809 1810
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
1811
@require_level('staff')
1812
def get_anon_ids(request, course_id):  # pylint: disable=unused-argument
1813 1814 1815 1816
    """
    Respond with 2-column CSV output of user-id, anonymized-user-id
    """
    # TODO: the User.objects query and CSV generation here could be
1817
    # centralized into instructor_analytics. Currently instructor_analytics
1818
    # has similar functionality but not quite what's needed.
1819
    course_id = CourseKey.from_string(course_id)
1820

1821 1822
    def csv_response(filename, header, rows):
        """Returns a CSV http response for the given header and rows (excel/utf-8)."""
1823
        response = HttpResponse(content_type='text/csv')
Abdallah committed
1824
        response['Content-Disposition'] = 'attachment; filename={0}'.format(unicode(filename).encode('utf-8'))
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
        writer = csv.writer(response, dialect='excel', quotechar='"', quoting=csv.QUOTE_ALL)
        # In practice, there should not be non-ascii data in this query,
        # but trying to do the right thing anyway.
        encoded = [unicode(s).encode('utf-8') for s in header]
        writer.writerow(encoded)
        for row in rows:
            encoded = [unicode(s).encode('utf-8') for s in row]
            writer.writerow(encoded)
        return response

    students = User.objects.filter(
        courseenrollment__course_id=course_id,
    ).order_by('id')
1838 1839
    header = ['User ID', 'Anonymized User ID', 'Course Specific Anonymized User ID']
    rows = [[s.id, unique_id_for_user(s, save=False), anonymous_id_for_user(s, course_id, save=False)] for s in students]
Calen Pennington committed
1840
    return csv_response(course_id.to_deprecated_string().replace('/', '-') + '-anon-ids.csv', header, rows)
1841 1842


1843
@require_POST
1844 1845
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
1846
@require_level('staff')
1847
@require_post_params(
1848
    unique_student_identifier="email or username of student for whom to get progress url"
1849
)
1850
@common_exceptions_400
1851 1852 1853 1854 1855
def get_student_progress_url(request, course_id):
    """
    Get the progress url of a student.
    Limited to staff access.

1856
    Takes query parameter unique_student_identifier and if the student exists
1857 1858 1859 1860
    returns e.g. {
        'progress_url': '/../...'
    }
    """
1861
    course_id = CourseKey.from_string(course_id)
1862
    user = get_student_from_identifier(request.POST.get('unique_student_identifier'))
1863

1864
    progress_url = reverse('student_progress', kwargs={'course_id': course_id.to_deprecated_string(), 'student_id': user.id})
1865 1866

    response_payload = {
1867
        'course_id': course_id.to_deprecated_string(),
1868 1869
        'progress_url': progress_url,
    }
1870
    return JsonResponse(response_payload)
1871 1872


1873
@transaction.non_atomic_requests
1874
@require_POST
1875 1876
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
1877
@require_level('staff')
1878
@require_post_params(
1879
    problem_to_reset="problem urlname to reset"
1880
)
1881
@common_exceptions_400
1882 1883 1884
def reset_student_attempts(request, course_id):
    """

1885 1886 1887 1888 1889
    Resets a students attempts counter or starts a task to reset all students
    attempts counters. Optionally deletes student state for a problem. Limited
    to staff access. Some sub-methods limited to instructor access.

    Takes some of the following query paremeters
Miles Steele committed
1890
        - problem_to_reset is a urlname of a problem
1891
        - unique_student_identifier is an email or username
1892 1893 1894 1895 1896 1897 1898
        - all_students is a boolean
            requires instructor access
            mutually exclusive with delete_module
            mutually exclusive with delete_module
        - delete_module is a boolean
            requires instructor access
            mutually exclusive with all_students
1899
    """
1900
    course_id = CourseKey.from_string(course_id)
1901
    course = get_course_with_access(
1902
        request.user, 'staff', course_id, depth=None
1903
    )
1904

1905 1906
    problem_to_reset = strip_if_string(request.POST.get('problem_to_reset'))
    student_identifier = request.POST.get('unique_student_identifier', None)
1907 1908 1909
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)
1910 1911
    all_students = _get_boolean_param(request, 'all_students')
    delete_module = _get_boolean_param(request, 'delete_module')
Miles Steele committed
1912

1913
    # parameter combinations
1914
    if all_students and student:
1915
        return HttpResponseBadRequest(
1916
            "all_students and unique_student_identifier are mutually exclusive."
1917 1918 1919 1920 1921
        )
    if all_students and delete_module:
        return HttpResponseBadRequest(
            "all_students and delete_module are mutually exclusive."
        )
Miles Steele committed
1922

1923
    # instructor authorization
1924
    if all_students or delete_module:
1925
        if not has_access(request.user, 'instructor', course):
1926
            return HttpResponseForbidden("Requires instructor access.")
1927

1928
    try:
1929
        module_state_key = UsageKey.from_string(problem_to_reset).map_into_course(course_id)
1930 1931
    except InvalidKeyError:
        return HttpResponseBadRequest()
Miles Steele committed
1932 1933 1934 1935

    response_payload = {}
    response_payload['problem_to_reset'] = problem_to_reset

1936
    if student:
Miles Steele committed
1937
        try:
1938 1939 1940 1941 1942 1943 1944
            enrollment.reset_student_attempts(
                course_id,
                student,
                module_state_key,
                requesting_user=request.user,
                delete_module=delete_module
            )
Miles Steele committed
1945
        except StudentModule.DoesNotExist:
1946 1947 1948 1949 1950
            return HttpResponseBadRequest(_("Module does not exist."))
        except sub_api.SubmissionError:
            # Trust the submissions API to log the error
            error_msg = _("An error occurred while deleting the score.")
            return HttpResponse(error_msg, status=500)
1951
        response_payload['student'] = student_identifier
Miles Steele committed
1952
    elif all_students:
1953
        lms.djangoapps.instructor_task.api.submit_reset_problem_attempts_for_all_students(request, module_state_key)
1954
        response_payload['task'] = TASK_SUBMISSION_OK
1955
        response_payload['student'] = 'All Students'
Miles Steele committed
1956 1957 1958
    else:
        return HttpResponseBadRequest()

1959
    return JsonResponse(response_payload)
Miles Steele committed
1960 1961


1962
@transaction.non_atomic_requests
1963
@require_POST
Miles Steele committed
1964 1965
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
@require_level('staff')
@common_exceptions_400
def reset_student_attempts_for_entrance_exam(request, course_id):  # pylint: disable=invalid-name
    """

    Resets a students attempts counter or starts a task to reset all students
    attempts counters for entrance exam. Optionally deletes student state for
    entrance exam. Limited to staff access. Some sub-methods limited to instructor access.

    Following are possible query parameters
        - unique_student_identifier is an email or username
        - all_students is a boolean
            requires instructor access
            mutually exclusive with delete_module
        - delete_module is a boolean
            requires instructor access
            mutually exclusive with all_students
    """
1984
    course_id = CourseKey.from_string(course_id)
1985 1986 1987 1988 1989 1990 1991 1992 1993
    course = get_course_with_access(
        request.user, 'staff', course_id, depth=None
    )

    if not course.entrance_exam_id:
        return HttpResponseBadRequest(
            _("Course has no entrance exam section.")
        )

1994
    student_identifier = request.POST.get('unique_student_identifier', None)
1995 1996 1997
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)
1998 1999
    all_students = _get_boolean_param(request, 'all_students')
    delete_module = _get_boolean_param(request, 'delete_module')
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016

    # parameter combinations
    if all_students and student:
        return HttpResponseBadRequest(
            _("all_students and unique_student_identifier are mutually exclusive.")
        )
    if all_students and delete_module:
        return HttpResponseBadRequest(
            _("all_students and delete_module are mutually exclusive.")
        )

    # instructor authorization
    if all_students or delete_module:
        if not has_access(request.user, 'instructor', course):
            return HttpResponseForbidden(_("Requires instructor access."))

    try:
2017
        entrance_exam_key = UsageKey.from_string(course.entrance_exam_id).map_into_course(course_id)
2018
        if delete_module:
2019 2020 2021 2022 2023
            lms.djangoapps.instructor_task.api.submit_delete_entrance_exam_state_for_student(
                request,
                entrance_exam_key,
                student
            )
2024
        else:
2025 2026 2027 2028 2029
            lms.djangoapps.instructor_task.api.submit_reset_problem_attempts_in_entrance_exam(
                request,
                entrance_exam_key,
                student
            )
2030 2031 2032
    except InvalidKeyError:
        return HttpResponseBadRequest(_("Course has no valid entrance exam section."))

2033
    response_payload = {'student': student_identifier or _('All Students'), 'task': TASK_SUBMISSION_OK}
2034 2035 2036
    return JsonResponse(response_payload)


2037
@transaction.non_atomic_requests
2038
@require_POST
2039 2040
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
2041
@require_level('instructor')
2042
@require_post_params(problem_to_reset="problem urlname to reset")
2043
@common_exceptions_400
Miles Steele committed
2044 2045 2046
def rescore_problem(request, course_id):
    """
    Starts a background process a students attempts counter. Optionally deletes student state for a problem.
2047
    Limited to instructor access.
Miles Steele committed
2048 2049 2050

    Takes either of the following query paremeters
        - problem_to_reset is a urlname of a problem
2051
        - unique_student_identifier is an email or username
Miles Steele committed
2052 2053
        - all_students is a boolean

2054
    all_students and unique_student_identifier cannot both be present.
Miles Steele committed
2055
    """
2056
    course_id = CourseKey.from_string(course_id)
2057 2058
    problem_to_reset = strip_if_string(request.POST.get('problem_to_reset'))
    student_identifier = request.POST.get('unique_student_identifier', None)
2059 2060 2061
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)
2062

2063 2064
    all_students = _get_boolean_param(request, 'all_students')
    only_if_higher = _get_boolean_param(request, 'only_if_higher')
2065

2066
    if not (problem_to_reset and (all_students or student)):
2067 2068
        return HttpResponseBadRequest("Missing query parameters.")

2069
    if all_students and student:
2070
        return HttpResponseBadRequest(
2071
            "Cannot rescore with all_students and unique_student_identifier."
2072
        )
2073

2074
    try:
2075
        module_state_key = UsageKey.from_string(problem_to_reset).map_into_course(course_id)
2076
    except InvalidKeyError:
Calen Pennington committed
2077
        return HttpResponseBadRequest("Unable to parse problem id")
2078

2079
    response_payload = {'problem_to_reset': problem_to_reset}
Miles Steele committed
2080

2081
    if student:
2082
        response_payload['student'] = student_identifier
2083 2084 2085 2086 2087 2088 2089 2090 2091
        try:
            lms.djangoapps.instructor_task.api.submit_rescore_problem_for_student(
                request,
                module_state_key,
                student,
                only_if_higher,
            )
        except NotImplementedError as exc:
            return HttpResponseBadRequest(exc.message)
2092

Miles Steele committed
2093
    elif all_students:
2094 2095 2096 2097 2098 2099 2100 2101
        try:
            lms.djangoapps.instructor_task.api.submit_rescore_problem_for_all_students(
                request,
                module_state_key,
                only_if_higher,
            )
        except NotImplementedError as exc:
            return HttpResponseBadRequest(exc.message)
Miles Steele committed
2102 2103 2104
    else:
        return HttpResponseBadRequest()

2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
    response_payload['task'] = TASK_SUBMISSION_OK
    return JsonResponse(response_payload)


@transaction.non_atomic_requests
@require_POST
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('instructor')
@require_post_params(problem_to_reset="problem urlname to reset", score='overriding score')
@common_exceptions_400
def override_problem_score(request, course_id):
    course_key = CourseKey.from_string(course_id)
    score = strip_if_string(request.POST.get('score'))
    problem_to_reset = strip_if_string(request.POST.get('problem_to_reset'))
    student_identifier = request.POST.get('unique_student_identifier', None)

    if not problem_to_reset:
        return HttpResponseBadRequest("Missing query parameter problem_to_reset.")

    if not student_identifier:
        return HttpResponseBadRequest("Missing query parameter student_identifier.")

    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)
    else:
        return _create_error_response(request, "Invalid student ID {}.".format(student_identifier))

    try:
        usage_key = UsageKey.from_string(problem_to_reset).map_into_course(course_key)
    except InvalidKeyError:
        return _create_error_response(request, "Unable to parse problem id {}.".format(problem_to_reset))

    # check the user's access to this specific problem
    if not has_access(request.user, "instructor", modulestore().get_item(usage_key)):
        _create_error_response(request, "User {} does not have permission to override scores for problem {}.".format(
            request.user.id,
            problem_to_reset
        ))

    response_payload = {
        'problem_to_reset': problem_to_reset,
        'student': student_identifier
    }
    try:
        submit_override_score(
            request,
            usage_key,
            student,
            score,
        )
    except NotImplementedError as exc:  # if we try to override the score of a non-scorable block, catch it here
        return _create_error_response(request, exc.message)

    except ValueError as exc:
        return _create_error_response(request, exc.message)

    response_payload['task'] = TASK_SUBMISSION_OK
2163
    return JsonResponse(response_payload)
Miles Steele committed
2164 2165


2166
@transaction.non_atomic_requests
2167
@require_POST
Miles Steele committed
2168 2169
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
@require_level('instructor')
@common_exceptions_400
def rescore_entrance_exam(request, course_id):
    """
    Starts a background process a students attempts counter for entrance exam.
    Optionally deletes student state for a problem. Limited to instructor access.

    Takes either of the following query parameters
        - unique_student_identifier is an email or username
        - all_students is a boolean

    all_students and unique_student_identifier cannot both be present.
    """
2183
    course_id = CourseKey.from_string(course_id)
2184 2185 2186 2187
    course = get_course_with_access(
        request.user, 'staff', course_id, depth=None
    )

2188
    student_identifier = request.POST.get('unique_student_identifier', None)
2189
    only_if_higher = request.POST.get('only_if_higher', None)
2190 2191 2192 2193
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)

2194
    all_students = _get_boolean_param(request, 'all_students')
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206

    if not course.entrance_exam_id:
        return HttpResponseBadRequest(
            _("Course has no entrance exam section.")
        )

    if all_students and student:
        return HttpResponseBadRequest(
            _("Cannot rescore with all_students and unique_student_identifier.")
        )

    try:
2207
        entrance_exam_key = UsageKey.from_string(course.entrance_exam_id).map_into_course(course_id)
2208 2209 2210 2211 2212 2213 2214 2215
    except InvalidKeyError:
        return HttpResponseBadRequest(_("Course has no valid entrance exam section."))

    response_payload = {}
    if student:
        response_payload['student'] = student_identifier
    else:
        response_payload['student'] = _("All Students")
2216 2217 2218 2219

    lms.djangoapps.instructor_task.api.submit_rescore_entrance_exam_for_student(
        request, entrance_exam_key, student, only_if_higher,
    )
2220
    response_payload['task'] = TASK_SUBMISSION_OK
2221 2222 2223
    return JsonResponse(response_payload)


2224
@require_POST
2225 2226
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
2227 2228 2229 2230 2231
@require_level('staff')
def list_background_email_tasks(request, course_id):  # pylint: disable=unused-argument
    """
    List background email tasks.
    """
2232
    course_id = CourseKey.from_string(course_id)
2233 2234
    task_type = 'bulk_course_email'
    # Specifying for the history of a single task type
2235 2236 2237 2238
    tasks = lms.djangoapps.instructor_task.api.get_instructor_task_history(
        course_id,
        task_type=task_type
    )
2239 2240 2241 2242 2243 2244 2245

    response_payload = {
        'tasks': map(extract_task_features, tasks),
    }
    return JsonResponse(response_payload)


2246
@require_POST
2247 2248 2249
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2250
def list_email_content(request, course_id):  # pylint: disable=unused-argument
2251 2252 2253
    """
    List the content of bulk emails sent
    """
2254
    course_id = CourseKey.from_string(course_id)
2255 2256
    task_type = 'bulk_course_email'
    # First get tasks list of bulk emails sent
2257
    emails = lms.djangoapps.instructor_task.api.get_instructor_task_history(course_id, task_type=task_type)
2258 2259 2260 2261 2262 2263 2264

    response_payload = {
        'emails': map(extract_email_features, emails),
    }
    return JsonResponse(response_payload)


2265
@require_POST
2266 2267 2268
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
Miles Steele committed
2269 2270 2271 2272
def list_instructor_tasks(request, course_id):
    """
    List instructor tasks.

2273 2274
    Takes optional query paremeters.
        - With no arguments, lists running tasks.
2275 2276
        - `problem_location_str` lists task history for problem
        - `problem_location_str` and `unique_student_identifier` lists task
2277
            history for problem AND student (intersection)
Miles Steele committed
2278
    """
2279
    course_id = CourseKey.from_string(course_id)
2280 2281
    problem_location_str = strip_if_string(request.POST.get('problem_location_str', False))
    student = request.POST.get('unique_student_identifier', None)
2282 2283
    if student is not None:
        student = get_student_from_identifier(student)
Miles Steele committed
2284

2285
    if student and not problem_location_str:
2286
        return HttpResponseBadRequest(
2287
            "unique_student_identifier must accompany problem_location_str"
2288
        )
2289

2290 2291
    if problem_location_str:
        try:
2292
            module_state_key = UsageKey.from_string(problem_location_str).map_into_course(course_id)
2293 2294
        except InvalidKeyError:
            return HttpResponseBadRequest()
2295
        if student:
2296
            # Specifying for a single student's history on this problem
2297
            tasks = lms.djangoapps.instructor_task.api.get_instructor_task_history(course_id, module_state_key, student)
Miles Steele committed
2298
        else:
2299
            # Specifying for single problem's history
2300
            tasks = lms.djangoapps.instructor_task.api.get_instructor_task_history(course_id, module_state_key)
Miles Steele committed
2301
    else:
2302
        # If no problem or student, just get currently running tasks
2303
        tasks = lms.djangoapps.instructor_task.api.get_running_instructor_tasks(course_id)
Miles Steele committed
2304

2305
    response_payload = {
Miles Steele committed
2306
        'tasks': map(extract_task_features, tasks),
2307
    }
2308
    return JsonResponse(response_payload)
Miles Steele committed
2309 2310


2311
@require_POST
Miles Steele committed
2312 2313
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
2314
@require_level('staff')
2315 2316 2317 2318 2319 2320 2321 2322
def list_entrance_exam_instructor_tasks(request, course_id):  # pylint: disable=invalid-name
    """
    List entrance exam related instructor tasks.

    Takes either of the following query parameters
        - unique_student_identifier is an email or username
        - all_students is a boolean
    """
2323
    course_id = CourseKey.from_string(course_id)
2324
    course = get_course_by_id(course_id)
2325
    student = request.POST.get('unique_student_identifier', None)
2326 2327 2328 2329
    if student is not None:
        student = get_student_from_identifier(student)

    try:
2330
        entrance_exam_key = UsageKey.from_string(course.entrance_exam_id).map_into_course(course_id)
2331 2332 2333 2334
    except InvalidKeyError:
        return HttpResponseBadRequest(_("Course has no valid entrance exam section."))
    if student:
        # Specifying for a single student's entrance exam history
2335 2336 2337 2338 2339
        tasks = lms.djangoapps.instructor_task.api.get_entrance_exam_instructor_task_history(
            course_id,
            entrance_exam_key,
            student
        )
2340 2341
    else:
        # Specifying for all student's entrance exam history
2342 2343 2344 2345
        tasks = lms.djangoapps.instructor_task.api.get_entrance_exam_instructor_task_history(
            course_id,
            entrance_exam_key
        )
2346 2347 2348 2349 2350 2351 2352

    response_payload = {
        'tasks': map(extract_task_features, tasks),
    }
    return JsonResponse(response_payload)


2353
@require_POST
2354 2355 2356
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2357
def list_report_downloads(_request, course_id):
2358 2359 2360
    """
    List grade CSV files that are available for download for this course.
    """
2361
    course_id = CourseKey.from_string(course_id)
2362 2363 2364 2365
    report_store = ReportStore.from_config(config_name='GRADES_DOWNLOAD')

    response_payload = {
        'downloads': [
2366
            dict(name=name, url=url, link=HTML('<a href="{}">{}</a>').format(HTML(url), Text(name)))
2367 2368 2369 2370 2371 2372
            for name, url in report_store.links_for(course_id)
        ]
    }
    return JsonResponse(response_payload)


2373
@require_POST
2374 2375 2376 2377 2378 2379 2380 2381
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
@require_finance_admin
def list_financial_report_downloads(_request, course_id):
    """
    List grade CSV files that are available for download for this course.
    """
2382
    course_id = CourseKey.from_string(course_id)
2383
    report_store = ReportStore.from_config(config_name='FINANCIAL_REPORTS')
2384 2385

    response_payload = {
2386
        'downloads': [
2387
            dict(name=name, url=url, link=HTML('<a href="{}">{}</a>').format(HTML(url), Text(name)))
2388
            for name, url in report_store.links_for(course_id)
2389 2390 2391 2392 2393
        ]
    }
    return JsonResponse(response_payload)


2394
@transaction.non_atomic_requests
2395
@require_POST
2396 2397 2398
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2399
@common_exceptions_400
2400 2401 2402 2403
def export_ora2_data(request, course_id):
    """
    Pushes a Celery task which will aggregate ora2 responses for a course into a .csv
    """
2404
    course_key = CourseKey.from_string(course_id)
2405 2406 2407
    report_type = _('ORA data')
    lms.djangoapps.instructor_task.api.submit_export_ora2_data(request, course_key)
    success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)
2408

2409
    return JsonResponse({"status": success_status})
2410 2411 2412


@transaction.non_atomic_requests
2413
@require_POST
2414 2415 2416
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2417
@common_exceptions_400
2418 2419 2420 2421
def calculate_grades_csv(request, course_id):
    """
    AlreadyRunningError is raised if the course's grades are already being updated.
    """
2422
    report_type = _('grade')
2423
    course_key = CourseKey.from_string(course_id)
2424 2425 2426 2427
    lms.djangoapps.instructor_task.api.submit_calculate_grades_csv(request, course_key)
    success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)

    return JsonResponse({"status": success_status})
2428 2429


2430
@transaction.non_atomic_requests
2431
@require_POST
2432 2433 2434
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2435
@common_exceptions_400
2436 2437
def problem_grade_report(request, course_id):
    """
Daniel Friedman committed
2438
    Request a CSV showing students' grades for all problems in the
2439 2440 2441 2442 2443
    course.

    AlreadyRunningError is raised if the course's grades are already being
    updated.
    """
2444
    course_key = CourseKey.from_string(course_id)
2445 2446 2447 2448 2449
    report_type = _('problem grade')
    lms.djangoapps.instructor_task.api.submit_problem_grade_report(request, course_key)
    success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)

    return JsonResponse({"status": success_status})
2450 2451


2452
@require_POST
2453 2454 2455
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2456
@require_post_params('rolename')
Miles Steele committed
2457 2458
def list_forum_members(request, course_id):
    """
2459
    Lists forum members of a certain rolename.
Miles Steele committed
2460 2461
    Limited to staff access.

2462 2463 2464 2465 2466
    The requesting user must be at least staff.
    Staff forum admins can access all roles EXCEPT for FORUM_ROLE_ADMINISTRATOR
        which is limited to instructors.

    Takes query parameter `rolename`.
Miles Steele committed
2467
    """
2468
    course_id = CourseKey.from_string(course_id)
2469
    course = get_course_by_id(course_id)
2470
    has_instructor_access = has_access(request.user, 'instructor', course)
2471 2472 2473 2474
    has_forum_admin = has_forum_access(
        request.user, course_id, FORUM_ROLE_ADMINISTRATOR
    )

2475
    rolename = request.POST.get('rolename')
Miles Steele committed
2476

2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
    # default roles require either (staff & forum admin) or (instructor)
    if not (has_forum_admin or has_instructor_access):
        return HttpResponseBadRequest(
            "Operation requires staff & forum admin or instructor access"
        )

    # EXCEPT FORUM_ROLE_ADMINISTRATOR requires (instructor)
    if rolename == FORUM_ROLE_ADMINISTRATOR and not has_instructor_access:
        return HttpResponseBadRequest("Operation requires instructor access.")

    # filter out unsupported for roles
2488 2489
    if rolename not in [FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_GROUP_MODERATOR,
                        FORUM_ROLE_COMMUNITY_TA]:
2490 2491 2492
        return HttpResponseBadRequest(strip_tags(
            "Unrecognized rolename '{}'.".format(rolename)
        ))
Miles Steele committed
2493 2494 2495 2496 2497 2498 2499

    try:
        role = Role.objects.get(name=rolename, course_id=course_id)
        users = role.users.all().order_by('username')
    except Role.DoesNotExist:
        users = []

2500 2501
    course_discussion_settings = get_course_discussion_settings(course_id)

Miles Steele committed
2502
    def extract_user_info(user):
2503
        """ Convert user to dict for json rendering. """
2504 2505 2506
        group_id = get_group_id_for_user(user, course_discussion_settings)
        group_name = get_group_name(group_id, course_discussion_settings)

Miles Steele committed
2507 2508 2509 2510 2511
        return {
            'username': user.username,
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name,
2512
            'group_name': group_name,
Miles Steele committed
2513 2514 2515
        }

    response_payload = {
2516
        'course_id': course_id.to_deprecated_string(),
2517
        rolename: map(extract_user_info, users),
2518
        'division_scheme': course_discussion_settings.division_scheme,
Miles Steele committed
2519
    }
2520
    return JsonResponse(response_payload)
Miles Steele committed
2521

2522

2523
@transaction.non_atomic_requests
2524
@require_POST
2525
@ensure_csrf_cookie
2526 2527
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2528
@require_post_params(send_to="sending to whom", subject="subject line", message="message text")
2529
@common_exceptions_400
2530 2531
def send_email(request, course_id):
    """
2532
    Send an email to self, staff, cohorts, or everyone involved in a course.
2533
    Query Parameters:
2534
    - 'send_to' specifies what group the email should be sent to
2535
       Options are defined by the CourseEmail model in
2536
       lms/djangoapps/bulk_email/models.py
2537 2538 2539
    - 'subject' specifies email's subject
    - 'message' specifies email's content
    """
2540
    course_id = CourseKey.from_string(course_id)
2541

2542
    if not BulkEmailFlag.feature_enabled(course_id):
2543
        log.warning(u'Email is not enabled for course %s', course_id)
2544 2545
        return HttpResponseForbidden("Email is not enabled for this course.")

2546
    targets = json.loads(request.POST.get("send_to"))
2547 2548
    subject = request.POST.get("subject")
    message = request.POST.get("message")
2549

2550
    # allow two branding points to come from Site Configuration: which CourseEmailTemplate should be used
2551 2552
    # and what the 'from' field in the email should be
    #
2553
    # If these are None (there is no site configuration enabled for the current site) than
2554
    # the system will use normal system defaults
2555
    course_overview = CourseOverview.get_from_id(course_id)
2556
    from_addr = configuration_helpers.get_value('course_email_from_addr')
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
    if isinstance(from_addr, dict):
        # If course_email_from_addr is a dict, we are customizing
        # the email template for each organization that has courses
        # on the site. The dict maps from addresses by org allowing
        # us to find the correct from address to use here.
        from_addr = from_addr.get(course_overview.display_org_with_default)

    template_name = configuration_helpers.get_value('course_email_template_name')
    if isinstance(template_name, dict):
        # If course_email_template_name is a dict, we are customizing
        # the email template for each organization that has courses
        # on the site. The dict maps template names by org allowing
        # us to find the correct template to use here.
        template_name = template_name.get(course_overview.display_org_with_default)
2571

2572 2573 2574
    # Create the CourseEmail object.  This is saved immediately, so that
    # any transaction that has been pending up to this point will also be
    # committed.
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
    try:
        email = CourseEmail.create(
            course_id,
            request.user,
            targets,
            subject, message,
            template_name=template_name,
            from_addr=from_addr
        )
    except ValueError as err:
2585 2586
        log.exception(u'Cannot create course email for course %s requested by user %s for targets %s',
                      course_id, request.user, targets)
2587
        return HttpResponseBadRequest(repr(err))
2588 2589

    # Submit the task, so that the correct InstructorTask object gets created (for monitoring purposes)
2590
    lms.djangoapps.instructor_task.api.submit_bulk_course_email(request, course_id, email.id)
2591

2592
    response_payload = {
Calen Pennington committed
2593
        'course_id': course_id.to_deprecated_string(),
2594 2595
        'success': True,
    }
2596

2597 2598 2599
    return JsonResponse(response_payload)


2600
@require_POST
2601 2602 2603
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2604
@require_post_params(
2605
    unique_student_identifier="email or username of user to change access",
2606
    rolename="the forum role",
2607
    action="'allow' or 'revoke'",
2608
)
2609
@common_exceptions_400
Miles Steele committed
2610 2611
def update_forum_role_membership(request, course_id):
    """
2612
    Modify user's forum role.
Miles Steele committed
2613

2614 2615 2616 2617 2618
    The requesting user must be at least staff.
    Staff forum admins can access all roles EXCEPT for FORUM_ROLE_ADMINISTRATOR
        which is limited to instructors.
    No one can revoke an instructors FORUM_ROLE_ADMINISTRATOR status.

Miles Steele committed
2619
    Query parameters:
2620
    - `email` is the target users email
2621 2622
    - `rolename` is one of [FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_GROUP_MODERATOR,
        FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA]
2623
    - `action` is one of ['allow', 'revoke']
Miles Steele committed
2624
    """
2625
    course_id = CourseKey.from_string(course_id)
2626
    course = get_course_by_id(course_id)
2627
    has_instructor_access = has_access(request.user, 'instructor', course)
2628 2629 2630 2631
    has_forum_admin = has_forum_access(
        request.user, course_id, FORUM_ROLE_ADMINISTRATOR
    )

2632 2633 2634
    unique_student_identifier = request.POST.get('unique_student_identifier')
    rolename = request.POST.get('rolename')
    action = request.POST.get('action')
Miles Steele committed
2635

2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
    # default roles require either (staff & forum admin) or (instructor)
    if not (has_forum_admin or has_instructor_access):
        return HttpResponseBadRequest(
            "Operation requires staff & forum admin or instructor access"
        )

    # EXCEPT FORUM_ROLE_ADMINISTRATOR requires (instructor)
    if rolename == FORUM_ROLE_ADMINISTRATOR and not has_instructor_access:
        return HttpResponseBadRequest("Operation requires instructor access.")

2646 2647
    if rolename not in [FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_GROUP_MODERATOR,
                        FORUM_ROLE_COMMUNITY_TA]:
2648 2649 2650
        return HttpResponseBadRequest(strip_tags(
            "Unrecognized rolename '{}'.".format(rolename)
        ))
2651

2652
    user = get_student_from_identifier(unique_student_identifier)
Miles Steele committed
2653 2654

    try:
2655
        update_forum_role(course_id, user, rolename, action)
2656 2657
    except Role.DoesNotExist:
        return HttpResponseBadRequest("Role does not exist.")
Miles Steele committed
2658 2659

    response_payload = {
2660
        'course_id': course_id.to_deprecated_string(),
2661
        'action': action,
Miles Steele committed
2662
    }
2663
    return JsonResponse(response_payload)
Miles Steele committed
2664

2665

2666
@require_POST
2667
def get_user_invoice_preference(request, course_id):  # pylint: disable=unused-argument
2668 2669 2670 2671
    """
    Gets invoice copy user's preferences.
    """
    invoice_copy_preference = True
2672 2673 2674
    invoice_preference_value = get_user_preference(request.user, INVOICE_KEY)
    if invoice_preference_value is not None:
        invoice_copy_preference = invoice_preference_value == 'True'
2675 2676 2677 2678 2679 2680

    return JsonResponse({
        'invoice_copy': invoice_copy_preference
    })


2681 2682 2683 2684 2685 2686
def _display_unit(unit):
    """
    Gets string for displaying unit to user.
    """
    name = getattr(unit, 'display_name', None)
    if name:
2687
        return u'{0} ({1})'.format(name, unit.location.to_deprecated_string())
2688
    else:
2689
        return unit.location.to_deprecated_string()
2690 2691 2692


@handle_dashboard_error
2693
@require_POST
2694 2695 2696
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2697
@require_post_params('student', 'url', 'due_datetime')
2698 2699 2700 2701
def change_due_date(request, course_id):
    """
    Grants a due date extension to a student for a particular unit.
    """
2702
    course = get_course_by_id(CourseKey.from_string(course_id))
2703 2704 2705
    student = require_student_from_identifier(request.POST.get('student'))
    unit = find_unit(course, request.POST.get('url'))
    due_date = parse_datetime(request.POST.get('due_datetime'))
2706 2707 2708 2709 2710 2711 2712 2713 2714
    set_due_date_extension(course, unit, student, due_date)

    return JsonResponse(_(
        'Successfully changed due date for student {0} for {1} '
        'to {2}').format(student.profile.name, _display_unit(unit),
                         due_date.strftime('%Y-%m-%d %H:%M')))


@handle_dashboard_error
2715
@require_POST
2716 2717 2718
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2719
@require_post_params('student', 'url')
2720 2721 2722 2723
def reset_due_date(request, course_id):
    """
    Rescinds a due date extension for a student on a particular unit.
    """
2724
    course = get_course_by_id(CourseKey.from_string(course_id))
2725 2726
    student = require_student_from_identifier(request.POST.get('student'))
    unit = find_unit(course, request.POST.get('url'))
2727
    set_due_date_extension(course, unit, student, None)
2728 2729 2730 2731 2732
    if not getattr(unit, "due", None):
        # It's possible the normal due date was deleted after an extension was granted:
        return JsonResponse(
            _("Successfully removed invalid due date extension (unit has no due date).")
        )
2733

2734
    original_due_date_str = unit.due.strftime('%Y-%m-%d %H:%M')
2735 2736 2737
    return JsonResponse(_(
        'Successfully reset due date for student {0} for {1} '
        'to {2}').format(student.profile.name, _display_unit(unit),
2738
                         original_due_date_str))
2739 2740 2741


@handle_dashboard_error
2742
@require_POST
2743 2744 2745
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2746
@require_post_params('url')
2747 2748 2749 2750
def show_unit_extensions(request, course_id):
    """
    Shows all of the students which have due date extensions for the given unit.
    """
2751
    course = get_course_by_id(CourseKey.from_string(course_id))
2752
    unit = find_unit(course, request.POST.get('url'))
2753 2754 2755 2756
    return JsonResponse(dump_module_extensions(course, unit))


@handle_dashboard_error
2757
@require_POST
2758 2759 2760
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
2761
@require_post_params('student')
2762 2763 2764 2765 2766
def show_student_extensions(request, course_id):
    """
    Shows all of the due date extensions granted to a particular student in a
    particular course.
    """
2767
    student = require_student_from_identifier(request.POST.get('student'))
2768
    course = get_course_by_id(CourseKey.from_string(course_id))
2769 2770 2771
    return JsonResponse(dump_student_extensions(course, student))


2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788
def _split_input_list(str_list):
    """
    Separate out individual student email from the comma, or space separated string.

    e.g.
    in: "Lorem@ipsum.dolor, sit@amet.consectetur\nadipiscing@elit.Aenean\r convallis@at.lacus\r, ut@lacinia.Sed"
    out: ['Lorem@ipsum.dolor', 'sit@amet.consectetur', 'adipiscing@elit.Aenean', 'convallis@at.lacus', 'ut@lacinia.Sed']

    `str_list` is a string coming from an input text area
    returns a list of separated values
    """

    new_list = re.split(r'[\n\r\s,]', str_list)
    new_list = [s.strip() for s in new_list]
    new_list = [s for s in new_list if s != '']

    return new_list
2789 2790


2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
def _instructor_dash_url(course_key, section=None):
    """Return the URL for a section in the instructor dashboard.

    Arguments:
        course_key (CourseKey)

    Keyword Arguments:
        section (str): The name of the section to load.

    Returns:
        unicode: The URL of a section in the instructor dashboard.

    """
    url = reverse('instructor_dashboard', kwargs={'course_id': unicode(course_key)})
    if section is not None:
        url += u'#view-{section}'.format(section=section)
    return url


@require_global_staff
@require_POST
def generate_example_certificates(request, course_id=None):  # pylint: disable=unused-argument
    """Start generating a set of example certificates.

    Example certificates are used to verify that certificates have
    been configured correctly for the course.

    Redirects back to the intructor dashboard once certificate
    generation has begun.

    """
    course_key = CourseKey.from_string(course_id)
    certs_api.generate_example_certificates(course_key)
    return redirect(_instructor_dash_url(course_key, section='certificates'))


@require_global_staff
@require_POST
def enable_certificate_generation(request, course_id=None):
    """Enable/disable self-generated certificates for a course.

    Once self-generated certificates have been enabled, students
    who have passed the course will be able to generate certificates.

    Redirects back to the intructor dashboard once the
    setting has been updated.

    """
    course_key = CourseKey.from_string(course_id)
    is_enabled = (request.POST.get('certificates-enabled', 'false') == 'true')
    certs_api.set_cert_generation_enabled(course_key, is_enabled)
    return redirect(_instructor_dash_url(course_key, section='certificates'))


2845 2846 2847 2848 2849 2850 2851 2852 2853
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
@require_POST
def mark_student_can_skip_entrance_exam(request, course_id):  # pylint: disable=invalid-name
    """
    Mark a student to skip entrance exam.
    Takes `unique_student_identifier` as required POST parameter.
    """
2854
    course_id = CourseKey.from_string(course_id)
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
    student_identifier = request.POST.get('unique_student_identifier')
    student = get_student_from_identifier(student_identifier)

    __, created = EntranceExamConfiguration.objects.get_or_create(user=student, course_id=course_id)
    if created:
        message = _('This student (%s) will skip the entrance exam.') % student_identifier
    else:
        message = _('This student (%s) is already allowed to skip the entrance exam.') % student_identifier
    response_payload = {
        'message': message,
    }
    return JsonResponse(response_payload)
2867 2868


2869
@transaction.non_atomic_requests
2870 2871 2872 2873
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_global_staff
@require_POST
2874
@common_exceptions_400
2875 2876 2877 2878 2879
def start_certificate_generation(request, course_id):
    """
    Start generating certificates for all students enrolled in given course.
    """
    course_key = CourseKey.from_string(course_id)
2880
    task = lms.djangoapps.instructor_task.api.generate_certificates_for_students(request, course_key)
2881 2882 2883 2884 2885 2886
    message = _('Certificate generation task for all students of this course has been started. '
                'You can view the status of the generation task in the "Pending Tasks" section.')
    response_payload = {
        'message': message,
        'task_id': task.task_id
    }
2887

2888
    return JsonResponse(response_payload)
2889 2890


2891
@transaction.non_atomic_requests
2892 2893 2894 2895
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_global_staff
@require_POST
2896
@common_exceptions_400
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910
def start_certificate_regeneration(request, course_id):
    """
    Start regenerating certificates for students whose certificate statuses lie with in 'certificate_statuses'
    entry in POST data.
    """
    course_key = CourseKey.from_string(course_id)
    certificates_statuses = request.POST.getlist('certificate_statuses', [])
    if not certificates_statuses:
        return JsonResponse(
            {'message': _('Please select one or more certificate statuses that require certificate regeneration.')},
            status=400
        )

    # Check if the selected statuses are allowed
2911 2912 2913 2914
    allowed_statuses = [
        CertificateStatuses.downloadable,
        CertificateStatuses.error,
        CertificateStatuses.notpassing,
2915 2916
        CertificateStatuses.audit_passing,
        CertificateStatuses.audit_notpassing,
2917
    ]
2918 2919 2920 2921 2922 2923
    if not set(certificates_statuses).issubset(allowed_statuses):
        return JsonResponse(
            {'message': _('Please select certificate statuses from the list only.')},
            status=400
        )

2924
    lms.djangoapps.instructor_task.api.regenerate_certificates(request, course_key, certificates_statuses)
2925 2926 2927 2928 2929 2930 2931 2932
    response_payload = {
        'message': _('Certificate regeneration task has been started. '
                     'You can view the status of the generation task in the "Pending Tasks" section.'),
        'success': True
    }
    return JsonResponse(response_payload)


2933
@transaction.non_atomic_requests
2934 2935 2936
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_global_staff
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
@require_http_methods(['POST', 'DELETE'])
def certificate_exception_view(request, course_id):
    """
    Add/Remove students to/from certificate white list.

    :param request: HttpRequest object
    :param course_id: course identifier of the course for whom to add/remove certificates exception.
    :return: JsonResponse object with success/error message or certificate exception data.
    """
    course_key = CourseKey.from_string(course_id)
    # Validate request data and return error response in case of invalid data
    try:
2949
        certificate_exception, student = parse_request_data_and_get_user(request, course_key)
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
    except ValueError as error:
        return JsonResponse({'success': False, 'message': error.message}, status=400)

    # Add new Certificate Exception for the student passed in request data
    if request.method == 'POST':
        try:
            exception = add_certificate_exception(course_key, student, certificate_exception)
        except ValueError as error:
            return JsonResponse({'success': False, 'message': error.message}, status=400)
        return JsonResponse(exception)

    # Remove Certificate Exception for the student passed in request data
    elif request.method == 'DELETE':
        try:
            remove_certificate_exception(course_key, student)
        except ValueError as error:
            return JsonResponse({'success': False, 'message': error.message}, status=400)

        return JsonResponse({}, status=204)


def add_certificate_exception(course_key, student, certificate_exception):
    """
    Add a certificate exception to CertificateWhitelist table.
    Raises ValueError in case Student is already white listed.

    :param course_key: identifier of the course whose certificate exception will be added.
    :param student: User object whose certificate exception will be added.
    :param certificate_exception: A dict object containing certificate exception info.
    :return: CertificateWhitelist item in dict format containing certificate exception info.
    """
    if len(CertificateWhitelist.get_certificate_white_list(course_key, student)) > 0:
        raise ValueError(
            _("Student (username/email={user}) already in certificate exception list.").format(user=student.username)
        )

    certificate_white_list, __ = CertificateWhitelist.objects.get_or_create(
        user=student,
        course_id=course_key,
        defaults={
            'whitelist': True,
            'notes': certificate_exception.get('notes', '')
        }
    )
2994
    log.info(u'%s has been added to the whitelist in course %s', student.username, course_key)
2995

2996
    generated_certificate = GeneratedCertificate.eligible_certificates.filter(
2997 2998 2999 3000 3001
        user=student,
        course_id=course_key,
        status=CertificateStatuses.downloadable,
    ).first()

3002 3003 3004 3005 3006
    exception = dict({
        'id': certificate_white_list.id,
        'user_email': student.email,
        'user_name': student.username,
        'user_id': student.id,
3007
        'certificate_generated': generated_certificate and generated_certificate.created_date.strftime("%B %d, %Y"),
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
        'created': certificate_white_list.created.strftime("%A, %B %d, %Y"),
    })

    return exception


def remove_certificate_exception(course_key, student):
    """
    Remove certificate exception for given course and student from CertificateWhitelist table and
    invalidate its GeneratedCertificate if present.
    Raises ValueError in case no exception exists for the student in the given course.

    :param course_key: identifier of the course whose certificate exception needs to be removed.
    :param student: User object whose certificate exception needs to be removed.
    :return:
    """
    try:
        certificate_exception = CertificateWhitelist.objects.get(user=student, course_id=course_key)
    except ObjectDoesNotExist:
        raise ValueError(
3028 3029
            _('Certificate exception (user={user}) does not exist in certificate white list. '
              'Please refresh the page and try again.').format(user=student.username)
3030 3031 3032
        )

    try:
3033 3034 3035 3036
        generated_certificate = GeneratedCertificate.objects.get(  # pylint: disable=no-member
            user=student,
            course_id=course_key
        )
3037
        generated_certificate.invalidate()
3038 3039 3040 3041 3042
        log.info(
            u'Certificate invalidated for %s in course %s when removed from certificate exception list',
            student.username,
            course_key
        )
3043 3044 3045
    except ObjectDoesNotExist:
        # Certificate has not been generated yet, so just remove the certificate exception from white list
        pass
3046
    log.info(u'%s has been removed from the whitelist in course %s', student.username, course_key)
3047 3048 3049
    certificate_exception.delete()


3050
def parse_request_data_and_get_user(request, course_key):
3051 3052 3053 3054 3055
    """
        Parse request data into Certificate Exception and User object.
        Certificate Exception is the dict object containing information about certificate exception.

    :param request:
3056
    :param course_key: Course Identifier of the course for whom to process certificate exception
3057 3058
    :return: key-value pairs containing certificate exception data and User object
    """
3059
    certificate_exception = parse_request_data(request)
3060 3061 3062

    user = certificate_exception.get('user_name', '') or certificate_exception.get('user_email', '')
    if not user:
3063
        raise ValueError(_('Student username/email field is required and can not be empty. '
asadiqbal committed
3064
                           'Kindly fill in username/email and then press "Add to Exception List" button.'))
3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
    db_user = get_student(user, course_key)

    return certificate_exception, db_user


def parse_request_data(request):
    """
    Parse and return request data, raise ValueError in case of invalid JSON data.

    :param request: HttpRequest request object.
    :return: dict object containing parsed json data.
    """
    try:
        data = json.loads(request.body or '{}')
    except ValueError:
        raise ValueError(_('The record is not in the correct format. Please add a valid username or email address.'))

    return data


def get_student(username_or_email, course_key):
    """
    Retrieve and return User object from db, raise ValueError
    if user is does not exists or is not enrolled in the given course.

    :param username_or_email: String containing either user name or email of the student.
    :param course_key: CourseKey object identifying the current course.
    :return: User object
    """
3094
    try:
3095
        student = get_user_by_username_or_email(username_or_email)
3096
    except ObjectDoesNotExist:
3097 3098 3099
        raise ValueError(_("{user} does not exist in the LMS. Please check your spelling and retry.").format(
            user=username_or_email
        ))
3100 3101

    # Make Sure the given student is enrolled in the course
3102
    if not CourseEnrollment.is_enrolled(student, course_key):
asadiqbal committed
3103
        raise ValueError(_("{user} is not enrolled in this course. Please check your spelling and retry.")
3104 3105
                         .format(user=username_or_email))
    return student
3106 3107 3108 3109 3110 3111


@transaction.non_atomic_requests
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_global_staff
3112
@require_POST
3113
@common_exceptions_400
3114
def generate_certificate_exceptions(request, course_id, generate_for=None):
3115
    """
3116 3117 3118 3119 3120 3121 3122
    Generate Certificate for students in the Certificate White List.

    :param request: HttpRequest object,
    :param course_id: course identifier of the course for whom to generate certificates
    :param generate_for: string to identify whether to generate certificates for 'all' or 'new'
            additions to the certificate white-list
    :return: JsonResponse object containing success/failure message and certificate exception data
3123 3124 3125
    """
    course_key = CourseKey.from_string(course_id)

3126
    if generate_for == 'all':
3127
        # Generate Certificates for all white listed students
3128 3129 3130 3131 3132 3133 3134
        students = 'all_whitelisted'

    elif generate_for == 'new':
        students = 'whitelisted_not_generated'

    else:
        # Invalid data, generate_for must be present for all certificate exceptions
3135 3136 3137
        return JsonResponse(
            {
                'success': False,
3138
                'message': _('Invalid data, generate_for must be "new" or "all".'),
3139 3140 3141
            },
            status=400
        )
3142

3143
    lms.djangoapps.instructor_task.api.generate_certificates_for_students(request, course_key, student_set=students)
3144 3145
    response_payload = {
        'success': True,
3146
        'message': _('Certificate generation started for white listed students.'),
3147 3148 3149
    }

    return JsonResponse(response_payload)
asadiqbal committed
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180


@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_global_staff
@require_POST
def generate_bulk_certificate_exceptions(request, course_id):  # pylint: disable=invalid-name
    """
    Add Students to certificate white list from the uploaded csv file.
    :return response in dict format.
    {
        general_errors: [errors related to csv file e.g. csv uploading, csv attachment, content reading etc. ],
        row_errors: {
            data_format_error:              [users/data in csv file that are not well formatted],
            user_not_exist:                 [csv with none exiting users in LMS system],
            user_already_white_listed:      [users that are already white listed],
            user_not_enrolled:              [rows with not enrolled users in the given course]
        },
        success: [list of successfully added users to the certificate white list model]
    }
    """
    user_index = 0
    notes_index = 1
    row_errors_key = ['data_format_error', 'user_not_exist', 'user_already_white_listed', 'user_not_enrolled']
    course_key = CourseKey.from_string(course_id)
    students, general_errors, success = [], [], []
    row_errors = {key: [] for key in row_errors_key}

    def build_row_errors(key, _user, row_count):
        """
        inner method to build dict of csv data as row errors.
        """
asadiqbal committed
3181
        row_errors[key].append(_('user "{user}" in row# {row}').format(user=_user, row=row_count))
asadiqbal committed
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242

    if 'students_list' in request.FILES:
        try:
            upload_file = request.FILES.get('students_list')
            if upload_file.name.endswith('.csv'):
                students = [row for row in csv.reader(upload_file.read().splitlines())]
            else:
                general_errors.append(_('Make sure that the file you upload is in CSV format with no '
                                        'extraneous characters or rows.'))

        except Exception:  # pylint: disable=broad-except
            general_errors.append(_('Could not read uploaded file.'))
        finally:
            upload_file.close()

        row_num = 0
        for student in students:
            row_num += 1
            # verify that we have exactly two column in every row either email or username and notes but allow for
            # blank lines
            if len(student) != 2:
                if len(student) > 0:
                    build_row_errors('data_format_error', student[user_index], row_num)
                    log.info(u'invalid data/format in csv row# %s', row_num)
                continue

            user = student[user_index]
            try:
                user = get_user_by_username_or_email(user)
            except ObjectDoesNotExist:
                build_row_errors('user_not_exist', user, row_num)
                log.info(u'student %s does not exist', user)
            else:
                if len(CertificateWhitelist.get_certificate_white_list(course_key, user)) > 0:
                    build_row_errors('user_already_white_listed', user, row_num)
                    log.warning(u'student %s already exist.', user.username)

                # make sure user is enrolled in course
                elif not CourseEnrollment.is_enrolled(user, course_key):
                    build_row_errors('user_not_enrolled', user, row_num)
                    log.warning(u'student %s is not enrolled in course.', user.username)

                else:
                    CertificateWhitelist.objects.create(
                        user=user,
                        course_id=course_key,
                        whitelist=True,
                        notes=student[notes_index]
                    )
                    success.append(_('user "{username}" in row# {row}').format(username=user.username, row=row_num))

    else:
        general_errors.append(_('File is not attached.'))

    results = {
        'general_errors': general_errors,
        'row_errors': row_errors,
        'success': success
    }

    return JsonResponse(results)
3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330


@transaction.non_atomic_requests
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_global_staff
@require_http_methods(['POST', 'DELETE'])
def certificate_invalidation_view(request, course_id):
    """
    Invalidate/Re-Validate students to/from certificate.

    :param request: HttpRequest object
    :param course_id: course identifier of the course for whom to add/remove certificates exception.
    :return: JsonResponse object with success/error message or certificate invalidation data.
    """
    course_key = CourseKey.from_string(course_id)
    # Validate request data and return error response in case of invalid data
    try:
        certificate_invalidation_data = parse_request_data(request)
        certificate = validate_request_data_and_get_certificate(certificate_invalidation_data, course_key)
    except ValueError as error:
        return JsonResponse({'message': error.message}, status=400)

    # Invalidate certificate of the given student for the course course
    if request.method == 'POST':
        try:
            certificate_invalidation = invalidate_certificate(request, certificate, certificate_invalidation_data)
        except ValueError as error:
            return JsonResponse({'message': error.message}, status=400)
        return JsonResponse(certificate_invalidation)

    # Re-Validate student certificate for the course course
    elif request.method == 'DELETE':
        try:
            re_validate_certificate(request, course_key, certificate)
        except ValueError as error:
            return JsonResponse({'message': error.message}, status=400)

        return JsonResponse({}, status=204)


def invalidate_certificate(request, generated_certificate, certificate_invalidation_data):
    """
    Invalidate given GeneratedCertificate and add CertificateInvalidation record for future reference or re-validation.

    :param request: HttpRequest object
    :param generated_certificate: GeneratedCertificate object, the certificate we want to invalidate
    :param certificate_invalidation_data: dict object containing data for CertificateInvalidation.
    :return: dict object containing updated certificate invalidation data.
    """
    if len(CertificateInvalidation.get_certificate_invalidations(
            generated_certificate.course_id,
            generated_certificate.user,
    )) > 0:
        raise ValueError(
            _("Certificate of {user} has already been invalidated. Please check your spelling and retry.").format(
                user=generated_certificate.user.username,
            )
        )

    # Verify that certificate user wants to invalidate is a valid one.
    if not generated_certificate.is_valid():
        raise ValueError(
            _("Certificate for student {user} is already invalid, kindly verify that certificate was generated "
              "for this student and then proceed.").format(user=generated_certificate.user.username)
        )

    # Add CertificateInvalidation record for future reference or re-validation
    certificate_invalidation, __ = CertificateInvalidation.objects.update_or_create(
        generated_certificate=generated_certificate,
        defaults={
            'invalidated_by': request.user,
            'notes': certificate_invalidation_data.get("notes", ""),
            'active': True,
        }
    )

    # Invalidate GeneratedCertificate
    generated_certificate.invalidate()
    return {
        'id': certificate_invalidation.id,
        'user': certificate_invalidation.generated_certificate.user.username,
        'invalidated_by': certificate_invalidation.invalidated_by.username,
        'created': certificate_invalidation.created.strftime("%B %d, %Y"),
        'notes': certificate_invalidation.notes,
    }


3331
@common_exceptions_400
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350
def re_validate_certificate(request, course_key, generated_certificate):
    """
    Remove certificate invalidation from db and start certificate generation task for this student.
    Raises ValueError if certificate invalidation is present.

    :param request: HttpRequest object
    :param course_key: CourseKey object identifying the current course.
    :param generated_certificate: GeneratedCertificate object of the student for the given course
    """
    try:
        # Fetch CertificateInvalidation object
        certificate_invalidation = CertificateInvalidation.objects.get(generated_certificate=generated_certificate)
    except ObjectDoesNotExist:
        raise ValueError(_("Certificate Invalidation does not exist, Please refresh the page and try again."))
    else:
        # Deactivate certificate invalidation if it was fetched successfully.
        certificate_invalidation.deactivate()

    # We need to generate certificate only for a single student here
3351
    student = certificate_invalidation.generated_certificate.user
3352

3353
    lms.djangoapps.instructor_task.api.generate_certificates_for_students(
3354 3355
        request, course_key, student_set="specific_student", specific_student_id=student.id
    )
3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385


def validate_request_data_and_get_certificate(certificate_invalidation, course_key):
    """
    Fetch and return GeneratedCertificate of the student passed in request data for the given course.

    Raises ValueError in case of missing student username/email or
    if student does not have certificate for the given course.

    :param certificate_invalidation: dict containing certificate invalidation data
    :param course_key: CourseKey object identifying the current course.
    :return: GeneratedCertificate object of the student for the given course
    """
    user = certificate_invalidation.get("user")

    if not user:
        raise ValueError(
            _('Student username/email field is required and can not be empty. '
              'Kindly fill in username/email and then press "Invalidate Certificate" button.')
        )

    student = get_student(user, course_key)

    certificate = GeneratedCertificate.certificate_for_student(student, course_key)
    if not certificate:
        raise ValueError(_(
            "The student {student} does not have certificate for the course {course}. Kindly verify student "
            "username/email and the selected course are correct and try again."
        ).format(student=student.username, course=course_key.course))
    return certificate
3386 3387 3388 3389 3390 3391 3392 3393 3394


def _get_boolean_param(request, param_name):
    """
    Returns the value of the boolean parameter with the given
    name in the POST request. Handles translation from string
    values to boolean values.
    """
    return request.POST.get(param_name, False) in ['true', 'True', True]
3395 3396 3397 3398 3399 3400 3401 3402


def _create_error_response(request, msg):
    """
    Creates the appropriate error response for the current request,
    in JSON form.
    """
    return JsonResponse({"error": _(msg)}, 400)