views.py 11.5 KB
Newer Older
1
"""Views provided by the registrations package"""
2
from django.conf import settings
3 4 5 6 7 8
from django.contrib import messages
from django.contrib.admin.utils import model_ngettext
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
9 10
from django.http import Http404
from django.shortcuts import redirect, get_object_or_404
11 12 13 14 15 16
from django.template.defaultfilters import floatformat
from django.urls import reverse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
from django.views import View
17
from django.views.generic import FormView, CreateView
18 19
from django.views.generic.base import TemplateResponseMixin, TemplateView

20
from members.decorators import membership_required
21
from members.models import Membership
Thom Wiggers's avatar
Thom Wiggers committed
22
from . import emails, forms, services
23
from .models import Entry, Registration, Renewal, Reference
Thom Wiggers's avatar
Thom Wiggers committed
24

25 26

class BecomeAMemberView(TemplateView):
27
    """View that render a HTML template with context data"""
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
    template_name = 'registrations/become_a_member.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['year_fees'] = floatformat(settings.MEMBERSHIP_PRICES[
                                               Entry.MEMBERSHIP_YEAR], 2)
        context['study_fees'] = floatformat(settings.MEMBERSHIP_PRICES[
                                                Entry.MEMBERSHIP_STUDY], 2)
        return context


@method_decorator(staff_member_required, name='dispatch')
@method_decorator(permission_required('registrations.review_entries'),
                  name='dispatch', )
class EntryAdminView(View):
43
    """
44
    View that handles the processing of entries
45
    """
46

47 48
    def post(self, request, *args, **kwargs):
        action = request.POST.get('action')
49 50 51 52 53 54
        entry_qs = Entry.objects.filter(pk=kwargs['pk'])
        try:
            entry = entry_qs.get()
        except Entry.DoesNotExist:
            return redirect('admin:index')

55
        if action == 'accept':
56 57 58 59
            if not services.check_unique_user(entry):
                messages.error(request, _('Could not accept %s. '
                                          'Username is not unique.') %
                               model_ngettext(entry, 1))
60
            elif services.accept_entries(request.user.pk, entry_qs) > 0:
61 62 63 64 65
                messages.success(request, _('Successfully accepted %s.') %
                                 model_ngettext(entry, 1))
            else:
                messages.error(request, _('Could not accept %s.') %
                               model_ngettext(entry, 1))
66
        elif action == 'reject':
67
            if services.reject_entries(request.user.pk, entry_qs) > 0:
68 69 70 71 72
                messages.success(request, _('Successfully rejected %s.') %
                                 model_ngettext(entry, 1))
            else:
                messages.error(request, _('Could not reject %s.') %
                               model_ngettext(entry, 1))
73 74 75 76 77
        elif action == 'resend':
            try:
                emails.send_registration_email_confirmation(entry.registration)
            except Registration.DoesNotExist:
                pass
78
        elif action == 'revert':
79
            services.revert_entry(request.user.pk, entry)
80 81 82 83 84 85 86 87 88 89 90 91

        if entry_qs.filter(renewal=None).exists():
            content_type = ContentType.objects.get_for_model(Registration)
        else:
            content_type = ContentType.objects.get_for_model(Renewal)

        return redirect("admin:%s_%s_change" %
                        (content_type.app_label, content_type.model),
                        kwargs['pk'])


class ConfirmEmailView(View, TemplateResponseMixin):
92 93 94 95
    """
    View that renders an HTML template and confirms the email address
    of the provided registration
    """
96 97 98
    template_name = 'registrations/confirm_email.html'

    def get(self, request, *args, **kwargs):
99
        queryset = Registration.objects.filter(pk=kwargs['pk'])
100

101
        processed = 0
102
        try:
103
            processed = services.confirm_entry(queryset)
104 105 106
        except ValidationError:
            pass

107
        if processed == 0:
108
            return redirect('registrations:register-member')
109

110 111 112 113 114 115 116
        registration = queryset.get()

        if (registration.membership_type == Membership.BENEFACTOR
                and not registration.no_references):
            emails.send_references_information_message(registration)

        emails.send_new_registration_board_message(registration)
117 118 119 120

        return self.render_to_response({})


121
class BaseRegistrationFormView(FormView):
122
    """
123
    View that renders a membership registration form
124
    """
125 126 127 128 129
    form_class = forms.MemberRegistrationForm
    template_name = 'registrations/register_member.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
Thalia Technicie's avatar
Thalia Technicie committed
130
        context['google_api_key'] = settings.GOOGLE_PLACES_API_KEY
131 132 133 134 135 136 137 138 139 140 141
        context['year_fees'] = floatformat(settings.MEMBERSHIP_PRICES[
                                               Entry.MEMBERSHIP_YEAR], 2)
        context['study_fees'] = floatformat(settings.MEMBERSHIP_PRICES[
                                                Entry.MEMBERSHIP_STUDY], 2)
        return context

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('registrations:renew')
        return super().get(request, args, kwargs)

142 143 144 145 146 147 148 149 150 151 152 153
    def form_valid(self, form):
        form.save()
        return redirect('registrations:register-success')


class MemberRegistrationFormView(BaseRegistrationFormView):
    """
    View that renders the `member` membership registration form
    """
    form_class = forms.MemberRegistrationForm
    template_name = 'registrations/register_member.html'

154 155 156 157 158 159 160
    def post(self, request, *args, **kwargs):
        request.POST = request.POST.dict()
        request.POST['language'] = request.LANGUAGE_CODE
        request.POST['membership_type'] = Membership.MEMBER
        return super().post(request, *args, **kwargs)

    def form_valid(self, form):
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        response = super().form_valid(form)
        emails.send_registration_email_confirmation(form.instance)
        return response


class BenefactorRegistrationFormView(BaseRegistrationFormView):
    """
    View that renders the `benefactor` membership registration form
    """
    form_class = forms.BenefactorRegistrationForm
    template_name = 'registrations/register_benefactor.html'

    def post(self, request, *args, **kwargs):
        request.POST = request.POST.dict()
        request.POST['language'] = request.LANGUAGE_CODE
        request.POST['membership_type'] = Membership.BENEFACTOR
        request.POST['length'] = Entry.MEMBERSHIP_YEAR
        request.POST['remarks'] = ('Registered as iCIS employee'
                                   if 'icis_employee' in request.POST else '')
        request.POST['no_references'] = 'icis_employee' in request.POST
        return super().post(request, *args, **kwargs)
182 183 184 185


@method_decorator(login_required, name='dispatch')
class RenewalFormView(FormView):
186 187 188
    """
    View that renders the membership renewal form
    """
189
    form_class = forms.RenewalForm
190 191 192 193 194 195 196 197
    template_name = 'registrations/renewal.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['year_fees'] = floatformat(settings.MEMBERSHIP_PRICES[
                                               Entry.MEMBERSHIP_YEAR], 2)
        context['study_fees'] = floatformat(settings.MEMBERSHIP_PRICES[
                                                Entry.MEMBERSHIP_STUDY], 2)
198
        context['latest_membership'] = self.request.member.latest_membership
Thom Wiggers's avatar
Thom Wiggers committed
199 200
        context['was_member'] = Membership.objects.filter(
            user=self.request.member, type=Membership.MEMBER).exists()
201
        context['benefactor_type'] = Membership.BENEFACTOR
202 203 204 205 206
        return context

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        member = self.request.member
207
        if member is not None and member.latest_membership is not None:
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
            latest_membership = member.latest_membership
            # If latest membership has not ended or does not ends
            # within 1 month: do not show 'year' length
            hide_year_choice = not (latest_membership is not None and
                                    latest_membership.until is not None and
                                    (latest_membership.until -
                                     timezone.now().date()).days <= 31)

            if hide_year_choice:
                form.fields['length'].choices = [
                    c for c in form.fields['length'].choices
                    if c[0] != Entry.MEMBERSHIP_YEAR
                ]

        return form

    def post(self, request, *args, **kwargs):
        request.POST = request.POST.dict()
226 227
        if request.member.latest_membership.type == Membership.BENEFACTOR:
            request.POST['membership_type'] = Membership.BENEFACTOR
228
            request.POST['length'] = Entry.MEMBERSHIP_YEAR
229
        request.POST['member'] = request.member.pk
230
        request.POST['remarks'] = ''
231
        request.POST['no_references'] = True
232 233

        if request.POST['membership_type'] == Membership.BENEFACTOR:
234
            request.POST['no_references'] = False
235 236 237 238 239 240 241 242
            if Membership.objects.filter(user=request.member,
                                         type=Membership.MEMBER).exists():
                request.POST['remarks'] = 'Was a Thalia member in the past.'
                request.POST['no_references'] = True
            if 'icis_employee' in request.POST:
                request.POST['remarks'] = 'Registered as iCIS employee.'
                request.POST['no_references'] = True

243 244 245 246
        return super().post(request, *args, **kwargs)

    def form_valid(self, form):
        renewal = form.save()
247 248
        if not renewal.no_references:
            emails.send_references_information_message(renewal)
249 250
        emails.send_new_renewal_board_message(renewal)
        return redirect('registrations:renew-success')
251 252 253 254 255 256 257 258 259


@method_decorator(login_required, name='dispatch')
@method_decorator(membership_required, name='dispatch')
class ReferenceCreateView(CreateView):
    """
    View that renders a reference creation form
    """
    model = Reference
260
    form_class = forms.ReferenceForm
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    template_name = 'registrations/reference.html'
    entry = None
    success = False

    def get_success_url(self):
        return reverse('registrations:reference-success',
                       args=(self.entry.pk,))

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['success'] = self.success
        try:
            context['name'] = self.entry.registration.get_full_name()
        except Registration.DoesNotExist:
            context['name'] = self.entry.renewal.member.get_full_name()

        return context

    def dispatch(self, request, *args, **kwargs):
        self.entry = get_object_or_404(Entry, pk=kwargs.get('pk'))

        if (self.entry.no_references or
                self.entry.membership_type != Membership.BENEFACTOR):
            raise Http404

        return super().dispatch(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.POST = request.POST.dict()
        request.POST['member'] = request.member.pk
        request.POST['entry'] = kwargs['pk']
        return super().post(request, *args, **kwargs)