odoo-api-client 4.0.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.
- odoo_api_client/__init__.py +745 -0
- odoo_api_client/models/__init__.py +6 -0
- odoo_api_client/models/account/__init__.py +6 -0
- odoo_api_client/models/account/move.py +267 -0
- odoo_api_client/models/account/move_line.py +31 -0
- odoo_api_client/models/account/move_send.py +37 -0
- odoo_api_client/models/account/payment.py +31 -0
- odoo_api_client/models/account/tax.py +31 -0
- odoo_api_client/models/helpdesk/__init__.py +6 -0
- odoo_api_client/models/helpdesk/helpdesk_team.py +31 -0
- odoo_api_client/models/helpdesk/helpdesk_ticket.py +208 -0
- odoo_api_client/models/ir/__init__.py +6 -0
- odoo_api_client/models/ir/attachment.py +32 -0
- odoo_api_client/models/l10n_cl/__init__.py +6 -0
- odoo_api_client/models/l10n_cl/account/__init__.py +6 -0
- odoo_api_client/models/l10n_cl/account/invoice_reference.py +35 -0
- odoo_api_client/models/l10n_latam/__init__.py +6 -0
- odoo_api_client/models/l10n_latam/document/__init__.py +6 -0
- odoo_api_client/models/l10n_latam/document/type.py +33 -0
- odoo_api_client/models/l10n_latam/identification/__init__.py +6 -0
- odoo_api_client/models/l10n_latam/identification/type.py +28 -0
- odoo_api_client/models/mail/__init__.py +6 -0
- odoo_api_client/models/mail/alias.py +27 -0
- odoo_api_client/models/mail/followers.py +194 -0
- odoo_api_client/models/mail/message.py +27 -0
- odoo_api_client/models/mailing/__init__.py +5 -0
- odoo_api_client/models/mailing/contact.py +37 -0
- odoo_api_client/models/mailing/optout.py +63 -0
- odoo_api_client/models/mailing/subscription.py +491 -0
- odoo_api_client/models/payment/__init__.py +6 -0
- odoo_api_client/models/payment/transaction.py +28 -0
- odoo_api_client/models/product/__init__.py +6 -0
- odoo_api_client/models/product/template.py +34 -0
- odoo_api_client/models/res/__init__.py +6 -0
- odoo_api_client/models/res/company.py +28 -0
- odoo_api_client/models/res/country.py +27 -0
- odoo_api_client/models/res/partner.py +27 -0
- odoo_api_client/models/res/user.py +27 -0
- odoo_api_client/models/sale/__init__.py +6 -0
- odoo_api_client/models/sale/order.py +236 -0
- odoo_api_client/models/sale/order_line.py +33 -0
- odoo_api_client/py.typed +0 -0
- odoo_api_client-4.0.0.dist-info/METADATA +112 -0
- odoo_api_client-4.0.0.dist-info/RECORD +47 -0
- odoo_api_client-4.0.0.dist-info/WHEEL +5 -0
- odoo_api_client-4.0.0.dist-info/licenses/LICENSE.md +83 -0
- odoo_api_client-4.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,745 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Odoo: Cliente de API en Python.
|
|
3
|
+
# Copyright (C) Dinn Odoo <https://www.dinnodoo.com>
|
|
4
|
+
#
|
|
5
|
+
|
|
6
|
+
"""
|
|
7
|
+
Cliente de API para Odoo en Python.
|
|
8
|
+
|
|
9
|
+
Este paquete proporciona clases y utilidades para interactuar con la API
|
|
10
|
+
de Odoo mediante XML-RPC, facilitando operaciones CRUD y consultas en
|
|
11
|
+
modelos de Odoo.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import time
|
|
15
|
+
import xmlrpc.client
|
|
16
|
+
from collections.abc import Mapping, Sequence
|
|
17
|
+
from os import getenv
|
|
18
|
+
from typing import TypeIs
|
|
19
|
+
|
|
20
|
+
type OdooValue = (
|
|
21
|
+
bool | int | float | str | list[OdooValue] | dict[str, OdooValue] | None
|
|
22
|
+
)
|
|
23
|
+
"""
|
|
24
|
+
Valor entregado por Odoo mediante XML-RPC.
|
|
25
|
+
|
|
26
|
+
Los campos vacíos llegan como ``False`` y los many2one como
|
|
27
|
+
``[id, nombre]``.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
type OdooRecord = dict[str, OdooValue]
|
|
31
|
+
"""Registro de Odoo: diccionario con el nombre del campo y su valor."""
|
|
32
|
+
|
|
33
|
+
type OdooParam = (
|
|
34
|
+
bool
|
|
35
|
+
| int
|
|
36
|
+
| float
|
|
37
|
+
| str
|
|
38
|
+
| Sequence[OdooParam]
|
|
39
|
+
| Mapping[str, OdooParam]
|
|
40
|
+
| None
|
|
41
|
+
)
|
|
42
|
+
"""Valor que se puede enviar a Odoo mediante XML-RPC."""
|
|
43
|
+
|
|
44
|
+
type OdooDomain = Sequence[OdooParam]
|
|
45
|
+
"""Dominio de búsqueda (``[['campo', '=', valor]]``) o listado de IDs."""
|
|
46
|
+
|
|
47
|
+
type OdooKwargs = Mapping[str, OdooParam]
|
|
48
|
+
"""Argumentos con nombre de una acción (``fields``, ``limit``, etc.)."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _is_list(value: object) -> TypeIs[list[object]]:
|
|
52
|
+
"""
|
|
53
|
+
Indica si un valor sin tipo conocido es una lista.
|
|
54
|
+
|
|
55
|
+
:param object value: Valor a revisar.
|
|
56
|
+
:return: Si el valor es una lista.
|
|
57
|
+
:rtype: bool
|
|
58
|
+
"""
|
|
59
|
+
return isinstance(value, list)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _is_dict(value: object) -> TypeIs[dict[object, object]]:
|
|
63
|
+
"""
|
|
64
|
+
Indica si un valor sin tipo conocido es un diccionario.
|
|
65
|
+
|
|
66
|
+
:param object value: Valor a revisar.
|
|
67
|
+
:return: Si el valor es un diccionario.
|
|
68
|
+
:rtype: bool
|
|
69
|
+
"""
|
|
70
|
+
return isinstance(value, dict)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _is_int(value: object) -> TypeIs[int]:
|
|
74
|
+
"""
|
|
75
|
+
Indica si un valor es un entero (``bool`` no se considera entero).
|
|
76
|
+
|
|
77
|
+
:param object value: Valor a revisar.
|
|
78
|
+
:return: Si el valor es un entero.
|
|
79
|
+
:rtype: bool
|
|
80
|
+
"""
|
|
81
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _to_odoo_value(value: object) -> OdooValue:
|
|
85
|
+
"""
|
|
86
|
+
Valida una respuesta de XML-RPC y la entrega con su tipo.
|
|
87
|
+
|
|
88
|
+
:param object value: Respuesta de Odoo.
|
|
89
|
+
:return: La misma respuesta, con tipo.
|
|
90
|
+
:rtype: OdooValue
|
|
91
|
+
:raises ApiException: Si la respuesta contiene un valor que Odoo no
|
|
92
|
+
entrega mediante XML-RPC.
|
|
93
|
+
"""
|
|
94
|
+
if value is None or isinstance(value, bool | int | float | str):
|
|
95
|
+
return value
|
|
96
|
+
if _is_list(value):
|
|
97
|
+
return [_to_odoo_value(item) for item in value]
|
|
98
|
+
if _is_dict(value):
|
|
99
|
+
record: OdooRecord = {}
|
|
100
|
+
for key, item in value.items():
|
|
101
|
+
if not isinstance(key, str):
|
|
102
|
+
raise ApiException(
|
|
103
|
+
'Odoo entregó un registro con un campo que no es texto.'
|
|
104
|
+
)
|
|
105
|
+
record[key] = _to_odoo_value(item)
|
|
106
|
+
return record
|
|
107
|
+
raise ApiException(
|
|
108
|
+
f'Odoo entregó un valor de tipo no soportado: {type(value).__name__}.'
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _to_xmlrpc(value: OdooParam) -> OdooValue:
|
|
113
|
+
"""
|
|
114
|
+
Convierte un valor a enviar a Odoo a listas y diccionarios.
|
|
115
|
+
|
|
116
|
+
XML-RPC solo envía listas, tuplas y diccionarios, por lo que otras
|
|
117
|
+
secuencias o mapeos se convierten.
|
|
118
|
+
|
|
119
|
+
:param OdooParam value: Valor a enviar.
|
|
120
|
+
:return: El valor con listas y diccionarios.
|
|
121
|
+
:rtype: OdooValue
|
|
122
|
+
"""
|
|
123
|
+
if value is None or isinstance(value, bool | int | float | str):
|
|
124
|
+
return value
|
|
125
|
+
if isinstance(value, Mapping):
|
|
126
|
+
return {key: _to_xmlrpc(item) for key, item in value.items()}
|
|
127
|
+
return [_to_xmlrpc(item) for item in value]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def many2one_id(value: OdooValue) -> int | None:
|
|
131
|
+
"""
|
|
132
|
+
Obtiene el ID de un campo many2one de Odoo.
|
|
133
|
+
|
|
134
|
+
:param OdooValue value: Valor del campo (``[id, nombre]`` o
|
|
135
|
+
``False`` si está vacío).
|
|
136
|
+
:return: ID del registro relacionado, o None si el campo está
|
|
137
|
+
vacío.
|
|
138
|
+
:rtype: int | None
|
|
139
|
+
"""
|
|
140
|
+
if isinstance(value, list) and value and _is_int(value[0]):
|
|
141
|
+
return value[0]
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def many2one_name(value: OdooValue) -> str | None:
|
|
146
|
+
"""
|
|
147
|
+
Obtiene el nombre de un campo many2one de Odoo.
|
|
148
|
+
|
|
149
|
+
:param OdooValue value: Valor del campo (``[id, nombre]`` o
|
|
150
|
+
``False`` si está vacío).
|
|
151
|
+
:return: Nombre del registro relacionado, o None si el campo está
|
|
152
|
+
vacío.
|
|
153
|
+
:rtype: str | None
|
|
154
|
+
"""
|
|
155
|
+
if isinstance(value, list) and len(value) > 1:
|
|
156
|
+
name = value[1]
|
|
157
|
+
if isinstance(name, str):
|
|
158
|
+
return name
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def record_id(record: OdooRecord) -> int:
|
|
163
|
+
"""
|
|
164
|
+
Obtiene el ID de un registro de Odoo.
|
|
165
|
+
|
|
166
|
+
:param OdooRecord record: Registro leído desde Odoo.
|
|
167
|
+
:return: ID del registro.
|
|
168
|
+
:rtype: int
|
|
169
|
+
:raises ApiException: Si el registro no tiene un ID válido.
|
|
170
|
+
"""
|
|
171
|
+
value = record.get('id')
|
|
172
|
+
if _is_int(value):
|
|
173
|
+
return value
|
|
174
|
+
raise ApiException('El registro de Odoo no tiene un ID válido.')
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class ApiClient:
|
|
178
|
+
|
|
179
|
+
"""
|
|
180
|
+
Cliente para interactuar con una API de Odoo usando XML-RPC.
|
|
181
|
+
|
|
182
|
+
:param str api_host: Host de la API. Si no se proporciona, se
|
|
183
|
+
intentará obtener de una variable de entorno.
|
|
184
|
+
:param str api_database: Base de datos de la API. Si no se
|
|
185
|
+
proporciona, se intentará obtener de una variable de entorno.
|
|
186
|
+
:param str api_user: Usuario de la API. Si no se proporciona,
|
|
187
|
+
se intentará obtener de una variable de entorno.
|
|
188
|
+
:param str api_password: Contraseña de la API. Si no se
|
|
189
|
+
proporciona, se intentará obtener de una variable de entorno.
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
api_uid: int | None = None
|
|
193
|
+
|
|
194
|
+
def __init__(
|
|
195
|
+
self,
|
|
196
|
+
api_host: str | None = None,
|
|
197
|
+
api_database: str | None = None,
|
|
198
|
+
api_user: str | None = None,
|
|
199
|
+
api_password: str | None = None,
|
|
200
|
+
) -> None:
|
|
201
|
+
"""Inicializa el cliente API con los detalles de conexión."""
|
|
202
|
+
self.api_host = self.__validate_api_host(api_host)
|
|
203
|
+
self.api_database = self.__validate_api_database(api_database)
|
|
204
|
+
self.api_user = self.__validate_api_user(api_user)
|
|
205
|
+
self.api_password = self.__validate_api_password(api_password)
|
|
206
|
+
if self.api_uid is None:
|
|
207
|
+
self.api_uid = self.__get_api_uid()
|
|
208
|
+
self._api_xmlrpc = xmlrpc.client.ServerProxy(
|
|
209
|
+
f'{self.api_host}/xmlrpc/2/object'
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
def __validate_api_host(self, api_host: str | None) -> str:
|
|
213
|
+
"""
|
|
214
|
+
Valida y retorna el host de la API.
|
|
215
|
+
|
|
216
|
+
:param str api_host: Host de la API a validar.
|
|
217
|
+
:return: Host validado.
|
|
218
|
+
:rtype: str
|
|
219
|
+
:raises ApiException: Si el host no es válido o está ausente.
|
|
220
|
+
"""
|
|
221
|
+
api_host = api_host or getenv('ODOO_API_HOST')
|
|
222
|
+
if not api_host:
|
|
223
|
+
raise ApiException('ODOO_API_HOST missing')
|
|
224
|
+
return api_host.strip()
|
|
225
|
+
|
|
226
|
+
def __validate_api_database(self, api_database: str | None) -> str:
|
|
227
|
+
"""
|
|
228
|
+
Valida y retorna el nombre de la base de datos de la API.
|
|
229
|
+
|
|
230
|
+
:param str api_database: Nombre de la base de datos a validar.
|
|
231
|
+
:return: Nombre de la base de datos validado.
|
|
232
|
+
:rtype: str
|
|
233
|
+
:raises ApiException: Si la base de datos no es válida o está ausente.
|
|
234
|
+
"""
|
|
235
|
+
api_database = api_database or getenv('ODOO_API_DATABASE')
|
|
236
|
+
if not api_database:
|
|
237
|
+
raise ApiException('ODOO_API_DATABASE missing')
|
|
238
|
+
return api_database.strip()
|
|
239
|
+
|
|
240
|
+
def __validate_api_user(self, api_user: str | None) -> str:
|
|
241
|
+
"""
|
|
242
|
+
Valida y retorna el usuario de la API.
|
|
243
|
+
|
|
244
|
+
:param str api_user: Usuario de la API a validar.
|
|
245
|
+
:return: Usuario validado.
|
|
246
|
+
:rtype: str
|
|
247
|
+
:raises ApiException: Si el usuario no es válido o está ausente.
|
|
248
|
+
"""
|
|
249
|
+
api_user = api_user or getenv('ODOO_API_USER')
|
|
250
|
+
if not api_user:
|
|
251
|
+
raise ApiException('ODOO_API_USER missing')
|
|
252
|
+
return api_user.strip()
|
|
253
|
+
|
|
254
|
+
def __validate_api_password(self, api_password: str | None) -> str:
|
|
255
|
+
"""
|
|
256
|
+
Valida y retorna la contraseña de la API.
|
|
257
|
+
|
|
258
|
+
:param str api_password: Contraseña de la API a validar.
|
|
259
|
+
:return: Contraseña validada.
|
|
260
|
+
:rtype: str
|
|
261
|
+
:raises ApiException: Si la contraseña no es válida o está ausente.
|
|
262
|
+
"""
|
|
263
|
+
api_password = api_password or getenv('ODOO_API_PASSWORD')
|
|
264
|
+
if not api_password:
|
|
265
|
+
raise ApiException('ODOO_API_PASSWORD missing')
|
|
266
|
+
return api_password.strip()
|
|
267
|
+
|
|
268
|
+
def __get_api_uid(self) -> int:
|
|
269
|
+
"""
|
|
270
|
+
Obtiene el UID del usuario de la API.
|
|
271
|
+
|
|
272
|
+
:return: UID del usuario.
|
|
273
|
+
:rtype: int
|
|
274
|
+
:raises ApiException: Si hay un error al obtener el UID o si
|
|
275
|
+
Odoo rechaza las credenciales.
|
|
276
|
+
"""
|
|
277
|
+
try:
|
|
278
|
+
common = xmlrpc.client.ServerProxy(
|
|
279
|
+
f'{self.api_host}/xmlrpc/2/common'
|
|
280
|
+
)
|
|
281
|
+
api_uid: object = common.authenticate(
|
|
282
|
+
self.api_database, self.api_user, self.api_password, {}
|
|
283
|
+
)
|
|
284
|
+
except xmlrpc.client.ProtocolError as e:
|
|
285
|
+
raise ApiException(
|
|
286
|
+
f'Error de protocolo al realizar la solicitud XML-RPC: {e!s}'
|
|
287
|
+
) from e
|
|
288
|
+
except xmlrpc.client.Fault as e:
|
|
289
|
+
raise ApiException(
|
|
290
|
+
f'Error de protocolo al realizar la solicitud XML-RPC: {e!s}'
|
|
291
|
+
) from e
|
|
292
|
+
# Odoo entrega False cuando el usuario o la contraseña no son
|
|
293
|
+
# válidos.
|
|
294
|
+
if not _is_int(api_uid):
|
|
295
|
+
raise ApiException(
|
|
296
|
+
'No fue posible autenticar en Odoo: revisar la base de '
|
|
297
|
+
'datos, el usuario y la contraseña de la API.'
|
|
298
|
+
)
|
|
299
|
+
return api_uid
|
|
300
|
+
|
|
301
|
+
def _execute_kw(
|
|
302
|
+
self, model: str, method: str, *arguments: OdooParam
|
|
303
|
+
) -> OdooValue:
|
|
304
|
+
"""
|
|
305
|
+
Ejecuta un método de un modelo mediante XML-RPC.
|
|
306
|
+
|
|
307
|
+
:param str model: Nombre del modelo.
|
|
308
|
+
:param str method: Método del modelo a ejecutar.
|
|
309
|
+
:param arguments: Argumentos de ``execute_kw`` después del
|
|
310
|
+
método (argumentos posicionales y con nombre del método).
|
|
311
|
+
:return: Respuesta de Odoo.
|
|
312
|
+
:rtype: OdooValue
|
|
313
|
+
"""
|
|
314
|
+
result: object = self._api_xmlrpc.execute_kw(
|
|
315
|
+
self.api_database,
|
|
316
|
+
self.api_uid,
|
|
317
|
+
self.api_password,
|
|
318
|
+
model,
|
|
319
|
+
method,
|
|
320
|
+
*[_to_xmlrpc(argument) for argument in arguments],
|
|
321
|
+
)
|
|
322
|
+
return _to_odoo_value(result)
|
|
323
|
+
|
|
324
|
+
def client_execute_kw(
|
|
325
|
+
self,
|
|
326
|
+
model: str,
|
|
327
|
+
action: str,
|
|
328
|
+
domains: OdooDomain | None = None,
|
|
329
|
+
action_data: OdooKwargs | OdooDomain | None = None,
|
|
330
|
+
) -> OdooValue:
|
|
331
|
+
"""
|
|
332
|
+
Ejecuta una acción en el modelo especificado de la API.
|
|
333
|
+
|
|
334
|
+
:param str model: Nombre del modelo en el que se ejecutará
|
|
335
|
+
la acción.
|
|
336
|
+
:param str action: Acción a ejecutar en el modelo.
|
|
337
|
+
:param list domains: Dominios para filtrar los datos
|
|
338
|
+
(opcional).
|
|
339
|
+
:param dict action_data: Datos adicionales para la acción
|
|
340
|
+
(opcional).
|
|
341
|
+
:return: Resultado de la acción ejecutada.
|
|
342
|
+
:rtype: OdooValue
|
|
343
|
+
:raises ApiException: Si los argumentos no son válidos, si
|
|
344
|
+
hay un error en la ejecución o si la respuesta de Odoo no
|
|
345
|
+
es válida.
|
|
346
|
+
"""
|
|
347
|
+
if domains is None:
|
|
348
|
+
domains = []
|
|
349
|
+
if action_data is None:
|
|
350
|
+
action_data = {}
|
|
351
|
+
# Tiempo de espera para evitar el error 429.
|
|
352
|
+
time.sleep(2)
|
|
353
|
+
if action not in {'create', 'create_context'}:
|
|
354
|
+
if len(domains) == 0:
|
|
355
|
+
raise ApiException(
|
|
356
|
+
"El argumento 'domains' no debe ser una lista vacía."
|
|
357
|
+
)
|
|
358
|
+
if action == 'write' and not isinstance(action_data, Mapping):
|
|
359
|
+
raise ApiException(
|
|
360
|
+
"Para la acción 'write', 'action_data' debe ser un "
|
|
361
|
+
'diccionario.'
|
|
362
|
+
)
|
|
363
|
+
try:
|
|
364
|
+
if action == 'create':
|
|
365
|
+
return self._execute_kw(model, action, action_data)
|
|
366
|
+
if action == 'create_context':
|
|
367
|
+
return self._execute_kw(model, 'create', domains, action_data)
|
|
368
|
+
if action == 'write':
|
|
369
|
+
return self._execute_kw(model, action, [domains, action_data])
|
|
370
|
+
return self._execute_kw(model, action, [domains], action_data)
|
|
371
|
+
except xmlrpc.client.Fault as e:
|
|
372
|
+
raise ApiException(
|
|
373
|
+
f'Error al ejecutar la petición al modelo {model}. '
|
|
374
|
+
f'Código de error {e.faultCode}. Error '
|
|
375
|
+
f'{e.faultString}',
|
|
376
|
+
code=e.faultCode,
|
|
377
|
+
) from e
|
|
378
|
+
except ValueError as e:
|
|
379
|
+
raise ApiException(
|
|
380
|
+
f'Error al ejecutar la petición al modelo {model}. '
|
|
381
|
+
f'Error: {e!s}'
|
|
382
|
+
) from e
|
|
383
|
+
except xmlrpc.client.ProtocolError as e:
|
|
384
|
+
raise ApiException(
|
|
385
|
+
f'Error de protocolo al realizar la solicitud XML-RPC: {e!s}'
|
|
386
|
+
) from e
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
class ApiException(Exception):
|
|
390
|
+
|
|
391
|
+
"""
|
|
392
|
+
Excepción personalizada para errores en el cliente de la API.
|
|
393
|
+
|
|
394
|
+
:param str message: Mensaje de error.
|
|
395
|
+
:param int code: Código de error (opcional).
|
|
396
|
+
:param dict params: Parámetros adicionales del error (opcional).
|
|
397
|
+
"""
|
|
398
|
+
|
|
399
|
+
def __init__(
|
|
400
|
+
self,
|
|
401
|
+
message: str,
|
|
402
|
+
code: int | None = None,
|
|
403
|
+
params: Mapping[str, object] | None = None,
|
|
404
|
+
) -> None:
|
|
405
|
+
"""
|
|
406
|
+
Inicializa la excepción.
|
|
407
|
+
|
|
408
|
+
Configura el mensaje, código y parámetros adicionales.
|
|
409
|
+
"""
|
|
410
|
+
self.message = message
|
|
411
|
+
self.code = code
|
|
412
|
+
self.params = params
|
|
413
|
+
super().__init__(message)
|
|
414
|
+
|
|
415
|
+
def __str__(self) -> str:
|
|
416
|
+
"""
|
|
417
|
+
Devuelve una representación en cadena del error.
|
|
418
|
+
|
|
419
|
+
Proporciona un contexto claro del problema ocurrido. Esta
|
|
420
|
+
representación incluye el prefijo "[Odoo]", seguido del
|
|
421
|
+
código de error si está presente, y el mensaje de error.
|
|
422
|
+
|
|
423
|
+
Si se especifica un código de error, el formato será:
|
|
424
|
+
"[Odoo] Error {code}: {message}"
|
|
425
|
+
|
|
426
|
+
Si no se especifica un código de error, el formato será:
|
|
427
|
+
"[Odoo] {message}"
|
|
428
|
+
|
|
429
|
+
:return: Una cadena que representa el error de una manera
|
|
430
|
+
clara y concisa.
|
|
431
|
+
"""
|
|
432
|
+
if self.code is not None:
|
|
433
|
+
return f'[Odoo] Error {self.code}: {self.message}'
|
|
434
|
+
else:
|
|
435
|
+
return f'[Odoo] {self.message}'
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _unexpected_response(model: str, action: str) -> ApiException:
|
|
439
|
+
"""
|
|
440
|
+
Crea el error para una respuesta de Odoo con un tipo inesperado.
|
|
441
|
+
|
|
442
|
+
:param str model: Modelo consultado.
|
|
443
|
+
:param str action: Acción ejecutada.
|
|
444
|
+
:return: Excepción a lanzar.
|
|
445
|
+
:rtype: ApiException
|
|
446
|
+
"""
|
|
447
|
+
return ApiException(
|
|
448
|
+
f"Odoo entregó una respuesta inesperada para '{action}' en el "
|
|
449
|
+
f'modelo {model}.'
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _as_records(value: OdooValue, model: str, action: str) -> list[OdooRecord]:
|
|
454
|
+
"""
|
|
455
|
+
Valida que la respuesta de Odoo sea un listado de registros.
|
|
456
|
+
|
|
457
|
+
:param OdooValue value: Respuesta de Odoo.
|
|
458
|
+
:param str model: Modelo consultado.
|
|
459
|
+
:param str action: Acción ejecutada.
|
|
460
|
+
:return: Registros entregados por Odoo.
|
|
461
|
+
:rtype: list[OdooRecord]
|
|
462
|
+
:raises ApiException: Si la respuesta no es un listado de
|
|
463
|
+
registros.
|
|
464
|
+
"""
|
|
465
|
+
if not isinstance(value, list):
|
|
466
|
+
raise _unexpected_response(model, action)
|
|
467
|
+
records: list[OdooRecord] = []
|
|
468
|
+
for item in value:
|
|
469
|
+
if not isinstance(item, dict):
|
|
470
|
+
raise _unexpected_response(model, action)
|
|
471
|
+
records.append(item)
|
|
472
|
+
return records
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _as_ids(value: OdooValue, model: str, action: str) -> list[int]:
|
|
476
|
+
"""
|
|
477
|
+
Valida que la respuesta de Odoo sea un listado de IDs.
|
|
478
|
+
|
|
479
|
+
:param OdooValue value: Respuesta de Odoo.
|
|
480
|
+
:param str model: Modelo consultado.
|
|
481
|
+
:param str action: Acción ejecutada.
|
|
482
|
+
:return: IDs entregados por Odoo.
|
|
483
|
+
:rtype: list[int]
|
|
484
|
+
:raises ApiException: Si la respuesta no es un listado de IDs.
|
|
485
|
+
"""
|
|
486
|
+
if not isinstance(value, list):
|
|
487
|
+
raise _unexpected_response(model, action)
|
|
488
|
+
ids: list[int] = []
|
|
489
|
+
for item in value:
|
|
490
|
+
if not _is_int(item):
|
|
491
|
+
raise _unexpected_response(model, action)
|
|
492
|
+
ids.append(item)
|
|
493
|
+
return ids
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _as_int(value: OdooValue, model: str, action: str) -> int:
|
|
497
|
+
"""
|
|
498
|
+
Valida que la respuesta de Odoo sea un entero.
|
|
499
|
+
|
|
500
|
+
:param OdooValue value: Respuesta de Odoo.
|
|
501
|
+
:param str model: Modelo consultado.
|
|
502
|
+
:param str action: Acción ejecutada.
|
|
503
|
+
:return: Entero entregado por Odoo.
|
|
504
|
+
:rtype: int
|
|
505
|
+
:raises ApiException: Si la respuesta no es un entero.
|
|
506
|
+
"""
|
|
507
|
+
if not _is_int(value):
|
|
508
|
+
raise _unexpected_response(model, action)
|
|
509
|
+
return value
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _as_bool(value: OdooValue, model: str, action: str) -> bool:
|
|
513
|
+
"""
|
|
514
|
+
Valida que la respuesta de Odoo sea un booleano.
|
|
515
|
+
|
|
516
|
+
:param OdooValue value: Respuesta de Odoo.
|
|
517
|
+
:param str model: Modelo consultado.
|
|
518
|
+
:param str action: Acción ejecutada.
|
|
519
|
+
:return: Booleano entregado por Odoo.
|
|
520
|
+
:rtype: bool
|
|
521
|
+
:raises ApiException: Si la respuesta no es un booleano.
|
|
522
|
+
"""
|
|
523
|
+
if not isinstance(value, bool):
|
|
524
|
+
raise _unexpected_response(model, action)
|
|
525
|
+
return value
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
class ApiBase:
|
|
529
|
+
|
|
530
|
+
"""
|
|
531
|
+
Clase base para las clases que consumen la API (wrappers).
|
|
532
|
+
|
|
533
|
+
:param str api_host: Host de la API.
|
|
534
|
+
:param str api_database: Base de datos de la API.
|
|
535
|
+
:param str api_user: Usuario de la API.
|
|
536
|
+
:param str api_password: Contraseña de la API.
|
|
537
|
+
"""
|
|
538
|
+
|
|
539
|
+
model: str | None = None
|
|
540
|
+
|
|
541
|
+
def __init__(
|
|
542
|
+
self,
|
|
543
|
+
api_host: str | None = None,
|
|
544
|
+
api_database: str | None = None,
|
|
545
|
+
api_user: str | None = None,
|
|
546
|
+
api_password: str | None = None,
|
|
547
|
+
) -> None:
|
|
548
|
+
"""
|
|
549
|
+
Inicializa la base de la API.
|
|
550
|
+
|
|
551
|
+
Configura los detalles de conexión y autenticación.
|
|
552
|
+
"""
|
|
553
|
+
self.client = ApiClient(api_host, api_database, api_user, api_password)
|
|
554
|
+
|
|
555
|
+
def search(
|
|
556
|
+
self, domains: OdooDomain, action_data: OdooKwargs | None = None
|
|
557
|
+
) -> list[int]:
|
|
558
|
+
"""
|
|
559
|
+
Realiza una búsqueda en el modelo especificado de la API.
|
|
560
|
+
|
|
561
|
+
:param list domains: Dominios para filtrar los datos.
|
|
562
|
+
:param dict action_data: Datos adicionales para la acción
|
|
563
|
+
(opcional).
|
|
564
|
+
:return: IDs de los registros encontrados.
|
|
565
|
+
:rtype: list[int]
|
|
566
|
+
"""
|
|
567
|
+
if action_data is None:
|
|
568
|
+
action_data = {}
|
|
569
|
+
if not self.model:
|
|
570
|
+
raise ApiException('El modelo no está definido')
|
|
571
|
+
return _as_ids(
|
|
572
|
+
self.client.client_execute_kw(
|
|
573
|
+
self.model, 'search', domains=domains, action_data=action_data
|
|
574
|
+
),
|
|
575
|
+
self.model,
|
|
576
|
+
'search',
|
|
577
|
+
)
|
|
578
|
+
|
|
579
|
+
def search_read(
|
|
580
|
+
self, domains: OdooDomain, action_data: OdooKwargs | None = None
|
|
581
|
+
) -> list[OdooRecord]:
|
|
582
|
+
"""
|
|
583
|
+
Realiza una búsqueda y devuelve los registros leídos.
|
|
584
|
+
|
|
585
|
+
:param list domains: Dominios para filtrar los datos.
|
|
586
|
+
:param dict action_data: Datos adicionales para la acción
|
|
587
|
+
(opcional).
|
|
588
|
+
:return: Registros leídos.
|
|
589
|
+
:rtype: list[OdooRecord]
|
|
590
|
+
"""
|
|
591
|
+
if action_data is None:
|
|
592
|
+
action_data = {}
|
|
593
|
+
if not self.model:
|
|
594
|
+
raise ApiException('El modelo no está definido')
|
|
595
|
+
return _as_records(
|
|
596
|
+
self.client.client_execute_kw(
|
|
597
|
+
self.model,
|
|
598
|
+
'search_read',
|
|
599
|
+
domains=domains,
|
|
600
|
+
action_data=action_data,
|
|
601
|
+
),
|
|
602
|
+
self.model,
|
|
603
|
+
'search_read',
|
|
604
|
+
)
|
|
605
|
+
|
|
606
|
+
def search_count(
|
|
607
|
+
self, domains: OdooDomain, action_data: OdooKwargs | None = None
|
|
608
|
+
) -> int:
|
|
609
|
+
"""
|
|
610
|
+
Cuenta registros que cumplen los dominios especificados.
|
|
611
|
+
|
|
612
|
+
:param list domains: Dominios para filtrar los datos.
|
|
613
|
+
:param dict action_data: Datos adicionales para la acción
|
|
614
|
+
(opcional).
|
|
615
|
+
:return: Número de registros encontrados.
|
|
616
|
+
:rtype: int
|
|
617
|
+
"""
|
|
618
|
+
if action_data is None:
|
|
619
|
+
action_data = {}
|
|
620
|
+
if not self.model:
|
|
621
|
+
raise ApiException('El modelo no está definido')
|
|
622
|
+
return _as_int(
|
|
623
|
+
self.client.client_execute_kw(
|
|
624
|
+
self.model,
|
|
625
|
+
'search_count',
|
|
626
|
+
domains=domains,
|
|
627
|
+
action_data=action_data,
|
|
628
|
+
),
|
|
629
|
+
self.model,
|
|
630
|
+
'search_count',
|
|
631
|
+
)
|
|
632
|
+
|
|
633
|
+
def read(
|
|
634
|
+
self, domains: OdooDomain, action_data: OdooKwargs | None = None
|
|
635
|
+
) -> list[OdooRecord]:
|
|
636
|
+
"""
|
|
637
|
+
Lee los registros especificados del modelo.
|
|
638
|
+
|
|
639
|
+
:param list domains: IDs de los registros a leer.
|
|
640
|
+
:param dict action_data: Datos adicionales para la acción
|
|
641
|
+
(opcional).
|
|
642
|
+
:return: Registros leídos.
|
|
643
|
+
:rtype: list[OdooRecord]
|
|
644
|
+
"""
|
|
645
|
+
if action_data is None:
|
|
646
|
+
action_data = {}
|
|
647
|
+
if not self.model:
|
|
648
|
+
raise ApiException('El modelo no está definido')
|
|
649
|
+
return _as_records(
|
|
650
|
+
self.client.client_execute_kw(
|
|
651
|
+
self.model, 'read', domains=domains, action_data=action_data
|
|
652
|
+
),
|
|
653
|
+
self.model,
|
|
654
|
+
'read',
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
def create(self, action_data: OdooDomain) -> int:
|
|
658
|
+
"""
|
|
659
|
+
Crea un nuevo registro en el modelo.
|
|
660
|
+
|
|
661
|
+
:param list action_data: Argumentos de ``create``: un listado
|
|
662
|
+
con el diccionario de datos del nuevo registro.
|
|
663
|
+
:return: ID del registro creado.
|
|
664
|
+
:rtype: int
|
|
665
|
+
"""
|
|
666
|
+
if not self.model:
|
|
667
|
+
raise ApiException('El modelo no está definido')
|
|
668
|
+
return _as_int(
|
|
669
|
+
self.client.client_execute_kw(
|
|
670
|
+
self.model, 'create', action_data=action_data
|
|
671
|
+
),
|
|
672
|
+
self.model,
|
|
673
|
+
'create',
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
def write(self, domains: OdooDomain, action_data: OdooKwargs) -> bool:
|
|
677
|
+
"""
|
|
678
|
+
Actualiza los registros especificados del modelo.
|
|
679
|
+
|
|
680
|
+
:param list domains: Dominios para identificar los registros
|
|
681
|
+
a actualizar.
|
|
682
|
+
:param dict action_data: Datos a actualizar en los registros.
|
|
683
|
+
:return: True si la actualización fue exitosa, False en caso
|
|
684
|
+
contrario.
|
|
685
|
+
:rtype: bool
|
|
686
|
+
"""
|
|
687
|
+
if not self.model:
|
|
688
|
+
raise ApiException('El modelo no está definido')
|
|
689
|
+
return _as_bool(
|
|
690
|
+
self.client.client_execute_kw(
|
|
691
|
+
self.model, 'write', domains=domains, action_data=action_data
|
|
692
|
+
),
|
|
693
|
+
self.model,
|
|
694
|
+
'write',
|
|
695
|
+
)
|
|
696
|
+
|
|
697
|
+
def unlink(
|
|
698
|
+
self, domains: OdooDomain, action_data: OdooKwargs | None = None
|
|
699
|
+
) -> bool:
|
|
700
|
+
"""
|
|
701
|
+
Elimina los registros especificados del modelo.
|
|
702
|
+
|
|
703
|
+
:param list domains: Dominios para identificar los registros
|
|
704
|
+
a eliminar.
|
|
705
|
+
:param dict action_data: Datos adicionales para la acción
|
|
706
|
+
(opcional).
|
|
707
|
+
:return: True si la eliminación fue exitosa, False en caso
|
|
708
|
+
contrario.
|
|
709
|
+
:rtype: bool
|
|
710
|
+
"""
|
|
711
|
+
if action_data is None:
|
|
712
|
+
action_data = {}
|
|
713
|
+
if not self.model:
|
|
714
|
+
raise ApiException('El modelo no está definido')
|
|
715
|
+
return _as_bool(
|
|
716
|
+
self.client.client_execute_kw(
|
|
717
|
+
self.model, 'unlink', domains=domains, action_data=action_data
|
|
718
|
+
),
|
|
719
|
+
self.model,
|
|
720
|
+
'unlink',
|
|
721
|
+
)
|
|
722
|
+
|
|
723
|
+
def action_method(
|
|
724
|
+
self,
|
|
725
|
+
action: str,
|
|
726
|
+
domains: OdooDomain,
|
|
727
|
+
action_data: OdooKwargs | None = None,
|
|
728
|
+
) -> OdooValue:
|
|
729
|
+
"""
|
|
730
|
+
Ejecuta una acción personalizada en el modelo especificado.
|
|
731
|
+
|
|
732
|
+
:param str action: Acción a ejecutar en el modelo.
|
|
733
|
+
:param list domains: Dominios para filtrar los datos.
|
|
734
|
+
:param dict action_data: Datos adicionales para la acción
|
|
735
|
+
(opcional).
|
|
736
|
+
:return: Resultado de la acción ejecutada.
|
|
737
|
+
:rtype: OdooValue
|
|
738
|
+
"""
|
|
739
|
+
if action_data is None:
|
|
740
|
+
action_data = {}
|
|
741
|
+
if not self.model:
|
|
742
|
+
raise ApiException('El modelo no está definido')
|
|
743
|
+
return self.client.client_execute_kw(
|
|
744
|
+
self.model, action, domains=domains, action_data=action_data
|
|
745
|
+
)
|