Exemplo n.º 1
0
 def generate_nfe_proc(self):
     if self.state in ['cancel', 'done', 'denied']:
         recibo = self.env['ir.attachment'].search(
             [('res_model', '=', 'eletronic.document'),
              ('res_id', '=', self.id), ('name', 'like', 'rec-ret')],
             limit=1)
         if not recibo:
             recibo = self.env['ir.attachment'].search(
                 [('res_model', '=', 'eletronic.document'),
                  ('res_id', '=', self.id), ('name', 'like', 'nfe-ret')],
                 limit=1)
         nfe_envio = self.env['ir.attachment'].search(
             [('res_model', '=', 'eletronic.document'),
              ('res_id', '=', self.id), ('name', 'like', 'nfe-envio')],
             limit=1)
         if nfe_envio.datas and recibo.datas:
             nfe_proc = gerar_nfeproc(
                 base64.decodestring(nfe_envio.datas).decode('utf-8'),
                 base64.decodestring(recibo.datas).decode('utf-8'),
             )
             self.sudo().write({
                 'nfe_processada':
                 base64.encodestring(nfe_proc),
                 'nfe_processada_name':
                 "NFe%08d.xml" % self.numero,
             })
     else:
         raise UserError(_('A NFe não está validada'))
Exemplo n.º 2
0
 def generate_nfe_proc(self):
     if self.state in ['cancel', 'done', 'denied']:
         recibo = self.env['ir.attachment'].search([
             ('res_model', '=', 'invoice.eletronic'),
             ('res_id', '=', self.id), ('datas_fname', 'like', 'rec-ret')
         ])
         if not recibo:
             recibo = self.env['ir.attachment'].search([
                 ('res_model', '=', 'invoice.eletronic'),
                 ('res_id', '=', self.id),
                 ('datas_fname', 'like', 'nfe-ret')
             ])
         nfe_envio = self.env['ir.attachment'].search([
             ('res_model', '=', 'invoice.eletronic'),
             ('res_id', '=', self.id), ('datas_fname', 'like', 'nfe-envio')
         ])
         if nfe_envio.datas and recibo.datas:
             nfe_proc = gerar_nfeproc(base64.decodestring(nfe_envio.datas),
                                      base64.decodestring(recibo.datas))
             self.nfe_processada = base64.encodestring(nfe_proc)
             self.nfe_processada_name = "NFe%08d.xml" % self.numero
     else:
         raise UserError('A NFe não está validada')
Exemplo n.º 3
0
    def action_send_eletronic_invoice(self):
        self.state = 'error'
        self.data_emissao = datetime.now()
        super(InvoiceEletronic, self).action_send_eletronic_invoice()

        if self.model not in ('55', '65'):
            return

        nfe_values = self._prepare_eletronic_invoice_values()
        lote = self._prepare_lote(self.id, nfe_values)
        cert = self.company_id.with_context({'bin_size': False}).nfe_a1_file
        cert_pfx = base64.decodestring(cert)

        certificado = Certificado(cert_pfx, self.company_id.nfe_a1_password)

        resposta_recibo = None
        resposta = autorizar_nfe(certificado, **lote)
        retorno = resposta['object'].Body.nfeAutorizacaoLoteResult
        retorno = retorno.getchildren()[0]
        if retorno.cStat == 103:
            obj = {
                'estado': self.company_id.partner_id.state_id.ibge_code,
                'ambiente': 1 if self.ambiente == 'producao' else 2,
                'obj': {
                    'ambiente': 1 if self.ambiente == 'producao' else 2,
                    'numero_recibo': retorno.infRec.nRec
                }
            }
            self.recibo_nfe = obj['obj']['numero_recibo']
            import time
            while True:
                time.sleep(2)
                resposta_recibo = retorno_autorizar_nfe(certificado, **obj)
                retorno = resposta_recibo['object'].Body.\
                    nfeRetAutorizacaoLoteResult.retConsReciNFe
                if retorno.cStat != 105:
                    break

        if retorno.cStat != 104:
            self.codigo_retorno = retorno.cStat
            self.mensagem_retorno = retorno.xMotivo
        else:
            self.codigo_retorno = retorno.protNFe.infProt.cStat
            self.mensagem_retorno = retorno.protNFe.infProt.xMotivo
            if self.codigo_retorno == '100':
                self.write({
                    'state': 'done',
                    'nfe_exception': False,
                    'protocolo_nfe': retorno.protNFe.infProt.nProt,
                    'data_autorizacao': retorno.protNFe.infProt.dhRecbto
                })
            # Duplicidade de NF-e significa que a nota já está emitida
            # TODO Buscar o protocolo de autorização, por hora só finalizar
            if self.codigo_retorno == '204':
                self.write({
                    'state': 'done',
                    'codigo_retorno': '100',
                    'nfe_exception': False,
                    'mensagem_retorno': 'Autorizado o uso da NF-e'
                })

            # Denegada e nota já está denegada
            if self.codigo_retorno in ('302', '205'):
                self.write({'state': 'denied', 'nfe_exception': True})

        self.env['invoice.eletronic.event'].create({
            'code':
            self.codigo_retorno,
            'name':
            self.mensagem_retorno,
            'invoice_eletronic_id':
            self.id,
        })
        self._create_attachment('nfe-envio', self, resposta['sent_xml'])
        self._create_attachment('nfe-ret', self, resposta['received_xml'])
        recibo_xml = resposta['received_xml']
        if resposta_recibo:
            self._create_attachment('rec', self, resposta_recibo['sent_xml'])
            self._create_attachment('rec-ret', self,
                                    resposta_recibo['received_xml'])
            recibo_xml = resposta_recibo['received_xml']

        if self.codigo_retorno == '100':
            nfe_proc = gerar_nfeproc(resposta['sent_xml'], recibo_xml)
            self.nfe_processada = base64.encodestring(nfe_proc)
            self.nfe_processada_name = "NFe%08d.xml" % self.numero
Exemplo n.º 4
0
    def action_send_eletronic_invoice(self):
        if self.model not in ['nfe', 'nfce']:
            return super(EletronicDocument,
                         self).action_send_eletronic_invoice()

        if self.state in ('done', 'denied', 'cancel'):
            return

        errors = self._hook_validation()
        if len(errors) > 0:
            msg = "\n".join(
                ["Por favor corrija os erros antes de prosseguir"] + errors)
            raise UserError(msg)

        self._update_document_values()
        self.action_post_validate()

        _logger.info('Sending NF-e (%s) (%.2f) - %s' %
                     (self.numero, self.valor_final, self.partner_id.name))
        self.write({'state': 'error', 'data_emissao': datetime.now()})

        cert = self.company_id.with_context({
            'bin_size': False
        }).l10n_br_certificate
        cert_pfx = base64.decodestring(cert)

        certificado = Certificado(cert_pfx,
                                  self.company_id.l10n_br_cert_password)

        xml_to_send = base64.decodestring(self.xml_to_send).decode('utf-8')

        resposta_recibo = None
        resposta = autorizar_nfe(
            certificado,
            xml=xml_to_send,
            estado=self.company_id.state_id.l10n_br_ibge_code,
            ambiente=1 if self.ambiente == 'producao' else 2,
            modelo='55' if self.model == 'nfe' else '65')
        retorno = resposta['object'].getchildren()[0]
        if retorno.cStat == 103:
            obj = {
                'estado':
                self.company_id.partner_id.state_id.l10n_br_ibge_code,
                'ambiente': 1 if self.ambiente == 'producao' else 2,
                'obj': {
                    'ambiente': 1 if self.ambiente == 'producao' else 2,
                    'numero_recibo': retorno.infRec.nRec
                },
                'modelo': '55' if self.model == 'nfe' else '65',
            }
            self.recibo_nfe = obj['obj']['numero_recibo']
            import time
            while True:
                time.sleep(2)
                resposta_recibo = retorno_autorizar_nfe(certificado, **obj)
                retorno = resposta_recibo['object'].getchildren()[0]
                if retorno.cStat != 105:
                    break

        if retorno.cStat != 104:
            self.write({
                'codigo_retorno': retorno.cStat,
                'mensagem_retorno': retorno.xMotivo,
            })
            self.notify_user()
        else:
            self.write({
                'codigo_retorno': retorno.protNFe.infProt.cStat,
                'mensagem_retorno': retorno.protNFe.infProt.xMotivo,
            })
            if self.codigo_retorno == '100':
                self.write({
                    'state': 'done',
                    'protocolo_nfe': retorno.protNFe.infProt.nProt,
                    'data_autorizacao': retorno.protNFe.infProt.dhRecbto
                })
            else:
                self.notify_user()
            # Duplicidade de NF-e significa que a nota já está emitida
            # TODO Buscar o protocolo de autorização, por hora só finalizar
            if self.codigo_retorno == '204':
                self.write({
                    'state': 'done',
                    'codigo_retorno': '100',
                    'mensagem_retorno': 'Autorizado o uso da NF-e'
                })

            # Denegada e nota já está denegada
            if self.codigo_retorno in ('302', '205'):
                self.write({'state': 'denied'})

        self._create_attachment('nfe-envio', self, resposta['sent_xml'])
        self._create_attachment('nfe-ret', self, resposta['received_xml'])
        recibo_xml = resposta['received_xml']
        if resposta_recibo:
            self._create_attachment('rec', self, resposta_recibo['sent_xml'])
            self._create_attachment('rec-ret', self,
                                    resposta_recibo['received_xml'])
            recibo_xml = resposta_recibo['received_xml']

        if self.codigo_retorno == '100':
            nfe_proc = gerar_nfeproc(resposta['sent_xml'], recibo_xml)
            self.sudo().write({
                'nfe_processada':
                base64.encodestring(nfe_proc),
                'nfe_processada_name':
                "NFe%08d.xml" % self.numero,
            })
        _logger.info('NF-e (%s) was finished with status %s' %
                     (self.numero, self.codigo_retorno))
Exemplo n.º 5
0
    def action_send_eletronic_invoice(self):
        super(InvoiceEletronic, self).action_send_eletronic_invoice()

        if self.model not in ('55', '65') or self.state in ('done', 'denied',
                                                            'cancel'):
            return

        self.state = 'error'
        self.data_emissao = datetime.now()

        cert = self.company_id.with_context({'bin_size': False}).nfe_a1_file
        cert_pfx = base64.decodestring(cert)

        certificado = Certificado(cert_pfx, self.company_id.nfe_a1_password)

        xml_to_send = base64.decodestring(self.xml_to_send).decode(
            'utf-8', 'ignore')
        import string
        _logger.info("----------before-------------%s", xml_to_send)
        xml_to_send = ''.join(x for x in xml_to_send if x in string.printable)
        xml_to_send = re.sub('\s+(?=<)', '', xml_to_send)
        xml_to_send = re.sub('\n', '', xml_to_send)
        _logger.info("----------xml_to_send-------------%s", xml_to_send)

        resposta_recibo = None
        resposta = autorizar_nfe(
            certificado,
            xml=xml_to_send,
            estado=self.company_id.state_id.ibge_code,
            ambiente=1 if self.ambiente == 'producao' else 2,
            modelo=self.model)
        retorno = resposta['object'].getchildren()[0]
        if retorno.cStat == 103:
            obj = {
                'estado': self.company_id.partner_id.state_id.ibge_code,
                'ambiente': 1 if self.ambiente == 'producao' else 2,
                'obj': {
                    'ambiente': 1 if self.ambiente == 'producao' else 2,
                    'numero_recibo': retorno.infRec.nRec
                },
                'modelo': self.model,
            }
            self.recibo_nfe = obj['obj']['numero_recibo']
            import time
            while True:
                time.sleep(2)
                resposta_recibo = retorno_autorizar_nfe(certificado, **obj)
                retorno = resposta_recibo['object'].getchildren()[0]
                if retorno.cStat != 105:
                    break

        if retorno.cStat != 104:
            self.codigo_retorno = retorno.cStat
            self.mensagem_retorno = retorno.xMotivo
        else:
            self.codigo_retorno = retorno.protNFe.infProt.cStat
            self.mensagem_retorno = retorno.protNFe.infProt.xMotivo
            if self.codigo_retorno == '100':
                self.write({
                    'state': 'done',
                    'protocolo_nfe': retorno.protNFe.infProt.nProt,
                    'data_autorizacao': retorno.protNFe.infProt.dhRecbto
                })
            # Duplicidade de NF-e significa que a nota já está emitida
            # TODO Buscar o protocolo de autorização, por hora só finalizar
            if self.codigo_retorno == '204':
                self.write({
                    'state': 'done',
                    'codigo_retorno': '100',
                    'mensagem_retorno': 'Autorizado o uso da NF-e'
                })

            # Denegada e nota já está denegada
            if self.codigo_retorno in ('302', '205'):
                self.write({'state': 'denied'})

        self.env['invoice.eletronic.event'].create({
            'code':
            self.codigo_retorno,
            'name':
            self.mensagem_retorno,
            'invoice_eletronic_id':
            self.id,
        })
        self._create_attachment('nfe-envio', self, resposta['sent_xml'])
        self._create_attachment('nfe-ret', self, resposta['received_xml'])
        recibo_xml = resposta['received_xml']
        if resposta_recibo:
            self._create_attachment('rec', self, resposta_recibo['sent_xml'])
            self._create_attachment('rec-ret', self,
                                    resposta_recibo['received_xml'])
            recibo_xml = resposta_recibo['received_xml']

        if self.codigo_retorno == '100':
            nfe_proc = gerar_nfeproc(resposta['sent_xml'], recibo_xml)
            self.nfe_processada = base64.encodestring(nfe_proc)
            self.nfe_processada_name = "NFe%08d.xml" % self.numero