foerderbarometer/input/views.py

216 lines
7.7 KiB
Python
Executable File

from smtplib import SMTPException
from django.shortcuts import render
from django.http import HttpResponse
from django.utils.safestring import mark_safe
from formtools.wizard.views import CookieWizardView
from django.core.mail import BadHeaderError, EmailMultiAlternatives
from django.template.loader import get_template
from django.conf import settings
from django.contrib.auth.decorators import login_required
from .forms import (
ExternForm,
LibraryForm,
ELiteratureForm,
SoftwareForm,
IFGForm,
LiteratureForm,
TravelForm,
EmailForm,
ListForm,
BusinessCardForm,
)
from .models import TYPE_CHOICES, MODELS, TYPE_BIB, TYPE_ELIT, TYPE_SOFT
LIBRARY_FORMS = {
TYPE_BIB: LibraryForm,
TYPE_ELIT: ELiteratureForm,
TYPE_SOFT: SoftwareForm,
}
def auth_deny(choice, pk, auth):
if choice not in MODELS:
return HttpResponse(f'ERROR! UNKNOWN CHOICE TYPE! {choice}')
MODELS[choice].set_granted(pk, auth)
return False
@login_required
def export(request):
'''export the project database to a csv'''
return HttpResponse('WE WANT CSV!')
@login_required
def authorize(request, choice, pk):
'''If IF grant a support they click a link in a mail which leads here.
We write the granted field in the database here and set a timestamp.'''
ret = auth_deny(choice, pk, True)
if ret:
return ret
else:
return HttpResponse(f"AUTHORIZED! choice: {choice}, pk: {pk}")
@login_required
def deny(request, choice, pk):
'''If IF denies a support they click a link in a mail which leads here
We write the granted field in the database here.'''
ret = auth_deny(choice, pk, False)
if ret:
return ret
else:
return HttpResponse(f"DENIED! choice: {choice}, pk: {pk}")
def done(request):
return HttpResponse("Deine Anfrage wurde gesendet. Du erhältst in Kürze eine E-Mail-Benachrichtigung mit deinen Angaben. Für alle Fragen kontaktiere bitte das Team Communitys und Engagement unter community@wikimedia.de.")
def index(request):
return render(request, 'input/index.html')
class ExternView(CookieWizardView):
'''This View is for Volunteers'''
template_name = "input/extern.html"
form_list = [ExternForm, LibraryForm]
def get_form(self, step=None, data=None, files=None):
'''this function determines which part of the multipart form is
displayed next'''
if step is None:
step = self.steps.current
print ("get_form() step " + step)
if step == '1':
prev_data = self.get_cleaned_data_for_step('0')
choice = prev_data.get('choice')
print(f'choice detection in ExternView: {TYPE_CHOICES[choice]}')
if choice == 'IFG':
form = IFGForm(data)
form.fields['notes'].help_text = mark_safe("Bitte gib an, wie die gewonnenen Informationen den<br>Wikimedia-Projekten zugute kommen sollen.")
elif choice in LIBRARY_FORMS:
form = LIBRARY_FORMS[choice](data)
elif choice == 'MAIL':
form = EmailForm(data)
form.fields['domain'].help_text = mark_safe("Mit welcher Domain, bzw. für welches Wikimedia-Projekt,<br>möchtest du eine Mailadresse beantragen?")
elif choice == 'LIT':
form = LiteratureForm(data)
form.fields['notes'].help_text = "Bitte gib an, wofür du die Literatur verwenden möchtest."
elif choice == 'VIS':
form = BusinessCardForm(data)
elif choice == 'LIST':
form = ListForm(data)
form.fields['domain'].help_text = mark_safe("Mit welcher Domain, bzw. für welches Wikimedia-Projekt,<br>möchtest du eine Mailingliste beantragen?")
elif choice == 'TRAV':
form = TravelForm(data)
else: # pragma: no cover
raise RuntimeError(f'ERROR! UNKNOWN FORMTYPE {choice} in ExternView')
self.choice = choice
else:
form = super().get_form(step, data, files)
return form
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if hasattr(self, 'choice'):
context["choice"] = TYPE_CHOICES[self.choice]
return context
def done(self, form_list, **kwargs):
print('ExternView.done() reached')
# gather data from all forms
data = {}
for form in form_list:
data = {**data, **form.cleaned_data}
if data['choice'] == 'LIT':
if data['selfbuy'] == 'TRUE':
data['selfbuy_give_data'] = 'False'
# write data to database
modell = form.save(commit=False)
# we have to copy the data from the first form here
# this is a bit ugly code. can we copy this without explicit writing?
if data['choice'] == 'LIT':
modell.selfbuy_give_data = data['selfbuy_give_data']
if user := self.request.session.get('user'):
modell.username = user['username']
modell.realname = data['realname']
modell.email = data['email']
# write type of form in some cases
if data['choice'] in ('BIB', 'ELIT', 'SOFT'):
modell.type = data['choice']
form.save()
# add some data to context for mail templates
data['pk'] = modell.pk
data['url_prefix'] = settings.EMAIL_URL_PREFIX
data['grant'] = ('LIT', 'SOFT', 'ELIT', 'BIB', 'IFG')
data['DOMAIN'] = ('MAIL', 'LIST')
data['typestring'] = TYPE_CHOICES[data['choice']]
# we need to send the following mails here:
context = { 'data': data }
try:
# - mail with entered data to the Volunteer
txt_mail_template1 = get_template('input/ifg_volunteer_mail.txt')
html_mail_template1 = get_template('input/ifg_volunteer_mail.html')
subject1, from_email1, to1 = 'Formular ausgefüllt', settings.IF_EMAIL, data['email']
text_content1 = txt_mail_template1.render(context)
html_content1 = html_mail_template1.render(context)
msg1 = EmailMultiAlternatives(subject1, text_content1, from_email1, [to1])
msg1.attach_alternative(html_content1, "text/html")
msg1.send()
#print('ifg volunteer mail would have been sent')
#send_mail(
# 'Formular ausgefüllt',
# txt_mail_template1.render(context),
# IF_EMAIL,
# [data['email']],
# fail_silently=False)
## - mail to IF with link to accept/decline
txt_mail_template = get_template('input/if_mail.txt')
html_mail_template = get_template('input/if_mail.html')
subject, from_email, to = 'Formular ausgefüllt', settings.IF_EMAIL, settings.IF_EMAIL
text_content = txt_mail_template.render(context)
html_content = html_mail_template.render(context)
msg2 = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg2.attach_alternative(html_content, "text/html")
msg2.send()
#print('if mail would have been sent')
#send_mail(
# 'Formular ausgefüllt',
# txt_mail_template.render(context),
# IF_EMAIL,
# [IF_EMAIL],
# fail_silently=False)
## raise SMTPException("testing pupose only")
except BadHeaderError:
modell.delete()
return HttpResponse('Invalid header found. Data not saved!')
except SMTPException:
modell.delete()
return HttpResponse('Error in sending mails (probably wrong adress?). Data not saved!')
return done(self.request)