views.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. from django.shortcuts import render
  2. from django.core.mail import send_mail
  3. from django.core.mail import SafeMIMEText
  4. from django.core.mail import EmailMultiAlternatives
  5. from django.template.loader import get_template
  6. from django.template import Context
  7. from django.template import engines, TemplateSyntaxError
  8. from datetime import date
  9. from uuid import uuid4,UUID
  10. import json
  11. import re
  12. from django.db.models import Sum
  13. #from .templatetags.commtags import *
  14. from django.shortcuts import render
  15. from .models import *
  16. from config.views import *
  17. from azienda.views import *
  18. from utente.views import *
  19. from documento.views import *
  20. def template_from_string(template_string, using=None):
  21. """
  22. Convert a string into a template object,
  23. using a given template engine or using the default backends
  24. from settings.TEMPLATES if no engine was specified.
  25. This function is based on django.template.loader.get_template,
  26. but uses Engine.from_string instead of Engine.get_template.
  27. """
  28. chain = []
  29. engine_list = engines.all() if using is None else [engines[using]]
  30. for engine in engine_list:
  31. try:
  32. return engine.from_string(template_string)
  33. except TemplateSyntaxError as e:
  34. chain.append(e)
  35. raise TemplateSyntaxError(template_string, chain=chain)
  36. class ServizioMail:
  37. def __init__(self,debug=False):
  38. self._from_ = getConfigurazione('default_mail_from')
  39. self._to_ = []
  40. self._to = {}
  41. self.debug = debug
  42. self.soggetto = ""
  43. self.corpo_testo = ""
  44. self.corpo_html = ""
  45. self.set_data()
  46. self.json = None
  47. def set_mailfrom(self,mail_from):
  48. self._from_ = mail_from
  49. if self.debug: print('mail_from',self._from_)
  50. def set_listadestinatari(self,lista=[]):
  51. self._to_ = []
  52. self.add_listadestinatari(lista)
  53. if self.debug: print('lista destinatari',self._to_)
  54. def set_rcptto(self,lista=[]):
  55. self.set_listadestinatari(lista)
  56. def add_listadestinatari(self,mail=None):
  57. if self.debug: print('type mail:',type(mail))
  58. if mail:
  59. if type(mail) == list:
  60. for i in mail:
  61. self._to_.append(i)
  62. return
  63. self._to_.append((mail))
  64. if self.debug: print('lista destinatari',self._to_)
  65. def add_to(self,mail=None):
  66. self.add_listadestinatari(mail)
  67. def set_soggetto(self,soggetto=""):
  68. self.soggetto = soggetto
  69. def set_oggetto(self,oggetto="",html=False):
  70. self.oggetto = oggetto
  71. if self.debug: print('set_oggetto html:',html)
  72. self.html = html
  73. def set_data(self,data={}):
  74. self.data = data
  75. #print('data',self.data)
  76. def set_json(self,data={}):
  77. self.json = json.dumps(data)
  78. if self.debug: print('json:',self.json)
  79. def send(self):
  80. # normalizza i destinatari (uno solo, non ripetuti)
  81. if self.debug: print('self._to_',self._to_)
  82. for i in self._to_:
  83. self._to[i] = i
  84. self._to_complete = [ x for x in self._to.values() ]
  85. if self.debug: print("destinatari:",self._to_complete)
  86. #rendering del soggetto
  87. soggetto = template_from_string(self.soggetto)
  88. soggetto_render = soggetto.render(self.data)
  89. if self.debug: print("soggetto",soggetto)
  90. oggetto = template_from_string(self.oggetto)
  91. oggetto_render = None
  92. try:
  93. oggetto_render = oggetto.render(self.data)
  94. except TemplateSyntaxError as tse:
  95. print('Errore nel Template')
  96. print(tse)
  97. if oggetto_render:
  98. if self.debug: print('oggetto render',oggetto_render)
  99. for tt in self._to_complete:
  100. ttl = [tt,]
  101. msg = None
  102. if self.debug: print('richiesta html::',self.html)
  103. if self.html:
  104. msg=EmailMultiAlternatives(soggetto_render, oggetto_render, self._from_, ttl)
  105. msg.attach_alternative(oggetto_render, "text/html")
  106. else: msg=EmailMultiAlternatives(soggetto_render, oggetto_render, self._from_, ttl)
  107. if self.json:
  108. msg.attach_alternative(self.json,'text/json')
  109. msg.send()
  110. def welcome(request):
  111. '''
  112. punto di ingresso.
  113. vengono mostrati tutti i modelli presenti presenti
  114. '''
  115. data = dict()
  116. data['HeaderTitle'] = getConfig('HeaderTitle')
  117. if not 'AziendaId' in request.session:
  118. print('manca azienda')
  119. return HttpResponseRedirect(reverse("login:start"))
  120. else:
  121. data['AziendaId'] = request.session['AziendaId']
  122. if not 'AdminId' in request.session or 'UserId' in request.session:
  123. print("Non rilevo presensa UserId e AdminId in request.session")
  124. return HttpResponseRedirect(reverse("login:start"))
  125. if 'AdminId' in request.session:
  126. data['AdminId'] = request.session['AdminId']
  127. if 'UserId' in request.session:
  128. data['UserId'] = request.session['UserId']
  129. #filtro:
  130. # selezionare tutti gli utenti per AziendaId
  131. data['admin'] = User.objects.get(pk=data['AdminId'])
  132. data['azienda'] = Azienda.objects.get(pk=data['AziendaId'])
  133. data['comunicazione'] = data['azienda'].comunicazione_set.all()
  134. print(data)
  135. '''
  136. #filtro:
  137. # selezionare tutti gli utenti per AziendaId
  138. admin = User.objects.get(pk=data['AdminId'])
  139. data['admin'] = admin
  140. azienda = Azienda.objects.get(pk=data['AziendaId'])
  141. data['azienda'] = azienda
  142. utenti = Utente.objects.filter(azienda = azienda)
  143. data['utenti'] = utenti
  144. if request.method == 'POST':
  145. if 'ritorna' in request.POST:
  146. return HttpResponseRedirect(reverse("azienda:welcome"))
  147. if 'DeleteDocument' in request.POST:
  148. print('Richiesta cancellazione Documento',request.POST)
  149. documento = request.POST['DeleteDocument'] # perche' lo considera una lista e non un singolo valore?
  150. print('richiesta cancellazione documento:',documento)
  151. try:
  152. d = Documento.objects.get(pk=documento)
  153. delete_file(d) #rimozione fisica del documento
  154. setLog(5,documento,admin)
  155. d.delete()
  156. except Documento.DoesNotExist as dne:
  157. print('il documento non esiste')
  158. filecaricati = AdminUpload(request.POST,request.FILES)
  159. if filecaricati.is_valid():
  160. print('record filecaricati validi')
  161. if 'indice' in filecaricati.cleaned_data and filecaricati.cleaned_data.get('indice'):
  162. fileindice = filecaricati.cleaned_data.get('indice')
  163. print('presente file indice',fileindice)
  164. save_and_load_file_indice(request,fileindice,azienda)
  165. if 'allegati' in filecaricati.cleaned_data and filecaricati.cleaned_data.get('allegati'):
  166. print('presenti documenti da allegare')
  167. listadocumenti = filecaricati.cleaned_data['allegati']
  168. print(listadocumenti)
  169. print(type(azienda))
  170. print(azienda.id)
  171. listaok,listanotok = save_and_load_file_multiple(listadocumenti,request,utenti,azienda,filecaricati.cleaned_data['descrizione'])
  172. data['listaok'] = listaok
  173. data['listanotok'] = listanotok
  174. ElencoDocumentiPerAzienda = Documento.objects.filter(azienda=azienda).order_by("utente__nome","documento")
  175. data['ElencoDocumentiPerAzienda'] = ElencoDocumentiPerAzienda
  176. print("Numero documenti associati",len(ElencoDocumentiPerAzienda))
  177. '''
  178. return render(request,'comunicazione.welcome.html',data)