views.py 7.23 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# -*- coding:utf-8 -*
#
# Copyright 2016,2017
# - Skia <skia@libskia.so>
#
# Ce fichier fait partie du site de l'Association des Étudiants de l'UTBM,
# http://ae.utbm.fr.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License a published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Sofware Foundation, Inc., 59 Temple
# Place - Suite 330, Boston, MA 02111-1307, USA.
#
#

25
from django.views.generic.edit import CreateView, FormView
26 27
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import PermissionDenied, ValidationError
28
from django.core.urlresolvers import reverse_lazy
29
from django.db import IntegrityError
30 31 32 33
from django import forms
from django.forms import Select
from django.conf import settings

34
from ajax_select.fields import AutoCompleteSelectField
35
import random
36

Skia's avatar
Skia committed
37
from subscription.models import Subscription
38
from core.views import CanEditMixin, CanEditPropMixin, CanViewMixin
39
from core.views.forms import SelectDateTime
40 41
from core.models import User

42 43 44 45 46 47 48 49 50 51 52 53

class SelectionDateForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(SelectionDateForm, self).__init__(*args, **kwargs)
        self.fields['start_date'] = forms.DateTimeField(
            ['%Y-%m-%d %H:%M:%S'], label=_("Start date"),
            widget=SelectDateTime, required=True)
        self.fields['end_date'] = forms.DateTimeField(
            ['%Y-%m-%d %H:%M:%S'], label=_("End date"),
            widget=SelectDateTime, required=True)


54 55 56
class SubscriptionForm(forms.ModelForm):
    class Meta:
        model = Subscription
Skia's avatar
Skia committed
57
        fields = ['member', 'subscription_type', 'payment_method', 'location']
58
    member = AutoCompleteSelectField('users', required=False, help_text=None)
59

60 61 62 63 64 65 66 67
    def __init__(self, *args, **kwargs):
        super(SubscriptionForm, self).__init__(*args, **kwargs)
        # Add fields to allow basic user creation
        self.fields['last_name'] = forms.CharField(max_length=User._meta.get_field('last_name').max_length)
        self.fields['first_name'] = forms.CharField(max_length=User._meta.get_field('first_name').max_length)
        self.fields['email'] = forms.EmailField()
        self.fields.move_to_end('subscription_type')
        self.fields.move_to_end('payment_method')
Skia's avatar
Skia committed
68
        self.fields.move_to_end('location')
69

70 71 72
    def clean_member(self):
        subscriber = self.cleaned_data.get("member")
        if subscriber:
Skia's avatar
Skia committed
73
            subscriber = User.objects.filter(id=subscriber.id).first()
74 75
        return subscriber

76 77 78 79 80 81 82
    def clean(self):
        cleaned_data = super(SubscriptionForm, self).clean()
        if (cleaned_data.get("member") is None
                and "last_name" not in self.errors.as_data()
                and "first_name" not in self.errors.as_data()
                and "email" not in self.errors.as_data()):
            self.errors.pop("member", None)
Skia's avatar
Skia committed
83 84
            if self.errors:
                return cleaned_data
Skia's avatar
Skia committed
85
            if User.objects.filter(email=cleaned_data.get("email")).first() is not None:
86 87
                self.add_error("email", ValidationError(_("A user with that email address already exists")))
            else:
Skia's avatar
Skia committed
88
                u = User(last_name = self.cleaned_data.get("last_name"),
89 90 91
                        first_name = self.cleaned_data.get("first_name"),
                        email = self.cleaned_data.get("email"))
                u.generate_username()
92
                u.set_password(str(random.randrange(1000000, 10000000)))
93 94 95 96 97 98 99 100 101 102 103 104
                u.save()
                cleaned_data["member"] = u
        elif cleaned_data.get("member") is not None:
            self.errors.pop("last_name", None)
            self.errors.pop("first_name", None)
            self.errors.pop("email", None)
        if cleaned_data.get("member") is None:
            # This should be handled here, but it is done in the Subscription model's clean method
            # TODO investigate why!
            raise ValidationError(_("You must either choose an existing user or create a new one properly"))
        return cleaned_data

Skia's avatar
Skia committed
105
class NewSubscription(CreateView):
Skia's avatar
Skia committed
106
    template_name = 'subscription/subscription.jinja'
107
    form_class = SubscriptionForm
Skia's avatar
Skia committed
108

Skia's avatar
Skia committed
109 110 111 112 113 114
    def dispatch(self, request, *arg, **kwargs):
        res = super(NewSubscription, self).dispatch(request, *arg, **kwargs)
        if request.user.is_in_group(settings.SITH_MAIN_BOARD_GROUP):
            return res
        raise PermissionDenied

Skia's avatar
Skia committed
115 116
    def get_initial(self):
        if 'member' in self.request.GET.keys():
Skia's avatar
Skia committed
117 118
            return {'member': self.request.GET['member'], 'subscription_type': 'deux-semestres'}
        return {'subscription_type': 'deux-semestres'}
Skia's avatar
Skia committed
119 120

    def form_valid(self, form):
121 122
        form.instance.subscription_start = Subscription.compute_start(
                duration=settings.SITH_SUBSCRIPTIONS[form.instance.subscription_type]['duration'])
Skia's avatar
Skia committed
123 124 125 126 127
        form.instance.subscription_end = Subscription.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[form.instance.subscription_type]['duration'],
                start=form.instance.subscription_start
                )
        return super(NewSubscription, self).form_valid(form)
128

Sli's avatar
Sli committed
129

130
class SubscriptionsStatsView(FormView):
Sli's avatar
Sli committed
131
    template_name = "subscription/stats.jinja"
132
    form_class = SelectionDateForm
Sli's avatar
Sli committed
133 134

    def dispatch(self, request, *arg, **kwargs):
135 136 137 138 139
        import datetime
        self.start_date = datetime.datetime.today()
        self.end_date = self.start_date
        res = super(SubscriptionsStatsView, self).dispatch(
            request, *arg, **kwargs)
Sli's avatar
Sli committed
140 141 142 143
        if request.user.is_root or request.user.is_board_member:
            return res
        raise PermissionDenied

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    def post(self, request, *args, **kwargs):
        self.form = self.get_form()
        self.start_date = self.form['start_date']
        self.end_date = self.form['end_date']
        res = super(SubscriptionsStatsView, self).post(
            request, *args, **kwargs)
        if request.user.is_root or request.user.is_board_member:
            return res
        raise PermissionDenied

    def get_initial(self):
        init = {
            'start_date': self.start_date.strftime('%Y-%m-%d %H:%M:%S'),
            'end_date': self.end_date.strftime('%Y-%m-%d %H:%M:%S')
        }
        return init

Sli's avatar
Sli committed
161 162 163
    def get_context_data(self, **kwargs):
        from subscription.models import Subscription
        kwargs = super(SubscriptionsStatsView, self).get_context_data(**kwargs)
164 165 166
        kwargs['subscriptions_total'] = Subscription.objects.filter(
            subscription_end__gte=self.end_date,
            subscription_start__lte=self.start_date)
Sli's avatar
Sli committed
167 168 169 170
        kwargs['subscriptions_types'] = settings.SITH_SUBSCRIPTIONS
        kwargs['payment_types'] = settings.SITH_COUNTER_PAYMENT_METHOD
        kwargs['locations'] = settings.SITH_SUBSCRIPTION_LOCATIONS
        return kwargs
171 172 173

    def get_success_url(self, **kwargs):
        return reverse_lazy('subscriptions:stats')