|
| 1 | +# Copyright (C) 2026 Raphaël Valyi - Akretion |
| 2 | + |
| 3 | +import logging |
| 4 | +from typing import Any, Optional |
| 5 | + |
| 6 | +from brazil_fiscal_client.fiscal_client import ( |
| 7 | + FiscalClient, |
| 8 | + Tamb, |
| 9 | +) |
| 10 | + |
| 11 | +# --- Content Bindings --- |
| 12 | +from nfelib.cte.client.v4_0.servers import Endpoint |
| 13 | + |
| 14 | +# --- Server Definitions --- |
| 15 | +from nfelib.cte.client.v4_0.servers import servers as SERVERS_CTE |
| 16 | + |
| 17 | +# --- SOAP Bindings --- |
| 18 | +from nfelib.cte.soap.v4_0.ctedistribuicaodfe import ( |
| 19 | + CteDistribuicaoDfeSoapCteDistDfeInteresse, |
| 20 | +) |
| 21 | + |
| 22 | +# --- Dist DF-e --- |
| 23 | +from nfelib.cte_dist_dfe.bindings.v1_0 import DistDfeInt, RetDistDfeInt |
| 24 | + |
| 25 | +_logger = logging.getLogger(__name__) |
| 26 | + |
| 27 | + |
| 28 | +class DfeClient(FiscalClient): |
| 29 | + """A façade for the CTe SOAP webservices.""" |
| 30 | + |
| 31 | + def __init__(self, **kwargs: Any): |
| 32 | + self.mod = kwargs.pop("mod", "55") |
| 33 | + super().__init__( |
| 34 | + service="nfe", |
| 35 | + versao="1.01", |
| 36 | + **kwargs, |
| 37 | + ) |
| 38 | + |
| 39 | + def _get_location(self, endpoint_type: Endpoint) -> str: |
| 40 | + """Construct the full HTTPS URL for the specified service.""" |
| 41 | + server_key = "AN" |
| 42 | + try: |
| 43 | + server_data = SERVERS_CTE[server_key] |
| 44 | + except KeyError: |
| 45 | + raise ValueError( |
| 46 | + f"No server configuration found for key: {server_key} " |
| 47 | + "(derived from UF {self.uf})" |
| 48 | + ) |
| 49 | + |
| 50 | + if self.ambiente == Tamb.PROD.value: |
| 51 | + endpoints = server_data["prod_endpoints"] |
| 52 | + else: |
| 53 | + endpoints = server_data.get("dev_endpoints", server_data["prod_endpoints"]) |
| 54 | + |
| 55 | + try: |
| 56 | + return endpoints[endpoint_type] |
| 57 | + except KeyError: |
| 58 | + raise ValueError( |
| 59 | + f"Endpoint {endpoint_type.name} not configured for server key: " |
| 60 | + "{server_key}" |
| 61 | + ) |
| 62 | + |
| 63 | + def send(self, action_class, obj, **kwargs): |
| 64 | + action_to_endpoint_map = { |
| 65 | + CteDistribuicaoDfeSoapCteDistDfeInteresse: Endpoint.CTEDISTRIBUICAODFE, |
| 66 | + } |
| 67 | + endpoint_type = action_to_endpoint_map[action_class] |
| 68 | + location = self._get_location(endpoint_type) |
| 69 | + |
| 70 | + wrapped_obj: dict[str, Any] |
| 71 | + if isinstance(obj, DistDfeInt): |
| 72 | + wrapped_obj = { |
| 73 | + # Notice the 'cteDistDFeInteresse' and 'cteDadosMsg' vs CTe |
| 74 | + "Body": {"cteDistDFeInteresse": {"cteDadosMsg": {"content": [obj]}}} |
| 75 | + } |
| 76 | + else: |
| 77 | + wrapped_obj = {"Body": {"cteDadosMsg": {"content": [obj]}}} |
| 78 | + |
| 79 | + response = super().send( |
| 80 | + action_class, |
| 81 | + location, |
| 82 | + wrapped_obj, |
| 83 | + **kwargs, |
| 84 | + ) |
| 85 | + |
| 86 | + # Unwrapping response logic |
| 87 | + soap_envelope = response.resposta if self.wrap_response else response |
| 88 | + result_container = ( |
| 89 | + soap_envelope.body.cteDistDFeInteresseResponse.cteDistDFeInteresseResult |
| 90 | + ) |
| 91 | + |
| 92 | + result_container = ( |
| 93 | + soap_envelope.body.cteDistDFeInteresseResponse.cteDistDFeInteresseResult |
| 94 | + ) |
| 95 | + |
| 96 | + if not self.wrap_response: |
| 97 | + return result_container.content[0] |
| 98 | + |
| 99 | + response.resposta = result_container.content[0] |
| 100 | + |
| 101 | + return response |
| 102 | + |
| 103 | + def consultar_distribuicao( |
| 104 | + self, |
| 105 | + cnpj_cpf: str, |
| 106 | + ultimo_nsu: str = "", |
| 107 | + nsu_especifico: str = "", |
| 108 | + chave: str = "", |
| 109 | + ) -> Optional[RetDistDfeInt]: |
| 110 | + """Consultar Distribução de CTe. |
| 111 | +
|
| 112 | + :param cnpj_cpf: CPF ou CNPJ a ser consultado |
| 113 | + :param ultimo_nsu: Último NSU para pesquisa. Formato: '999999999999999' |
| 114 | + :param nsu_especifico: NSU Específico para pesquisa. |
| 115 | + Formato: '999999999999999' |
| 116 | + :param chave: Chave de acesso do documento |
| 117 | + :return: Retorna uma estrutura contendo as estruturas de envio |
| 118 | + e retorno preenchidas |
| 119 | + """ |
| 120 | + if not ultimo_nsu and not nsu_especifico and not chave: |
| 121 | + return None |
| 122 | + |
| 123 | + distNSU = consNSU = None |
| 124 | + if ultimo_nsu: |
| 125 | + distNSU = DistDfeInt.DistNsu(ultNSU=ultimo_nsu) |
| 126 | + if nsu_especifico: |
| 127 | + consNSU = DistDfeInt.ConsNsu(NSU=nsu_especifico) |
| 128 | + |
| 129 | + if distNSU and consNSU: |
| 130 | + # TODO: Raise? |
| 131 | + return None |
| 132 | + |
| 133 | + return self.send( |
| 134 | + CteDistribuicaoDfeSoapCteDistDfeInteresse, |
| 135 | + DistDfeInt( |
| 136 | + versao=self.versao, |
| 137 | + tpAmb=self.ambiente, |
| 138 | + cUFAutor=self.uf, |
| 139 | + CNPJ=cnpj_cpf if len(cnpj_cpf) > 11 else None, |
| 140 | + CPF=cnpj_cpf if len(cnpj_cpf) <= 11 else None, |
| 141 | + distNSU=distNSU, |
| 142 | + consNSU=consNSU, |
| 143 | + ), |
| 144 | + ) |
0 commit comments