Example #1
1
def consulta_distribuicao_nfe(certificado, **kwargs):
    if "xml" not in kwargs:
        kwargs['xml'] = xml_consulta_distribuicao_nfe(certificado, **kwargs)
    xml_send = kwargs["xml"]
    base_url = localizar_url(
        'NFeDistribuicaoDFe',  kwargs['estado'], kwargs['modelo'],
        kwargs['ambiente'])

    cert, key = extract_cert_and_key_from_pfx(
        certificado.pfx, certificado.password)
    cert, key = save_cert_key(cert, key)

    session = Session()
    session.cert = (cert, key)
    session.verify = False
    transport = Transport(session=session)

    xml = etree.fromstring(xml_send)
    xml_um = etree.fromstring('<nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/"><cUF>AN</cUF><versaoDados>1.00</versaoDados></nfeCabecMsg>')
    client = Client(base_url, transport=transport)

    port = next(iter(client.wsdl.port_types))
    first_operation = next(iter(client.wsdl.port_types[port].operations))
    with client.settings(raw_response=True):
        response = client.service[first_operation](nfeDadosMsg=xml, _soapheaders=[xml_um])
        response, obj = sanitize_response(response.text)
        return {
            'sent_xml': xml_send,
            'received_xml': response,
            'object': obj.Body.nfeDistDFeInteresseResponse.nfeDistDFeInteresseResult
        }
Example #2
0
def _send(certificado, method, **kwargs):
    # A little hack to test
    path = os.path.join(os.path.dirname(__file__), "templates")
    if (method == "TesteEnvioLoteRPS" or method == "EnvioLoteRPS"
            or method == "CancelamentoNFe"):
        sign_tag(certificado, **kwargs)

    if method == "TesteEnvioLoteRPS":
        xml_send = render_xml(path, "EnvioLoteRPS.xml", False, **kwargs)
    else:
        xml_send = render_xml(path, "%s.xml" % method, False, **kwargs)
    base_url = "https://nfe.prefeitura.sp.gov.br/ws/lotenfe.asmx?wsdl"

    cert, key = extract_cert_and_key_from_pfx(certificado.pfx,
                                              certificado.password)
    cert, key = save_cert_key(cert, key)
    client = get_authenticated_client(base_url, cert, key)

    signer = Assinatura(cert, key, certificado.password)
    xml_send = signer.assina_xml(xml_send, "")

    try:
        response = getattr(client.service, method)(1, xml_send)
    except suds.WebFault as e:
        return {
            "sent_xml": xml_send,
            "received_xml": e.fault.faultstring,
            "object": None,
        }

    response, obj = sanitize_response(response)
    return {"sent_xml": xml_send, "received_xml": response, "object": obj}
Example #3
0
def nfeInutilizacaoCE(session, xml_send, ambiente):
    soap = ('<Envelope xmlns="http://www.w3.org/2003/05/soap-envelope"><Body>\
<nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NFeInutilizacao4"\
>' + xml_send + "</nfeDadosMsg></Body></Envelope>")
    headers = {
        "SOAPAction": "",
        "Content-Type": 'application/soap+xml; charset="utf-8"',
    }
    if ambiente == 1:
        response = session.post(
            "https://nfe.sefaz.ce.gov.br/nfe4/services/NFeInutilizacao4",
            data=soap,
            headers=headers,
        )
    else:
        response = session.post(
            "https://nfeh.sefaz.ce.gov.br/nfe4/services/NFeInutilizacao4",
            data=soap,
            headers=headers,
        )
    response, obj = sanitize_response(response.text)
    return {
        "sent_xml": xml_send,
        "received_xml": response,
        "object": obj.Body.getchildren()[0],
    }
Example #4
0
def _send(certificado, method, **kwargs):
    base_url = ""
    if kwargs["ambiente"] == "producao":
        base_url = "https://wsnfsev1.natal.rn.gov.br:8444"
    else:
        base_url = "https://wsnfsev1homologacao.natal.rn.gov.br:8443/axis2/services/NfseWSServiceV1?wsdl"

    base_url = "https://wsnfsev1homologacao.natal.rn.gov.br:8443/axis2/services/NfseWSServiceV1?wsdl"
    cert, key = extract_cert_and_key_from_pfx(
        certificado.pfx, certificado.password)
    cert, key = save_cert_key(cert, key)

    disable_warnings()
    session = Session()
    session.cert = (cert, key)
    session.verify = False
    transport = Transport(session=session)

    client = Client(wsdl=base_url, transport=transport)
    xml_send = {}
    xml_send = {
        "nfseDadosMsg": kwargs["xml"],
        "nfseCabecMsg": """<?xml version="1.0"?>
        <cabecalho xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" versao="1" xmlns="http://www.abrasf.org.br/ABRASF/arquivos/nfse.xsd">
        <versaoDados>1</versaoDados>
        </cabecalho>""",
    }

    response = client.service[method](**xml_send)
    response, obj = sanitize_response(response)
    return {"sent_xml": xml_send, "received_xml": response, "object": obj}
Example #5
0
def _send(certificado, method, **kwargs):
    xml_send = kwargs["xml"]
    base_url = localizar_url(method, kwargs['estado'], kwargs['modelo'],
                             kwargs['ambiente'])

    cert, key = extract_cert_and_key_from_pfx(certificado.pfx,
                                              certificado.password)
    cert, key = save_cert_key(cert, key)

    session = Session()
    session.cert = (cert, key)
    session.verify = False
    transport = Transport(session=session)

    xml = etree.fromstring(xml_send)
    history = MyLoggingPlugin()
    client = Client(base_url, transport=transport, plugins=[history])

    port = next(iter(client.wsdl.port_types))
    first_operation = next(iter(client.wsdl.port_types[port].operations))
    with client.settings(raw_response=True):
        response = client.service[first_operation](xml)
        #         _logger.info(history.last_sent)
        #         _logger.info(history.last_received)
        response, obj = sanitize_response(response.text)
        return {
            'sent_xml': xml_send,
            'sent_raw_xml': history.last_sent,
            'received_xml': response,
            'object': obj.Body.getchildren()[0]
        }
 def test_inutilizacao_falha_schema(self, inutilizar, validar):
     validar.return_value = ''
     with open(os.path.join(self.caminho,
                            'xml/inutilizacao_sent_xml.xml')) as f:
         sent_xml = f.read()
     with open(
             os.path.join(self.caminho,
                          'xml/inutilizacao_falha_schema.xml')) as f:
         received_xml = f.read()
     _, obj = sanitize_response(received_xml)
     inutilizar.return_value = {
         'received_xml': received_xml,
         'sent_xml': sent_xml,
         'object': obj
     }
     justif = 'Sed lorem nibh, sodales ut ex a, tristique ullamcor'
     wizard = self.env['wizard.inutilization.nfe.numeration'].create(
         dict(numeration_start=0,
              numeration_end=5,
              serie=self.serie.id,
              modelo='55',
              justificativa=justif))
     wizard.action_inutilize_nfe()
     inutilized = self.env['invoice.eletronic.inutilized'].search([])
     self.assertEqual(inutilized.state, 'error')
Example #7
0
def _send(certificado, method, **kwargs):
    base_url = ""
    if kwargs["ambiente"] == "producao":
        base_url = "https://notacarioca.rio.gov.br/WSNacional/nfse.asmx?wsdl"
    else:
        base_url = "https://notacariocahom.rio.gov.br/WSNacional/nfse.asmx?wsdl"  # noqa

    xml_send = kwargs["xml"].decode("utf-8")
    cert, key = extract_cert_and_key_from_pfx(certificado.pfx,
                                              certificado.password)
    cert, key = save_cert_key(cert, key)
    client = get_authenticated_client(base_url, cert, key)

    try:
        response = getattr(client.service, method)(xml_send)
    except suds.WebFault as e:
        return {
            "sent_xml": str(xml_send),
            "received_xml": str(e.fault.faultstring),
            "object": None,
        }

    response, obj = sanitize_response(response)
    return {
        "sent_xml": str(xml_send),
        "received_xml": str(response),
        "object": obj
    }
    def test_nfse_cancelamento_erro(self, cancelar):
        for invoice in self.invoices:
            invoice.company_id.tipo_ambiente_nfse = 'producao'
            # Confirmando a fatura deve gerar um documento eletrônico
            invoice.action_invoice_open()

            # Lote recebido com sucesso
            xml_recebido = open(
                os.path.join(self.caminho, 'xml/cancelamento-erro.xml'),
                'r').read()
            resp = sanitize_response(xml_recebido)
            cancelar.return_value = {
                'object': resp[1],
                'sent_xml': '<xml />',
                'received_xml': xml_recebido
            }

            invoice_eletronic = self.env['invoice.eletronic'].search([
                ('invoice_id', '=', invoice.id)
            ])
            invoice_eletronic.verify_code = '123'
            invoice_eletronic.numero_nfse = '123'
            invoice_eletronic.ambiente = 'producao'
            invoice_eletronic.action_cancel_document(
                justificativa="Cancelamento de teste")
            self.assertEquals(invoice_eletronic.state, 'draft')
            self.assertEquals(invoice_eletronic.codigo_retorno, "1305")
            self.assertEquals(
                invoice_eletronic.mensagem_retorno,
                "Assinatura de cancelamento da NFS-e incorreta.")
Example #9
0
    def test_consulta_cadastro(self, consulta):
        partner = self.env['res.partner'].create({
            'name': 'Empresa',
            'cnpj_cpf': '22814429000155',
            'is_company': True,
            'country_id': self.env.ref('base.br').id,
            'state_id': self.env.ref('base.state_br_sc').id,
        })
        with self.assertRaises(UserError):
            partner.action_check_sefaz()
        self.env.ref('base.main_company').nfe_a1_password = '******'
        self.env.ref('base.main_company').nfe_a1_file = base64.b64encode(
            open(os.path.join(self.caminho, 'teste.pfx'), 'rb').read())

        # Consulta cadastro com sucesso
        xml_recebido = open(os.path.join(
            self.caminho, 'xml/consulta_cadastro.xml'), 'r').read()
        resp = sanitize_response(xml_recebido)
        consulta.return_value = {
            'object': resp[1],
            'sent_xml': '<xml />',
            'received_xml': xml_recebido
        }

        partner.action_check_sefaz()
        self.assertEquals(partner.cnpj_cpf, '22814429000155')
        self.assertEquals(partner.inscr_est, '112632165')
        self.assertEquals(partner.street, 'RUA PADRE JOAO')
        self.assertEquals(partner.district, 'Centro')
        self.assertEquals(partner.city_id.id, 3776)
        self.assertEquals(partner.zip, '88032050')
Example #10
0
def _send(certificado, method, **kwargs):
    base_url = ""
    if kwargs["ambiente"] == "producao":
        base_url = "https://isse.maringa.pr.gov.br/ws/?wsdl"
    else:
        base_url = "https://isseteste.maringa.pr.gov.br/ws/?wsdl"

    xml_send = kwargs["xml"].decode("utf-8")

    cert, key = extract_cert_and_key_from_pfx(certificado.pfx,
                                              certificado.password)
    cert, key = save_cert_key(cert, key)

    session = Session()
    session.cert = (cert, key)
    session.verify = False
    transport = Transport(session=session)

    client = Client(base_url, transport=transport)
    response = client.service[method](xml_send)

    response, obj = sanitize_response(response)
    return {
        "sent_xml": str(xml_send),
        "received_xml": str(response),
        "object": obj
    }
    def test_nfse_cancel(self, cancelar):
        for invoice in self.invoices:
            # Confirmando a fatura deve gerar um documento eletrônico
            invoice.action_invoice_open()

            # Lote recebido com sucesso
            xml_recebido = open(
                os.path.join(self.caminho, 'xml/cancelamento-sucesso.xml'),
                'r').read()
            resp = sanitize_response(xml_recebido)
            cancelar.return_value = {
                'object': resp[1],
                'sent_xml': '<xml />',
                'received_xml': xml_recebido
            }

            invoice_eletronic = self.env['invoice.eletronic'].search([
                ('invoice_id', '=', invoice.id)
            ])
            invoice_eletronic.verify_code = '123'
            invoice_eletronic.numero_nfse = '123'
            invoice_eletronic.action_cancel_document(
                justificativa="Cancelamento de teste")

            self.assertEquals(invoice_eletronic.state, 'cancel')
            self.assertEquals(invoice_eletronic.codigo_retorno, "100")
            self.assertEquals(invoice_eletronic.mensagem_retorno,
                              "Nota Fiscal Paulistana Cancelada")
Example #12
0
def _send(certificado, method, **kwargs):
    xml_send = kwargs["xml"]
    base_url = localizar_url(
        method,  kwargs['estado'], kwargs['modelo'], kwargs['ambiente'])

    cert, key = extract_cert_and_key_from_pfx(
        certificado.pfx, certificado.password)
    cert, key = save_cert_key(cert, key)

    session = Session()
    session.cert = (cert, key)
    session.verify = False
    transport = Transport(session=session)

    xml = etree.fromstring(xml_send)
    client = Client(base_url, transport=transport)

    port = next(iter(client.wsdl.port_types))
    first_operation = next(iter(client.wsdl.port_types[port].operations))
    
    namespaceNFe = xml.find(".//{http://www.portalfiscal.inf.br/nfe}NFe")
    if namespaceNFe is not None:
        namespaceNFe.set('xmlns', 'http://www.portalfiscal.inf.br/nfe')
            
    with client.settings(raw_response=True):
        response = client.service[first_operation](xml)
        response, obj = sanitize_response(response.text)
        return {
            'sent_xml': xml_send,
            'received_xml': response,
            'object': obj.Body.getchildren()[0]
        }
Example #13
0
    def test_nfe_cancelamento_ok(self, cancelar):
        for invoice in self.invoices:
            # Confirmando a fatura deve gerar um documento eletrônico
            invoice.action_invoice_open()

            # Lote recebido com sucesso
            xml_recebido = open(
                os.path.join(self.caminho, 'xml/cancelamento-sucesso.xml'),
                'r').read()
            resp = sanitize_response(xml_recebido)
            cancelar.return_value = {
                'object': resp[1],
                'sent_xml': '<xml />',
                'received_xml': xml_recebido
            }

            invoice_eletronic = self.env['invoice.eletronic'].search([
                ('invoice_id', '=', invoice.id)
            ])

            # As 2 linhas seguintes servem apenas para setar o nfe_processada
            # do invoice_eletronic -> famosa gambiarra
            encoded_xml = '<xml />'.encode('utf-8')
            invoice_eletronic.nfe_processada = base64.encodestring(encoded_xml)

            invoice_eletronic.action_cancel_document(
                justificativa="Cancelamento de teste")

            self.assertEquals(invoice_eletronic.state, 'cancel')
            self.assertEquals(invoice_eletronic.codigo_retorno, "135")
            self.assertEquals(invoice_eletronic.mensagem_retorno,
                              "Evento registrado e vinculado a NF-e")
Example #14
0
def _send(certificado, method, **kwargs):
    url = _get_url(**kwargs)

    path = os.path.join(os.path.dirname(__file__), 'templates')

    xml_send = _render(path, method, **kwargs)
    client = get_client(url)
    response = False

    if certificado:
        cert, key = extract_cert_and_key_from_pfx(certificado.pfx,
                                                  certificado.password)
        cert, key = save_cert_key(cert, key)
        signer = Assinatura(cert, key, certificado.password)
        xml_send = signer.assina_xml(xml_send, '')

    try:
        response = getattr(client.service, method)(xml_send)
        response, obj = sanitize_response(response.encode())
    except suds.WebFault as e:
        return {
            'sent_xml': xml_send,
            'received_xml': e.fault.faultstring,
            'object': None
        }
    except Exception as e:
        if response:
            raise Exception(response)
        else:
            raise e

    return {'sent_xml': xml_send, 'received_xml': response, 'object': obj}
Example #15
0
def _send_v310(certificado, **kwargs):
    xml_send = kwargs["xml"]
    base_url = localizar_url(
        "NFeDistribuicaoDFe", kwargs["estado"], kwargs["modelo"], kwargs["ambiente"]
    )

    cert, key = extract_cert_and_key_from_pfx(certificado.pfx, certificado.password)
    cert, key = save_cert_key(cert, key)

    session = Session()
    session.cert = (cert, key)
    session.verify = False
    transport = Transport(session=session)

    xml = etree.fromstring(xml_send)
    xml_um = etree.fromstring(
        '<nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/"><cUF>AN</cUF><versaoDados>1.00</versaoDados></nfeCabecMsg>'
    )
    client = Client(base_url, transport=transport)

    port = next(iter(client.wsdl.port_types))
    first_operation = next(iter(client.wsdl.port_types[port].operations))
    with client.settings(raw_response=True):
        response = client.service[first_operation](
            nfeDadosMsg=xml, _soapheaders=[xml_um]
        )
        response, obj = sanitize_response(response.text)
        return {
            "sent_xml": xml_send,
            "received_xml": response,
            "object": obj.Body.nfeDistDFeInteresseResponse.nfeDistDFeInteresseResult,
        }
 def test_sanitize_response(self):
     path = os.path.join(os.path.dirname(__file__), "XMLs")
     xml_to_clear = open(os.path.join(path, "jinja_result.xml"), "r").read()
     xml, obj = sanitize_response(xml_to_clear)
     self.assertEqual(xml, xml_to_clear)
     self.assertEqual(obj.tpAmb, "oi")
     self.assertEqual(obj.CNPJ, "ola")
     self.assertEqual(obj.indNFe, "")
     self.assertEqual(obj.indEmi, "comovai")
Example #17
0
 def test_sanitize_response(self):
     path = os.path.join(os.path.dirname(__file__), 'XMLs')
     xml_to_clear = open(os.path.join(path, 'jinja_result.xml'), 'r').read()
     xml, obj = sanitize_response(xml_to_clear)
     self.assertEqual(xml, xml_to_clear)
     self.assertEqual(obj.tpAmb, 'oi')
     self.assertEqual(obj.CNPJ, 'ola')
     self.assertEqual(obj.indNFe, '')
     self.assertEqual(obj.indEmi, 'comovai')
Example #18
0
    def test_envio_nfse(self):
        nfse = _get_nfse()

        xml_send = render_xml(self.template_path, 'EnvioLoteRPS.xml', False, nfse=nfse)
        expected_xml = open(os.path.join(self.xml_path, 'xml_send_rps_batch_to_paulistana.xml'), 'r').read()

        _, obj = sanitize_response(xml_send)

        self.assertEqual(obj.Cabecalho.QtdRPS, self.BATCH_SIZE)
        self.assertEqual(xml_send, expected_xml)
Example #19
0
    def test_lote_rps_sem_valores(self):
        xml_lote_rps = render_xml(self.template_path,
                                  'EnvioLoteRPS.xml',
                                  False,
                                  nfse=self.nfse)

        _, obj = sanitize_response(xml_lote_rps)

        for attr in attrs:
            self.assertEqual(getattr(obj.RPS, attr), default_values[attr])
    def test_sanitize_response(self):
        path = os.path.join(os.path.dirname(__file__), 'XMLs')
        xml_to_clear = open(os.path.join(path, 'jinja_result.xml'), 'r').read()
        xml, obj = sanitize_response(xml_to_clear)

        self.assertEqual(xml, xml_to_clear)
        self.assertEqual(obj.tpAmb, 'oi')
        self.assertEqual(obj.CNPJ, 'ola')
        self.assertEqual(obj.indNFe, '')
        self.assertEqual(obj.indEmi, 'comovai')
Example #21
0
def _send(certificado, method, **kwargs):
    base_url = ''
    if kwargs['ambiente'] == 'producao':
        base_url = 'https://petropolis.sigiss.com.br/petropolis/ws/sigiss_ws.php'  # noqa
    else:
        raise Exception('Não existe ambiente de homologação!')

    xml_send = kwargs["xml"].decode('utf-8')
    headers = {
        'SOAPAction': "urn:sigiss_ws#%s" % method,
        'Content-Type': 'text/xml; charset="utf-8"'
    }

    r = requests.post(base_url, data=xml_send, headers=headers)
    response, obj = sanitize_response(r.text.strip())

    return {'sent_xml': xml_send, 'received_xml': response, 'object': obj.Body}
Example #22
0
def _send_zeep(first_operation, client, xml_send):
    parser = etree.XMLParser(strip_cdata=False)
    xml = etree.fromstring(xml_send, parser=parser)

    namespaceNFe = xml.find(".//{http://www.portalfiscal.inf.br/nfe}NFe")
    if namespaceNFe is not None:
        namespaceNFe.set("xmlns", "http://www.portalfiscal.inf.br/nfe")

    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    with client.settings(raw_response=True):
        response = client.service[first_operation](xml)
        response, obj = sanitize_response(response.text)
        return {
            "sent_xml": xml_send,
            "received_xml": response,
            "object": obj.Body.getchildren()[0],
        }
Example #23
0
def _send_zeep(first_operation, client, xml_send, raise_for_status=False):
    parser = etree.XMLParser(strip_cdata=False)
    xml = etree.fromstring(xml_send, parser=parser)

    namespaceNFe = xml.find(".//{http://www.portalfiscal.inf.br/nfe}NFe")
    if namespaceNFe is not None:
        namespaceNFe.set('xmlns', 'http://www.portalfiscal.inf.br/nfe')

    with client.settings(raw_response=True):
        response = client.service[first_operation](xml)
        if raise_for_status:
            response.raise_for_status()
        response, obj = sanitize_response(response.text)
        return {
            'sent_xml': xml_send,
            'received_xml': response,
            'object': obj.Body.getchildren()[0]
        }
Example #24
0
def _send(certificado, method, **kwargs):
    base_url = "https://nfse.goiania.go.gov.br/ws/nfse.asmx?wsdl"
    xml_send = kwargs["xml"]
    cert, key = extract_cert_and_key_from_pfx(certificado.pfx, certificado.password)
    cert, key = save_cert_key(cert, key)
    client = get_authenticated_client(base_url, cert, key)

    try:
        response = getattr(client.service, method)(xml_send)
    except suds.WebFault as e:
        return {
            "send_xml": str(xml_send),
            "received_xml": str(e.fault.faultstring),
            "object": None,
        }

    response, obj = sanitize_response(response)
    return {"send_xml": str(xml_send), "received_xml": str(response), "object": obj}
Example #25
0
def _send(method, **kwargs):
    if kwargs["ambiente"] == "producao":
        base_url = "http://sistemas.pmp.sp.gov.br/semfi/simpliss/ws_nfse/nfseservice.svc"  # noqa
    else:
        base_url = "http://wshomologacao.simplissweb.com.br/nfseservice.svc"  # noqa

    base_url = "http://wshomologacao.simplissweb.com.br/nfseservice.svc"
    xml_send = kwargs["xml"]
    path = os.path.join(os.path.dirname(__file__), "templates")
    soap = render_xml(path, "SoapRequest.xml", False, soap_body=xml_send)

    act = "http://www.sistema.com.br/Sistema.Ws.Nfse/INfseService/%s" % method

    client = HttpClient(base_url)
    response = client.post_soap(soap, act)

    response, obj = sanitize_response(response)
    return {"sent_xml": xml_send, "received_xml": response, "object": obj}
Example #26
0
def _send(method, **kwargs):
    if kwargs['ambiente'] == 'producao':
        base_url = 'http://sistemas.pmp.sp.gov.br/semfi/simpliss/ws_nfse/nfseservice.svc'  # noqa
    else:
        base_url = 'http://wshomologacao.simplissweb.com.br/nfseservice.svc'  # noqa

    base_url = 'http://wshomologacao.simplissweb.com.br/nfseservice.svc'
    xml_send = kwargs["xml"].replace('<?xml version="1.0"?>', '')
    path = os.path.join(os.path.dirname(__file__), 'templates')
    soap = render_xml(path, 'SoapRequest.xml', False, soap_body=xml_send)

    act = 'http://www.sistema.com.br/Sistema.Ws.Nfse/INfseService/%s' % method

    client = HttpClient(base_url)
    response = client.post_soap(soap, act)

    response, obj = sanitize_response(response)
    return {'sent_xml': xml_send, 'received_xml': response, 'object': obj}
Example #27
0
def _send(certificado, method, **kwargs):
    base_url = ""
    if kwargs["ambiente"] == "producao":
        base_url = (
            "https://petropolis.sigiss.com.br/petropolis/ws/sigiss_ws.php"  # noqa
        )
    else:
        raise Exception("Não existe ambiente de homologação!")

    xml_send = kwargs["xml"].decode("utf-8")
    headers = {
        "SOAPAction": "urn:sigiss_ws#%s" % method,
        "Content-Type": 'text/xml; charset="utf-8"',
    }

    r = requests.post(base_url, data=xml_send, headers=headers)
    response, obj = sanitize_response(r.text.strip())

    return {"sent_xml": xml_send, "received_xml": response, "object": obj.Body}
Example #28
0
def _send(certificado, method, **kwargs):
    base_url = ''
    if kwargs['ambiente'] == 'producao':
        base_url = 'https://nfe.etransparencia.com.br/rj.petropolis/webservice/aws_nfe.aspx'  # noqa
    else:
        base_url = 'https://nfehomologacao.etransparencia.com.br/rj.petropolis/webservice/aws_nfe.aspx'  # noqa

    xml_send = kwargs["xml"]
    path = os.path.join(os.path.dirname(__file__), 'templates')
    soap = render_xml(path, 'SoapRequest.xml', False, soap_body=xml_send)

    client = HttpClient(base_url)
    response = client.post_soap(soap, 'NFeaction/AWS_NFE.%s' % method)

    response, obj = sanitize_response(response)
    return {
        'sent_xml': xml_send,
        'received_xml': response,
        'object': obj
    }
 def test_inutilizacao_2_sequences(self, inutilizar, validar):
     validar.return_value = ''
     with open(os.path.join(self.caminho,
                            'xml/inutilizacao_sent_xml.xml')) as f:
         sent_xml = f.read()
     with open(
             os.path.join(self.caminho,
                          'xml/inutilizacao_received_ok_xml.xml')) as f:
         received_xml = f.read()
     _, obj = sanitize_response(received_xml)
     inutilizar.return_value = {
         'received_xml': received_xml,
         'sent_xml': sent_xml,
         'object': obj
     }
     wizard1 = self.env['wizard.inutilization.nfe.numeration'].create(
         dict(numeration_start=0,
              numeration_end=5,
              serie=self.serie.id,
              modelo='55',
              justificativa=
              'Sed lorem nibh, sodales ut ex a, tristique ullamcor'))
     wizard1.action_inutilize_nfe()
     wizard2 = self.env['wizard.inutilization.nfe.numeration'].create(
         dict(numeration_start=6,
              numeration_end=9,
              serie=self.serie.id,
              modelo='55',
              justificativa=
              'Sed lorem nibh, sodales ut ex a, tristique ullamcor'))
     wizard2.action_inutilize_nfe()
     invoice = self.env['account.move'].create(
         dict(
             self.default_invoice.items(),
             partner_id=self.partner_fisica.id,
         ))
     invoice.action_invoice_open()
     inv_eletr = self.env['invoice.eletronic'].search([('invoice_id', '=',
                                                        invoice.id)])
     self.assertEqual(inv_eletr.numero_nfe, '1')  # TODO Fix, should be 6
Example #30
0
 def test_inutilizacao_return_ok(self, inutilizar, validar):
     validar.return_value = ''
     with open(os.path.join(self.caminho,
                            'xml/inutilizacao_sent_xml.xml')) as f:
         sent_xml = f.read()
     with open(
             os.path.join(self.caminho,
                          'xml/inutilizacao_received_ok_xml.xml')) as f:
         received_xml = f.read()
     _, obj = sanitize_response(received_xml)
     inutilizar.return_value = {
         'received_xml': received_xml,
         'sent_xml': sent_xml,
         'object': obj
     }
     justif = 'Sed lorem nibh, sodales ut ex a, tristique ullamcor'
     wizard = self.env['wizard.inutilization.nfe.numeration'].create(
         dict(numeration_start=0,
              numeration_end=5,
              serie=self.serie.id,
              modelo='55',
              justificativa=justif))
     wizard.action_inutilize_nfe()
     inut_inv = self.env['invoice.eletronic.inutilized'].search([])
     self.assertEqual(len(inut_inv), 1)
     self.assertEqual(inut_inv.numeration_start, 0)
     self.assertEqual(inut_inv.numeration_end, 5)
     self.assertEqual(inut_inv.serie, self.serie)
     self.assertEqual(inut_inv.name, u'Série Inutilizada 0 - 5')
     self.assertEqual(inut_inv.justificativa, justif)
     self.assertEqual(inut_inv.state, 'done')
     invoice = self.env['account.invoice'].create(
         dict(
             self.default_invoice.items(),
             partner_id=self.partner_fisica.id,
         ))
     invoice.action_invoice_open()
     inv_eletr = self.env['invoice.eletronic'].search([('invoice_id', '=',
                                                        invoice.id)])
     self.assertEqual(inv_eletr.numero_nfe, '1')  # TODO Fix, should be 6
Example #31
0
    def test_nfse_sucesso_homologacao(self, envio_lote):
        for invoice in self.invoices:
            # Confirmando a fatura deve gerar um documento eletrônico
            invoice.action_invoice_open()

            # Lote recebido com sucesso
            xml_recebido = open(
                os.path.join(self.caminho, 'xml/nfse-sucesso.xml'),
                'r').read()
            resp = sanitize_response(xml_recebido)
            envio_lote.return_value = {
                'object': resp[1],
                'sent_xml': '<xml />',
                'received_xml': xml_recebido
            }
            invoice_eletronic = self.env['invoice.eletronic'].search([
                ('invoice_id', '=', invoice.id)
            ])
            invoice_eletronic.action_send_eletronic_invoice()
            self.assertEqual(invoice_eletronic.state, 'done')
            self.assertEqual(invoice_eletronic.codigo_retorno, '100')
            self.assertEqual(len(invoice_eletronic.eletronic_event_ids), 1)
Example #32
0
def _send(certificado, method, **kwargs):
    url = URLS[kwargs['ambiente']][method]
    xml_send = kwargs['xml']

    token = _get_oauth_token(**kwargs)
    if "access_token" not in token:
        raise Exception("%s - %s: %s" % (token["status"], token["error"],
                                         token["message"]))
    kwargs.update({"numero": 1, 'access_token': token["access_token"]})

    headers = {"Accept": "application/xml;charset=UTF-8",
               "Content-Type": "application/xml",
               "Authorization": "Bearer %s" % kwargs['access_token']}
    r = requests.post(url, headers=headers, data=xml_send)

    response, obj = sanitize_response(r.text.strip())
    return {
        'sent_xml': xml_send,
        'received_xml': response.encode('utf-8'),
        'object': obj,
        'status_code': r.status_code,
    }
    def test_carta_correca_eletronica(self, recepcao):
        # Mock o retorno da CCE
        xml_recebido = open(os.path.join(self.caminho, 'xml/cce-retorno.xml'),
                            'r').read()
        resp = sanitize_response(xml_recebido)
        recepcao.return_value = {
            'object': resp[1],
            'sent_xml': '<xml />',
            'received_xml': xml_recebido
        }
        self.carta_wizard_right.send_letter()

        Id = "ID1101103516122133291700016355001000000004115817672101"
        carta = self.env['carta.correcao.eletronica.evento'].search([])
        self.assertEquals(len(carta), 1)
        self.assertEquals(carta.message,
                          u"Evento registrado e vinculado a NF-e")
        self.assertEquals(carta.protocolo, "135160008802236")
        self.assertEquals(carta.correcao, 'Teste de Carta de Correcao' * 10)
        self.assertEquals(carta.sequencial_evento, 1)
        self.assertEquals(carta.tipo_evento, '110110')
        self.assertEquals(carta.id_cce, Id)
Example #34
0
def _send(method, **kwargs):
    if kwargs['ambiente'] == 'producao':
        base_url = 'http://sistemas.pmp.sp.gov.br/semfi/simpliss/ws_nfse/nfseservice.svc'  # noqa
    else:
        base_url = 'http://wshomologacao.simplissweb.com.br/nfseservice.svc'  # noqa

    base_url = 'http://wshomologacao.simplissweb.com.br/nfseservice.svc'
    xml_send = kwargs["xml"].replace('<?xml version="1.0"?>', '')
    path = os.path.join(os.path.dirname(__file__), 'templates')
    soap = render_xml(path, 'SoapRequest.xml', False, soap_body=xml_send)

    act = 'http://www.sistema.com.br/Sistema.Ws.Nfse/INfseService/%s' % method

    client = HttpClient(base_url)
    response = client.post_soap(soap, act)

    response, obj = sanitize_response(response)
    return {
        'sent_xml': xml_send,
        'received_xml': response,
        'object': obj
    }
Example #35
0
    cert, key = extract_cert_and_key_from_pfx(
        certificado.pfx, certificado.password)
    cert, key = save_cert_key(cert, key)
    client = get_authenticated_client(base_url, cert, key)
    try:
        xml_send = kwargs['xml']
        header = '<ns2:cabecalho xmlns:ns2="http://www.ginfes.com.br/cabecalho_v03.xsd" versao="3"><versaoDados>3</versaoDados></ns2:cabecalho>' #noqa
        response = getattr(client.service, method)(header, xml_send)
    except suds.WebFault, e:
        return {
            'sent_xml': xml_send,
            'received_xml': e.fault.faultstring,
            'object': None
        }

    response, obj = sanitize_response(response)
    return {
        'sent_xml': xml_send,
        'received_xml': response,
        'object': obj
    }


def xml_recepcionar_lote_rps(certificado, **kwargs):
    return _render(certificado, 'RecepcionarLoteRpsV3', **kwargs)


def recepcionar_lote_rps(certificado, **kwargs):
    if "xml" not in kwargs:
        kwargs['xml'] = xml_recepcionar_lote_rps(certificado, **kwargs)
    return _send(certificado, 'RecepcionarLoteRpsV3', **kwargs)