add import audit trail, live indicator recompute, reportes endpoints; production hardening

This commit is contained in:
Roberto Treviño Cervantes
2026-10-30 11:19:30 -06:00
parent 168edb30f5
commit 2b2c290f58
74 changed files with 4095 additions and 1782 deletions
+23 -19
View File
@@ -25,6 +25,10 @@ class ImportRequestError(Exception):
bad connection string or an invalid on_conflict. Mapped to HTTP 400."""
class DatabaseRefused(ImportRequestError):
"""The database rejected the batch at write time; nothing was written."""
@dataclass(frozen=True)
class ImportSource:
"""One parsed and structurally validated entry of a request's `sources`."""
@@ -40,32 +44,32 @@ class ImportSource:
@classmethod
def parse(cls, raw: Any) -> "ImportSource":
if not isinstance(raw, dict):
raise ImportRequestError("each source must be an object")
raise ImportRequestError("cada fuente debe ser un objeto")
target = raw.get("target")
if not target:
raise ImportRequestError("source is missing 'target'")
raise ImportRequestError("a la fuente le falta 'target'")
spec = ENTITY_REGISTRY.get(target)
if spec is None:
raise ImportRequestError(f"unknown target: {target!r}")
raise ImportRequestError(f"destino desconocido: {target!r}")
fields = set(spec.schema.model_fields)
mapping = raw.get("column_mapping") or {}
defaults = raw.get("defaults") or {}
if not isinstance(mapping, dict) or not isinstance(defaults, dict):
raise ImportRequestError("'column_mapping' and 'defaults' must be objects")
raise ImportRequestError("'column_mapping' y 'defaults' deben ser objetos")
unknown = sorted((set(mapping.values()) | set(defaults)) - fields)
if unknown:
raise ImportRequestError(f"{target} has no field(s) {unknown}")
raise ImportRequestError(f"{target} no tiene los campos {unknown}")
targets = list(mapping.values())
duplicated = sorted({t for t in targets if targets.count(t) > 1})
if duplicated:
raise ImportRequestError(f"more than one source column mapped to {duplicated}")
raise ImportRequestError(f"más de una columna de origen asignada a {duplicated}")
if not mapping and not defaults:
raise ImportRequestError(f"source for {target} maps no columns")
raise ImportRequestError(f"la fuente de {target} no asigna ninguna columna")
payload = raw.get("payload")
if not isinstance(payload, dict):
raise ImportRequestError("source is missing 'payload'")
raise ImportRequestError("a la fuente le falta 'payload'")
return cls(
source_type=raw.get("source_type", ""),
target=target,
@@ -159,12 +163,12 @@ class SourceCommitResult:
def _parse_batch(raw_sources: Any) -> list[ImportSource]:
if not isinstance(raw_sources, list) or not raw_sources:
raise ImportRequestError("'sources' must be a non-empty list")
raise ImportRequestError("'sources' debe ser una lista no vacía")
sources = [ImportSource.parse(raw) for raw in raw_sources]
domains = sorted({source.domain for source in sources})
if len(domains) > 1:
raise ImportRequestError(
f"a batch cannot mix domains — got {domains}, every source must target the same one"
f"un lote no puede mezclar dominios ({', '.join(domains)}): todas las fuentes deben ir al mismo"
)
return sources
@@ -214,11 +218,8 @@ def merge_duplicates(sources: list[ImportSource], rows: list[list[dict[str, Any]
def _key_part(value: Any) -> Any:
"""Normalized for comparison across sources: a CSV's natural key is
always a string ("5001"), while a typed source (the document extractor,
a SQL column) can hand back an int or a date for the very same value.
Stringifying both sides is what lets rows that describe the same record
actually match, instead of silently landing as two separate ones."""
"""Normalized for comparison across sources: a CSV key is the string "5001"
where a typed source gives the int 5001."""
if _is_blank(value):
return None
return str(value).strip().upper()
@@ -232,14 +233,14 @@ def commit_sources(
try:
policy = ConflictPolicy(on_conflict)
except ValueError as exc:
raise ImportRequestError(f"invalid on_conflict: {on_conflict!r}") from exc
raise ImportRequestError(f"on_conflict inválido: {on_conflict!r}") from exc
sources = _parse_batch(raw_sources)
tracked = [audit.source(source) for source in sources] if audit else []
if policy is ConflictPolicy.UPSERT:
keyless = sorted({s.target for s in sources if not s.spec.conflict_fields})
if keyless:
raise ImportRequestError(f"{', '.join(keyless)} has no natural key — on_conflict=upsert is not valid for it")
raise ImportRequestError(f"{', '.join(keyless)} no tiene llave natural: on_conflict=upsert no aplica")
# Read + validate everything before opening the write transaction, so a
# slow source (OCR, a remote SQL table) never holds database locks.
@@ -274,7 +275,7 @@ def commit_sources(
"row_index": validation.accepted_rows[outcome.index].row_index,
"field": ",".join(source.spec.conflict_fields or ()),
"category": "conflict",
"message": outcome.error or "conflict",
"message": outcome.error or "conflicto",
"raw_value": _jsonable(
validation.accepted_rows[outcome.index].data.get((source.spec.conflict_fields or ("",))[0])
),
@@ -303,7 +304,10 @@ def commit_sources(
session.commit()
except SQLAlchemyError as exc:
session.rollback()
raise ImportRequestError(f"the database refused the batch, nothing was written: {exc.__class__.__name__}: {exc.orig if hasattr(exc, 'orig') else exc}") from exc
detail = exc.orig if hasattr(exc, "orig") else exc
raise DatabaseRefused(
f"la base de datos rechazó el lote y no se escribió nada: {exc.__class__.__name__}: {detail}"
) from exc
finally:
session.close()
return [results[i] for i in range(len(validated))]