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.

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