views.py 15.6 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.
#
#

Skia's avatar
Skia committed
25
from django.shortcuts import render, redirect, get_object_or_404
Skia's avatar
Skia committed
26
from django.http import HttpResponseRedirect
27
from django.views.generic import ListView, DetailView, RedirectView
Skia's avatar
Skia committed
28
from django.views.generic.edit import UpdateView, CreateView, DeleteView
Skia's avatar
Skia committed
29
from django.views.generic.detail import SingleObjectMixin
Skia's avatar
Skia committed
30
from django.utils.translation import ugettext_lazy as _
31
from django.core.urlresolvers import reverse, reverse_lazy
32 33
from django.core.exceptions import ValidationError
from django.utils import timezone
Skia's avatar
Skia committed
34
from django.conf import settings
Skia's avatar
Skia committed
35
from django.db.models import Max
Skia's avatar
Skia committed
36
from django.forms.models import modelform_factory
37
from django import forms
38

39 40
from datetime import timedelta

Skia's avatar
Skia committed
41
from com.models import Sith, News, NewsDate, Weekmail, WeekmailArticle
Skia's avatar
Skia committed
42
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, TabedViewMixin, CanCreateMixin, QuickNotifMixin
43
from core.views.forms import SelectDateTime
Skia's avatar
Skia committed
44
from core.models import Notification, RealGroup
45 46
from club.models import Club

47

48
# Sith object
49 50 51 52 53 54 55 56 57

sith = Sith.objects.first

class ComTabsMixin(TabedViewMixin):
    def get_tabs_title(self):
        return _("Communication administration")

    def get_list_of_tabs(self):
        tab_list = []
Skia's avatar
Skia committed
58 59 60 61 62
        tab_list.append({
                    'url': reverse('com:weekmail'),
                    'slug': 'weekmail',
                    'name': _("Weekmail"),
                    })
Skia's avatar
Skia committed
63 64 65 66 67
        tab_list.append({
                    'url': reverse('com:weekmail_destinations'),
                    'slug': 'weekmail_destinations',
                    'name': _("Weekmail destinations"),
                    })
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
        tab_list.append({
                    'url': reverse('com:index_edit'),
                    'slug': 'index',
                    'name': _("Index page"),
                    })
        tab_list.append({
                    'url': reverse('com:info_edit'),
                    'slug': 'info',
                    'name': _("Info message"),
                    })
        tab_list.append({
                    'url': reverse('com:alert_edit'),
                    'slug': 'alert',
                    'name': _("Alert message"),
                    })
        return tab_list

class ComEditView(ComTabsMixin, CanEditPropMixin, UpdateView):
    model = Sith
    template_name = 'core/edit.jinja'

    def get_object(self, queryset=None):
        return Sith.objects.first()

class AlertMsgEditView(ComEditView):
    fields = ['alert_msg']
    current_tab = "alert"
    success_url = reverse_lazy('com:alert_edit')

class InfoMsgEditView(ComEditView):
    fields = ['info_msg']
    current_tab = "info"
    success_url = reverse_lazy('com:info_edit')

class IndexEditView(ComEditView):
    fields = ['index_page']
    current_tab = "index"
    success_url = reverse_lazy('com:index_edit')
106

Skia's avatar
Skia committed
107 108 109 110 111
class WeekmailDestinationEditView(ComEditView):
    fields = ['weekmail_destinations']
    current_tab = "weekmail_destinations"
    success_url = reverse_lazy('com:weekmail_destinations')

112 113 114 115 116
# News

class NewsForm(forms.ModelForm):
    class Meta:
        model = News
Skia's avatar
Skia committed
117
        fields = ['type', 'title', 'club', 'summary', 'content', 'author']
118
        widgets = {
Skia's avatar
Skia committed
119
                'author': forms.HiddenInput,
120 121 122 123 124
                'type': forms.RadioSelect,
                }
    start_date = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("Start date"), widget=SelectDateTime, required=False)
    end_date = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("End date"), widget=SelectDateTime, required=False)
    until = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("Until"), widget=SelectDateTime, required=False)
Skia's avatar
Skia committed
125
    automoderation = forms.BooleanField(label=_("Automoderation"), required=False)
126 127 128 129 130 131 132 133

    def clean(self):
        self.cleaned_data = super(NewsForm, self).clean()
        if self.cleaned_data['type'] != "NOTICE":
            if not self.cleaned_data['start_date']:
                self.add_error('start_date', ValidationError(_("This field is required.")))
            if not self.cleaned_data['end_date']:
                self.add_error('end_date', ValidationError(_("This field is required.")))
Skia's avatar
Skia committed
134 135
            if self.cleaned_data['start_date'] > self.cleaned_data['end_date']:
                self.add_error('end_date', ValidationError(_("You crazy? You can not finish an event before starting it.")))
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
            if self.cleaned_data['type'] == "WEEKLY" and not self.cleaned_data['until']:
                self.add_error('until', ValidationError(_("This field is required.")))
        return self.cleaned_data

    def save(self):
        ret = super(NewsForm, self).save()
        self.instance.dates.all().delete()
        if self.instance.type == "EVENT" or self.instance.type == "CALL":
            NewsDate(start_date=self.cleaned_data['start_date'],
                    end_date=self.cleaned_data['end_date'],
                    news=self.instance).save()
        elif self.instance.type == "WEEKLY":
            start_date = self.cleaned_data['start_date']
            end_date = self.cleaned_data['end_date']
            while start_date <= self.cleaned_data['until']:
                NewsDate(start_date=start_date,
                        end_date=end_date,
                        news=self.instance).save()
                start_date += timedelta(days=7)
                end_date += timedelta(days=7)
        return ret

Skia's avatar
Skia committed
158
class NewsEditView(CanEditMixin, UpdateView):
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    model = News
    form_class = NewsForm
    template_name = 'com/news_edit.jinja'
    pk_url_kwarg = 'news_id'

    def get_initial(self):
        init = {}
        try:
            init['start_date'] = self.object.dates.order_by('id').first().start_date.strftime('%Y-%m-%d %H:%M:%S')
        except: pass
        try:
            init['end_date'] = self.object.dates.order_by('id').first().end_date.strftime('%Y-%m-%d %H:%M:%S')
        except: pass
        return init

Skia's avatar
Skia committed
174 175 176 177 178 179 180
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid() and not 'preview' in request.POST.keys():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

Skia's avatar
Skia committed
181 182 183 184 185 186 187 188 189
    def form_valid(self, form):
        self.object = form.save()
        if form.cleaned_data['automoderation'] and self.request.user.is_in_group(settings.SITH_GROUP_COM_ADMIN_ID):
            self.object.moderator = self.request.user
            self.object.is_moderated = True
            self.object.save()
        else:
            self.object.is_moderated = False
            self.object.save()
Skia's avatar
Skia committed
190 191 192
            for u in RealGroup.objects.filter(id=settings.SITH_GROUP_COM_ADMIN_ID).first().users.all():
                if not u.notifications.filter(type="NEWS_MODERATION", viewed=False).exists():
                    Notification(user=u, url=reverse("com:news_detail", kwargs={'news_id': self.object.id}), type="NEWS_MODERATION").save()
Skia's avatar
Skia committed
193 194
        return super(NewsEditView, self).form_valid(form)

Skia's avatar
Skia committed
195
class NewsCreateView(CanCreateMixin, CreateView):
196 197 198 199 200
    model = News
    form_class = NewsForm
    template_name = 'com/news_edit.jinja'

    def get_initial(self):
Skia's avatar
Skia committed
201
        init = {'author': self.request.user}
202 203 204 205 206
        try:
            init['club'] = Club.objects.filter(id=self.request.GET['club']).first()
        except: pass
        return init

Skia's avatar
Skia committed
207 208 209 210 211 212 213 214
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid() and not 'preview' in request.POST.keys():
            return self.form_valid(form)
        else:
            self.object = form.instance
            return self.form_invalid(form)

Skia's avatar
Skia committed
215 216 217 218 219 220
    def form_valid(self, form):
        self.object = form.save()
        if form.cleaned_data['automoderation'] and self.request.user.is_in_group(settings.SITH_GROUP_COM_ADMIN_ID):
            self.object.moderator = self.request.user
            self.object.is_moderated = True
            self.object.save()
Skia's avatar
Skia committed
221 222 223 224
        else:
            for u in RealGroup.objects.filter(id=settings.SITH_GROUP_COM_ADMIN_ID).first().users.all():
                if not u.notifications.filter(type="NEWS_MODERATION", viewed=False).exists():
                    Notification(user=u, url=reverse("com:news_detail", kwargs={'news_id': self.object.id}), type="NEWS_MODERATION").save()
Skia's avatar
Skia committed
225 226 227 228 229 230 231 232
        return super(NewsCreateView, self).form_valid(form)

class NewsModerateView(CanEditMixin, SingleObjectMixin):
    model = News
    pk_url_kwarg = 'news_id'

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
Skia's avatar
Skia committed
233 234 235 236
        if 'remove' in request.GET.keys():
            self.object.is_moderated = False
        else:
            self.object.is_moderated = True
Skia's avatar
Skia committed
237 238 239 240 241 242 243
        self.object.moderator = request.user
        self.object.save()
        if 'next' in self.request.GET.keys():
            return redirect(self.request.GET['next'])
        return redirect('com:news_admin_list')

class NewsAdminListView(CanEditMixin, ListView):
244 245
    model = News
    template_name = 'com/news_admin_list.jinja'
Skia's avatar
Skia committed
246
    queryset = News.objects.filter(dates__end_date__gte=timezone.now()).distinct().order_by('id')
247

Skia's avatar
Skia committed
248
class NewsListView(CanViewMixin, ListView):
249 250 251
    model = News
    template_name = 'com/news_list.jinja'

Skia's avatar
Skia committed
252 253 254 255 256 257 258
    def get_context_data(self, **kwargs):
        kwargs = super(NewsListView, self).get_context_data(**kwargs)
        kwargs['NewsDate'] = NewsDate
        kwargs['timedelta'] = timedelta
        return kwargs

class NewsDetailView(CanViewMixin, DetailView):
259 260 261
    model = News
    template_name = 'com/news_detail.jinja'
    pk_url_kwarg = 'news_id'
Skia's avatar
Skia committed
262

Skia's avatar
Skia committed
263 264
# Weekmail

Skia's avatar
Skia committed
265
class WeekmailPreviewView(ComTabsMixin, CanEditPropMixin, DetailView):
Skia's avatar
Skia committed
266 267 268
    model = Weekmail
    template_name = 'com/weekmail_preview.jinja'
    success_url = reverse_lazy('com:weekmail')
Skia's avatar
Skia committed
269 270 271 272 273 274 275 276 277 278
    current_tab = "weekmail"

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        try:
            if request.POST['send'] == "validate":
                self.object.send()
                return HttpResponseRedirect(reverse('com:weekmail') + "?qn_weekmail_send_success")
        except: pass
        return super(WeekmailEditView, self).get(request, *args, **kwargs)
Skia's avatar
Skia committed
279 280 281 282 283 284 285

    def get_object(self, queryset=None):
        return self.model.objects.filter(sent=False).order_by('-id').first()

    def get_context_data(self, **kwargs):
        """Add rendered weekmail"""
        kwargs = super(WeekmailPreviewView, self).get_context_data(**kwargs)
Skia's avatar
Skia committed
286
        kwargs['weekmail_rendered'] = self.object.render_html()
Skia's avatar
Skia committed
287 288
        return kwargs

Skia's avatar
Skia committed
289
class WeekmailEditView(ComTabsMixin, QuickNotifMixin, CanEditPropMixin, UpdateView):
Skia's avatar
Skia committed
290 291
    model = Weekmail
    template_name = 'com/weekmail.jinja'
Skia's avatar
Skia committed
292 293
    form_class = modelform_factory(Weekmail, fields=['title', 'intro', 'joke', 'protip', 'conclusion'],
            help_texts={'title': _("Delete and save to regenerate")})
Skia's avatar
Skia committed
294
    success_url = reverse_lazy('com:weekmail')
Skia's avatar
Skia committed
295
    current_tab = "weekmail"
Skia's avatar
Skia committed
296 297

    def get_object(self, queryset=None):
Skia's avatar
Skia committed
298 299 300 301
        weekmail = self.model.objects.filter(sent=False).order_by('-id').first()
        if not weekmail.title:
            now = timezone.now()
            weekmail.title = _("Weekmail of the ") + (now + timedelta(days=6 - now.weekday())).strftime('%d/%m/%Y')
Skia's avatar
Skia committed
302
            weekmail.save()
Skia's avatar
Skia committed
303
        return weekmail
Skia's avatar
Skia committed
304

Skia's avatar
Skia committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        if 'up_article' in request.GET.keys():
            art = get_object_or_404(WeekmailArticle, id=request.GET['up_article'], weekmail=self.object)
            prev_art = self.object.articles.order_by('rank').filter(rank__lt=art.rank).last()
            if prev_art:
                art.rank, prev_art.rank = prev_art.rank, art.rank
                art.save()
                prev_art.save()
                self.quick_notif_list += ['qn_success']
        if 'down_article' in request.GET.keys():
            art = get_object_or_404(WeekmailArticle, id=request.GET['down_article'], weekmail=self.object)
            next_art = self.object.articles.order_by('rank').filter(rank__gt=art.rank).first()
            if next_art:
                art.rank, next_art.rank = next_art.rank, art.rank
                art.save()
                next_art.save()
                self.quick_notif_list += ['qn_success']
        if 'add_article' in request.GET.keys():
            art = get_object_or_404(WeekmailArticle, id=request.GET['add_article'], weekmail=None)
            art.weekmail = self.object
            art.rank = self.object.articles.aggregate(Max('rank'))['rank__max'] or 0
            art.rank += 1
            art.save()
            self.quick_notif_list += ['qn_success']
        if 'del_article' in request.GET.keys():
            art = get_object_or_404(WeekmailArticle, id=request.GET['del_article'], weekmail=self.object)
            art.weekmail = None
            art.rank = -1
            art.save()
            self.quick_notif_list += ['qn_success']
        return super(WeekmailEditView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        """Add orphan articles """
        kwargs = super(WeekmailEditView, self).get_context_data(**kwargs)
        kwargs['orphans'] = WeekmailArticle.objects.filter(weekmail=None)
        return kwargs

Skia's avatar
Skia committed
344
class WeekmailArticleEditView(ComTabsMixin, QuickNotifMixin, CanEditPropMixin, UpdateView):
Skia's avatar
Skia committed
345 346
    """Edit an article"""
    model = WeekmailArticle
347
    fields = ['title', 'club', 'content']
Skia's avatar
Skia committed
348 349 350 351
    pk_url_kwarg = "article_id"
    template_name = 'core/edit.jinja'
    success_url = reverse_lazy('com:weekmail')
    quick_notif_url_arg = "qn_weekmail_article_edit"
Skia's avatar
Skia committed
352
    current_tab = "weekmail"
Skia's avatar
Skia committed
353

354
class WeekmailArticleCreateView(QuickNotifMixin, CreateView):
Skia's avatar
Skia committed
355 356
    """Post an article"""
    model = WeekmailArticle
357
    fields = ['title', 'club', 'content']
Skia's avatar
Skia committed
358 359 360 361
    template_name = 'core/create.jinja'
    success_url = reverse_lazy('core:user_tools')
    quick_notif_url_arg = "qn_weekmail_new_article"

362 363 364
    def get_initial(self):
        init = {}
        try:
Skia's avatar
Skia committed
365
            init['club'] = Club.objects.filter(id=self.request.GET['club']).first()
366 367 368
        except: pass
        return init

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        self.object = form.instance
        form.is_valid() # Valid a first time to populate club field
        try:
            m = form.instance.club.get_membership_for(request.user)
            if m.role <= settings.SITH_MAXIMUM_FREE_ROLE:
                raise
        except:
            form.add_error('club', ValidationError(_("You must be a board member of the selected club to post in the Weekmail.")))
        if form.is_valid() and not 'preview' in request.POST.keys():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

Skia's avatar
Skia committed
384 385 386 387
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super(WeekmailArticleCreateView, self).form_valid(form)

Skia's avatar
Skia committed
388
class WeekmailArticleDeleteView(CanEditPropMixin, DeleteView):
Skia's avatar
Skia committed
389 390 391
    """Delete an article"""
    model = WeekmailArticle
    template_name = 'core/delete_confirm.jinja'
392
    success_url = reverse_lazy('com:weekmail')
393
    pk_url_kwarg = "article_id"
Skia's avatar
Skia committed
394 395 396 397




Skia's avatar
Skia committed
398