loop-api-sdk 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
loop_api_sdk/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from .client import DEFAULT_BASE_URL, LoopAPI, SyncResult
|
|
2
|
+
from .exceptions import LoopAPIError, LoopSyncError
|
|
3
|
+
|
|
4
|
+
__all__ = [
|
|
5
|
+
"LoopAPI",
|
|
6
|
+
"SyncResult",
|
|
7
|
+
"LoopAPIError",
|
|
8
|
+
"LoopSyncError",
|
|
9
|
+
"DEFAULT_BASE_URL",
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
# A versão vem do setup.cfg (lida dos metadados do pacote instalado).
|
|
13
|
+
try:
|
|
14
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
15
|
+
except ImportError: # Python < 3.8
|
|
16
|
+
from importlib_metadata import PackageNotFoundError, version
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
__version__ = version("loop-api-sdk") # mesmo valor do "name" no setup.cfg
|
|
20
|
+
except PackageNotFoundError: # código rodando sem ter sido instalado com pip
|
|
21
|
+
__version__ = "0.0.0+unknown"
|
loop_api_sdk/client.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any, Dict, Iterator, List, Optional
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from .exceptions import LoopAPIError, LoopSyncError
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger("loop_api_sdk")
|
|
11
|
+
|
|
12
|
+
DEFAULT_BASE_URL = "https://integration.readymix.io/api/sync"
|
|
13
|
+
|
|
14
|
+
# "get", "post", "put" ou "delete" (typing.Literal só existe a partir do 3.8)
|
|
15
|
+
HttpMethod = str
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class SyncResult:
|
|
20
|
+
"""Resultado de um envio em lotes.
|
|
21
|
+
|
|
22
|
+
Avalia como True/False em `if`, então `if api.send_orders(...):` continua funcionando.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
endpoint: str
|
|
26
|
+
total_items: int
|
|
27
|
+
total_batches: int
|
|
28
|
+
responses: List[Dict[str, Any]] = field(default_factory=list)
|
|
29
|
+
sent_items: int = 0
|
|
30
|
+
failed_batch: Optional[int] = None # número do lote que falhou (começa em 1)
|
|
31
|
+
error: Optional[LoopAPIError] = None
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def success(self) -> bool:
|
|
35
|
+
return self.error is None
|
|
36
|
+
|
|
37
|
+
def __bool__(self) -> bool:
|
|
38
|
+
return self.success
|
|
39
|
+
|
|
40
|
+
def raise_for_error(self) -> "SyncResult":
|
|
41
|
+
if self.error is not None:
|
|
42
|
+
raise LoopSyncError(self) from self.error
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class LoopAPI:
|
|
47
|
+
"""Cliente da API de sincronização do Loop."""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
token: str,
|
|
52
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
53
|
+
batch_max_size: int = 50,
|
|
54
|
+
timeout: float = 120,
|
|
55
|
+
raise_on_error: bool = False,
|
|
56
|
+
session: Optional[requests.Session] = None,
|
|
57
|
+
):
|
|
58
|
+
if not token:
|
|
59
|
+
raise ValueError("token é obrigatório")
|
|
60
|
+
if batch_max_size < 1:
|
|
61
|
+
raise ValueError("batch_max_size deve ser >= 1")
|
|
62
|
+
|
|
63
|
+
self.base_url = base_url.rstrip("/")
|
|
64
|
+
self.batch_max_size = batch_max_size
|
|
65
|
+
self.timeout = timeout
|
|
66
|
+
self.raise_on_error = raise_on_error
|
|
67
|
+
|
|
68
|
+
self.session = session or requests.Session()
|
|
69
|
+
self.session.headers.update({
|
|
70
|
+
"token": token,
|
|
71
|
+
"Content-Type": "application/json",
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
@classmethod
|
|
75
|
+
def from_env(cls, prefix: str = "LOOP_", **kwargs) -> "LoopAPI":
|
|
76
|
+
"""Cria o cliente a partir de LOOP_TOKEN e (opcional) LOOP_BASE_URL."""
|
|
77
|
+
token = os.environ.get(f"{prefix}TOKEN")
|
|
78
|
+
if not token:
|
|
79
|
+
raise ValueError(f"Variável de ambiente {prefix}TOKEN não definida")
|
|
80
|
+
base_url = os.environ.get(f"{prefix}BASE_URL")
|
|
81
|
+
if base_url:
|
|
82
|
+
kwargs.setdefault("base_url", base_url)
|
|
83
|
+
return cls(token=token, **kwargs)
|
|
84
|
+
|
|
85
|
+
# ---------- context manager ----------
|
|
86
|
+
|
|
87
|
+
def close(self) -> None:
|
|
88
|
+
self.session.close()
|
|
89
|
+
|
|
90
|
+
def __enter__(self) -> "LoopAPI":
|
|
91
|
+
return self
|
|
92
|
+
|
|
93
|
+
def __exit__(self, *exc) -> None:
|
|
94
|
+
self.close()
|
|
95
|
+
|
|
96
|
+
# ---------- endpoints ----------
|
|
97
|
+
|
|
98
|
+
def send_deliveries(self, body: list) -> SyncResult:
|
|
99
|
+
return self.send("tickets", body)
|
|
100
|
+
|
|
101
|
+
def send_projects(self, body: list, create_even_if_inactive: bool = True) -> SyncResult:
|
|
102
|
+
return self.send("projects", body, params={"create_even_if_inactive": create_even_if_inactive})
|
|
103
|
+
|
|
104
|
+
def send_customers(self, body: list) -> SyncResult:
|
|
105
|
+
return self.send("customers", body)
|
|
106
|
+
|
|
107
|
+
def send_products(self, body: list) -> SyncResult:
|
|
108
|
+
return self.send("products", body)
|
|
109
|
+
|
|
110
|
+
def send_orders(self, body: list, create_plans: bool = True, update_plans: bool = True) -> SyncResult:
|
|
111
|
+
return self.send("orders", body, params={"create_plans": create_plans, "update_plans": update_plans})
|
|
112
|
+
|
|
113
|
+
def send_purchase_orders(self, body: list, update_after_start: Optional[bool] = None) -> SyncResult:
|
|
114
|
+
params = {}
|
|
115
|
+
if update_after_start is not None:
|
|
116
|
+
params["update_after_start"] = update_after_start
|
|
117
|
+
return self.send("po", body, params=params or None)
|
|
118
|
+
|
|
119
|
+
def send_invoices(self, body: list) -> SyncResult:
|
|
120
|
+
return self.send("invoices", body)
|
|
121
|
+
|
|
122
|
+
# ---------- genérico ----------
|
|
123
|
+
|
|
124
|
+
def send(self, endpoint: str, body: list, params: Optional[dict] = None) -> SyncResult:
|
|
125
|
+
"""Envia `body` em lotes via POST para {base_url}/{endpoint}.
|
|
126
|
+
|
|
127
|
+
Para no primeiro lote que falhar; os lotes anteriores já foram aceitos pela API.
|
|
128
|
+
"""
|
|
129
|
+
batches = list(_chunks(body, self.batch_max_size))
|
|
130
|
+
result = SyncResult(endpoint=endpoint, total_items=len(body), total_batches=len(batches))
|
|
131
|
+
|
|
132
|
+
for i, batch in enumerate(batches, start=1):
|
|
133
|
+
logger.info("Enviando %s: lote %d/%d (%d itens)", endpoint, i, len(batches), len(batch))
|
|
134
|
+
try:
|
|
135
|
+
data = self.request("post", endpoint, body=batch, params=params)
|
|
136
|
+
except LoopAPIError as e:
|
|
137
|
+
logger.error("Falha em %s no lote %d/%d: %s", endpoint, i, len(batches), e)
|
|
138
|
+
result.error = e
|
|
139
|
+
result.failed_batch = i
|
|
140
|
+
break
|
|
141
|
+
result.responses.append(data)
|
|
142
|
+
result.sent_items += len(batch)
|
|
143
|
+
|
|
144
|
+
if self.raise_on_error:
|
|
145
|
+
result.raise_for_error()
|
|
146
|
+
return result
|
|
147
|
+
|
|
148
|
+
def request(
|
|
149
|
+
self,
|
|
150
|
+
method: HttpMethod,
|
|
151
|
+
endpoint: str,
|
|
152
|
+
body: Any = None,
|
|
153
|
+
params: Optional[dict] = None,
|
|
154
|
+
) -> Dict[str, Any]:
|
|
155
|
+
"""Faz uma requisição única. Retorna o JSON ou lança LoopAPIError."""
|
|
156
|
+
url = f"{self.base_url}/{endpoint.lstrip('/')}"
|
|
157
|
+
|
|
158
|
+
try:
|
|
159
|
+
resp = self.session.request(
|
|
160
|
+
method.upper(), url, json=body, params=params, timeout=self.timeout
|
|
161
|
+
)
|
|
162
|
+
except requests.RequestException as e:
|
|
163
|
+
raise LoopAPIError(f"Erro de conexão com {url}: {e}") from e
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
data = resp.json()
|
|
167
|
+
except ValueError:
|
|
168
|
+
raise LoopAPIError(
|
|
169
|
+
"Resposta não é JSON", status_code=resp.status_code, payload=resp.text[:2000]
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
logger.debug("%s %s -> HTTP %s: %s", method.upper(), url, resp.status_code, data)
|
|
173
|
+
|
|
174
|
+
if not isinstance(data, dict) or data.get("success") is not True:
|
|
175
|
+
raise LoopAPIError("API retornou success != true", status_code=resp.status_code, payload=data)
|
|
176
|
+
|
|
177
|
+
return data
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _chunks(items: list, size: int) -> Iterator[list]:
|
|
181
|
+
for i in range(0, len(items), size):
|
|
182
|
+
yield items[i:i + size]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from typing import Any, Optional
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class LoopAPIError(Exception):
|
|
5
|
+
"""Falha numa requisição à API do Loop (conexão, resposta inválida ou success=False)."""
|
|
6
|
+
|
|
7
|
+
def __init__(self, message: str, status_code: Optional[int] = None, payload: Any = None):
|
|
8
|
+
super().__init__(message)
|
|
9
|
+
self.status_code = status_code
|
|
10
|
+
self.payload = payload
|
|
11
|
+
|
|
12
|
+
def __str__(self) -> str:
|
|
13
|
+
base = super().__str__()
|
|
14
|
+
if self.status_code is not None:
|
|
15
|
+
base = f"[HTTP {self.status_code}] {base}"
|
|
16
|
+
if self.payload is not None:
|
|
17
|
+
base = f"{base} | resposta: {self.payload}"
|
|
18
|
+
return base
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LoopSyncError(Exception):
|
|
22
|
+
"""Lançada por SyncResult.raise_for_error() ou quando raise_on_error=True."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, result):
|
|
25
|
+
self.result = result
|
|
26
|
+
super().__init__(
|
|
27
|
+
f"Falha ao enviar para '{result.endpoint}': lote {result.failed_batch} "
|
|
28
|
+
f"de {result.total_batches} falhou ({result.sent_items}/{result.total_items} "
|
|
29
|
+
f"itens já enviados). Erro: {result.error}"
|
|
30
|
+
)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: loop-api-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cliente Python para a API de sincronização do Loop
|
|
5
|
+
Classifier: Programming Language :: Python :: 3
|
|
6
|
+
Classifier: Programming Language :: Python :: 3.6
|
|
7
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Requires-Python: >=3.6
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
Requires-Dist: requests>=2.25
|
|
18
|
+
Requires-Dist: dataclasses; python_version < "3.7"
|
|
19
|
+
Requires-Dist: importlib-metadata; python_version < "3.8"
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest>=6.2; extra == "dev"
|
|
22
|
+
|
|
23
|
+
# loop-api-sdk
|
|
24
|
+
|
|
25
|
+
Cliente Python para a API de sincronização do Loop.
|
|
26
|
+
|
|
27
|
+
## Instalação
|
|
28
|
+
|
|
29
|
+
No `requirements.txt` do integrador:
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
loop-api-sdk @ git+ssh://git@bitbucket.org/<workspace>/loop-api-sdk.git@v0.1.0
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Uso
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import logging
|
|
39
|
+
from loop_api_sdk import LoopAPI
|
|
40
|
+
|
|
41
|
+
logging.basicConfig(level=logging.INFO)
|
|
42
|
+
|
|
43
|
+
api = LoopAPI.from_env() # lê LOOP_TOKEN e, opcionalmente, LOOP_BASE_URL
|
|
44
|
+
|
|
45
|
+
result = api.send_orders(orders)
|
|
46
|
+
if not result:
|
|
47
|
+
print(f"Falhou no lote {result.failed_batch}: {result.error}")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Para lançar exceção em vez de checar o retorno: `LoopAPI(..., raise_on_error=True)`
|
|
51
|
+
ou `api.send_orders(orders).raise_for_error()`.
|
|
52
|
+
|
|
53
|
+
Endpoint ainda sem método próprio: `api.send("novo-endpoint", body, params={...})`.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
loop_api_sdk/__init__.py,sha256=9E69k9FIXD9pTvuTJ0qQaurf8mz3IO49ZisFp6Kwwsg,665
|
|
2
|
+
loop_api_sdk/client.py,sha256=0V19u2olxWYba1SAAWTJxS2XN1Ft0Ln2oGbaslV_BW8,6182
|
|
3
|
+
loop_api_sdk/exceptions.py,sha256=LFQ9xisvcUYQLhiLln2-FY0U-LuukqJf7RuBMntjSrU,1084
|
|
4
|
+
loop_api_sdk-0.1.0.dist-info/METADATA,sha256=Jn3HGbIzXD5JzYSY2NcPAIphNOu7IKNLECTipczWvkQ,1627
|
|
5
|
+
loop_api_sdk-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
loop_api_sdk-0.1.0.dist-info/top_level.txt,sha256=fI5y1AxY1lzuvTXGR6wjsidZSPwRzdIUyRO6Q1RCcN0,13
|
|
7
|
+
loop_api_sdk-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
loop_api_sdk
|