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.
- smartdoc/__init__.py +144 -0
- smartdoc/_core/__init__.py +0 -0
- smartdoc/_core/async_config.py +254 -0
- smartdoc/_core/config.py +368 -0
- smartdoc/_core/pagination.py +144 -0
- smartdoc/_core/transport.py +379 -0
- smartdoc/async_client.py +128 -0
- smartdoc/builders/__init__.py +9 -0
- smartdoc/builders/associated.py +107 -0
- smartdoc/builders/items.py +241 -0
- smartdoc/builders/recipient.py +256 -0
- smartdoc/client.py +160 -0
- smartdoc/constants/__init__.py +100 -0
- smartdoc/constants/_base.py +166 -0
- smartdoc/constants/api_errors.py +52 -0
- smartdoc/constants/countries.py +108 -0
- smartdoc/constants/countries_data.json +1 -0
- smartdoc/constants/documents.py +169 -0
- smartdoc/constants/events.py +106 -0
- smartdoc/constants/permissions.py +76 -0
- smartdoc/constants/sifen.py +200 -0
- smartdoc/constants/statuses.py +194 -0
- smartdoc/errors.py +170 -0
- smartdoc/geo/__init__.py +270 -0
- smartdoc/geo/data.json +1 -0
- smartdoc/models.py +264 -0
- smartdoc/py.typed +0 -0
- smartdoc/resources/__init__.py +0 -0
- smartdoc/resources/async_base.py +175 -0
- smartdoc/resources/async_resources.py +481 -0
- smartdoc/resources/auto_invoices.py +182 -0
- smartdoc/resources/base.py +243 -0
- smartdoc/resources/bodies.py +384 -0
- smartdoc/resources/invoices.py +219 -0
- smartdoc/resources/notes.py +138 -0
- smartdoc/resources/receipts.py +140 -0
- smartdoc/resources/remission_notes.py +285 -0
- smartdoc/resources/support.py +222 -0
- smartdoc/webhooks/__init__.py +37 -0
- smartdoc/webhooks/adapters.py +94 -0
- smartdoc/webhooks/event.py +206 -0
- smartdoc/webhooks/router.py +289 -0
- smartdoc/webhooks/server.py +93 -0
- smartdocpy-0.1.0.dist-info/METADATA +265 -0
- smartdocpy-0.1.0.dist-info/RECORD +46 -0
- smartdocpy-0.1.0.dist-info/WHEEL +4 -0
smartdoc/__init__.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""SDK de Python para SmartDoc — facturación electrónica en Paraguay.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
import smartdoc
|
|
6
|
+
|
|
7
|
+
sd = smartdoc.Client(api_key="pk_...")
|
|
8
|
+
|
|
9
|
+
factura = sd.invoices.create(
|
|
10
|
+
recipient=smartdoc.Recipient.entity(
|
|
11
|
+
ruc="80012345-1", social_name="Cliente S.A."
|
|
12
|
+
),
|
|
13
|
+
items=[smartdoc.Item("Consultoría", quantity=1, unit_amount=1_100_000)],
|
|
14
|
+
)
|
|
15
|
+
factura = sd.invoices.wait_until_final(factura.id)
|
|
16
|
+
print(factura.status, factura.cdc)
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from . import constants, geo, webhooks
|
|
22
|
+
from .async_client import AsyncClient
|
|
23
|
+
from .builders import AssociatedDocument, Item, Recipient
|
|
24
|
+
from .client import Client
|
|
25
|
+
from .constants import (
|
|
26
|
+
AssociatedDocumentType,
|
|
27
|
+
CarrierDocumentType,
|
|
28
|
+
ClientType,
|
|
29
|
+
Currency,
|
|
30
|
+
DocumentStatus,
|
|
31
|
+
DocumentType,
|
|
32
|
+
EntityType,
|
|
33
|
+
ErrorCode,
|
|
34
|
+
Event,
|
|
35
|
+
FreightResponsible,
|
|
36
|
+
Iva,
|
|
37
|
+
MeasureUnit,
|
|
38
|
+
Permission,
|
|
39
|
+
PrintedDocumentType,
|
|
40
|
+
ProviderDocumentType,
|
|
41
|
+
ProviderType,
|
|
42
|
+
ReceiptPaymentMethod,
|
|
43
|
+
RemissionReason,
|
|
44
|
+
RemissionResponsible,
|
|
45
|
+
SaleType,
|
|
46
|
+
TransactionType,
|
|
47
|
+
TransportMode,
|
|
48
|
+
TransportType,
|
|
49
|
+
VehicleIdentificationType,
|
|
50
|
+
is_error,
|
|
51
|
+
is_success,
|
|
52
|
+
is_terminal,
|
|
53
|
+
)
|
|
54
|
+
from .errors import (
|
|
55
|
+
APIError,
|
|
56
|
+
AuthenticationError,
|
|
57
|
+
ConfigurationError,
|
|
58
|
+
ConflictError,
|
|
59
|
+
NotFoundError,
|
|
60
|
+
PermissionError,
|
|
61
|
+
RateLimitError,
|
|
62
|
+
ServerError,
|
|
63
|
+
SignatureError,
|
|
64
|
+
SmartDocError,
|
|
65
|
+
TimeoutError,
|
|
66
|
+
ValidationError,
|
|
67
|
+
)
|
|
68
|
+
from .resources.auto_invoices import Provider
|
|
69
|
+
from .resources.receipts import ReceiptItem
|
|
70
|
+
from .resources.remission_notes import (
|
|
71
|
+
Carrier,
|
|
72
|
+
RemissionItem,
|
|
73
|
+
TransportEndpoint,
|
|
74
|
+
Vehicle,
|
|
75
|
+
)
|
|
76
|
+
from .webhooks import WebhookEvent, Webhooks
|
|
77
|
+
|
|
78
|
+
__version__ = "0.1.0"
|
|
79
|
+
|
|
80
|
+
__all__ = [
|
|
81
|
+
"__version__",
|
|
82
|
+
# Cliente
|
|
83
|
+
"Client",
|
|
84
|
+
"AsyncClient",
|
|
85
|
+
"Webhooks",
|
|
86
|
+
"WebhookEvent",
|
|
87
|
+
# Constructores
|
|
88
|
+
"Recipient",
|
|
89
|
+
"Item",
|
|
90
|
+
"AssociatedDocument",
|
|
91
|
+
"ReceiptItem",
|
|
92
|
+
"RemissionItem",
|
|
93
|
+
"TransportEndpoint",
|
|
94
|
+
"Vehicle",
|
|
95
|
+
"Carrier",
|
|
96
|
+
"Provider",
|
|
97
|
+
# Módulos
|
|
98
|
+
"constants",
|
|
99
|
+
"geo",
|
|
100
|
+
"webhooks",
|
|
101
|
+
# Catálogos de SmartDoc
|
|
102
|
+
"Iva",
|
|
103
|
+
"Currency",
|
|
104
|
+
"SaleType",
|
|
105
|
+
"ClientType",
|
|
106
|
+
"AssociatedDocumentType",
|
|
107
|
+
"DocumentType",
|
|
108
|
+
"ReceiptPaymentMethod",
|
|
109
|
+
"ProviderType",
|
|
110
|
+
"ProviderDocumentType",
|
|
111
|
+
# Catálogos de SIFEN
|
|
112
|
+
"TransactionType",
|
|
113
|
+
"MeasureUnit",
|
|
114
|
+
"RemissionReason",
|
|
115
|
+
"RemissionResponsible",
|
|
116
|
+
"TransportType",
|
|
117
|
+
"TransportMode",
|
|
118
|
+
"FreightResponsible",
|
|
119
|
+
"VehicleIdentificationType",
|
|
120
|
+
"PrintedDocumentType",
|
|
121
|
+
"CarrierDocumentType",
|
|
122
|
+
# Vocabulario de la API
|
|
123
|
+
"DocumentStatus",
|
|
124
|
+
"is_terminal",
|
|
125
|
+
"is_success",
|
|
126
|
+
"is_error",
|
|
127
|
+
"Event",
|
|
128
|
+
"EntityType",
|
|
129
|
+
"Permission",
|
|
130
|
+
"ErrorCode",
|
|
131
|
+
# Errores
|
|
132
|
+
"SmartDocError",
|
|
133
|
+
"APIError",
|
|
134
|
+
"AuthenticationError",
|
|
135
|
+
"PermissionError",
|
|
136
|
+
"NotFoundError",
|
|
137
|
+
"ValidationError",
|
|
138
|
+
"RateLimitError",
|
|
139
|
+
"ConflictError",
|
|
140
|
+
"ServerError",
|
|
141
|
+
"ConfigurationError",
|
|
142
|
+
"SignatureError",
|
|
143
|
+
"TimeoutError",
|
|
144
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Resolución de los datos del emisor, versión asíncrona.
|
|
2
|
+
|
|
3
|
+
Es el gemelo de :mod:`smartdoc._core.config`. Tiene que existir aparte porque las
|
|
4
|
+
consultas de descubrimiento son de red: todo lo demás —las reglas de cuándo se
|
|
5
|
+
descubre, cuándo se cachea y cuándo se falla por ambigüedad— se comparte a través
|
|
6
|
+
de las funciones auxiliares de aquel módulo.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ..errors import ConfigurationError
|
|
15
|
+
from .config import StampInfo, TaxPayerInfo, pick_only_one
|
|
16
|
+
|
|
17
|
+
__all__ = ["AsyncIssuerConfig"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class AsyncIssuerConfig:
|
|
22
|
+
"""Como :class:`~smartdoc._core.config.IssuerConfig`, pero con ``await``."""
|
|
23
|
+
|
|
24
|
+
_request: Any = field(repr=False)
|
|
25
|
+
stamp_identifier: str | None = None
|
|
26
|
+
stamp_begin_date: str | None = None
|
|
27
|
+
establishment: str | int | None = None
|
|
28
|
+
dispatch_point: str | int | None = None
|
|
29
|
+
auto_fill: bool = True
|
|
30
|
+
|
|
31
|
+
_taxpayer: TaxPayerInfo | None = field(default=None, init=False, repr=False)
|
|
32
|
+
_stamp: StampInfo | None = field(default=None, init=False, repr=False)
|
|
33
|
+
_discovered_establishment: str | None = field(default=None, init=False, repr=False)
|
|
34
|
+
_discovered_dispatch_points: dict[str, str] = field(
|
|
35
|
+
default_factory=dict, init=False, repr=False
|
|
36
|
+
)
|
|
37
|
+
_establishments: list[dict[str, Any]] | None = field(
|
|
38
|
+
default=None, init=False, repr=False
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
async def taxpayer(self) -> TaxPayerInfo:
|
|
42
|
+
"""El contribuyente, consultado una sola vez."""
|
|
43
|
+
if self._taxpayer is None:
|
|
44
|
+
result = await self._request("GET", "/taxpayer")
|
|
45
|
+
self._taxpayer = TaxPayerInfo.from_api(result.data)
|
|
46
|
+
return self._taxpayer
|
|
47
|
+
|
|
48
|
+
async def stamp(self) -> StampInfo:
|
|
49
|
+
"""El timbrado habilitado."""
|
|
50
|
+
if self._stamp is not None:
|
|
51
|
+
return self._stamp
|
|
52
|
+
|
|
53
|
+
if self.stamp_identifier and self.stamp_begin_date:
|
|
54
|
+
self._stamp = StampInfo(
|
|
55
|
+
id=0,
|
|
56
|
+
identifier=self.stamp_identifier,
|
|
57
|
+
begin_date=self.stamp_begin_date,
|
|
58
|
+
)
|
|
59
|
+
return self._stamp
|
|
60
|
+
|
|
61
|
+
enabled = [
|
|
62
|
+
StampInfo.from_api(s)
|
|
63
|
+
for s in await self._list("/stamps", {"enabled": "true", "limit": 100})
|
|
64
|
+
]
|
|
65
|
+
if self.stamp_identifier:
|
|
66
|
+
enabled = [s for s in enabled if s.identifier == self.stamp_identifier]
|
|
67
|
+
if not enabled:
|
|
68
|
+
raise ConfigurationError(
|
|
69
|
+
f"No encontré un timbrado habilitado con identificador "
|
|
70
|
+
f"{self.stamp_identifier!r}."
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
self._stamp = pick_only_one(
|
|
74
|
+
enabled,
|
|
75
|
+
what="timbrados habilitados",
|
|
76
|
+
how_to_pick="stamp=('12345678', '2024-01-01') al construir el cliente",
|
|
77
|
+
describe=lambda s: f"{s.identifier} (desde {s.begin_date})",
|
|
78
|
+
)
|
|
79
|
+
return self._stamp
|
|
80
|
+
|
|
81
|
+
async def establishment_code(self, override: str | int | None = None) -> str:
|
|
82
|
+
"""El código de establecimiento a usar.
|
|
83
|
+
|
|
84
|
+
Acepta el código (``"001"``) o el id interno de SmartDoc (``8``).
|
|
85
|
+
"""
|
|
86
|
+
chosen = override if override is not None else self.establishment
|
|
87
|
+
if chosen is not None:
|
|
88
|
+
return await self._as_establishment_code(chosen)
|
|
89
|
+
if self._discovered_establishment is None:
|
|
90
|
+
self._discovered_establishment = pick_only_one(
|
|
91
|
+
[e["code"] for e in await self.establishments()],
|
|
92
|
+
what="establecimientos",
|
|
93
|
+
how_to_pick=(
|
|
94
|
+
"establishment='001' al construir el cliente, o "
|
|
95
|
+
"establishment='001' en la llamada"
|
|
96
|
+
),
|
|
97
|
+
describe=str,
|
|
98
|
+
)
|
|
99
|
+
return self._discovered_establishment
|
|
100
|
+
|
|
101
|
+
async def establishments(self) -> list[dict[str, Any]]:
|
|
102
|
+
"""Los establecimientos, consultados una sola vez."""
|
|
103
|
+
if self._establishments is None:
|
|
104
|
+
self._establishments = await self._list("/establishments", {"limit": 100})
|
|
105
|
+
return self._establishments
|
|
106
|
+
|
|
107
|
+
async def dispatch_point_identifier(
|
|
108
|
+
self,
|
|
109
|
+
override: str | int | None = None,
|
|
110
|
+
*,
|
|
111
|
+
establishment_code: str | None = None,
|
|
112
|
+
) -> str:
|
|
113
|
+
"""El punto de expedición a usar, dentro de un establecimiento.
|
|
114
|
+
|
|
115
|
+
Se filtra por establecimiento porque un mismo identificador suele existir
|
|
116
|
+
bajo varios, y el par equivocado produce un documento inválido.
|
|
117
|
+
"""
|
|
118
|
+
chosen = override if override is not None else self.dispatch_point
|
|
119
|
+
if chosen is not None:
|
|
120
|
+
return await self._as_dispatch_point_identifier(chosen, establishment_code)
|
|
121
|
+
|
|
122
|
+
key = establishment_code or ""
|
|
123
|
+
if key not in self._discovered_dispatch_points:
|
|
124
|
+
self._discovered_dispatch_points[key] = pick_only_one(
|
|
125
|
+
await self._dispatch_points_of(establishment_code),
|
|
126
|
+
what=(
|
|
127
|
+
f"puntos de expedición en el establecimiento {establishment_code}"
|
|
128
|
+
if establishment_code
|
|
129
|
+
else "puntos de expedición"
|
|
130
|
+
),
|
|
131
|
+
how_to_pick=(
|
|
132
|
+
"dispatch_point='001' al construir el cliente, o "
|
|
133
|
+
"dispatch_point='001' en la llamada"
|
|
134
|
+
),
|
|
135
|
+
describe=str,
|
|
136
|
+
)
|
|
137
|
+
return self._discovered_dispatch_points[key]
|
|
138
|
+
|
|
139
|
+
async def _dispatch_points_of(self, establishment_code: str | None) -> list[str]:
|
|
140
|
+
"""Identificadores de los puntos de expedición de un establecimiento.
|
|
141
|
+
|
|
142
|
+
Se filtra del lado del servidor con ``?establishmentId=``. Si no se puede
|
|
143
|
+
resolver el id, se listan todos: es preferible levantar una ambigüedad a
|
|
144
|
+
filtrar por el criterio equivocado.
|
|
145
|
+
"""
|
|
146
|
+
params: dict[str, Any] = {"limit": 100}
|
|
147
|
+
establishment_id = await self._establishment_id(establishment_code)
|
|
148
|
+
if establishment_id is not None:
|
|
149
|
+
params["establishmentId"] = establishment_id
|
|
150
|
+
|
|
151
|
+
return [p["identifier"] for p in await self._list("/dispatch_points", params)]
|
|
152
|
+
|
|
153
|
+
async def _as_establishment_code(self, value: str | int) -> str:
|
|
154
|
+
"""Normaliza un establecimiento dado por código o por id interno."""
|
|
155
|
+
if not isinstance(value, int):
|
|
156
|
+
return str(value)
|
|
157
|
+
establishments = await self.establishments()
|
|
158
|
+
for e in establishments:
|
|
159
|
+
if e.get("id") == value:
|
|
160
|
+
return str(e["code"])
|
|
161
|
+
raise ConfigurationError(
|
|
162
|
+
f"No hay un establecimiento con id {value}.",
|
|
163
|
+
options=[f"{e.get('id')} → {e.get('code')}" for e in establishments],
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
async def _as_dispatch_point_identifier(
|
|
167
|
+
self, value: str | int, establishment_code: str | None
|
|
168
|
+
) -> str:
|
|
169
|
+
"""Normaliza un punto de expedición dado por identificador o por id."""
|
|
170
|
+
if not isinstance(value, int):
|
|
171
|
+
return str(value)
|
|
172
|
+
|
|
173
|
+
params: dict[str, Any] = {"limit": 100}
|
|
174
|
+
establishment_id = await self._establishment_id(establishment_code)
|
|
175
|
+
if establishment_id is not None:
|
|
176
|
+
params["establishmentId"] = establishment_id
|
|
177
|
+
|
|
178
|
+
points = await self._list("/dispatch_points", params)
|
|
179
|
+
for d in points:
|
|
180
|
+
if d.get("id") == value:
|
|
181
|
+
return str(d["identifier"])
|
|
182
|
+
raise ConfigurationError(
|
|
183
|
+
f"No hay un punto de expedición con id {value}"
|
|
184
|
+
+ (
|
|
185
|
+
f" en el establecimiento {establishment_code}."
|
|
186
|
+
if establishment_code
|
|
187
|
+
else "."
|
|
188
|
+
),
|
|
189
|
+
options=[f"{d.get('id')} → {d.get('identifier')}" for d in points],
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
async def _establishment_id(self, code: str | None) -> int | None:
|
|
193
|
+
"""El id interno del establecimiento con ese código."""
|
|
194
|
+
if code is None:
|
|
195
|
+
return None
|
|
196
|
+
for e in await self.establishments():
|
|
197
|
+
if e.get("code") == code:
|
|
198
|
+
found: int | None = e.get("id")
|
|
199
|
+
return found
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
async def document_base(
|
|
203
|
+
self,
|
|
204
|
+
*,
|
|
205
|
+
establishment: str | None = None,
|
|
206
|
+
dispatch_point: str | None = None,
|
|
207
|
+
overrides: dict[str, Any] | None = None,
|
|
208
|
+
) -> dict[str, Any]:
|
|
209
|
+
"""Los siete campos comunes a todo documento."""
|
|
210
|
+
overrides = {k: v for k, v in (overrides or {}).items() if v is not None}
|
|
211
|
+
if not self.auto_fill:
|
|
212
|
+
return overrides
|
|
213
|
+
|
|
214
|
+
base: dict[str, Any] = {}
|
|
215
|
+
|
|
216
|
+
if not {"taxPayerRuc", "taxPayerSocialName", "taxPayerFantasyName"} <= set(
|
|
217
|
+
overrides
|
|
218
|
+
):
|
|
219
|
+
taxpayer = await self.taxpayer()
|
|
220
|
+
base["taxPayerRuc"] = taxpayer.ruc
|
|
221
|
+
base["taxPayerSocialName"] = taxpayer.social_name
|
|
222
|
+
base["taxPayerFantasyName"] = taxpayer.fantasy_name
|
|
223
|
+
|
|
224
|
+
if not {"stampIdentifier", "stampBeginDate"} <= set(overrides):
|
|
225
|
+
stamp = await self.stamp()
|
|
226
|
+
base["stampIdentifier"] = stamp.identifier
|
|
227
|
+
base["stampBeginDate"] = stamp.begin_date
|
|
228
|
+
|
|
229
|
+
# El establecimiento se resuelve primero: el punto se filtra por él.
|
|
230
|
+
code = overrides.get("establishmentCode") or await self.establishment_code(
|
|
231
|
+
establishment
|
|
232
|
+
)
|
|
233
|
+
if "establishmentCode" not in overrides:
|
|
234
|
+
base["establishmentCode"] = code
|
|
235
|
+
if "dispatchPointIdentifier" not in overrides:
|
|
236
|
+
base["dispatchPointIdentifier"] = await self.dispatch_point_identifier(
|
|
237
|
+
dispatch_point, establishment_code=code
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
base.update(overrides)
|
|
241
|
+
return base
|
|
242
|
+
|
|
243
|
+
def refresh(self) -> None:
|
|
244
|
+
"""Olvida lo descubierto."""
|
|
245
|
+
self._taxpayer = None
|
|
246
|
+
self._stamp = None
|
|
247
|
+
self._discovered_establishment = None
|
|
248
|
+
self._discovered_dispatch_points.clear()
|
|
249
|
+
self._establishments = None
|
|
250
|
+
|
|
251
|
+
async def _list(self, path: str, params: dict[str, Any]) -> list[dict[str, Any]]:
|
|
252
|
+
result = await self._request("GET", path, params=params)
|
|
253
|
+
data = result.data or []
|
|
254
|
+
return list(data) if isinstance(data, list) else []
|