ir_attachment.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from odoo import api, fields, models
  2. from os.path import basename
  3. from zipfile import ZipFile
  4. from tempfile import TemporaryDirectory
  5. import base64
  6. import os.path
  7. class IrAttachment(models.Model):
  8. _inherit = "ir.attachment"
  9. def download_massive_zip(self):
  10. self = self.with_user(1)
  11. zip_name = "Descarga masiva.zip"
  12. zip_file = self.env['ir.attachment'].sudo().search([('name', '=', zip_name)], limit=1)
  13. if zip_file:
  14. zip_file.sudo().unlink()
  15. # Funcion para decodificar el archivo
  16. def isBase64_decodestring(s):
  17. try:
  18. decode_archive = base64.decodebytes(s)
  19. return decode_archive
  20. except Exception as e:
  21. raise ValidationError('Error:', + str(e))
  22. tempdir_file = TemporaryDirectory()
  23. location_tempdir = tempdir_file.name
  24. # Creando ruta dinamica para poder guardar el archivo zip
  25. date_act = fields.Date.today()
  26. file_name = 'DescargaMasiva(Fecha de descarga' + " - " + str(date_act) + ")"
  27. file_name_zip = file_name + ".zip"
  28. zipfilepath = os.path.join(location_tempdir, file_name_zip)
  29. path_files = os.path.join(location_tempdir)
  30. # Creando zip
  31. for file in self:
  32. object_name = file.name
  33. ruta_ob = object_name
  34. object_handle = open(os.path.join(location_tempdir, ruta_ob), "wb")
  35. object_handle.write(isBase64_decodestring(file.datas))
  36. object_handle.close()
  37. with ZipFile(zipfilepath, 'w') as zip_obj:
  38. for file in os.listdir(path_files):
  39. file_path = os.path.join(path_files, file)
  40. if file_path != zipfilepath:
  41. zip_obj.write(file_path, basename(file_path))
  42. with open(zipfilepath, 'rb') as file_data:
  43. bytes_content = file_data.read()
  44. encoded = base64.b64encode(bytes_content)
  45. data = {
  46. 'name': zip_name,
  47. 'type': 'binary',
  48. 'datas': encoded,
  49. 'company_id': self.env.company.id
  50. }
  51. attachment = self.env['ir.attachment'].sudo().create(data)
  52. self.unlink()
  53. return self.download_zip(file_name_zip, attachment.id)
  54. def download_zip(self, filename, id_file):
  55. path = "/web/binary/download_document?"
  56. model = "ir.attachment"
  57. url = path + "model={}&id={}&filename={}".format(model, id_file, filename)
  58. return {
  59. 'type': 'ir.actions.act_url',
  60. 'url': url,
  61. 'target': 'self',
  62. }