tools2fast-fastapi 0.1.0__tar.gz → 0.1.1__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.0/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.1.1}/PKG-INFO +1 -1
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/pyproject.toml +3 -1
- tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/__version__.py +1 -0
- tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/models/mixins.py +76 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi/schemas/mixins.py +12 -0
- tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/services/__init__.py +0 -0
- tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/services/number_service.py +38 -0
- tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/services/revision_service.py +166 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1/src/tools2fast_fastapi.egg-info}/PKG-INFO +1 -1
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi.egg-info/SOURCES.txt +4 -0
- tools2fast_fastapi-0.1.1/tests/test_revision_service.py +322 -0
- tools2fast_fastapi-0.1.0/src/tools2fast_fastapi/__version__.py +0 -1
- tools2fast_fastapi-0.1.0/src/tools2fast_fastapi/models/mixins.py +0 -42
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/LICENSE +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/MANIFEST.in +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/README.md +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/docs/guide.md +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/examples/example.py +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/setup.cfg +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi/__init__.py +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi/models/__init__.py +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi/schemas/__init__.py +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi.egg-info/dependency_links.txt +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi.egg-info/requires.txt +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi.egg-info/top_level.txt +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/tests/test_initial.py +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/tests/test_schemas.py +0 -0
{tools2fast_fastapi-0.1.0/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.1.1}/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.1
|
|
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.1"
|
|
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"
|
|
@@ -44,6 +44,8 @@ test = [
|
|
|
44
44
|
"pytest>=7.0.0",
|
|
45
45
|
"pytest-asyncio>=0.21.0",
|
|
46
46
|
"httpx>=0.24.0",
|
|
47
|
+
"aiosqlite>=0.22.1",
|
|
48
|
+
"greenlet>=3.3.2",
|
|
47
49
|
]
|
|
48
50
|
|
|
49
51
|
[project.urls]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.1"
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
from datetime import datetime, timezone
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import DateTime, func
|
|
4
|
+
from sqlmodel import BigInteger, Field
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class IdMixin:
|
|
8
|
+
"""Mixin para proveer clave primaria autoincremental tipo BigInteger."""
|
|
9
|
+
|
|
10
|
+
id: int | None = Field(default=None, primary_key=True, index=True, sa_type=BigInteger)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TimestampMixin:
|
|
14
|
+
"""Mixin reutilizable para marcas de tiempo en UTC."""
|
|
15
|
+
|
|
16
|
+
created_at: datetime = Field(
|
|
17
|
+
default_factory=lambda: datetime.now(timezone.utc),
|
|
18
|
+
nullable=False,
|
|
19
|
+
sa_type=DateTime(timezone=True),
|
|
20
|
+
)
|
|
21
|
+
updated_at: datetime = Field(
|
|
22
|
+
default_factory=lambda: datetime.now(timezone.utc),
|
|
23
|
+
nullable=False,
|
|
24
|
+
sa_type=DateTime(timezone=True),
|
|
25
|
+
sa_column_kwargs={"onupdate": func.now()},
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AuditMixin:
|
|
30
|
+
"""Mixin para rastrear el usuario que crea y actualiza un registro."""
|
|
31
|
+
|
|
32
|
+
created_by: int | None = Field(
|
|
33
|
+
default=None,
|
|
34
|
+
index=True,
|
|
35
|
+
description="ID of the user who created this record.",
|
|
36
|
+
sa_type=BigInteger,
|
|
37
|
+
)
|
|
38
|
+
updated_by: int | None = Field(
|
|
39
|
+
default=None,
|
|
40
|
+
index=True,
|
|
41
|
+
description="ID of the user who last updated this record.",
|
|
42
|
+
sa_type=BigInteger,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
class NumberMixin:
|
|
46
|
+
"""
|
|
47
|
+
Mixin para proveer un campo `number` que actúa como un identificador continuo
|
|
48
|
+
independiente de la clave primaria (ID).
|
|
49
|
+
|
|
50
|
+
Sirve para mostrar un número de registro humano-legible (ej. "Cotización #123"),
|
|
51
|
+
permitiendo que un mismo registro lógico pueda tener múltiples versiones
|
|
52
|
+
o revisiones manteniendo el mismo `number` consecutivo.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
number: int = Field(index=True)
|
|
56
|
+
|
|
57
|
+
class RevisionMixin(NumberMixin):
|
|
58
|
+
"""
|
|
59
|
+
Mixin reutilizable para cualquier tabla SQLModel que necesite versionado.
|
|
60
|
+
|
|
61
|
+
Agrega:
|
|
62
|
+
- revision (int): Número de revisión del registro (comienza en 1, incrementa con cada cambio).
|
|
63
|
+
|
|
64
|
+
La "revisión actual" es siempre la que tenga el mayor valor de `revision`
|
|
65
|
+
para un mismo `number`. No existe campo de status — la más reciente es la vigente.
|
|
66
|
+
|
|
67
|
+
Uso:
|
|
68
|
+
class MyModel(RevisionMixin, TenantModel, table=True):
|
|
69
|
+
__tablename__ = "my_models"
|
|
70
|
+
__table_args__ = (
|
|
71
|
+
UniqueConstraint("number", "revision", name="uq_my_model_number_revision"),
|
|
72
|
+
)
|
|
73
|
+
...
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
revision: int = Field(default=1, ge=1, index=True)
|
{tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi/schemas/mixins.py
RENAMED
|
@@ -21,3 +21,15 @@ class AuditMixin(SQLModel):
|
|
|
21
21
|
|
|
22
22
|
created_by: int | None = None
|
|
23
23
|
updated_by: int | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class NumberMixin(SQLModel):
|
|
27
|
+
"""Schema mixin for resources that use a continuous sequence number."""
|
|
28
|
+
|
|
29
|
+
number: int
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RevisionMixin(NumberMixin):
|
|
33
|
+
"""Schema mixin for resources that include a revision number."""
|
|
34
|
+
|
|
35
|
+
revision: int
|
|
File without changes
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NumberService — utilidades para manejar secuencias continuas de campos 'number'.
|
|
3
|
+
|
|
4
|
+
Provee funciones param obtener el siguiente número disponible en modelos que
|
|
5
|
+
hereden de NumberMixin. Al consultar el máximo actual en la base de datos
|
|
6
|
+
y sumar 1, garantizamos que si se borra el registro más reciente y se crea
|
|
7
|
+
uno nuevo, el nuevo tomará su lugar (max + 1).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from typing import TypeVar
|
|
11
|
+
|
|
12
|
+
from sqlalchemy import func
|
|
13
|
+
from sqlmodel import select
|
|
14
|
+
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
15
|
+
|
|
16
|
+
T = TypeVar("T")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def get_next_number(
|
|
20
|
+
session: AsyncSession,
|
|
21
|
+
model_class: type[T],
|
|
22
|
+
) -> int:
|
|
23
|
+
"""
|
|
24
|
+
Devuelve el siguiente `number` disponible para un modelo con NumberMixin.
|
|
25
|
+
Busca el valor máximo actual y le suma 1. Si no hay registros, inicia en 1.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
session: Sesión async activa.
|
|
29
|
+
model_class: Clase del modelo (debe tener el campo `number`).
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
El siguiente número a utilizar (int).
|
|
33
|
+
"""
|
|
34
|
+
stmt = select(func.max(model_class.number)) # type: ignore[attr-defined]
|
|
35
|
+
result = await session.exec(stmt)
|
|
36
|
+
max_number = result.first()
|
|
37
|
+
|
|
38
|
+
return (max_number or 0) + 1
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""
|
|
2
|
+
RevisionService — utilidades genéricas de versionado.
|
|
3
|
+
|
|
4
|
+
Compatible con CUALQUIER modelo que herede RevisionMixin.
|
|
5
|
+
|
|
6
|
+
Flujo:
|
|
7
|
+
- La "revisión actual" es siempre la de mayor `revision`.
|
|
8
|
+
- Crear una nueva revisión no toca el registro anterior (solo clona con revision+1).
|
|
9
|
+
- Eliminar la revisión más reciente restaura automáticamente la anterior como vigente.
|
|
10
|
+
|
|
11
|
+
Casos de uso:
|
|
12
|
+
Caso 1 — Solo versionado de cabecera:
|
|
13
|
+
new_record = await create_revision(session, current, changes)
|
|
14
|
+
|
|
15
|
+
Caso 2 — Versionado de cabecera con ítems:
|
|
16
|
+
new_header = await create_revision(session, current_header, changes)
|
|
17
|
+
new_items = await clone_children(
|
|
18
|
+
session, ChildModel, "parent_fk_field",
|
|
19
|
+
old_parent=current_header, new_parent=new_header,
|
|
20
|
+
)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from typing import Any, TypeVar
|
|
24
|
+
|
|
25
|
+
from sqlmodel import select
|
|
26
|
+
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
27
|
+
|
|
28
|
+
T = TypeVar("T")
|
|
29
|
+
|
|
30
|
+
# Campos que nunca se copian al clonar (los genera la BD o el ORM automáticamente)
|
|
31
|
+
_EXCLUDED_ON_CLONE = {"id", "created_at", "updated_at"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ─────────────────────────────────────────────────────────────
|
|
35
|
+
# Lectura genérica
|
|
36
|
+
# ─────────────────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def get_latest_revision(
|
|
40
|
+
session: AsyncSession,
|
|
41
|
+
model_class: type[T],
|
|
42
|
+
number: int,
|
|
43
|
+
) -> T | None:
|
|
44
|
+
"""
|
|
45
|
+
Devuelve el registro con la revisión más alta para un `number` dado.
|
|
46
|
+
Compatible con cualquier modelo que tenga RevisionMixin.
|
|
47
|
+
"""
|
|
48
|
+
stmt = (
|
|
49
|
+
select(model_class)
|
|
50
|
+
.where(model_class.number == number) # type: ignore[attr-defined]
|
|
51
|
+
.order_by(model_class.revision.desc()) # type: ignore[attr-defined]
|
|
52
|
+
.limit(1)
|
|
53
|
+
)
|
|
54
|
+
result = await session.exec(stmt)
|
|
55
|
+
return result.first()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def list_revisions(
|
|
59
|
+
session: AsyncSession,
|
|
60
|
+
model_class: type[T],
|
|
61
|
+
number: int,
|
|
62
|
+
) -> list[T]:
|
|
63
|
+
"""
|
|
64
|
+
Lista todas las revisiones de un registro por su `number`, de mayor a menor revisión.
|
|
65
|
+
Compatible con cualquier modelo que tenga RevisionMixin.
|
|
66
|
+
"""
|
|
67
|
+
stmt = (
|
|
68
|
+
select(model_class)
|
|
69
|
+
.where(model_class.number == number) # type: ignore[attr-defined]
|
|
70
|
+
.order_by(model_class.revision.desc()) # type: ignore[attr-defined]
|
|
71
|
+
)
|
|
72
|
+
result = await session.exec(stmt)
|
|
73
|
+
return list(result.all())
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ─────────────────────────────────────────────────────────────
|
|
77
|
+
# Escritura genérica
|
|
78
|
+
# ─────────────────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def create_revision(
|
|
82
|
+
session: AsyncSession,
|
|
83
|
+
current: T,
|
|
84
|
+
changes: dict[str, Any] | None = None,
|
|
85
|
+
) -> T:
|
|
86
|
+
"""
|
|
87
|
+
Crea una nueva revisión de cualquier modelo con RevisionMixin.
|
|
88
|
+
|
|
89
|
+
Clona todos los campos del registro actual, aplica `changes` y sube `revision` en 1.
|
|
90
|
+
El registro anterior queda intacto — la nueva revisión es la vigente por tener mayor número.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
session: Sesión async activa.
|
|
94
|
+
current: Registro actual (cualquier modelo con RevisionMixin).
|
|
95
|
+
changes: Campos a cambiar en la nueva revisión. Si es None, clona sin cambios.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
La nueva instancia creada (ya con flush aplicado, id disponible).
|
|
99
|
+
"""
|
|
100
|
+
changes = changes or {}
|
|
101
|
+
model_class: type[T] = type(current)
|
|
102
|
+
|
|
103
|
+
# Clonar todos los campos del registro actual, excluyendo los auto-generados
|
|
104
|
+
field_values: dict[str, Any] = current.model_dump(exclude=_EXCLUDED_ON_CLONE)
|
|
105
|
+
|
|
106
|
+
# Aplicar cambios y subir revisión
|
|
107
|
+
field_values.update(changes)
|
|
108
|
+
field_values["revision"] = current.revision + 1 # type: ignore[attr-defined]
|
|
109
|
+
|
|
110
|
+
new_record = model_class(**field_values)
|
|
111
|
+
session.add(new_record)
|
|
112
|
+
await session.flush() # Obtener id antes de que el caller use new_record.id
|
|
113
|
+
return new_record
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
async def clone_children(
|
|
117
|
+
session: AsyncSession,
|
|
118
|
+
item_model: type[T],
|
|
119
|
+
parent_fk_field: str,
|
|
120
|
+
old_parent: Any,
|
|
121
|
+
new_parent: Any,
|
|
122
|
+
overrides: dict[int, dict[str, Any]] | None = None,
|
|
123
|
+
) -> list[T]:
|
|
124
|
+
"""
|
|
125
|
+
Clona todos los registros hijo de `old_parent` hacia `new_parent`.
|
|
126
|
+
|
|
127
|
+
Funciona con cualquier modelo de ítems, sin importar sus campos específicos.
|
|
128
|
+
Usa model_dump() para copiar genéricamente y luego reasigna el FK al nuevo padre.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
session: Sesión async activa.
|
|
132
|
+
item_model: Clase del modelo hijo (e.g. QuotationItem, OrderItem).
|
|
133
|
+
parent_fk_field: Nombre del campo FK al padre (e.g. "quotation_header_id").
|
|
134
|
+
old_parent: Instancia del padre anterior (se extrae .id internamente).
|
|
135
|
+
new_parent: Instancia del nuevo padre (se extrae .id internamente).
|
|
136
|
+
overrides: Cambios a aplicar a ítems específicos { item.number -> {campo: valor} }.
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
Lista de nuevos ítems creados (pendientes de commit).
|
|
140
|
+
"""
|
|
141
|
+
overrides = overrides or {}
|
|
142
|
+
|
|
143
|
+
# Filtrar ítems del padre anterior por su FK
|
|
144
|
+
fk_col = getattr(item_model, parent_fk_field)
|
|
145
|
+
stmt = select(item_model).where(fk_col == old_parent.id)
|
|
146
|
+
result = await session.exec(stmt)
|
|
147
|
+
old_items = list(result.all())
|
|
148
|
+
|
|
149
|
+
new_items: list[T] = []
|
|
150
|
+
for item in old_items:
|
|
151
|
+
# Clonar todos los campos excepto los auto-generados
|
|
152
|
+
item_values: dict[str, Any] = item.model_dump(exclude=_EXCLUDED_ON_CLONE)
|
|
153
|
+
|
|
154
|
+
# Aplicar overrides específicos del ítem (buscado por número)
|
|
155
|
+
item_number = item_values.get("number")
|
|
156
|
+
if item_number in overrides:
|
|
157
|
+
item_values.update(overrides[item_number])
|
|
158
|
+
|
|
159
|
+
# Reasignar FK al nuevo padre
|
|
160
|
+
item_values[parent_fk_field] = new_parent.id
|
|
161
|
+
|
|
162
|
+
new_item = item_model(**item_values)
|
|
163
|
+
session.add(new_item)
|
|
164
|
+
new_items.append(new_item)
|
|
165
|
+
|
|
166
|
+
return new_items
|
{tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1/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.1
|
|
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.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi.egg-info/SOURCES.txt
RENAMED
|
@@ -15,5 +15,9 @@ 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/services/__init__.py
|
|
19
|
+
src/tools2fast_fastapi/services/number_service.py
|
|
20
|
+
src/tools2fast_fastapi/services/revision_service.py
|
|
18
21
|
tests/test_initial.py
|
|
22
|
+
tests/test_revision_service.py
|
|
19
23
|
tests/test_schemas.py
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Tests genéricos para RevisionMixin y NumberMixin.
|
|
3
|
+
|
|
4
|
+
Utiliza una base de datos SQLite en memoria (configurada en conftest.py) para
|
|
5
|
+
validar el funcionamiento agnóstico y genérico del versionado de documentos.
|
|
6
|
+
|
|
7
|
+
Ejecutar con:
|
|
8
|
+
uv run --group test pytest tests/test_revision_service.py -v
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
13
|
+
|
|
14
|
+
from sqlmodel import Field, SQLModel
|
|
15
|
+
from tools2fast_fastapi.models.mixins import NumberMixin, RevisionMixin
|
|
16
|
+
from tools2fast_fastapi.services.revision_service import (
|
|
17
|
+
clone_children,
|
|
18
|
+
create_revision,
|
|
19
|
+
get_latest_revision,
|
|
20
|
+
list_revisions,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class DocumentHeader(RevisionMixin, SQLModel, table=True):
|
|
25
|
+
"""Modelo dummy de Header para pruebas"""
|
|
26
|
+
|
|
27
|
+
__tablename__ = "test_document_headers"
|
|
28
|
+
id: int | None = Field(default=None, primary_key=True)
|
|
29
|
+
client_id: int
|
|
30
|
+
currency_id: int
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class DocumentItem(NumberMixin, SQLModel, table=True):
|
|
34
|
+
"""Modelo dummy de Item para pruebas"""
|
|
35
|
+
|
|
36
|
+
__tablename__ = "test_document_items"
|
|
37
|
+
id: int | None = Field(default=None, primary_key=True)
|
|
38
|
+
document_header_id: int = Field(index=True)
|
|
39
|
+
material_id: int | None = None
|
|
40
|
+
quantity: float
|
|
41
|
+
unit_price: float | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# ─────────────────────────────────────────────────────────────
|
|
45
|
+
# Helpers
|
|
46
|
+
# ─────────────────────────────────────────────────────────────
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
async def _create_header(session: AsyncSession, number: int = 1001) -> DocumentHeader:
|
|
50
|
+
"""Crea un DocumentHeader de revisión 1."""
|
|
51
|
+
header = DocumentHeader(
|
|
52
|
+
number=number,
|
|
53
|
+
client_id=1,
|
|
54
|
+
currency_id=1,
|
|
55
|
+
revision=1,
|
|
56
|
+
)
|
|
57
|
+
session.add(header)
|
|
58
|
+
await session.flush()
|
|
59
|
+
return header
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
async def _add_item(
|
|
63
|
+
session: AsyncSession,
|
|
64
|
+
header_id: int,
|
|
65
|
+
number: int = 1,
|
|
66
|
+
material_id: int = 10,
|
|
67
|
+
qty: float = 5.0,
|
|
68
|
+
price: float = 100.0,
|
|
69
|
+
) -> DocumentItem:
|
|
70
|
+
"""Agrega una partida a un header."""
|
|
71
|
+
item = DocumentItem(
|
|
72
|
+
document_header_id=header_id,
|
|
73
|
+
number=number,
|
|
74
|
+
material_id=material_id,
|
|
75
|
+
quantity=qty,
|
|
76
|
+
unit_price=price,
|
|
77
|
+
)
|
|
78
|
+
session.add(item)
|
|
79
|
+
await session.flush()
|
|
80
|
+
return item
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ─────────────────────────────────────────────────────────────
|
|
84
|
+
# Tests: RevisionMixin
|
|
85
|
+
# ─────────────────────────────────────────────────────────────
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@pytest.mark.asyncio
|
|
89
|
+
async def test_header_default_revision(session: AsyncSession):
|
|
90
|
+
"""Un header nuevo debe tener revision=1."""
|
|
91
|
+
header = await _create_header(session)
|
|
92
|
+
await session.commit()
|
|
93
|
+
await session.refresh(header)
|
|
94
|
+
|
|
95
|
+
assert header.revision == 1
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@pytest.mark.asyncio
|
|
99
|
+
async def test_item_links_to_header(session: AsyncSession):
|
|
100
|
+
"""Una partida nueva debe estar vinculada a su header correctamente."""
|
|
101
|
+
header = await _create_header(session)
|
|
102
|
+
item = await _add_item(session, header.id, number=1, qty=7.0)
|
|
103
|
+
await session.commit()
|
|
104
|
+
await session.refresh(item)
|
|
105
|
+
|
|
106
|
+
assert item.document_header_id == header.id
|
|
107
|
+
assert item.quantity == 7.0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ─────────────────────────────────────────────────────────────
|
|
111
|
+
# Tests: create_revision (genérico)
|
|
112
|
+
# ─────────────────────────────────────────────────────────────
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@pytest.mark.asyncio
|
|
116
|
+
async def test_create_revision_increments(session: AsyncSession):
|
|
117
|
+
"""create_revision debe incrementar revision en 1."""
|
|
118
|
+
header = await _create_header(session)
|
|
119
|
+
await session.commit()
|
|
120
|
+
|
|
121
|
+
new_header = await create_revision(session, header)
|
|
122
|
+
await session.commit()
|
|
123
|
+
|
|
124
|
+
assert new_header.revision == 2
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@pytest.mark.asyncio
|
|
128
|
+
async def test_create_revision_old_record_unchanged(session: AsyncSession):
|
|
129
|
+
"""El registro original debe quedar intacto con revision=1."""
|
|
130
|
+
header = await _create_header(session)
|
|
131
|
+
original_id = header.id
|
|
132
|
+
await session.commit()
|
|
133
|
+
|
|
134
|
+
await create_revision(session, header)
|
|
135
|
+
await session.commit()
|
|
136
|
+
|
|
137
|
+
old = await session.get(DocumentHeader, original_id)
|
|
138
|
+
assert old is not None
|
|
139
|
+
assert old.revision == 1
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@pytest.mark.asyncio
|
|
143
|
+
async def test_create_revision_applies_changes(session: AsyncSession):
|
|
144
|
+
"""Los cambios deben reflejarse en la nueva revisión."""
|
|
145
|
+
header = await _create_header(session)
|
|
146
|
+
await session.commit()
|
|
147
|
+
|
|
148
|
+
new_header = await create_revision(session, header, {"client_id": 99})
|
|
149
|
+
await session.commit()
|
|
150
|
+
|
|
151
|
+
assert new_header.client_id == 99
|
|
152
|
+
assert new_header.number == header.number # El number no cambia
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@pytest.mark.asyncio
|
|
156
|
+
async def test_create_revision_same_type(session: AsyncSession):
|
|
157
|
+
"""create_revision debe devolver el mismo tipo que el original."""
|
|
158
|
+
header = await _create_header(session)
|
|
159
|
+
await session.commit()
|
|
160
|
+
|
|
161
|
+
new_header = await create_revision(session, header)
|
|
162
|
+
await session.commit()
|
|
163
|
+
|
|
164
|
+
assert type(new_header) is DocumentHeader
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# ─────────────────────────────────────────────────────────────
|
|
168
|
+
# Tests: clone_children (genérico)
|
|
169
|
+
# ─────────────────────────────────────────────────────────────
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@pytest.mark.asyncio
|
|
173
|
+
async def test_clone_children_copies_all_items(session: AsyncSession):
|
|
174
|
+
"""clone_children debe crear copias de todos los ítems en el nuevo padre."""
|
|
175
|
+
header = await _create_header(session)
|
|
176
|
+
await _add_item(session, header.id, number=1)
|
|
177
|
+
await _add_item(session, header.id, number=2, material_id=20)
|
|
178
|
+
|
|
179
|
+
new_header = await _create_header(session, number=1002)
|
|
180
|
+
await session.commit()
|
|
181
|
+
|
|
182
|
+
new_items = await clone_children(
|
|
183
|
+
session, DocumentItem, "document_header_id",
|
|
184
|
+
old_parent=header, new_parent=new_header,
|
|
185
|
+
)
|
|
186
|
+
await session.commit()
|
|
187
|
+
|
|
188
|
+
assert len(new_items) == 2
|
|
189
|
+
assert all(it.document_header_id == new_header.id for it in new_items)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@pytest.mark.asyncio
|
|
193
|
+
async def test_clone_children_applies_override(session: AsyncSession):
|
|
194
|
+
"""El override debe modificar únicamente el ítem indicado."""
|
|
195
|
+
header = await _create_header(session)
|
|
196
|
+
await _add_item(session, header.id, number=1, qty=5.0)
|
|
197
|
+
await _add_item(session, header.id, number=2, qty=10.0)
|
|
198
|
+
|
|
199
|
+
new_header = await _create_header(session, number=1002)
|
|
200
|
+
await session.commit()
|
|
201
|
+
|
|
202
|
+
new_items = await clone_children(
|
|
203
|
+
session, DocumentItem, "document_header_id",
|
|
204
|
+
old_parent=header, new_parent=new_header,
|
|
205
|
+
overrides={1: {"quantity": 99.0}},
|
|
206
|
+
)
|
|
207
|
+
await session.commit()
|
|
208
|
+
|
|
209
|
+
item_1 = next(it for it in new_items if it.number == 1)
|
|
210
|
+
item_2 = next(it for it in new_items if it.number == 2)
|
|
211
|
+
|
|
212
|
+
assert item_1.quantity == 99.0 # Modificado
|
|
213
|
+
assert item_2.quantity == 10.0 # Intacto
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
# ─────────────────────────────────────────────────────────────
|
|
217
|
+
# Tests: get_latest_revision y list_revisions
|
|
218
|
+
# ─────────────────────────────────────────────────────────────
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@pytest.mark.asyncio
|
|
222
|
+
async def test_get_latest_revision(session: AsyncSession):
|
|
223
|
+
"""get_latest_revision debe devolver la revisión más alta."""
|
|
224
|
+
header = await _create_header(session, number=2001)
|
|
225
|
+
await session.commit()
|
|
226
|
+
|
|
227
|
+
rev2 = await create_revision(session, header)
|
|
228
|
+
await session.commit()
|
|
229
|
+
|
|
230
|
+
latest = await get_latest_revision(session, DocumentHeader, 2001)
|
|
231
|
+
assert latest is not None
|
|
232
|
+
assert latest.revision == 2
|
|
233
|
+
assert latest.id == rev2.id
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@pytest.mark.asyncio
|
|
237
|
+
async def test_list_revisions_returns_all_ordered(session: AsyncSession):
|
|
238
|
+
"""list_revisions debe devolver todas las revisiones en orden descendente."""
|
|
239
|
+
header = await _create_header(session, number=3001)
|
|
240
|
+
await session.commit()
|
|
241
|
+
|
|
242
|
+
rev2 = await create_revision(session, header)
|
|
243
|
+
await session.commit()
|
|
244
|
+
|
|
245
|
+
await create_revision(session, rev2)
|
|
246
|
+
await session.commit()
|
|
247
|
+
|
|
248
|
+
revisions = await list_revisions(session, DocumentHeader, 3001)
|
|
249
|
+
assert len(revisions) == 3
|
|
250
|
+
assert revisions[0].revision == 3
|
|
251
|
+
assert revisions[1].revision == 2
|
|
252
|
+
assert revisions[2].revision == 1
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# ─────────────────────────────────────────────────────────────
|
|
256
|
+
# Tests: flujo completo cabecera + ítems (Caso 2)
|
|
257
|
+
# ─────────────────────────────────────────────────────────────
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@pytest.mark.asyncio
|
|
261
|
+
async def test_full_revision_with_items_creates_new_header(session: AsyncSession):
|
|
262
|
+
"""Crear una revisión con ítems debe generar un nuevo header con revision=2."""
|
|
263
|
+
header = await _create_header(session, number=4001)
|
|
264
|
+
await _add_item(session, header.id, number=1, qty=5.0)
|
|
265
|
+
await _add_item(session, header.id, number=2, qty=3.0)
|
|
266
|
+
await session.commit()
|
|
267
|
+
|
|
268
|
+
new_header = await create_revision(session, header)
|
|
269
|
+
await clone_children(
|
|
270
|
+
session, DocumentItem, "document_header_id",
|
|
271
|
+
old_parent=header, new_parent=new_header,
|
|
272
|
+
overrides={1: {"quantity": 20.0}},
|
|
273
|
+
)
|
|
274
|
+
await session.commit()
|
|
275
|
+
|
|
276
|
+
assert new_header.revision == 2
|
|
277
|
+
assert new_header.number == 4001
|
|
278
|
+
|
|
279
|
+
# Header original intacto
|
|
280
|
+
old = await session.get(DocumentHeader, header.id)
|
|
281
|
+
assert old.revision == 1
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
@pytest.mark.asyncio
|
|
285
|
+
async def test_full_revision_override_applies_to_correct_item(session: AsyncSession):
|
|
286
|
+
"""Solo el ítem con override debe cambiar; los demás quedan iguales."""
|
|
287
|
+
header = await _create_header(session, number=5001)
|
|
288
|
+
await _add_item(session, header.id, number=1, qty=5.0, price=100.0)
|
|
289
|
+
await _add_item(session, header.id, number=2, qty=3.0, price=200.0)
|
|
290
|
+
await session.commit()
|
|
291
|
+
|
|
292
|
+
new_header = await create_revision(session, header)
|
|
293
|
+
new_items = await clone_children(
|
|
294
|
+
session, DocumentItem, "document_header_id",
|
|
295
|
+
old_parent=header, new_parent=new_header,
|
|
296
|
+
overrides={2: {"unit_price": 999.0}},
|
|
297
|
+
)
|
|
298
|
+
await session.commit()
|
|
299
|
+
|
|
300
|
+
item_1 = next(it for it in new_items if it.number == 1)
|
|
301
|
+
item_2 = next(it for it in new_items if it.number == 2)
|
|
302
|
+
|
|
303
|
+
assert item_1.unit_price == 100.0 # Sin cambio
|
|
304
|
+
assert item_2.unit_price == 999.0 # Modificado
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
@pytest.mark.asyncio
|
|
308
|
+
async def test_full_revision_preserves_item_count(session: AsyncSession):
|
|
309
|
+
"""La nueva revisión debe tener el mismo número de ítems que la anterior."""
|
|
310
|
+
header = await _create_header(session, number=6001)
|
|
311
|
+
for i in range(1, 5):
|
|
312
|
+
await _add_item(session, header.id, number=i)
|
|
313
|
+
await session.commit()
|
|
314
|
+
|
|
315
|
+
new_header = await create_revision(session, header)
|
|
316
|
+
new_items = await clone_children(
|
|
317
|
+
session, DocumentItem, "document_header_id",
|
|
318
|
+
old_parent=header, new_parent=new_header,
|
|
319
|
+
)
|
|
320
|
+
await session.commit()
|
|
321
|
+
|
|
322
|
+
assert len(new_items) == 4
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.1.0"
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
from datetime import datetime, timezone
|
|
2
|
-
|
|
3
|
-
from sqlalchemy import DateTime, func
|
|
4
|
-
from sqlmodel import BigInteger, Field
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
class IdMixin:
|
|
8
|
-
"""Mixin para proveer clave primaria autoincremental tipo BigInteger."""
|
|
9
|
-
|
|
10
|
-
id: int | None = Field(default=None, primary_key=True, index=True, sa_type=BigInteger)
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
class TimestampMixin:
|
|
14
|
-
"""Mixin reutilizable para marcas de tiempo en UTC."""
|
|
15
|
-
|
|
16
|
-
created_at: datetime = Field(
|
|
17
|
-
default_factory=lambda: datetime.now(timezone.utc),
|
|
18
|
-
nullable=False,
|
|
19
|
-
sa_type=DateTime(timezone=True),
|
|
20
|
-
)
|
|
21
|
-
updated_at: datetime = Field(
|
|
22
|
-
default_factory=lambda: datetime.now(timezone.utc),
|
|
23
|
-
nullable=False,
|
|
24
|
-
sa_type=DateTime(timezone=True),
|
|
25
|
-
sa_column_kwargs={"onupdate": func.now()},
|
|
26
|
-
)
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
class AuditMixin:
|
|
30
|
-
"""Mixin para rastrear el usuario que crea y actualiza un registro."""
|
|
31
|
-
|
|
32
|
-
created_by: int | None = Field(
|
|
33
|
-
default=None,
|
|
34
|
-
description="ID of the user who created this record.",
|
|
35
|
-
sa_type=BigInteger,
|
|
36
|
-
)
|
|
37
|
-
updated_by: int | None = Field(
|
|
38
|
-
default=None,
|
|
39
|
-
description="ID of the user who last updated this record.",
|
|
40
|
-
sa_type=BigInteger,
|
|
41
|
-
)
|
|
42
|
-
|
|
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.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi/models/__init__.py
RENAMED
|
File without changes
|
{tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi/schemas/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
{tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi.egg-info/requires.txt
RENAMED
|
File without changes
|
{tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.1}/src/tools2fast_fastapi.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|