smartdocpy 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.
Files changed (46) hide show
  1. smartdoc/__init__.py +144 -0
  2. smartdoc/_core/__init__.py +0 -0
  3. smartdoc/_core/async_config.py +254 -0
  4. smartdoc/_core/config.py +368 -0
  5. smartdoc/_core/pagination.py +144 -0
  6. smartdoc/_core/transport.py +379 -0
  7. smartdoc/async_client.py +128 -0
  8. smartdoc/builders/__init__.py +9 -0
  9. smartdoc/builders/associated.py +107 -0
  10. smartdoc/builders/items.py +241 -0
  11. smartdoc/builders/recipient.py +256 -0
  12. smartdoc/client.py +160 -0
  13. smartdoc/constants/__init__.py +100 -0
  14. smartdoc/constants/_base.py +166 -0
  15. smartdoc/constants/api_errors.py +52 -0
  16. smartdoc/constants/countries.py +108 -0
  17. smartdoc/constants/countries_data.json +1 -0
  18. smartdoc/constants/documents.py +169 -0
  19. smartdoc/constants/events.py +106 -0
  20. smartdoc/constants/permissions.py +76 -0
  21. smartdoc/constants/sifen.py +200 -0
  22. smartdoc/constants/statuses.py +194 -0
  23. smartdoc/errors.py +170 -0
  24. smartdoc/geo/__init__.py +270 -0
  25. smartdoc/geo/data.json +1 -0
  26. smartdoc/models.py +264 -0
  27. smartdoc/py.typed +0 -0
  28. smartdoc/resources/__init__.py +0 -0
  29. smartdoc/resources/async_base.py +175 -0
  30. smartdoc/resources/async_resources.py +481 -0
  31. smartdoc/resources/auto_invoices.py +182 -0
  32. smartdoc/resources/base.py +243 -0
  33. smartdoc/resources/bodies.py +384 -0
  34. smartdoc/resources/invoices.py +219 -0
  35. smartdoc/resources/notes.py +138 -0
  36. smartdoc/resources/receipts.py +140 -0
  37. smartdoc/resources/remission_notes.py +285 -0
  38. smartdoc/resources/support.py +222 -0
  39. smartdoc/webhooks/__init__.py +37 -0
  40. smartdoc/webhooks/adapters.py +94 -0
  41. smartdoc/webhooks/event.py +206 -0
  42. smartdoc/webhooks/router.py +289 -0
  43. smartdoc/webhooks/server.py +93 -0
  44. smartdocpy-0.1.0.dist-info/METADATA +265 -0
  45. smartdocpy-0.1.0.dist-info/RECORD +46 -0
  46. smartdocpy-0.1.0.dist-info/WHEEL +4 -0
smartdoc/models.py ADDED
@@ -0,0 +1,264 @@
1
+ """Objetos que devuelve la API.
2
+
3
+ Son envoltorios finos sobre el JSON: exponen con nombre las propiedades que
4
+ forman parte del contrato y dejan el resto accesible por clave. La razón es que
5
+ la API devuelve más campos de los que documenta, y varios son propios de cada
6
+ tipo de documento (``invoiceNumber``, ``creditNoteNumber``, …) que **no forman
7
+ parte del contrato y pueden cambiar sin aviso**. Modelarlos todos daría una
8
+ falsa sensación de estabilidad.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Iterator, Mapping
14
+ from typing import Any
15
+
16
+ from .constants.documents import DocumentType
17
+ from .constants.statuses import (
18
+ ERROR,
19
+ DocumentStatus,
20
+ is_error,
21
+ is_success,
22
+ is_terminal,
23
+ )
24
+
25
+ __all__ = ["Document", "TaxPayer", "Stamp", "Establishment", "DispatchPoint", "Client"]
26
+
27
+
28
+ class Record:
29
+ """Un objeto de la API, con acceso por clave a lo que el SDK no modela.
30
+
31
+ No hereda de ``Mapping`` a propósito: :class:`Document` necesita exponer
32
+ ``items`` como los ítems del documento, y eso chocaría con el ``items()`` de
33
+ la interfaz de mapeo. Para el JSON completo está :attr:`raw`.
34
+ """
35
+
36
+ __slots__ = ("_data",)
37
+
38
+ def __init__(self, data: Mapping[str, Any] | None = None) -> None:
39
+ self._data: dict[str, Any] = dict(data or {})
40
+
41
+ @property
42
+ def raw(self) -> dict[str, Any]:
43
+ """El JSON completo tal como lo devolvió la API."""
44
+ return self._data
45
+
46
+ def __getitem__(self, key: str) -> Any:
47
+ return self._data[key]
48
+
49
+ def __contains__(self, key: str) -> bool:
50
+ return key in self._data
51
+
52
+ def __iter__(self) -> Iterator[str]:
53
+ return iter(self._data)
54
+
55
+ def __len__(self) -> int:
56
+ return len(self._data)
57
+
58
+ def get(self, key: str, default: Any = None) -> Any:
59
+ """El valor de un campo que el SDK no modela."""
60
+ return self._data.get(key, default)
61
+
62
+ def __repr__(self) -> str:
63
+ return f"{type(self).__name__}({self._data!r})"
64
+
65
+
66
+ class Document(Record):
67
+ """Un documento electrónico: factura, recibo, nota o autofactura."""
68
+
69
+ __slots__ = ("_document_type",)
70
+
71
+ def __init__(
72
+ self,
73
+ data: Mapping[str, Any] | None = None,
74
+ document_type: DocumentType | None = None,
75
+ ) -> None:
76
+ super().__init__(data)
77
+ self._document_type = document_type
78
+
79
+ @property
80
+ def id(self) -> int:
81
+ return int(self._data["id"])
82
+
83
+ @property
84
+ def status(self) -> DocumentStatus | str:
85
+ """Estado actual. Devuelve el valor crudo si SmartDoc agregó uno nuevo."""
86
+ raw = self._data.get("status", "")
87
+ try:
88
+ return DocumentStatus(raw)
89
+ except ValueError:
90
+ return str(raw)
91
+
92
+ @property
93
+ def cdc(self) -> str | None:
94
+ """Código de Control de 44 caracteres.
95
+
96
+ Es ``None`` mientras el documento no se generó, y **no existe en los
97
+ recibos**, que no se envían a la DNIT.
98
+ """
99
+ return self._data.get("cdc")
100
+
101
+ @property
102
+ def document_type(self) -> DocumentType | None:
103
+ return self._document_type
104
+
105
+ @property
106
+ def is_terminal(self) -> bool:
107
+ """Si el documento ya no se mueve solo."""
108
+ return is_terminal(str(self._data.get("status", "")), self._document_type)
109
+
110
+ @property
111
+ def is_approved(self) -> bool:
112
+ """Si quedó válido fiscalmente.
113
+
114
+ Para un recibo, alcanza con estar generado: no pasa por la DNIT.
115
+ """
116
+ return is_success(str(self._data.get("status", "")), self._document_type)
117
+
118
+ @property
119
+ def is_error(self) -> bool:
120
+ return is_error(str(self._data.get("status", "")))
121
+
122
+ @property
123
+ def _has_problem(self) -> bool:
124
+ """Si el estado del documento amerita mirar el código de error.
125
+
126
+ ``RECOVERABLE_ERROR`` y ``CANCELLATION_FAILED`` se suman a los errores
127
+ firmes: no son terminales, pero el código explica qué pasó y sirve para
128
+ decidir si reintentar.
129
+ """
130
+ status = DocumentStatus.coerce(str(self._data.get("status", "")))
131
+ return status in ERROR or status in {
132
+ DocumentStatus.RECOVERABLE_ERROR,
133
+ DocumentStatus.CANCELLATION_FAILED,
134
+ }
135
+
136
+ @property
137
+ def error_code(self) -> str | None:
138
+ """Código del error, o ``None`` si el documento no está en error.
139
+
140
+ Puede ser ``None`` aun con el documento en error, según de dónde venga
141
+ el rechazo; :attr:`error_message` trae el detalle en todos los casos.
142
+ Para ramificar conviene :attr:`is_error`.
143
+ """
144
+ if not self._has_problem:
145
+ return None
146
+ return self._data.get("setResponseCode")
147
+
148
+ @property
149
+ def error_message(self) -> str | None:
150
+ """Descripción del error, o ``None`` si el documento no está en error."""
151
+ if not self._has_problem:
152
+ return None
153
+ return self._data.get("setResponseDescription") or self._data.get("setError")
154
+
155
+ @property
156
+ def amount(self) -> float | None:
157
+ """Monto total. Las notas de remisión no tienen."""
158
+ value = self._data.get("amount")
159
+ return float(value) if value is not None else None
160
+
161
+ @property
162
+ def items(self) -> list[dict[str, Any]]:
163
+ return list(self._data.get("items") or [])
164
+
165
+ def __repr__(self) -> str:
166
+ return (
167
+ f"<Document id={self._data.get('id')} "
168
+ f"status={self._data.get('status')!r} cdc={self.cdc!r}>"
169
+ )
170
+
171
+
172
+ class TaxPayer(Record):
173
+ """El contribuyente dueño de la API Key."""
174
+
175
+ @property
176
+ def id(self) -> int:
177
+ return int(self._data["id"])
178
+
179
+ @property
180
+ def ruc(self) -> str:
181
+ return str(self._data["ruc"])
182
+
183
+ @property
184
+ def social_name(self) -> str:
185
+ return str(self._data.get("socialName", ""))
186
+
187
+ @property
188
+ def fantasy_name(self) -> str:
189
+ return str(self._data.get("fantasyName", ""))
190
+
191
+ @property
192
+ def is_demo(self) -> bool:
193
+ """En una cuenta demo los documentos no se envían a la DNIT.
194
+
195
+ La respuesta se simula, así que se puede integrar y probar todo el
196
+ circuito, webhooks incluidos.
197
+
198
+ Con una salvedad: antes de enviar nada, SmartDoc verifica que el
199
+ certificado del contribuyente esté vigente, y esa verificación no
200
+ distingue si la cuenta es demo. Con el certificado vencido el documento
201
+ queda en ``error`` con código ``2450`` y nunca llega a la simulación.
202
+ Los recibos no aplican esa verificación.
203
+ """
204
+ return bool(self._data.get("isDemo"))
205
+
206
+
207
+ class Stamp(Record):
208
+ """Un timbrado."""
209
+
210
+ @property
211
+ def id(self) -> int:
212
+ return int(self._data["id"])
213
+
214
+ @property
215
+ def identifier(self) -> str:
216
+ return str(self._data["identifier"])
217
+
218
+ @property
219
+ def begin_date(self) -> str:
220
+ return str(self._data.get("beginDate", ""))[:10]
221
+
222
+ @property
223
+ def enabled(self) -> bool:
224
+ return bool(self._data.get("enabled", True))
225
+
226
+
227
+ class Establishment(Record):
228
+ """Un establecimiento."""
229
+
230
+ @property
231
+ def id(self) -> int:
232
+ return int(self._data["id"])
233
+
234
+ @property
235
+ def code(self) -> str:
236
+ return str(self._data["code"])
237
+
238
+
239
+ class DispatchPoint(Record):
240
+ """Un punto de expedición."""
241
+
242
+ @property
243
+ def id(self) -> int:
244
+ return int(self._data["id"])
245
+
246
+ @property
247
+ def identifier(self) -> str:
248
+ return str(self._data["identifier"])
249
+
250
+
251
+ class Client(Record):
252
+ """Un cliente cargado en SmartDoc."""
253
+
254
+ @property
255
+ def id(self) -> int:
256
+ return int(self._data["id"])
257
+
258
+ @property
259
+ def ruc(self) -> str:
260
+ return str(self._data.get("ruc", ""))
261
+
262
+ @property
263
+ def social_name(self) -> str:
264
+ return str(self._data.get("socialName", ""))
smartdoc/py.typed ADDED
File without changes
File without changes
@@ -0,0 +1,175 @@
1
+ """Recursos asíncronos.
2
+
3
+ Son el gemelo de :mod:`smartdoc.resources.base`. Lo que cambia es solo el
4
+ ``await``: las reglas de negocio —qué acciones acepta cada documento, cuándo un
5
+ estado es final, cómo se arma el cuerpo— viven en módulos compartidos
6
+ (:mod:`smartdoc.resources.bodies`, :mod:`smartdoc.constants.statuses`) y no se
7
+ duplican.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import time
14
+ from typing import Any, Generic, TypeVar, cast
15
+
16
+ from .._core.pagination import AsyncPage
17
+ from .._core.transport import Result, new_idempotency_key
18
+ from ..constants.documents import DocumentType
19
+ from ..errors import TimeoutError as SmartDocTimeout
20
+ from ..models import Document, Record
21
+
22
+ __all__ = ["AsyncResource", "AsyncDocumentResource"]
23
+
24
+ R = TypeVar("R", bound=Record)
25
+
26
+
27
+ class AsyncResource(Generic[R]):
28
+ """CRUD asíncrono sobre un recurso de la API."""
29
+
30
+ path: str = ""
31
+ model: type[Record] = Record
32
+
33
+ def __init__(self, transport: Any, config: Any = None) -> None:
34
+ self._transport = transport
35
+ self._config = config
36
+
37
+ def _wrap(self, data: Any) -> R:
38
+ return cast("R", self.model(data or {}))
39
+
40
+ async def _request(self, method: str, suffix: str = "", **kw: Any) -> Result:
41
+ result: Result = await self._transport.request(
42
+ method, f"/{self.path}{suffix}", **kw
43
+ )
44
+ return result
45
+
46
+ async def get(self, id: int) -> R:
47
+ """Un recurso por su id."""
48
+ return self._wrap((await self._request("GET", f"/{id}")).data)
49
+
50
+ async def list(
51
+ self, *, limit: int | None = None, cursor: str | None = None, **filtros: Any
52
+ ) -> AsyncPage[R]:
53
+ """Una página de resultados.
54
+
55
+ Para recorrer todo::
56
+
57
+ async for factura in (await sd.invoices.list()).auto_paging_iter():
58
+ ...
59
+ """
60
+ params = {k: v for k, v in filtros.items() if v is not None}
61
+ if limit is not None:
62
+ params["limit"] = limit
63
+ if cursor is not None:
64
+ params["cursor"] = cursor
65
+ return await self._page(params)
66
+
67
+ async def _page(self, params: dict[str, Any]) -> AsyncPage[R]:
68
+ result = await self._request("GET", params=params)
69
+ items = [self._wrap(d) for d in (result.data or [])]
70
+
71
+ async def fetch_next(next_cursor: str) -> AsyncPage[R]:
72
+ return await self._page({**params, "cursor": next_cursor})
73
+
74
+ return AsyncPage.from_result(items, result.pagination, fetch_next)
75
+
76
+ async def _create(self, body: dict[str, Any], idempotency_key: str | None) -> R:
77
+ result = await self._request(
78
+ "POST",
79
+ json=body,
80
+ idempotency_key=idempotency_key or new_idempotency_key(),
81
+ )
82
+ return self._wrap(result.data)
83
+
84
+ async def _update(self, id: int, body: dict[str, Any]) -> R:
85
+ return self._wrap((await self._request("PUT", f"/{id}", json=body)).data)
86
+
87
+ async def delete(self, id: int) -> None:
88
+ """Borra el recurso."""
89
+ await self._request("DELETE", f"/{id}")
90
+
91
+
92
+ class AsyncDocumentResource(AsyncResource[Document]):
93
+ """Un recurso asíncrono que además emite documentos electrónicos."""
94
+
95
+ model = Document
96
+ document_type: DocumentType
97
+ actions: frozenset[str] = frozenset()
98
+ has_kude: bool = False
99
+
100
+ def _wrap(self, data: Any) -> Document:
101
+ return Document(data or {}, self.document_type)
102
+
103
+ async def _action(
104
+ self, id: int, action: str, body: dict[str, Any] | None = None
105
+ ) -> dict[str, Any]:
106
+ """Ejecuta la acción y devuelve el ``data`` crudo de la respuesta.
107
+
108
+ Cada acción devuelve una forma distinta, así que envolver esto en un
109
+ :class:`Document` a ciegas daría un objeto sin estado. Ver la versión
110
+ síncrona para el detalle.
111
+ """
112
+ if action not in self.actions:
113
+ available = ", ".join(sorted(self.actions))
114
+ raise ValueError(
115
+ f"{type(self).__name__} no acepta la acción {action!r}. "
116
+ f"Acepta: {available}."
117
+ )
118
+ result = await self._request("POST", f"/{id}/actions/{action}", json=body or {})
119
+ return result.data or {}
120
+
121
+ async def cancel(self, id: int, reason: str) -> None:
122
+ """Anula el documento ante la DNIT. El motivo es obligatorio.
123
+
124
+ No devuelve el documento: la API responde el id de la anulación. Hay que
125
+ releerlo con :meth:`get` o esperarlo con :meth:`wait_until_final`.
126
+ """
127
+ await self._action(id, "cancel", {"reason": reason})
128
+
129
+ async def resend_email(self, id: int) -> None:
130
+ """Reenvía el documento por correo al receptor."""
131
+ await self._action(id, "resend_email")
132
+
133
+ async def resend_to_set(self, id: int) -> None:
134
+ """Reenvía a la DNIT un documento que quedó en error.
135
+
136
+ Como :meth:`cancel`, no devuelve el documento: hay que releerlo.
137
+ """
138
+ await self._action(id, "resend_to_set")
139
+
140
+ async def kude_url(self, id: int) -> str:
141
+ """URL temporal del KuDE en PDF."""
142
+ if not self.has_kude:
143
+ raise ValueError(f"{type(self).__name__} no expone KuDE en la API v2.")
144
+ result = await self._request("GET", f"/{id}/kude")
145
+ return str((result.data or {}).get("kudeUrl", ""))
146
+
147
+ async def wait_until_final(
148
+ self,
149
+ id: int,
150
+ *,
151
+ timeout: float = 300.0,
152
+ poll_interval: float = 2.0,
153
+ ) -> Document:
154
+ """Consulta el documento hasta que llegue a un estado final.
155
+
156
+ ``recoverable_error`` **no** corta la espera: SmartDoc lo reintenta solo.
157
+
158
+ El plazo por omisión es holgado porque el documento pasa por varios
159
+ estados intermedios y el recorrido puede llevar minutos.
160
+ """
161
+ deadline = time.monotonic() + timeout
162
+ document = await self.get(id)
163
+
164
+ while not document.is_terminal:
165
+ if time.monotonic() >= deadline:
166
+ raise SmartDocTimeout(
167
+ f"El documento {id} sigue en {document.status!r} después de "
168
+ f"{timeout:g}s. No es un error: el documento sigue su curso, "
169
+ f"lo que se agotó es la espera.",
170
+ last_status=str(document.status),
171
+ )
172
+ await asyncio.sleep(poll_interval)
173
+ document = await self.get(id)
174
+
175
+ return document