tools2fast-fastapi 0.1.1__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.
Files changed (31) hide show
  1. {tools2fast_fastapi-0.1.1/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.1.2}/PKG-INFO +1 -1
  2. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/pyproject.toml +1 -1
  3. tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/__init__.py +17 -0
  4. tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/__version__.py +1 -0
  5. tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/models/__init__.py +10 -0
  6. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi/models/mixins.py +10 -0
  7. tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/services/__init__.py +15 -0
  8. tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/services/document_simple_revision_service.py +114 -0
  9. tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/services/document_with_items_revision_service.py +198 -0
  10. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2/src/tools2fast_fastapi.egg-info}/PKG-INFO +1 -1
  11. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi.egg-info/SOURCES.txt +2 -0
  12. tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/__init__.py +0 -11
  13. tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/__version__.py +0 -1
  14. tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/models/__init__.py +0 -7
  15. tools2fast_fastapi-0.1.1/src/tools2fast_fastapi/services/__init__.py +0 -0
  16. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/LICENSE +0 -0
  17. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/MANIFEST.in +0 -0
  18. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/README.md +0 -0
  19. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/docs/guide.md +0 -0
  20. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/examples/example.py +0 -0
  21. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/setup.cfg +0 -0
  22. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi/schemas/__init__.py +0 -0
  23. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi/schemas/mixins.py +0 -0
  24. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi/services/number_service.py +0 -0
  25. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi/services/revision_service.py +0 -0
  26. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi.egg-info/dependency_links.txt +0 -0
  27. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi.egg-info/requires.txt +0 -0
  28. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/src/tools2fast_fastapi.egg-info/top_level.txt +0 -0
  29. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/tests/test_initial.py +0 -0
  30. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/tests/test_revision_service.py +0 -0
  31. {tools2fast_fastapi-0.1.1 → tools2fast_fastapi-0.1.2}/tests/test_schemas.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tools2fast-fastapi
3
- Version: 0.1.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.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"
@@ -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,10 @@
1
+ from .mixins import IdMixin, TimestampMixin, AuditMixin, NumberUniqueMixin, RevisionMixin, NumberMixin
2
+
3
+ __all__ = [
4
+ "IdMixin",
5
+ "TimestampMixin",
6
+ "AuditMixin",
7
+ "NumberUniqueMixin",
8
+ "RevisionMixin",
9
+ "NumberMixin",
10
+ ]
@@ -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,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()
@@ -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()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tools2fast-fastapi
3
- Version: 0.1.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
@@ -16,6 +16,8 @@ src/tools2fast_fastapi/models/mixins.py
16
16
  src/tools2fast_fastapi/schemas/__init__.py
17
17
  src/tools2fast_fastapi/schemas/mixins.py
18
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
19
21
  src/tools2fast_fastapi/services/number_service.py
20
22
  src/tools2fast_fastapi/services/revision_service.py
21
23
  tests/test_initial.py
@@ -1,11 +0,0 @@
1
- from .models.mixins import AuditMixin, IdMixin, TimestampMixin
2
- from . import schemas
3
- from .__version__ import __version__
4
-
5
- __all__ = [
6
- "IdMixin",
7
- "TimestampMixin",
8
- "AuditMixin",
9
- "schemas",
10
- "__version__",
11
- ]
@@ -1 +0,0 @@
1
- __version__ = "0.1.1"
@@ -1,7 +0,0 @@
1
- from .mixins import IdMixin, TimestampMixin, AuditMixin
2
-
3
- __all__ = [
4
- "IdMixin",
5
- "TimestampMixin",
6
- "AuditMixin",
7
- ]