Corregido: Problema de timing en recálculo de max_score

🐛 Problema
Al crear 1 pregunta → max_score quedaba en 0
Al crear 2 preguntas → max_score mostraba 1
Al quedar 1 pregunta → max_score mostraba 0
🔍 Causa
Llamaba a recalculate_checklist_max_score() ANTES del db.commit(), entonces la consulta SQL no encontraba las preguntas recién agregadas/modificadas porque aún no estaban persistidas en la base de datos.
This commit is contained in:
2025-12-01 00:27:20 -03:00
parent d86a216766
commit 1988ec95da

View File

@@ -207,7 +207,7 @@ def send_completed_inspection_to_n8n(inspection, db):
# No lanzamos excepción para no interrumpir el flujo normal
BACKEND_VERSION = "1.0.88"
BACKEND_VERSION = "1.0.89"
app = FastAPI(title="Checklist Inteligente API", version=BACKEND_VERSION)
# S3/MinIO configuration
@@ -963,13 +963,13 @@ def create_question(
db_question = models.Question(**question.dict())
db.add(db_question)
# Recalcular max_score del checklist (más robusto que sumar)
recalculate_checklist_max_score(question.checklist_id, db)
db.commit()
db.refresh(db_question)
# Recalcular max_score del checklist DESPUÉS de persistir
recalculate_checklist_max_score(question.checklist_id, db)
db.commit()
# Registrar auditoría
audit_log = models.QuestionAuditLog(
question_id=db_question.id,
@@ -1033,9 +1033,8 @@ def update_question(
})
setattr(db_question, key, value)
# Si cambiaron los puntos, recalcular max_score del checklist
if any(change['field'] == 'points' for change in changes):
recalculate_checklist_max_score(db_question.checklist_id, db)
# Si cambiaron los puntos, hacer flush y recalcular
points_changed = any(change['field'] == 'points' for change in changes)
db.commit()
db.refresh(db_question)
@@ -1057,6 +1056,11 @@ def update_question(
if changes:
db.commit()
# Si cambiaron los puntos, recalcular DESPUÉS del commit
if points_changed:
recalculate_checklist_max_score(db_question.checklist_id, db)
db.commit()
return db_question
@@ -1160,9 +1164,10 @@ def delete_question(
)
db.add(sub_audit_log)
# Recalcular max_score del checklist después de eliminar
recalculate_checklist_max_score(db_question.checklist_id, db)
db.commit()
# Recalcular max_score del checklist DESPUÉS del commit
recalculate_checklist_max_score(db_question.checklist_id, db)
db.commit()
message = "Pregunta eliminada exitosamente"