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.

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