views.py 9.03 KB
Newer Older
Skia's avatar
Skia committed
1
from django import forms
2
from django.shortcuts import render
3
from django.views.generic import ListView, DetailView
Skia's avatar
Skia committed
4
5
from django.views.generic.edit import UpdateView, CreateView
from django.forms import CheckboxSelectMultiple
Skia's avatar
Skia committed
6
from django.core.exceptions import ValidationError
Skia's avatar
Skia committed
7
8
9
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils import timezone
10
from django.utils.translation import ugettext as _
Skia's avatar
Skia committed
11
12
13
from django.conf import settings

from datetime import timedelta
14

15
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, TabedViewMixin
Skia's avatar
Skia committed
16
from core.views.forms import SelectDate, SelectSingle, SelectDateTime
17
from club.models import Club, Membership
18
from sith.settings import SITH_MAXIMUM_FREE_ROLE, SITH_MAIN_BOARD_GROUP
Skia's avatar
Skia committed
19
from counter.models import Product, Selling, Counter
20

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
class ClubTabsMixin(TabedViewMixin):
    def get_tabs_title(self):
        return self.object.get_display_name()

    def get_list_of_tabs(self):
        tab_list = []
        tab_list.append({
                    'url': reverse('club:club_view', kwargs={'club_id': self.object.id}),
                    'slug': 'infos',
                    'name': _("Infos"),
                    })
        if self.request.user.can_view(self.object):
            tab_list.append({
                        'url': reverse('club:club_members', kwargs={'club_id': self.object.id}),
                        'slug': 'members',
                        'name': _("Members"),
                        })
            tab_list.append({
                        'url': reverse('club:club_old_members', kwargs={'club_id': self.object.id}),
                        'slug': 'elderlies',
                        'name': _("Old members"),
                        })
        if self.request.user.can_edit(self.object):
            tab_list.append({
                        'url': reverse('club:tools', kwargs={'club_id': self.object.id}),
                        'slug': 'tools',
                        'name': _("Tools"),
                        })
            tab_list.append({
                        'url': reverse('club:club_edit', kwargs={'club_id': self.object.id}),
                        'slug': 'edit',
                        'name': _("Edit"),
                        })
Skia's avatar
Skia committed
54
55
56
57
58
            tab_list.append({
                        'url': reverse('club:club_sellings', kwargs={'club_id': self.object.id}),
                        'slug': 'sellings',
                        'name': _("Sellings"),
                        })
59
60
61
62
63
64
65
66
        if self.request.user.is_owner(self.object):
            tab_list.append({
                        'url': reverse('club:club_prop', kwargs={'club_id': self.object.id}),
                        'slug': 'props',
                        'name': _("Props"),
                        })
        return tab_list

Skia's avatar
Skia committed
67
class ClubListView(ListView):
Skia's avatar
Skia committed
68
69
70
    """
    List the Clubs
    """
71
72
73
    model = Club
    template_name = 'club/club_list.jinja'

74
class ClubView(ClubTabsMixin, DetailView):
Skia's avatar
Skia committed
75
76
77
    """
    Front page of a Club
    """
78
79
80
    model = Club
    pk_url_kwarg = "club_id"
    template_name = 'club/club_detail.jinja'
81
    current_tab = "infos"
82

83
class ClubToolsView(ClubTabsMixin, CanEditMixin, DetailView):
Skia's avatar
Skia committed
84
85
86
87
88
89
    """
    Tools page of a Club
    """
    model = Club
    pk_url_kwarg = "club_id"
    template_name = 'club/club_tools.jinja'
90
    current_tab = "tools"
Skia's avatar
Skia committed
91

Skia's avatar
Skia committed
92
class ClubMemberForm(forms.ModelForm):
Skia's avatar
Skia committed
93
94
95
    """
    Form handling the members of a club
    """
Skia's avatar
Skia committed
96
97
98
99
    error_css_class = 'error'
    required_css_class = 'required'
    class Meta:
        model = Membership
Skia's avatar
Skia committed
100
        fields = ['user', 'role', 'description']
Skia's avatar
Skia committed
101
102

    def clean(self):
Skia's avatar
Skia committed
103
104
105
106
        """
        Validates the permissions
        e.g.: the president can add anyone anywhere, but a member can not make someone become president
        """
Skia's avatar
Skia committed
107
108
        ret = super(ClubMemberForm, self).clean()
        ms = self.instance.club.get_membership_for(self._user)
109
        if (self.cleaned_data['role'] <= SITH_MAXIMUM_FREE_ROLE or
Skia's avatar
Skia committed
110
            (ms is not None and ms.role >= self.cleaned_data['role']) or
Skia's avatar
Skia committed
111
            self._user.is_in_group(SITH_MAIN_BOARD_GROUP) or
Skia's avatar
Skia committed
112
            self._user.is_superuser):
Skia's avatar
Skia committed
113
114
            return ret
        raise ValidationError("You do not have the permission to do that")
Skia's avatar
Skia committed
115

Skia's avatar
Skia committed
116
117
118
119
120
121
122
    def save(self, *args, **kwargs):
        """
        Overloaded to return the club, and not to a Membership object that has no view
        """
        ret = super(ClubMemberForm, self).save(*args, **kwargs)
        return self.instance.club

123
class ClubMembersView(ClubTabsMixin, CanViewMixin, UpdateView):
Skia's avatar
Skia committed
124
125
126
    """
    View of a club's members
    """
127
128
    model = Club
    pk_url_kwarg = "club_id"
Skia's avatar
Skia committed
129
    form_class = ClubMemberForm
130
    template_name = 'club/club_members.jinja'
131
    current_tab = "members"
132

Skia's avatar
Skia committed
133
    def get_form(self):
Skia's avatar
Skia committed
134
135
136
137
        """
        Here we get a Membership object, but the view handles Club object.
        That's why the save method of ClubMemberForm is overridden.
        """
Skia's avatar
Skia committed
138
        form = super(ClubMembersView, self).get_form()
Skia's avatar
Skia committed
139
140
141
142
143
        if 'user' in form.data and form.data.get('user') != '': # Load an existing membership if possible
            form.instance = Membership.objects.filter(club=self.object).filter(user=form.data.get('user')).filter(end_date=None).first()
        if form.instance is None: # Instanciate a new membership
            form.instance = Membership(club=self.object, user=self.request.user)
        form.initial = {'user': self.request.user}
Skia's avatar
Skia committed
144
        form._user = self.request.user
Skia's avatar
Skia committed
145
146
        return form

147
class ClubOldMembersView(ClubTabsMixin, CanViewMixin, DetailView):
Skia's avatar
Skia committed
148
149
150
151
152
153
    """
    Old members of a club
    """
    model = Club
    pk_url_kwarg = "club_id"
    template_name = 'club/club_old_members.jinja'
154
    current_tab = "elderlies"
Skia's avatar
Skia committed
155

Skia's avatar
Skia committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
class SellingsFormBase(forms.Form):
    begin_date = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("Begin date"), required=False, widget=SelectDateTime)
    end_date = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("End date"), required=False, widget=SelectDateTime)
    counter = forms.ModelChoiceField(Counter.objects.order_by('name').all(), label=_("Counter"), required=False)

class ClubSellingView(ClubTabsMixin, CanEditMixin, DetailView):
    """
    Sellings of a club
    """
    model = Club
    pk_url_kwarg = "club_id"
    template_name = 'club/club_sellings.jinja'
    current_tab = "sellings"

    def get_form_class(self):
        kwargs = {
                'product': forms.ModelChoiceField(self.object.products.order_by('name').all(), label=_("Product"), required=False)
                }
        return type('SellingsForm', (SellingsFormBase,), kwargs)

    def get_context_data(self, **kwargs):
        kwargs = super(ClubSellingView, self).get_context_data(**kwargs)
        form = self.get_form_class()(self.request.GET, initial={'begin_date': timezone.now()-timedelta(days=7)})
        # form = self.get_form_class()(initial={'begin_date': timezone.now()-timedelta(days=7)})
        qs = Selling.objects.filter(club=self.object)
        if form.is_valid():
            if form.cleaned_data['begin_date']:
                qs = qs.filter(date__gte=form.cleaned_data['begin_date'])
            if form.cleaned_data['end_date']:
                qs = qs.filter(date__lte=form.cleaned_data['end_date'])
            if form.cleaned_data['counter']:
                qs = qs.filter(counter=form.cleaned_data['counter'])
            if form.cleaned_data['product']:
                qs = qs.filter(product__id=form.cleaned_data['product'].id)
            kwargs['result'] = qs.all().order_by('-id')
            kwargs['total'] = sum([s.quantity * s.unit_price for s in qs.all()])
        else:
            kwargs['result'] = qs[:0]
        kwargs['form'] = form
        return kwargs

197
class ClubEditView(ClubTabsMixin, CanEditMixin, UpdateView):
Skia's avatar
Skia committed
198
199
200
201
202
203
    """
    Edit a Club's main informations (for the club's members)
    """
    model = Club
    pk_url_kwarg = "club_id"
    fields = ['address']
204
205
    template_name = 'core/edit.jinja'
    current_tab = "edit"
Skia's avatar
Skia committed
206

207
class ClubEditPropView(ClubTabsMixin, CanEditPropMixin, UpdateView):
Skia's avatar
Skia committed
208
209
210
    """
    Edit the properties of a Club object (for the Sith admins)
    """
211
212
    model = Club
    pk_url_kwarg = "club_id"
Skia's avatar
Skia committed
213
    fields = ['name', 'unix_name', 'parent']
214
215
    template_name = 'core/edit.jinja'
    current_tab = "props"
Skia's avatar
Skia committed
216
217
218
219
220
221
222
223

class ClubCreateView(CanEditPropMixin, CreateView):
    """
    Create a club (for the Sith admin)
    """
    model = Club
    pk_url_kwarg = "club_id"
    fields = ['name', 'unix_name', 'parent']
224
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
225

Skia's avatar
Skia committed
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
class MembershipSetOldView(CanEditMixin, DetailView):
    """
    Set a membership as beeing old
    """
    model = Membership
    pk_url_kwarg = "membership_id"

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.object.end_date = timezone.now()
        self.object.save()
        return HttpResponseRedirect(reverse('club:club_members', args=self.args, kwargs={'club_id': self.object.club.id}))

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        return HttpResponseRedirect(reverse('club:club_members', args=self.args, kwargs={'club_id': self.object.club.id}))