tools2fast-fastapi 0.3.11__tar.gz → 0.3.13__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 (36) hide show
  1. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/MANIFEST.in +3 -2
  2. {tools2fast_fastapi-0.3.11/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.3.13}/PKG-INFO +3 -1
  3. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/README.md +2 -0
  4. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/pyproject.toml +10 -1
  5. tools2fast_fastapi-0.3.13/src/tools2fast_fastapi/__version__.py +1 -0
  6. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/services/__init__.py +4 -0
  7. tools2fast_fastapi-0.3.13/src/tools2fast_fastapi/services/query_filters.py +122 -0
  8. tools2fast_fastapi-0.3.13/src/tools2fast_fastapi/skills/SKILL.md +60 -0
  9. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13/src/tools2fast_fastapi.egg-info}/PKG-INFO +3 -1
  10. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi.egg-info/SOURCES.txt +3 -0
  11. tools2fast_fastapi-0.3.13/tests/test_query_filters.py +390 -0
  12. tools2fast_fastapi-0.3.11/src/tools2fast_fastapi/__version__.py +0 -1
  13. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/LICENSE +0 -0
  14. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/docs/guide.md +0 -0
  15. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/examples/example.py +0 -0
  16. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/setup.cfg +0 -0
  17. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/__init__.py +0 -0
  18. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/models/__init__.py +0 -0
  19. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/models/mixins.py +0 -0
  20. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/schemas/__init__.py +0 -0
  21. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/schemas/mixins.py +0 -0
  22. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/schemas/response_schema.py +0 -0
  23. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/services/document_simple_revision_service.py +0 -0
  24. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/services/document_with_items_revision_service.py +0 -0
  25. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/services/number_service.py +0 -0
  26. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/services/revision_service.py +0 -0
  27. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/services/transaction_service.py +0 -0
  28. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/utils/__init__.py +0 -0
  29. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi/utils/routing.py +0 -0
  30. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi.egg-info/dependency_links.txt +0 -0
  31. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi.egg-info/requires.txt +0 -0
  32. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/src/tools2fast_fastapi.egg-info/top_level.txt +0 -0
  33. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/tests/test_initial.py +0 -0
  34. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/tests/test_response_schema.py +0 -0
  35. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/tests/test_revision_service.py +0 -0
  36. {tools2fast_fastapi-0.3.11 → tools2fast_fastapi-0.3.13}/tests/test_schemas.py +0 -0
@@ -1,8 +1,9 @@
1
1
  include README.md
2
2
  include LICENSE
3
3
  recursive-include docs *.md *.example
4
- recursive-include examples *.py
5
- recursive-include src/tools2fast_fastapi *.py *.html
4
+ recursive-include examples *.py *.example *.json
5
+ recursive-include src/tools2fast_fastapi *.py *.html *.json *.md
6
+
6
7
  global-exclude __pycache__
7
8
  global-exclude *.py[co]
8
9
  global-exclude .DS_Store
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tools2fast-fastapi
3
- Version: 0.3.11
3
+ Version: 0.3.13
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
@@ -50,6 +50,8 @@ Dynamic: license-file
50
50
 
51
51
  Shared tools, mixins, and base services for FastAPI applications. Designed for internal use by the Solautyc Team to standardize model definitions and common services across multiple packages.
52
52
 
53
+ > 📖 **Conventions reference**: this package follows the [2fast-handbook](https://github.com/AngelDanielSanchezCastillo/2fast-handbook) for ecosystem conventions (structure, versioning, README, commits, release).
54
+
53
55
  ## Installation
54
56
 
55
57
  You can install this package from PyPI (if published) or use it locally within your workspace:
@@ -2,6 +2,8 @@
2
2
 
3
3
  Shared tools, mixins, and base services for FastAPI applications. Designed for internal use by the Solautyc Team to standardize model definitions and common services across multiple packages.
4
4
 
5
+ > 📖 **Conventions reference**: this package follows the [2fast-handbook](https://github.com/AngelDanielSanchezCastillo/2fast-handbook) for ecosystem conventions (structure, versioning, README, commits, release).
6
+
5
7
  ## Installation
6
8
 
7
9
  You can install this package from PyPI (if published) or use it locally within your workspace:
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tools2fast-fastapi"
7
- version = "0.3.11"
7
+ dynamic = ["version"]
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"
@@ -61,6 +61,15 @@ package-dir = {"" = "src"}
61
61
  where = ["src"]
62
62
  include = ["tools2fast_fastapi*"]
63
63
 
64
+ # Single source of truth for the version: __version__.py
65
+ [tool.setuptools.dynamic]
66
+ version = {attr = "tools2fast_fastapi.__version__.__version__"}
67
+
68
+ [tool.setuptools.package-data]
69
+ tools2fast_fastapi = [
70
+ "skills/*.md",
71
+ ]
72
+
64
73
  [tool.pytest.ini_options]
65
74
  testpaths = ["tests"]
66
75
  python_files = ["test_*.py"]
@@ -0,0 +1 @@
1
+ __version__ = "0.3.13"
@@ -1,6 +1,7 @@
1
1
  from .document_simple_revision_service import DocumentSimpleRevisionService
2
2
  from .document_with_items_revision_service import DocumentWithItemsRevisionService
3
3
  from .number_service import get_next_number
4
+ from .query_filters import apply_filters, build_count, list_with_total
4
5
  from .revision_service import get_latest_revision, list_revisions, create_revision, clone_children
5
6
  from .transaction_service import TransactionService
6
7
 
@@ -9,6 +10,9 @@ __all__ = [
9
10
  "DocumentSimpleRevisionService",
10
11
  "DocumentWithItemsRevisionService",
11
12
  "get_next_number",
13
+ "apply_filters",
14
+ "build_count",
15
+ "list_with_total",
12
16
  "get_latest_revision",
13
17
  "list_revisions",
14
18
  "create_revision",
@@ -0,0 +1,122 @@
1
+ """Filtros de consulta genericos reutilizables para listados paginados.
2
+
3
+ Provee un mini-DSL de filtros (igualdad exacta + sufijos), un constructor de
4
+ COUNT que reutiliza los WHERE filtrados y un helper que ejecuta las dos
5
+ consultas (total + items paginados) en una sola llamada.
6
+ """
7
+
8
+ from typing import Any, TypeVar, cast
9
+
10
+ from fastapi import HTTPException
11
+ from sqlalchemy import Select, func
12
+ from sqlalchemy.engine import Row
13
+ from sqlalchemy.sql.elements import ColumnElement
14
+ from sqlmodel.ext.asyncio.session import AsyncSession
15
+
16
+ ModelT = TypeVar("ModelT", bound=Any)
17
+
18
+ # Sufijos soportados por el DSL: <campo>__<sufijo>
19
+ _FILTER_SUFFIXES = ("__contains", "__in", "__gte", "__lte")
20
+
21
+
22
+ def _split_suffix(key: str) -> tuple[str, str]:
23
+ """Separa el campo del sufijo DSL (ej. 'code__contains' -> ('code', '__contains'))."""
24
+ for suffix in _FILTER_SUFFIXES:
25
+ if key.endswith(suffix) and len(key) > len(suffix):
26
+ return key[: -len(suffix)], suffix
27
+ return key, ""
28
+
29
+
30
+ def apply_filters(stmt: Select, model: type[ModelT], filters: dict) -> Select:
31
+ """Aplica filtros con whitelist sobre el statement.
32
+
33
+ Nombres planos = igualdad exacta (incluye booleanos y FKs). Sufijos:
34
+ - ``__contains``: contiene el texto (LIKE %valor%).
35
+ - ``__in``: pertenece a una lista de valores.
36
+ - ``__gte`` / ``__lte``: mayor/igual o menor/igual.
37
+ Los valores llegan tipados por FastAPI (no se coercionan aqui). Un campo
38
+ fuera de la whitelist del modelo lanza HTTPException 422 en espanol.
39
+ """
40
+ whitelist = {column.name for column in cast(Any, model).__table__.columns}
41
+ for key, value in filters.items():
42
+ # Parametros opcionales no enviados (None) se ignoran
43
+ if value is None:
44
+ continue
45
+ field, suffix = _split_suffix(key)
46
+ if field not in whitelist:
47
+ raise HTTPException(
48
+ status_code=422,
49
+ detail=(
50
+ f"Campo de filtro '{field}' no permitido para "
51
+ f"el modelo {model.__name__}."
52
+ ),
53
+ )
54
+ column = getattr(model, field)
55
+ column = cast(Any, column)
56
+ if suffix == "__contains":
57
+ stmt = stmt.where(column.contains(str(value)))
58
+ elif suffix == "__in":
59
+ stmt = stmt.where(column.in_(value))
60
+ elif suffix == "__gte":
61
+ stmt = stmt.where(column >= value)
62
+ elif suffix == "__lte":
63
+ stmt = stmt.where(column <= value)
64
+ else:
65
+ stmt = stmt.where(column == value)
66
+ return stmt
67
+
68
+
69
+ def build_count(stmt: Select, model: type[ModelT]) -> Select:
70
+ """Construye un ``select(func.count(model.id))`` con los WHERE filtrados.
71
+
72
+ Reutiliza las condiciones WHERE y los FROM/JOIN del statement (necesario
73
+ para statements base pre-construidos como el de latest-revision de
74
+ cotizaciones) pero excluye offset/limit, order_by y group_by: el total
75
+ siempre refleja el universo filtrado, no la pagina.
76
+ """
77
+ inner = stmt.order_by(None).group_by(None).offset(None).limit(None)
78
+ return inner.with_only_columns(func.count(cast(Any, model).id))
79
+
80
+
81
+ def _scalar_count(result: Any) -> int:
82
+ """Normaliza el valor del COUNT sin importar el tipo de statement.
83
+
84
+ ``session.exec`` devuelve un escalar puro cuando el statement es un
85
+ ``SelectOfScalar`` (sqlmodel.select) y un ``Row`` cuando es un ``Select``
86
+ plano de SQLAlchemy. Ambos representan el mismo valor.
87
+ """
88
+ first = result.one()
89
+ if isinstance(first, Row):
90
+ return int(first[0])
91
+ return int(first)
92
+
93
+
94
+ async def list_with_total(
95
+ session: AsyncSession,
96
+ stmt: Select,
97
+ model: type[ModelT],
98
+ filters: dict,
99
+ skip: int = 0,
100
+ limit: int = 50,
101
+ order_by: ColumnElement | None = None,
102
+ ) -> tuple[list, int]:
103
+ """Ejecuta las dos consultas de un listado paginado: total + items.
104
+
105
+ - ``count``: sin paginacion, reutilizando los mismos filtros (build_count).
106
+ - ``items``: con offset/limit y un order_by opcional.
107
+
108
+ Acepta un statement base pre-construido (p. ej. el de latest-revision de
109
+ cotizaciones) al que se le aplican los filtros encima. Devuelve
110
+ ``(items, total)`` donde total es el universo filtrado completo.
111
+ """
112
+ filtered = apply_filters(stmt, model, filters)
113
+ count_stmt = build_count(filtered, model)
114
+
115
+ total = _scalar_count(await session.exec(count_stmt))
116
+
117
+ items_stmt = filtered.offset(skip).limit(limit)
118
+ if order_by is not None:
119
+ items_stmt = items_stmt.order_by(order_by)
120
+
121
+ result = await session.exec(items_stmt)
122
+ return list(result.all()), total
@@ -0,0 +1,60 @@
1
+ ---
2
+ name: tools2fast-fastapi
3
+ description: "Trigger: working on or with tools2fast-fastapi. Shared base layer of the 2fast stack: model/schema mixins, APIResponse envelope, SafeRouter, revision and number services. Prevails over the 2fast-handbook base skill for this package."
4
+ license: MIT
5
+ metadata:
6
+ author: AngelDanielSanchezCastillo
7
+ version: "1.0"
8
+ ---
9
+
10
+ ## Purpose
11
+
12
+ Shared foundation consumed by nearly every 2fast package (oauth2fast,
13
+ permissions2fast, tenants2fast, cashing2fast, Metal-ERP): model mixins,
14
+ schema mixins, the response envelope (`APIResponse`), `SafeRouter`, audit
15
+ automation, and revision/document services. No settings module by design.
16
+
17
+ ## Import quirk — TWO mixin namespaces, same names
18
+
19
+ - Top-level `from tools2fast_fastapi import IdMixin, TimestampMixin, ...` exports the **MODEL** versions (`models/mixins.py`): DB columns — nullable BigInteger PK `id`, tz-aware `created_at`/`updated_at` with `onupdate`, `revision` defaults to 1, `NumberUniqueMixin` has NO `tenant_id`.
20
+ - `tools2fast_fastapi.schemas.*` are the validation-only versions: REQUIRED `id`, REQUIRED `revision`, `NumberUniqueMixin` REQUIRES `tenant_id`. A schema built on `NumberUniqueMixin` cannot round-trip the model.
21
+ - Never mix the two families in one class; downstream imports top-level (model) mixins — that re-export is a hard cross-package contract.
22
+
23
+ ## Envelope — `APIResponse`
24
+
25
+ - Success factories `ok/saved/created/deleted` return **bare Pydantic models** (HTTP 200 implied; a 201 must come from the route decorator).
26
+ - Error factories `fail(message, status_code=400)` / `payment_required` / `from_exception` return **`(model, http_status)` tuples** the caller must wrap in a `JSONResponse`.
27
+ - `error_type` Literal allows ONLY `controlled` / `unexpected` / `payment_required`. Unexpected errors **hide `error.detail`** (security) with fixed Spanish message "Ha ocurrido un error".
28
+ - `ERROR_RESPONSES` maps {400/402/404/500} → response classes (reuse for OpenAPI docs).
29
+ - `from_exception` treats `ValueError` subclasses as controlled 400; anything else → 500. Legacy `schemas.BaseResponse/DataResponse/ErrorResponse` still exported until all routers migrate.
30
+
31
+ ## SafeRouter / handle_exceptions (traps)
32
+
33
+ - Endpoints under `SafeRouter`/`handle_exceptions` MUST be `async def` — the wrapper awaits unconditionally, sync endpoints crash with TypeError.
34
+ - **`HTTPException` is NOT a controlled error** → it becomes a 500 with hidden detail (loses the intended 404). Only `ValueError` subclasses survive as 400s. Prefer `TransactionService` + explicit `APIResponse.fail`/`from_exception`; never rely on SafeRouter to emit 404s.
35
+
36
+ ## AuditTimestampMixin
37
+
38
+ - Only auto-audits **when tenants2fast is installed** (lazy import of `get_user_context` inside SQLAlchemy events; silently skipped otherwise). `created_by` filled only if absent; `updated_by` always set; `updated_at` force-set on every flush (even no-op updates).
39
+ - Revision clones copy `created_by`/`updated_by` verbatim (`_EXCLUDED_ON_CLONE = {"id", "created_at", "updated_at"}`) — new revisions carry stale audit attribution.
40
+
41
+ ## Revision / number services
42
+
43
+ - `RevisionMixin` invariant: the consumer table MUST declare `UniqueConstraint("number", "revision", ...)` — **services never enforce it**; "current revision = max revision" depends on that constraint.
44
+ - Item/document services key items by the numeric `number` column (AttributeError otherwise); deleted items are implicit (absent from the payload → not cloned); `create_document_with_items` **mutates the caller's dict** (injects the header FK).
45
+ - `get_next_number(session, model_class)` = `max(number) + 1` over the WHOLE table — not tenant-filtered, **not atomic** (race-prone under concurrency), safe only in per-tenant DBs, and untested.
46
+
47
+ ## Conventions
48
+
49
+ - Spanish response messages ("Éxito", "Guardado con éxito", "Ha ocurrido un error", "Pago requerido").
50
+ - All `error_type` values are Literals — only the three above exist.
51
+
52
+ ## Stale docs
53
+
54
+ - README claims services are "(coming soon)" — 5 service modules exist; its `docs/guide.md` and `examples/` only cover the 3 basic mixins. Docstrings reference a nonexistent `tenant.*` module (copied from the original project).
55
+ - `pyproject.toml` pins deps with `>=` ranges and leaves `pydantic`/`sqlalchemy`/`tenant2fast` undeclared (tenant2fast is imported lazily at runtime).
56
+
57
+ ## Golden rule (inherited)
58
+
59
+ Follow the 2fast-handbook base skill for layout/versioning/naming/README/commits/release.
60
+ Local edits are fine; NEVER bump/publish on your own — prepare the exact command and hand it to the developer.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tools2fast-fastapi
3
- Version: 0.3.11
3
+ Version: 0.3.13
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
@@ -50,6 +50,8 @@ Dynamic: license-file
50
50
 
51
51
  Shared tools, mixins, and base services for FastAPI applications. Designed for internal use by the Solautyc Team to standardize model definitions and common services across multiple packages.
52
52
 
53
+ > 📖 **Conventions reference**: this package follows the [2fast-handbook](https://github.com/AngelDanielSanchezCastillo/2fast-handbook) for ecosystem conventions (structure, versioning, README, commits, release).
54
+
53
55
  ## Installation
54
56
 
55
57
  You can install this package from PyPI (if published) or use it locally within your workspace:
@@ -20,11 +20,14 @@ src/tools2fast_fastapi/services/__init__.py
20
20
  src/tools2fast_fastapi/services/document_simple_revision_service.py
21
21
  src/tools2fast_fastapi/services/document_with_items_revision_service.py
22
22
  src/tools2fast_fastapi/services/number_service.py
23
+ src/tools2fast_fastapi/services/query_filters.py
23
24
  src/tools2fast_fastapi/services/revision_service.py
24
25
  src/tools2fast_fastapi/services/transaction_service.py
26
+ src/tools2fast_fastapi/skills/SKILL.md
25
27
  src/tools2fast_fastapi/utils/__init__.py
26
28
  src/tools2fast_fastapi/utils/routing.py
27
29
  tests/test_initial.py
30
+ tests/test_query_filters.py
28
31
  tests/test_response_schema.py
29
32
  tests/test_revision_service.py
30
33
  tests/test_schemas.py
@@ -0,0 +1,390 @@
1
+ """Pruebas independientes del paquete tools2fast-fastapi: query_filters.
2
+
3
+ Validan:
4
+ - apply_filters: DSL de filtros (igualdad exacta + sufijos __contains/__in/__gte/__lte),
5
+ booleans/FKs como igualdad, whitelist por modelo y campo desconocido -> HTTP 422.
6
+ - build_count: COUNT que reutiliza los WHERE filtrados y excluye offset/limit.
7
+ - list_with_total: dos queries (count + items paginados), acepta statements base
8
+ pre-construidos (caso cotizaciones => latest revision) y respeta el join.
9
+
10
+ Estas pruebas NO importan routers de Metal-ERP: son autocontenidas (pytest + aiosqlite)
11
+ y portables al repo de tools2fast-fastapi.
12
+ """
13
+
14
+ from typing import Any
15
+
16
+ import pytest
17
+ import pytest_asyncio
18
+ from fastapi import HTTPException
19
+ from sqlalchemy import BigInteger, Column, Integer, func
20
+ from sqlalchemy.engine import Row
21
+ from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
22
+ from sqlalchemy.pool import StaticPool
23
+ from sqlmodel import Field, SQLModel, select
24
+ from sqlmodel.ext.asyncio.session import AsyncSession
25
+
26
+ # PK BigInteger que, en SQLite (test), delega a Integer para conservar el
27
+ # autoincrement; en Postgres/SQLAlchemy mantiene BigInteger real.
28
+ BigIntPk = BigInteger().with_variant(Integer, "sqlite")
29
+
30
+ # Import del modulo en desarrollo: falla en RED porque query_filters no existe aun.
31
+ from tools2fast_fastapi.services.query_filters import (
32
+ apply_filters,
33
+ build_count,
34
+ list_with_total,
35
+ )
36
+
37
+
38
+ class ProductFilterModel(SQLModel, table=True):
39
+ """Modelo de prueba: replica columnas tipicas (familia/FK, stock, is_active)."""
40
+
41
+ __tablename__ = "tf_query_filter_product"
42
+
43
+ id: int | None = Field(
44
+ default=None,
45
+ sa_column=Column(BigIntPk, primary_key=True, autoincrement=True),
46
+ )
47
+ code: str = Field(index=True)
48
+ family_id: int | None = Field(default=None, index=True)
49
+ stock: int = Field(default=0)
50
+ is_active: bool = Field(default=True)
51
+
52
+
53
+ class FilterJoinModel(SQLModel, table=True):
54
+ """Modelo auxiliar para probar counts con statements base que traen JOINs."""
55
+
56
+ __tablename__ = "tf_query_filter_join"
57
+
58
+ id: int | None = Field(
59
+ default=None,
60
+ sa_column=Column(BigIntPk, primary_key=True, autoincrement=True),
61
+ )
62
+ product_id: int = Field(index=True)
63
+
64
+
65
+ @pytest_asyncio.fixture
66
+ async def db_engine() -> AsyncEngine:
67
+ """Engine SQLite in-memory compartido (StaticPool) para las pruebas."""
68
+ engine = create_async_engine(
69
+ "sqlite+aiosqlite://",
70
+ poolclass=StaticPool,
71
+ )
72
+ async with engine.begin() as conn:
73
+ # Solo creamos nuestras tablas; el metadata global puede contener otras.
74
+ await conn.run_sync(
75
+ SQLModel.metadata.create_all,
76
+ tables=[ProductFilterModel.__table__, FilterJoinModel.__table__],
77
+ )
78
+ yield engine
79
+ await engine.dispose()
80
+
81
+
82
+ @pytest_asyncio.fixture
83
+ async def session(db_engine: AsyncEngine) -> AsyncSession:
84
+ async with AsyncSession(db_engine, expire_on_commit=False) as s:
85
+ yield s
86
+
87
+
88
+ async def _seed_products(session: AsyncSession, rows: list[dict]) -> list[int]:
89
+ """Crea productos y devuelve sus IDs en orden de insercion."""
90
+ ids: list[int] = []
91
+ for data in rows:
92
+ product = ProductFilterModel(**data)
93
+ session.add(product)
94
+ await session.flush()
95
+ ids.append(int(product.id))
96
+ await session.commit()
97
+ return ids
98
+
99
+
100
+ async def _fetch_count(session: AsyncSession, stmt: Any) -> int:
101
+ """Extrae el valor del COUNT sin importar si exec devuelve Row o escalar."""
102
+ first = (await session.exec(stmt)).one()
103
+ if isinstance(first, Row):
104
+ return int(first[0])
105
+ return int(first)
106
+
107
+
108
+ # ─────────────────────────────────────────────────────────────────────────────
109
+ # apply_filters
110
+ # ─────────────────────────────────────────────────────────────────────────────
111
+
112
+
113
+ async def test_apply_filters_exact_and_suffix_dsl(session: AsyncSession) -> None:
114
+ """Igualdad exacta + __contains + __gte combinados filtran en AND."""
115
+ ids = await _seed_products(
116
+ session,
117
+ [
118
+ {"code": "A1-X", "family_id": 3, "stock": 10}, # cumple todo
119
+ {"code": "A1-X", "family_id": 3, "stock": 2}, # stock < 5 -> afuera
120
+ {"code": "B2-X", "family_id": 3, "stock": 10}, # code sin "A1" -> afuera
121
+ {"code": "A1-X", "family_id": 4, "stock": 10}, # otra familia -> afuera
122
+ ],
123
+ )
124
+
125
+ stmt = apply_filters(
126
+ select(ProductFilterModel),
127
+ ProductFilterModel,
128
+ {"family_id": 3, "code__contains": "A1", "stock__gte": 5},
129
+ )
130
+ result = await session.exec(stmt)
131
+ products = list(result.all())
132
+
133
+ assert [p.id for p in products] == [ids[0]]
134
+ assert products[0].code == "A1-X"
135
+ assert products[0].stock == 10
136
+
137
+
138
+ async def test_apply_filters_in_and_lte(session: AsyncSession) -> None:
139
+ """Sufijos __in y __lte generan IN (...) y <=."""
140
+ ids = await _seed_products(
141
+ session,
142
+ [
143
+ {"code": "P1", "family_id": 3, "stock": 4}, # in(3,4) y <=5
144
+ {"code": "P2", "family_id": 4, "stock": 5}, # in(3,4) y <=5
145
+ {"code": "P3", "family_id": 4, "stock": 9}, # stock muy alto -> afuera
146
+ {"code": "P4", "family_id": 9, "stock": 1}, # familia fuera -> afuera
147
+ ],
148
+ )
149
+
150
+ stmt = apply_filters(
151
+ select(ProductFilterModel),
152
+ ProductFilterModel,
153
+ {"family_id__in": [3, 4], "stock__lte": 5},
154
+ )
155
+ result = await session.exec(stmt)
156
+ products = list(result.all())
157
+
158
+ assert sorted(p.id for p in products) == sorted(ids[:2])
159
+
160
+
161
+ async def test_apply_filters_boolean_and_fk_equality(session: AsyncSession) -> None:
162
+ """Booleans y FK se tratan como igualdad exacta."""
163
+ ids = await _seed_products(
164
+ session,
165
+ [
166
+ {"code": "F4-A", "family_id": 4, "is_active": True}, # cumple
167
+ {"code": "F4-B", "family_id": 4, "is_active": False}, # inactivo -> afuera
168
+ {
169
+ "code": "F9-A",
170
+ "family_id": 9,
171
+ "is_active": True,
172
+ }, # otra familia -> afuera
173
+ ],
174
+ )
175
+
176
+ stmt = apply_filters(
177
+ select(ProductFilterModel),
178
+ ProductFilterModel,
179
+ {"is_active": True, "family_id": 4},
180
+ )
181
+ result = await session.exec(stmt)
182
+ products = list(result.all())
183
+
184
+ assert [p.id for p in products] == [ids[0]]
185
+
186
+
187
+ async def test_apply_filters_unknown_field_raises_422_spanish(
188
+ session: AsyncSession,
189
+ ) -> None:
190
+ """Campo fuera de la whitelist -> HTTPException 422 con mensaje en espanol."""
191
+ await _seed_products(session, [{"code": "X1", "family_id": 1, "stock": 1}])
192
+
193
+ with pytest.raises(HTTPException) as excinfo:
194
+ apply_filters(
195
+ select(ProductFilterModel),
196
+ ProductFilterModel,
197
+ {"impostor_field": 1},
198
+ )
199
+
200
+ assert excinfo.value.status_code == 422
201
+ assert "impostor_field" in str(excinfo.value.detail)
202
+
203
+
204
+ async def test_apply_filters_empty_filters_returns_all_rows(
205
+ session: AsyncSession,
206
+ ) -> None:
207
+ """Sin filtros el statement queda intacto (todos los registros)."""
208
+ ids = await _seed_products(
209
+ session,
210
+ [
211
+ {"code": c, "family_id": 1, "stock": i}
212
+ for i, c in enumerate(["A", "B", "C"])
213
+ ],
214
+ )
215
+
216
+ stmt = apply_filters(select(ProductFilterModel), ProductFilterModel, {})
217
+ result = await session.exec(stmt)
218
+ products = list(result.all())
219
+
220
+ assert sorted(p.id for p in products) == sorted(ids)
221
+
222
+
223
+ # ─────────────────────────────────────────────────────────────────────────────
224
+ # build_count
225
+ # ─────────────────────────────────────────────────────────────────────────────
226
+
227
+
228
+ async def test_build_count_ignores_paging(session: AsyncSession) -> None:
229
+ """Count usa los WHERE filtrados pero ignora offset/limit."""
230
+ await _seed_products(
231
+ session,
232
+ [{"code": f"F3-{i}", "family_id": 3, "stock": i} for i in range(25)]
233
+ + [{"code": f"F4-{i}", "family_id": 4, "stock": i} for i in range(5)],
234
+ )
235
+
236
+ # Statement filtrado por familia 3 con paginacion aplicada
237
+ filtered = select(ProductFilterModel).where(ProductFilterModel.family_id == 3)
238
+ paged = filtered.offset(10).limit(10)
239
+ count_stmt = build_count(paged, ProductFilterModel)
240
+
241
+ assert (
242
+ int(await _fetch_count(session, count_stmt)) == 25
243
+ ) # no 10 (limit) ni 30 (sin filtro)
244
+
245
+
246
+ async def test_build_count_empty_filters_counts_dataset(session: AsyncSession) -> None:
247
+ """Sin filtro, count = tamano total del dataset (aunque haya offset/limit)."""
248
+ await _seed_products(
249
+ session,
250
+ [{"code": f"P-{i}", "family_id": 1, "stock": i} for i in range(60)],
251
+ )
252
+
253
+ paged = select(ProductFilterModel).offset(20).limit(10)
254
+ count_stmt = build_count(paged, ProductFilterModel)
255
+
256
+ assert int(await _fetch_count(session, count_stmt)) == 60
257
+
258
+
259
+ async def test_build_count_excludes_aggregate_columns(session: AsyncSession) -> None:
260
+ """El count no incluye funciones agregadas del statement original."""
261
+ await _seed_products(
262
+ session,
263
+ [{"code": f"P-{i}", "family_id": 1, "stock": i} for i in range(5)],
264
+ )
265
+
266
+ # Simula un statement con group_by (como el COUNT(DISTINCT number) de cotizaciones)
267
+ grouped = select(
268
+ ProductFilterModel.family_id, func.count(ProductFilterModel.id)
269
+ ).group_by(ProductFilterModel.family_id)
270
+ count_stmt = build_count(grouped, ProductFilterModel)
271
+
272
+ assert (
273
+ int(await _fetch_count(session, count_stmt)) == 5
274
+ ) # filas base, no la agregacion
275
+
276
+
277
+ # ─────────────────────────────────────────────────────────────────────────────
278
+ # list_with_total
279
+ # ─────────────────────────────────────────────────────────────────────────────
280
+
281
+
282
+ async def test_list_with_total_filtered_across_pages(session: AsyncSession) -> None:
283
+ """25 filas que matchean: skip=10/limit=10 => 10 items y total=25 (no page length)."""
284
+ ids = await _seed_products(
285
+ session,
286
+ [{"code": f"F3-{i}", "family_id": 3, "stock": i} for i in range(25)]
287
+ + [{"code": f"F4-{i}", "family_id": 4, "stock": i} for i in range(7)],
288
+ )
289
+
290
+ items, total = await list_with_total(
291
+ session,
292
+ select(ProductFilterModel),
293
+ ProductFilterModel,
294
+ {"family_id": 3},
295
+ skip=10,
296
+ limit=10,
297
+ order_by=ProductFilterModel.id,
298
+ )
299
+
300
+ assert len(items) == 10
301
+ assert total == 25
302
+ # Pagina 2 (items 11..20): los 25 de la familia 3 son los primeros 25 ids
303
+ assert [p.id for p in items] == ids[10:20]
304
+
305
+
306
+ async def test_list_with_total_empty_filters_and_bounds(session: AsyncSession) -> None:
307
+ """Sin filtros: primeros N rows (skip=0, limit=50) y total = tamano del dataset."""
308
+ ids = await _seed_products(
309
+ session,
310
+ [{"code": f"P-{i}", "family_id": 1, "stock": i} for i in range(80)],
311
+ )
312
+
313
+ items, total = await list_with_total(
314
+ session,
315
+ select(ProductFilterModel),
316
+ ProductFilterModel,
317
+ {},
318
+ skip=0,
319
+ limit=50,
320
+ order_by=ProductFilterModel.id,
321
+ )
322
+
323
+ assert len(items) == 50
324
+ assert total == 80
325
+ assert [p.id for p in items] == ids[:50]
326
+
327
+
328
+ async def test_list_with_total_accepts_prebuilt_base_statement(
329
+ session: AsyncSession,
330
+ ) -> None:
331
+ """Acepta un statement base pre-filtrado (caso cotizaciones latest-revision)."""
332
+ await _seed_products(
333
+ session,
334
+ [
335
+ {"code": f"F3H-{i}", "family_id": 3, "stock": 10} for i in range(8)
336
+ ] # cumple base (stock>=5) y filtro extra (familia 3)
337
+ + [
338
+ {"code": f"F3L-{i}", "family_id": 3, "stock": 1} for i in range(4)
339
+ ] # base lo excluye (stock<5)
340
+ + [
341
+ {"code": f"F4H-{i}", "family_id": 4, "stock": 10} for i in range(3)
342
+ ], # pasa base pero filtro extra (familia 3) lo excluye
343
+ )
344
+
345
+ base_stmt = select(ProductFilterModel).where(ProductFilterModel.stock >= 5)
346
+
347
+ items, total = await list_with_total(
348
+ session,
349
+ base_stmt,
350
+ ProductFilterModel,
351
+ {"family_id": 3},
352
+ skip=2,
353
+ limit=4,
354
+ )
355
+
356
+ assert len(items) == 4 # paginacion respetada sobre el base + filtros
357
+ assert total == 8 # solo los F3H: base (stock>=5) AND familia 3
358
+
359
+
360
+ async def test_list_with_total_preserves_join_in_count(session: AsyncSession) -> None:
361
+ """El total de un statement base con JOIN cuenta SOLO las filas del join."""
362
+ await _seed_products(
363
+ session,
364
+ [{"code": f"P-{i}", "family_id": 1, "stock": i} for i in range(3)],
365
+ )
366
+ # Solo los productos 1 y 2 tienen fila en el join
367
+ session.add_all(
368
+ [
369
+ FilterJoinModel(product_id=1, id=1),
370
+ FilterJoinModel(product_id=2, id=2),
371
+ ]
372
+ )
373
+ await session.commit()
374
+
375
+ base_stmt = select(ProductFilterModel).join(
376
+ FilterJoinModel,
377
+ FilterJoinModel.product_id == ProductFilterModel.id,
378
+ )
379
+
380
+ items, total = await list_with_total(
381
+ session,
382
+ base_stmt,
383
+ ProductFilterModel,
384
+ {},
385
+ skip=0,
386
+ limit=50,
387
+ )
388
+
389
+ assert total == 2 # el count NO debe ignorar el join (seria 3)
390
+ assert sorted(int(p.id) for p in items) == [1, 2]
@@ -1 +0,0 @@
1
- __version__ = "0.3.11"