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 # 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) app = FastAPI(title="Checklist Inteligente API", version=BACKEND_VERSION)
# S3/MinIO configuration # S3/MinIO configuration
@@ -963,13 +963,13 @@ def create_question(
db_question = models.Question(**question.dict()) db_question = models.Question(**question.dict())
db.add(db_question) 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.commit()
db.refresh(db_question) 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 # Registrar auditoría
audit_log = models.QuestionAuditLog( audit_log = models.QuestionAuditLog(
question_id=db_question.id, question_id=db_question.id,
@@ -1033,9 +1033,8 @@ def update_question(
}) })
setattr(db_question, key, value) setattr(db_question, key, value)
# Si cambiaron los puntos, recalcular max_score del checklist # Si cambiaron los puntos, hacer flush y recalcular
if any(change['field'] == 'points' for change in changes): points_changed = any(change['field'] == 'points' for change in changes)
recalculate_checklist_max_score(db_question.checklist_id, db)
db.commit() db.commit()
db.refresh(db_question) db.refresh(db_question)
@@ -1057,6 +1056,11 @@ def update_question(
if changes: if changes:
db.commit() 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 return db_question
@@ -1160,9 +1164,10 @@ def delete_question(
) )
db.add(sub_audit_log) db.add(sub_audit_log)
# Recalcular max_score del checklist después de eliminar db.commit()
recalculate_checklist_max_score(db_question.checklist_id, db)
# Recalcular max_score del checklist DESPUÉS del commit
recalculate_checklist_max_score(db_question.checklist_id, db)
db.commit() db.commit()
message = "Pregunta eliminada exitosamente" message = "Pregunta eliminada exitosamente"