Skip to content
exam.py 33.8 KiB
Newer Older
from __future__ import annotations
Andreas Klöckner's avatar
Andreas Klöckner committed

__copyright__ = "Copyright (C) 2015 Andreas Kloeckner"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from collections.abc import Collection
from dataclasses import dataclass
from typing import TYPE_CHECKING, cast
Andreas Klöckner's avatar
Andreas Klöckner committed

import django.forms as forms
Andreas Klöckner's avatar
Andreas Klöckner committed
from crispy_forms.layout import Submit
from django import http
from django.contrib import messages
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import permission_required
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.core.exceptions import (  # noqa
    ObjectDoesNotExist,
    PermissionDenied,
    SuspiciousOperation,
Andreas Klöckner's avatar
Andreas Klöckner committed
)
from django.db import transaction
from django.db.models import Q
from django.http.request import HttpRequest
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.shortcuts import get_object_or_404, redirect, render  # noqa
from django.urls import reverse
from django.utils.html import escape
from django.utils.safestring import mark_safe
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.utils.translation import gettext, gettext_lazy as _, pgettext
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.views.decorators.debug import sensitive_post_parameters
from course.constants import (
    SESSION_LOCKED_TO_FLOW_PK,
    exam_ticket_states,
    participation_permission as pperm,
    participation_status,
Andreas Klöckner's avatar
Andreas Klöckner committed
)
    Course,
    Exam,
    ExamTicket,
    FlowSession,
    Participation,
    ParticipationTag,
Andreas Klöckner's avatar
Andreas Klöckner committed
from course.utils import course_view, render_course_page
from relate.utils import (
    HTML5DateTimeInput,
    RelateHttpRequest,
    StyledForm,
    not_none,
    string_concat,
)
    import datetime
ticket_alphabet = "ABCDEFGHJKLPQRSTUVWXYZabcdefghjkpqrstuvwxyz23456789"


def gen_ticket_code():
    from random import choice
    return "".join(choice(ticket_alphabet) for i in range(8))


# {{{ issue ticket

class IssueTicketForm(StyledForm):
    def __init__(self, now_datetime, *args, **kwargs):
        initial_exam = kwargs.pop("initial_exam", None)

        super().__init__(*args, **kwargs)
Andreas Klöckner's avatar
Andreas Klöckner committed
        from course.auth import UserSearchWidget

        self.fields["user"] = forms.ModelChoiceField(
                queryset=(get_user_model().objects
                    .order_by("last_name")),
                widget=UserSearchWidget(),
                required=True,
                help_text=_("Select participant for whom ticket is to "
                "be issued."),
                label=_("Participant"))
        self.fields["exam"] = forms.ModelChoiceField(
                queryset=(
                    Exam.objects
                    .filter(
                        Q(active=True)
                        & (
                            Q(no_exams_after__isnull=True)
                            | Q(no_exams_after__gt=now_datetime)
                            ))
                    .order_by("no_exams_before")
                    ),
                required=True,
                initial=initial_exam,
                label=_("Exam"))

        self.fields["valid_start_time"] = forms.DateTimeField(
                label=_("Start validity"),
                required=False)
        self.fields["valid_end_time"] = forms.DateTimeField(
                label=_("End validity"),
                required=False)
        self.fields["restrict_to_facility"] = forms.CharField(
                label=_("Restrict to facility"),
                help_text=_("If not blank, the exam ticket may only be used in the "
                    "given facility"),
                required=False)

        self.fields["require_login"] = forms.BooleanField(
                required=False,
                help_text=_(
                    "If set, the exam ticket can only be used once logged in"))
        self.fields["code"] = forms.CharField(
                help_text=_(
                    "If non-empty, this code will be used for the exam ticket"),
                required=False,
                widget=forms.PasswordInput())

Andreas Klöckner's avatar
Andreas Klöckner committed
        self.fields["revoke_prior"] = forms.BooleanField(
                label=_("Revoke prior exam tickets for this user"),
                required=False,
                initial=True)

        self.helper.add_input(
                Submit(
                    "issue",
                    _("Issue ticket")))
Dong Zhuang's avatar
Dong Zhuang committed
@permission_required("course.can_issue_exam_tickets", raise_exception=True)
def issue_exam_ticket(request):
    # must import locally for mock to work
    from course.views import get_now_or_fake_time
    now_datetime = get_now_or_fake_time(request)

    if request.method == "POST":
        form = IssueTicketForm(now_datetime, request.POST)

        if form.is_valid():
            exam = form.cleaned_data["exam"]
            try:
                participation = Participation.objects.get(
                                course=exam.course,
                                user=form.cleaned_data["user"],
                                status=participation_status.active,
                                )

            except ObjectDoesNotExist:
                messages.add_message(request, messages.ERROR,
                        _("User is not enrolled in course."))
                participation = None

            if participation is not None:
Andreas Klöckner's avatar
Andreas Klöckner committed
                if form.cleaned_data["revoke_prior"]:
                    ExamTicket.objects.filter(
                            exam=exam,
                            participation=participation,
                            state__in=(
                                exam_ticket_states.valid,
                                exam_ticket_states.used,
                                )
Andreas Klöckner's avatar
Andreas Klöckner committed
                            ).update(state=exam_ticket_states.revoked)

                ticket = ExamTicket()
                ticket.exam = exam
                ticket.participation = participation
                ticket.creator = request.user
Loading
Loading full blame...