tools.py 7.59 KB
Newer Older
1 2 3
"""
Tools for the instructor dashboard
"""
4 5 6
import dateutil
import json

7
from django.contrib.auth.models import User
8 9 10 11
from django.http import HttpResponseBadRequest
from django.utils.timezone import utc
from django.utils.translation import ugettext as _

12 13 14 15 16 17 18
from courseware.models import StudentFieldOverride
from courseware.field_overrides import disable_overrides
from courseware.student_field_overrides import (
    clear_override_for_user,
    get_override_for_user,
    override_field_for_user,
)
19
from xmodule.fields import Date
20
from opaque_keys.edx.keys import UsageKey
21

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
DATE_FIELD = Date()


class DashboardError(Exception):
    """
    Errors arising from use of the instructor dashboard.
    """
    def response(self):
        """
        Generate an instance of HttpResponseBadRequest for this error.
        """
        error = unicode(self)
        return HttpResponseBadRequest(json.dumps({'error': error}))


def handle_dashboard_error(view):
    """
    Decorator which adds seamless DashboardError handling to a view.  If a
    DashboardError is raised during view processing, an HttpResponseBadRequest
    is sent back to the client with JSON data about the error.
    """
    def wrapper(request, course_id):
        """
        Wrap the view.
        """
        try:
            return view(request, course_id=course_id)
        except DashboardError, error:
            return error.response()

    return wrapper

54

55 56 57 58
def strip_if_string(value):
    if isinstance(value, basestring):
        return value.strip()
    return value
59

60

61 62 63 64 65 66 67 68 69 70 71 72 73 74
def get_student_from_identifier(unique_student_identifier):
    """
    Gets a student object using either an email address or username.

    Returns the student object associated with `unique_student_identifier`

    Raises User.DoesNotExist if no user object can be found.
    """
    unique_student_identifier = strip_if_string(unique_student_identifier)
    if "@" in unique_student_identifier:
        student = User.objects.get(email=unique_student_identifier)
    else:
        student = User.objects.get(username=unique_student_identifier)
    return student
75 76


77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
def require_student_from_identifier(unique_student_identifier):
    """
    Same as get_student_from_identifier() but will raise a DashboardError if
    the student does not exist.
    """
    try:
        return get_student_from_identifier(unique_student_identifier)
    except User.DoesNotExist:
        raise DashboardError(
            _("Could not find student matching identifier: {student_identifier}").format(
                student_identifier=unique_student_identifier
            )
        )


92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
def parse_datetime(datestr):
    """
    Convert user input date string into an instance of `datetime.datetime` in
    UTC.
    """
    try:
        return dateutil.parser.parse(datestr).replace(tzinfo=utc)
    except ValueError:
        raise DashboardError(_("Unable to parse date: ") + datestr)


def find_unit(course, url):
    """
    Finds the unit (block, module, whatever the terminology is) with the given
    url in the course tree and returns the unit.  Raises DashboardError if no
    unit is found.
    """
    def find(node, url):
        """
        Find node in course tree for url.
        """
113
        if node.location.to_deprecated_string() == url:
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
            return node
        for child in node.get_children():
            found = find(child, url)
            if found:
                return found
        return None

    unit = find(course, url)
    if unit is None:
        raise DashboardError(_("Couldn't find module for url: {0}").format(url))
    return unit


def get_units_with_due_date(course):
    """
    Returns all top level units which have due dates.  Does not return
    descendents of those nodes.
    """
    units = []

    def visit(node):
        """
        Visit a node.  Checks to see if node has a due date and appends to
        `units` if it does.  Otherwise recurses into children to search for
        nodes with due dates.
        """
        if getattr(node, 'due', None):
            units.append(node)
        else:
            for child in node.get_children():
                visit(child)
    visit(course)
    #units.sort(key=_title_or_url)
    return units


def title_or_url(node):
    """
    Returns the `display_name` attribute of the passed in node of the course
    tree, if it has one.  Otherwise returns the node's url.
    """
    title = getattr(node, 'display_name', None)
    if not title:
157
        title = node.location.to_deprecated_string()
158 159 160 161 162
    return title


def set_due_date_extension(course, unit, student, due_date):
    """
163
    Sets a due date extension. Raises DashboardError if the unit or extended
164
    due date is invalid.
165
    """
166 167
    if due_date:
        # Check that the new due date is valid:
168 169
        with disable_overrides():
            original_due_date = getattr(unit, 'due', None)
170

171 172
        if not original_due_date:
            raise DashboardError(_("Unit {0} has no due date to extend.").format(unit.location))
173 174
        if due_date < original_due_date:
            raise DashboardError(_("An extended due date must be later than the original due date."))
175 176 177

        override_field_for_user(student, unit, 'due', due_date)

178 179
    else:
        # We are deleting a due date extension. Check that it exists:
180
        if not get_override_for_user(student, unit, 'due'):
181
            raise DashboardError(_("No due date extension is set for that student and unit."))
182

183
        clear_override_for_user(student, unit, 'due')
184 185 186 187 188 189 190 191 192


def dump_module_extensions(course, unit):
    """
    Dumps data about students with due date extensions for a particular module,
    specified by 'url', in a particular course.
    """
    data = []
    header = [_("Username"), _("Full Name"), _("Extended Due Date")]
193
    query = StudentFieldOverride.objects.filter(
194
        course_id=course.id,
195 196 197 198 199 200
        location=unit.location,
        field='due')
    for override in query:
        due = DATE_FIELD.from_json(json.loads(override.value))
        due = due.strftime("%Y-%m-%d %H:%M")
        fullname = override.student.profile.name
201 202
        data.append(dict(zip(
            header,
203
            (override.student.username, fullname, due))))
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    data.sort(key=lambda x: x[header[0]])
    return {
        "header": header,
        "title": _("Users with due date extensions for {0}").format(
            title_or_url(unit)),
        "data": data
    }


def dump_student_extensions(course, student):
    """
    Dumps data about the due date extensions granted for a particular student
    in a particular course.
    """
    data = []
    header = [_("Unit"), _("Extended Due Date")]
    units = get_units_with_due_date(course)
221 222
    units = {u.location: u for u in units}
    query = StudentFieldOverride.objects.filter(
223
        course_id=course.id,
224 225 226 227 228
        student=student,
        field='due')
    for override in query:
        location = override.location.replace(course_key=course.id)
        if location not in units:
229
            continue
230 231 232 233
        due = DATE_FIELD.from_json(json.loads(override.value))
        due = due.strftime("%Y-%m-%d %H:%M")
        title = title_or_url(units[location])
        data.append(dict(zip(header, (title, due))))
234 235 236 237 238
    return {
        "header": header,
        "title": _("Due date extensions for {0} {1} ({2})").format(
            student.first_name, student.last_name, student.username),
        "data": data}
239 240 241 242 243 244 245 246 247 248


def add_block_ids(payload):
    """
    rather than manually parsing block_ids from module_ids on the client, pass the block_ids explicitly in the payload
    """
    if 'data' in payload:
        for ele in payload['data']:
            if 'module_id' in ele:
                ele['block_id'] = UsageKey.from_string(ele['module_id']).block_id