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.

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