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.

288 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 .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 Communitys und Engagement 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. if data['selfbuy'] == 'TRUE':
  96. data['selfbuy_give_data'] = 'False'
  97. print(data)
  98. # write data to database
  99. form = form.save(commit=False)
  100. # we have to copy the data from the first form here
  101. # this is ugly code. how can we copy this without explicit writing?
  102. # i found no way to access the ModelForm.Meta.exclude-tupel
  103. form.realname = data['realname']
  104. # form.username = data['username']
  105. form.email = data['email']
  106. form.granted = True
  107. form.granted_date = date.today()
  108. if data['choice'] == 'LIT':
  109. form.selfbuy_give_data = data['selfbuy_give_data']
  110. form.save()
  111. return done(self.request)
  112. # these where used as labels in the second form TYPE_CHOICES is used for the first form and the
  113. # text above the second form. only used for BIB, SOFT, ELIT in the moment
  114. LABEL_CHOICES = {'BIB': format_html('Bibliothek'),
  115. 'ELIT': format_html('Datenbank/Online-Ressource'),
  116. 'MAIL': format_html('E-Mail-Adresse'),
  117. 'IFG': format_html('Kostenübernahme IFG-Anfrage'),
  118. 'LIT': format_html('Literaturstipendium'),
  119. 'LIST': format_html('Mailingliste'),
  120. 'TRAV': format_html('Reisekosten'),
  121. 'SOFT': format_html('Software'),
  122. 'VIS': format_html('Visitenkarten'),
  123. }
  124. HELP_CHOICES = {'BIB': format_html("In welchem Zeitraum möchtest du recherchieren oder<br>wie lange ist der Bibliotheksausweis gültig?"),
  125. 'ELIT': "Wie lange gilt der Zugang?",
  126. 'SOFT': "Wie lange gilt die Lizenz?",
  127. }
  128. class ExternView(CookieWizardView):
  129. '''This View is for Volunteers'''
  130. template_name = "input/extern.html"
  131. form_list = [ExternForm, LibraryForm]
  132. def get_form(self, step=None, data=None, files=None):
  133. '''this function determines which part of the multipart form is
  134. displayed next'''
  135. if step is None:
  136. step = self.steps.current
  137. print ("get_form() step " + step)
  138. if step == '1':
  139. prev_data = self.get_cleaned_data_for_step('0')
  140. choice = prev_data.get('choice')
  141. print(f'choice detection in ExternView: {TYPE_CHOICES[choice]}')
  142. if choice == 'IFG':
  143. form = IFGForm(data)
  144. form.fields['notes'].help_text = format_html("Bitte gib an, wie die gewonnenen Informationen den<br>Wikimedia-Projekten zugute kommen sollen.")
  145. elif choice in ('BIB', 'SOFT', 'ELIT'):
  146. form = LibraryForm(data)
  147. form.fields['library'].label = LABEL_CHOICES[choice]
  148. form.fields['library'].help_text = f"Für welche {LABEL_CHOICES[choice]} gilt das Stipendium?"
  149. form.fields['duration'].help_text = HELP_CHOICES[choice]
  150. elif choice == 'MAIL':
  151. form = EmailForm(data)
  152. form.fields['domain'].help_text = format_html("Mit welcher Domain, bzw. für welches Wikimedia-Projekt,<br>möchtest du eine Mailadresse beantragen?")
  153. elif choice == 'LIT':
  154. form = LiteratureForm(data)
  155. form.fields['notes'].help_text = "Bitte gib an, wofür du die Literatur verwenden möchtest."
  156. elif choice == 'VIS':
  157. form = BusinessCardForm(data)
  158. elif choice == 'LIST':
  159. form = ListForm(data)
  160. form.fields['domain'].help_text = format_html("Mit welcher Domain, bzw. für welches Wikimedia-Projekt,<br>möchtest du eine Mailingliste beantragen?")
  161. elif choice == 'TRAV':
  162. form = TravelForm(data)
  163. else:
  164. raise RuntimeError(f'ERROR! UNKNOWN FORMTYPE {choice} in ExternView')
  165. self.choice = choice
  166. else:
  167. form = super().get_form(step, data, files)
  168. return form
  169. def get_context_data(self, **kwargs):
  170. context = super().get_context_data(**kwargs)
  171. if hasattr(self, 'choice'):
  172. context["choice"] = TYPE_CHOICES[self.choice]
  173. return context
  174. def done(self, form_list, **kwargs):
  175. print('ExternView.done() reached')
  176. # gather data from all forms
  177. data = {}
  178. for form in form_list:
  179. data = {**data, **form.cleaned_data}
  180. if data['selfbuy'] == 'TRUE':
  181. data['selfbuy_give_data'] = 'False'
  182. print(data)
  183. # write data to database
  184. modell = form.save(commit=False)
  185. # we have to copy the data from the first form here
  186. # this is a bit ugly code. can we copy this without explicit writing?
  187. if data['choice'] == 'LIT':
  188. modell.selfbuy_give_data = data['selfbuy_give_data']
  189. modell.realname = data['realname']
  190. modell.username = data['username']
  191. modell.email = data['email']
  192. # write type of form in some cases
  193. if data['choice'] in ('BIB', 'ELIT', 'SOFT'):
  194. modell.type = data['choice']
  195. form.save()
  196. # add some data to context for mail templates
  197. data['pk'] = modell.pk
  198. data['urlprefix'] = settings.URLPREFIX
  199. data['grant'] = ('LIT', 'SOFT', 'ELIT', 'BIB', 'IFG')
  200. data['DOMAIN'] = ('MAIL', 'LIST')
  201. data['typestring'] = TYPE_CHOICES[data['choice']]
  202. # we need to send the following mails here:
  203. context = { 'data': data }
  204. try:
  205. # - mail with entered data to the Volunteer
  206. txt_mail_template = get_template('input/ifg_volunteer_mail.txt')
  207. html_mail_template = get_template('input/ifg_volunteer_mail.html')
  208. subject, from_email, to = 'Formular ausgefüllt', IF_EMAIL, data['email']
  209. text_content = txt_mail_template.render(context)
  210. html_content = html_mail_template.render(context)
  211. msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
  212. msg.attach_alternative(html_content, "text/html")
  213. #msg.send()
  214. print('ifg volunteer mail would have been sent')
  215. #send_mail(
  216. # 'Formular ausgefüllt',
  217. # mail_template.render(context),
  218. # IF_EMAIL,
  219. # [data['email']],
  220. # fail_silently=False)
  221. ## - mail to IF with link to accept/decline
  222. txt_mail_template = get_template('input/if_mail.txt')
  223. html_mail_template = get_template('input/if_mail.html')
  224. subject, from_email, to = 'Formular ausgefüllt', IF_EMAIL, IF_EMAIL
  225. text_content = txt_mail_template.render(context)
  226. html_content = html_mail_template.render(context)
  227. msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
  228. msg.attach_alternative(html_content, "text/html")
  229. #msg.send()
  230. print('if mail would have been sent')
  231. #send_mail(
  232. # 'Formular ausgefüllt',
  233. # mail_template.render(context),
  234. # IF_EMAIL,
  235. # [IF_EMAIL],
  236. # fail_silently=False)
  237. ## raise SMTPException("testing pupose only")
  238. except BadHeaderError:
  239. modell.delete()
  240. return HttpResponse('Invalid header found. Data not saved!')
  241. except SMTPException:
  242. modell.delete()
  243. return HttpResponse('Error in sending mails (propably wrong adress?). Data not saved!')
  244. return done(self.request)