fix(typing): resolucion integral de advertencias de tipado, extraccion de payload con get_request_payload y limpieza de modelos

This commit is contained in:
2026-10-19 16:02:42 -03:00
parent 5ed62d5d30
commit eff5ed5ce0
13 changed files with 78 additions and 235 deletions
+1 -9
View File
@@ -21,15 +21,7 @@ class AuditLog(db.Model):
# Relación con usuario
user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('audit_records', lazy='dynamic'))
def __init__(self, user_id=None, user_email=None, action=None, module=None, entity_id=None, details=None, ip_address=None, **kwargs):
super().__init__()
self.user_id = user_id
self.user_email = user_email
self.action = action
self.module = module
self.entity_id = entity_id
self.details = details
self.ip_address = ip_address
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
+3 -3
View File
@@ -177,7 +177,7 @@ class GeneticAlgorithm:
"""Run genetic algorithm with high concurrency to find optimal reservation schedule"""
import concurrent.futures
classrooms_dict = {c.id: c for c in available_classrooms}
classrooms_dict: Dict[int, Classroom] = {int(c.id): c for c in available_classrooms}
requests_dict = {r.commission_id: r for r in requests}
# Initialize population
@@ -263,7 +263,7 @@ class GeneticAlgorithm:
gene = Gene(
commission_id=request.commission_id,
classroom_id=classroom.id,
classroom_id=int(classroom.id),
start_time=start_time,
end_time=end_time,
expected_attendees=request.expected_attendees,
@@ -309,7 +309,7 @@ class GeneticAlgorithm:
# Change classroom
suitable_classrooms = [c for c in classrooms if c.capacity >= gene_to_mutate.expected_attendees]
if suitable_classrooms:
gene_to_mutate.classroom_id = random.choice(suitable_classrooms).id
gene_to_mutate.classroom_id = int(random.choice(suitable_classrooms).id)
elif mutation_type == 'time':
# Slightly adjust time
+3 -2
View File
@@ -58,7 +58,7 @@ class MilestoneGrade(db.Model):
"""Determina si la nota está aprobada (>= 4.00 y no ausente)."""
if self.is_absent or self.score is None:
return False
return self.score >= 4.0
return bool(float(self.score) >= 4.0)
@property
def display_score(self) -> str:
@@ -66,7 +66,8 @@ class MilestoneGrade(db.Model):
if self.is_absent:
return 'Ausente'
if self.score is not None:
return f'{self.score:.1f}' if self.score % 1 != 0 else f'{int(self.score)}'
val = float(self.score)
return f'{val:.1f}' if val % 1 != 0 else f'{int(val)}'
return '-'
def to_dict(self):
+2 -9
View File
@@ -100,7 +100,7 @@ class Role(db.Model):
# Relationships
permissions = db.relationship('Permission', backref='role', lazy='joined', cascade='all, delete-orphan')
users: Any = db.relationship('User', backref='role_obj', lazy='select')
users = db.relationship('User', backref='role_obj', lazy='select')
def __init__(self, **kwargs):
super().__init__(**kwargs)
@@ -167,14 +167,7 @@ class Permission(db.Model):
db.UniqueConstraint('role_id', 'module', name='uq_role_module'),
)
def __init__(self, role=None, role_id=None, module=None, access_level='none', **kwargs):
super().__init__()
if role is not None:
self.role = role
if role_id is not None:
self.role_id = role_id
self.module = module
self.access_level = access_level
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
+1 -6
View File
@@ -256,12 +256,7 @@ class CommissionTeacher(db.Model):
__table_args__ = (db.UniqueConstraint('commission_id', 'user_id'),)
def __init__(self, commission_id=None, user_id=None, role='Titular', is_primary=False, **kwargs):
super().__init__()
self.commission_id = commission_id
self.user_id = user_id
self.role = role
self.is_primary = is_primary
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
+3 -3
View File
@@ -35,16 +35,16 @@ class MoodleSyncTask(db.Model):
@property
def payload(self):
try:
return json.loads(self._payload) if self._payload else {}
return json.loads(str(self._payload)) if self._payload else {}
except Exception:
return {}
@payload.setter
def payload(self, val):
if isinstance(val, (dict, list)):
self._payload = json.dumps(val)
setattr(self, '_payload', json.dumps(val))
else:
self._payload = str(val or '{}')
setattr(self, '_payload', str(val or '{}'))
def get_payload_dict(self):
return self.payload
+3 -3
View File
@@ -54,11 +54,11 @@ class User(db.Model):
def set_password(self, password):
"""Set password hash"""
self.password_hash = generate_password_hash(password, method='pbkdf2:sha256')
setattr(self, 'password_hash', generate_password_hash(password, method='pbkdf2:sha256'))
def check_password(self, password):
"""Check password"""
return check_password_hash(self.password_hash, password)
return check_password_hash(str(self.password_hash or ''), password)
def is_admin(self):
"""Check if user is admin"""
@@ -146,7 +146,7 @@ class User(db.Model):
def update_last_login(self):
"""Update last login timestamp"""
self.last_login = datetime.now(timezone.utc).replace(tzinfo=None)
setattr(self, 'last_login', datetime.now(timezone.utc).replace(tzinfo=None))
db.session.commit()
def to_dict(self):
+22 -7
View File
@@ -8,13 +8,13 @@ class AuditService:
"""Servicio para la captura y consulta de la bitácora inmutable de auditoría."""
@staticmethod
def log(action: str, module: str, entity_id: Optional[int] = None,
details: Optional[Any] = None, user: Optional[User] = None,
def log(action: str, module: str, entity_id: Optional[Any] = None,
details: Optional[Any] = None, user: Optional[Any] = None,
ip_address: Optional[str] = None,
user_id: Optional[int] = None,
user_email: Optional[str] = None,
user_id: Optional[Any] = None,
user_email: Optional[Any] = None,
status: Optional[str] = None,
**kwargs) -> AuditLog:
**kwargs) -> Optional[AuditLog]:
"""
Registra un evento de auditoría de forma segura e inmutable.
"""
@@ -28,8 +28,23 @@ class AuditService:
# 1. Determinar usuario actuante
if user:
user_id = user.id
user_email = user.email
user_id = getattr(user, 'id', None)
user_email = getattr(user, 'email', None)
if user_id is not None:
try:
user_id = int(user_id)
except Exception:
pass
if user_email is not None:
user_email = str(user_email)
if entity_id is not None:
try:
entity_id = int(entity_id)
except Exception:
pass
# 2. IP de origen
if not ip_address:
+4 -3
View File
@@ -28,17 +28,18 @@ class CryptoService:
return encrypted_bytes.decode('utf-8')
@classmethod
def decrypt(cls, cipher_text: str) -> str:
def decrypt(cls, cipher_text: Any) -> str:
"""Descifra un texto cifrado y retorna el texto original. Si falla, retorna vacío."""
if not cipher_text:
return ''
cipher_str = str(cipher_text)
try:
fernet = cls._get_fernet()
decrypted_bytes = fernet.decrypt(cipher_text.encode('utf-8'))
decrypted_bytes = fernet.decrypt(cipher_str.encode('utf-8'))
return decrypted_bytes.decode('utf-8')
except Exception:
# Si no era un texto cifrado con Fernet o fue alterado, retornar el texto tal cual o vacío
return cipher_text
return cipher_str
crypto_service = CryptoService()
+3 -7
View File
@@ -105,12 +105,8 @@ class OptimizerService:
with cls._lock:
cls._jobs[job_id] = job
# Si no se pasó app explícitamente, intentar obtener current_app
if app is None:
try:
app = getattr(current_app, '_get_current_object', lambda: current_app)()
except Exception:
app = None
# No background app context required in FastAPI
app = None
thread = threading.Thread(
target=cls._run_job_worker,
@@ -217,7 +213,7 @@ class OptimizerService:
is_virtual=c_dto.isVirtual,
is_active=True
)
room.id = c_dto.classroomId
setattr(room, 'id', c_dto.classroomId)
classrooms.append(room)
else:
classrooms = Classroom.query.filter_by(is_active=True).all()