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.

299 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. data['username'] = self.request.session['user']['username']
  188. if data['choice'] == 'LIT':
  189. if data['selfbuy'] == 'TRUE':
  190. data['selfbuy_give_data'] = 'False'
  191. # write data to database
  192. modell = form.save(commit=False)
  193. # we have to copy the data from the first form here
  194. # this is a bit ugly code. can we copy this without explicit writing?
  195. if data['choice'] == 'LIT':
  196. modell.selfbuy_give_data = data['selfbuy_give_data']
  197. modell.realname = data['realname']
  198. modell.username = data['username']
  199. modell.email = data['email']
  200. # write type of form in some cases
  201. if data['choice'] in ('BIB', 'ELIT', 'SOFT'):
  202. modell.type = data['choice']
  203. form.save()
  204. # add some data to context for mail templates
  205. data['pk'] = modell.pk
  206. data['urlprefix'] = settings.URLPREFIX
  207. data['grant'] = ('LIT', 'SOFT', 'ELIT', 'BIB', 'IFG')
  208. data['DOMAIN'] = ('MAIL', 'LIST')
  209. data['typestring'] = TYPE_CHOICES[data['choice']]
  210. # we need to send the following mails here:
  211. context = { 'data': data }
  212. try:
  213. # - mail with entered data to the Volunteer
  214. txt_mail_template1 = get_template('input/ifg_volunteer_mail.txt')
  215. html_mail_template1 = get_template('input/ifg_volunteer_mail.html')
  216. subject1, from_email1, to1 = 'Formular ausgefüllt', IF_EMAIL, data['email']
  217. text_content1 = txt_mail_template1.render(context)
  218. html_content1 = html_mail_template1.render(context)
  219. msg1 = EmailMultiAlternatives(subject1, text_content1, from_email1, [to1])
  220. msg1.attach_alternative(html_content1, "text/html")
  221. msg1.send()
  222. #print('ifg volunteer mail would have been sent')
  223. #send_mail(
  224. # 'Formular ausgefüllt',
  225. # txt_mail_template1.render(context),
  226. # IF_EMAIL,
  227. # [data['email']],
  228. # fail_silently=False)
  229. ## - mail to IF with link to accept/decline
  230. txt_mail_template = get_template('input/if_mail.txt')
  231. html_mail_template = get_template('input/if_mail.html')
  232. subject, from_email, to = 'Formular ausgefüllt', IF_EMAIL, IF_EMAIL
  233. text_content = txt_mail_template.render(context)
  234. html_content = html_mail_template.render(context)
  235. msg2 = EmailMultiAlternatives(subject, text_content, from_email, [to])
  236. msg2.attach_alternative(html_content, "text/html")
  237. msg2.send()
  238. #print('if mail would have been sent')
  239. #send_mail(
  240. # 'Formular ausgefüllt',
  241. # txt_mail_template.render(context),
  242. # IF_EMAIL,
  243. # [IF_EMAIL],
  244. # fail_silently=False)
  245. ## raise SMTPException("testing pupose only")
  246. except BadHeaderError:
  247. modell.delete()
  248. return HttpResponse('Invalid header found. Data not saved!')
  249. except SMTPException:
  250. modell.delete()
  251. return HttpResponse('Error in sending mails (probably wrong adress?). Data not saved!')
  252. return done(self.request)