managefile.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. from django.shortcuts import render
  2. from django.http import HttpResponse,HttpResponseRedirect,FileResponse
  3. from django.contrib.auth.models import User
  4. from django.urls import reverse
  5. from django.db import IntegrityError
  6. from .models import *
  7. from config.views import *
  8. from django.conf import settings
  9. from django.conf.urls.static import static
  10. from django.contrib.auth import authenticate
  11. import mimetypes
  12. from random import randint
  13. import csv
  14. import time
  15. import datetime
  16. #pip install python-codicefiscale
  17. from codicefiscale import codicefiscale
  18. import os
  19. # come sono gestiti i file nella configurazione:
  20. # MEDIA_ROOT=os.path.join(BASE_DIR,'static/upload')
  21. # che diventa = os.path.join(BASE_DIR,getConfig('DocPath'))
  22. def delete_file(documento):
  23. # questo blocco rimuove fisicamente il file prima della sua rimozione logica nel db
  24. file_path = os.path.join(BASE_DIR,getConfig('DocPath'),documento.utente.azienda.partitaiva,documento.utente.codicefiscale,documento.storage)
  25. print('Path completa:',file_path)
  26. if os.path.isfile(file_path):
  27. print('rimozione fisica file:',posizione)
  28. try:
  29. os.remove(posizione)
  30. except OSError as ose:
  31. print('errore nella rimozione del file:',ose)
  32. def download_file(request,uid):
  33. utente = Utenti.objects.get(pk=uid)
  34. file_path = os.path.join(BASE_DIR,getConfig('DocPath'),documento.utente.azienda.partitaiva,documento.utente.codicefiscale,utente.storage)
  35. print('Path completa da Basedir:',file_path)
  36. if utente.storage and os.path.isfile(file_path):
  37. try:
  38. fl = open(file_path, 'rb')
  39. except Exception as er:
  40. print('errore',er)
  41. data=dict()
  42. data['errore']="File non esistente o non ancora disponibile"
  43. data['utente'] = utente
  44. return render(request,'welcome.error.html',data)
  45. else:
  46. print('il file non esiste',file_path)
  47. data=dict()
  48. data['errore']='File non esistente o non ancora disponibile'
  49. data['utente'] = utente
  50. return render(request,'welcome.error.html',data)
  51. mime_type, _ = mimetypes.guess_type(file_path)
  52. print('file',file_path,mime_type)
  53. response = FileResponse(open(file_path,'rb'),content_type='application/pdf',as_attachment=False)
  54. #response['Content-Disposition'] = "attachment; filename=%s" % u.documento
  55. return response
  56. def upload_file(uploaded_file,utente,originale=False):
  57. '''
  58. caricamento files
  59. '''
  60. stored_file = ''.join((str(time.time()),'.saved'))
  61. fl_path = os.path.join(BASE_DIR,getConfig('DocPath'))
  62. print('nome file',uploaded_file.name,stored_file)
  63. nomefile=None
  64. if originale:
  65. nomefile = uploaded_file.name
  66. else:
  67. nomefile = stored_file
  68. # vediamo se caricare o meno.
  69. # in questo caso, se il documento esiste gia', non lo carica.
  70. # come facciamo a stabilire se il documento esiste gia'?
  71. # fl_path = corrisponde a media.ROOT (che mi domando se non e' il caso di spostarlo nella configurazione)
  72. # azienda.partitaiva
  73. # utente.codicefiscale (prima era "record" e mi sono deciso a cambiarlo)
  74. try:
  75. os.mkdir(os.path.join(fl_path,utente.azienda.partitaiva))
  76. except FileExistsError as fee:
  77. print(os.path.join(fl_path,utente.azienda.partitaiva),"esistente")
  78. try:
  79. os.mkdir(os.path.join(fl_path,utente.azienda.partitaiva,utente.codicefiscale))
  80. except FileExistsError as fee:
  81. print(os.path.join(fl_path,utente.azienda.partitaiva,utente.codicefiscale),"esistente")
  82. with open(os.path.join(fl_path,utente.azienda.partitaiva,utente.codicefiscale,nomefile),'wb+') as d:
  83. for chunk in uploaded_file.chunks():
  84. d.write(chunk)
  85. if originale:
  86. return os.path.join(fl_path,utente.azienda.partitaiva,utente.codicefiscale,nomefile)
  87. return stored_file
  88. def save_and_load_file_multiple(listadocumenti,request,utente,azienda,descrizione):
  89. listaok = list()
  90. listanotok = list()
  91. for singolodocumento in listadocumenti:
  92. print('singolodocumento',singolodocumento)
  93. for ut in utente:
  94. if ut.codicefiscale.strip() in singolodocumento.name:
  95. print('match utente-documento')
  96. risultato = upload_file(singolodocumento,ut)
  97. documento = Documento()
  98. documento.dataupload = datetime.datetime.now()
  99. documento.utente = ut
  100. documento.azienda = azienda
  101. documento.documento = singolodocumento.name
  102. documento.storage = risultato
  103. documento.descrizione = descrizione
  104. try:
  105. documento.save()
  106. listaok.append(documento.documento)
  107. except IntegrityError as ie:
  108. print("problema di integrita', il file esiste",ie)
  109. listanotok.append(documento.documento)
  110. print(listaok,listanotok)
  111. return (listaok,listanotok)
  112. def save_and_load_file_single(listadocumenti,request,utente,azienda,descrizione):
  113. listaok = list()
  114. listanotok = list()
  115. for singolodocumento in listadocumenti:
  116. print('singolodocumento',singolodocumento,descrizione)
  117. risultato = upload_file(singolodocumento,utente)
  118. documento = Documento()
  119. documento.dataupload = datetime.datetime.now()
  120. documento.utente = utente
  121. documento.azienda = azienda
  122. documento.documento = singolodocumento.name
  123. documento.storage = risultato
  124. documento.descrizione = descrizione
  125. try:
  126. documento.save()
  127. listaok.append(documento.documento)
  128. except IntegritiError as ie:
  129. print("problema di integrita', il file esiste",ie)
  130. listanotok.append(documento.documento)
  131. return (listaok,listanotok)
  132. def save_and_load_file_indice(fileindice,request,documento):
  133. print('nome indice caricato',fileindice.name)
  134. upload_file(fileindice,request.FILES['indice'],True)
  135. fl_path = getConfig('DocPath')
  136. risultato = None
  137. with open(os.path.join(fl_path,fileindice.name),'rb') as ind:
  138. risultato = ind.read()
  139. risultato = risultato.decode('utf-8',errors='replace')
  140. if isinstance(risultato,str):
  141. risultato = risultato.encode('utf8')
  142. with open(os.path.join(fl_path,fileindice.name,'.cvtd'),'wb') as ind:
  143. ind.write(risultato)
  144. print('una volta convertito, passiamo oltre')
  145. with open(os.path.join(fl_path,'/',fileindice.name,'.cvtd'),'rt') as ind:
  146. spamreader = csv.reader(ind,delimiter=';')
  147. errori = list()
  148. count = 0
  149. for sr in spamreader:
  150. salvare = False
  151. count +=1
  152. if count==1: continue
  153. print(count,'sr',sr,len(sr))
  154. '''
  155. rispetto a farma, questo tracciato e' diverso
  156. 0: 0308 - BOX3 S.R.L.;
  157. 1: Elaborazioni - Lul Libro Unico del Lavoro lavoratore;
  158. 2: ALESSE ANTONIO - LSSNTN63A25H501Y;
  159. 3: DA0308_L.U.L._LAVORATORE_#_ALESSE_ANTONIO_#_LSSNTN63A25H501Y_#_06.2024_12.07.2024_10.18.43.pdf;
  160. 4: ="06.2024";
  161. 5: 12.07.2024 10:34:17;
  162. 6: Cliente;
  163. 7: 2024.07.15 11:40:33;
  164. 8: 12.07.2024;
  165. 9: 12.07.2024;
  166. '''
  167. if len(sr) > 1: # la lunghezza del record segnala qualcosa
  168. utente = None
  169. try:
  170. utente = Utente.objects.get(codicefiscale=sr[2].split(' - ')[1].strip().upper())
  171. except Utente.DoesNotExist as dne:
  172. print('Utente non trovato')
  173. utente = Utente()
  174. utente.azienda = azienda
  175. utente.nome = sr[2].capitalize()
  176. try:
  177. data_convertita = datetime.datetime.strptime(sr[8], "%d.%m.%Y")
  178. print('data convertita',data_convertita)
  179. utente.datanascita = data_convertita
  180. except ValueError as ve:
  181. print(ve)
  182. utente.codicefiscale = sr[2].split(' - ')[1].strip().upper()
  183. utente.password = str(randint(100000,999999))
  184. utente.save()
  185. # caricamento documenti
  186. if filecaricati.cleaned_data.get('allegati'):
  187. print('presenti documenti da allegare')
  188. listadocumenti = filecaricati.cleaned_data['allegati']
  189. print(listadocumenti)
  190. utenti = Utenti.objects.all()
  191. for singolodocumento in listadocumenti:
  192. print('singolodocumento',singolodocumento)
  193. for utente in utenti:
  194. if utente.codicefiscale.strip() in singolodocumento.name:
  195. print('match utente-documento')
  196. risultato = upload_file(singolodocumento,utente)
  197. # risultato: nome del file memorizzato (nome interno)
  198. # singolodocumento.name = nome del file originale