You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

245 lines
9.8 KiB

4 years ago
4 years ago
4 years ago
4 years ago
  1. from datetime import date
  2. from smtplib import SMTPException
  3. from django.shortcuts import render
  4. from django.forms import modelformset_factory
  5. from django.http import HttpResponse
  6. from formtools.wizard.views import CookieWizardView
  7. from django.core.mail import send_mail, BadHeaderError
  8. from django.conf import settings
  9. from django.template.loader import get_template
  10. from django.template import Context
  11. from django.contrib.auth.decorators import login_required
  12. from django.contrib.auth.mixins import LoginRequiredMixin
  13. from django.utils.html import format_html
  14. from .forms import ProjectForm, ExternForm, LibraryForm, IFGForm, LiteratureForm,\
  15. HonoraryCertificateForm, InternForm, TravelForm, EmailForm,\
  16. ListForm, BusinessCardForm, INTERN_CHOICES
  17. from .models import Project, TYPE_CHOICES, Library, Literature
  18. from .settings import IF_EMAIL
  19. def auth_deny(choice,pk,auth):
  20. if choice in ('BIB', 'ELIT', 'SOFT'):
  21. Library.set_granted(pk,auth)
  22. if choice == 'LIT':
  23. Literature.set_granted(pk,auth)
  24. if choice == 'IFG':
  25. IFG.set_granted(pk,auth)
  26. else:
  27. return HttpResponse(f'ERROR! UNKNWON CHOICE TYPE! {choice}')
  28. return False
  29. @login_required
  30. def authorize(request, choice, pk):
  31. '''If IF grant a support they click a link in a mail which leads here.
  32. We write the granted field in the database here and set a timestamp.'''
  33. ret = auth_deny(choice, pk, True)
  34. if ret:
  35. return ret
  36. else:
  37. return HttpResponse(f"AUTHORIZED! choice: {choice}, pk: {pk}")
  38. @login_required
  39. def deny(request, choice, pk):
  40. '''If IF denies a support they click a link in a mail which leads here
  41. We write the granted field in the database here.'''
  42. ret = auth_deny(choice, pk, False)
  43. if ret:
  44. return ret
  45. else:
  46. return HttpResponse(f"DENIED! choice: {choice}, pk: {pk}")
  47. def done(request):
  48. 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 Ideenförderung unter community@wikimedia.de.")
  49. class InternView(LoginRequiredMixin, CookieWizardView):
  50. '''This View is for WMDE-employees only'''
  51. template_name = 'input/extern.html'
  52. form_list = [InternForm, ProjectForm]
  53. def get_form(self, step=None, data=None, files=None):
  54. '''this function determines which part of the multipart form is
  55. displayed next'''
  56. if step is None:
  57. step = self.steps.current
  58. print ("get_form() step " + step)
  59. if step == '1':
  60. prev_data = self.get_cleaned_data_for_step('0')
  61. choice = prev_data.get('choice')
  62. print(f'choice detection: {INTERN_CHOICES[choice]}')
  63. if choice == 'HON':
  64. form = HonoraryCertificateForm(data)
  65. elif choice == 'PRO':
  66. form = ProjectForm(data)
  67. elif choice == 'TRAV':
  68. form = TravelForm(data)
  69. else:
  70. raise RuntimeError(f'ERROR! UNKNOWN FORMTYPE {choice} in InternView')
  71. self.choice = choice
  72. else:
  73. form = super().get_form(step, data, files)
  74. form.fields['realname'].help_text = format_html("Vor- und Zuname (Realname), Wer hat das Projekt beantragt?<br>\
  75. Wer ist Hauptansprechperson? Bei WMDE-MAs immer (WMDE),<br>\
  76. bei externen Partnern (PART) hinzufügen.")
  77. return form
  78. def get_context_data(self, **kwargs):
  79. context = super().get_context_data(**kwargs)
  80. if hasattr(self, 'choice'):
  81. context["choice"] = INTERN_CHOICES[self.choice]
  82. return context
  83. def done(self, form_list, **kwargs):
  84. print('InternView.done() reached')
  85. # gather data from all forms
  86. data = {}
  87. for form in form_list:
  88. data = {**data, **form.cleaned_data}
  89. print(data)
  90. # write data to database
  91. form = form.save(commit=False)
  92. # we have to copy the data from the first form here
  93. # this is ugly code. how can we copy this without explicit writing?
  94. # i found no way to access the ModelForm.Meta.exclude-tupel
  95. form.realname = data['realname']
  96. # form.username = data['username']
  97. form.email = data['email']
  98. form.granted = True
  99. form.granted_date = date.today()
  100. form.save()
  101. return done(self.request)
  102. # these where used as labels in the second form TYPE_CHOICES is used for the first form and the
  103. # text above the second form. only used for BIB, SOFT, ELIT in the moment
  104. LABEL_CHOICES = {'BIB': format_html('Bibliothek'),
  105. 'ELIT': format_html('Datenbank/Online-Ressource'),
  106. 'MAIL': format_html('E-Mail-Adresse'),
  107. 'IFG': format_html('Kostenübernahme IFG-Anfrage'),
  108. 'LIT': format_html('Literaturstipendium'),
  109. 'LIST': format_html('Mailingliste'),
  110. 'SOFT': format_html('Software'),
  111. 'VIS': format_html('Visitenkarten'),
  112. }
  113. HELP_CHOICES = {'BIB': format_html("In welchem Zeitraum möchtest du recherchieren oder<br>wie lange ist der Bibliotheksausweis gültig?"),
  114. 'ELIT': "Wie lange gilt der Zugang?",
  115. 'SOFT': "Wie lange gilt die Lizenz?",
  116. }
  117. class ExternView(CookieWizardView):
  118. '''This View is for Volunteers'''
  119. template_name = "input/extern.html"
  120. form_list = [ExternForm, LibraryForm]
  121. def get_form(self, step=None, data=None, files=None):
  122. '''this function determines which part of the multipart form is
  123. displayed next'''
  124. if step is None:
  125. step = self.steps.current
  126. print ("get_form() step " + step)
  127. if step == '1':
  128. prev_data = self.get_cleaned_data_for_step('0')
  129. choice = prev_data.get('choice')
  130. print(f'choice detection in ExternView: {TYPE_CHOICES[choice]}')
  131. if choice == 'IFG':
  132. form = IFGForm(data)
  133. form.fields['notes'].help_text = format_html("Bitte gib an, wie die gewonnenen Informationen den<br>Wikimedia-Projekten zugute kommen sollen.")
  134. elif choice in ('BIB', 'SOFT', 'ELIT'):
  135. form = LibraryForm(data)
  136. form.fields['library'].label = LABEL_CHOICES[choice]
  137. form.fields['library'].help_text = f"Für welche {LABEL_CHOICES[choice]} gilt das Stipendium?"
  138. form.fields['duration'].help_text = HELP_CHOICES[choice]
  139. elif choice == 'MAIL':
  140. form = EmailForm(data)
  141. form.fields['domain'].help_text = format_html("Mit welcher Domain, bzw. für welches Wikimedia-Projekt,<br>möchtest du eine Mailadresse beantragen?")
  142. elif choice == 'LIT':
  143. form = LiteratureForm(data)
  144. form.fields['notes'].help_text = "Bitte gib an, wofür du die Literatur verwenden möchtest."
  145. elif choice == 'VIS':
  146. form = BusinessCardForm(data)
  147. elif choice == 'LIST':
  148. form = ListForm(data)
  149. form.fields['domain'].help_text = format_html("Mit welcher Domain, bzw. für welches Wikimedia-Projekt,<br>möchtest du eine Mailingliste beantragen?")
  150. else:
  151. raise RuntimeError(f'ERROR! UNKNOWN FORMTYPE {choice} in ExternView')
  152. self.choice = choice
  153. else:
  154. form = super().get_form(step, data, files)
  155. return form
  156. def get_context_data(self, **kwargs):
  157. context = super().get_context_data(**kwargs)
  158. if hasattr(self, 'choice'):
  159. context["choice"] = TYPE_CHOICES[self.choice]
  160. return context
  161. def done(self, form_list, **kwargs):
  162. print('ExternView.done() reached')
  163. # gather data from all forms
  164. data = {}
  165. for form in form_list:
  166. data = {**data, **form.cleaned_data}
  167. print(data)
  168. # write data to database
  169. modell = form.save(commit=False)
  170. # we have to copy the data from the first form here
  171. # this is a bit ugly code. can we copy this without explicit writing?
  172. modell.realname = data['realname']
  173. # form.username = data['username']
  174. modell.email = data['email']
  175. # write type of form in some cases
  176. if data['choice'] in ('BIB', 'ELIT', 'SOFT'):
  177. modell.type = data['choice']
  178. form.save()
  179. # add some data to context for mail templates
  180. data['pk'] = modell.pk
  181. data['urlprefix'] = settings.URLPREFIX
  182. data['grant'] = ('LIT', 'SOFT', 'ELIT', 'BIB', 'IFG')
  183. data['DOMAIN'] = ('MAIL', 'LIST')
  184. data['typestring'] = TYPE_CHOICES[data['choice']]
  185. # we need to send the following mails here:
  186. context = { 'data': data }
  187. try:
  188. # - mail with entered data to the Volunteer
  189. mail_template = get_template('input/ifg_volunteer_mail.txt')
  190. send_mail(
  191. 'Formular ausgefüllt',
  192. mail_template.render(context),
  193. IF_EMAIL,
  194. [data['email']],
  195. fail_silently=False)
  196. # - mail to IF with link to accept/decline
  197. mail_template = get_template('input/if_mail.txt')
  198. send_mail(
  199. 'Formular ausgefüllt',
  200. mail_template.render(context),
  201. IF_EMAIL,
  202. [IF_EMAIL],
  203. fail_silently=False)
  204. # raise SMTPException("testing pupose only")
  205. except BadHeaderError:
  206. modell.delete()
  207. return HttpResponse('Invalid header found. Data not saved!')
  208. except SMTPException:
  209. modell.delete()
  210. return HttpResponse('Error in sending mails (propably wrong adress?). Data not saved!')
  211. return done(self.request)