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/errors.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Excepciones del SDK.
|
|
2
|
+
|
|
3
|
+
Este módulo no importa nada del resto del paquete, así que puede usarse desde
|
|
4
|
+
cualquier lado sin ciclos.
|
|
5
|
+
|
|
6
|
+
La jerarquía separa dos orígenes:
|
|
7
|
+
|
|
8
|
+
* Errores que devolvió SmartDoc (`APIError` y sus subclases), que traen el
|
|
9
|
+
`code` y el `message` del cuerpo de la respuesta.
|
|
10
|
+
* Errores que detecta el SDK antes de salir a la red (`ValidationError`,
|
|
11
|
+
`ConfigurationError`, `SignatureError`), que existen justamente para no
|
|
12
|
+
gastar una llamada en algo que ya se sabe que va a fallar.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Mapping, Sequence
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"SmartDocError",
|
|
22
|
+
"APIError",
|
|
23
|
+
"AuthenticationError",
|
|
24
|
+
"PermissionError",
|
|
25
|
+
"NotFoundError",
|
|
26
|
+
"ValidationError",
|
|
27
|
+
"RateLimitError",
|
|
28
|
+
"ConflictError",
|
|
29
|
+
"ServerError",
|
|
30
|
+
"ConfigurationError",
|
|
31
|
+
"SignatureError",
|
|
32
|
+
"TimeoutError",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SmartDocError(Exception):
|
|
37
|
+
"""Base de todos los errores del SDK."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# ─── Errores devueltos por la API ────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class APIError(SmartDocError):
|
|
44
|
+
"""Error devuelto por SmartDoc.
|
|
45
|
+
|
|
46
|
+
Atributos:
|
|
47
|
+
code: el campo ``code`` del cuerpo (por ejemplo ``NOT_FOUND``).
|
|
48
|
+
message: el campo ``message``.
|
|
49
|
+
status_code: el código HTTP.
|
|
50
|
+
raw: el cuerpo completo, por si trae algo que el SDK no modela.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
message: str,
|
|
56
|
+
*,
|
|
57
|
+
code: str | None = None,
|
|
58
|
+
status_code: int | None = None,
|
|
59
|
+
raw: Mapping[str, Any] | None = None,
|
|
60
|
+
) -> None:
|
|
61
|
+
super().__init__(message)
|
|
62
|
+
self.message = message
|
|
63
|
+
self.code = code
|
|
64
|
+
self.status_code = status_code
|
|
65
|
+
self.raw: dict[str, Any] = dict(raw or {})
|
|
66
|
+
|
|
67
|
+
def __str__(self) -> str:
|
|
68
|
+
if self.code:
|
|
69
|
+
return f"[{self.code}] {self.message}"
|
|
70
|
+
return self.message
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class AuthenticationError(APIError):
|
|
74
|
+
"""401 — la API Key falta, es inválida o expiró."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class PermissionError(APIError): # noqa: A001 - sombrea el builtin a propósito
|
|
78
|
+
"""403 — la API Key es válida pero no tiene el permiso necesario.
|
|
79
|
+
|
|
80
|
+
Los permisos de SmartDoc no son jerárquicos ni se heredan: ``write_invoices``
|
|
81
|
+
no habilita nada que pida ``read_invoices``. Si esto salta, hay que marcar el
|
|
82
|
+
permiso que falta en la API Key desde el panel.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(self, *args: Any, missing_permission: str | None = None, **kw: Any):
|
|
86
|
+
super().__init__(*args, **kw)
|
|
87
|
+
self.missing_permission = missing_permission
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class NotFoundError(APIError):
|
|
91
|
+
"""404 — el recurso no existe o no pertenece a este contribuyente."""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class ValidationError(APIError):
|
|
95
|
+
"""422 de la API, o una validación que el SDK hizo localmente.
|
|
96
|
+
|
|
97
|
+
Cuando viene de la API, ``field_errors`` mapea campo → mensaje. Cuando la
|
|
98
|
+
detecta el SDK, ``status_code`` es ``None`` y el mensaje explica cómo
|
|
99
|
+
corregirlo.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
def __init__(
|
|
103
|
+
self,
|
|
104
|
+
message: str,
|
|
105
|
+
*,
|
|
106
|
+
field_errors: Mapping[str, str] | None = None,
|
|
107
|
+
**kw: Any,
|
|
108
|
+
) -> None:
|
|
109
|
+
super().__init__(message, **kw)
|
|
110
|
+
self.field_errors: dict[str, str] = dict(field_errors or {})
|
|
111
|
+
|
|
112
|
+
def __str__(self) -> str:
|
|
113
|
+
base = super().__str__()
|
|
114
|
+
if not self.field_errors:
|
|
115
|
+
return base
|
|
116
|
+
detail = "; ".join(
|
|
117
|
+
f"{field}: {msg}" for field, msg in self.field_errors.items()
|
|
118
|
+
)
|
|
119
|
+
return f"{base} ({detail})"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class RateLimitError(APIError):
|
|
123
|
+
"""429 — se superó el límite de 5 solicitudes por segundo.
|
|
124
|
+
|
|
125
|
+
SmartDoc no envía ``Retry-After``, así que el SDK reintenta con backoff
|
|
126
|
+
exponencial propio. Si igual llega hasta acá, es que se agotaron los
|
|
127
|
+
reintentos.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class ConflictError(APIError):
|
|
132
|
+
"""409, o una acción no permitida para el estado actual del documento."""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class ServerError(APIError):
|
|
136
|
+
"""5xx — error interno de SmartDoc."""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# ─── Errores locales del SDK ─────────────────────────────────────────────────
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class ConfigurationError(SmartDocError):
|
|
143
|
+
"""El SDK no pudo resolver la configuración necesaria para emitir.
|
|
144
|
+
|
|
145
|
+
El caso típico es que el contribuyente tenga más de un establecimiento o
|
|
146
|
+
punto de expedición y no se haya indicado cuál usar. El SDK nunca elige uno
|
|
147
|
+
en silencio, porque el elegido queda impreso en el documento.
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
def __init__(self, message: str, *, options: Sequence[str] | None = None) -> None:
|
|
151
|
+
if options:
|
|
152
|
+
message = f"{message} Opciones disponibles: {', '.join(options)}."
|
|
153
|
+
super().__init__(message)
|
|
154
|
+
self.options = list(options or [])
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class SignatureError(SmartDocError):
|
|
158
|
+
"""La firma de un webhook no validó.
|
|
159
|
+
|
|
160
|
+
Las dos causas habituales son verificar contra el JSON reserializado en vez
|
|
161
|
+
del cuerpo crudo, y usar el secreto de otro endpoint.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class TimeoutError(SmartDocError): # noqa: A001 - sombrea el builtin a propósito
|
|
166
|
+
"""Se agotó la espera de ``wait_until_final`` sin llegar a un estado final."""
|
|
167
|
+
|
|
168
|
+
def __init__(self, message: str, *, last_status: str | None = None) -> None:
|
|
169
|
+
super().__init__(message)
|
|
170
|
+
self.last_status = last_status
|
smartdoc/geo/__init__.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"""Catálogo geográfico de Paraguay (departamentos, distritos y ciudades).
|
|
2
|
+
|
|
3
|
+
Todo documento cuyo receptor tenga dirección necesita seis campos que salen de
|
|
4
|
+
acá: ``clientDepartment``, ``clientDepartmentDescription``, ``clientDistrict``,
|
|
5
|
+
``clientDistrictDescription``, ``clientCity`` y ``clientCityDescription``.
|
|
6
|
+
|
|
7
|
+
**La API pública de SmartDoc no expone este catálogo**: vive en las tablas
|
|
8
|
+
``Departments`` / ``Districts`` / ``Cities`` y solo se consulta desde
|
|
9
|
+
``/location/*``, que exige JWT de usuario. Una API Key no alcanza. Por eso el SDK
|
|
10
|
+
lo embebe, generado con ``scripts/extract_geo.py``.
|
|
11
|
+
|
|
12
|
+
Una sola búsqueda resuelve los seis campos::
|
|
13
|
+
|
|
14
|
+
ciudad = smartdoc.geo.find_city("Asunción")
|
|
15
|
+
|
|
16
|
+
smartdoc.Receptor.person(
|
|
17
|
+
ruc="5000001-1",
|
|
18
|
+
name="Juan Pérez",
|
|
19
|
+
address="Av. España 1234",
|
|
20
|
+
house_number=1234,
|
|
21
|
+
city=ciudad,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
Los nombres están en mayúsculas y sin tildes, como los guarda SmartDoc, pero las
|
|
25
|
+
búsquedas ignoran mayúsculas y tildes.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import json
|
|
31
|
+
import re
|
|
32
|
+
import unicodedata
|
|
33
|
+
from collections.abc import Callable
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
from functools import lru_cache
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
|
|
38
|
+
from ..errors import ValidationError
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"Department",
|
|
42
|
+
"District",
|
|
43
|
+
"City",
|
|
44
|
+
"find_city",
|
|
45
|
+
"search_cities",
|
|
46
|
+
"city",
|
|
47
|
+
"district",
|
|
48
|
+
"department",
|
|
49
|
+
"departments",
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
_DATA_FILE = Path(__file__).parent / "data.json"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class Department:
|
|
57
|
+
"""Departamento del catálogo de la DNIT."""
|
|
58
|
+
|
|
59
|
+
code: int
|
|
60
|
+
name: str
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class District:
|
|
65
|
+
"""Distrito, con su departamento."""
|
|
66
|
+
|
|
67
|
+
code: int
|
|
68
|
+
name: str
|
|
69
|
+
department: Department
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class City:
|
|
74
|
+
"""Ciudad, con su distrito y su departamento.
|
|
75
|
+
|
|
76
|
+
Es lo que se le pasa a ``Receptor``: de acá salen los seis campos de
|
|
77
|
+
dirección que exige el documento electrónico.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
code: int
|
|
81
|
+
name: str
|
|
82
|
+
district: District
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def department(self) -> Department:
|
|
86
|
+
return self.district.department
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@lru_cache(maxsize=1)
|
|
90
|
+
def _load() -> tuple[dict[int, Department], dict[int, District], dict[int, City]]:
|
|
91
|
+
raw = json.loads(_DATA_FILE.read_text(encoding="utf-8"))
|
|
92
|
+
|
|
93
|
+
departments = {
|
|
94
|
+
int(code): Department(code=int(code), name=name)
|
|
95
|
+
for code, name in raw["departments"].items()
|
|
96
|
+
}
|
|
97
|
+
districts = {
|
|
98
|
+
int(code): District(
|
|
99
|
+
code=int(code), name=name, department=departments[int(dep_code)]
|
|
100
|
+
)
|
|
101
|
+
for code, (dep_code, name) in raw["districts"].items()
|
|
102
|
+
}
|
|
103
|
+
cities = {
|
|
104
|
+
int(code): City(code=int(code), name=name, district=districts[int(dist_code)])
|
|
105
|
+
for code, (dist_code, name) in raw["cities"].items()
|
|
106
|
+
}
|
|
107
|
+
return departments, districts, cities
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _normalize(text: str) -> str:
|
|
111
|
+
"""Minúsculas y sin tildes, para que 'Asunción' encuentre 'ASUNCION'."""
|
|
112
|
+
without_accents = unicodedata.normalize("NFKD", text)
|
|
113
|
+
without_accents = "".join(
|
|
114
|
+
c for c in without_accents if not unicodedata.combining(c)
|
|
115
|
+
)
|
|
116
|
+
return " ".join(without_accents.casefold().split())
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
_SUFFIX_RE = re.compile(r"\s*\([^)]*\)\s*$")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _without_suffix(name: str) -> str:
|
|
123
|
+
"""Quita el paréntesis final de nombres como ``ASUNCION (DISTRITO)``.
|
|
124
|
+
|
|
125
|
+
293 de las 6419 ciudades traen un paréntesis al final —casi siempre
|
|
126
|
+
``(MUNICIPIO)`` o ``(DISTRITO)``, que marcan la cabecera del distrito—. Nadie
|
|
127
|
+
va a escribirlo, así que se indexa también la forma corta.
|
|
128
|
+
"""
|
|
129
|
+
return _SUFFIX_RE.sub("", name)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@lru_cache(maxsize=1)
|
|
133
|
+
def _city_index() -> dict[str, list[City]]:
|
|
134
|
+
"""Índice nombre normalizado → ciudades.
|
|
135
|
+
|
|
136
|
+
Cada ciudad se indexa por su nombre completo y, si tiene paréntesis final,
|
|
137
|
+
también por la forma corta.
|
|
138
|
+
"""
|
|
139
|
+
index: dict[str, list[City]] = {}
|
|
140
|
+
for found_city in _load()[2].values():
|
|
141
|
+
keys = {
|
|
142
|
+
_normalize(found_city.name),
|
|
143
|
+
_normalize(_without_suffix(found_city.name)),
|
|
144
|
+
}
|
|
145
|
+
for key in keys:
|
|
146
|
+
if key:
|
|
147
|
+
index.setdefault(key, []).append(found_city)
|
|
148
|
+
return index
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# ─── Búsqueda ────────────────────────────────────────────────────────────────
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def find_city(
|
|
155
|
+
name: str,
|
|
156
|
+
*,
|
|
157
|
+
department: str | None = None,
|
|
158
|
+
district: str | None = None,
|
|
159
|
+
) -> City:
|
|
160
|
+
"""Busca una ciudad por nombre exacto y devuelve una sola.
|
|
161
|
+
|
|
162
|
+
Ignora mayúsculas y tildes. Si el nombre es ambiguo se levanta
|
|
163
|
+
``ValidationError`` con todas las opciones y su código, en vez de elegir una:
|
|
164
|
+
la ciudad queda impresa en el documento y adivinar sería imprimir una
|
|
165
|
+
dirección equivocada.
|
|
166
|
+
|
|
167
|
+
La ambigüedad viene de dos lados. A veces son ciudades homónimas en
|
|
168
|
+
departamentos distintos (hay tres ``CONCEPCION``), y ahí desempata
|
|
169
|
+
``department``. Otras veces SIFEN distingue el centro urbano del municipio
|
|
170
|
+
dentro del mismo distrito —``ENCARNACION`` y ``ENCARNACION (MUNICIPIO)``—, y
|
|
171
|
+
ahí no hay nada que desempate: hay que elegir por código con :func:`city`.
|
|
172
|
+
|
|
173
|
+
Para búsquedas parciales o exploratorias, usar :func:`search_cities`.
|
|
174
|
+
"""
|
|
175
|
+
candidates = list(_city_index().get(_normalize(name), []))
|
|
176
|
+
|
|
177
|
+
if not candidates:
|
|
178
|
+
suggestions = search_cities(name, limit=5)
|
|
179
|
+
detail = ""
|
|
180
|
+
if suggestions:
|
|
181
|
+
names = ", ".join(f"{c.name} ({c.department.name})" for c in suggestions)
|
|
182
|
+
detail = f" ¿Quisiste decir alguna de estas? {names}."
|
|
183
|
+
raise ValidationError(f"No encontré la ciudad {name!r}.{detail}")
|
|
184
|
+
|
|
185
|
+
if department is not None:
|
|
186
|
+
candidates = _filter_by(candidates, department, lambda c: c.department.name)
|
|
187
|
+
if not candidates:
|
|
188
|
+
raise ValidationError(
|
|
189
|
+
f"No encontré la ciudad {name!r} en el departamento {department!r}."
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
if district is not None:
|
|
193
|
+
candidates = _filter_by(candidates, district, lambda c: c.district.name)
|
|
194
|
+
if not candidates:
|
|
195
|
+
raise ValidationError(
|
|
196
|
+
f"No encontré la ciudad {name!r} en el distrito {district!r}."
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
if len(candidates) > 1:
|
|
200
|
+
options = "; ".join(
|
|
201
|
+
f"código {c.code}: {c.name} "
|
|
202
|
+
f"(distrito {c.district.name}, departamento {c.department.name})"
|
|
203
|
+
for c in candidates
|
|
204
|
+
)
|
|
205
|
+
raise ValidationError(
|
|
206
|
+
f"{name!r} es ambiguo: hay {len(candidates)} ciudades con ese nombre. "
|
|
207
|
+
f"Desempatá con department=... o district=..., o elegí por código con "
|
|
208
|
+
f"geo.city(...). Opciones: {options}."
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
return candidates[0]
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _filter_by(
|
|
215
|
+
cities: list[City], value: str, field: Callable[[City], str]
|
|
216
|
+
) -> list[City]:
|
|
217
|
+
"""Filtra por nombre, tolerando el sufijo entre paréntesis."""
|
|
218
|
+
target = _normalize(value)
|
|
219
|
+
return [
|
|
220
|
+
c
|
|
221
|
+
for c in cities
|
|
222
|
+
if target in (_normalize(field(c)), _normalize(_without_suffix(field(c))))
|
|
223
|
+
]
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def search_cities(term: str, *, limit: int = 20) -> list[City]:
|
|
227
|
+
"""Ciudades cuyo nombre contiene ``term``, ignorando mayúsculas y tildes."""
|
|
228
|
+
target = _normalize(term)
|
|
229
|
+
if not target:
|
|
230
|
+
return []
|
|
231
|
+
|
|
232
|
+
found = [
|
|
233
|
+
found_city
|
|
234
|
+
for found_city in _load()[2].values()
|
|
235
|
+
if target in _normalize(found_city.name)
|
|
236
|
+
]
|
|
237
|
+
found.sort(key=lambda c: (len(c.name), c.name))
|
|
238
|
+
return found[:limit]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# ─── Acceso por código ───────────────────────────────────────────────────────
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def city(code: int) -> City:
|
|
245
|
+
"""La ciudad con ese código."""
|
|
246
|
+
try:
|
|
247
|
+
return _load()[2][int(code)]
|
|
248
|
+
except KeyError:
|
|
249
|
+
raise ValidationError(f"No existe la ciudad con código {code}.") from None
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def district(code: int) -> District:
|
|
253
|
+
"""El distrito con ese código."""
|
|
254
|
+
try:
|
|
255
|
+
return _load()[1][int(code)]
|
|
256
|
+
except KeyError:
|
|
257
|
+
raise ValidationError(f"No existe el distrito con código {code}.") from None
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def department(code: int) -> Department:
|
|
261
|
+
"""El departamento con ese código."""
|
|
262
|
+
try:
|
|
263
|
+
return _load()[0][int(code)]
|
|
264
|
+
except KeyError:
|
|
265
|
+
raise ValidationError(f"No existe el departamento con código {code}.") from None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def departments() -> list[Department]:
|
|
269
|
+
"""Los 18 departamentos, ordenados por código."""
|
|
270
|
+
return sorted(_load()[0].values(), key=lambda d: d.code)
|