account_cfdi_zip.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. from odoo import models, fields, api
  3. from odoo.exceptions import RedirectWarning, ValidationError
  4. from zipfile import ZipFile
  5. import base64
  6. import tempfile
  7. import os
  8. import logging
  9. _logger = logging.getLogger(__name__)
  10. class AccountCfdiZip(models.TransientModel):
  11. _name = 'account.cfdi.zip'
  12. _description = 'Importación con archivo ZIP'
  13. file = fields.Binary(string='Archivo', required=True)
  14. file_name = fields.Char(string='Nombre del archivo', required=True)
  15. company_id = fields.Many2one(comodel_name='res.company', string='Empresa', default=lambda self: self.env.company, readonly=True)
  16. result = fields.Char(string='Resultado')
  17. state = fields.Selection(selection=[('draft', 'Seleccionar'), ('done', 'Importado'), ], string='Estado', default='draft')
  18. def import_zip(self):
  19. count_xml = 0
  20. if self.file:
  21. zip_file_id = self.env['ir.attachment'].create({
  22. 'name': self.file_name,
  23. 'type': 'binary',
  24. 'company_id': self.company_id.id,
  25. 'datas': self.file,
  26. 'store_fname': self.file_name,
  27. 'mimetype': 'application/zip'
  28. })
  29. fd, path = tempfile.mkstemp()
  30. with os.fdopen(fd, 'wb') as tmp:
  31. tmp.write(base64.b64decode(zip_file_id.datas))
  32. try:
  33. with ZipFile(path, 'r') as zip:
  34. attachment_list = []
  35. for filename in zip.namelist():
  36. with zip.open(filename) as file:
  37. xml_content = file.read()
  38. attachment_data = {
  39. 'name': filename,
  40. 'type': 'binary',
  41. 'company_id': self.company_id.id,
  42. 'datas': base64.b64encode(xml_content),
  43. 'store_fname': filename,
  44. 'mimetype': 'application/xml'
  45. }
  46. data_uuid = {
  47. "xml": attachment_data,
  48. }
  49. attachment_list.append(data_uuid)
  50. if attachment_list:
  51. cfdi_ids = self.env['account.cfdi'].create_cfdis(attachment_list)
  52. count_xml = len(cfdi_ids)
  53. except Exception as e:
  54. raise ValidationError(e)
  55. self.write({
  56. 'result': "Archivos XML procesados correctamente: " + str(count_xml),
  57. 'state': 'done',
  58. })
  59. return {
  60. 'type': 'ir.actions.act_window',
  61. 'res_model': 'account.cfdi.zip',
  62. 'view_mode': 'form',
  63. 'view_type': 'form',
  64. 'res_id': self.id,
  65. 'views': [(False, 'form')],
  66. 'target': 'new',
  67. }