kpsul/cof/views.py

599 lines
24 KiB
Python
Raw Normal View History

2016-07-15 00:02:56 +02:00
# -*- coding: utf-8 -*-
import unicodecsv
import uuid
from datetime import timedelta
from icalendar import Calendar, Event as Vevent
from custommail.shortcuts import send_custom_mail
from django.shortcuts import get_object_or_404, render
from django.http import Http404, HttpResponse
2012-06-27 23:28:35 +02:00
from django.contrib.auth.decorators import login_required
2016-05-28 23:54:21 +02:00
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.utils import timezone
2017-01-29 16:24:07 +01:00
from django.contrib import messages
import django.utils.six as six
2012-07-11 17:39:20 +02:00
from gestion.models import (
Event, EventRegistration, EventOption, EventOptionChoice,
EventCommentField, EventCommentValue
)
from .models import Survey, SurveyAnswer, SurveyQuestion, \
SurveyQuestionAnswer, CalendarSubscription
from .models import CofProfile
from .decorators import buro_required, cof_required
from .forms import (
SurveyForm, SurveyStatusFilterForm,
RegistrationUserForm, RegistrationProfileForm, RegistrationCofProfileForm,
CalendarForm, EventFormset, RegistrationPassUserForm
)
2012-06-27 23:28:35 +02:00
from bda.models import Tirage, Spectacle
from gestion.models import Profile
2012-06-27 23:28:35 +02:00
@login_required
def home(request):
data = {"surveys": Survey.objects.filter(old=False).all(),
"open_surveys":
Survey.objects.filter(survey_open=True, old=False).all(),
"open_events":
Event.objects.filter(registration_open=True, old=False).all(),
"active_tirages": Tirage.objects.filter(active=True).all(),
"open_tirages":
Tirage.objects.filter(active=True,
ouverture__lte=timezone.now()).all(),
"now": timezone.now()}
return render(request, "home.html", data)
2012-06-27 23:28:35 +02:00
2012-06-27 23:28:35 +02:00
@login_required
def survey(request, survey_id):
survey = get_object_or_404(Survey, id=survey_id)
if not survey.survey_open or survey.old:
2012-06-27 23:28:35 +02:00
raise Http404
success = False
2012-07-11 17:39:20 +02:00
deleted = False
2012-06-27 23:28:35 +02:00
if request.method == "POST":
form = SurveyForm(request.POST, survey=survey)
2012-07-11 17:39:20 +02:00
if request.POST.get('delete'):
2012-06-27 23:28:35 +02:00
try:
current_answer = SurveyAnswer.objects.get(user=request.user,
survey=survey)
2012-07-11 17:39:20 +02:00
current_answer.delete()
current_answer = None
2012-06-27 23:28:35 +02:00
except SurveyAnswer.DoesNotExist:
2012-07-11 17:39:20 +02:00
current_answer = None
form = SurveyForm(survey=survey)
2012-06-27 23:28:35 +02:00
success = True
2012-07-11 17:39:20 +02:00
deleted = True
else:
if form.is_valid():
all_answers = []
for question_id, answers_ids in form.answers():
question = get_object_or_404(SurveyQuestion,
id=question_id,
survey=survey)
2012-07-11 17:39:20 +02:00
if type(answers_ids) != list:
answers_ids = [answers_ids]
if not question.multi_answers and len(answers_ids) > 1:
raise Http404
for answer_id in answers_ids:
if not answer_id:
continue
answer_id = int(answer_id)
answer = SurveyQuestionAnswer.objects.get(
id=answer_id,
survey_question=question)
2012-07-11 17:39:20 +02:00
all_answers.append(answer)
try:
current_answer = SurveyAnswer.objects.get(
user=request.user, survey=survey)
2012-07-11 17:39:20 +02:00
except SurveyAnswer.DoesNotExist:
current_answer = SurveyAnswer(user=request.user,
survey=survey)
2012-07-11 17:39:20 +02:00
current_answer.save()
current_answer.answers = all_answers
current_answer.save()
success = True
2012-06-27 23:28:35 +02:00
else:
try:
current_answer = SurveyAnswer.objects.get(user=request.user,
survey=survey)
form = SurveyForm(survey=survey,
current_answers=current_answer.answers)
2012-06-27 23:28:35 +02:00
except SurveyAnswer.DoesNotExist:
2012-07-11 17:39:20 +02:00
current_answer = None
form = SurveyForm(survey=survey)
2017-01-29 16:24:07 +01:00
# Messages
if success:
if deleted:
messages.success(request,
"Votre réponse a bien été supprimée")
else:
messages.success(request,
"Votre réponse a bien été enregistrée ! Vous "
"pouvez cependant la modifier jusqu'à la fin "
"du sondage.")
2017-02-12 19:36:17 +01:00
return render(request, "cof/survey.html", {
2017-01-29 16:24:07 +01:00
"survey": survey,
"form": form,
"current_answer": current_answer
})
2012-07-11 17:39:20 +02:00
2012-07-11 17:39:20 +02:00
def clean_post_for_status(initial):
d = initial.copy()
2012-07-11 17:39:20 +02:00
for k, v in d.items():
if k.startswith("id_"):
del d[k]
d[k[3:]] = v
2012-07-11 17:39:20 +02:00
return d
@buro_required
2012-07-11 17:39:20 +02:00
def survey_status(request, survey_id):
survey = get_object_or_404(Survey, id=survey_id)
answers_query = SurveyAnswer.objects.filter(survey=survey)
2012-07-11 17:39:20 +02:00
post_data = clean_post_for_status(request.POST)
form = SurveyStatusFilterForm(post_data or None, survey=survey)
2012-07-11 17:39:20 +02:00
if form.is_valid():
for question_id, answer_id, value in form.filters():
answer = get_object_or_404(SurveyQuestionAnswer, id=answer_id,
survey_question__id=question_id)
2012-07-11 17:39:20 +02:00
if value == "none":
continue
if value == "yes":
answers_query = answers_query.filter(
answers__id__exact=answer.id)
2012-07-11 17:39:20 +02:00
elif value == "no":
answers_query = answers_query.exclude(
answers__id__exact=answer.id)
2012-07-11 17:39:20 +02:00
user_answers = answers_query.prefetch_related("user").all()
questions = SurveyQuestion.objects.filter(survey=survey).all()
2012-07-11 17:39:20 +02:00
answers_count = {}
for question in questions:
for answer in question.answers.all():
answers_count[answer.id] = 0
for user_answer in user_answers:
for answer in user_answer.answers.all():
answers_count[answer.id] += 1
return render(request, "survey_status.html",
{"survey": survey, "user_answers": user_answers,
"questions": questions, "answers_count": answers_count,
"form": form})
2012-07-11 17:39:20 +02:00
def registration_set_ro_fields(user_form, profile_form):
user_form.fields['username'].widget.attrs['readonly'] = True
profile_form.fields['login_clipper'].widget.attrs['readonly'] = True
@buro_required
def registration_form2(request, login_clipper=None, username=None,
fullname=None):
events = Event.objects.filter(old=False).all()
2016-08-13 02:56:42 +02:00
member = None
if login_clipper:
try: # check if the given user is already registered
2016-08-13 02:56:42 +02:00
member = User.objects.get(username=login_clipper)
username = member.username
login_clipper = None
except User.DoesNotExist:
# new user, but prefill
2016-08-13 02:56:42 +02:00
# user
user_form = RegistrationUserForm(initial={
'username': login_clipper,
'email': "%s@clipper.ens.fr" % login_clipper})
if fullname:
bits = fullname.split(" ")
user_form.fields['first_name'].initial = bits[0]
if len(bits) > 1:
user_form.fields['last_name'].initial = " ".join(bits[1:])
2016-08-13 02:56:42 +02:00
# profile
profile_form = RegistrationProfileForm(initial={
'login_clipper': login_clipper})
# COF - profile
cofprofile_form = RegistrationCofProfileForm()
registration_set_ro_fields(user_form, profile_form)
# events
2016-08-13 02:56:42 +02:00
event_formset = EventFormset(events=events, prefix='events')
if username:
member = get_object_or_404(User, username=username)
(profile, _) = Profile.objects.get_or_create(user=member)
(cofprofile, _) = CofProfile.objects.get_or_create(profile=profile)
# already existing, prefill
user_form = RegistrationUserForm(instance=member)
profile_form = RegistrationProfileForm(instance=profile)
cofprofile_form = RegistrationCofProfileForm(instance=cofprofile)
registration_set_ro_fields(user_form, profile_form)
2016-08-13 02:56:42 +02:00
# events
current_registrations = []
for event in events:
try:
current_registrations.append(
EventRegistration.objects.get(user=member, event=event))
except EventRegistration.DoesNotExist:
current_registrations.append(None)
event_formset = EventFormset(
events=events, prefix='events',
current_registrations=current_registrations)
elif not login_clipper:
# new user
user_form = RegistrationPassUserForm()
2016-08-24 16:26:43 +02:00
user_form.force_long_username()
profile_form = RegistrationProfileForm()
cofprofile_form = RegistrationCofProfileForm()
event_formset = EventFormset(events=events, prefix='events')
2017-02-12 19:36:17 +01:00
return render(request, "cof/registration_form.html",
{"member": member, "login_clipper": login_clipper,
"user_form": user_form,
"profile_form": profile_form,
"cofprofile_form": cofprofile_form,
"event_formset": event_formset})
def get_event_form_choices(event, form):
all_choices = []
for option_id, choices_ids in form.choices():
option = get_object_or_404(EventOption, id=option_id,
event=event)
if type(choices_ids) != list:
choices_ids = [choices_ids]
if not option.multi_choices and len(choices_ids) > 1:
raise Http404
for choice_id in choices_ids:
if not choice_id:
continue
choice_id = int(choice_id)
choice = EventOptionChoice.objects.get(
id=choice_id,
event_option=option)
all_choices.append(choice)
return all_choices
def update_event_form_comments(event, form, registration):
for commentfield_id, value in form.comments():
field = get_object_or_404(EventCommentField, id=commentfield_id,
event=event)
if value == field.default:
continue
(storage, _) = EventCommentValue.objects.get_or_create(
commentfield=field,
registration=registration)
storage.content = value
storage.save()
@buro_required
2012-07-11 17:39:20 +02:00
def registration(request):
if request.POST:
request_dict = request.POST.copy()
# num ne peut pas être défini manuellement
if "num" in request_dict:
del request_dict["num"]
member = None
login_clipper = None
success = False
# -----
# Remplissage des formulaires
# -----
if 'password1' in request_dict or 'password2' in request_dict:
user_form = RegistrationPassUserForm(request_dict)
else:
2016-08-24 15:38:04 +02:00
user_form = RegistrationUserForm(request_dict)
profile_form = RegistrationProfileForm(request_dict)
2017-02-11 18:41:47 +01:00
cofprofile_form = RegistrationCofProfileForm(request_dict)
events = Event.objects.filter(old=False).all()
event_formset = EventFormset(events=events, data=request_dict,
prefix='events')
if "user_exists" in request_dict and request_dict["user_exists"]:
username = request_dict["username"]
try:
member = User.objects.get(username=username)
user_form = RegistrationUserForm(request_dict, instance=member)
if member.profile.login_clipper:
login_clipper = member.profile.login_clipper
else:
2016-08-24 16:26:43 +02:00
user_form.force_long_username()
except User.DoesNotExist:
user_form.force_long_username()
2016-08-24 16:26:43 +02:00
else:
user_form.force_long_username()
# -----
# Validation des formulaires
# -----
if user_form.is_valid():
member = user_form.save()
2017-02-11 18:41:47 +01:00
cofprofile, _ = (CofProfile.objects
.get_or_create(profile=member.profile))
was_cof = cofprofile.is_cof
request_dict["num"] = cofprofile.num
# Maintenant on remplit le formulaire de profil
cofprofile_form = RegistrationCofProfileForm(
request_dict,
instance=cofprofile
)
2017-02-11 18:41:47 +01:00
profile_form = RegistrationProfileForm(
request_dict,
instance=member.profile
)
forms_are_valid = all((
profile_form.is_valid(),
cofprofile_form.is_valid(),
event_formset.is_valid(),
2017-02-11 18:41:47 +01:00
))
if forms_are_valid:
# Enregistrement du profil
profile = profile_form.save()
if profile.is_cof and not was_cof:
send_custom_mail(
2017-02-11 16:15:17 +01:00
"welcome", "cof@ens.fr", [member.email],
context={'member': member},
)
# Enregistrement des inscriptions aux événements
for form in event_formset:
if 'status' not in form.cleaned_data:
form.cleaned_data['status'] = 'no'
if form.cleaned_data['status'] == 'no':
try:
current_registration = EventRegistration.objects \
.get(user=member, event=form.event)
current_registration.delete()
except EventRegistration.DoesNotExist:
pass
continue
all_choices = get_event_form_choices(form.event, form)
(current_registration, created_reg) = \
EventRegistration.objects.get_or_create(
user=member, event=form.event)
update_event_form_comments(form.event, form,
current_registration)
current_registration.options = all_choices
current_registration.paid = \
(form.cleaned_data['status'] == 'paid')
current_registration.save()
# if form.event.title == "Mega 15" and created_reg:
# field = EventCommentField.objects.get(
# event=form.event, name="Commentaires")
# try:
# comments = EventCommentValue.objects.get(
# commentfield=field,
# registration=current_registration).content
# except EventCommentValue.DoesNotExist:
# comments = field.default
# FIXME : il faut faire quelque chose de propre ici,
# par exemple écrire un mail générique pour
# l'inscription aux événements et/ou donner la
# possibilité d'associer un mail aux événements
# send_custom_mail(...)
success = True
2017-01-30 13:36:51 +01:00
# Messages
if success:
msg = ("L'inscription de {:s} (<tt>{:s}</tt>) a été "
2017-02-11 11:41:49 +01:00
"enregistrée avec succès"
2017-01-30 13:36:51 +01:00
.format(member.get_full_name(), member.email))
if member.profile.is_cof:
msg += "Il est désormais membre du COF n°{:d} !".format(
member.profile.num)
messages.success(request, msg, extra_tags='safe')
2017-02-12 19:36:17 +01:00
return render(request, "cof/registration_post.html",
2017-01-30 13:36:51 +01:00
{"user_form": user_form,
"profile_form": profile_form,
"cofprofile_form": cofprofile_form,
"member": member,
"login_clipper": login_clipper,
"event_formset": event_formset})
else:
return render(request, "registration.html")
@buro_required
def export_members(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=membres_cof.csv'
2016-06-27 19:11:39 +02:00
writer = unicodecsv.writer(response)
for profile in CofProfile.objects.filter(profile__user__groups__name='cof_members').all():
user = profile.user
bits = [profile.num, user.username, user.first_name, user.last_name,
user.email, profile.phone, profile.occupation,
profile.departement, profile.type_cotiz]
2016-07-15 00:02:56 +02:00
writer.writerow([six.text_type(bit) for bit in bits])
return response
def csv_export_mega(filename, qs):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=' + filename
2016-06-27 19:13:53 +02:00
writer = unicodecsv.writer(response)
for reg in qs.all():
user = reg.user
profile = user.profile
comments = "---".join(
[comment.content for comment in reg.comments.all()])
bits = [user.username, user.first_name, user.last_name, user.email,
profile.phone, profile.num,
profile.comments if profile.comments else "", comments]
2016-07-15 00:02:56 +02:00
writer.writerow([six.text_type(bit) for bit in bits])
return response
@buro_required
def export_mega_remarksonly(request):
2016-12-04 10:40:38 +01:00
filename = 'remarques_mega_2016.csv'
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=' + filename
2016-06-27 19:13:53 +02:00
writer = unicodecsv.writer(response)
2016-12-04 10:40:38 +01:00
event = Event.objects.get(title="Mega 2016")
commentfield = event.commentfields.get(name="Commentaires")
for val in commentfield.values.all():
reg = val.registration
user = reg.user
profile = user.profile
bits = [user.username, user.first_name, user.last_name, user.email,
profile.phone, profile.num, profile.comments, val.content]
2016-07-15 00:02:56 +02:00
writer.writerow([six.text_type(bit) for bit in bits])
return response
@buro_required
def export_mega_bytype(request, type):
2015-09-13 18:23:47 +02:00
types = {"orga-actif": "Orga élève",
"orga-branleur": "Orga étudiant",
"conscrit-eleve": "Conscrit élève",
"conscrit-etudiant": "Conscrit étudiant"}
if type not in types:
raise Http404
2016-12-04 10:40:38 +01:00
event = Event.objects.get(title="Mega 2016")
type_option = event.options.get(name="Type")
participant_type = type_option.choices.get(value=types[type]).id
qs = EventRegistration.objects.filter(event=event).filter(
options__id__exact=participant_type)
2016-12-04 10:40:38 +01:00
return csv_export_mega(type + '_mega_2016.csv', qs)
@buro_required
def export_mega_orgas(request):
2016-12-04 10:40:38 +01:00
event = Event.objects.get(title="Mega 2016")
type_option = event.options.get(name="Conscrit ou orga ?")
participant_type = type_option.choices.get(value="Vieux").id
qs = EventRegistration.objects.filter(event=event).exclude(
2016-12-04 10:40:38 +01:00
options__id=participant_type)
return csv_export_mega('orgas_mega_2016.csv', qs)
@buro_required
def export_mega_participants(request):
2016-12-04 10:40:38 +01:00
event = Event.objects.get(title="Mega 2016")
type_option = event.options.get(name="Conscrit ou orga ?")
participant_type = type_option.choices.get(value="Conscrit").id
qs = EventRegistration.objects.filter(event=event).filter(
2016-12-04 10:40:38 +01:00
options__id=participant_type)
return csv_export_mega('participants_mega_2016.csv', qs)
@buro_required
def export_mega(request):
2016-12-04 10:40:38 +01:00
event = Event.objects.filter(title="Mega 2016")
qs = EventRegistration.objects.filter(event=event) \
.order_by("user__username")
2016-12-04 10:40:38 +01:00
return csv_export_mega('all_mega_2016.csv', qs)
@buro_required
def utile_cof(request):
return render(request, "cof/utile_cof.html", {})
@buro_required
def utile_bda(request):
tirages = Tirage.objects.all()
return render(request, "utile_bda.html", {'tirages': tirages})
@buro_required
def liste_bdadiff(request):
titre = "BdA diffusion"
personnes = CofProfile.objects.filter(mailing_bda=True, profile__user__groups__name='cof_members').all()
return render(request, "liste_mails.html",
{"titre": titre, "personnes": personnes})
@buro_required
def liste_bdarevente(request):
titre = "BdA revente"
personnes = CofProfile.objects.filter(mailing_bda_revente=True,
profile__user__groups__name='cof_members').all()
return render(request, "liste_mails.html", {"titre": titre,
"personnes": personnes})
@buro_required
def liste_diffcof(request):
titre = "Diffusion COF"
personnes = CofProfile.objects.filter(mailing_cof=True, user__groups__name='cof_members').all()
return render(request, "liste_mails.html", {"titre": titre,
"personnes": personnes})
@cof_required
def calendar(request):
try:
instance = CalendarSubscription.objects.get(user=request.user)
except CalendarSubscription.DoesNotExist:
instance = None
if request.method == 'POST':
form = CalendarForm(request.POST, instance=instance)
if form.is_valid():
subscription = form.save(commit=False)
if instance is None:
subscription.user = request.user
subscription.token = uuid.uuid4()
subscription.save()
form.save_m2m()
messages.success(request,
"Calendrier mis à jour avec succès.")
return render(request, "cof/calendar_subscription.html",
{'form': form,
'token': str(subscription.token)})
else:
messages.error(request, "Formulaire incorrect.")
return render(request, "cof/calendar_subscription.html",
{'form': form})
else:
return render(request, "cof/calendar_subscription.html",
{'form': CalendarForm(instance=instance),
'token': instance.token if instance else None})
def calendar_ics(request, token):
subscription = get_object_or_404(CalendarSubscription, token=token)
shows = subscription.other_shows.all()
if subscription.subscribe_to_my_shows:
shows |= Spectacle.objects.filter(
attribues__participant__user=subscription.user,
tirage__active=True)
shows = shows.distinct()
vcal = Calendar()
site = Site.objects.get_current()
for show in shows:
vevent = Vevent()
vevent.add('dtstart', show.date)
vevent.add('dtend', show.date + timedelta(seconds=7200))
vevent.add('summary', show.title)
vevent.add('location', show.location.name)
vevent.add('uid', 'show-{:d}-{:d}@{:s}'.format(
show.pk, show.tirage_id, site.domain))
vcal.add_component(vevent)
if subscription.subscribe_to_events:
for event in Event.objects.filter(old=False).all():
vevent = Vevent()
vevent.add('dtstart', event.start_date)
vevent.add('dtend', event.end_date)
vevent.add('summary', event.title)
vevent.add('location', event.location)
vevent.add('description', event.description)
vevent.add('uid', 'event-{:d}@{:s}'.format(
event.pk, site.domain))
vcal.add_component(vevent)
response = HttpResponse(content=vcal.to_ical())
response['Content-Type'] = "text/calendar"
return response