tools2fast-fastapi 0.1.0__tar.gz → 0.1.2__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.2}/PKG-INFO +1 -1
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/pyproject.toml +3 -1
- tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/__init__.py +17 -0
- tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/__version__.py +1 -0
- tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/models/__init__.py +10 -0
- tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/models/mixins.py +86 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi/schemas/mixins.py +12 -0
- tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/services/__init__.py +15 -0
- tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/services/document_simple_revision_service.py +114 -0
- tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/services/document_with_items_revision_service.py +198 -0
- tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/services/number_service.py +38 -0
- tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/services/revision_service.py +166 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2/src/tools2fast_fastapi.egg-info}/PKG-INFO +1 -1
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi.egg-info/SOURCES.txt +6 -0
- tools2fast_fastapi-0.1.2/tests/test_revision_service.py +322 -0
- tools2fast_fastapi-0.1.0/src/tools2fast_fastapi/__init__.py +0 -11
- tools2fast_fastapi-0.1.0/src/tools2fast_fastapi/__version__.py +0 -1
- tools2fast_fastapi-0.1.0/src/tools2fast_fastapi/models/__init__.py +0 -7
- tools2fast_fastapi-0.1.0/src/tools2fast_fastapi/models/mixins.py +0 -42
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/LICENSE +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/MANIFEST.in +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/README.md +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/docs/guide.md +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/examples/example.py +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/setup.cfg +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi/schemas/__init__.py +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi.egg-info/dependency_links.txt +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi.egg-info/requires.txt +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi.egg-info/top_level.txt +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/tests/test_initial.py +0 -0
- {tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/tests/test_schemas.py +0 -0
{tools2fast_fastapi-0.1.0/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.1.2}/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.2
|
|
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.2"
|
|
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,17 @@
|
|
|
1
|
+
from .models.mixins import AuditMixin, IdMixin, TimestampMixin, NumberUniqueMixin, RevisionMixin, NumberMixin
|
|
2
|
+
from . import schemas
|
|
3
|
+
from .services import DocumentSimpleRevisionService, DocumentWithItemsRevisionService
|
|
4
|
+
from .__version__ import __version__
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"IdMixin",
|
|
8
|
+
"TimestampMixin",
|
|
9
|
+
"AuditMixin",
|
|
10
|
+
"NumberUniqueMixin",
|
|
11
|
+
"RevisionMixin",
|
|
12
|
+
"NumberMixin",
|
|
13
|
+
"DocumentSimpleRevisionService",
|
|
14
|
+
"DocumentWithItemsRevisionService",
|
|
15
|
+
"schemas",
|
|
16
|
+
"__version__",
|
|
17
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.2"
|
|
@@ -0,0 +1,86 @@
|
|
|
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 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
|
+
|
|
67
|
+
class RevisionMixin(NumberMixin):
|
|
68
|
+
"""
|
|
69
|
+
Mixin reutilizable para cualquier tabla SQLModel que necesite versionado.
|
|
70
|
+
|
|
71
|
+
Agrega:
|
|
72
|
+
- revision (int): Número de revisión del registro (comienza en 1, incrementa con cada cambio).
|
|
73
|
+
|
|
74
|
+
La "revisión actual" es siempre la que tenga el mayor valor de `revision`
|
|
75
|
+
para un mismo `number`. No existe campo de status — la más reciente es la vigente.
|
|
76
|
+
|
|
77
|
+
Uso:
|
|
78
|
+
class MyModel(RevisionMixin, TenantModel, table=True):
|
|
79
|
+
__tablename__ = "my_models"
|
|
80
|
+
__table_args__ = (
|
|
81
|
+
UniqueConstraint("number", "revision", name="uq_my_model_number_revision"),
|
|
82
|
+
)
|
|
83
|
+
...
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
revision: int = Field(default=1, ge=1, index=True)
|
{tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/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
|
|
@@ -0,0 +1,15 @@
|
|
|
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
|
+
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"DocumentSimpleRevisionService",
|
|
9
|
+
"DocumentWithItemsRevisionService",
|
|
10
|
+
"get_next_number",
|
|
11
|
+
"get_latest_revision",
|
|
12
|
+
"list_revisions",
|
|
13
|
+
"create_revision",
|
|
14
|
+
"clone_children",
|
|
15
|
+
]
|
|
@@ -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.2/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,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.2/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.2
|
|
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.2}/src/tools2fast_fastapi.egg-info/SOURCES.txt
RENAMED
|
@@ -15,5 +15,11 @@ 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/document_simple_revision_service.py
|
|
20
|
+
src/tools2fast_fastapi/services/document_with_items_revision_service.py
|
|
21
|
+
src/tools2fast_fastapi/services/number_service.py
|
|
22
|
+
src/tools2fast_fastapi/services/revision_service.py
|
|
18
23
|
tests/test_initial.py
|
|
24
|
+
tests/test_revision_service.py
|
|
19
25
|
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
|
{tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi/schemas/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
{tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi.egg-info/requires.txt
RENAMED
|
File without changes
|
{tools2fast_fastapi-0.1.0 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|