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.

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