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/_core/config.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
"""Resolución de los datos del emisor.
|
|
2
|
+
|
|
3
|
+
Todo documento electrónico lleva siete campos que no cambian entre uno y otro y
|
|
4
|
+
que el integrador no debería tener que repetir::
|
|
5
|
+
|
|
6
|
+
taxPayerRuc, taxPayerSocialName, taxPayerFantasyName,
|
|
7
|
+
stampIdentifier, stampBeginDate,
|
|
8
|
+
establishmentCode, dispatchPointIdentifier
|
|
9
|
+
|
|
10
|
+
Los cinco primeros salen de ``GET /taxpayer`` y ``GET /stamps``, se descubren la
|
|
11
|
+
primera vez que hacen falta y quedan en memoria: el contribuyente y su timbrado
|
|
12
|
+
no cambian mientras el proceso vive.
|
|
13
|
+
|
|
14
|
+
Los dos últimos son distintos. Un contribuyente puede tener varios
|
|
15
|
+
establecimientos y varios puntos de expedición, y cuál se usa **cambia de un
|
|
16
|
+
documento a otro** —es lo que identifica la sucursal o la caja que emitió—. Por
|
|
17
|
+
eso se pueden pasar por llamada, o fijar un default al construir el cliente. Se
|
|
18
|
+
descubren solos únicamente cuando hay exactamente uno, que es el caso del
|
|
19
|
+
contribuyente chico.
|
|
20
|
+
|
|
21
|
+
Cuando hay más de uno y no se dijo cuál, el SDK **falla** en vez de elegir: el
|
|
22
|
+
código elegido queda impreso en el documento y en su CDC, y equivocarlo obliga a
|
|
23
|
+
anular y reemitir.
|
|
24
|
+
|
|
25
|
+
Los puntos de expedición **pertenecen a un establecimiento**, así que el
|
|
26
|
+
descubrimiento los filtra por el establecimiento en uso. Sin ese filtro se puede
|
|
27
|
+
armar un par inválido: el identificador ``001`` suele existir bajo más de un
|
|
28
|
+
establecimiento.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
from dataclasses import dataclass, field
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
from ..errors import ConfigurationError
|
|
37
|
+
|
|
38
|
+
__all__ = ["IssuerConfig", "TaxPayerInfo", "StampInfo", "pick_only_one"]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class TaxPayerInfo:
|
|
43
|
+
"""El contribuyente dueño de la API Key."""
|
|
44
|
+
|
|
45
|
+
id: int
|
|
46
|
+
ruc: str
|
|
47
|
+
social_name: str
|
|
48
|
+
fantasy_name: str
|
|
49
|
+
is_demo: bool = False
|
|
50
|
+
is_active: bool = True
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
def from_api(cls, data: dict[str, Any]) -> TaxPayerInfo:
|
|
54
|
+
return cls(
|
|
55
|
+
id=data["id"],
|
|
56
|
+
ruc=data["ruc"],
|
|
57
|
+
social_name=data.get("socialName", ""),
|
|
58
|
+
fantasy_name=data.get("fantasyName", ""),
|
|
59
|
+
is_demo=bool(data.get("isDemo")),
|
|
60
|
+
is_active=bool(data.get("isActive", True)),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class StampInfo:
|
|
66
|
+
"""Un timbrado."""
|
|
67
|
+
|
|
68
|
+
id: int
|
|
69
|
+
identifier: str
|
|
70
|
+
begin_date: str
|
|
71
|
+
enabled: bool = True
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
def from_api(cls, data: dict[str, Any]) -> StampInfo:
|
|
75
|
+
return cls(
|
|
76
|
+
id=data["id"],
|
|
77
|
+
identifier=data["identifier"],
|
|
78
|
+
begin_date=str(data.get("beginDate", ""))[:10],
|
|
79
|
+
enabled=bool(data.get("enabled", True)),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass
|
|
84
|
+
class IssuerConfig:
|
|
85
|
+
"""Descubre y cachea los datos del emisor.
|
|
86
|
+
|
|
87
|
+
Todo lo que se pase explícitamente gana sobre lo descubierto, y nada sale a
|
|
88
|
+
la red hasta que hace falta: un cliente que solo lee documentos nunca
|
|
89
|
+
consulta el timbrado.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
_request: Any = field(repr=False)
|
|
93
|
+
stamp_identifier: str | None = None
|
|
94
|
+
stamp_begin_date: str | None = None
|
|
95
|
+
establishment: str | int | None = None
|
|
96
|
+
dispatch_point: str | int | None = None
|
|
97
|
+
auto_fill: bool = True
|
|
98
|
+
|
|
99
|
+
_taxpayer: TaxPayerInfo | None = field(default=None, init=False, repr=False)
|
|
100
|
+
_stamp: StampInfo | None = field(default=None, init=False, repr=False)
|
|
101
|
+
_discovered_establishment: str | None = field(default=None, init=False, repr=False)
|
|
102
|
+
_discovered_dispatch_points: dict[str, str] = field(
|
|
103
|
+
default_factory=dict, init=False, repr=False
|
|
104
|
+
)
|
|
105
|
+
_establishments: list[dict[str, Any]] | None = field(
|
|
106
|
+
default=None, init=False, repr=False
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
# ─── Descubrimiento ──────────────────────────────────────────────────────
|
|
110
|
+
|
|
111
|
+
def taxpayer(self) -> TaxPayerInfo:
|
|
112
|
+
"""El contribuyente, consultado una sola vez."""
|
|
113
|
+
if self._taxpayer is None:
|
|
114
|
+
result = self._request("GET", "/taxpayer")
|
|
115
|
+
self._taxpayer = TaxPayerInfo.from_api(result.data)
|
|
116
|
+
return self._taxpayer
|
|
117
|
+
|
|
118
|
+
def stamp(self) -> StampInfo:
|
|
119
|
+
"""El timbrado habilitado.
|
|
120
|
+
|
|
121
|
+
Si hay más de uno habilitado, hay que decir cuál con ``stamp=`` en el
|
|
122
|
+
cliente: el timbrado forma parte del CDC del documento.
|
|
123
|
+
"""
|
|
124
|
+
if self._stamp is not None:
|
|
125
|
+
return self._stamp
|
|
126
|
+
|
|
127
|
+
if self.stamp_identifier and self.stamp_begin_date:
|
|
128
|
+
self._stamp = StampInfo(
|
|
129
|
+
id=0,
|
|
130
|
+
identifier=self.stamp_identifier,
|
|
131
|
+
begin_date=self.stamp_begin_date,
|
|
132
|
+
)
|
|
133
|
+
return self._stamp
|
|
134
|
+
|
|
135
|
+
enabled = [
|
|
136
|
+
StampInfo.from_api(s)
|
|
137
|
+
for s in self._list("/stamps", {"enabled": "true", "limit": 100})
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
if self.stamp_identifier:
|
|
141
|
+
enabled = [s for s in enabled if s.identifier == self.stamp_identifier]
|
|
142
|
+
if not enabled:
|
|
143
|
+
raise ConfigurationError(
|
|
144
|
+
f"No encontré un timbrado habilitado con identificador "
|
|
145
|
+
f"{self.stamp_identifier!r}."
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
self._stamp = pick_only_one(
|
|
149
|
+
enabled,
|
|
150
|
+
what="timbrados habilitados",
|
|
151
|
+
how_to_pick="stamp=('12345678', '2024-01-01') al construir el cliente",
|
|
152
|
+
describe=lambda s: f"{s.identifier} (desde {s.begin_date})",
|
|
153
|
+
)
|
|
154
|
+
return self._stamp
|
|
155
|
+
|
|
156
|
+
def establishments(self) -> list[dict[str, Any]]:
|
|
157
|
+
"""Los establecimientos, consultados una sola vez."""
|
|
158
|
+
if self._establishments is None:
|
|
159
|
+
self._establishments = self._list("/establishments", {"limit": 100})
|
|
160
|
+
return self._establishments
|
|
161
|
+
|
|
162
|
+
def establishment_code(self, override: str | int | None = None) -> str:
|
|
163
|
+
"""El código de establecimiento a usar.
|
|
164
|
+
|
|
165
|
+
Acepta el código impreso en el documento (``"001"``) o el id interno de
|
|
166
|
+
SmartDoc (``8``). El id se resuelve a código consultando la lista de
|
|
167
|
+
establecimientos, que queda cacheada.
|
|
168
|
+
"""
|
|
169
|
+
chosen = override if override is not None else self.establishment
|
|
170
|
+
if chosen is not None:
|
|
171
|
+
return self._as_establishment_code(chosen)
|
|
172
|
+
if self._discovered_establishment is None:
|
|
173
|
+
self._discovered_establishment = pick_only_one(
|
|
174
|
+
[e["code"] for e in self.establishments()],
|
|
175
|
+
what="establecimientos",
|
|
176
|
+
how_to_pick=(
|
|
177
|
+
"establishment='001' al construir el cliente, o "
|
|
178
|
+
"establishment='001' en la llamada"
|
|
179
|
+
),
|
|
180
|
+
describe=str,
|
|
181
|
+
)
|
|
182
|
+
return self._discovered_establishment
|
|
183
|
+
|
|
184
|
+
def dispatch_point_identifier(
|
|
185
|
+
self,
|
|
186
|
+
override: str | int | None = None,
|
|
187
|
+
*,
|
|
188
|
+
establishment_code: str | None = None,
|
|
189
|
+
) -> str:
|
|
190
|
+
"""El punto de expedición a usar, dentro de un establecimiento.
|
|
191
|
+
|
|
192
|
+
Como en el establecimiento, acepta el identificador (``"001"``) o el id
|
|
193
|
+
interno (``14``).
|
|
194
|
+
|
|
195
|
+
El filtrado por establecimiento no es cosmético: un mismo identificador
|
|
196
|
+
—``001`` es el caso típico— suele existir bajo varios establecimientos, y
|
|
197
|
+
combinarlo con el establecimiento equivocado produce un documento
|
|
198
|
+
inválido.
|
|
199
|
+
"""
|
|
200
|
+
chosen = override if override is not None else self.dispatch_point
|
|
201
|
+
if chosen is not None:
|
|
202
|
+
return self._as_dispatch_point_identifier(chosen, establishment_code)
|
|
203
|
+
|
|
204
|
+
key = establishment_code or ""
|
|
205
|
+
if key not in self._discovered_dispatch_points:
|
|
206
|
+
self._discovered_dispatch_points[key] = pick_only_one(
|
|
207
|
+
self._dispatch_points_of(establishment_code),
|
|
208
|
+
what=(
|
|
209
|
+
f"puntos de expedición en el establecimiento {establishment_code}"
|
|
210
|
+
if establishment_code
|
|
211
|
+
else "puntos de expedición"
|
|
212
|
+
),
|
|
213
|
+
how_to_pick=(
|
|
214
|
+
"dispatch_point='001' al construir el cliente, o "
|
|
215
|
+
"dispatch_point='001' en la llamada"
|
|
216
|
+
),
|
|
217
|
+
describe=str,
|
|
218
|
+
)
|
|
219
|
+
return self._discovered_dispatch_points[key]
|
|
220
|
+
|
|
221
|
+
def _dispatch_points_of(self, establishment_code: str | None) -> list[str]:
|
|
222
|
+
"""Identificadores de los puntos de expedición de un establecimiento.
|
|
223
|
+
|
|
224
|
+
Se filtra del lado del servidor con ``?establishmentId=``. Si no se puede
|
|
225
|
+
resolver el id del establecimiento, se listan todos: es preferible
|
|
226
|
+
levantar una ambigüedad a filtrar por el criterio equivocado.
|
|
227
|
+
"""
|
|
228
|
+
params: dict[str, Any] = {"limit": 100}
|
|
229
|
+
establishment_id = self._establishment_id(establishment_code)
|
|
230
|
+
if establishment_id is not None:
|
|
231
|
+
params["establishmentId"] = establishment_id
|
|
232
|
+
|
|
233
|
+
return [p["identifier"] for p in self._list("/dispatch_points", params)]
|
|
234
|
+
|
|
235
|
+
def _as_establishment_code(self, value: str | int) -> str:
|
|
236
|
+
"""Normaliza un establecimiento dado por código o por id interno."""
|
|
237
|
+
if not isinstance(value, int):
|
|
238
|
+
return str(value)
|
|
239
|
+
for e in self.establishments():
|
|
240
|
+
if e.get("id") == value:
|
|
241
|
+
return str(e["code"])
|
|
242
|
+
raise ConfigurationError(
|
|
243
|
+
f"No hay un establecimiento con id {value}.",
|
|
244
|
+
options=[f"{e.get('id')} → {e.get('code')}" for e in self.establishments()],
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
def _as_dispatch_point_identifier(
|
|
248
|
+
self, value: str | int, establishment_code: str | None
|
|
249
|
+
) -> str:
|
|
250
|
+
"""Normaliza un punto de expedición dado por identificador o por id."""
|
|
251
|
+
if not isinstance(value, int):
|
|
252
|
+
return str(value)
|
|
253
|
+
|
|
254
|
+
params: dict[str, Any] = {"limit": 100}
|
|
255
|
+
establishment_id = self._establishment_id(establishment_code)
|
|
256
|
+
if establishment_id is not None:
|
|
257
|
+
params["establishmentId"] = establishment_id
|
|
258
|
+
|
|
259
|
+
points = self._list("/dispatch_points", params)
|
|
260
|
+
for d in points:
|
|
261
|
+
if d.get("id") == value:
|
|
262
|
+
return str(d["identifier"])
|
|
263
|
+
raise ConfigurationError(
|
|
264
|
+
f"No hay un punto de expedición con id {value}"
|
|
265
|
+
+ (
|
|
266
|
+
f" en el establecimiento {establishment_code}."
|
|
267
|
+
if establishment_code
|
|
268
|
+
else "."
|
|
269
|
+
),
|
|
270
|
+
options=[f"{d.get('id')} → {d.get('identifier')}" for d in points],
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
def _establishment_id(self, code: str | None) -> int | None:
|
|
274
|
+
"""El id interno del establecimiento con ese código."""
|
|
275
|
+
if code is None:
|
|
276
|
+
return None
|
|
277
|
+
for e in self.establishments():
|
|
278
|
+
if e.get("code") == code:
|
|
279
|
+
found: int | None = e.get("id")
|
|
280
|
+
return found
|
|
281
|
+
return None
|
|
282
|
+
|
|
283
|
+
# ─── Uso ─────────────────────────────────────────────────────────────────
|
|
284
|
+
|
|
285
|
+
def document_base(
|
|
286
|
+
self,
|
|
287
|
+
*,
|
|
288
|
+
establishment: str | None = None,
|
|
289
|
+
dispatch_point: str | None = None,
|
|
290
|
+
overrides: dict[str, Any] | None = None,
|
|
291
|
+
) -> dict[str, Any]:
|
|
292
|
+
"""Los siete campos comunes a todo documento.
|
|
293
|
+
|
|
294
|
+
Lo que venga en ``overrides`` con valor distinto de ``None`` gana y evita
|
|
295
|
+
la consulta correspondiente.
|
|
296
|
+
"""
|
|
297
|
+
overrides = {k: v for k, v in (overrides or {}).items() if v is not None}
|
|
298
|
+
if not self.auto_fill:
|
|
299
|
+
return overrides
|
|
300
|
+
|
|
301
|
+
base: dict[str, Any] = {}
|
|
302
|
+
|
|
303
|
+
if not {"taxPayerRuc", "taxPayerSocialName", "taxPayerFantasyName"} <= set(
|
|
304
|
+
overrides
|
|
305
|
+
):
|
|
306
|
+
taxpayer = self.taxpayer()
|
|
307
|
+
base["taxPayerRuc"] = taxpayer.ruc
|
|
308
|
+
base["taxPayerSocialName"] = taxpayer.social_name
|
|
309
|
+
base["taxPayerFantasyName"] = taxpayer.fantasy_name
|
|
310
|
+
|
|
311
|
+
if not {"stampIdentifier", "stampBeginDate"} <= set(overrides):
|
|
312
|
+
stamp = self.stamp()
|
|
313
|
+
base["stampIdentifier"] = stamp.identifier
|
|
314
|
+
base["stampBeginDate"] = stamp.begin_date
|
|
315
|
+
|
|
316
|
+
# El establecimiento se resuelve primero: el punto de expedición se
|
|
317
|
+
# filtra por él.
|
|
318
|
+
code = overrides.get("establishmentCode") or self.establishment_code(
|
|
319
|
+
establishment
|
|
320
|
+
)
|
|
321
|
+
if "establishmentCode" not in overrides:
|
|
322
|
+
base["establishmentCode"] = code
|
|
323
|
+
if "dispatchPointIdentifier" not in overrides:
|
|
324
|
+
base["dispatchPointIdentifier"] = self.dispatch_point_identifier(
|
|
325
|
+
dispatch_point, establishment_code=code
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
base.update(overrides)
|
|
329
|
+
return base
|
|
330
|
+
|
|
331
|
+
def refresh(self) -> None:
|
|
332
|
+
"""Olvida lo descubierto. Útil si se cargó un timbrado nuevo."""
|
|
333
|
+
self._taxpayer = None
|
|
334
|
+
self._stamp = None
|
|
335
|
+
self._discovered_establishment = None
|
|
336
|
+
self._discovered_dispatch_points.clear()
|
|
337
|
+
self._establishments = None
|
|
338
|
+
|
|
339
|
+
def _list(self, path: str, params: dict[str, Any]) -> list[dict[str, Any]]:
|
|
340
|
+
result = self._request("GET", path, params=params)
|
|
341
|
+
data = result.data or []
|
|
342
|
+
return list(data) if isinstance(data, list) else []
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def pick_only_one(
|
|
346
|
+
options: list[Any],
|
|
347
|
+
*,
|
|
348
|
+
what: str,
|
|
349
|
+
how_to_pick: str,
|
|
350
|
+
describe: Any,
|
|
351
|
+
) -> Any:
|
|
352
|
+
"""Devuelve la única opción, o falla explicando cómo desempatar.
|
|
353
|
+
|
|
354
|
+
Vive fuera de la clase porque la comparte la versión asíncrona: la regla
|
|
355
|
+
—nunca elegir en silencio— tiene que ser la misma en las dos.
|
|
356
|
+
"""
|
|
357
|
+
if not options:
|
|
358
|
+
raise ConfigurationError(
|
|
359
|
+
f"El contribuyente no tiene {what}. Hay que configurarlos en el "
|
|
360
|
+
f"panel de SmartDoc antes de emitir."
|
|
361
|
+
)
|
|
362
|
+
if len(options) > 1:
|
|
363
|
+
raise ConfigurationError(
|
|
364
|
+
f"El contribuyente tiene {len(options)} {what} y no se indicó "
|
|
365
|
+
f"cuál usar. Elegilo con {how_to_pick}.",
|
|
366
|
+
options=[describe(o) for o in options],
|
|
367
|
+
)
|
|
368
|
+
return options[0]
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Paginación por cursor.
|
|
2
|
+
|
|
3
|
+
Los listados devuelven ``pagination.nextCursor``, un cursor opaco que hay que
|
|
4
|
+
mandar como parámetro ``cursor`` para pedir la página siguiente. El tamaño por
|
|
5
|
+
defecto es 20 y el máximo 100.
|
|
6
|
+
|
|
7
|
+
:class:`Page` es la página que devolvió la API, y se recorre como una lista.
|
|
8
|
+
Para recorrer *todo* sin escribir el bucle del cursor está
|
|
9
|
+
:meth:`Page.auto_paging_iter`, que respeta el regulador de tasa del transporte.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import Callable, Iterator
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any, Generic, TypeVar
|
|
17
|
+
|
|
18
|
+
__all__ = ["Page", "AsyncPage"]
|
|
19
|
+
|
|
20
|
+
T = TypeVar("T")
|
|
21
|
+
|
|
22
|
+
#: Lo que acepta la API. Pedir más de 100 no falla, pero se recorta en silencio.
|
|
23
|
+
MAX_PAGE_SIZE = 100
|
|
24
|
+
DEFAULT_PAGE_SIZE = 20
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Page(Generic[T]):
|
|
29
|
+
"""Una página de resultados.
|
|
30
|
+
|
|
31
|
+
Se comporta como una secuencia: ``len(page)``, ``page[0]``, ``for x in page``
|
|
32
|
+
recorren **solo esta página**. Para recorrer todas, usar
|
|
33
|
+
:meth:`auto_paging_iter`.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
items: list[T]
|
|
37
|
+
next_cursor: str | None = None
|
|
38
|
+
has_more: bool = False
|
|
39
|
+
limit: int = DEFAULT_PAGE_SIZE
|
|
40
|
+
#: Cómo pedir la página siguiente. Lo inyecta el recurso.
|
|
41
|
+
_fetch_next: Callable[[str], Page[T]] | None = field(
|
|
42
|
+
default=None, repr=False, compare=False
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def __iter__(self) -> Iterator[T]:
|
|
46
|
+
return iter(self.items)
|
|
47
|
+
|
|
48
|
+
def __len__(self) -> int:
|
|
49
|
+
return len(self.items)
|
|
50
|
+
|
|
51
|
+
def __getitem__(self, index: int) -> T:
|
|
52
|
+
return self.items[index]
|
|
53
|
+
|
|
54
|
+
def __bool__(self) -> bool:
|
|
55
|
+
return bool(self.items)
|
|
56
|
+
|
|
57
|
+
def next_page(self) -> Page[T] | None:
|
|
58
|
+
"""La página siguiente, o ``None`` si esta era la última."""
|
|
59
|
+
if not self.has_more or not self.next_cursor or self._fetch_next is None:
|
|
60
|
+
return None
|
|
61
|
+
return self._fetch_next(self.next_cursor)
|
|
62
|
+
|
|
63
|
+
def auto_paging_iter(self) -> Iterator[T]:
|
|
64
|
+
"""Recorre todos los resultados, siguiendo el cursor solo.
|
|
65
|
+
|
|
66
|
+
El transporte regula a 5 solicitudes por segundo, así que recorrer un
|
|
67
|
+
listado largo es lento pero no dispara 429.
|
|
68
|
+
"""
|
|
69
|
+
pagina: Page[T] | None = self
|
|
70
|
+
while pagina is not None:
|
|
71
|
+
yield from pagina.items
|
|
72
|
+
pagina = pagina.next_page()
|
|
73
|
+
|
|
74
|
+
@classmethod
|
|
75
|
+
def from_result(
|
|
76
|
+
cls,
|
|
77
|
+
items: list[T],
|
|
78
|
+
pagination: dict[str, Any] | None,
|
|
79
|
+
fetch_next: Callable[[str], Page[T]] | None = None,
|
|
80
|
+
) -> Page[T]:
|
|
81
|
+
pagination = pagination or {}
|
|
82
|
+
return cls(
|
|
83
|
+
items=items,
|
|
84
|
+
next_cursor=pagination.get("nextCursor"),
|
|
85
|
+
has_more=bool(pagination.get("hasMore")),
|
|
86
|
+
limit=pagination.get("limit", DEFAULT_PAGE_SIZE),
|
|
87
|
+
_fetch_next=fetch_next,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass
|
|
92
|
+
class AsyncPage(Generic[T]):
|
|
93
|
+
"""Igual que :class:`Page`, para el cliente asíncrono."""
|
|
94
|
+
|
|
95
|
+
items: list[T]
|
|
96
|
+
next_cursor: str | None = None
|
|
97
|
+
has_more: bool = False
|
|
98
|
+
limit: int = DEFAULT_PAGE_SIZE
|
|
99
|
+
_fetch_next: Callable[[str], Any] | None = field(
|
|
100
|
+
default=None, repr=False, compare=False
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def __iter__(self) -> Iterator[T]:
|
|
104
|
+
return iter(self.items)
|
|
105
|
+
|
|
106
|
+
def __len__(self) -> int:
|
|
107
|
+
return len(self.items)
|
|
108
|
+
|
|
109
|
+
def __getitem__(self, index: int) -> T:
|
|
110
|
+
return self.items[index]
|
|
111
|
+
|
|
112
|
+
def __bool__(self) -> bool:
|
|
113
|
+
return bool(self.items)
|
|
114
|
+
|
|
115
|
+
async def next_page(self) -> AsyncPage[T] | None:
|
|
116
|
+
"""La página siguiente, o ``None`` si esta era la última."""
|
|
117
|
+
if not self.has_more or not self.next_cursor or self._fetch_next is None:
|
|
118
|
+
return None
|
|
119
|
+
result: AsyncPage[T] = await self._fetch_next(self.next_cursor)
|
|
120
|
+
return result
|
|
121
|
+
|
|
122
|
+
async def auto_paging_iter(self) -> Any:
|
|
123
|
+
"""Recorre todos los resultados. Se usa con ``async for``."""
|
|
124
|
+
pagina: AsyncPage[T] | None = self
|
|
125
|
+
while pagina is not None:
|
|
126
|
+
for item in pagina.items:
|
|
127
|
+
yield item
|
|
128
|
+
pagina = await pagina.next_page()
|
|
129
|
+
|
|
130
|
+
@classmethod
|
|
131
|
+
def from_result(
|
|
132
|
+
cls,
|
|
133
|
+
items: list[T],
|
|
134
|
+
pagination: dict[str, Any] | None,
|
|
135
|
+
fetch_next: Callable[[str], Any] | None = None,
|
|
136
|
+
) -> AsyncPage[T]:
|
|
137
|
+
pagination = pagination or {}
|
|
138
|
+
return cls(
|
|
139
|
+
items=items,
|
|
140
|
+
next_cursor=pagination.get("nextCursor"),
|
|
141
|
+
has_more=bool(pagination.get("hasMore")),
|
|
142
|
+
limit=pagination.get("limit", DEFAULT_PAGE_SIZE),
|
|
143
|
+
_fetch_next=fetch_next,
|
|
144
|
+
)
|