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.

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