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.

230 lines
8.3 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
  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
  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. if choice == 'LIT':
  23. Literature.set_granted(pk,auth)
  24. if choice == 'IFG':
  25. IFG.set_granted(pk,auth)
  26. else:
  27. return HttpResponse(f'ERROR! UNKNWON CHOICE TYPE! {choice}')
  28. return False
  29. @login_required
  30. def authorize(request, choice, pk):
  31. '''If IF grant a support they click a link in a mail which leads here.
  32. We write the granted field in the database here and set a timestamp.'''
  33. ret = auth_deny(choice, pk, True)
  34. if ret:
  35. return ret
  36. else:
  37. return HttpResponse(f"AUTHORIZED! choice: {choice}, pk: {pk}")
  38. @login_required
  39. def deny(request, choice, pk):
  40. '''If IF denies a support they click a link in a mail which leads here
  41. We write the granted field in the database here.'''
  42. ret = auth_deny(choice, pk, False)
  43. if ret:
  44. return ret
  45. else:
  46. return HttpResponse(f"DENIED! choice: {choice}, pk: {pk}")
  47. def done(request):
  48. return HttpResponse("Your data is save now.")
  49. class InternView(LoginRequiredMixin, CookieWizardView):
  50. '''This View is for WMDE-employees only'''
  51. template_name = 'input/extern.html'
  52. form_list = [InternForm, ProjectForm]
  53. def get_form(self, step=None, data=None, files=None):
  54. '''this function determines which part of the multipart form is
  55. displayed next'''
  56. if step is None:
  57. step = self.steps.current
  58. print ("get_form() step " + step)
  59. if step == '1':
  60. prev_data = self.get_cleaned_data_for_step('0')
  61. choice = prev_data.get('choice')
  62. print(f'choice detection: {INTERN_CHOICES[choice]}')
  63. if choice == 'HON':
  64. form = HonoraryCertificateForm(data)
  65. elif choice == 'PRO':
  66. form = ProjectForm(data)
  67. elif choice == 'TRAV':
  68. form = TravelForm(data)
  69. else:
  70. raise RuntimeError(f'ERROR! UNKNOWN FORMTYPE {choice} in InternView')
  71. else:
  72. form = super().get_form(step, data, files)
  73. return form
  74. def done(self, form_list, **kwargs):
  75. print('InternView.done() reached')
  76. # gather data from all forms
  77. data = {}
  78. for form in form_list:
  79. data = {**data, **form.cleaned_data}
  80. print(data)
  81. # write data to database
  82. form = form.save(commit=False)
  83. # we have to copy the data from the first form here
  84. # this is ugly code. how can we copy this without explicit writing?
  85. # i found no way to access the ModelForm.Meta.exclude-tupel
  86. form.realname = data['realname']
  87. # form.username = data['username']
  88. form.email = data['email']
  89. form.granted = True
  90. form.granted_date = date.today()
  91. form.save()
  92. return done(self.request)
  93. # these where used as labels in the second form TYPE_CHOICES is used for the first form and the
  94. # text above the second form. only used for BIB, SOFT, ELIT in the moment
  95. LABEL_CHOICES = {'BIB': format_html('Bibliothek'),
  96. 'ELIT': format_html('Datenbank/Online-Ressource'),
  97. 'MAIL': format_html('E-Mail-Adresse'),
  98. 'IFG': format_html('Kostenübernahme IFG-Anfrage'),
  99. 'LIT': format_html('Literaturstipendium'),
  100. 'LIST': format_html('Mailingliste'),
  101. 'SOFT': format_html('Software'),
  102. 'VIS': format_html('Visitenkarten'),
  103. }
  104. HELP_CHOICES = {'BIB': format_html("In welchem Zeitraum möchtest du recherchieren oder<br>wie lange ist der Bibliotheksausweis gültig?"),
  105. 'ELIT': "Wie lange gilt der Zugang?",
  106. 'SOFT': "Wie lange gilt die Lizenz?",
  107. }
  108. class ExternView(CookieWizardView):
  109. '''This View is for Volunteers'''
  110. template_name = "input/extern.html"
  111. form_list = [ExternForm, LibraryForm]
  112. def get_form(self, step=None, data=None, files=None):
  113. '''this function determines which part of the multipart form is
  114. displayed next'''
  115. if step is None:
  116. step = self.steps.current
  117. print ("get_form() step " + step)
  118. if step == '1':
  119. prev_data = self.get_cleaned_data_for_step('0')
  120. choice = prev_data.get('choice')
  121. print(f'choice detection in ExternView: {TYPE_CHOICES[choice]}')
  122. if choice == 'IFG':
  123. form = IFGForm(data)
  124. elif choice in ('BIB', 'SOFT', 'ELIT'):
  125. form = LibraryForm(data)
  126. form.fields['library'].label = LABEL_CHOICES[choice]
  127. form.fields['duration'].help_text = HELP_CHOICES[choice]
  128. elif choice == 'MAIL':
  129. form = EmailForm(data)
  130. elif choice == 'LIT':
  131. form = LiteratureForm(data)
  132. elif choice == 'VIS':
  133. form = BusinessCardForm(data)
  134. elif choice == 'LIST':
  135. form = ListForm(data)
  136. else:
  137. raise RuntimeError(f'ERROR! UNKNOWN FORMTYPE {choice} in ExternView')
  138. self.choice = choice
  139. else:
  140. form = super().get_form(step, data, files)
  141. return form
  142. def get_context_data(self, **kwargs):
  143. context = super().get_context_data(**kwargs)
  144. if hasattr(self, 'choice'):
  145. context["choice"] = TYPE_CHOICES[self.choice]
  146. return context
  147. def done(self, form_list, **kwargs):
  148. print('ExternView.done() reached')
  149. # gather data from all forms
  150. data = {}
  151. for form in form_list:
  152. data = {**data, **form.cleaned_data}
  153. print(data)
  154. # write data to database
  155. modell = form.save(commit=False)
  156. # we have to copy the data from the first form here
  157. # this is a bit ugly code. can we copy this without explicit writing?
  158. modell.realname = data['realname']
  159. # form.username = data['username']
  160. modell.email = data['email']
  161. # write type of form in some cases
  162. if data['choice'] in ('BIB', 'ELIT', 'SOFT'):
  163. modell.type = data['choice']
  164. form.save()
  165. # add some data to context for mail templates
  166. data['pk'] = modell.pk
  167. data['urlprefix'] = settings.URLPREFIX
  168. data['grant'] = ('LIT', 'SOFT', 'ELIT', 'BIB', 'IFG')
  169. data['DOMAIN'] = ('MAIL', 'LIST')
  170. data['typestring'] = TYPE_CHOICES[data['choice']]
  171. # we need to send the following mails here:
  172. context = { 'data': data }
  173. try:
  174. # - mail with entered data to the Volunteer
  175. mail_template = get_template('input/ifg_volunteer_mail.txt')
  176. send_mail(
  177. 'Formular ausgefüllt',
  178. mail_template.render(context),
  179. IF_EMAIL,
  180. [data['email']],
  181. fail_silently=False)
  182. # - mail to IF with link to accept/decline
  183. mail_template = get_template('input/if_mail.txt')
  184. send_mail(
  185. 'Formular ausgefüllt',
  186. mail_template.render(context),
  187. IF_EMAIL,
  188. [IF_EMAIL],
  189. fail_silently=False)
  190. # raise SMTPException("testing pupose only")
  191. except BadHeaderError:
  192. modell.delete()
  193. return HttpResponse('Invalid header found. Data not saved!')
  194. except SMTPException:
  195. modell.delete()
  196. return HttpResponse('Error in sending mails (propably wrong adress?). Data not saved!')
  197. return done(self.request)