Newer
Older
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.http import HttpRequest, HttpResponse
from django.utils.decorators import method_decorator
from django.utils.text import slugify
from django.views.decorators.cache import never_cache
from django.views.generic.detail import DetailView
import reversion
from django_tables2 import RequestConfig
from django_tables2.views import SingleTableView
from formtools.wizard.views import SessionWizardView
from reversion.views import RevisionMixin
from rules.contrib.views import PermissionRequiredMixin, permission_required
from templated_email import send_templated_mail
from aleksis.apps.postbuero.models import MailAddress
from aleksis.core.mixins import AdvancedCreateView, AdvancedDeleteView, AdvancedEditView
from aleksis.core.models import Activity, Person
from aleksis.core.util import messages
from aleksis.core.util.core_helpers import lazy_preference, objectgetter_optional
from .filters import EventFilter, EventRegistrationFilter, VoucherFilter, TermsFilter
from .forms import (
EditEventForm,
EditEventRegistrationForm,
EditVoucherForm,
GenerateListForm,
from .models import Event, EventRegistration, Voucher, Terms
from .tables import EventRegistrationsTable, ManageEventsTable, VouchersTable, TermsTable
@method_decorator(never_cache, name="dispatch")
class CreateEventView(PermissionRequiredMixin, AdvancedCreateView):
form_class = EditEventForm
model = Event
permission_required = "paweljong.change_event"
template_name = "paweljong/event/create.html"
success_url = reverse_lazy("mange_events")
success_message = _("The event has been saved.")
@method_decorator(never_cache, name="dispatch")
class EditEventView(PermissionRequiredMixin, RevisionMixin, AdvancedEditView):
form_class = EditEventForm
model = Event
permission_required = "paweljong.change_event"
context_object_name = "manage_events"
template_name = "paweljong/event/edit.html"
success_url = reverse_lazy("manage_events")
success_message = _("The event has been saved.")
@permission_required("paweljong.change_events")
def manage_events(request: HttpRequest) -> HttpResponse:
"""List view listing all registrations."""
context = {}
# Get all registrations
now = timezone.datetime.today()
events = Event.objects.filter(date_event__gte=now)
# Get filter
events_filter = EventFilter(request.GET, queryset=events)
context["events_filter"] = events_filter
# Build table
events_table = ManageEventsTable(events_filter.qs)
RequestConfig(request).configure(events_table)
context["events_table"] = events_table
return render(request, "paweljong/event/manage.html", context)
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
@permission_required("paweljong.view_vouchers")
def vouchers(request):
context = {}
# Get all unused vouchers
vouchers = Voucher.objects.filter(used=False, deleted=False)
# Get filter
vouchers_filter = VoucherFilter(request.GET, queryset=vouchers)
context["vouchers_filter"] = vouchers_filter
# Build table
vouchers_table = VouchersTable(vouchers_filter.qs)
RequestConfig(request).configure(vouchers_table)
context["vouchers_table"] = vouchers_table
return render(request, "paweljong/voucher/list.html", context)
@permission_required("paweljong.generate_lists")
def generate_lists(request: HttpRequest) -> HttpResponse:
context = {}
generate_list_form = GenerateListForm()
if request.method == "POST":
generate_list_form = GenerateListForm(request.POST)
if generate_list_form.is_valid():
context["group"] = generate_list_form.cleaned_data["group"]
template = generate_list_form.cleaned_data["template"]
context["landscape"] = generate_list_form.cleaned_data["landscape"]
return render(request, "paweljong/print/%s.html" % (template), context)
context["generate_list_form"] = generate_list_form
return render(request, "paweljong/print/manage.html", context)
@permission_required("paweljong.view_registrations")
def registrations(request: HttpRequest) -> HttpResponse:
"""List view listing all registrations."""
context = {}
# Get all registrations
registrations = EventRegistration.objects.all()
# Get filter
registrations_filter = EventRegistrationFilter(request.GET, queryset=registrations)
context["registrations_filter"] = registrations_filter
# Build table
registrations_table = EventRegistrationsTable(registrations_filter.qs)
RequestConfig(request).configure(registrations_table)
context["registrations_table"] = registrations_table
return render(request, "paweljong/event_registration/list.html", context)
@method_decorator(never_cache, name="dispatch")
class EventRegistrationCreateView(PermissionRequiredMixin, AdvancedCreateView):
"""Create view for event registrations."""
model = EventRegistration
form_class = EditEventRegistrationForm
permission_required = "paweljong.manage_registration"
template_name = "paweljong/event_registration/create.html"
success_url = reverse_lazy("event_registrations")
success_message = _("The event registration has been created.")
@method_decorator(never_cache, name="dispatch")
class EventRegistrationEditView(PermissionRequiredMixin, AdvancedEditView):
"""Edit view for event registrations."""
model = EventRegistration
form_class = EditEventRegistrationForm
permission_required = "paweljong.manage_eventregistration"
template_name = "paweljong/event_registration/edit.html"
success_url = reverse_lazy("event_registrations")
success_message = _("The event registration has been saved.")
@permission_required(
"paweljong.manage_registrations",
fn=objectgetter_optional(EventRegistration, None, False),
)
def edit_registration(request: HttpRequest, pk) -> HttpResponse:
registration = objectgetter_optional(EventRegistration, None, False)(request, pk)
edit_event_registration_form = EditEventRegistrationForm(
request.POST or None, instance=registration
)
if request.method == "POST":
if edit_event_registration_form.is_valid():
with reversion.create_revision():
edit_event_registration_form.save(commit=True)
messages.success(request, _("The registration has been saved."))
return redirect("registration")
context["edit_event_registration_form"] = edit_event_registration_form
return render(request, "paweljong/event_registration/edit.html", context)
@permission_required("paweljong.is_own_voucher", fn=objectgetter_optional(Voucher, None, False))
def print_voucher(request: HttpRequest, pk) -> HttpResponse:
context["voucher"] = voucher
return render(request, "paweljong/print/voucher.html", context)
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
class EventRegistrationDetailView(PermissionRequiredMixin, DetailView):
"""Detail view for an application instance."""
context_object_name = "registration"
permission_required = "paweljong.view_registration"
template_name = "paweljong/event_registration/full.html"
def get_queryset(self):
return EventRegistration.objects.all()
class EventRegistrationDeleteView(PermissionRequiredMixin, AdvancedDeleteView):
"""Delete view for registrations."""
model = EventRegistration
permission_required = "paweljong.delete_eventregistration"
template_name = "core/pages/delete.html"
success_url = reverse_lazy("registrations")
success_message = _("The registration has been deleted.")
@method_decorator(never_cache, name="dispatch")
class VoucherCreateView(PermissionRequiredMixin, AdvancedCreateView):
"""Create view for vouchers."""
model = Voucher
form_class = EditVoucherForm
permission_required = "paweljong.add_voucher"
template_name = "paweljong/voucher/create.html"
success_url = reverse_lazy("vouchers")
success_message = _("The voucher has been created.")
@method_decorator(never_cache, name="dispatch")
class VoucherEditView(PermissionRequiredMixin, AdvancedEditView):
"""Edit view for vouchers."""
model = Voucher
form_class = EditVoucherForm
permission_required = "paweljong.edit_voucher"
template_name = "paweljong/voucher/edit.html"
success_url = reverse_lazy("vouchers")
success_message = _("The voucher has been saved.")
class VoucherDeleteView(PermissionRequiredMixin, AdvancedDeleteView):
"""Delete view for vouchers."""
model = Voucher
permission_required = "paweljong.delete_voucher"
template_name = "core/pages/delete.html"
success_url = reverse_lazy("vouchers")
success_message = _("The voucher has been deleted.")
def is_person_anonymous(wizard):
return wizard.request.user.is_anonymous
def is_email_needed(wizard):
if wizard.request.session.get("email_needed"):
wizard.request.session.pop("email_needed")
return True
class RegisterEventWizardView(SessionWizardView):
template_name = "paweljong/event/register_wizard.html"
file_storage = settings.DEFAULT_FILE_STORAGE
def get_context_data(self, form, **kwargs):
context = super().get_context_data(form, **kwargs)
context["event"] = Event.objects.get(linked_group__short_name=self.kwargs["slug"])
if self.steps.current == "email":
context["page_title"] = ""
context["browser_title"] = ""
context["info_title"] = _("Create e-mail address")
context["info_text"] = _("All participants need a personal e-mail address, which they check and read "
"temselves. We offer the possibility to register an e-mail address "
"on our secure servers, made for young users.")
elif self.steps.current == "register":
context["page_title"] = ""
context["browser_title"] = ""
context["info_title"] = _("Event registration")
context["info_text"] = _("First, please enter some basic information about yourself, and check "
"whether all information is correct.")
elif self.steps.current == "contact_details":
context["page_title"] = ""
context["browser_title"] = ""
context["info_title"] = _("Contact information")
context["info_text"] = _("Tell us how we can contact you. You will receive information about "
"the event by e-mail. Please use your personal e-mail address "
"where you will read mails yourself, not an address of your parents. "
"We will always send all important information to your parents as well, "
"and you will enter their e-mail address on the next page.")
elif self.steps.current == "guardians":
context["page_title"] = ""
context["browser_title"] = ""
context["info_title"] = _("Legal guardians / parents")
context["info_text"] = _("Tell us how we can reach your parents or other legal guardians. "
"This should be the person who was present when you registered for the "
"event (which is now). If you want to add another parent, please tell us "
"later as a comment.")
elif self.steps.current == "additional":
context["page_title"] = ""
context["browser_title"] = ""
context["info_title"] = _("Additional registration information")
context["info_text"] = _("Please answer the following questions as precisely as you can, so "
"we can make sure your event attendance will be organised as wel las possible.")
elif self.steps.current == "financial":
context["page_title"] = ""
context["browser_title"] = ""
context["info_title"] = _("Payment")
context["info_text"] = _("By default, we will send you an invoice, which you or your parents "
"can pay by bank transfer. You can also choose to pay by direct debit – "
"please make sure to enter exactly what your parents tell you.")
elif self.steps.current == "consent":
context["page_title"] = ""
context["browser_title"] = ""
context["info_title"] = _("Consent")
context["info_text"] = _("Lastly, please read the terms and conditions carefully, together "
"with your parents. After that, you will need to confirm that you "
"agree with everything yourself, and that your parents also agree.")
return context
def get_form_kwargs(self, step):
kwargs = super().get_form_kwargs()
if step == "email":
kwargs["request"] = self.request
if step == "additional" or step == "consent":
event = Event.objects.get(linked_group__short_name=self.kwargs["slug"])
kwargs["event"] = event
return kwargs
def get_form_initial(self, step):
initial = self.initial_dict.get(step, {})
if step == "register":
cleaned_data_email = self.get_cleaned_data_for_step("email")
if cleaned_data_email:
domain = cleaned_data_email["domain"]
email = f"{cleaned_data_email['local_part']}@{domain.domain}"
initial.update(
{
"email": email,
"email2": email,
}
)
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
if step == "guardians":
if hasattr(self.request.user, "person"):
person = self.request.user.person
if person.guardians.first():
initial.update(
{
"guardian_first_name": person.guardians.first().first_name,
"guardian_last_name": person.guardians.first().last_name,
"guardian_mobile_number": person.guardians.first().mobile_number,
"guardian_email": person.guardians.first().email,
}
)
if step == "contact_details":
if hasattr(self.request.user, "person"):
person = self.request.user.person
initial.update(
{
"first_name": person.first_name,
"last_name": person.last_name,
"mobile_number": person.mobile_number,
"email": person.email,
"street": person.street,
"place": person.place,
"housenumber": person.housenumber,
"sex": person.sex,
"date_of_birth": person.date_of_birth,
"postal_code": person.postal_code,
}
else:
cleaned_data_register = self.get_cleaned_data_for_step("register")
if cleaned_data_register:
initial.update(
{
"first_name": cleaned_data_register["first_name"],
"last_name": cleaned_data_register["last_name"],
"email": cleaned_data_register["email"],
"date_of_birth": cleaned_data_register["date_of_birth"],
}
)
return self.initial_dict.get(step, initial)
def done(self, form_list, **kwargs):
event = Event.objects.get(linked_group__short_name=self.kwargs["slug"])
cleaned_data_email = self.get_cleaned_data_for_step("email")
cleaned_data_contact_details = self.get_cleaned_data_for_step("contact_details")
cleaned_data_guardians = self.get_cleaned_data_for_step("guardians")
cleaned_data_register = self.get_cleaned_data_for_step("register")
cleaned_data_additional = self.get_cleaned_data_for_step("additional")
cleaned_data_financial = self.get_cleaned_data_for_step("financial")
cleaned_data_consent = self.get_cleaned_data_for_step("consent")
if cleaned_data_financial["voucher_code"] != "":
vouchers = Voucher.objects.filter(person=person, event=event, used=False, code=cleaned_data_financial["voucher_code"])
if vouchers:
voucher = vouchers.first()
else:
messages.error(self.request, _("You entered an invalid voucher code!"))
# Create email address
if cleaned_data_email:
_email = MailAddress.objects.create(
local_part=cleaned_data_email["local_part"],
domain=cleaned_data_email["domain"],
)
# Create user
if cleaned_data_register:
user = User.objects.create(
username=cleaned_data_register["username"],
email=cleaned_data_register["email"],
)
user.set_password(cleaned_data_register["password1"])
user.save()
else:
user = self.request.user
user=user,
defaults={
"email": cleaned_data_contact_details["email"],
"first_name": cleaned_data_contact_details["first_name"],
"last_name": cleaned_data_contact_details["last_name"],
}
)
or "sex" in cleaned_data_contact_details
or "date_of_birth" in cleaned_data_contact_details
):
person.mobile_number = cleaned_data_contact_details["mobile_number"]
person.sex = cleaned_data_contact_details["sex"]
person.date_of_birth = cleaned_data_contact_details["date_of_birth"]
person.save()
# Store postal address in database
if (
"postal_code" in cleaned_data_contact_details
or "place" in cleaned_data_contact_details
or "street" in cleaned_data_contact_details
):
person.street = cleaned_data_contact_details["street"]
person.postal_code = cleaned_data_contact_details["postal_code"]
person.place = cleaned_data_contact_details["place"]
person.housenumber = cleaned_data_contact_details["housenumber"]
person.save()
if (
"guardian_first_name" in cleaned_data_guardians
or "guardian_last_name" in cleaned_data_guardians
or "guardian_mobile_number" in cleaned_data_guardians
or "guardian_email" in cleaned_data_guardians
):
guardian = Person.objects.get_or_create(
defaults={
"first_name": cleaned_data_guardians["guardian_first_name"],
"last_name": cleaned_data_guardians["guardian_last_name"],
"mobile_number": cleaned_data_guardians["guardian_mobile_number"],
},
first_name=cleaned_data_guardians["guardian_first_name"],
last_name=cleaned_data_guardians["guardian_last_name"],
email=cleaned_data_guardians["guardian_email"],
)
person.guardians.add(guardian[0])
person.save()
if cleaned_data_email:
_email.person = person
_email.save()
# Add the current person to the event
event.linked_group.members.add(person)
registration = EventRegistration.objects.create(
event=event,
person=person,
medical_information=cleaned_data_additional["medical_information"],
donation=cleaned_data_financial["donation"],
accept_sepa=cleaned_data_financial["accept_sepa"],
iban=cleaned_data_financial["iban"],
school = cleaned_data_contact_details["school"],
school_class = cleaned_data_contact_details["school_class"],
school_place = cleaned_data_contact_details["school_place"],
)
for field in event.linked_group.additional_fields.all():
registration.extended_data[
slugify(field.title).replace("-", "_")
] = cleaned_data_additional[field.title]
for field in event.terms.all():
registration.extended_data[slugify(field.title).replace("-", "_")] = cleaned_data_consent[field.title]
registration.save()
if cleaned_data_financial["voucher_code"] != "":
vouchers = Voucher.objects.filter(person=person, event=event, used=False, code=cleaned_data_financial["voucher_code"])
if vouchers:
voucher = vouchers.first()
voucher.used = True
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
registration.save()
else:
messages.error(self.request, _("You entered an invalid voucher code!"))
context = {}
context["registration"] = registration
send_templated_mail(
template_name="event_registred",
from_email=lazy_preference("mail", "address"),
recipient_list=["orga@teckids.org"],
headers={
"reply_to": [
person.email,
person.guardians.first().email,
],
},
context=context,
)
messages.success(
self.request,
_(
"You have successfully registered for the event. Please give us "
"up to two days to process your registration. You will then "
"receive an email from us."
),
)
act = Activity(
title=_("You registred for an event"),
description=_("You registred for the event %s" % event.display_name),
user=person,
)
act.save()
return redirect("index")
class EventFullView(DetailView):
template_name = "paweljong/event/full.html"
object_context_name = "event"
context = super().get_context_data(**kwargs)
context["can_register"] = context["event"].can_register(request=self.request)
return context
class RegisterEventStart(DetailView):
model = Event
template_name = "paweljong/event/register_start.html"
object_context_name = "event"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["can_register"] = context["event"].can_register(request=self.request)
return context
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
class TermListView(PermissionRequiredMixin, SingleTableView):
"""Table of all terms."""
model = Terms
table_class = TermsTable
permission_required = "paweljong.view_terms"
template_name = "paweljong/term/list.html"
@method_decorator(never_cache, name="dispatch")
class TermCreateView(PermissionRequiredMixin, AdvancedCreateView):
"""Create view for terms."""
model = Terms
form_class = EditTermForm
permission_required = "paweljong.add_terms"
template_name = "paweljong/term/create.html"
success_url = reverse_lazy("terms")
success_message = _("The term has been created.")
@method_decorator(never_cache, name="dispatch")
class TermEditView(PermissionRequiredMixin, AdvancedEditView):
"""Edit view for terms."""
model = Terms
form_class = EditTermForm
permission_required = "paweljong.edit_terms"
template_name = "paweljong/term/edit.html"
success_url = reverse_lazy("terms")
success_message = _("The term has been saved.")