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
@@ -0,0 +1,379 @@
1
+ """Capa HTTP: autenticación, reintentos, idempotencia y traducción de errores.
2
+
3
+ Los recursos se escriben una sola vez contra el protocolo :class:`Transport`, y
4
+ después ``Client`` inyecta la versión síncrona y ``AsyncClient`` la asíncrona.
5
+ Por eso acá vive todo lo que depende de httpx y nada más lo toca.
6
+
7
+ Tres cosas que la API obliga a manejar y conviene que el integrador no vea:
8
+
9
+ * **``Idempotency-Key`` es obligatorio** al crear documentos. Si falta, la API
10
+ responde 400. El SDK genera un UUID por llamada, salvo que se pase uno.
11
+ * **El límite es de 5 solicitudes por segundo** y la respuesta 429 **no trae**
12
+ ``Retry-After``, así que el backoff lo tiene que inventar el cliente. Además
13
+ de reintentar, el SDK regula de forma preventiva para no llegar al 429.
14
+ * **Los errores vienen como ``{"status": "error", "code": ..., "message": ...}``**
15
+ y hay que traducirlos a excepciones tipadas.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import random
21
+ import threading
22
+ import time
23
+ import uuid
24
+ from dataclasses import dataclass, field
25
+ from typing import Any, Protocol
26
+
27
+ import httpx
28
+
29
+ from ..errors import (
30
+ APIError,
31
+ AuthenticationError,
32
+ ConflictError,
33
+ NotFoundError,
34
+ PermissionError,
35
+ RateLimitError,
36
+ ServerError,
37
+ ValidationError,
38
+ )
39
+
40
+ __all__ = ["Transport", "SyncTransport", "AsyncTransport", "Result", "RetryPolicy"]
41
+
42
+ #: La instancia de producción de SmartDoc. Solo hace falta indicar otra si el
43
+ #: contribuyente está en una instancia propia.
44
+ DEFAULT_BASE_URL = "https://api.smartdoc.araitek.com/api/v2"
45
+
46
+ #: Códigos HTTP que vale la pena reintentar. El 429 porque el límite es por
47
+ #: segundo y se libera solo; los 5xx porque suelen ser transitorios.
48
+ _RETRYABLE = frozenset({429, 500, 502, 503, 504})
49
+
50
+ #: Cuánto se estira el espaciado por encima del mínimo teórico.
51
+ #:
52
+ #: El servidor no cuenta con una ventana deslizante sino con una **fija** de un
53
+ #: segundo (``INCR`` y ``EXPIRE 1`` sobre Redis). Con solicitudes espaciadas
54
+ #: exactamente ``1/N`` caben ``N + 1`` en una misma ventana —las de los
55
+ #: instantes ``0, 1/N, …, 1``—, así que apuntar justo al límite garantiza el
56
+ #: 429 en vez de evitarlo. Con este margen entran ``N`` como mucho, y sobra
57
+ #: lugar para el jitter de la red y del planificador del sistema operativo.
58
+ _RATE_LIMIT_MARGIN = 1.2
59
+
60
+
61
+ @dataclass
62
+ class Result:
63
+ """Respuesta ya desenvuelta de la API.
64
+
65
+ La API siempre responde ``{"status": ..., "data": ...}``; acá queda el
66
+ contenido de ``data``, más la paginación si vino.
67
+ """
68
+
69
+ data: Any
70
+ pagination: dict[str, Any] | None = None
71
+ status_code: int = 200
72
+
73
+
74
+ @dataclass
75
+ class RetryPolicy:
76
+ """Cuántas veces reintentar y cuánto esperar entre intentos."""
77
+
78
+ max_retries: int = 3
79
+ #: Espera base en segundos. Las esperas son base * 2**intento, con jitter.
80
+ backoff_base: float = 0.5
81
+ backoff_max: float = 8.0
82
+
83
+ def delay(self, attempt: int) -> float:
84
+ """Espera antes del intento ``attempt`` (0 = primer reintento)."""
85
+ ceiling = min(self.backoff_base * (2**attempt), self.backoff_max)
86
+ # Jitter completo: evita que varios procesos reintenten sincronizados.
87
+ return random.uniform(0, ceiling)
88
+
89
+
90
+ class _RateLimiter:
91
+ """Regulador preventivo, para no gastar reintentos en 429 evitables.
92
+
93
+ La API permite 5 solicitudes por segundo por API Key. Es un límite bajo, y
94
+ operaciones normales del SDK —recorrer páginas, esperar a que un documento
95
+ llegue a estado final— lo tocan enseguida. Espaciar las solicitudes sale más
96
+ barato que chocarse y reintentar.
97
+ """
98
+
99
+ def __init__(self, per_second: float) -> None:
100
+ self._interval = (
101
+ (1.0 / per_second) * _RATE_LIMIT_MARGIN if per_second > 0 else 0.0
102
+ )
103
+ self._next_slot = 0.0
104
+ self._lock = threading.Lock()
105
+
106
+ def wait_needed(self) -> float:
107
+ if self._interval <= 0:
108
+ return 0.0
109
+ with self._lock:
110
+ now = time.monotonic()
111
+ wait = max(0.0, self._next_slot - now)
112
+ self._next_slot = max(now, self._next_slot) + self._interval
113
+ return wait
114
+
115
+
116
+ class Transport(Protocol):
117
+ """Lo que los recursos necesitan de la capa HTTP."""
118
+
119
+ def request(
120
+ self,
121
+ method: str,
122
+ path: str,
123
+ *,
124
+ params: dict[str, Any] | None = ...,
125
+ json: dict[str, Any] | None = ...,
126
+ idempotency_key: str | None = ...,
127
+ ) -> Result: ...
128
+
129
+
130
+ # ─── Piezas compartidas entre sync y async ───────────────────────────────────
131
+
132
+
133
+ @dataclass
134
+ class _Base:
135
+ api_key: str
136
+ base_url: str = DEFAULT_BASE_URL
137
+ timeout: float = 30.0
138
+ retry: RetryPolicy = field(default_factory=RetryPolicy)
139
+ rate_limit_per_second: float = 5.0
140
+ user_agent: str = ""
141
+
142
+ def __post_init__(self) -> None:
143
+ self.base_url = self.base_url.rstrip("/")
144
+ self._limiter = _RateLimiter(self.rate_limit_per_second)
145
+
146
+ def _build_headers(self, idempotency_key: str | None) -> dict[str, str]:
147
+ from .. import __version__
148
+
149
+ headers = {
150
+ "Authorization": f"Bearer {self.api_key}",
151
+ "Accept": "application/json",
152
+ "User-Agent": self.user_agent or f"smartdoc-python/{__version__}",
153
+ }
154
+ if idempotency_key:
155
+ headers["Idempotency-Key"] = idempotency_key
156
+ return headers
157
+
158
+ def _should_retry(
159
+ self, method: str, idempotency_key: str | None, status: int | None
160
+ ) -> bool:
161
+ """Si conviene reintentar esta solicitud.
162
+
163
+ ``GET``, ``PUT`` y ``DELETE`` son idempotentes por definición. ``POST``
164
+ solo se reintenta si lleva ``Idempotency-Key``: sin ella, un reintento
165
+ sobre un 5xx podría emitir el documento dos veces.
166
+
167
+ El 429 es la excepción, y se reintenta siempre. Ahí el servidor rechaza
168
+ la solicitud *antes* de procesarla —el límite se controla en un
169
+ middleware, por delante de los handlers—, así que no hay nada hecho a
170
+ medias que un reintento pudiera duplicar. Sin esta excepción las
171
+ acciones (``cancel``, ``resend_to_set``, …) quedarían sin reintento,
172
+ porque son ``POST`` y no llevan clave de idempotencia.
173
+ """
174
+ if status is not None and status not in _RETRYABLE:
175
+ return False
176
+ if status == 429:
177
+ return True
178
+ if method.upper() == "POST":
179
+ return idempotency_key is not None
180
+ return True
181
+
182
+ def _url(self, path: str) -> str:
183
+ return f"{self.base_url}/{path.lstrip('/')}"
184
+
185
+
186
+ def _unwrap(response: httpx.Response) -> Result:
187
+ """Traduce la respuesta de la API a un :class:`Result` o a una excepción."""
188
+ try:
189
+ body = response.json()
190
+ except ValueError:
191
+ body = {}
192
+
193
+ if not isinstance(body, dict):
194
+ body = {"data": body}
195
+
196
+ if response.is_success and body.get("status") != "error":
197
+ return Result(
198
+ data=body.get("data"),
199
+ pagination=body.get("pagination"),
200
+ status_code=response.status_code,
201
+ )
202
+
203
+ raise _to_exception(response.status_code, body)
204
+
205
+
206
+ def _to_exception(status: int, body: dict[str, Any]) -> APIError:
207
+ code: str | None = body.get("code")
208
+ message: str = body.get("message") or f"La API respondió {status}."
209
+
210
+ if status == 401:
211
+ return AuthenticationError(message, code=code, status_code=status, raw=body)
212
+ if status == 403:
213
+ return PermissionError(
214
+ message,
215
+ missing_permission=_missing_permission(message),
216
+ code=code,
217
+ status_code=status,
218
+ raw=body,
219
+ )
220
+ if status == 404:
221
+ return NotFoundError(message, code=code, status_code=status, raw=body)
222
+ if status in (400, 422):
223
+ # 422 trae `fieldErrors`; 400 es un error de negocio con un solo mensaje.
224
+ return ValidationError(
225
+ message,
226
+ field_errors=body.get("fieldErrors"),
227
+ code=code,
228
+ status_code=status,
229
+ raw=body,
230
+ )
231
+ if status == 409:
232
+ return ConflictError(message, code=code, status_code=status, raw=body)
233
+ if status == 429:
234
+ return RateLimitError(message, code=code, status_code=status, raw=body)
235
+ if status >= 500:
236
+ return ServerError(message, code=code, status_code=status, raw=body)
237
+ return APIError(message, code=code, status_code=status, raw=body)
238
+
239
+
240
+ def _missing_permission(message: str) -> str | None:
241
+ """Saca el permiso del mensaje del 403, que lo nombra en texto plano."""
242
+ for word in message.replace(".", " ").replace(",", " ").split():
243
+ cleaned = word.strip("'\"`")
244
+ if cleaned.startswith(("read_", "write_")):
245
+ return cleaned
246
+ return None
247
+
248
+
249
+ # ─── Síncrono ────────────────────────────────────────────────────────────────
250
+
251
+
252
+ class SyncTransport(_Base):
253
+ """Transporte sobre :class:`httpx.Client`."""
254
+
255
+ def __init__(self, *args: Any, client: httpx.Client | None = None, **kw: Any):
256
+ super().__init__(*args, **kw)
257
+ self._client = client or httpx.Client(timeout=self.timeout)
258
+ self._propio = client is None
259
+
260
+ def request(
261
+ self,
262
+ method: str,
263
+ path: str,
264
+ *,
265
+ params: dict[str, Any] | None = None,
266
+ json: dict[str, Any] | None = None,
267
+ idempotency_key: str | None = None,
268
+ ) -> Result:
269
+ headers = self._build_headers(idempotency_key)
270
+ url = self._url(path)
271
+ last_error: Exception | None = None
272
+
273
+ for attempt in range(self.retry.max_retries + 1):
274
+ wait = self._limiter.wait_needed()
275
+ if wait:
276
+ time.sleep(wait)
277
+
278
+ try:
279
+ response = self._client.request(
280
+ method, url, params=params, json=json, headers=headers
281
+ )
282
+ except httpx.TransportError as e:
283
+ last_error = e
284
+ if attempt >= self.retry.max_retries or not self._should_retry(
285
+ method, idempotency_key, None
286
+ ):
287
+ raise APIError(f"No se pudo conectar con SmartDoc: {e}") from e
288
+ time.sleep(self.retry.delay(attempt))
289
+ continue
290
+
291
+ should_retry = (
292
+ response.status_code in _RETRYABLE
293
+ and attempt < self.retry.max_retries
294
+ and self._should_retry(method, idempotency_key, response.status_code)
295
+ )
296
+ if should_retry:
297
+ time.sleep(self.retry.delay(attempt))
298
+ continue
299
+
300
+ return _unwrap(response)
301
+
302
+ raise APIError(f"Se agotaron los reintentos: {last_error}")
303
+
304
+ def close(self) -> None:
305
+ if self._propio:
306
+ self._client.close()
307
+
308
+
309
+ # ─── Asíncrono ───────────────────────────────────────────────────────────────
310
+
311
+
312
+ class AsyncTransport(_Base):
313
+ """Transporte sobre :class:`httpx.AsyncClient`."""
314
+
315
+ def __init__(self, *args: Any, client: httpx.AsyncClient | None = None, **kw: Any):
316
+ super().__init__(*args, **kw)
317
+ self._client = client or httpx.AsyncClient(timeout=self.timeout)
318
+ self._propio = client is None
319
+
320
+ async def request(
321
+ self,
322
+ method: str,
323
+ path: str,
324
+ *,
325
+ params: dict[str, Any] | None = None,
326
+ json: dict[str, Any] | None = None,
327
+ idempotency_key: str | None = None,
328
+ ) -> Result:
329
+ import asyncio
330
+
331
+ headers = self._build_headers(idempotency_key)
332
+ url = self._url(path)
333
+ last_error: Exception | None = None
334
+
335
+ for attempt in range(self.retry.max_retries + 1):
336
+ wait = self._limiter.wait_needed()
337
+ if wait:
338
+ await asyncio.sleep(wait)
339
+
340
+ try:
341
+ response = await self._client.request(
342
+ method, url, params=params, json=json, headers=headers
343
+ )
344
+ except httpx.TransportError as e:
345
+ last_error = e
346
+ if attempt >= self.retry.max_retries or not self._should_retry(
347
+ method, idempotency_key, None
348
+ ):
349
+ raise APIError(f"No se pudo conectar con SmartDoc: {e}") from e
350
+ await asyncio.sleep(self.retry.delay(attempt))
351
+ continue
352
+
353
+ should_retry = (
354
+ response.status_code in _RETRYABLE
355
+ and attempt < self.retry.max_retries
356
+ and self._should_retry(method, idempotency_key, response.status_code)
357
+ )
358
+ if should_retry:
359
+ await asyncio.sleep(self.retry.delay(attempt))
360
+ continue
361
+
362
+ return _unwrap(response)
363
+
364
+ raise APIError(f"Se agotaron los reintentos: {last_error}")
365
+
366
+ async def aclose(self) -> None:
367
+ if self._propio:
368
+ await self._client.aclose()
369
+
370
+
371
+ def new_idempotency_key() -> str:
372
+ """Una clave de idempotencia nueva.
373
+
374
+ Va una por intento de creación. Ojo: la API guarda la respuesta 24 horas
375
+ **incluidos los errores**, así que reintentar con la misma clave después de
376
+ corregir el cuerpo devuelve el error viejo. Por eso el SDK genera una nueva
377
+ en cada llamada a ``create()`` en vez de derivarla del contenido.
378
+ """
379
+ return str(uuid.uuid4())
@@ -0,0 +1,128 @@
1
+ """El cliente asíncrono."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ import httpx
9
+
10
+ from ._core.async_config import AsyncIssuerConfig
11
+ from ._core.transport import DEFAULT_BASE_URL, AsyncTransport, RetryPolicy
12
+ from .errors import ConfigurationError
13
+ from .resources.async_resources import (
14
+ AsyncAutoInvoices,
15
+ AsyncClients,
16
+ AsyncCreditNotes,
17
+ AsyncDebitNotes,
18
+ AsyncDispatchPoints,
19
+ AsyncEstablishments,
20
+ AsyncInvoices,
21
+ AsyncReceipts,
22
+ AsyncReceivedDocuments,
23
+ AsyncRemissionNotes,
24
+ AsyncSandbox,
25
+ AsyncStamps,
26
+ AsyncTaxPayerResource,
27
+ )
28
+
29
+ __all__ = ["AsyncClient"]
30
+
31
+
32
+ class AsyncClient:
33
+ """Igual que :class:`smartdoc.Client`, con ``await``.
34
+
35
+ ::
36
+
37
+ async with smartdoc.AsyncClient(api_key="pk_...") as sd:
38
+ factura = await sd.invoices.create(
39
+ receptor=smartdoc.Receptor.entity(
40
+ ruc="80012345-1", social_name="Cliente S.A."
41
+ ),
42
+ items=[smartdoc.Item("Consultoría", quantity=1, unit_amount=1_100_000)],
43
+ )
44
+
45
+ Los parámetros son los mismos que los del cliente síncrono.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ api_key: str | None = None,
51
+ *,
52
+ base_url: str | None = None,
53
+ establishment: str | int | None = None,
54
+ dispatch_point: str | int | None = None,
55
+ stamp: tuple[str, str] | str | None = None,
56
+ timeout: float = 30.0,
57
+ max_retries: int = 3,
58
+ rate_limit_per_second: float = 5.0,
59
+ auto_fill: bool = True,
60
+ http_client: httpx.AsyncClient | None = None,
61
+ ) -> None:
62
+ key = api_key or os.environ.get("SMARTDOC_API_KEY")
63
+ if not key:
64
+ raise ConfigurationError(
65
+ "Falta la API Key. Pasala como AsyncClient(api_key='pk_...') o "
66
+ "poné la variable de entorno SMARTDOC_API_KEY."
67
+ )
68
+
69
+ self._transport = AsyncTransport(
70
+ api_key=key,
71
+ base_url=base_url
72
+ or os.environ.get("SMARTDOC_BASE_URL")
73
+ or DEFAULT_BASE_URL,
74
+ timeout=timeout,
75
+ retry=RetryPolicy(max_retries=max_retries),
76
+ rate_limit_per_second=rate_limit_per_second,
77
+ client=http_client,
78
+ )
79
+
80
+ if stamp is None:
81
+ identifier, begin_date = None, None
82
+ elif isinstance(stamp, str):
83
+ identifier, begin_date = stamp, None
84
+ else:
85
+ identifier, begin_date = stamp
86
+
87
+ self._config = AsyncIssuerConfig(
88
+ _request=self._transport.request,
89
+ stamp_identifier=identifier,
90
+ stamp_begin_date=begin_date,
91
+ establishment=establishment,
92
+ dispatch_point=dispatch_point,
93
+ auto_fill=auto_fill,
94
+ )
95
+
96
+ # Documentos electrónicos
97
+ self.invoices = AsyncInvoices(self._transport, self._config)
98
+ self.receipts = AsyncReceipts(self._transport, self._config)
99
+ self.credit_notes = AsyncCreditNotes(self._transport, self._config)
100
+ self.debit_notes = AsyncDebitNotes(self._transport, self._config)
101
+ self.remission_notes = AsyncRemissionNotes(self._transport, self._config)
102
+ self.auto_invoices = AsyncAutoInvoices(self._transport, self._config)
103
+
104
+ # Recursos de soporte
105
+ self.stamps = AsyncStamps(self._transport, self._config)
106
+ self.clients = AsyncClients(self._transport, self._config)
107
+ self.establishments = AsyncEstablishments(self._transport, self._config)
108
+ self.dispatch_points = AsyncDispatchPoints(self._transport, self._config)
109
+ self.received_documents = AsyncReceivedDocuments(self._transport, self._config)
110
+ self.taxpayer_resource = AsyncTaxPayerResource(self._transport, self._config)
111
+ self.sandbox = AsyncSandbox(self._transport)
112
+
113
+ async def taxpayer(self) -> Any:
114
+ """El contribuyente de esta API Key. Se consulta una vez y se cachea."""
115
+ return await self._config.taxpayer()
116
+
117
+ def refresh_config(self) -> None:
118
+ """Olvida lo descubierto: contribuyente, timbrado, establecimiento y punto."""
119
+ self._config.refresh()
120
+
121
+ async def aclose(self) -> None:
122
+ await self._transport.aclose()
123
+
124
+ async def __aenter__(self) -> AsyncClient:
125
+ return self
126
+
127
+ async def __aexit__(self, *exc: Any) -> None:
128
+ await self.aclose()
@@ -0,0 +1,9 @@
1
+ """Constructores de los datos que van en un documento."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .associated import AssociatedDocument
6
+ from .items import Item, totals_for
7
+ from .recipient import Recipient
8
+
9
+ __all__ = ["Recipient", "Item", "AssociatedDocument", "totals_for"]
@@ -0,0 +1,107 @@
1
+ """Documento asociado.
2
+
3
+ Las notas de crédito y débito tienen que decir a qué documento corrigen, y los
4
+ recibos a qué factura corresponden. Según el tipo, la API pide un juego de
5
+ campos distinto: con factura electrónica alcanza el CDC; con factura impresa hay
6
+ que dar timbrado, establecimiento, punto de expedición, número y fecha.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from datetime import date
13
+ from typing import Any
14
+
15
+ from ..constants.documents import AssociatedDocumentType
16
+ from ..constants.sifen import PrintedDocumentType
17
+ from ..errors import ValidationError
18
+
19
+ __all__ = ["AssociatedDocument"]
20
+
21
+
22
+ @dataclass
23
+ class AssociatedDocument:
24
+ """Referencia al documento que se corrige o recibe."""
25
+
26
+ type: AssociatedDocumentType
27
+ cdc: str | None = None
28
+ printed_type: PrintedDocumentType | int | None = None
29
+ stamp_identifier: str | None = None
30
+ establishment_code: str | None = None
31
+ dispatch_point_code: str | None = None
32
+ number: str | None = None
33
+ document_date: date | str | None = None
34
+
35
+ @classmethod
36
+ def electronic(cls, cdc: str) -> AssociatedDocument:
37
+ """Una factura electrónica, referida por su CDC de 44 caracteres."""
38
+ if len(cdc) != 44:
39
+ raise ValidationError(
40
+ f"El CDC tiene que tener exactamente 44 caracteres; este tiene "
41
+ f"{len(cdc)}."
42
+ )
43
+ return cls(type=AssociatedDocumentType.ELECTRONIC_INVOICE, cdc=cdc)
44
+
45
+ @classmethod
46
+ def printed(
47
+ cls,
48
+ *,
49
+ stamp_identifier: str,
50
+ establishment_code: str,
51
+ dispatch_point_code: str,
52
+ number: str,
53
+ document_date: date | str,
54
+ printed_type: PrintedDocumentType | int = PrintedDocumentType.INVOICE,
55
+ ) -> AssociatedDocument:
56
+ """Un documento preimpreso, de antes de la facturación electrónica."""
57
+ for name, value, length in [
58
+ ("stamp_identifier", stamp_identifier, 8),
59
+ ("establishment_code", establishment_code, 3),
60
+ ("dispatch_point_code", dispatch_point_code, 3),
61
+ ("number", number, 7),
62
+ ]:
63
+ if len(value) != length:
64
+ raise ValidationError(
65
+ f"{name} tiene que tener exactamente {length} caracteres; "
66
+ f"{value!r} tiene {len(value)}."
67
+ )
68
+ if not value.isdigit():
69
+ raise ValidationError(f"{name} tiene que ser numérico: {value!r}.")
70
+
71
+ return cls(
72
+ type=AssociatedDocumentType.PRINTED_INVOICE,
73
+ printed_type=PrintedDocumentType.coerce(printed_type),
74
+ stamp_identifier=stamp_identifier,
75
+ establishment_code=establishment_code,
76
+ dispatch_point_code=dispatch_point_code,
77
+ number=number,
78
+ document_date=document_date,
79
+ )
80
+
81
+ @classmethod
82
+ def none(cls) -> AssociatedDocument:
83
+ """Sin documento asociado. Solo lo aceptan los recibos."""
84
+ return cls(type=AssociatedDocumentType.NONE)
85
+
86
+ def to_api(self) -> dict[str, Any]:
87
+ body: dict[str, Any] = {
88
+ "associatedDocumentType": AssociatedDocumentType.coerce(self.type).value
89
+ }
90
+ if self.cdc is not None:
91
+ body["associatedDocumentCdc"] = self.cdc
92
+ if self.printed_type is not None:
93
+ body["associatedDocumentPrintedType"] = str(int(self.printed_type))
94
+ if self.stamp_identifier is not None:
95
+ body["associatedDocumentStampIdentifier"] = self.stamp_identifier
96
+ if self.establishment_code is not None:
97
+ body["associatedDocumentEstablishmentCode"] = self.establishment_code
98
+ if self.dispatch_point_code is not None:
99
+ body["associatedDocumentDispatchPointCode"] = self.dispatch_point_code
100
+ if self.number is not None:
101
+ body["associatedDocumentNumber"] = self.number
102
+ if self.document_date is not None:
103
+ date_value = self.document_date
104
+ body["associatedDocumentDate"] = (
105
+ date_value.isoformat() if isinstance(date_value, date) else date_value
106
+ )
107
+ return body