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.

224 lines
8.0 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. class ExternView(CookieWizardView):
  105. '''This View is for Volunteers'''
  106. template_name = "input/extern.html"
  107. form_list = [ExternForm, LibraryForm]
  108. def get_form(self, step=None, data=None, files=None):
  109. '''this function determines which part of the multipart form is
  110. displayed next'''
  111. if step is None:
  112. step = self.steps.current
  113. print ("get_form() step " + step)
  114. if step == '1':
  115. prev_data = self.get_cleaned_data_for_step('0')
  116. choice = prev_data.get('choice')
  117. print(f'choice detection in ExternView: {TYPE_CHOICES[choice]}')
  118. if choice == 'IFG':
  119. form = IFGForm(data)
  120. elif choice in ('BIB', 'SOFT', 'ELIT'):
  121. form = LibraryForm(data)
  122. form.fields['library'].label = LABEL_CHOICES[choice]
  123. elif choice == 'MAIL':
  124. form = EmailForm(data)
  125. elif choice == 'LIT':
  126. form = LiteratureForm(data)
  127. elif choice == 'VIS':
  128. form = BusinessCardForm(data)
  129. elif choice == 'LIST':
  130. form = ListForm(data)
  131. else:
  132. raise RuntimeError(f'ERROR! UNKNOWN FORMTYPE {choice} in ExternView')
  133. self.choice = choice
  134. else:
  135. form = super().get_form(step, data, files)
  136. return form
  137. def get_context_data(self, **kwargs):
  138. context = super().get_context_data(**kwargs)
  139. if hasattr(self, 'choice'):
  140. context["choice"] = TYPE_CHOICES[self.choice]
  141. return context
  142. def done(self, form_list, **kwargs):
  143. print('ExternView.done() reached')
  144. # gather data from all forms
  145. data = {}
  146. for form in form_list:
  147. data = {**data, **form.cleaned_data}
  148. print(data)
  149. # write data to database
  150. modell = form.save(commit=False)
  151. # we have to copy the data from the first form here
  152. # this is a bit ugly code. can we copy this without explicit writing?
  153. modell.realname = data['realname']
  154. # form.username = data['username']
  155. modell.email = data['email']
  156. # write type of form in some cases
  157. if data['choice'] in ('BIB', 'ELIT', 'SOFT'):
  158. modell.type = data['choice']
  159. form.save()
  160. # add some data to context for mail templates
  161. data['pk'] = modell.pk
  162. data['urlprefix'] = settings.URLPREFIX
  163. data['grant'] = ('LIT', 'SOFT', 'ELIT', 'BIB', 'IFG')
  164. data['DOMAIN'] = ('MAIL', 'LIST')
  165. data['typestring'] = TYPE_CHOICES[data['choice']]
  166. # we need to send the following mails here:
  167. context = { 'data': data }
  168. try:
  169. # - mail with entered data to the Volunteer
  170. mail_template = get_template('input/ifg_volunteer_mail.txt')
  171. send_mail(
  172. 'Formular ausgefüllt',
  173. mail_template.render(context),
  174. IF_EMAIL,
  175. [data['email']],
  176. fail_silently=False)
  177. # - mail to IF with link to accept/decline
  178. mail_template = get_template('input/if_mail.txt')
  179. send_mail(
  180. 'Formular ausgefüllt',
  181. mail_template.render(context),
  182. IF_EMAIL,
  183. [IF_EMAIL],
  184. fail_silently=False)
  185. # raise SMTPException("testing pupose only")
  186. except BadHeaderError:
  187. modell.delete()
  188. return HttpResponse('Invalid header found. Data not saved!')
  189. except SMTPException:
  190. modell.delete()
  191. return HttpResponse('Error in sending mails (propably wrong adress?). Data not saved!')
  192. return done(self.request)