tools2fast-fastapi 0.1.1__tar.gz → 0.1.3__tar.gz
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.
- {tools2fast_fastapi-0.1.1/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.1.3}/PKG-INFO +1 -1
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/pyproject.toml +1 -1
- tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/__init__.py +23 -0
- tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/__version__.py +1 -0
- tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/models/__init__.py +10 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/models/mixins.py +10 -0
- tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/schemas/__init__.py +13 -0
- tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/schemas/response_schema.py +282 -0
- tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/services/__init__.py +17 -0
- tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/services/document_simple_revision_service.py +114 -0
- tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/services/document_with_items_revision_service.py +198 -0
- tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/services/transaction_service.py +67 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3/src/tools2fast_fastapi.egg-info}/PKG-INFO +1 -1
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/SOURCES.txt +4 -0
- tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/__init__.py +0 -11
- tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/__version__.py +0 -1
- tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/models/__init__.py +0 -7
- tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/schemas/__init__.py +0 -7
- tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/services/__init__.py +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/LICENSE +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/MANIFEST.in +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/README.md +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/docs/guide.md +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/examples/example.py +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/setup.cfg +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/schemas/mixins.py +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/services/number_service.py +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/services/revision_service.py +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/dependency_links.txt +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/requires.txt +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/top_level.txt +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/tests/test_initial.py +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/tests/test_revision_service.py +0 -0
- {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/tests/test_schemas.py +0 -0
{tools2fast_fastapi-0.1.1/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.1.3}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tools2fast-fastapi
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.3
|
|
4
4
|
Summary: Shared tools, mixins, and base services for FastAPI applications - Solautyc Team internal use
|
|
5
5
|
Author-email: Angel Daniel Sanchez Castillo <angeldaniel.sanchezcastillo@gmail.com>
|
|
6
6
|
License: MIT License
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "tools2fast-fastapi"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.3"
|
|
8
8
|
description = "Shared tools, mixins, and base services for FastAPI applications - Solautyc Team internal use"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from .models.mixins import AuditMixin, IdMixin, TimestampMixin, NumberUniqueMixin, RevisionMixin, NumberMixin
|
|
2
|
+
from .services import DocumentSimpleRevisionService, DocumentWithItemsRevisionService, TransactionService
|
|
3
|
+
from .schemas import APIResponse, BaseResponse, DataResponse, MessageResponse
|
|
4
|
+
from . import schemas
|
|
5
|
+
from .__version__ import __version__
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"IdMixin",
|
|
9
|
+
"TimestampMixin",
|
|
10
|
+
"AuditMixin",
|
|
11
|
+
"NumberUniqueMixin",
|
|
12
|
+
"RevisionMixin",
|
|
13
|
+
"NumberMixin",
|
|
14
|
+
"APIResponse",
|
|
15
|
+
"BaseResponse",
|
|
16
|
+
"DataResponse",
|
|
17
|
+
"MessageResponse",
|
|
18
|
+
"DocumentSimpleRevisionService",
|
|
19
|
+
"DocumentWithItemsRevisionService",
|
|
20
|
+
"TransactionService",
|
|
21
|
+
"schemas",
|
|
22
|
+
"__version__",
|
|
23
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.3"
|
{tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/models/mixins.py
RENAMED
|
@@ -54,6 +54,16 @@ class NumberMixin:
|
|
|
54
54
|
|
|
55
55
|
number: int = Field(index=True)
|
|
56
56
|
|
|
57
|
+
class NumberUniqueMixin:
|
|
58
|
+
"""
|
|
59
|
+
Mixin para proveer un campo `number` que actúa como un identificador único
|
|
60
|
+
independiente de la clave primaria (ID).
|
|
61
|
+
|
|
62
|
+
Sirve para mostrar un número de registro humano-legible (ej. "Cotización #123"),
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
number: int = Field(index=True, unique=True)
|
|
66
|
+
|
|
57
67
|
class RevisionMixin(NumberMixin):
|
|
58
68
|
"""
|
|
59
69
|
Mixin reutilizable para cualquier tabla SQLModel que necesite versionado.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from .mixins import AuditMixin, IdMixin, TimestampMixin
|
|
2
|
+
from .response_schema import APIResponse, BaseResponse, DataResponse, ErrorResponse, MessageResponse
|
|
3
|
+
|
|
4
|
+
__all__ = [
|
|
5
|
+
"IdMixin",
|
|
6
|
+
"TimestampMixin",
|
|
7
|
+
"AuditMixin",
|
|
8
|
+
"APIResponse",
|
|
9
|
+
"BaseResponse",
|
|
10
|
+
"DataResponse",
|
|
11
|
+
"ErrorResponse",
|
|
12
|
+
"MessageResponse"
|
|
13
|
+
]
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Schemas de respuesta estándar para todos los endpoints.
|
|
3
|
+
|
|
4
|
+
Jerarquía de modelos:
|
|
5
|
+
|
|
6
|
+
BaseResponse
|
|
7
|
+
├── MessageResponse → success/delete/create sin datos (data: None)
|
|
8
|
+
├── DataResponse[T] → respuestas con payload tipado (data: T)
|
|
9
|
+
└── ErrorResponse → errores controlados e inesperados (data: None, success: False)
|
|
10
|
+
|
|
11
|
+
Factoría:
|
|
12
|
+
APIResponse → métodos estáticos que devuelven los modelos anteriores.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
from typing import Any, Generic, TypeVar
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel
|
|
21
|
+
from fastapi import status
|
|
22
|
+
from fastapi.responses import JSONResponse
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
T = TypeVar("T")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# ═══════════════════════════════════════════════════════
|
|
30
|
+
# Modelo auxiliar
|
|
31
|
+
# ═══════════════════════════════════════════════════════
|
|
32
|
+
|
|
33
|
+
class ErrorDetail(BaseModel):
|
|
34
|
+
"""Información estructurada de un error."""
|
|
35
|
+
|
|
36
|
+
type: str
|
|
37
|
+
"""Nombre de la clase de la excepción, p. ej. ``'ValueError'``."""
|
|
38
|
+
|
|
39
|
+
detail: str | None = None
|
|
40
|
+
"""Mensaje de detalle. ``null`` en errores no controlados (seguridad)."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# ═══════════════════════════════════════════════════════
|
|
44
|
+
# Jerarquía de respuesta
|
|
45
|
+
# ═══════════════════════════════════════════════════════
|
|
46
|
+
|
|
47
|
+
class BaseResponse(BaseModel):
|
|
48
|
+
"""Estructura base compartida por todas las respuestas de la API.
|
|
49
|
+
|
|
50
|
+
Todos los endpoints devuelven exactamente estos cuatro campos::
|
|
51
|
+
|
|
52
|
+
{
|
|
53
|
+
"success": bool,
|
|
54
|
+
"message": str,
|
|
55
|
+
"error": {"type": str, "detail": str | null} | null,
|
|
56
|
+
"data": <T> | null
|
|
57
|
+
}
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
success: bool
|
|
61
|
+
message: str
|
|
62
|
+
error: ErrorDetail | None = None
|
|
63
|
+
data: Any = None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class MessageResponse(BaseResponse):
|
|
67
|
+
"""Respuesta exitosa **sin** payload de datos.
|
|
68
|
+
|
|
69
|
+
Usada en: ``saved()``, ``deleted()``, ``created()`` sin argumento.
|
|
70
|
+
``data`` está fijado en ``None`` — no admite payload.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
success: bool = True
|
|
74
|
+
data: None = None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class DataResponse(BaseResponse, Generic[T]):
|
|
78
|
+
"""Respuesta exitosa **con** payload de datos tipado.
|
|
79
|
+
|
|
80
|
+
Usada en: ``ok()``, ``created(data=…)``
|
|
81
|
+
|
|
82
|
+
Declara el tipo concreto en el decorador del endpoint::
|
|
83
|
+
|
|
84
|
+
response_model=DataResponse[QuotationHeaderRead]
|
|
85
|
+
response_model=DataResponse[list[ClientRead]]
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
success: bool = True
|
|
89
|
+
data: T # type: ignore[assignment]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class ErrorResponse(BaseResponse):
|
|
93
|
+
"""Respuesta de error (controlado o inesperado).
|
|
94
|
+
|
|
95
|
+
``success`` siempre es ``False``.
|
|
96
|
+
``data`` siempre es ``null``.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
success: bool = False
|
|
100
|
+
data: None = None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ═══════════════════════════════════════════════════════
|
|
104
|
+
# Factoría
|
|
105
|
+
# ═══════════════════════════════════════════════════════
|
|
106
|
+
|
|
107
|
+
class APIResponse:
|
|
108
|
+
"""Factoría de respuestas con tipado estricto para endpoints FastAPI.
|
|
109
|
+
|
|
110
|
+
Métodos de **éxito** → devuelven instancias Pydantic
|
|
111
|
+
(:class:`MessageResponse` / :class:`DataResponse`) que FastAPI serializa
|
|
112
|
+
y documenta automáticamente via ``response_model``.
|
|
113
|
+
|
|
114
|
+
Métodos de **error** → devuelven :class:`~fastapi.responses.JSONResponse`
|
|
115
|
+
porque necesitan ``status_code`` variable (400, 404, 500…).
|
|
116
|
+
|
|
117
|
+
Constante de clase:
|
|
118
|
+
``ERROR_RESPONSES`` — dict listo para pasarse al ``APIRouter`` o a
|
|
119
|
+
cualquier decorador de endpoint::
|
|
120
|
+
|
|
121
|
+
router = APIRouter(responses=APIResponse.ERROR_RESPONSES)
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
ERROR_RESPONSES: dict = {
|
|
125
|
+
400: {"model": ErrorResponse, "description": "Error controlado"},
|
|
126
|
+
500: {"model": ErrorResponse, "description": "Error inesperado del servidor"},
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
# ─────────────────────────────────────────────────────────────────────────
|
|
130
|
+
# Éxito
|
|
131
|
+
# ─────────────────────────────────────────────────────────────────────────
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
def ok(data: Any, *, message: str = "OK") -> DataResponse:
|
|
135
|
+
"""Respuesta exitosa ``200`` con payload ``data``.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
data: Objeto a devolver. Se serializa con ``.model_dump()``
|
|
139
|
+
automáticamente si es un modelo Pydantic.
|
|
140
|
+
message: Texto descriptivo. Por defecto ``"OK"``.
|
|
141
|
+
|
|
142
|
+
Example::
|
|
143
|
+
|
|
144
|
+
return APIResponse.ok(client)
|
|
145
|
+
return APIResponse.ok([item1, item2], message="Listado obtenido")
|
|
146
|
+
"""
|
|
147
|
+
if hasattr(data, "model_dump"):
|
|
148
|
+
data = data.model_dump()
|
|
149
|
+
elif isinstance(data, list):
|
|
150
|
+
data = [
|
|
151
|
+
item.model_dump() if hasattr(item, "model_dump") else item
|
|
152
|
+
for item in data
|
|
153
|
+
]
|
|
154
|
+
return DataResponse(message=message, data=data)
|
|
155
|
+
|
|
156
|
+
@staticmethod
|
|
157
|
+
def saved(*, message: str = "Guardado con éxito") -> MessageResponse:
|
|
158
|
+
"""Respuesta ``200`` sin datos para PUT / PATCH.
|
|
159
|
+
|
|
160
|
+
Example::
|
|
161
|
+
|
|
162
|
+
return APIResponse.saved()
|
|
163
|
+
"""
|
|
164
|
+
return MessageResponse(message=message)
|
|
165
|
+
|
|
166
|
+
@staticmethod
|
|
167
|
+
def created(
|
|
168
|
+
data: Any = None,
|
|
169
|
+
*,
|
|
170
|
+
message: str = "Creado con éxito",
|
|
171
|
+
) -> MessageResponse | DataResponse:
|
|
172
|
+
"""Respuesta ``201 Created``.
|
|
173
|
+
|
|
174
|
+
Sin ``data`` → :class:`MessageResponse` (solo mensaje).
|
|
175
|
+
Con ``data=`` → :class:`DataResponse` con el objeto serializado.
|
|
176
|
+
|
|
177
|
+
Example::
|
|
178
|
+
|
|
179
|
+
return APIResponse.created() # solo 201 + mensaje
|
|
180
|
+
return APIResponse.created(new_client) # 201 + objeto
|
|
181
|
+
"""
|
|
182
|
+
if data is None:
|
|
183
|
+
return MessageResponse(message=message)
|
|
184
|
+
if hasattr(data, "model_dump"):
|
|
185
|
+
data = data.model_dump()
|
|
186
|
+
elif isinstance(data, list):
|
|
187
|
+
data = [
|
|
188
|
+
item.model_dump() if hasattr(item, "model_dump") else item
|
|
189
|
+
for item in data
|
|
190
|
+
]
|
|
191
|
+
return DataResponse(message=message, data=data)
|
|
192
|
+
|
|
193
|
+
@staticmethod
|
|
194
|
+
def deleted(*, message: str = "Eliminado con éxito") -> MessageResponse:
|
|
195
|
+
"""Respuesta ``200`` de confirmación de eliminación sin payload.
|
|
196
|
+
|
|
197
|
+
``data`` siempre es ``null`` — no tiene sentido devolver el objeto
|
|
198
|
+
que ya no existe.
|
|
199
|
+
|
|
200
|
+
Example::
|
|
201
|
+
|
|
202
|
+
return APIResponse.deleted()
|
|
203
|
+
"""
|
|
204
|
+
return MessageResponse(message=message)
|
|
205
|
+
|
|
206
|
+
# ─────────────────────────────────────────────────────────────────────────
|
|
207
|
+
# Error
|
|
208
|
+
# ─────────────────────────────────────────────────────────────────────────
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def fail(
|
|
212
|
+
message: str,
|
|
213
|
+
*,
|
|
214
|
+
error: str | dict | None = None,
|
|
215
|
+
status_code: int = status.HTTP_400_BAD_REQUEST,
|
|
216
|
+
) -> JSONResponse:
|
|
217
|
+
"""Error controlado **manual** desde el router.
|
|
218
|
+
|
|
219
|
+
Usar para validaciones que el router detecta antes de llamar al service
|
|
220
|
+
(ID inválido, permisos, etc.).
|
|
221
|
+
|
|
222
|
+
Args:
|
|
223
|
+
message: Mensaje legible para el usuario.
|
|
224
|
+
error: Detalle opcional: ``str`` o ``{"type": …, "detail": …}``.
|
|
225
|
+
status_code: Código HTTP. Por defecto ``400``.
|
|
226
|
+
|
|
227
|
+
Example::
|
|
228
|
+
|
|
229
|
+
return APIResponse.fail("ID inválido", status_code=422)
|
|
230
|
+
"""
|
|
231
|
+
error_detail: ErrorDetail | None = None
|
|
232
|
+
if error is not None:
|
|
233
|
+
if isinstance(error, dict):
|
|
234
|
+
error_detail = ErrorDetail(**error)
|
|
235
|
+
else:
|
|
236
|
+
error_detail = ErrorDetail(type="Error", detail=str(error))
|
|
237
|
+
|
|
238
|
+
body = ErrorResponse(message=message, error=error_detail)
|
|
239
|
+
return JSONResponse(status_code=status_code, content=body.model_dump())
|
|
240
|
+
|
|
241
|
+
@staticmethod
|
|
242
|
+
def from_exception(
|
|
243
|
+
exc: Exception,
|
|
244
|
+
*,
|
|
245
|
+
controlled: tuple[type[Exception], ...] = (ValueError,),
|
|
246
|
+
status_code: int = status.HTTP_400_BAD_REQUEST,
|
|
247
|
+
) -> JSONResponse:
|
|
248
|
+
"""Convierte una excepción en un :class:`JSONResponse` estandarizado.
|
|
249
|
+
|
|
250
|
+
- **Controlada** → expone el mensaje al cliente y lo incluye en ``error.detail``.
|
|
251
|
+
- **No controlada** → mensaje genérico; ``error.detail`` oculto (seguridad);
|
|
252
|
+
traceback completo al logger.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
exc: La excepción capturada.
|
|
256
|
+
controlled: Tipos "esperados". Por defecto ``(ValueError,)``.
|
|
257
|
+
status_code: Código HTTP para errores controlados.
|
|
258
|
+
|
|
259
|
+
Example::
|
|
260
|
+
|
|
261
|
+
try:
|
|
262
|
+
result = await TransactionService.run(session, ...)
|
|
263
|
+
return APIResponse.ok(result)
|
|
264
|
+
except Exception as exc:
|
|
265
|
+
return APIResponse.from_exception(exc)
|
|
266
|
+
"""
|
|
267
|
+
error_detail = ErrorDetail(
|
|
268
|
+
type=type(exc).__name__,
|
|
269
|
+
detail=str(exc) if str(exc) else None,
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
if isinstance(exc, controlled):
|
|
273
|
+
body = ErrorResponse(message=str(exc), error=error_detail)
|
|
274
|
+
return JSONResponse(status_code=status_code, content=body.model_dump())
|
|
275
|
+
|
|
276
|
+
logger.exception("Error inesperado [%s]: %s", type(exc).__name__, exc)
|
|
277
|
+
error_detail.detail = None
|
|
278
|
+
body = ErrorResponse(message="Ha ocurrido un error", error=error_detail)
|
|
279
|
+
return JSONResponse(
|
|
280
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
281
|
+
content=body.model_dump(),
|
|
282
|
+
)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .document_simple_revision_service import DocumentSimpleRevisionService
|
|
2
|
+
from .document_with_items_revision_service import DocumentWithItemsRevisionService
|
|
3
|
+
from .number_service import get_next_number
|
|
4
|
+
from .revision_service import get_latest_revision, list_revisions, create_revision, clone_children
|
|
5
|
+
from .transaction_service import TransactionService
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"DocumentSimpleRevisionService",
|
|
10
|
+
"DocumentWithItemsRevisionService",
|
|
11
|
+
"get_next_number",
|
|
12
|
+
"get_latest_revision",
|
|
13
|
+
"list_revisions",
|
|
14
|
+
"create_revision",
|
|
15
|
+
"clone_children",
|
|
16
|
+
"TransactionService",
|
|
17
|
+
]
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
from typing import Any, Generic, TypeVar
|
|
2
|
+
|
|
3
|
+
from fastapi import HTTPException
|
|
4
|
+
from sqlalchemy import func
|
|
5
|
+
from sqlmodel import select
|
|
6
|
+
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
7
|
+
|
|
8
|
+
ModelT = TypeVar("ModelT")
|
|
9
|
+
|
|
10
|
+
class DocumentSimpleRevisionService(Generic[ModelT]):
|
|
11
|
+
"""
|
|
12
|
+
Servicio genérico para manejar documentos que tienen control de revisiones
|
|
13
|
+
(RevisionMixin y NumberMixin) pero NO tienen partidas (ítems) asociadas.
|
|
14
|
+
|
|
15
|
+
Abstrae la creación, obtención, versionado y eliminación de la cabecera
|
|
16
|
+
de forma eficiente.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, model_class: type[ModelT]):
|
|
20
|
+
self.model_class = model_class
|
|
21
|
+
# Se excluyen los campos internos auto-generados típicamente por SQLAlchemy/Pydantic
|
|
22
|
+
self._excluded_on_clone = {"id", "created_at", "updated_at"}
|
|
23
|
+
|
|
24
|
+
# ═══════════════════════════════════════════════════════
|
|
25
|
+
# LECTURA
|
|
26
|
+
# ═══════════════════════════════════════════════════════
|
|
27
|
+
|
|
28
|
+
async def get_latest_document(self, session: AsyncSession, number: int) -> ModelT:
|
|
29
|
+
"""Devuelve la revisión más reciente (mayor revision) de un documento."""
|
|
30
|
+
stmt = (
|
|
31
|
+
select(self.model_class)
|
|
32
|
+
.where(self.model_class.number == number) # type: ignore
|
|
33
|
+
.order_by(self.model_class.revision.desc()) # type: ignore
|
|
34
|
+
.limit(1)
|
|
35
|
+
)
|
|
36
|
+
result = await session.exec(stmt)
|
|
37
|
+
document = result.first()
|
|
38
|
+
if not document:
|
|
39
|
+
raise HTTPException(status_code=404, detail=f"Documento número {number} no encontrado.")
|
|
40
|
+
return document
|
|
41
|
+
|
|
42
|
+
async def list_latest_documents(self, session: AsyncSession, skip: int = 0, limit: int = 100) -> list[ModelT]:
|
|
43
|
+
"""Devuelve únicamente la revisión más reciente de CADA documento."""
|
|
44
|
+
subq = (
|
|
45
|
+
select(
|
|
46
|
+
self.model_class.number, # type: ignore
|
|
47
|
+
func.max(self.model_class.revision).label("max_rev"), # type: ignore
|
|
48
|
+
)
|
|
49
|
+
.group_by(self.model_class.number) # type: ignore
|
|
50
|
+
.subquery()
|
|
51
|
+
)
|
|
52
|
+
stmt = (
|
|
53
|
+
select(self.model_class)
|
|
54
|
+
.join(
|
|
55
|
+
subq,
|
|
56
|
+
(self.model_class.number == subq.c.number) # type: ignore
|
|
57
|
+
& (self.model_class.revision == subq.c.max_rev), # type: ignore
|
|
58
|
+
)
|
|
59
|
+
.order_by(self.model_class.number) # type: ignore
|
|
60
|
+
.offset(skip)
|
|
61
|
+
.limit(limit)
|
|
62
|
+
)
|
|
63
|
+
result = await session.exec(stmt)
|
|
64
|
+
return list(result.all())
|
|
65
|
+
|
|
66
|
+
async def list_document_revisions(self, session: AsyncSession, number: int) -> list[ModelT]:
|
|
67
|
+
"""Lista todo el historial de revisiones de un documento específico."""
|
|
68
|
+
stmt = (
|
|
69
|
+
select(self.model_class)
|
|
70
|
+
.where(self.model_class.number == number) # type: ignore
|
|
71
|
+
.order_by(self.model_class.revision.desc()) # type: ignore
|
|
72
|
+
)
|
|
73
|
+
result = await session.exec(stmt)
|
|
74
|
+
revisions = list(result.all())
|
|
75
|
+
if not revisions:
|
|
76
|
+
raise HTTPException(status_code=404, detail=f"Documento número {number} no encontrado.")
|
|
77
|
+
return revisions
|
|
78
|
+
|
|
79
|
+
# ═══════════════════════════════════════════════════════
|
|
80
|
+
# ESCRITURA
|
|
81
|
+
# ═══════════════════════════════════════════════════════
|
|
82
|
+
|
|
83
|
+
async def create_document(self, session: AsyncSession, create_kwargs: dict[str, Any]) -> ModelT:
|
|
84
|
+
"""Crea un documento nuevo, inicializado siempre en la versión 1."""
|
|
85
|
+
document = self.model_class(**create_kwargs, revision=1)
|
|
86
|
+
session.add(document)
|
|
87
|
+
await session.flush()
|
|
88
|
+
return document
|
|
89
|
+
|
|
90
|
+
async def revise_document(self, session: AsyncSession, number: int, changes: dict[str, Any]) -> ModelT:
|
|
91
|
+
"""
|
|
92
|
+
Crea la nueva versión del documento preservando campos internos ocultos e inyectándole
|
|
93
|
+
los nuevos valores desde `changes`. Todo el historial previo queda intacto.
|
|
94
|
+
"""
|
|
95
|
+
current_document = await self.get_latest_document(session, number)
|
|
96
|
+
|
|
97
|
+
# Filtramos los campos prohibidos de la clonación
|
|
98
|
+
field_values: dict[str, Any] = current_document.model_dump(exclude=self._excluded_on_clone) # type: ignore
|
|
99
|
+
|
|
100
|
+
# Aplicamos inyección/overrides provenientes del Payload JSON y subimos +1 a la revisión
|
|
101
|
+
field_values.update(changes)
|
|
102
|
+
field_values["revision"] = getattr(current_document, "revision") + 1
|
|
103
|
+
|
|
104
|
+
new_document = self.model_class(**field_values)
|
|
105
|
+
session.add(new_document)
|
|
106
|
+
await session.flush()
|
|
107
|
+
|
|
108
|
+
return new_document
|
|
109
|
+
|
|
110
|
+
async def delete_latest_revision(self, session: AsyncSession, number: int) -> None:
|
|
111
|
+
"""Elimina físicamente la revisión más reciente (Hard delete)."""
|
|
112
|
+
latest = await self.get_latest_document(session, number)
|
|
113
|
+
await session.delete(latest)
|
|
114
|
+
await session.commit()
|
tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/services/document_with_items_revision_service.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
from typing import Any, Generic, TypeVar, Callable
|
|
2
|
+
|
|
3
|
+
from fastapi import HTTPException
|
|
4
|
+
from sqlalchemy import func
|
|
5
|
+
from sqlmodel import select
|
|
6
|
+
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
7
|
+
|
|
8
|
+
HeaderT = TypeVar("HeaderT")
|
|
9
|
+
ItemT = TypeVar("ItemT")
|
|
10
|
+
|
|
11
|
+
class DocumentWithItemsRevisionService(Generic[HeaderT, ItemT]):
|
|
12
|
+
"""
|
|
13
|
+
Servicio genérico que fusiona la lógica de versionado (revision_service)
|
|
14
|
+
y el manejo en bloque de documentos (document_service) en una sola clase
|
|
15
|
+
altamente optimizada.
|
|
16
|
+
|
|
17
|
+
Abstrae la creación, obtención, versionado y clonación de partidas.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
header_model: type[HeaderT],
|
|
23
|
+
item_model: type[ItemT],
|
|
24
|
+
header_fk_field: str,
|
|
25
|
+
):
|
|
26
|
+
self.header_model = header_model
|
|
27
|
+
self.item_model = item_model
|
|
28
|
+
self.header_fk_field = header_fk_field
|
|
29
|
+
self._excluded_on_clone = {"id", "created_at", "updated_at"}
|
|
30
|
+
|
|
31
|
+
# ═══════════════════════════════════════════════════════
|
|
32
|
+
# LECTURA
|
|
33
|
+
# ═══════════════════════════════════════════════════════
|
|
34
|
+
|
|
35
|
+
async def get_latest_header(self, session: AsyncSession, number: int) -> HeaderT:
|
|
36
|
+
"""Devuelve la revisión más reciente (mayor revision) de un documento."""
|
|
37
|
+
stmt = (
|
|
38
|
+
select(self.header_model)
|
|
39
|
+
.where(self.header_model.number == number) # type: ignore
|
|
40
|
+
.order_by(self.header_model.revision.desc()) # type: ignore
|
|
41
|
+
.limit(1)
|
|
42
|
+
)
|
|
43
|
+
result = await session.exec(stmt)
|
|
44
|
+
header = result.first()
|
|
45
|
+
if not header:
|
|
46
|
+
raise HTTPException(status_code=404, detail=f"Documento número {number} no encontrado.")
|
|
47
|
+
return header
|
|
48
|
+
|
|
49
|
+
async def get_document_with_items(self, session: AsyncSession, number: int) -> tuple[HeaderT, list[ItemT]]:
|
|
50
|
+
"""Devuelve la revisión más reciente junto con sus partidas."""
|
|
51
|
+
header = await self.get_latest_header(session, number)
|
|
52
|
+
items = await self.list_items_by_header(session, getattr(header, "id"))
|
|
53
|
+
return header, items
|
|
54
|
+
|
|
55
|
+
async def list_latest_headers(self, session: AsyncSession, skip: int = 0, limit: int = 100) -> list[HeaderT]:
|
|
56
|
+
"""Devuelve únicamente la revisión más reciente de CADA documento."""
|
|
57
|
+
subq = (
|
|
58
|
+
select(
|
|
59
|
+
self.header_model.number, # type: ignore
|
|
60
|
+
func.max(self.header_model.revision).label("max_rev"), # type: ignore
|
|
61
|
+
)
|
|
62
|
+
.group_by(self.header_model.number) # type: ignore
|
|
63
|
+
.subquery()
|
|
64
|
+
)
|
|
65
|
+
stmt = (
|
|
66
|
+
select(self.header_model)
|
|
67
|
+
.join(
|
|
68
|
+
subq,
|
|
69
|
+
(self.header_model.number == subq.c.number) # type: ignore
|
|
70
|
+
& (self.header_model.revision == subq.c.max_rev), # type: ignore
|
|
71
|
+
)
|
|
72
|
+
.order_by(self.header_model.number) # type: ignore
|
|
73
|
+
.offset(skip)
|
|
74
|
+
.limit(limit)
|
|
75
|
+
)
|
|
76
|
+
result = await session.exec(stmt)
|
|
77
|
+
return list(result.all())
|
|
78
|
+
|
|
79
|
+
async def list_document_revisions(self, session: AsyncSession, number: int) -> list[HeaderT]:
|
|
80
|
+
"""Lista todo el historial de revisiones de un documento específico."""
|
|
81
|
+
stmt = (
|
|
82
|
+
select(self.header_model)
|
|
83
|
+
.where(self.header_model.number == number) # type: ignore
|
|
84
|
+
.order_by(self.header_model.revision.desc()) # type: ignore
|
|
85
|
+
)
|
|
86
|
+
result = await session.exec(stmt)
|
|
87
|
+
revisions = list(result.all())
|
|
88
|
+
if not revisions:
|
|
89
|
+
raise HTTPException(status_code=404, detail=f"Documento número {number} no encontrado.")
|
|
90
|
+
return revisions
|
|
91
|
+
|
|
92
|
+
async def list_items_by_header(self, session: AsyncSession, header_id: int) -> list[ItemT]:
|
|
93
|
+
"""Devuelve todas las partidas asociadas al ID de una cabecera."""
|
|
94
|
+
fk_col = getattr(self.item_model, self.header_fk_field)
|
|
95
|
+
stmt = select(self.item_model).where(fk_col == header_id)
|
|
96
|
+
result = await session.exec(stmt)
|
|
97
|
+
return list(result.all())
|
|
98
|
+
|
|
99
|
+
# ═══════════════════════════════════════════════════════
|
|
100
|
+
# ESCRITURA
|
|
101
|
+
# ═══════════════════════════════════════════════════════
|
|
102
|
+
|
|
103
|
+
async def create_document_with_items(
|
|
104
|
+
self,
|
|
105
|
+
session: AsyncSession,
|
|
106
|
+
create_header_kwargs: dict[str, Any],
|
|
107
|
+
create_items_kwargs_list: list[dict[str, Any]],
|
|
108
|
+
) -> tuple[HeaderT, list[ItemT]]:
|
|
109
|
+
"""
|
|
110
|
+
Crea un documento (revisión 1) y sus partidas iniciales.
|
|
111
|
+
"""
|
|
112
|
+
header = self.header_model(**create_header_kwargs, revision=1)
|
|
113
|
+
session.add(header)
|
|
114
|
+
await session.flush()
|
|
115
|
+
|
|
116
|
+
items: list[ItemT] = []
|
|
117
|
+
for item_kwargs in create_items_kwargs_list:
|
|
118
|
+
item_kwargs[self.header_fk_field] = header.id # type: ignore
|
|
119
|
+
item = self.item_model(**item_kwargs)
|
|
120
|
+
session.add(item)
|
|
121
|
+
items.append(item)
|
|
122
|
+
|
|
123
|
+
return header, items
|
|
124
|
+
|
|
125
|
+
async def _create_revision_header(
|
|
126
|
+
self, session: AsyncSession, current_header: HeaderT, changes: dict[str, Any]
|
|
127
|
+
) -> HeaderT:
|
|
128
|
+
"""Crea la nueva versión de la cabecera preservando campos internos."""
|
|
129
|
+
field_values: dict[str, Any] = current_header.model_dump(exclude=self._excluded_on_clone) # type: ignore
|
|
130
|
+
field_values.update(changes)
|
|
131
|
+
field_values["revision"] = getattr(current_header, "revision") + 1
|
|
132
|
+
|
|
133
|
+
new_header = self.header_model(**field_values)
|
|
134
|
+
session.add(new_header)
|
|
135
|
+
await session.flush()
|
|
136
|
+
return new_header
|
|
137
|
+
|
|
138
|
+
async def revise_document_with_items(
|
|
139
|
+
self,
|
|
140
|
+
session: AsyncSession,
|
|
141
|
+
number: int,
|
|
142
|
+
header_changes: dict[str, Any],
|
|
143
|
+
new_items_datas: list[Any],
|
|
144
|
+
extract_item_kwargs: Callable[[Any, int], tuple[int, dict[str, Any]]],
|
|
145
|
+
) -> tuple[HeaderT, list[ItemT]]:
|
|
146
|
+
"""
|
|
147
|
+
Fusión eficiente: Crea la nueva revisión de la cabecera y aplica un
|
|
148
|
+
reemplazo total de ítems en una sola pasada.
|
|
149
|
+
|
|
150
|
+
Soporta: Clona campos internos de ítems viejos, ignora eliminados y crea nuevos.
|
|
151
|
+
"""
|
|
152
|
+
current_header = await self.get_latest_header(session, number)
|
|
153
|
+
new_header = await self._create_revision_header(session, current_header, header_changes)
|
|
154
|
+
|
|
155
|
+
# Obtener los ítems de la revisión anterior
|
|
156
|
+
fk_col = getattr(self.item_model, self.header_fk_field)
|
|
157
|
+
stmt = select(self.item_model).where(fk_col == getattr(current_header, "id"))
|
|
158
|
+
result = await session.exec(stmt)
|
|
159
|
+
old_items_by_num = {getattr(it, "number"): it for it in result.all()}
|
|
160
|
+
|
|
161
|
+
new_items: list[ItemT] = []
|
|
162
|
+
|
|
163
|
+
for i, item_data in enumerate(new_items_datas, start=1):
|
|
164
|
+
num, kwargs = extract_item_kwargs(item_data, i)
|
|
165
|
+
kwargs[self.header_fk_field] = getattr(new_header, "id")
|
|
166
|
+
|
|
167
|
+
if num in old_items_by_num:
|
|
168
|
+
# 1. ACTUALIZAR: Clonar el ítem anterior para preservar campos ocultos +OVERRIDES
|
|
169
|
+
old_item = old_items_by_num[num]
|
|
170
|
+
item_values: dict[str, Any] = old_item.model_dump(exclude=self._excluded_on_clone) # type: ignore
|
|
171
|
+
item_values.update(kwargs)
|
|
172
|
+
new_item = self.item_model(**item_values)
|
|
173
|
+
else:
|
|
174
|
+
# 2. CREAR: Es un ítem completamente nuevo
|
|
175
|
+
kwargs["number"] = num
|
|
176
|
+
new_item = self.item_model(**kwargs)
|
|
177
|
+
|
|
178
|
+
# 3. BORRAR: Implícito. Si un ítem estaba en old_items pero el cliente
|
|
179
|
+
# no lo mandó en new_items_datas, el ciclo simplemente lo ignora.
|
|
180
|
+
|
|
181
|
+
session.add(new_item)
|
|
182
|
+
new_items.append(new_item)
|
|
183
|
+
|
|
184
|
+
new_items.sort(key=lambda x: getattr(x, "number"))
|
|
185
|
+
return new_header, new_items
|
|
186
|
+
|
|
187
|
+
async def delete_latest_revision(self, session: AsyncSession, number: int) -> None:
|
|
188
|
+
"""Elimina físicamente la revisión más reciente (cabecera + ítems)."""
|
|
189
|
+
latest = await self.get_latest_header(session, number)
|
|
190
|
+
|
|
191
|
+
fk_col = getattr(self.item_model, self.header_fk_field)
|
|
192
|
+
stmt = select(self.item_model).where(fk_col == getattr(latest, "id"))
|
|
193
|
+
result = await session.exec(stmt)
|
|
194
|
+
for item in result.all():
|
|
195
|
+
await session.delete(item)
|
|
196
|
+
|
|
197
|
+
await session.delete(latest)
|
|
198
|
+
await session.commit()
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TransactionService
|
|
3
|
+
|
|
4
|
+
Servicio genérico que centraliza el manejo de transacciones de base de datos
|
|
5
|
+
(commit / rollback automático).
|
|
6
|
+
|
|
7
|
+
Para el manejo de respuestas HTTP usa :class:`~tenant.schemas.response_schema.APIResponse`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Awaitable, Callable, TypeVar
|
|
13
|
+
|
|
14
|
+
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
15
|
+
|
|
16
|
+
T = TypeVar("T")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TransactionService:
|
|
20
|
+
"""Servicio genérico de transacciones para routers FastAPI."""
|
|
21
|
+
|
|
22
|
+
@staticmethod
|
|
23
|
+
async def run(
|
|
24
|
+
session: AsyncSession,
|
|
25
|
+
operation: Callable[[], Awaitable[T]],
|
|
26
|
+
) -> T:
|
|
27
|
+
"""Ejecuta ``operation`` y confirma la transacción.
|
|
28
|
+
|
|
29
|
+
Si ``operation`` lanza una excepción se hace rollback automático y se
|
|
30
|
+
re-lanza el error para que el llamador lo maneje con
|
|
31
|
+
:meth:`~tenant.schemas.response_schema.APIResponse.from_exception`.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
session: Sesión asíncrona de SQLModel / SQLAlchemy.
|
|
35
|
+
operation: Coroutine factory sin argumentos que realiza las
|
|
36
|
+
operaciones de base de datos deseadas.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
El valor que devuelva ``operation``.
|
|
40
|
+
|
|
41
|
+
Raises:
|
|
42
|
+
Exception: La misma excepción lanzada dentro de ``operation``
|
|
43
|
+
tras ejecutar el rollback.
|
|
44
|
+
|
|
45
|
+
Example::
|
|
46
|
+
|
|
47
|
+
from tenant.schemas.response_schema import APIResponse
|
|
48
|
+
from tenant.services import TransactionService
|
|
49
|
+
|
|
50
|
+
@router.post("/")
|
|
51
|
+
async def create(data: MySchema, session: AsyncSession = Depends(...)):
|
|
52
|
+
try:
|
|
53
|
+
result = await TransactionService.run(
|
|
54
|
+
session,
|
|
55
|
+
lambda: my_db_function(session, data),
|
|
56
|
+
)
|
|
57
|
+
return APIResponse.created(result)
|
|
58
|
+
except Exception as exc:
|
|
59
|
+
return APIResponse.from_exception(exc)
|
|
60
|
+
"""
|
|
61
|
+
try:
|
|
62
|
+
result = await operation()
|
|
63
|
+
await session.commit()
|
|
64
|
+
return result
|
|
65
|
+
except Exception:
|
|
66
|
+
await session.rollback()
|
|
67
|
+
raise
|
{tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3/src/tools2fast_fastapi.egg-info}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tools2fast-fastapi
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.3
|
|
4
4
|
Summary: Shared tools, mixins, and base services for FastAPI applications - Solautyc Team internal use
|
|
5
5
|
Author-email: Angel Daniel Sanchez Castillo <angeldaniel.sanchezcastillo@gmail.com>
|
|
6
6
|
License: MIT License
|
{tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/SOURCES.txt
RENAMED
|
@@ -15,9 +15,13 @@ src/tools2fast_fastapi/models/__init__.py
|
|
|
15
15
|
src/tools2fast_fastapi/models/mixins.py
|
|
16
16
|
src/tools2fast_fastapi/schemas/__init__.py
|
|
17
17
|
src/tools2fast_fastapi/schemas/mixins.py
|
|
18
|
+
src/tools2fast_fastapi/schemas/response_schema.py
|
|
18
19
|
src/tools2fast_fastapi/services/__init__.py
|
|
20
|
+
src/tools2fast_fastapi/services/document_simple_revision_service.py
|
|
21
|
+
src/tools2fast_fastapi/services/document_with_items_revision_service.py
|
|
19
22
|
src/tools2fast_fastapi/services/number_service.py
|
|
20
23
|
src/tools2fast_fastapi/services/revision_service.py
|
|
24
|
+
src/tools2fast_fastapi/services/transaction_service.py
|
|
21
25
|
tests/test_initial.py
|
|
22
26
|
tests/test_revision_service.py
|
|
23
27
|
tests/test_schemas.py
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.1.1"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/schemas/mixins.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/requires.txt
RENAMED
|
File without changes
|
{tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|