|
| 1 | +# Copyright (C) 2019 Luis Felipe Mileo - KMEE |
| 2 | +# Copyright (C) 2025 Raphaël Valyi - Akretion |
| 3 | + |
| 4 | +import logging |
| 5 | +from typing import Any, Optional |
| 6 | + |
| 7 | +from brazil_fiscal_client.fiscal_client import ( |
| 8 | + FiscalClient, |
| 9 | + Tamb, |
| 10 | +) |
| 11 | + |
| 12 | +# --- Content Bindings --- |
| 13 | +from nfelib.nfe.client.v4_0.servers import Endpoint |
| 14 | + |
| 15 | +# --- Server Definitions --- |
| 16 | +from nfelib.nfe.client.v4_0.servers import servers as SERVERS_NFE |
| 17 | + |
| 18 | +# --- SOAP Bindings --- |
| 19 | +from nfelib.nfe.soap.v4_0.nfedistribuicaodfe import ( |
| 20 | + NfeDistribuicaoDfeSoapNfeDistDfeInteresse, |
| 21 | +) |
| 22 | + |
| 23 | +# --- Dist DF-e --- |
| 24 | +from nfelib.nfe_dist_dfe.bindings.v1_0 import DistDfeInt, RetDistDfeInt |
| 25 | + |
| 26 | +_logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +class DfeClient(FiscalClient): |
| 30 | + """A façade for the NFe SOAP webservices.""" |
| 31 | + |
| 32 | + def __init__(self, **kwargs: Any): |
| 33 | + self.mod = kwargs.pop("mod", "55") |
| 34 | + super().__init__( |
| 35 | + service="nfe", |
| 36 | + versao="4.00", |
| 37 | + **kwargs, |
| 38 | + ) |
| 39 | + |
| 40 | + def _get_location(self, endpoint_type: Endpoint) -> str: |
| 41 | + """Construct the full HTTPS URL for the specified service.""" |
| 42 | + server_key = "AN" |
| 43 | + try: |
| 44 | + server_data = SERVERS_NFE[server_key] |
| 45 | + except KeyError: |
| 46 | + raise ValueError( |
| 47 | + f"No server configuration found for key: {server_key} " |
| 48 | + "(derived from UF {self.uf})" |
| 49 | + ) |
| 50 | + |
| 51 | + if self.ambiente == Tamb.PROD.value: |
| 52 | + server_host = server_data["prod_server"] |
| 53 | + else: |
| 54 | + server_host = server_data["dev_server"] |
| 55 | + |
| 56 | + try: |
| 57 | + path = server_data["endpoints"][endpoint_type] |
| 58 | + except KeyError: |
| 59 | + raise ValueError( |
| 60 | + f"Endpoint {endpoint_type.name} not configured for server key: " |
| 61 | + "{server_key}" |
| 62 | + ) |
| 63 | + |
| 64 | + location = f"https://{server_host}{path}" |
| 65 | + _logger.debug( |
| 66 | + f"Determined location for {endpoint_type.name} (UF: {self.uf}, " |
| 67 | + "Amb: {self.ambiente}): {location}" |
| 68 | + ) |
| 69 | + return location |
| 70 | + |
| 71 | + def send( |
| 72 | + self, |
| 73 | + action_class: type, |
| 74 | + obj: Any, |
| 75 | + placeholder_exp: Optional[str] = None, |
| 76 | + placeholder_content: Optional[str] = None, |
| 77 | + **kwargs: Any, |
| 78 | + ) -> Any: |
| 79 | + """Build and send a request for the input object. |
| 80 | +
|
| 81 | + Args: |
| 82 | + action_class: type generated with xsdata for the SOAP wsdl action |
| 83 | + (e.g., NfeStatusServico4SoapNfeStatusServicoNf). |
| 84 | + obj: The *content* model instance (e.g., ConsStatServ) or a dictionary. |
| 85 | + This will be wrapped inside nfeDadosMsg. |
| 86 | + placeholder_content: A string content to be injected in the payload. |
| 87 | + Used for signed content to avoid signature issues. |
| 88 | + placeholder_exp: Placeholder expression where to inject placeholder_content. |
| 89 | + kwargs: Additional keyword arguments for FiscalClient.send. |
| 90 | +
|
| 91 | + Returns: |
| 92 | + The *content* response model instance (e.g., RetConsStatServ). |
| 93 | + """ |
| 94 | + try: |
| 95 | + # Determine the correct endpoint enum based on the action class |
| 96 | + action_to_endpoint_map: dict[type, Endpoint] = { |
| 97 | + NfeDistribuicaoDfeSoapNfeDistDfeInteresse: Endpoint.NFEDISTRIBUICAODFE, |
| 98 | + } |
| 99 | + endpoint_type = action_to_endpoint_map[action_class] |
| 100 | + location = self._get_location(endpoint_type) |
| 101 | + |
| 102 | + except KeyError: |
| 103 | + raise ValueError( |
| 104 | + "Could not determine Endpoint for action_class: {action_class.__name__}" |
| 105 | + ) |
| 106 | + |
| 107 | + wrapped_obj: dict[str, Any] |
| 108 | + if isinstance(obj, DistDfeInt): |
| 109 | + wrapped_obj = { |
| 110 | + "Body": {"nfeDistDFeInteresse": {"nfeDadosMsg": {"content": [obj]}}} |
| 111 | + } |
| 112 | + else: |
| 113 | + wrapped_obj = {"Body": {"nfeDadosMsg": {"content": [obj]}}} |
| 114 | + |
| 115 | + response = super().send( |
| 116 | + action_class, |
| 117 | + location, |
| 118 | + wrapped_obj, |
| 119 | + placeholder_exp=placeholder_exp, |
| 120 | + placeholder_content=placeholder_content, |
| 121 | + **kwargs, |
| 122 | + ) |
| 123 | + |
| 124 | + result_container = ( |
| 125 | + response.body.nfeDistDFeInteresseResponse.nfeDistDFeInteresseResult |
| 126 | + ) |
| 127 | + |
| 128 | + if not self.wrap_response: |
| 129 | + return result_container.content[0] |
| 130 | + |
| 131 | + response.resposta = result_container.content[0] |
| 132 | + |
| 133 | + return response |
| 134 | + |
| 135 | + def consultar_distribuicao( |
| 136 | + self, |
| 137 | + cnpj_cpf: str, |
| 138 | + ultimo_nsu: str = "", |
| 139 | + nsu_especifico: str = "", |
| 140 | + chave: str = "", |
| 141 | + ) -> Optional[RetDistDfeInt]: |
| 142 | + """Consultar Distribução de NFe. |
| 143 | +
|
| 144 | + :param cnpj_cpf: CPF ou CNPJ a ser consultado |
| 145 | + :param ultimo_nsu: Último NSU para pesquisa. Formato: '999999999999999' |
| 146 | + :param nsu_especifico: NSU Específico para pesquisa. |
| 147 | + Formato: '999999999999999' |
| 148 | + :param chave: Chave de acesso do documento |
| 149 | + :return: Retorna uma estrutura contendo as estruturas de envio |
| 150 | + e retorno preenchidas |
| 151 | + """ |
| 152 | + if not ultimo_nsu and not nsu_especifico and not chave: |
| 153 | + return None |
| 154 | + |
| 155 | + distNSU = consNSU = consChNFe = None |
| 156 | + if ultimo_nsu: |
| 157 | + distNSU = DistDfeInt.DistNsu(ultNSU=ultimo_nsu) |
| 158 | + if nsu_especifico: |
| 159 | + consNSU = DistDfeInt.ConsNsu(NSU=nsu_especifico) |
| 160 | + if chave: |
| 161 | + consChNFe = DistDfeInt.ConsChNfe(chNFe=chave) |
| 162 | + |
| 163 | + if (distNSU and consNSU) or (distNSU and consChNFe) or (consNSU and consChNFe): |
| 164 | + # TODO: Raise? |
| 165 | + return None |
| 166 | + |
| 167 | + return self.send( |
| 168 | + NfeDistribuicaoDfeSoapNfeDistDfeInteresse, |
| 169 | + DistDfeInt( |
| 170 | + versao=self.versao, |
| 171 | + tpAmb=self.ambiente, |
| 172 | + cUFAutor=self.uf, |
| 173 | + CNPJ=cnpj_cpf if len(cnpj_cpf) > 11 else None, |
| 174 | + CPF=cnpj_cpf if len(cnpj_cpf) <= 11 else None, |
| 175 | + distNSU=distNSU, |
| 176 | + consNSU=consNSU, |
| 177 | + consChNFe=consChNFe, |
| 178 | + ), |
| 179 | + ) |
0 commit comments