feat: Version 1.10.0 - Refactorizacion, optimizacion UI y mejoras de seguridad

- Extraccion de helpers en backend: audit_helpers.py, helpers.py
- Modularizacion de schemas en archivos individuales por dominio
- Reduccion de audit.py en 953 lineas (74% del archivo)
- Reduccion de tickets.py en 655 lineas (60% del archivo)
- Expansion de auth.py con recuperacion de contrasenia y tokens
- Nuevos modulos: core/email.py, core/cache.py
- Reorganizacion de scripts a backend/scripts/
- Frontend: refactorizacion de audit page con array-driven components
- Frontend: correccion de 11 errores ortograficos en tickets page
- Frontend: proxy Docker corregido en vite.config.js
- Frontend: nuevas rutas forgot-password, reset-password, organization, profile
- Nuevas utilidades TS: colorUtils.ts, dateFormats.ts
- 5 nuevos archivos de tests unitarios en backend/tests/unit/
- Eliminacion de 3 scripts temporales de prueba
- Documentacion tecnica: CAMBIOS_v1.10.0.md, OPTIMIZACIONES_RENDIMIENTO.md
This commit is contained in:
2026-02-19 13:48:21 -07:00
parent 16d795e8bd
commit 517297e89a
57 changed files with 8022 additions and 3660 deletions

308
backend/app/core/cache.py Normal file
View File

@@ -0,0 +1,308 @@
"""
Redis Caching Service - ServiceManagerWeb
Servicio centralizado para manejo de caché con Redis.
"""
from redis import asyncio as aioredis
from typing import Optional, Any, Union
import json
import structlog
from functools import wraps
from app.core.config import get_settings
logger = structlog.get_logger(__name__)
settings = get_settings()
class CacheService:
"""
Servicio de caché usando Redis.
Proporciona métodos para get/set/delete de datos con serialización JSON.
Usa un singleton pattern para compartir la conexión Redis.
"""
_instance = None
_redis = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
async def connect(self):
"""Conectar a Redis si aún no está conectado."""
if self._redis is None:
try:
self._redis = await aioredis.from_url(
settings.REDIS_URL,
encoding="utf-8",
decode_responses=True,
socket_connect_timeout=5,
socket_timeout=5
)
logger.info("Redis cache connected", url=settings.REDIS_URL)
except Exception as e:
logger.error("Failed to connect to Redis", error=str(e))
self._redis = None
async def disconnect(self):
"""Cerrar conexión Redis."""
if self._redis:
await self._redis.close()
self._redis = None
logger.info("Redis cache disconnected")
async def get(self, key: str) -> Optional[Any]:
"""
Obtener valor del cache.
Args:
key: Clave del cache
Returns:
Valor deserializado o None si no existe
"""
if self._redis is None:
await self.connect()
if self._redis is None:
logger.warning("Redis not available, skipping cache get", key=key)
return None
try:
value = await self._redis.get(key)
if value:
logger.debug("Cache hit", key=key)
return json.loads(value)
logger.debug("Cache miss", key=key)
return None
except Exception as e:
logger.error("Cache get error", key=key, error=str(e))
return None
async def set(
self,
key: str,
value: Any,
ttl: int = 300
) -> bool:
"""
Guardar valor en cache.
Args:
key: Clave del cache
value: Valor a guardar (será serializado a JSON)
ttl: Tiempo de vida en segundos (default: 5 minutos)
Returns:
True si se guardó exitosamente
"""
if self._redis is None:
await self.connect()
if self._redis is None:
logger.warning("Redis not available, skipping cache set", key=key)
return False
try:
serialized = json.dumps(value, default=str)
await self._redis.setex(key, ttl, serialized)
logger.debug("Cache set", key=key, ttl=ttl)
return True
except Exception as e:
logger.error("Cache set error", key=key, error=str(e))
return False
async def delete(self, key: str) -> bool:
"""
Eliminar clave del cache.
Args:
key: Clave a eliminar
Returns:
True si se eliminó exitosamente
"""
if self._redis is None:
await self.connect()
if self._redis is None:
logger.warning("Redis not available, skipping cache delete", key=key)
return False
try:
await self._redis.delete(key)
logger.debug("Cache delete", key=key)
return True
except Exception as e:
logger.error("Cache delete error", key=key, error=str(e))
return False
async def delete_pattern(self, pattern: str) -> int:
"""
Eliminar todas las claves que coincidan con el patrón.
Args:
pattern: Patrón de búsqueda (ej: "tickets:tenant:*")
Returns:
Número de claves eliminadas
"""
if self._redis is None:
await self.connect()
if self._redis is None:
logger.warning("Redis not available, skipping pattern delete", pattern=pattern)
return 0
try:
keys = []
async for key in self._redis.scan_iter(pattern):
keys.append(key)
if keys:
deleted = await self._redis.delete(*keys)
logger.info("Cache pattern delete", pattern=pattern, deleted=deleted)
return deleted
return 0
except Exception as e:
logger.error("Cache pattern delete error", pattern=pattern, error=str(e))
return 0
async def exists(self, key: str) -> bool:
"""
Verificar si una clave existe en cache.
Args:
key: Clave a verificar
Returns:
True si existe
"""
if self._redis is None:
await self.connect()
if self._redis is None:
return False
try:
return await self._redis.exists(key) > 0
except Exception as e:
logger.error("Cache exists error", key=key, error=str(e))
return False
async def incr(self, key: str, amount: int = 1) -> Optional[int]:
"""
Incrementar un contador en cache.
Args:
key: Clave del contador
amount: Cantidad a incrementar
Returns:
Nuevo valor del contador
"""
if self._redis is None:
await self.connect()
if self._redis is None:
return None
try:
return await self._redis.incrby(key, amount)
except Exception as e:
logger.error("Cache incr error", key=key, error=str(e))
return None
async def expire(self, key: str, ttl: int) -> bool:
"""
Establecer tiempo de expiración a una clave existente.
Args:
key: Clave a expirar
ttl: Tiempo de vida en segundos
Returns:
True si se estableció exitosamente
"""
if self._redis is None:
await self.connect()
if self._redis is None:
return False
try:
return await self._redis.expire(key, ttl)
except Exception as e:
logger.error("Cache expire error", key=key, error=str(e))
return False
# Singleton instance
cache = CacheService()
def cache_key(*parts: str) -> str:
"""
Helper para construir claves de cache consistentes.
Args:
*parts: Partes de la clave a unir
Returns:
Clave formateada
Example:
cache_key("tickets", "tenant", tenant_id) -> "tickets:tenant:123"
"""
return ":".join(str(part) for part in parts)
def cached(
key_prefix: str,
ttl: int = 300,
key_builder: Optional[callable] = None
):
"""
Decorator para cachear resultados de funciones async.
Args:
key_prefix: Prefijo para la clave de cache
ttl: Tiempo de vida en segundos
key_builder: Función opcional para construir la clave
Example:
@cached("categories", ttl=600)
async def get_categories(tenant_id: str):
return await db.query(Category).all()
"""
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
# Construir clave de cache
if key_builder:
key = key_builder(*args, **kwargs)
else:
# Default: usar nombre de función y args
key_parts = [key_prefix, func.__name__]
key_parts.extend(str(arg) for arg in args)
key_parts.extend(f"{k}={v}" for k, v in sorted(kwargs.items()))
key = cache_key(*key_parts)
# Intentar obtener del cache
cached_value = await cache.get(key)
if cached_value is not None:
return cached_value
# Si no está en cache, ejecutar función
result = await func(*args, **kwargs)
# Guardar en cache
await cache.set(key, result, ttl=ttl)
return result
return wrapper
return decorator

View File

@@ -27,7 +27,7 @@ class Settings(BaseSettings):
DEBUG: bool = Field(default=False)
SECRET_KEY: str = Field(...)
API_VERSION: str = Field(default="v1")
APP_VERSION: str = Field(default="1.6.0")
APP_VERSION: str = Field(default="1.9.0")
# ===================================
# DATABASE

View File

@@ -19,10 +19,11 @@ settings = get_settings()
engine = create_async_engine(
settings.DATABASE_URL,
echo=settings.DEBUG,
pool_size=5,
max_overflow=10,
pool_size=20, # Increased for better concurrency
max_overflow=30, # Increased for peak loads
pool_pre_ping=True, # Verify connections before use
pool_recycle=3600, # Recycle connections after 1 hour
pool_timeout=30, # Wait up to 30s for connection from pool
)
# Create session factory

179
backend/app/core/email.py Normal file
View File

@@ -0,0 +1,179 @@
"""
Email Utility - ServiceManagerWeb
Envío directo de emails desde el backend para flujos críticos
(reseteo de contraseña, verificación) sin depender de Celery.
"""
import asyncio
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from typing import Optional
import structlog
from app.core.config import get_settings
settings = get_settings()
logger = structlog.get_logger(__name__)
def _send_smtp_sync(
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str] = None,
) -> None:
"""
Enviar email de forma síncrona vía SMTP.
Llamar desde asyncio.to_thread para no bloquear el event loop.
"""
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = f"{settings.DEFAULT_FROM_NAME} <{settings.DEFAULT_FROM_EMAIL}>"
msg["To"] = to_email
if text_content:
msg.attach(MIMEText(text_content, "plain", "utf-8"))
msg.attach(MIMEText(html_content, "html", "utf-8"))
if settings.SMTP_USE_SSL:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(settings.SMTP_HOST, settings.SMTP_PORT, context=context) as server:
if settings.SMTP_USER and settings.SMTP_PASSWORD:
server.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
server.sendmail(settings.DEFAULT_FROM_EMAIL, to_email, msg.as_string())
else:
with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) as server:
if settings.SMTP_USE_TLS:
server.starttls()
if settings.SMTP_USER and settings.SMTP_PASSWORD:
server.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
server.sendmail(settings.DEFAULT_FROM_EMAIL, to_email, msg.as_string())
async def send_email(
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str] = None,
) -> bool:
"""
Enviar email de forma asíncrona.
Retorna True si el envío fue exitoso, False con log de error si falló.
Se diseña para no propagar excepciones (fail-silent) en flujos de UI.
"""
try:
await asyncio.to_thread(
_send_smtp_sync,
to_email,
subject,
html_content,
text_content,
)
logger.info("Email sent", to=to_email, subject=subject)
return True
except Exception as exc:
logger.error("Email send failed", to=to_email, subject=subject, error=str(exc))
return False
# ============================================================
# Plantillas HTML inline
# ============================================================
def build_password_reset_email(reset_url: str, user_name: str) -> tuple[str, str]:
"""
Construir HTML y texto plano para email de reseteo de contraseña.
Returns:
(html_content, text_content)
"""
html = f"""
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Restablecer contraseña</title>
</head>
<body style="margin:0;padding:0;background:#f4f6f8;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6f8;padding:40px 0;">
<tr><td align="center">
<table width="560" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,.08);">
<!-- Header -->
<tr>
<td style="background:#1d4ed8;padding:32px 40px;text-align:center;">
<span style="color:#ffffff;font-size:22px;font-weight:700;letter-spacing:-.5px;">ServiceManager</span>
</td>
</tr>
<!-- Body -->
<tr>
<td style="padding:40px;">
<h2 style="margin:0 0 16px;font-size:20px;color:#111827;">Restablece tu contraseña</h2>
<p style="margin:0 0 12px;font-size:15px;color:#374151;line-height:1.6;">
Hola <strong>{user_name}</strong>,
</p>
<p style="margin:0 0 24px;font-size:15px;color:#374151;line-height:1.6;">
Recibimos una solicitud para restablecer la contraseña de tu cuenta.
Haz clic en el botón de abajo para crear una nueva contraseña.
Este enlace es válido por <strong>30 minutos</strong>.
</p>
<table cellpadding="0" cellspacing="0" style="margin:0 auto 32px;">
<tr>
<td style="background:#1d4ed8;border-radius:6px;">
<a href="{reset_url}"
style="display:inline-block;padding:14px 32px;color:#ffffff;font-size:15px;font-weight:600;text-decoration:none;border-radius:6px;">
Restablecer contraseña
</a>
</td>
</tr>
</table>
<p style="margin:0 0 8px;font-size:13px;color:#6b7280;">
Si no puedes hacer clic en el botón, copia y pega este enlace en tu navegador:
</p>
<p style="margin:0 0 24px;font-size:12px;color:#2563eb;word-break:break-all;">
<a href="{reset_url}" style="color:#2563eb;">{reset_url}</a>
</p>
<hr style="border:none;border-top:1px solid #e5e7eb;margin:24px 0;">
<p style="margin:0;font-size:13px;color:#9ca3af;line-height:1.6;">
Si no solicitaste restablecer tu contraseña, puedes ignorar este mensaje.
Tu contraseña no se modificará.<br>
Por seguridad, este enlace expira en 30 minutos y solo puede usarse una vez.
</p>
</td>
</tr>
<!-- Footer -->
<tr>
<td style="padding:20px 40px;background:#f9fafb;text-align:center;">
<p style="margin:0;font-size:12px;color:#9ca3af;">
&copy; 2026 Aduanasoft &mdash; Acceso exclusivo autorizado
</p>
</td>
</tr>
</table>
</td></tr>
</table>
</body>
</html>
"""
text = (
f"Hola {user_name},\n\n"
"Recibimos una solicitud para restablecer la contraseña de tu cuenta.\n\n"
f"Haz clic en el siguiente enlace (válido por 30 minutos):\n{reset_url}\n\n"
"Si no solicitaste este cambio, ignora este mensaje.\n\n"
"— ServiceManager"
)
return html, text