Skip to content

Commit

Permalink
trabalho em desenvolvimento
Browse files Browse the repository at this point in the history
  • Loading branch information
CristianoMafraJunior committed Jan 16, 2025
1 parent da45177 commit 7340f90
Show file tree
Hide file tree
Showing 20 changed files with 551 additions and 434 deletions.
1 change: 1 addition & 0 deletions l10n_br_fiscal/views/cfop_view.xml
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
name="tax_definition_ids"
nolabel="1"
context="{'tree_view_ref': 'l10n_br_fiscal.tax_definition_tree','form_view_ref': 'l10n_br_fiscal.tax_definition_form', 'default_cfop_id': id}"
colspan="2"
/>
</group>
</sheet>
Expand Down
8 changes: 4 additions & 4 deletions l10n_br_fiscal_dfe/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,11 @@ Authors
Contributors
------------

- `KMEE <https://www.kmee.com.br>`__:
- `KMEE <https://www.kmee.com.br>`__:

- Luis Felipe Miléo <[email protected]>
- Gabriel Cardoso <[email protected]>
- Felipe Zago <[email protected]>
- Luis Felipe Miléo <[email protected]>
- Gabriel Cardoso <[email protected]>
- Felipe Zago <[email protected]>

Maintainers
-----------
Expand Down
2 changes: 1 addition & 1 deletion l10n_br_fiscal_dfe/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"data": [
"data/ir_cron.xml",
"security/ir.model.access.csv",
"views/dfe/dfe_views.xml",
"views/dfe/dfe_monitor_views.xml",
"views/l10n_br_fiscal_menu.xml",
"views/res_company_view.xml",
],
Expand Down
11 changes: 11 additions & 0 deletions l10n_br_fiscal_dfe/constants/dfe.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,14 @@
DFE_ENVIRONMENTS = [("1", "Produção"), ("2", "Homologação")]

DFE_ENVIRONMENT_DEFAULT = "2"

OP_TYPE_ENTRADA = ("0", "Entrada")
OP_TYPE_SAIDA = ("1", "Saída")

OPERATION_TYPE = [OP_TYPE_ENTRADA, OP_TYPE_SAIDA]


SIT_NFE_AUTORIZADA = ("1", "Autorizada")
SIT_NFE_CANCELADA = ("2", "Cancelada")
SIT_NFE_DENEGADA = ("3", "Denegada")
SITUACAO_NFE = [SIT_NFE_AUTORIZADA, SIT_NFE_CANCELADA, SIT_NFE_DENEGADA]
3 changes: 2 additions & 1 deletion l10n_br_fiscal_dfe/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from . import dfe
from . import dfe_monitor
from . import document
from . import attachment
from . import res_company
from . import dfe
207 changes: 68 additions & 139 deletions l10n_br_fiscal_dfe/models/dfe.py
Original file line number Diff line number Diff line change
@@ -1,157 +1,86 @@
# Copyright (C) 2023 KMEE Informatica LTDA
# License AGPL-3 or later (http://www.gnu.org/licenses/agpl)
from odoo import fields, models

import logging
import re

from erpbrasil.transmissao import TransmissaoSOAP
from nfelib.nfe.ws.edoc_legacy import NFeAdapter as edoc_nfe
from requests import Session

from odoo import _, api, fields, models

from ..tools import utils

_logger = logging.getLogger(__name__)
from ..constants.dfe import (
OPERATION_TYPE,
SITUACAO_NFE,
)


class DFe(models.Model):
_name = "l10n_br_fiscal.dfe"
_inherit = ["mail.thread", "mail.activity.mixin"]
_description = "Consult DF-e"
_order = "id desc"
_rec_name = "display_name"

display_name = fields.Char(compute="_compute_display_name")
key = fields.Char(string="Access Key", size=44)

serie = fields.Char(size=3, index=True)

company_id = fields.Many2one(comodel_name="res.company", string="Company")
number = fields.Float(string="Document Number", index=True, digits=(18, 0))

version = fields.Selection(related="company_id.dfe_version")
emitter = fields.Char(size=60)

environment = fields.Selection(related="company_id.dfe_environment")
cnpj_cpf = fields.Char(string="CNPJ/CPF", size=18)

last_nsu = fields.Char(string="Last NSU", size=25, default="0")
nsu = fields.Char(string="NSU", size=25, index=True)

last_query = fields.Datetime(string="Last query")
operation_type = fields.Selection(
selection=OPERATION_TYPE,
)

document_value = fields.Float(
string="Document Total Value",
readonly=True,
digits=(18, 2),
)

ie = fields.Char(string="Inscrição estadual", size=18)

partner_id = fields.Many2one(
comodel_name="res.partner",
string="Supplier (partner)",
)

imported_document_ids = fields.One2many(
comodel_name="l10n_br_fiscal.document",
inverse_name="dfe_id",
string="Imported Documents",
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
default=lambda self: self.env.company,
readonly=True,
)

use_cron = fields.Boolean(
default=False,
string="Download new documents automatically",
help="If activated, allows new manifestations to be automatically "
"searched with a Cron",
emission_datetime = fields.Datetime(
string="Emission Date",
index=True,
default=fields.Datetime.now,
)

@api.depends("company_id.name", "last_nsu")
def name_get(self):
return self.mapped(lambda d: (d.id, f"{d.company_id.name} - NSU: {d.last_nsu}"))

@api.model
def _get_processor(self):
certificado = self.env.company._get_br_ecertificate()
session = Session()
session.verify = False
return edoc_nfe(
TransmissaoSOAP(certificado, session),
self.company_id.state_id.ibge_code,
versao=self.version,
ambiente=self.environment,
)

@api.model
def validate_distribution_response(self, result):
valid = False
message = result.resposta.xMotivo
if result.retorno.status_code != 200:
code = result.retorno.status_code
elif result.resposta.cStat != "138":
code = result.resposta.cStat
else:
valid = True

if not valid:
self.message_post(
body=_(
_(
"Error validating document distribution:"
"\n\n%(code)s - %(message)s",
code=code,
message=message,
)
)
)

return valid

@api.model
def _document_distribution(self):
maxNSU = ""
while maxNSU != self.last_nsu:
try:
result = self._get_processor().consultar_distribuicao(
cnpj_cpf=re.sub("[^0-9]", "", self.company_id.cnpj_cpf),
ultimo_nsu=utils.format_nsu(self.last_nsu),
)
except Exception as e:
self.message_post(
body=_("Error on searching documents.\n%(error)s", error=e)
)
break

self.write(
{
"last_nsu": result.resposta.ultNSU,
"last_query": fields.Datetime.now(),
}
)

if not self.validate_distribution_response(result):
break

self._process_distribution(result)

maxNSU = result.resposta.maxNSU

@api.model
def _process_distribution(self, result):
"""Method to process the distribution data."""

@api.model
def _parse_xml_document(self, document):
schema_type = document.schema.split("_")[0]
method = "parse_%s" % schema_type
if not hasattr(self, method):
return

xml = utils.parse_gzip_xml(document.valueOf_)
return getattr(self, method)(xml)

@api.model
def _download_document(self, nfe_key):
try:
result = self._get_processor().consultar_distribuicao(
chave=nfe_key, cnpj_cpf=re.sub("[^0-9]", "", self.company_id.cnpj_cpf)
)
except Exception as e:
self.message_post(
body=_("Error on searching documents.\n%(error)s", error=e)
)
return

if not self.validate_distribution_response(result):
return

return result.resposta.loteDistDFeInt.docZip[0]

@api.model
def _cron_search_documents(self):
self.search([("use_cron", "=", True)]).search_documents()

def search_documents(self):
for record in self:
record._document_distribution()
inclusion_datetime = fields.Datetime(
string="Inclusion Date",
index=True,
default=fields.Datetime.now,
)

inclusion_mode = fields.Char(size=255)

document_state = fields.Selection(
selection=SITUACAO_NFE,
index=True,
)

cfop_ids = fields.Many2many(
comodel_name="l10n_br_fiscal.cfop",
string="CFOPs",
)

dfe_nfe_document_type = fields.Selection(
selection=[
("dfe_nfe_complete", "NF-e Completa"),
("dfe_nfe_summary", "Resumo da NF-e"),
("dfe_nfe_event", "Evento da NF-e"),
],
string="DFe Document Type",
)

dfe_monitor_id = fields.Many2one(
comodel_name="l10n_br_fiscal.dfe_monitor",
string="DFe Monitor",
)
Loading

0 comments on commit 7340f90

Please sign in to comment.