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
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Ítems y cálculo de totales.
|
|
2
|
+
|
|
3
|
+
El cálculo no es una comodidad: es una defensa. La API valida que ``amount``
|
|
4
|
+
coincida con la suma de los ítems y rechaza el documento si no —con tolerancia
|
|
5
|
+
de 1, y contemplando descuento por ítem, descuento global y descuento SEDECO—.
|
|
6
|
+
Calcularlo mal significa un 422 en el mejor caso.
|
|
7
|
+
|
|
8
|
+
Los desgloses de IVA (``amount10Percent``, ``taxed10Percent``, ``iva10Percent``
|
|
9
|
+
y sus equivalentes al 5%) son opcionales en la API, pero si se mandan tienen que
|
|
10
|
+
ser coherentes. El SDK los calcula todos a partir de los ítems para que lo sean.
|
|
11
|
+
|
|
12
|
+
**Cómo se calcula el IVA en Paraguay.** El precio ya lo incluye, no se le suma.
|
|
13
|
+
Para un ítem de 1.100.000 al 10%, el IVA es 1.100.000 / 11 = 100.000 y la base
|
|
14
|
+
gravada es el millón restante. Al 5%, el divisor es 21.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from ..constants.documents import Iva
|
|
25
|
+
from ..constants.sifen import MeasureUnit
|
|
26
|
+
from ..errors import ValidationError
|
|
27
|
+
|
|
28
|
+
__all__ = ["Item", "totals_for"]
|
|
29
|
+
|
|
30
|
+
#: La API acepta una diferencia de hasta 1 entre `amount` y la suma de ítems.
|
|
31
|
+
TOLERANCE = Decimal("1")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _dec(value: Any) -> Decimal:
|
|
35
|
+
"""A Decimal, pasando por str para no arrastrar el error del float."""
|
|
36
|
+
if isinstance(value, Decimal):
|
|
37
|
+
return value
|
|
38
|
+
return Decimal(str(value))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _round(value: Decimal) -> Decimal:
|
|
42
|
+
"""Redondea a 4 decimales, que es lo que tolera la DNIT."""
|
|
43
|
+
return value.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _as_number(value: Decimal) -> float | int:
|
|
47
|
+
"""Decimal a algo serializable en JSON, sin decimales de más."""
|
|
48
|
+
as_integer = value.to_integral_value()
|
|
49
|
+
return int(as_integer) if value == as_integer else float(value)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Item:
|
|
54
|
+
"""Un ítem de un documento.
|
|
55
|
+
|
|
56
|
+
``total_amount`` se calcula como ``quantity * unit_amount`` salvo que se
|
|
57
|
+
pase explícitamente.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
description: descripción del producto o servicio.
|
|
61
|
+
quantity: cantidad.
|
|
62
|
+
unit_amount: precio unitario, con el IVA ya incluido.
|
|
63
|
+
iva: tratamiento de IVA de **este** ítem. Si no se pasa, se emite al
|
|
64
|
+
**10%**, que es la tasa general. Los cinco valores posibles son
|
|
65
|
+
``TEN``, ``FIVE``, ``EXEMPT``, ``MIXED_TEN`` y ``MIXED_FIVE``.
|
|
66
|
+
|
|
67
|
+
El tratamiento es una propiedad del producto, no de su categoría
|
|
68
|
+
comercial: dentro de cualquier categoría hay excepciones. Emitir con
|
|
69
|
+
el tratamiento equivocado obliga a anular y reemitir, así que
|
|
70
|
+
conviene guardarlo en la ficha del producto y no inferirlo.
|
|
71
|
+
code: código interno. Si no se pasa, se numera por posición.
|
|
72
|
+
measure_unit: unidad de medida SIFEN. Por defecto ``UNIT`` (77), que es
|
|
73
|
+
lo que usa SmartDoc en toda su interfaz.
|
|
74
|
+
discount: descuento **por unidad**, no del total de la línea. Así lo
|
|
75
|
+
interpreta la validación del servidor, que multiplica por la
|
|
76
|
+
cantidad.
|
|
77
|
+
iva_base: porcentaje gravado, solo para los tipos de IVA mixtos.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
description: str
|
|
81
|
+
quantity: float | int | Decimal
|
|
82
|
+
unit_amount: float | int | Decimal
|
|
83
|
+
iva: Iva | str = Iva.TEN
|
|
84
|
+
code: str | None = None
|
|
85
|
+
measure_unit: MeasureUnit | int = MeasureUnit.UNIT
|
|
86
|
+
discount: float | int | Decimal = 0
|
|
87
|
+
iva_base: float | int | Decimal | None = None
|
|
88
|
+
obs: str | None = None
|
|
89
|
+
total_amount: float | int | Decimal | None = None
|
|
90
|
+
dncp_level_code_general: str | None = None
|
|
91
|
+
dncp_level_code_specific: str | None = None
|
|
92
|
+
|
|
93
|
+
def __post_init__(self) -> None:
|
|
94
|
+
self.iva = Iva.coerce(self.iva)
|
|
95
|
+
self.measure_unit = MeasureUnit.coerce(self.measure_unit)
|
|
96
|
+
|
|
97
|
+
if self.iva_type.is_mixed and self.iva_base is None:
|
|
98
|
+
raise ValidationError(
|
|
99
|
+
f"El tipo de IVA {self.iva_type.value!r} es mixto y necesita "
|
|
100
|
+
f"iva_base: el porcentaje de la operación que está gravado."
|
|
101
|
+
)
|
|
102
|
+
if _dec(self.quantity) <= 0:
|
|
103
|
+
raise ValidationError(
|
|
104
|
+
f"La cantidad del ítem {self.description!r} tiene que ser mayor a 0."
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def iva_type(self) -> Iva:
|
|
109
|
+
"""El IVA como miembro del catálogo, sin importar cómo se haya pasado."""
|
|
110
|
+
return Iva.coerce(self.iva)
|
|
111
|
+
|
|
112
|
+
# ─── Montos ──────────────────────────────────────────────────────────────
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def line_total(self) -> Decimal:
|
|
116
|
+
"""Total de la línea, antes de descuentos."""
|
|
117
|
+
if self.total_amount is not None:
|
|
118
|
+
return _dec(self.total_amount)
|
|
119
|
+
return _round(_dec(self.quantity) * _dec(self.unit_amount))
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def line_discount(self) -> Decimal:
|
|
123
|
+
"""Descuento total de la línea: el unitario por la cantidad."""
|
|
124
|
+
return _round(_dec(self.discount) * _dec(self.quantity))
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def net(self) -> Decimal:
|
|
128
|
+
"""Lo que la línea aporta al total del documento."""
|
|
129
|
+
return self.line_total - self.line_discount
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def taxable_share(self) -> Decimal:
|
|
133
|
+
"""Fracción de la línea que está gravada.
|
|
134
|
+
|
|
135
|
+
Es 1 salvo en los tipos mixtos, donde la define ``iva_base``.
|
|
136
|
+
"""
|
|
137
|
+
if self.iva_type.is_mixed:
|
|
138
|
+
return _dec(self.iva_base) / Decimal(100)
|
|
139
|
+
return Decimal(1)
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def iva_amount(self) -> Decimal:
|
|
143
|
+
"""IVA contenido en la línea.
|
|
144
|
+
|
|
145
|
+
El precio ya lo incluye: al 10% se divide por 11, al 5% por 21.
|
|
146
|
+
"""
|
|
147
|
+
if self.iva_type is Iva.EXEMPT:
|
|
148
|
+
return Decimal(0)
|
|
149
|
+
taxed = self.net * self.taxable_share
|
|
150
|
+
divisor = Decimal(11) if self.iva_type.rate == 0.10 else Decimal(21)
|
|
151
|
+
return _round(taxed / divisor)
|
|
152
|
+
|
|
153
|
+
def to_api(self, *, position: int = 1) -> dict[str, Any]:
|
|
154
|
+
"""El ítem en el formato que espera la API."""
|
|
155
|
+
body: dict[str, Any] = {
|
|
156
|
+
"description": self.description,
|
|
157
|
+
"code": self.code or str(position),
|
|
158
|
+
"measureUnit": int(self.measure_unit),
|
|
159
|
+
"quantity": _as_number(_dec(self.quantity)),
|
|
160
|
+
"unitAmount": _as_number(_dec(self.unit_amount)),
|
|
161
|
+
"totalAmount": _as_number(self.line_total),
|
|
162
|
+
"ivaType": self.iva_type.value,
|
|
163
|
+
}
|
|
164
|
+
if self.obs is not None:
|
|
165
|
+
body["obs"] = self.obs
|
|
166
|
+
if _dec(self.discount):
|
|
167
|
+
body["discount"] = _as_number(_dec(self.discount))
|
|
168
|
+
if self.iva_type.is_mixed:
|
|
169
|
+
body["ivaBase"] = _as_number(_dec(self.iva_base))
|
|
170
|
+
if self.dncp_level_code_general:
|
|
171
|
+
body["dncpLevelCodeGeneral"] = self.dncp_level_code_general
|
|
172
|
+
if self.dncp_level_code_specific:
|
|
173
|
+
body["dncpLevelCodeSpecific"] = self.dncp_level_code_specific
|
|
174
|
+
|
|
175
|
+
body.update(_item_breakdown(self))
|
|
176
|
+
return body
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _item_breakdown(item: Item) -> dict[str, Any]:
|
|
180
|
+
"""Los campos de desglose de IVA de un ítem."""
|
|
181
|
+
taxed = item.net * item.taxable_share
|
|
182
|
+
exempt = item.net - taxed
|
|
183
|
+
iva = item.iva_amount
|
|
184
|
+
base = taxed - iva
|
|
185
|
+
|
|
186
|
+
breakdown: dict[str, Any] = {}
|
|
187
|
+
if item.iva_type is Iva.EXEMPT:
|
|
188
|
+
breakdown["amountExempt"] = _as_number(item.net)
|
|
189
|
+
return breakdown
|
|
190
|
+
|
|
191
|
+
if item.iva_type.rate == 0.10:
|
|
192
|
+
breakdown["amount10Percent"] = _as_number(_round(taxed))
|
|
193
|
+
breakdown["taxed10Percent"] = _as_number(_round(base))
|
|
194
|
+
breakdown["iva10Percent"] = _as_number(iva)
|
|
195
|
+
else:
|
|
196
|
+
breakdown["amount5Percent"] = _as_number(_round(taxed))
|
|
197
|
+
breakdown["taxed5Percent"] = _as_number(_round(base))
|
|
198
|
+
breakdown["iva5Percent"] = _as_number(iva)
|
|
199
|
+
|
|
200
|
+
if exempt:
|
|
201
|
+
breakdown["amountExempt"] = _as_number(_round(exempt))
|
|
202
|
+
return breakdown
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def totals_for(
|
|
206
|
+
items: Sequence[Item],
|
|
207
|
+
*,
|
|
208
|
+
global_discount: float | int | Decimal = 0,
|
|
209
|
+
sedeco_discount: float | int | Decimal = 0,
|
|
210
|
+
) -> dict[str, Any]:
|
|
211
|
+
"""Totales del documento a partir de sus ítems.
|
|
212
|
+
|
|
213
|
+
Devuelve ``amount`` más el desglose de IVA, listo para el cuerpo. El
|
|
214
|
+
``amount`` replica la fórmula que valida el servidor: suma de las líneas,
|
|
215
|
+
menos los descuentos por ítem, menos el global, menos el de SEDECO.
|
|
216
|
+
"""
|
|
217
|
+
if not items:
|
|
218
|
+
raise ValidationError("El documento necesita al menos un ítem.")
|
|
219
|
+
|
|
220
|
+
lines_total = sum((i.line_total for i in items), Decimal(0))
|
|
221
|
+
discounts = sum((i.line_discount for i in items), Decimal(0))
|
|
222
|
+
total = lines_total - discounts - _dec(global_discount) - _dec(sedeco_discount)
|
|
223
|
+
|
|
224
|
+
if total < 0:
|
|
225
|
+
all_discounts = discounts + _dec(global_discount) + _dec(sedeco_discount)
|
|
226
|
+
raise ValidationError(
|
|
227
|
+
f"Los descuentos ({_as_number(all_discounts)}) superan el total "
|
|
228
|
+
f"de los ítems ({_as_number(lines_total)})."
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
totals: dict[str, Any] = {"amount": _as_number(_round(total))}
|
|
232
|
+
|
|
233
|
+
accumulated: dict[str, Decimal] = {}
|
|
234
|
+
for item in items:
|
|
235
|
+
for field, value in _item_breakdown(item).items():
|
|
236
|
+
accumulated[field] = accumulated.get(field, Decimal(0)) + _dec(value)
|
|
237
|
+
|
|
238
|
+
for field, value in accumulated.items():
|
|
239
|
+
totals[field] = _as_number(_round(value))
|
|
240
|
+
|
|
241
|
+
return totals
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""El receptor del documento.
|
|
2
|
+
|
|
3
|
+
La API pide unos 18 campos con prefijo ``client*`` y reglas condicionales entre
|
|
4
|
+
ellos: la dirección es obligatoria si ``clientHasAddress`` es verdadero, salvo
|
|
5
|
+
que el cliente sea extranjero; los códigos de departamento, distrito y ciudad
|
|
6
|
+
son numéricos y no hay endpoint público para resolverlos.
|
|
7
|
+
|
|
8
|
+
:class:`Receptor` los agrupa detrás de constructores por tipo de cliente, que es
|
|
9
|
+
como se piensa el problema en la práctica: "le facturo a una persona", "le
|
|
10
|
+
facturo a una empresa", "es una venta sin nominar".
|
|
11
|
+
|
|
12
|
+
Una sola búsqueda geográfica resuelve los seis campos de dirección::
|
|
13
|
+
|
|
14
|
+
Receptor.person(
|
|
15
|
+
ruc="5000001-1",
|
|
16
|
+
name="Juan Pérez",
|
|
17
|
+
address="Av. España 1234",
|
|
18
|
+
house_number=1234,
|
|
19
|
+
city=smartdoc.geo.find_city("Asunción"),
|
|
20
|
+
)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from ..constants import countries
|
|
29
|
+
from ..constants.documents import ClientType
|
|
30
|
+
from ..errors import ValidationError
|
|
31
|
+
from ..geo import City
|
|
32
|
+
|
|
33
|
+
__all__ = ["Recipient"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Recipient:
|
|
38
|
+
"""Datos del receptor de un documento.
|
|
39
|
+
|
|
40
|
+
En general no se instancia directo: se usan los constructores
|
|
41
|
+
:meth:`person`, :meth:`entity`, :meth:`foreign`, :meth:`not_nominated`,
|
|
42
|
+
:meth:`government`, :meth:`diplomatic` o :meth:`from_client_id`.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
client_type: ClientType
|
|
46
|
+
ruc: str = ""
|
|
47
|
+
social_name: str = ""
|
|
48
|
+
fantasy_name: str | None = None
|
|
49
|
+
is_taxpayer: bool = False
|
|
50
|
+
country_code: str = countries.PARAGUAY
|
|
51
|
+
|
|
52
|
+
city: City | None = None
|
|
53
|
+
address: str | None = None
|
|
54
|
+
house_number: int | None = None
|
|
55
|
+
|
|
56
|
+
email: str | None = None
|
|
57
|
+
phone: str | None = None
|
|
58
|
+
code: str | None = None
|
|
59
|
+
client_id: int | None = None
|
|
60
|
+
|
|
61
|
+
#: Campos crudos, para lo que el SDK no modele.
|
|
62
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
63
|
+
|
|
64
|
+
def __post_init__(self) -> None:
|
|
65
|
+
self.client_type = ClientType.coerce(self.client_type)
|
|
66
|
+
if self.country_code:
|
|
67
|
+
self.country_code = countries.validate(self.country_code) or ""
|
|
68
|
+
|
|
69
|
+
if self.code is not None and not 3 <= len(str(self.code)) <= 15:
|
|
70
|
+
raise ValidationError(
|
|
71
|
+
f"El código del receptor tiene que tener entre 3 y 15 "
|
|
72
|
+
f"caracteres; {self.code!r} tiene {len(str(self.code))}. Si "
|
|
73
|
+
f"venís de un identificador corto, completalo: 'cliente-77' o "
|
|
74
|
+
f"f'{{id:04d}}'."
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# El extranjero es el único que puede tener dirección sin códigos
|
|
78
|
+
# geográficos: SIFEN no tiene catálogo para direcciones de afuera.
|
|
79
|
+
if (
|
|
80
|
+
self.address
|
|
81
|
+
and self.city is None
|
|
82
|
+
and self.client_type is not ClientType.FOREIGN_ENTITY
|
|
83
|
+
):
|
|
84
|
+
raise ValidationError(
|
|
85
|
+
"Cuando el receptor tiene dirección hacen falta los códigos de "
|
|
86
|
+
"departamento, distrito y ciudad. Pasá city=smartdoc.geo."
|
|
87
|
+
"find_city('...') y el SDK completa los seis campos."
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
# ─── Constructores ───────────────────────────────────────────────────────
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def person(
|
|
94
|
+
cls,
|
|
95
|
+
*,
|
|
96
|
+
ruc: str,
|
|
97
|
+
name: str,
|
|
98
|
+
is_taxpayer: bool = False,
|
|
99
|
+
**kw: Any,
|
|
100
|
+
) -> Recipient:
|
|
101
|
+
"""Una persona física.
|
|
102
|
+
|
|
103
|
+
``ruc`` es el RUC con dígito verificador, o la cédula si no es
|
|
104
|
+
contribuyente.
|
|
105
|
+
"""
|
|
106
|
+
return cls(
|
|
107
|
+
client_type=ClientType.PERSON,
|
|
108
|
+
ruc=ruc,
|
|
109
|
+
social_name=name,
|
|
110
|
+
is_taxpayer=is_taxpayer,
|
|
111
|
+
**kw,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
@classmethod
|
|
115
|
+
def entity(
|
|
116
|
+
cls,
|
|
117
|
+
*,
|
|
118
|
+
ruc: str,
|
|
119
|
+
social_name: str,
|
|
120
|
+
is_taxpayer: bool = True,
|
|
121
|
+
**kw: Any,
|
|
122
|
+
) -> Recipient:
|
|
123
|
+
"""Una empresa o entidad con RUC."""
|
|
124
|
+
return cls(
|
|
125
|
+
client_type=ClientType.ENTITY,
|
|
126
|
+
ruc=ruc,
|
|
127
|
+
social_name=social_name,
|
|
128
|
+
is_taxpayer=is_taxpayer,
|
|
129
|
+
**kw,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
@classmethod
|
|
133
|
+
def foreign(
|
|
134
|
+
cls,
|
|
135
|
+
*,
|
|
136
|
+
name: str,
|
|
137
|
+
country_code: str,
|
|
138
|
+
document_number: str = "",
|
|
139
|
+
**kw: Any,
|
|
140
|
+
) -> Recipient:
|
|
141
|
+
"""Un cliente del exterior.
|
|
142
|
+
|
|
143
|
+
Es el único tipo que puede llevar dirección sin códigos geográficos
|
|
144
|
+
paraguayos.
|
|
145
|
+
"""
|
|
146
|
+
return cls(
|
|
147
|
+
client_type=ClientType.FOREIGN_ENTITY,
|
|
148
|
+
ruc=document_number,
|
|
149
|
+
social_name=name,
|
|
150
|
+
country_code=country_code,
|
|
151
|
+
is_taxpayer=False,
|
|
152
|
+
**kw,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
@classmethod
|
|
156
|
+
def not_nominated(cls, **kw: Any) -> Recipient:
|
|
157
|
+
"""Venta sin identificar al comprador.
|
|
158
|
+
|
|
159
|
+
Es la factura innominada del mostrador. Se puede nominar después con
|
|
160
|
+
``sd.invoices.nominate(id, client_id=...)``.
|
|
161
|
+
"""
|
|
162
|
+
return cls(
|
|
163
|
+
client_type=ClientType.NOT_NOMINATED,
|
|
164
|
+
ruc="",
|
|
165
|
+
social_name="Sin Nombre",
|
|
166
|
+
is_taxpayer=False,
|
|
167
|
+
**kw,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
@classmethod
|
|
171
|
+
def government(cls, *, ruc: str, social_name: str, **kw: Any) -> Recipient:
|
|
172
|
+
"""Un organismo del Estado."""
|
|
173
|
+
return cls(
|
|
174
|
+
client_type=ClientType.GOVERNMENT,
|
|
175
|
+
ruc=ruc,
|
|
176
|
+
social_name=social_name,
|
|
177
|
+
is_taxpayer=True,
|
|
178
|
+
**kw,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
@classmethod
|
|
182
|
+
def diplomatic(cls, *, ruc: str, social_name: str, **kw: Any) -> Recipient:
|
|
183
|
+
"""Una misión diplomática con exoneración fiscal."""
|
|
184
|
+
return cls(
|
|
185
|
+
client_type=ClientType.DIPLOMATIC,
|
|
186
|
+
ruc=ruc,
|
|
187
|
+
social_name=social_name,
|
|
188
|
+
is_taxpayer=False,
|
|
189
|
+
**kw,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
@classmethod
|
|
193
|
+
def from_client_id(cls, client_id: int, **kw: Any) -> Recipient:
|
|
194
|
+
"""Un cliente ya cargado en SmartDoc, por su id.
|
|
195
|
+
|
|
196
|
+
Igual hay que dar los datos que van impresos en el documento; el id sirve
|
|
197
|
+
para que SmartDoc lo asocie a su ficha.
|
|
198
|
+
"""
|
|
199
|
+
return cls(client_id=client_id, **kw)
|
|
200
|
+
|
|
201
|
+
# ─── Serialización ───────────────────────────────────────────────────────
|
|
202
|
+
|
|
203
|
+
def to_api(self) -> dict[str, Any]:
|
|
204
|
+
"""Los campos ``client*`` que espera la API."""
|
|
205
|
+
has_address = self.address is not None
|
|
206
|
+
|
|
207
|
+
body: dict[str, Any] = {
|
|
208
|
+
"clientType": ClientType.coerce(self.client_type).value,
|
|
209
|
+
"clientRuc": self.ruc,
|
|
210
|
+
"clientSocialName": self.social_name,
|
|
211
|
+
"clientIsTaxPayer": self.is_taxpayer,
|
|
212
|
+
"clientCountryCode": self.country_code,
|
|
213
|
+
"clientHasAddress": has_address,
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if self.fantasy_name is not None:
|
|
217
|
+
body["clientFantasyName"] = self.fantasy_name
|
|
218
|
+
if self.email is not None:
|
|
219
|
+
body["clientEmail"] = self.email
|
|
220
|
+
if self.phone is not None:
|
|
221
|
+
body["clientPhoneNumber"] = self.phone
|
|
222
|
+
if self.code is not None:
|
|
223
|
+
body["clientCode"] = self.code
|
|
224
|
+
if self.client_id is not None:
|
|
225
|
+
body["clientId"] = self.client_id
|
|
226
|
+
|
|
227
|
+
if has_address:
|
|
228
|
+
body["clientAddress"] = self.address
|
|
229
|
+
if self.house_number is not None:
|
|
230
|
+
body["clientHouseNumber"] = self.house_number
|
|
231
|
+
if self.city is not None:
|
|
232
|
+
body.update(
|
|
233
|
+
{
|
|
234
|
+
"clientDepartment": self.city.department.code,
|
|
235
|
+
"clientDepartmentDescription": self.city.department.name,
|
|
236
|
+
"clientDistrict": self.city.district.code,
|
|
237
|
+
"clientDistrictDescription": self.city.district.name,
|
|
238
|
+
"clientCity": self.city.code,
|
|
239
|
+
"clientCityDescription": self.city.name,
|
|
240
|
+
}
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
body.update(self.extra)
|
|
244
|
+
return body
|
|
245
|
+
|
|
246
|
+
def validate_for(self, allowed_types: frozenset[ClientType]) -> None:
|
|
247
|
+
"""Verifica que este tipo de receptor sirva para el documento.
|
|
248
|
+
|
|
249
|
+
Los recibos, por ejemplo, aceptan solo persona, entidad y extranjero.
|
|
250
|
+
"""
|
|
251
|
+
if self.client_type not in allowed_types:
|
|
252
|
+
permitidos = ", ".join(sorted(t.value for t in allowed_types))
|
|
253
|
+
raise ValidationError(
|
|
254
|
+
f"Un receptor de tipo {self.client_type.value!r} no sirve para "
|
|
255
|
+
f"este documento. Tipos permitidos: {permitidos}."
|
|
256
|
+
)
|
smartdoc/client.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""El cliente síncrono."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from ._core.config import IssuerConfig
|
|
11
|
+
from ._core.transport import DEFAULT_BASE_URL, RetryPolicy, SyncTransport
|
|
12
|
+
from .errors import ConfigurationError
|
|
13
|
+
from .resources.auto_invoices import AutoInvoices
|
|
14
|
+
from .resources.invoices import Invoices
|
|
15
|
+
from .resources.notes import CreditNotes, DebitNotes
|
|
16
|
+
from .resources.receipts import Receipts
|
|
17
|
+
from .resources.remission_notes import RemissionNotes
|
|
18
|
+
from .resources.support import (
|
|
19
|
+
Clients,
|
|
20
|
+
DispatchPoints,
|
|
21
|
+
Establishments,
|
|
22
|
+
ReceivedDocuments,
|
|
23
|
+
Sandbox,
|
|
24
|
+
Stamps,
|
|
25
|
+
TaxPayerResource,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = ["Client"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Client:
|
|
32
|
+
"""Punto de entrada al SDK.
|
|
33
|
+
|
|
34
|
+
::
|
|
35
|
+
|
|
36
|
+
import smartdoc
|
|
37
|
+
|
|
38
|
+
sd = smartdoc.Client(api_key="pk_...")
|
|
39
|
+
|
|
40
|
+
factura = sd.invoices.create(
|
|
41
|
+
receptor=smartdoc.Receptor.entity(
|
|
42
|
+
ruc="80012345-1", social_name="Cliente S.A."
|
|
43
|
+
),
|
|
44
|
+
items=[smartdoc.Item("Consultoría", quantity=1, unit_amount=1_100_000)],
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
api_key: la API Key del contribuyente. Si no se pasa, se lee de
|
|
49
|
+
``SMARTDOC_API_KEY``.
|
|
50
|
+
base_url: la URL de la API v2. Si no se pasa, se lee de
|
|
51
|
+
``SMARTDOC_BASE_URL``, y si tampoco está, se usa la instancia de
|
|
52
|
+
producción. Solo hace falta indicarla con una instancia propia.
|
|
53
|
+
establishment: código de establecimiento por defecto. Solo hace falta si
|
|
54
|
+
el contribuyente tiene más de uno.
|
|
55
|
+
dispatch_point: punto de expedición por defecto. Ídem.
|
|
56
|
+
stamp: timbrado, como ``(identificador, fecha_inicio)``. Solo hace falta
|
|
57
|
+
si hay más de uno habilitado.
|
|
58
|
+
timeout: segundos de espera por solicitud.
|
|
59
|
+
max_retries: reintentos ante 429, 5xx y fallas de red.
|
|
60
|
+
rate_limit_per_second: regulación preventiva. La API permite 5 por
|
|
61
|
+
segundo; poner ``0`` la desactiva.
|
|
62
|
+
auto_fill: si el SDK completa los datos del emisor. Apagarlo obliga a
|
|
63
|
+
mandar los siete campos en cada documento.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
api_key: str | None = None,
|
|
69
|
+
*,
|
|
70
|
+
base_url: str | None = None,
|
|
71
|
+
establishment: str | int | None = None,
|
|
72
|
+
dispatch_point: str | int | None = None,
|
|
73
|
+
stamp: tuple[str, str] | str | None = None,
|
|
74
|
+
timeout: float = 30.0,
|
|
75
|
+
max_retries: int = 3,
|
|
76
|
+
rate_limit_per_second: float = 5.0,
|
|
77
|
+
auto_fill: bool = True,
|
|
78
|
+
http_client: httpx.Client | None = None,
|
|
79
|
+
) -> None:
|
|
80
|
+
key = api_key or os.environ.get("SMARTDOC_API_KEY")
|
|
81
|
+
if not key:
|
|
82
|
+
raise ConfigurationError(
|
|
83
|
+
"Falta la API Key. Pasala como Client(api_key='pk_...') o "
|
|
84
|
+
"poné la variable de entorno SMARTDOC_API_KEY."
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
self._transport = SyncTransport(
|
|
88
|
+
api_key=key,
|
|
89
|
+
base_url=base_url
|
|
90
|
+
or os.environ.get("SMARTDOC_BASE_URL")
|
|
91
|
+
or DEFAULT_BASE_URL,
|
|
92
|
+
timeout=timeout,
|
|
93
|
+
retry=RetryPolicy(max_retries=max_retries),
|
|
94
|
+
rate_limit_per_second=rate_limit_per_second,
|
|
95
|
+
client=http_client,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
identifier, begin_date = _split_stamp(stamp)
|
|
99
|
+
self._config = IssuerConfig(
|
|
100
|
+
_request=self._transport.request,
|
|
101
|
+
stamp_identifier=identifier,
|
|
102
|
+
stamp_begin_date=begin_date,
|
|
103
|
+
establishment=establishment,
|
|
104
|
+
dispatch_point=dispatch_point,
|
|
105
|
+
auto_fill=auto_fill,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
# Documentos electrónicos
|
|
109
|
+
self.invoices = Invoices(self._transport, self._config)
|
|
110
|
+
self.receipts = Receipts(self._transport, self._config)
|
|
111
|
+
self.credit_notes = CreditNotes(self._transport, self._config)
|
|
112
|
+
self.debit_notes = DebitNotes(self._transport, self._config)
|
|
113
|
+
self.remission_notes = RemissionNotes(self._transport, self._config)
|
|
114
|
+
self.auto_invoices = AutoInvoices(self._transport, self._config)
|
|
115
|
+
|
|
116
|
+
# Recursos de soporte
|
|
117
|
+
self.stamps = Stamps(self._transport, self._config)
|
|
118
|
+
self.clients = Clients(self._transport, self._config)
|
|
119
|
+
self.establishments = Establishments(self._transport, self._config)
|
|
120
|
+
self.dispatch_points = DispatchPoints(self._transport, self._config)
|
|
121
|
+
self.received_documents = ReceivedDocuments(self._transport, self._config)
|
|
122
|
+
self.taxpayer_resource = TaxPayerResource(self._transport, self._config)
|
|
123
|
+
self.sandbox = Sandbox(self._transport)
|
|
124
|
+
|
|
125
|
+
# ─── Contribuyente ───────────────────────────────────────────────────────
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def taxpayer(self) -> Any:
|
|
129
|
+
"""El contribuyente de esta API Key. Se consulta una vez y se cachea."""
|
|
130
|
+
return self._config.taxpayer()
|
|
131
|
+
|
|
132
|
+
def refresh_config(self) -> None:
|
|
133
|
+
"""Olvida lo descubierto: contribuyente, timbrado, establecimiento y punto.
|
|
134
|
+
|
|
135
|
+
Hace falta si se cargó un timbrado nuevo mientras el proceso corría.
|
|
136
|
+
"""
|
|
137
|
+
self._config.refresh()
|
|
138
|
+
|
|
139
|
+
# ─── Ciclo de vida ───────────────────────────────────────────────────────
|
|
140
|
+
|
|
141
|
+
def close(self) -> None:
|
|
142
|
+
self._transport.close()
|
|
143
|
+
|
|
144
|
+
def __enter__(self) -> Client:
|
|
145
|
+
return self
|
|
146
|
+
|
|
147
|
+
def __exit__(self, *exc: Any) -> None:
|
|
148
|
+
self.close()
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _split_stamp(
|
|
152
|
+
stamp: tuple[str, str] | str | None,
|
|
153
|
+
) -> tuple[str | None, str | None]:
|
|
154
|
+
"""Acepta ``("12345678", "2024-01-01")`` o solo el identificador."""
|
|
155
|
+
if stamp is None:
|
|
156
|
+
return None, None
|
|
157
|
+
if isinstance(stamp, str):
|
|
158
|
+
return stamp, None
|
|
159
|
+
identifier, begin_date = stamp
|
|
160
|
+
return identifier, begin_date
|