views.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. print("Azienda rilevata",data['AziendaId'])
  123. if not 'AdminId' in request.session or 'UserId' in request.session:
  124. print("Non rilevo presensa UserId e AdminId in request.session")
  125. return HttpResponseRedirect(reverse("login:start"))
  126. if 'AdminId' in request.session:
  127. data['AdminId'] = request.session['AdminId']
  128. if 'UserId' in request.session:
  129. data['UserId'] = request.session['UserId']
  130. #filtro:
  131. # selezionare tutti gli utenti per AziendaId
  132. data['admin'] = User.objects.get(pk=data['AdminId'])
  133. data['azienda'] = Azienda.objects.get(pk=data['AziendaId'])
  134. data['comunicazione'] = data['azienda'].comunicazione_set.all()
  135. print(data)
  136. if request.method == "POST":
  137. print('Richiesta effettuata')
  138. return render(request,'comunicazione.welcome.html',data)
  139. '''
  140. #filtro:
  141. # selezionare tutti gli utenti per AziendaId
  142. admin = User.objects.get(pk=data['AdminId'])
  143. data['admin'] = admin
  144. azienda = Azienda.objects.get(pk=data['AziendaId'])
  145. data['azienda'] = azienda
  146. utenti = Utente.objects.filter(azienda = azienda)
  147. data['utenti'] = utenti
  148. if request.method == 'POST':
  149. if 'ritorna' in request.POST:
  150. return HttpResponseRedirect(reverse("azienda:welcome"))
  151. if 'DeleteDocument' in request.POST:
  152. print('Richiesta cancellazione Documento',request.POST)
  153. documento = request.POST['DeleteDocument'] # perche' lo considera una lista e non un singolo valore?
  154. print('richiesta cancellazione documento:',documento)
  155. try:
  156. d = Documento.objects.get(pk=documento)
  157. delete_file(d) #rimozione fisica del documento
  158. setLog(5,documento,admin)
  159. d.delete()
  160. except Documento.DoesNotExist as dne:
  161. print('il documento non esiste')
  162. filecaricati = AdminUpload(request.POST,request.FILES)
  163. if filecaricati.is_valid():
  164. print('record filecaricati validi')
  165. if 'indice' in filecaricati.cleaned_data and filecaricati.cleaned_data.get('indice'):
  166. fileindice = filecaricati.cleaned_data.get('indice')
  167. print('presente file indice',fileindice)
  168. save_and_load_file_indice(request,fileindice,azienda)
  169. if 'allegati' in filecaricati.cleaned_data and filecaricati.cleaned_data.get('allegati'):
  170. print('presenti documenti da allegare')
  171. listadocumenti = filecaricati.cleaned_data['allegati']
  172. print(listadocumenti)
  173. print(type(azienda))
  174. print(azienda.id)
  175. listaok,listanotok = save_and_load_file_multiple(listadocumenti,request,utenti,azienda,filecaricati.cleaned_data['descrizione'])
  176. data['listaok'] = listaok
  177. data['listanotok'] = listanotok
  178. ElencoDocumentiPerAzienda = Documento.objects.filter(azienda=azienda).order_by("utente__nome","documento")
  179. data['ElencoDocumentiPerAzienda'] = ElencoDocumentiPerAzienda
  180. print("Numero documenti associati",len(ElencoDocumentiPerAzienda))
  181. '''