示例#1
0
    def action_post_validate(self):
        super(InvoiceEletronic, self).action_post_validate()
        if self.model not in ('55', '65'):
            return
        chave_dict = {
            'cnpj': re.sub('[^0-9]', '', self.company_id.cnpj_cpf),
            'estado': self.company_id.state_id.ibge_code,
            'emissao': self.data_emissao[2:4] + self.data_emissao[5:7],
            'modelo': self.model,
            'numero': self.numero,
            'serie': self.serie.code.zfill(3),
            'tipo': int(self.tipo_emissao),
            'codigo': "%08d" % self.numero_controle
        }
        self.chave_nfe = gerar_chave(ChaveNFe(**chave_dict))

        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)

        nfe_values = self._prepare_eletronic_invoice_values()
        lote = self._prepare_lote(self.id, nfe_values)

        xml_enviar = xml_autorizar_nfe(certificado, **lote)

        mensagens_erro = valida_nfe(xml_enviar)
        if mensagens_erro:
            raise UserError(mensagens_erro)

        self.xml_to_send = base64.encodestring(xml_enviar.encode('utf-8'))
        self.xml_to_send_name = 'nfse-enviar-%s.xml' % self.numero
示例#2
0
def _send(certificado, method, sign, **kwargs):
    path = os.path.join(os.path.dirname(__file__), 'templates')
    xmlElem_send = render_xml(path, '%s.xml' % method, True, **kwargs)
    modelo = xmlElem_send.find(".//{http://www.portalfiscal.inf.br/nfe}mod")
    modelo = modelo.text if modelo is not None else '55'
    if modelo == '65':
        pagamento = etree.Element('pag')
        tipo_pagamento = etree.Element('tPag')
        valor = etree.Element('vPag')
        valor_pago = kwargs['NFes'][0]['infNFe']['total']['vNF']
        metodo_pagamento = kwargs['NFes'][0]['infNFe']['pagamento']
        tipo_pagamento.text, valor.text = metodo_pagamento, valor_pago
        pagamento.append(tipo_pagamento)
        pagamento.append(valor)
        transp = xmlElem_send.find(
            ".//{http://www.portalfiscal.inf.br/nfe}transp")
        transp.addnext(pagamento)

    if sign:
        # Caso for autorização temos que adicionar algumas tags tipo
        # cEan, cEANTrib porque o governo sempre complica e não segue padrão
        if method == 'NfeAutorizacao':
            xmlElem_send = _add_required_node(xmlElem_send)

        signer = Assinatura(certificado.pfx, certificado.password)
        if method == 'NfeInutilizacao':
            xml_send = signer.assina_xml(xmlElem_send, kwargs['obj']['id'])
        if method == 'NfeAutorizacao':
            xml_send = signer.assina_xml(xmlElem_send,
                                         kwargs['NFes'][0]['infNFe']['Id'])
            if 'validate' in kwargs:
                erros = valida_nfe(xml_send)
                if erros:
                    raise NFeValidationException('Erro ao validar NFe',
                                                 erros=erros,
                                                 sent_xml=xml_send)
        elif method == 'RecepcaoEventoCancelamento':
            xml_send = signer.assina_xml(xmlElem_send,
                                         kwargs['eventos'][0]['Id'])

        if method == 'RecepcaoEventoCarta':
            xml_send = signer.assina_xml(xmlElem_send, kwargs['Id'])

        if modelo == '65':
            xml_send = _add_qrCode(xml_send, **kwargs)

    else:
        xml_send = etree.tostring(xmlElem_send)

    url = localizar_url(method, kwargs['estado'], modelo, kwargs['ambiente'])
    cabecalho = _build_header(method, **kwargs)

    response, obj = executar_consulta(certificado, url, cabecalho, xml_send)
    return {'sent_xml': xml_send, 'received_xml': response, 'object': obj}
示例#3
0
    def action_post_validate(self):
        super(InvoiceEletronic, self).action_post_validate()
        if self.model not in ('55', '65'):
            return
        chave_dict = {
            'cnpj': re.sub('[^0-9]', '', self.company_id.cnpj_cpf),
            'estado': self.company_id.state_id.ibge_code,
            'emissao': self.data_emissao[2:4] + self.data_emissao[5:7],
            'modelo': self.model,
            'numero': self.numero,
            'serie': self.serie.code.zfill(3),
            'tipo': int(self.tipo_emissao),
            'codigo': "%08d" % self.numero_controle
        }
        self.chave_nfe = gerar_chave(ChaveNFe(**chave_dict))

        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)

        nfe_values = self._prepare_eletronic_invoice_values()

        lote = self._prepare_lote(self.id, nfe_values)
        xml_enviar = xml_autorizar_nfe(certificado, **lote)
        # _logger.info("============================xml_enviar before===========================%s", xml_enviar)
        # xml_enviar1 = xml_enviar.split('<dest>')[0]
        # xml_enviar2 = xml_enviar.split('<dest>')[1]
        # if self.ind_dest == '3':
        #    xml_enviar = xml_enviar1+'<dest><idEstrangeiro>'+re.sub('[^0-9]', '', self.partner_id.cnpj_cpf or '')+'</idEstrangeiro>'+xml_enviar2 if self.partner_id.cnpj_cpf else xml_enviar1+'<dest><idEstrangeiro/>'+xml_enviar2
        #    _logger.info("========================xml_enviar after===========================%s", xml_enviar)

        mensagens_erro = valida_nfe(xml_enviar)
        _logger.info(
            "========================mensagens_erro===========================%s",
            mensagens_erro)
        if mensagens_erro:
            raise UserError(mensagens_erro)

        self.xml_to_send = base64.encodestring(xml_enviar.encode('utf-8'))
        self.xml_to_send_name = 'nfse-enviar-%s.xml' % self.numero
        _logger.info(
            "========================self.xml_to_send_name===========================%s",
            self.xml_to_send_name)
示例#4
0
def _render(certificado, method, sign, **kwargs):
    path = os.path.join(os.path.dirname(__file__), 'templates')
    xmlElem_send = render_xml(path, '%s.xml' % method, True, **kwargs)

    modelo = xmlElem_send.find(".//{http://www.portalfiscal.inf.br/nfe}mod")
    modelo = modelo.text if modelo is not None else '55'

    if sign:
        # Caso for autorização temos que adicionar algumas tags tipo
        # cEan, cEANTrib porque o governo sempre complica e não segue padrão
        if method == 'NfeAutorizacao':
            xmlElem_send = _add_required_node(xmlElem_send)

        signer = Assinatura(certificado.pfx, certificado.password)
        if method == 'NfeInutilizacao':
            xml_send = signer.assina_xml(xmlElem_send, kwargs['obj']['id'])
        if method == 'NfeAutorizacao':
            xml_send = signer.assina_xml(xmlElem_send,
                                         kwargs['NFes'][0]['infNFe']['Id'])
            if modelo == '65' and 'validate' in kwargs:
                #xml_send = _add_qrCode(xml_send, **kwargs)
                #if 'validate' in kwargs:
                erros = valida_nfe(xml_send)
                if erros:
                    raise NFeValidationException('Erro ao validar NFe',
                                                 erros=erros,
                                                 sent_xml=xml_send)
        elif method == 'RecepcaoEventoCancelamento':
            xml_send = signer.assina_xml(xmlElem_send,
                                         kwargs['eventos'][0]['Id'])

        if method == 'RecepcaoEvento':
            xml_send = signer.assina_xml(xmlElem_send,
                                         kwargs['eventos'][0]['Id'])
        elif method == 'RecepcaoEventoManifesto':
            xml_send = signer.assina_xml(xmlElem_send,
                                         kwargs['manifesto']['identificador'])

    else:
        xml_send = etree.tostring(xmlElem_send, encoding=str)

    return xml_send
示例#5
0
    def action_post_validate(self):
        chave_dict = {
            'cnpj': re.sub('[^0-9]', '', self.company_id.l10n_br_cnpj_cpf),
            'estado': self.company_id.state_id.l10n_br_ibge_code,
            'emissao': self.data_emissao.strftime("%y%m"),
            'modelo': '55' if self.model == 'nfe' else '65',
            'numero': self.numero,
            'serie': self.serie_documento.zfill(3),
            'tipo': int(self.tipo_emissao),
            'codigo': "%08d" % self.numero_controle
        }
        self.chave_nfe = gerar_chave(ChaveNFe(**chave_dict))

        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)

        nfe_values = self._prepare_eletronic_invoice_values()

        lote = self._prepare_lote(self.id, nfe_values)

        xml_enviar = xml_autorizar_nfe(certificado, **lote)

        mensagens_erro = valida_nfe(xml_enviar)
        if mensagens_erro:
            raise UserError(mensagens_erro)

        self.sudo().write({
            'xml_to_send':
            base64.encodestring(xml_enviar.encode('utf-8')),
            'xml_to_send_name':
            'nfe-enviar-%s.xml' % self.numero,
        })
示例#6
0
        'indSinc': 0,
        'estado': 13,
        'ambiente': 2,
        'NFes': [{
            'infNFe': _prepare_eletronic_invoice_values()
        }],
        'modelo': '55',
    }


lote = _prepare_lote()
print(lote)

# Funções Para Gerar e Assinar o XML
xml_enviar = xml_autorizar_nfe(certificado, **lote)
mensagens_erro = valida_nfe(xml_enviar)
if mensagens_erro:
    print(mensagens_erro)
print(xml_enviar)

#xml_to_send = base64.encodestring(xml_enviar.encode('utf-8'))

#Funções para Envio do XML
estado = '15'
resposta_recibo = None
resposta = autorizar_nfe(certificado,
                         xml=xml_enviar,
                         estado='13',
                         ambiente=2,
                         modelo='55')
#import pudb;pu.db