views.py 9.24 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
from django.conf import settings
Sli's avatar
Sli committed
12
from ajax_select.fields import AutoCompleteSelectField
Skia's avatar
Skia committed
13
14

from datetime import timedelta
15

16
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, TabedViewMixin
Skia's avatar
Skia committed
17
from core.views.forms import SelectDate, SelectSingle, SelectDateTime
18
from club.models import Club, Membership
19
from sith.settings import SITH_MAXIMUM_FREE_ROLE, SITH_MAIN_BOARD_GROUP
Skia's avatar
Skia committed
20
from counter.models import Product, Selling, Counter
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
54
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
55
56
57
58
59
            tab_list.append({
                        'url': reverse('club:club_sellings', kwargs={'club_id': self.object.id}),
                        'slug': 'sellings',
                        'name': _("Sellings"),
                        })
60
61
62
63
64
65
66
67
        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
68
class ClubListView(ListView):
Skia's avatar
Skia committed
69
70
71
    """
    List the Clubs
    """
72
73
74
    model = Club
    template_name = 'club/club_list.jinja'

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

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

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

Skia's avatar
Skia committed
104
105
106
107
108
109
110
    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

111
class ClubMembersView(ClubTabsMixin, CanViewMixin, UpdateView):
Skia's avatar
Skia committed
112
113
114
    """
    View of a club's members
    """
115
116
    model = Club
    pk_url_kwarg = "club_id"
Skia's avatar
Skia committed
117
    form_class = ClubMemberForm
118
    template_name = 'club/club_members.jinja'
119
    current_tab = "members"
120

Skia's avatar
Skia committed
121
    def get_form(self):
Skia's avatar
Skia committed
122
123
124
125
        """
        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
126
        form = super(ClubMembersView, self).get_form()
Skia's avatar
Skia committed
127
128
129
130
        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)
Sli's avatar
Sli committed
131
132
        # form.initial = {'user': self.request.user}
        # form._user = self.request.user
Skia's avatar
Skia committed
133
134
        return form

Sli's avatar
Sli committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
    def post(self, request, *args, **kwargs):
        """
            Check user rights
        """
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            ms = self.object.get_membership_for(request.user)
            if (form.cleaned_data['role'] <= SITH_MAXIMUM_FREE_ROLE or
                (ms is not None and ms.role >= form.cleaned_data['role']) or
                request.user.is_in_group(SITH_MAIN_BOARD_GROUP) or
                request.user.is_root or request.user.is_board_member):
                return self.form_valid(form)
            else:
                return self.form_invalid(form)
        else:
            return self.form_invalid(form)

153
class ClubOldMembersView(ClubTabsMixin, CanViewMixin, DetailView):
Skia's avatar
Skia committed
154
155
156
157
158
159
    """
    Old members of a club
    """
    model = Club
    pk_url_kwarg = "club_id"
    template_name = 'club/club_old_members.jinja'
160
    current_tab = "elderlies"
Skia's avatar
Skia committed
161

Skia's avatar
Skia committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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)
Skia's avatar
Skia committed
184
        form = self.get_form_class()(self.request.GET)
Skia's avatar
Skia committed
185
186
        qs = Selling.objects.filter(club=self.object)
        if form.is_valid():
Skia's avatar
Skia committed
187
188
            if not len([v for v in form.cleaned_data.values() if v is not None]):
                qs = Selling.objects.filter(id=-1)
Skia's avatar
Skia committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
            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

204
class ClubEditView(ClubTabsMixin, CanEditMixin, UpdateView):
Skia's avatar
Skia committed
205
206
207
208
209
210
    """
    Edit a Club's main informations (for the club's members)
    """
    model = Club
    pk_url_kwarg = "club_id"
    fields = ['address']
211
212
    template_name = 'core/edit.jinja'
    current_tab = "edit"
Skia's avatar
Skia committed
213

214
class ClubEditPropView(ClubTabsMixin, CanEditPropMixin, UpdateView):
Skia's avatar
Skia committed
215
216
217
    """
    Edit the properties of a Club object (for the Sith admins)
    """
218
219
    model = Club
    pk_url_kwarg = "club_id"
Skia's avatar
Skia committed
220
    fields = ['name', 'unix_name', 'parent']
221
222
    template_name = 'core/edit.jinja'
    current_tab = "props"
Skia's avatar
Skia committed
223
224
225
226
227
228
229
230

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

Skia's avatar
Skia committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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}))