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.

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