views.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 uuid import uuid4,UUID
  9. import json
  10. import re
  11. from django.db.models import Sum
  12. #from .templatetags.commtags import *
  13. from django.shortcuts import render
  14. from .models import *
  15. from .forms import *
  16. import datetime
  17. import sys
  18. from config.views import *
  19. from azienda.views import *
  20. # se serve aiuta a capire quali sono i moduli caricati, ma meglio
  21. # disattivarlo che sono una cifra lunghissima
  22. #print(sys.modules)
  23. def template_from_string(template_string, using=None):
  24. """
  25. Convert a string into a template object,
  26. using a given template engine or using the default backends
  27. from settings.TEMPLATES if no engine was specified.
  28. This function is based on django.template.loader.get_template,
  29. but uses Engine.from_string instead of Engine.get_template.
  30. """
  31. chain = []
  32. engine_list = engines.all() if using is None else [engines[using]]
  33. for engine in engine_list:
  34. try:
  35. return engine.from_string(template_string)
  36. except TemplateSyntaxError as e:
  37. chain.append(e)
  38. raise TemplateSyntaxError(template_string, chain=chain)
  39. class ServizioMail:
  40. def __init__(self,debug=False):
  41. self._from_ = getConfig('DefaultEmail')
  42. self._to_ = []
  43. self._to = {}
  44. self.debug = debug
  45. self.soggetto = ""
  46. self.corpo = ""
  47. self.corpo_testo = ""
  48. self.corpo_html = ""
  49. self.data = dict()
  50. self.json = None
  51. if self.debug: print('attivato flag di debug')
  52. def set_mailfrom(self,mail_from):
  53. self._from_ = mail_from
  54. if self.debug: print('mail_from',self._from_)
  55. def set_listadestinatari(self,lista=[]):
  56. self._to_ = []
  57. self.add_listadestinatari(lista)
  58. if self.debug: print('lista destinatari',self._to_)
  59. def set_rcptto(self,lista=[]):
  60. self.set_listadestinatari(lista)
  61. def add_listadestinatari(self,mail=None):
  62. if self.debug: print('type mail:',type(mail))
  63. if mail:
  64. if type(mail) == list:
  65. for i in mail:
  66. self._to_.append(i)
  67. return
  68. self._to_.append((mail))
  69. if self.debug: print('lista destinatari',self._to_)
  70. def add_to(self,mail=None):
  71. self.add_listadestinatari(mail)
  72. def set_soggetto(self,soggetto=""):
  73. self.soggetto = soggetto
  74. if self.debug:
  75. print("########")
  76. print('soggetto:',self.soggetto)
  77. print("########")
  78. def set_corpo(self,corpo="",html=False):
  79. self.corpo = corpo
  80. if self.debug:
  81. print("########")
  82. print('corpo:',self.corpo)
  83. print('set_corpo html:',html)
  84. print("########")
  85. self.html = html
  86. def set_data(self,data={}):
  87. self.data = data
  88. if not 'ora_data' in self.data:
  89. self.data['ora_data'] = datetime.datetime.now().strftime('%H:%M %d/%m/%Y')
  90. if not 'ora' in self.data:
  91. self.data['ora'] = datetime.datetime.now().strftime('%H:%m')
  92. if not 'data' in self.data:
  93. self.data['data'] = datetime.datetime.now().strftime('%d/%m/%Y')
  94. if self.debug: print('data',self.data)
  95. def set_json(self,data={}):
  96. self.json = json.dumps(data)
  97. if self.debug: print('json:',self.json)
  98. def send(self):
  99. # normalizza i destinatari (uno solo, non ripetuti)
  100. if self.debug: print('spedisco a:',self._to_)
  101. for i in self._to_:
  102. self._to[i] = i
  103. self._to_complete = [ x for x in self._to.values() ]
  104. if self.debug: print("destinatari tutti:",self._to_complete)
  105. #rendering del soggetto
  106. soggetto = template_from_string(self.soggetto)
  107. soggetto_render = soggetto.render(self.data)
  108. print('soggetto_render:',soggetto_render)
  109. if self.debug: print("soggetto",soggetto)
  110. corpo = template_from_string(self.corpo)
  111. corpo_render = None
  112. try:
  113. corpo_render = corpo.render(self.data)
  114. print('corpo_render:',corpo_render)
  115. except TemplateSyntaxError as tse:
  116. print('Errore nel Template')
  117. print(tse)
  118. print('quanti sono',len(self._to_complete))
  119. for tt in self._to_complete:
  120. ttl = [tt,]
  121. print('ttl',ttl,)
  122. msg = None
  123. if self.debug: print('richiesta html::',self.html)
  124. if self.html:
  125. msg=EmailMultiAlternatives(soggetto_render, corpo_render, self._from_, ttl)
  126. msg.attach_alternative(corpo_render, "text/html")
  127. else: msg=EmailMultiAlternatives(soggetto_render, corpo_render, self._from_, ttl)
  128. if self.json:
  129. msg.attach_alternative(self.json,'text/json')
  130. try:
  131. msg.send()
  132. print('messaggio inviato')
  133. except ConnectionRefusedError as cre:
  134. print('impossibile inviare mail',cre)
  135. ####################
  136. # modulo comunicazioni
  137. ####################
  138. def welcome(request):
  139. '''
  140. punto di ingresso.
  141. vengono mostrati tutti i modelli presenti presenti
  142. '''
  143. print('__name__',__name__,'welcome')
  144. data = dict()
  145. data['HeaderTitle'] = getConfig('HeaderTitle')
  146. if not 'AziendaId' in request.session:
  147. print('manca azienda')
  148. return HttpResponseRedirect(reverse("login:start"))
  149. else:
  150. data['AziendaId'] = request.session['AziendaId']
  151. print("Azienda rilevata",data['AziendaId'])
  152. if not 'AdminId' in request.session or 'UserId' in request.session:
  153. print("Non rilevo presensa UserId e AdminId in request.session")
  154. return HttpResponseRedirect(reverse("login:start"))
  155. else:
  156. data['AdminId'] = request.session['AdminId']
  157. if 'UserId' in request.session:
  158. data['UserId'] = request.session['UserId']
  159. sede = None
  160. SedeId = None
  161. if 'SedeId' in request.session:
  162. SedeId = request.session['SedeId']
  163. data['SedeId']=SedeId
  164. print('SedeId',SedeId)
  165. try:
  166. sede = Sede.objects.get(pk=SedeId)
  167. except Sede.DoesNotExist as dne:
  168. print("sede non esistente")
  169. data['sede'] = sede
  170. #filtro:
  171. # selezionare tutti gli utenti per AziendaId
  172. data['admin'] = Amministratore.objects.get(pk=data['AdminId'])
  173. data['azienda'] = Azienda.objects.get(pk=data['AziendaId'])
  174. print('SedeId',SedeId)
  175. if 'SedeId' in data and data['SedeId'] is not -1:
  176. data['sede'] = Sede.objects.get(pk=data['SedeId'])
  177. data['comunicazione'] = data['azienda'].comunicazione_set.all()
  178. print(data)
  179. if request.method == "POST":
  180. print('Richiesta effettuata')
  181. print(request.POST)
  182. if 'indietro' in request.POST:
  183. return HttpResponseRedirect(reverse("azienda:welcome"))
  184. if 'Nuovo' in request.POST:
  185. if 'ComId' in request.session:
  186. del request.session['ComId']
  187. return HttpResponseRedirect(reverse("comunicazione:edit"))
  188. if 'edit' in request.POST:
  189. request.session['ComId'] = request.POST.get('edit')
  190. print('ComId',request.session.get('ComId'))
  191. return HttpResponseRedirect(reverse("comunicazione:edit"))
  192. return render(request,'comunicazione.welcome.html',data)
  193. def edit(request):
  194. print('__name__',__name__,'edit')
  195. data = dict()
  196. data['HeaderTitle'] = getConfig('HeaderTitle')
  197. if not 'AziendaId' in request.session:
  198. print('manca azienda')
  199. return HttpResponseRedirect(reverse("login:start"))
  200. data['AziendaId'] = request.session['AziendaId']
  201. print("Azienda rilevata",data['AziendaId'])
  202. data['azienda'] = Azienda.objects.get(pk=data['AziendaId'])
  203. if not 'AdminId' in request.session or 'UserId' in request.session:
  204. print("Non rilevo presensa UserId e AdminId in request.session")
  205. return HttpResponseRedirect(reverse("login:start"))
  206. data['AdminId'] = request.session['AdminId']
  207. print(data)
  208. if 'UserId' in request.session:
  209. data['UserId'] = request.session['UserId']
  210. comunicazione = Comunicazione()
  211. if 'ComId' in request.session:
  212. ComId = request.session.get('ComId')
  213. print('trovato ComId',ComId)
  214. comunicazione = Comunicazione.objects.get(pk=ComId)
  215. if request.method == 'POST':
  216. print('richiesta effettuata')
  217. if 'Ritorna' in request.POST:
  218. return HttpResponseRedirect(reverse("comunicazione:welcome"))
  219. fd = formComunicazione(request.POST)
  220. if fd.is_valid():
  221. print('comunicazione valido')
  222. comunicazione.mittente = fd.cleaned_data.get('mittente')
  223. comunicazione.soggetto = fd.cleaned_data.get('soggetto')
  224. comunicazione.corpo = fd.cleaned_data.get('corpo')
  225. comunicazione.azienda = data['azienda']
  226. comunicazione.save()
  227. else:
  228. print('comunicazione non valido')
  229. data['comunicazione'] = formComunicazione(request.POST)
  230. else:
  231. print('post non valido')
  232. tmp = dict()
  233. if len(data['azienda'].mail):
  234. print('azienda contiene email',data['azienda'].mail)
  235. tmp['mittente'] = data['azienda'].mail
  236. else:
  237. print('azienda non contiene email, prendo default',getConfig("DefaultEmail"))
  238. tmp['mittente'] = getConfig("DefaultEmail")
  239. tmp['soggetto'] = comunicazione.soggetto
  240. tmp['corpo'] = comunicazione.corpo
  241. data['comunicazione'] = formComunicazione(tmp)
  242. print(data)
  243. return render(request,'comunicazione.edit.html',data)