Spaces:
Running
Running
deploy from github actions
Browse files- alembic/env.py +1 -1
- app/main.py +6 -0
- app/models/aprendizaje.py +0 -42
- app/routers/admin.py +3 -10
- app/routers/aprendizaje.py +58 -675
- app/routers/iglesia.py +0 -3
- init_supabase_db.py +1 -1
alembic/env.py
CHANGED
|
@@ -25,7 +25,7 @@ from app.models.user import User
|
|
| 25 |
from app.models.process import Task
|
| 26 |
from app.models.lyrics import Group, UserGroup, Lyric, Repertorio, RepertorioLyric, Invitation
|
| 27 |
from app.models.iglesia import Iglesia, IglesiaRol, IglesiaMember, Miembro, RelacionFamiliar, Calendario, Servicio, Asistencia, Finanza, Momento, Inventario
|
| 28 |
-
from app.models.aprendizaje import BibliaLibro, BibliaVersiculo, PlanLectura, DiaLectura, PreguntaQuiz, ProgresoPlan
|
| 29 |
from app.models.midi import PartituraMidi
|
| 30 |
|
| 31 |
# add your model's MetaData object here
|
|
|
|
| 25 |
from app.models.process import Task
|
| 26 |
from app.models.lyrics import Group, UserGroup, Lyric, Repertorio, RepertorioLyric, Invitation
|
| 27 |
from app.models.iglesia import Iglesia, IglesiaRol, IglesiaMember, Miembro, RelacionFamiliar, Calendario, Servicio, Asistencia, Finanza, Momento, Inventario
|
| 28 |
+
from app.models.aprendizaje import BibliaLibro, BibliaVersiculo, PlanLectura, DiaLectura, PreguntaQuiz, ProgresoPlan
|
| 29 |
from app.models.midi import PartituraMidi
|
| 30 |
|
| 31 |
# add your model's MetaData object here
|
app/main.py
CHANGED
|
@@ -28,6 +28,12 @@ _COLUMNAS_NUEVAS = [
|
|
| 28 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS peaks TEXT",
|
| 29 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS trabajo_json TEXT",
|
| 30 |
"ALTER TABLE workers ADD COLUMN IF NOT EXISTS publico_aprobado BOOLEAN",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
]
|
| 32 |
try:
|
| 33 |
from sqlalchemy import text as _sql_text
|
|
|
|
| 28 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS peaks TEXT",
|
| 29 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS trabajo_json TEXT",
|
| 30 |
"ALTER TABLE workers ADD COLUMN IF NOT EXISTS publico_aprobado BOOLEAN",
|
| 31 |
+
# El progreso de lectura es de la persona: no se pierde al salir o borrar una iglesia
|
| 32 |
+
"UPDATE progresos_plan SET iglesia_id = NULL WHERE iglesia_id IS NOT NULL",
|
| 33 |
+
# Aprendizaje es solo lectura: ya no existen ligas ni torneos
|
| 34 |
+
"DROP TABLE IF EXISTS participantes_torneo",
|
| 35 |
+
"DROP TABLE IF EXISTS torneos",
|
| 36 |
+
"DROP TABLE IF EXISTS puntuaciones_liga",
|
| 37 |
]
|
| 38 |
try:
|
| 39 |
from sqlalchemy import text as _sql_text
|
app/models/aprendizaje.py
CHANGED
|
@@ -66,45 +66,3 @@ class ProgresoPlan(Base):
|
|
| 66 |
user = relationship("User")
|
| 67 |
plan = relationship("PlanLectura")
|
| 68 |
iglesia = relationship("Iglesia")
|
| 69 |
-
|
| 70 |
-
class PuntuacionLiga(Base):
|
| 71 |
-
__tablename__ = "puntuaciones_liga"
|
| 72 |
-
id = Column(Integer, primary_key=True, index=True)
|
| 73 |
-
user_id = Column(Integer, ForeignKey("users.id"))
|
| 74 |
-
iglesia_id = Column(Integer, ForeignKey("iglesias.id"))
|
| 75 |
-
puntos_totales = Column(Integer, default=0)
|
| 76 |
-
maxima_racha = Column(Integer, default=0)
|
| 77 |
-
|
| 78 |
-
user = relationship("User")
|
| 79 |
-
iglesia = relationship("Iglesia")
|
| 80 |
-
|
| 81 |
-
class Torneo(Base):
|
| 82 |
-
__tablename__ = "torneos"
|
| 83 |
-
id = Column(Integer, primary_key=True, index=True)
|
| 84 |
-
codigo = Column(String, unique=True, index=True) # e.g. "BIB-7A2F"
|
| 85 |
-
nombre = Column(String)
|
| 86 |
-
creador_id = Column(Integer, ForeignKey("users.id"))
|
| 87 |
-
estado = Column(String, default="activo") # "activo", "desempate", "terminado"
|
| 88 |
-
ganador_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
| 89 |
-
preguntas_json = Column(Text) # JSON list of 5 question IDs
|
| 90 |
-
desempate_preguntas_json = Column(Text, nullable=True)
|
| 91 |
-
fecha_creacion = Column(String)
|
| 92 |
-
primero_termino_en = Column(String, nullable=True)
|
| 93 |
-
|
| 94 |
-
creador = relationship("User", foreign_keys=[creador_id])
|
| 95 |
-
ganador = relationship("User", foreign_keys=[ganador_id])
|
| 96 |
-
|
| 97 |
-
class ParticipanteTorneo(Base):
|
| 98 |
-
__tablename__ = "participantes_torneo"
|
| 99 |
-
id = Column(Integer, primary_key=True, index=True)
|
| 100 |
-
torneo_id = Column(Integer, ForeignKey("torneos.id"))
|
| 101 |
-
user_id = Column(Integer, ForeignKey("users.id"))
|
| 102 |
-
score = Column(Integer, default=0)
|
| 103 |
-
tiempo_empleado = Column(Float, default=0.0) # seconds taken
|
| 104 |
-
score_desempate = Column(Integer, default=0)
|
| 105 |
-
tiempo_desempate = Column(Float, default=0.0)
|
| 106 |
-
eliminado = Column(Boolean, default=False)
|
| 107 |
-
estado = Column(String, default="pendiente") # "pendiente", "jugado", "desempate_pendiente", "desempate_jugado"
|
| 108 |
-
|
| 109 |
-
user = relationship("User")
|
| 110 |
-
torneo = relationship("Torneo")
|
|
|
|
| 66 |
user = relationship("User")
|
| 67 |
plan = relationship("PlanLectura")
|
| 68 |
iglesia = relationship("Iglesia")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/routers/admin.py
CHANGED
|
@@ -451,7 +451,6 @@ def delete_church_admin(church_id: int, db: Session = Depends(get_db), current_a
|
|
| 451 |
|
| 452 |
# Eliminar en cascada absoluta en el orden correcto de integridad referencial
|
| 453 |
from app.models.iglesia import Asistencia, Servicio, Calendario, Momento, Finanza, Miembro, IglesiaMember, Inventario, DismissedVisita, RelacionFamiliar, IglesiaRol
|
| 454 |
-
from app.models.aprendizaje import ProgresoPlan, PuntuacionLiga
|
| 455 |
|
| 456 |
# 1. Asistencias
|
| 457 |
db.query(Asistencia).filter(
|
|
@@ -467,12 +466,10 @@ def delete_church_admin(church_id: int, db: Session = Depends(get_db), current_a
|
|
| 467 |
)
|
| 468 |
).delete(synchronize_session=False)
|
| 469 |
|
| 470 |
-
# 3. Calendarios, Finanzas, Inventario,
|
| 471 |
db.query(Calendario).filter(Calendario.iglesia_id == church_id).delete(synchronize_session=False)
|
| 472 |
db.query(Finanza).filter(Finanza.iglesia_id == church_id).delete(synchronize_session=False)
|
| 473 |
db.query(Inventario).filter(Inventario.iglesia_id == church_id).delete(synchronize_session=False)
|
| 474 |
-
db.query(ProgresoPlan).filter(ProgresoPlan.iglesia_id == church_id).delete(synchronize_session=False)
|
| 475 |
-
db.query(PuntuacionLiga).filter(PuntuacionLiga.iglesia_id == church_id).delete(synchronize_session=False)
|
| 476 |
db.query(Momento).filter(Momento.iglesia_id == church_id).delete(synchronize_session=False)
|
| 477 |
|
| 478 |
# 4. DismissedVisitas (antes de borrar Miembros)
|
|
@@ -846,9 +843,7 @@ def delete_user(user_id: int, background_tasks: BackgroundTasks, db: Session = D
|
|
| 846 |
("user_groups", "user_id"),
|
| 847 |
("iglesia_members", "user_id"),
|
| 848 |
("dismissed_visitas", "user_id"),
|
| 849 |
-
("progresos_plan", "user_id")
|
| 850 |
-
("puntuaciones_liga", "user_id"),
|
| 851 |
-
("participantes_torneo", "user_id")
|
| 852 |
]
|
| 853 |
for table, col in deletes:
|
| 854 |
if table in db_tables:
|
|
@@ -867,9 +862,7 @@ def delete_user(user_id: int, background_tasks: BackgroundTasks, db: Session = D
|
|
| 867 |
("asistencias", "registrado_por"),
|
| 868 |
("finanzas", "registrado_por"),
|
| 869 |
("momentos", "registrado_por"),
|
| 870 |
-
("inventario", "registrado_por")
|
| 871 |
-
("torneos", "creador_id"),
|
| 872 |
-
("torneos", "ganador_id")
|
| 873 |
]
|
| 874 |
for table, col in updates:
|
| 875 |
if table in db_tables:
|
|
|
|
| 451 |
|
| 452 |
# Eliminar en cascada absoluta en el orden correcto de integridad referencial
|
| 453 |
from app.models.iglesia import Asistencia, Servicio, Calendario, Momento, Finanza, Miembro, IglesiaMember, Inventario, DismissedVisita, RelacionFamiliar, IglesiaRol
|
|
|
|
| 454 |
|
| 455 |
# 1. Asistencias
|
| 456 |
db.query(Asistencia).filter(
|
|
|
|
| 466 |
)
|
| 467 |
).delete(synchronize_session=False)
|
| 468 |
|
| 469 |
+
# 3. Calendarios, Finanzas, Inventario, Momentos
|
| 470 |
db.query(Calendario).filter(Calendario.iglesia_id == church_id).delete(synchronize_session=False)
|
| 471 |
db.query(Finanza).filter(Finanza.iglesia_id == church_id).delete(synchronize_session=False)
|
| 472 |
db.query(Inventario).filter(Inventario.iglesia_id == church_id).delete(synchronize_session=False)
|
|
|
|
|
|
|
| 473 |
db.query(Momento).filter(Momento.iglesia_id == church_id).delete(synchronize_session=False)
|
| 474 |
|
| 475 |
# 4. DismissedVisitas (antes de borrar Miembros)
|
|
|
|
| 843 |
("user_groups", "user_id"),
|
| 844 |
("iglesia_members", "user_id"),
|
| 845 |
("dismissed_visitas", "user_id"),
|
| 846 |
+
("progresos_plan", "user_id")
|
|
|
|
|
|
|
| 847 |
]
|
| 848 |
for table, col in deletes:
|
| 849 |
if table in db_tables:
|
|
|
|
| 862 |
("asistencias", "registrado_por"),
|
| 863 |
("finanzas", "registrado_por"),
|
| 864 |
("momentos", "registrado_por"),
|
| 865 |
+
("inventario", "registrado_por")
|
|
|
|
|
|
|
| 866 |
]
|
| 867 |
for table, col in updates:
|
| 868 |
if table in db_tables:
|
app/routers/aprendizaje.py
CHANGED
|
@@ -9,31 +9,15 @@ from sqlalchemy.orm import Session
|
|
| 9 |
|
| 10 |
from app.database import get_db
|
| 11 |
from app.models.user import User
|
| 12 |
-
from app.models.iglesia import IglesiaMember
|
| 13 |
from app.models.aprendizaje import (
|
| 14 |
-
PlanLectura, DiaLectura, PreguntaQuiz, ProgresoPlan,
|
| 15 |
-
BibliaLibro, BibliaVersiculo
|
| 16 |
)
|
| 17 |
from app.routers.auth import get_current_user
|
| 18 |
from app.routers.iglesia import get_iglesia_usuario
|
| 19 |
|
| 20 |
router = APIRouter(prefix="/aprendizaje", tags=["aprendizaje"])
|
| 21 |
|
| 22 |
-
def notificar_participantes_torneo(torneo_id: int, message_type: str, db: Session):
|
| 23 |
-
try:
|
| 24 |
-
from app.websocket_manager import send_sync_message
|
| 25 |
-
participantes = db.query(ParticipanteTorneo).filter(ParticipanteTorneo.torneo_id == torneo_id).all()
|
| 26 |
-
for p in participantes:
|
| 27 |
-
try:
|
| 28 |
-
send_sync_message({
|
| 29 |
-
"type": message_type,
|
| 30 |
-
"torneo_id": torneo_id
|
| 31 |
-
}, p.user_id)
|
| 32 |
-
except Exception:
|
| 33 |
-
pass
|
| 34 |
-
except Exception as e:
|
| 35 |
-
print(f"[WebSocket] Error notificar_participantes_torneo: {e}")
|
| 36 |
-
|
| 37 |
# ──────────────────────────────────────────────────────────
|
| 38 |
# PARSER DE PASAJES BÍBLICOS
|
| 39 |
# Permite convertir "Matthew 1" o "Matthew 1-3" en versículos reales
|
|
@@ -147,25 +131,25 @@ class CompletarDiaRequest(BaseModel):
|
|
| 147 |
def check_and_reset_streaks(user_id: int, db: Session, fecha_hoy_str: Optional[str] = None):
|
| 148 |
if not fecha_hoy_str:
|
| 149 |
fecha_hoy_str = datetime.utcnow().strftime("%Y-%m-%d")
|
| 150 |
-
|
| 151 |
progresos = db.query(ProgresoPlan).filter(ProgresoPlan.user_id == user_id).all()
|
| 152 |
updated = False
|
| 153 |
for progreso in progresos:
|
| 154 |
if not progreso.ultima_lectura_fecha:
|
| 155 |
continue
|
| 156 |
-
|
| 157 |
try:
|
| 158 |
ultima_fecha = datetime.strptime(progreso.ultima_lectura_fecha, "%Y-%m-%d").date()
|
| 159 |
fecha_hoy = datetime.strptime(fecha_hoy_str, "%Y-%m-%d").date()
|
| 160 |
except ValueError:
|
| 161 |
continue
|
| 162 |
-
|
| 163 |
diff = (fecha_hoy - ultima_fecha).days
|
| 164 |
if diff > 1:
|
| 165 |
if progreso.racha_actual > 0:
|
| 166 |
progreso.racha_actual = 0
|
| 167 |
updated = True
|
| 168 |
-
|
| 169 |
if updated:
|
| 170 |
db.commit()
|
| 171 |
|
|
@@ -173,14 +157,32 @@ def check_and_reset_streaks(user_id: int, db: Session, fecha_hoy_str: Optional[s
|
|
| 173 |
# ENDPOINTS
|
| 174 |
# ──────────────────────────────────────────────────────────
|
| 175 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
@router.get("/planes")
|
| 177 |
def listar_planes(fecha_local: Optional[str] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 178 |
check_and_reset_streaks(current_user.id, db, fecha_local)
|
| 179 |
-
iglesia = get_iglesia_usuario(current_user.id, db)
|
| 180 |
-
iglesia_id = iglesia.id if iglesia else None
|
| 181 |
planes = db.query(PlanLectura).filter(PlanLectura.nombre != "Desafío de Sabios: Preguntas Avanzadas").all()
|
| 182 |
-
|
| 183 |
-
prog_dict = {p.plan_id: p for p in progresos}
|
| 184 |
|
| 185 |
resultado = []
|
| 186 |
for plan in planes:
|
|
@@ -199,19 +201,11 @@ def listar_planes(fecha_local: Optional[str] = None, db: Session = Depends(get_d
|
|
| 199 |
|
| 200 |
@router.post("/suscribir/{plan_id}")
|
| 201 |
def suscribir_a_plan(plan_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 202 |
-
iglesia = get_iglesia_usuario(current_user.id, db)
|
| 203 |
-
if not iglesia:
|
| 204 |
-
raise HTTPException(status_code=400, detail="Debes pertenecer a una iglesia para suscribirte a un plan de lectura")
|
| 205 |
-
|
| 206 |
plan = db.query(PlanLectura).filter(PlanLectura.id == plan_id).first()
|
| 207 |
if not plan:
|
| 208 |
raise HTTPException(status_code=404, detail="Plan de lectura no encontrado")
|
| 209 |
|
| 210 |
-
progreso = db.
|
| 211 |
-
ProgresoPlan.user_id == current_user.id,
|
| 212 |
-
ProgresoPlan.plan_id == plan.id,
|
| 213 |
-
ProgresoPlan.iglesia_id == iglesia.id
|
| 214 |
-
).first()
|
| 215 |
|
| 216 |
if progreso:
|
| 217 |
return {"message": "Ya estás suscrito a este plan", "dia_actual": progreso.dia_actual}
|
|
@@ -219,7 +213,6 @@ def suscribir_a_plan(plan_id: int, db: Session = Depends(get_db), current_user:
|
|
| 219 |
nuevo_progreso = ProgresoPlan(
|
| 220 |
user_id=current_user.id,
|
| 221 |
plan_id=plan.id,
|
| 222 |
-
iglesia_id=iglesia.id,
|
| 223 |
dia_actual=1,
|
| 224 |
completado=False,
|
| 225 |
racha_actual=0
|
|
@@ -230,34 +223,26 @@ def suscribir_a_plan(plan_id: int, db: Session = Depends(get_db), current_user:
|
|
| 230 |
|
| 231 |
@router.post("/cancelar/{plan_id}")
|
| 232 |
def cancelar_plan(plan_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 233 |
-
|
| 234 |
-
iglesia_id = iglesia.id if iglesia else None
|
| 235 |
-
progreso = db.query(ProgresoPlan).filter(
|
| 236 |
ProgresoPlan.user_id == current_user.id,
|
| 237 |
-
ProgresoPlan.plan_id == plan_id
|
| 238 |
-
|
| 239 |
-
).first()
|
| 240 |
|
| 241 |
-
if not
|
| 242 |
-
raise HTTPException(status_code=404, detail="No estás suscrito a este plan
|
| 243 |
|
| 244 |
-
|
|
|
|
| 245 |
db.commit()
|
| 246 |
return {"message": "Plan cancelado exitosamente"}
|
| 247 |
|
| 248 |
@router.get("/dia/{plan_id}")
|
| 249 |
def obtener_dia_lectura(plan_id: int, fecha_local: Optional[str] = None, dia_pedido: Optional[int] = Query(None, alias="dia"), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 250 |
check_and_reset_streaks(current_user.id, db, fecha_local)
|
| 251 |
-
|
| 252 |
-
iglesia_id = iglesia.id if iglesia else None
|
| 253 |
-
progreso = db.query(ProgresoPlan).filter(
|
| 254 |
-
ProgresoPlan.user_id == current_user.id,
|
| 255 |
-
ProgresoPlan.plan_id == plan_id,
|
| 256 |
-
ProgresoPlan.iglesia_id == iglesia_id
|
| 257 |
-
).first()
|
| 258 |
|
| 259 |
if not progreso:
|
| 260 |
-
raise HTTPException(status_code=400, detail="No estás suscrito a este plan
|
| 261 |
|
| 262 |
# Releer un día ya leído (anterior al actual, o cualquiera si el plan está completo).
|
| 263 |
# Antes siempre se devolvía el día actual aunque se pidiera otro.
|
|
@@ -288,24 +273,6 @@ def obtener_dia_lectura(plan_id: int, fecha_local: Optional[str] = None, dia_ped
|
|
| 288 |
# Obtener los versículos del pasaje
|
| 289 |
versiculos = parse_and_fetch_passage(dia.pasajes, db)
|
| 290 |
|
| 291 |
-
# Obtener preguntas de este día
|
| 292 |
-
preguntas = db.query(PreguntaQuiz).filter(PreguntaQuiz.dia_lectura_id == dia.id).all()
|
| 293 |
-
preguntas_list = []
|
| 294 |
-
for p in preguntas:
|
| 295 |
-
opciones_parsed = []
|
| 296 |
-
try:
|
| 297 |
-
opciones_parsed = json.loads(p.opciones) if p.opciones else []
|
| 298 |
-
except:
|
| 299 |
-
opciones_parsed = []
|
| 300 |
-
|
| 301 |
-
preguntas_list.append({
|
| 302 |
-
"id": p.id,
|
| 303 |
-
"tipo": p.tipo,
|
| 304 |
-
"pregunta": p.pregunta,
|
| 305 |
-
"opciones": opciones_parsed,
|
| 306 |
-
"respuesta_correcta": p.respuesta_correcta
|
| 307 |
-
})
|
| 308 |
-
|
| 309 |
return {
|
| 310 |
"completado_todo": False,
|
| 311 |
"es_repaso": es_repaso,
|
|
@@ -313,20 +280,12 @@ def obtener_dia_lectura(plan_id: int, fecha_local: Optional[str] = None, dia_ped
|
|
| 313 |
"pasajes": dia.pasajes,
|
| 314 |
"titulo": dia.titulo or f"Día {dia.dia_numero}",
|
| 315 |
"versiculos": versiculos,
|
| 316 |
-
"preguntas":
|
| 317 |
}
|
| 318 |
|
| 319 |
@router.post("/completar-dia")
|
| 320 |
def completar_dia(data: CompletarDiaRequest, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 321 |
-
|
| 322 |
-
if not iglesia:
|
| 323 |
-
raise HTTPException(status_code=404, detail="No perteneces a ninguna iglesia para sumar puntos de liga")
|
| 324 |
-
|
| 325 |
-
progreso = db.query(ProgresoPlan).filter(
|
| 326 |
-
ProgresoPlan.user_id == current_user.id,
|
| 327 |
-
ProgresoPlan.plan_id == data.plan_id,
|
| 328 |
-
ProgresoPlan.iglesia_id == iglesia.id
|
| 329 |
-
).first()
|
| 330 |
|
| 331 |
if not progreso:
|
| 332 |
raise HTTPException(status_code=400, detail="No suscrito al plan")
|
|
@@ -343,7 +302,7 @@ def completar_dia(data: CompletarDiaRequest, db: Session = Depends(get_db), curr
|
|
| 343 |
# 1. VALIDACIÓN DE LA RACHA (STREAK)
|
| 344 |
hoy = data.fecha_local # Formato "YYYY-MM-DD"
|
| 345 |
racha_antes = progreso.racha_actual
|
| 346 |
-
|
| 347 |
if progreso.ultima_lectura_fecha == hoy:
|
| 348 |
# Ya leyó hoy, no incrementa racha pero actualiza progreso
|
| 349 |
pass
|
|
@@ -351,7 +310,7 @@ def completar_dia(data: CompletarDiaRequest, db: Session = Depends(get_db), curr
|
|
| 351 |
ultima_fecha = datetime.strptime(progreso.ultima_lectura_fecha, "%Y-%m-%d").date()
|
| 352 |
fecha_dispositivo = datetime.strptime(hoy, "%Y-%m-%d").date()
|
| 353 |
diff = (fecha_dispositivo - ultima_fecha).days
|
| 354 |
-
|
| 355 |
if diff == 1:
|
| 356 |
progreso.racha_actual += 1
|
| 357 |
elif diff > 1:
|
|
@@ -365,30 +324,7 @@ def completar_dia(data: CompletarDiaRequest, db: Session = Depends(get_db), curr
|
|
| 365 |
|
| 366 |
progreso.ultima_lectura_fecha = hoy
|
| 367 |
|
| 368 |
-
# 2.
|
| 369 |
-
# Base: 10 XP por leer. Cada acierto del quiz: +5 XP
|
| 370 |
-
puntos_ganados = 10 + (data.respuestas_correctas * 5)
|
| 371 |
-
|
| 372 |
-
# Actualizar o crear marcador en la Liga de la Iglesia
|
| 373 |
-
liga = db.query(PuntuacionLiga).filter(
|
| 374 |
-
PuntuacionLiga.user_id == current_user.id,
|
| 375 |
-
PuntuacionLiga.iglesia_id == iglesia.id
|
| 376 |
-
).first()
|
| 377 |
-
|
| 378 |
-
if not liga:
|
| 379 |
-
liga = PuntuacionLiga(
|
| 380 |
-
user_id=current_user.id,
|
| 381 |
-
iglesia_id=iglesia.id,
|
| 382 |
-
puntos_totales=puntos_ganados,
|
| 383 |
-
maxima_racha=progreso.racha_actual
|
| 384 |
-
)
|
| 385 |
-
db.add(liga)
|
| 386 |
-
else:
|
| 387 |
-
liga.puntos_totales += puntos_ganados
|
| 388 |
-
if progreso.racha_actual > liga.maxima_racha:
|
| 389 |
-
liga.maxima_racha = progreso.racha_actual
|
| 390 |
-
|
| 391 |
-
# 3. AVANCE DE DÍA
|
| 392 |
plan = db.query(PlanLectura).filter(PlanLectura.id == data.plan_id).first()
|
| 393 |
if progreso.dia_actual >= plan.dias_totales:
|
| 394 |
progreso.completado = True
|
|
@@ -398,65 +334,24 @@ def completar_dia(data: CompletarDiaRequest, db: Session = Depends(get_db), curr
|
|
| 398 |
db.commit()
|
| 399 |
|
| 400 |
return {
|
| 401 |
-
"puntos_ganados":
|
| 402 |
"nueva_racha": progreso.racha_actual,
|
| 403 |
"dia_siguiente": progreso.dia_actual,
|
| 404 |
"completado": progreso.completado
|
| 405 |
}
|
| 406 |
|
| 407 |
-
@router.get("/liga")
|
| 408 |
-
def obtener_tabla_posiciones(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 409 |
-
iglesia = get_iglesia_usuario(current_user.id, db)
|
| 410 |
-
if not iglesia:
|
| 411 |
-
raise HTTPException(status_code=404, detail="No perteneces a ninguna iglesia")
|
| 412 |
-
|
| 413 |
-
# Obtener IDs de usuarios que pertenecen a esta iglesia
|
| 414 |
-
miembros_ids = [m.user_id for m in db.query(IglesiaMember).filter(
|
| 415 |
-
IglesiaMember.iglesia_id == iglesia.id,
|
| 416 |
-
IglesiaMember.estado == "activo"
|
| 417 |
-
).all()]
|
| 418 |
-
|
| 419 |
-
# Buscar puntuaciones ordenadas
|
| 420 |
-
puntuaciones = db.query(PuntuacionLiga).filter(
|
| 421 |
-
PuntuacionLiga.user_id.in_(miembros_ids)
|
| 422 |
-
).order_by(PuntuacionLiga.puntos_totales.desc()).all()
|
| 423 |
-
|
| 424 |
-
leaderboard = []
|
| 425 |
-
for idx, p in enumerate(puntuaciones):
|
| 426 |
-
leaderboard.append({
|
| 427 |
-
"posicion": idx + 1,
|
| 428 |
-
"user_id": p.user_id,
|
| 429 |
-
"username": p.user.username,
|
| 430 |
-
"puntos": p.puntos_totales,
|
| 431 |
-
"maxima_racha": p.maxima_racha
|
| 432 |
-
})
|
| 433 |
-
|
| 434 |
-
return {
|
| 435 |
-
"iglesia_nombre": iglesia.nombre,
|
| 436 |
-
"leaderboard": leaderboard
|
| 437 |
-
}
|
| 438 |
-
|
| 439 |
@router.get("/mi-estado")
|
| 440 |
def obtener_mi_estado(fecha_local: Optional[str] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 441 |
check_and_reset_streaks(current_user.id, db, fecha_local)
|
| 442 |
iglesia = get_iglesia_usuario(current_user.id, db)
|
| 443 |
-
|
| 444 |
-
progresos =
|
| 445 |
racha_maxima = max([p.racha_actual for p in progresos]) if progresos else 0
|
| 446 |
-
|
| 447 |
-
puntos_liga = 0
|
| 448 |
-
if iglesia:
|
| 449 |
-
liga = db.query(PuntuacionLiga).filter(
|
| 450 |
-
PuntuacionLiga.user_id == current_user.id,
|
| 451 |
-
PuntuacionLiga.iglesia_id == iglesia.id
|
| 452 |
-
).first()
|
| 453 |
-
if liga:
|
| 454 |
-
puntos_liga = liga.puntos_totales
|
| 455 |
|
| 456 |
return {
|
| 457 |
"user_id": current_user.id,
|
| 458 |
"racha_actual": racha_maxima,
|
| 459 |
-
"puntos_liga":
|
| 460 |
"tiene_iglesia": iglesia is not None
|
| 461 |
}
|
| 462 |
|
|
@@ -467,32 +362,24 @@ def obtener_estado_usuario(user_id: int, fecha_local: Optional[str] = None, db:
|
|
| 467 |
user = db.query(User).filter(User.id == user_id).first()
|
| 468 |
if not user:
|
| 469 |
raise HTTPException(status_code=404, detail="Usuario no encontrado")
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
puntos_liga = 0
|
| 475 |
-
iglesia = get_iglesia_usuario(user_id, db)
|
| 476 |
-
if iglesia:
|
| 477 |
-
liga = db.query(PuntuacionLiga).filter_by(user_id=user_id, iglesia_id=iglesia.id).first()
|
| 478 |
-
if liga:
|
| 479 |
-
puntos_liga = liga.puntos_totales
|
| 480 |
-
|
| 481 |
planes_info = []
|
| 482 |
racha_maxima = max([p.racha_actual for p in progresos]) if progresos else 0
|
| 483 |
-
|
| 484 |
for p in progresos:
|
| 485 |
plan_obj = db.query(PlanLectura).filter_by(id=p.plan_id).first()
|
| 486 |
if plan_obj:
|
| 487 |
dias_totales = plan_obj.dias_totales
|
| 488 |
dias_leidos = p.dia_actual - 1 if not p.completado else dias_totales
|
| 489 |
dias_faltantes = max(0, dias_totales - dias_leidos)
|
| 490 |
-
|
| 491 |
hoy = datetime.utcnow().strftime("%Y-%m-%d")
|
| 492 |
estado_ritmo = "Al día" if p.ultima_lectura_fecha == hoy else "Atrasado"
|
| 493 |
if p.completado:
|
| 494 |
estado_ritmo = "Completado"
|
| 495 |
-
|
| 496 |
planes_info.append({
|
| 497 |
"plan_id": plan_obj.id,
|
| 498 |
"nombre": plan_obj.nombre,
|
|
@@ -505,12 +392,12 @@ def obtener_estado_usuario(user_id: int, fecha_local: Optional[str] = None, db:
|
|
| 505 |
"estado_ritmo": estado_ritmo,
|
| 506 |
"ultima_lectura": p.ultima_lectura_fecha
|
| 507 |
})
|
| 508 |
-
|
| 509 |
return {
|
| 510 |
"user_id": user.id,
|
| 511 |
"username": user.username,
|
| 512 |
"racha_actual": racha_maxima,
|
| 513 |
-
"puntos_liga":
|
| 514 |
"planes": planes_info
|
| 515 |
}
|
| 516 |
|
|
@@ -602,519 +489,15 @@ def completar_examen_repaso(
|
|
| 602 |
"message": "Repaso ya completado anteriormente (duplicado silenciado)"
|
| 603 |
}
|
| 604 |
|
| 605 |
-
iglesia = get_iglesia_usuario(current_user.id, db)
|
| 606 |
-
puntos_ganados = 50
|
| 607 |
-
|
| 608 |
-
if iglesia:
|
| 609 |
-
liga = db.query(PuntuacionLiga).filter(
|
| 610 |
-
PuntuacionLiga.user_id == current_user.id,
|
| 611 |
-
PuntuacionLiga.iglesia_id == iglesia.id
|
| 612 |
-
).first()
|
| 613 |
-
|
| 614 |
-
if not liga:
|
| 615 |
-
liga = PuntuacionLiga(
|
| 616 |
-
user_id=current_user.id,
|
| 617 |
-
iglesia_id=iglesia.id,
|
| 618 |
-
puntos_totales=puntos_ganados,
|
| 619 |
-
maxima_racha=progreso.racha_actual
|
| 620 |
-
)
|
| 621 |
-
db.add(liga)
|
| 622 |
-
else:
|
| 623 |
-
liga.puntos_totales += puntos_ganados
|
| 624 |
-
if progreso.racha_actual > liga.maxima_racha:
|
| 625 |
-
liga.maxima_racha = progreso.racha_actual
|
| 626 |
-
|
| 627 |
progreso.repaso_completado_hasta = data.dias_hito
|
| 628 |
db.commit()
|
| 629 |
|
| 630 |
return {
|
| 631 |
-
"puntos_ganados":
|
| 632 |
"nueva_racha": progreso.racha_actual,
|
| 633 |
"repaso_completado_hasta": progreso.repaso_completado_hasta
|
| 634 |
}
|
| 635 |
|
| 636 |
-
# ──────────────────────────────────────────────────────────
|
| 637 |
-
# MOTOR DE TORNEOS MULTIJUGADOR BÍBLICOS
|
| 638 |
-
# ──────────────────────────────────────────────────────────
|
| 639 |
-
|
| 640 |
-
class CrearTorneoRequest(BaseModel):
|
| 641 |
-
nombre: str
|
| 642 |
-
|
| 643 |
-
class JugarTorneoRequest(BaseModel):
|
| 644 |
-
torneo_id: int
|
| 645 |
-
score: int
|
| 646 |
-
tiempo_empleado: float
|
| 647 |
-
es_desempate: bool = False
|
| 648 |
-
|
| 649 |
-
@router.post("/torneos/crear")
|
| 650 |
-
def crear_torneo(
|
| 651 |
-
data: CrearTorneoRequest,
|
| 652 |
-
db: Session = Depends(get_db),
|
| 653 |
-
current_user: User = Depends(get_current_user)
|
| 654 |
-
):
|
| 655 |
-
codigo = ""
|
| 656 |
-
while True:
|
| 657 |
-
num = random.randint(1000, 9999)
|
| 658 |
-
codigo = f"BIB-{num}"
|
| 659 |
-
ex = db.query(Torneo).filter(Torneo.codigo == codigo).first()
|
| 660 |
-
if not ex:
|
| 661 |
-
break
|
| 662 |
-
|
| 663 |
-
# Validar que no tenga ya un torneo activo/pendiente/desempate
|
| 664 |
-
torneo_existente = db.query(Torneo).filter(
|
| 665 |
-
Torneo.creador_id == current_user.id,
|
| 666 |
-
Torneo.estado.in_(["pendiente", "activo", "desempate"])
|
| 667 |
-
).first()
|
| 668 |
-
if torneo_existente:
|
| 669 |
-
raise HTTPException(
|
| 670 |
-
status_code=400,
|
| 671 |
-
detail="Ya tienes un torneo pendiente o activo. Debes finalizarlo antes de crear otro."
|
| 672 |
-
)
|
| 673 |
-
|
| 674 |
-
todas = db.query(PreguntaQuiz).all()
|
| 675 |
-
if len(todas) < 5:
|
| 676 |
-
raise HTTPException(status_code=400, detail="No hay suficientes preguntas bíblicas registradas en el sistema")
|
| 677 |
-
|
| 678 |
-
preguntas_seleccionadas = random.sample(todas, 5)
|
| 679 |
-
preguntas_ids = [q.id for q in preguntas_seleccionadas]
|
| 680 |
-
|
| 681 |
-
nuevo_torneo = Torneo(
|
| 682 |
-
codigo=codigo,
|
| 683 |
-
nombre=data.nombre,
|
| 684 |
-
creador_id=current_user.id,
|
| 685 |
-
preguntas_json=json.dumps(preguntas_ids),
|
| 686 |
-
estado="pendiente", # Estado inicial cambiado a pendiente
|
| 687 |
-
fecha_creacion=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 688 |
-
)
|
| 689 |
-
db.add(nuevo_torneo)
|
| 690 |
-
db.commit()
|
| 691 |
-
db.refresh(nuevo_torneo)
|
| 692 |
-
|
| 693 |
-
participante = ParticipanteTorneo(
|
| 694 |
-
torneo_id=nuevo_torneo.id,
|
| 695 |
-
user_id=current_user.id,
|
| 696 |
-
estado="pendiente"
|
| 697 |
-
)
|
| 698 |
-
db.add(participante)
|
| 699 |
-
db.commit()
|
| 700 |
-
|
| 701 |
-
return {
|
| 702 |
-
"id": nuevo_torneo.id,
|
| 703 |
-
"codigo": nuevo_torneo.codigo,
|
| 704 |
-
"nombre": nuevo_torneo.nombre,
|
| 705 |
-
"creador_id": nuevo_torneo.creador_id,
|
| 706 |
-
"estado": nuevo_torneo.estado
|
| 707 |
-
}
|
| 708 |
-
|
| 709 |
-
@router.post("/torneos/unirse/{codigo}")
|
| 710 |
-
def unirse_a_torneo(
|
| 711 |
-
codigo: str,
|
| 712 |
-
db: Session = Depends(get_db),
|
| 713 |
-
current_user: User = Depends(get_current_user)
|
| 714 |
-
):
|
| 715 |
-
torneo = db.query(Torneo).filter(Torneo.codigo == codigo.upper().strip()).first()
|
| 716 |
-
if not torneo:
|
| 717 |
-
raise HTTPException(status_code=404, detail="Torneo no encontrado")
|
| 718 |
-
|
| 719 |
-
if torneo.estado == "terminado":
|
| 720 |
-
raise HTTPException(status_code=400, detail="Este torneo ya ha finalizado")
|
| 721 |
-
|
| 722 |
-
# Validar que no tenga otra participación activa o pendiente en curso
|
| 723 |
-
participacion_activa = db.query(ParticipanteTorneo).join(Torneo).filter(
|
| 724 |
-
ParticipanteTorneo.user_id == current_user.id,
|
| 725 |
-
Torneo.estado.in_(["pendiente", "activo", "desempate"])
|
| 726 |
-
).first()
|
| 727 |
-
if participacion_activa and participacion_activa.torneo_id != torneo.id:
|
| 728 |
-
raise HTTPException(
|
| 729 |
-
status_code=400,
|
| 730 |
-
detail="Ya participas en otro torneo activo o pendiente en curso. No puedes unirte a otro."
|
| 731 |
-
)
|
| 732 |
-
|
| 733 |
-
existente = db.query(ParticipanteTorneo).filter(
|
| 734 |
-
ParticipanteTorneo.torneo_id == torneo.id,
|
| 735 |
-
ParticipanteTorneo.user_id == current_user.id
|
| 736 |
-
).first()
|
| 737 |
-
|
| 738 |
-
if existente:
|
| 739 |
-
return {"message": "Ya eres participante de este torneo", "torneo_id": torneo.id}
|
| 740 |
-
|
| 741 |
-
nuevo_participante = ParticipanteTorneo(
|
| 742 |
-
torneo_id=torneo.id,
|
| 743 |
-
user_id=current_user.id,
|
| 744 |
-
estado="pendiente"
|
| 745 |
-
)
|
| 746 |
-
db.add(nuevo_participante)
|
| 747 |
-
db.commit()
|
| 748 |
-
|
| 749 |
-
notificar_participantes_torneo(torneo.id, "torneo_updated", db)
|
| 750 |
-
|
| 751 |
-
return {
|
| 752 |
-
"message": "Te has unido al torneo exitosamente",
|
| 753 |
-
"torneo_id": torneo.id,
|
| 754 |
-
"nombre": torneo.nombre
|
| 755 |
-
}
|
| 756 |
-
|
| 757 |
-
@router.post("/torneos/comenzar/{torneo_id}")
|
| 758 |
-
def comenzar_torneo(
|
| 759 |
-
torneo_id: int,
|
| 760 |
-
db: Session = Depends(get_db),
|
| 761 |
-
current_user: User = Depends(get_current_user)
|
| 762 |
-
):
|
| 763 |
-
torneo = db.query(Torneo).filter(Torneo.id == torneo_id).first()
|
| 764 |
-
if not torneo:
|
| 765 |
-
raise HTTPException(status_code=404, detail="Torneo no encontrado")
|
| 766 |
-
if torneo.creador_id != current_user.id:
|
| 767 |
-
raise HTTPException(status_code=403, detail="Solamente el creador del torneo puede comenzar el juego")
|
| 768 |
-
if torneo.estado != "pendiente":
|
| 769 |
-
raise HTTPException(status_code=400, detail="El torneo ya ha comenzado o ha finalizado")
|
| 770 |
-
|
| 771 |
-
# Validar que haya al menos un participante conectado aparte del creador
|
| 772 |
-
from app.websocket_manager import manager
|
| 773 |
-
otros_participantes = db.query(ParticipanteTorneo).filter(
|
| 774 |
-
ParticipanteTorneo.torneo_id == torneo.id,
|
| 775 |
-
ParticipanteTorneo.user_id != torneo.creador_id
|
| 776 |
-
).all()
|
| 777 |
-
|
| 778 |
-
hay_otro_conectado = any(p.user_id in manager.active_connections for p in otros_participantes)
|
| 779 |
-
if not hay_otro_conectado:
|
| 780 |
-
raise HTTPException(
|
| 781 |
-
status_code=400,
|
| 782 |
-
detail="No se puede iniciar el torneo. Debe haber al menos un participante con conexión activa aparte del creador."
|
| 783 |
-
)
|
| 784 |
-
|
| 785 |
-
torneo.estado = "activo"
|
| 786 |
-
db.commit()
|
| 787 |
-
notificar_participantes_torneo(torneo.id, "torneo_updated", db)
|
| 788 |
-
return {"message": "El torneo ha comenzado exitosamente", "estado": torneo.estado}
|
| 789 |
-
|
| 790 |
-
@router.get("/torneos")
|
| 791 |
-
def listar_mis_torneos(
|
| 792 |
-
db: Session = Depends(get_db),
|
| 793 |
-
current_user: User = Depends(get_current_user)
|
| 794 |
-
):
|
| 795 |
-
# Chequear timeouts de los torneos de este usuario antes de listar
|
| 796 |
-
participaciones_raw = db.query(ParticipanteTorneo).filter(ParticipanteTorneo.user_id == current_user.id).all()
|
| 797 |
-
for p in participaciones_raw:
|
| 798 |
-
check_torneo_timeout(p.torneo_id, db)
|
| 799 |
-
|
| 800 |
-
participaciones = db.query(ParticipanteTorneo).join(Torneo).filter(
|
| 801 |
-
ParticipanteTorneo.user_id == current_user.id,
|
| 802 |
-
Torneo.estado != "terminado"
|
| 803 |
-
).all()
|
| 804 |
-
|
| 805 |
-
torneos_data = []
|
| 806 |
-
for part in participaciones:
|
| 807 |
-
t = part.torneo
|
| 808 |
-
if not t:
|
| 809 |
-
continue
|
| 810 |
-
|
| 811 |
-
todos_p = db.query(ParticipanteTorneo).filter(
|
| 812 |
-
ParticipanteTorneo.torneo_id == t.id
|
| 813 |
-
).all()
|
| 814 |
-
|
| 815 |
-
ranking = []
|
| 816 |
-
for p in todos_p:
|
| 817 |
-
user_info = db.query(User).filter(User.id == p.user_id).first()
|
| 818 |
-
username = user_info.username if user_info else "Anónimo"
|
| 819 |
-
ranking.append({
|
| 820 |
-
"user_id": p.user_id,
|
| 821 |
-
"username": username,
|
| 822 |
-
"score": p.score,
|
| 823 |
-
"tiempo_empleado": p.tiempo_empleado,
|
| 824 |
-
"score_desempate": p.score_desempate,
|
| 825 |
-
"tiempo_desempate": p.tiempo_desempate,
|
| 826 |
-
"eliminado": p.eliminado,
|
| 827 |
-
"estado": p.estado
|
| 828 |
-
})
|
| 829 |
-
|
| 830 |
-
if t.estado == "desempate":
|
| 831 |
-
ranking.sort(
|
| 832 |
-
key=lambda x: (
|
| 833 |
-
x["eliminado"],
|
| 834 |
-
-x["score_desempate"],
|
| 835 |
-
x["tiempo_desempate"] if x["tiempo_desempate"] > 0 else 99999.0
|
| 836 |
-
)
|
| 837 |
-
)
|
| 838 |
-
else:
|
| 839 |
-
ranking.sort(key=lambda x: (-x["score"], x["tiempo_empleado"] if x["tiempo_empleado"] > 0 else 99999.0))
|
| 840 |
-
|
| 841 |
-
torneos_data.append({
|
| 842 |
-
"id": t.id,
|
| 843 |
-
"codigo": t.codigo,
|
| 844 |
-
"nombre": t.nombre,
|
| 845 |
-
"estado": t.estado,
|
| 846 |
-
"creador_id": t.creador_id,
|
| 847 |
-
"ganador_id": t.ganador_id,
|
| 848 |
-
"fecha_creacion": t.fecha_creacion,
|
| 849 |
-
"mi_estado": part.estado,
|
| 850 |
-
"mi_eliminado": part.eliminado,
|
| 851 |
-
"ranking": ranking
|
| 852 |
-
})
|
| 853 |
-
|
| 854 |
-
return torneos_data
|
| 855 |
-
|
| 856 |
-
@router.post("/torneos/jugar")
|
| 857 |
-
def registrar_respuestas_torneo(
|
| 858 |
-
data: JugarTorneoRequest,
|
| 859 |
-
db: Session = Depends(get_db),
|
| 860 |
-
current_user: User = Depends(get_current_user)
|
| 861 |
-
):
|
| 862 |
-
torneo = db.query(Torneo).filter(Torneo.id == data.torneo_id).first()
|
| 863 |
-
if not torneo:
|
| 864 |
-
raise HTTPException(status_code=404, detail="Torneo no encontrado")
|
| 865 |
-
|
| 866 |
-
participante = db.query(ParticipanteTorneo).filter(
|
| 867 |
-
ParticipanteTorneo.torneo_id == data.torneo_id,
|
| 868 |
-
ParticipanteTorneo.user_id == current_user.id
|
| 869 |
-
).first()
|
| 870 |
-
|
| 871 |
-
if not participante:
|
| 872 |
-
raise HTTPException(status_code=403, detail="No eres parte de este torneo")
|
| 873 |
-
|
| 874 |
-
if participante.eliminado:
|
| 875 |
-
raise HTTPException(status_code=403, detail="Fuiste eliminado de este torneo")
|
| 876 |
-
|
| 877 |
-
if data.es_desempate:
|
| 878 |
-
if torneo.estado != "desempate":
|
| 879 |
-
raise HTTPException(status_code=400, detail="Este torneo no está en fase de muerte súbita")
|
| 880 |
-
participante.score_desempate = data.score
|
| 881 |
-
participante.tiempo_desempate = data.tiempo_empleado
|
| 882 |
-
participante.estado = "desempate_jugado"
|
| 883 |
-
else:
|
| 884 |
-
if participante.estado != "pendiente":
|
| 885 |
-
raise HTTPException(status_code=400, detail="Ya jugaste este torneo")
|
| 886 |
-
participante.score = data.score
|
| 887 |
-
participante.tiempo_empleado = data.tiempo_empleado
|
| 888 |
-
participante.estado = "jugado"
|
| 889 |
-
|
| 890 |
-
db.commit()
|
| 891 |
-
|
| 892 |
-
# Si es el primer participante en terminar y hay otros pendientes, iniciar el timer de 10 min
|
| 893 |
-
if not torneo.primero_termino_en:
|
| 894 |
-
if data.es_desempate:
|
| 895 |
-
faltantes = db.query(ParticipanteTorneo).filter(
|
| 896 |
-
ParticipanteTorneo.torneo_id == torneo.id,
|
| 897 |
-
ParticipanteTorneo.estado == "desempate_pendiente",
|
| 898 |
-
ParticipanteTorneo.eliminado == False
|
| 899 |
-
).count()
|
| 900 |
-
else:
|
| 901 |
-
faltantes = db.query(ParticipanteTorneo).filter(
|
| 902 |
-
ParticipanteTorneo.torneo_id == torneo.id,
|
| 903 |
-
ParticipanteTorneo.estado == "pendiente"
|
| 904 |
-
).count()
|
| 905 |
-
|
| 906 |
-
if faltantes > 0:
|
| 907 |
-
torneo.primero_termino_en = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 908 |
-
db.commit()
|
| 909 |
-
|
| 910 |
-
# Resolver torneo automáticamente tras registrar respuestas, aplicando el chequeo de timeout
|
| 911 |
-
try:
|
| 912 |
-
check_torneo_timeout(data.torneo_id, db)
|
| 913 |
-
resolver_clasificacion_torneo(data.torneo_id, db, current_user)
|
| 914 |
-
except Exception as e:
|
| 915 |
-
print(f"Error al resolver torneo automáticamente: {e}")
|
| 916 |
-
|
| 917 |
-
notificar_participantes_torneo(data.torneo_id, "torneo_updated", db)
|
| 918 |
-
|
| 919 |
-
return {"message": "Respuestas guardadas exitosamente", "estado": participante.estado}
|
| 920 |
-
|
| 921 |
-
@router.get("/torneo/{torneo_id}/preguntas")
|
| 922 |
-
def obtener_preguntas_torneo(
|
| 923 |
-
torneo_id: int,
|
| 924 |
-
db: Session = Depends(get_db),
|
| 925 |
-
current_user: User = Depends(get_current_user)
|
| 926 |
-
):
|
| 927 |
-
check_torneo_timeout(torneo_id, db)
|
| 928 |
-
|
| 929 |
-
torneo = db.query(Torneo).filter(Torneo.id == torneo_id).first()
|
| 930 |
-
if not torneo:
|
| 931 |
-
raise HTTPException(status_code=404, detail="Torneo no encontrado")
|
| 932 |
-
|
| 933 |
-
if torneo.estado == "pendiente":
|
| 934 |
-
raise HTTPException(status_code=400, detail="El torneo todavia no ha sido iniciado por su creador")
|
| 935 |
-
|
| 936 |
-
participante = db.query(ParticipanteTorneo).filter(
|
| 937 |
-
ParticipanteTorneo.torneo_id == torneo_id,
|
| 938 |
-
ParticipanteTorneo.user_id == current_user.id
|
| 939 |
-
).first()
|
| 940 |
-
|
| 941 |
-
if not participante or participante.eliminado:
|
| 942 |
-
raise HTTPException(status_code=403, detail="No eres parte de este torneo o fuiste eliminado")
|
| 943 |
-
|
| 944 |
-
es_desempate = (torneo.estado == "desempate")
|
| 945 |
-
p_ids_str = torneo.desempate_preguntas_json if es_desempate else torneo.preguntas_json
|
| 946 |
-
p_ids = json.loads(p_ids_str) if p_ids_str else []
|
| 947 |
-
|
| 948 |
-
preguntas = db.query(PreguntaQuiz).filter(PreguntaQuiz.id.in_(p_ids)).all()
|
| 949 |
-
|
| 950 |
-
preguntas_data = []
|
| 951 |
-
for q in preguntas:
|
| 952 |
-
try:
|
| 953 |
-
opciones = json.loads(q.opciones)
|
| 954 |
-
except Exception:
|
| 955 |
-
opciones = q.opciones
|
| 956 |
-
|
| 957 |
-
preguntas_data.append({
|
| 958 |
-
"id": q.id,
|
| 959 |
-
"tipo": q.tipo,
|
| 960 |
-
"pregunta": q.pregunta,
|
| 961 |
-
"opciones": opciones,
|
| 962 |
-
"respuesta_correcta": q.respuesta_correcta
|
| 963 |
-
})
|
| 964 |
-
|
| 965 |
-
return {
|
| 966 |
-
"id": f"torneo-{torneo_id}",
|
| 967 |
-
"titulo": f"Torneo: {torneo.nombre}",
|
| 968 |
-
"pasajes": "Trivia General de la Biblia",
|
| 969 |
-
"versiculos": [],
|
| 970 |
-
"preguntas": preguntas_data,
|
| 971 |
-
"es_desempate": es_desempate
|
| 972 |
-
}
|
| 973 |
-
|
| 974 |
-
def check_torneo_timeout(torneo_id: int, db: Session):
|
| 975 |
-
torneo = db.query(Torneo).filter(Torneo.id == torneo_id).first()
|
| 976 |
-
if not torneo or torneo.estado == "terminado":
|
| 977 |
-
return
|
| 978 |
-
|
| 979 |
-
if torneo.primero_termino_en:
|
| 980 |
-
try:
|
| 981 |
-
primero_time = datetime.strptime(torneo.primero_termino_en, "%Y-%m-%d %H:%M:%S")
|
| 982 |
-
elapsed = datetime.now() - primero_time
|
| 983 |
-
if elapsed > timedelta(minutes=10):
|
| 984 |
-
print(f"[Timeout] Torneo {torneo_id} ha expirado. Resolviendo por tiempo...")
|
| 985 |
-
participantes = db.query(ParticipanteTorneo).filter(
|
| 986 |
-
ParticipanteTorneo.torneo_id == torneo_id
|
| 987 |
-
).all()
|
| 988 |
-
|
| 989 |
-
modificado = False
|
| 990 |
-
for p in participantes:
|
| 991 |
-
if p.estado == "pendiente":
|
| 992 |
-
p.estado = "jugado"
|
| 993 |
-
p.score = 0
|
| 994 |
-
p.tiempo_empleado = 99999.0
|
| 995 |
-
modificado = True
|
| 996 |
-
elif p.estado == "desempate_pendiente":
|
| 997 |
-
p.estado = "desempate_jugado"
|
| 998 |
-
p.score_desempate = 0
|
| 999 |
-
p.tiempo_desempate = 99999.0
|
| 1000 |
-
modificado = True
|
| 1001 |
-
|
| 1002 |
-
torneo.primero_termino_en = None
|
| 1003 |
-
db.commit()
|
| 1004 |
-
|
| 1005 |
-
if modificado:
|
| 1006 |
-
resolver_clasificacion_torneo(torneo_id, db, None)
|
| 1007 |
-
except Exception as e:
|
| 1008 |
-
print(f"[Timeout] Error al procesar timeout del torneo {torneo_id}: {e}")
|
| 1009 |
-
|
| 1010 |
-
@router.post("/torneos/resolver/{torneo_id}")
|
| 1011 |
-
def resolver_clasificacion_torneo(
|
| 1012 |
-
torneo_id: int,
|
| 1013 |
-
db: Session = Depends(get_db),
|
| 1014 |
-
current_user: User = Depends(get_current_user)
|
| 1015 |
-
):
|
| 1016 |
-
torneo = db.query(Torneo).filter(Torneo.id == torneo_id).first()
|
| 1017 |
-
if not torneo:
|
| 1018 |
-
raise HTTPException(status_code=404, detail="Torneo no encontrado")
|
| 1019 |
-
|
| 1020 |
-
if torneo.estado == "terminado":
|
| 1021 |
-
return {"message": "El torneo ya está terminado", "ganador_id": torneo.ganador_id}
|
| 1022 |
-
|
| 1023 |
-
participantes = db.query(ParticipanteTorneo).filter(
|
| 1024 |
-
ParticipanteTorneo.torneo_id == torneo_id
|
| 1025 |
-
).all()
|
| 1026 |
-
|
| 1027 |
-
if torneo.estado == "desempate":
|
| 1028 |
-
pendientes = [p for p in participantes if not p.eliminado and p.estado == "desempate_pendiente"]
|
| 1029 |
-
if len(pendientes) > 0:
|
| 1030 |
-
return {"message": "Esperando a que todos los finalistas terminen de jugar el desempate"}
|
| 1031 |
-
|
| 1032 |
-
competidores = [p for p in participantes if not p.eliminado and p.estado == "desempate_jugado"]
|
| 1033 |
-
if len(competidores) < 1:
|
| 1034 |
-
return {"message": "Nadie ha completado la muerte súbita todavía"}
|
| 1035 |
-
|
| 1036 |
-
competidores.sort(key=lambda x: (-x.score_desempate, x.tiempo_desempate))
|
| 1037 |
-
max_score = competidores[0].score_desempate
|
| 1038 |
-
winners = [c for c in competidores if c.score_desempate == max_score]
|
| 1039 |
-
|
| 1040 |
-
if len(winners) == 1 or len(competidores) == 1:
|
| 1041 |
-
campeon = competidores[0]
|
| 1042 |
-
torneo.ganador_id = campeon.user_id
|
| 1043 |
-
torneo.estado = "terminado"
|
| 1044 |
-
|
| 1045 |
-
for p in participantes:
|
| 1046 |
-
if p.user_id != campeon.user_id:
|
| 1047 |
-
p.eliminado = True
|
| 1048 |
-
|
| 1049 |
-
iglesia = get_iglesia_usuario(campeon.user_id, db)
|
| 1050 |
-
if iglesia:
|
| 1051 |
-
liga = db.query(PuntuacionLiga).filter(
|
| 1052 |
-
PuntuacionLiga.user_id == campeon.user_id,
|
| 1053 |
-
PuntuacionLiga.iglesia_id == iglesia.id
|
| 1054 |
-
).first()
|
| 1055 |
-
if liga:
|
| 1056 |
-
liga.puntos_totales += 100
|
| 1057 |
-
|
| 1058 |
-
db.commit()
|
| 1059 |
-
notificar_participantes_torneo(torneo_id, "torneo_updated", db)
|
| 1060 |
-
return {"message": "Torneo terminado", "ganador_id": torneo.ganador_id, "estado": "terminado"}
|
| 1061 |
-
else:
|
| 1062 |
-
campeon = competidores[0]
|
| 1063 |
-
torneo.ganador_id = campeon.user_id
|
| 1064 |
-
torneo.estado = "terminado"
|
| 1065 |
-
db.commit()
|
| 1066 |
-
notificar_participantes_torneo(torneo_id, "torneo_updated", db)
|
| 1067 |
-
return {"message": "Torneo terminado por tiempo", "ganador_id": torneo.ganador_id, "estado": "terminado"}
|
| 1068 |
-
else:
|
| 1069 |
-
pendientes = [p for p in participantes if p.estado == "pendiente"]
|
| 1070 |
-
if len(pendientes) > 0:
|
| 1071 |
-
return {"message": "Esperando a que todos los participantes terminen de jugar el torneo"}
|
| 1072 |
-
|
| 1073 |
-
jugaron = [p for p in participantes if p.estado == "jugado"]
|
| 1074 |
-
if len(jugaron) < 1:
|
| 1075 |
-
return {"message": "Nadie ha jugado el torneo todavía"}
|
| 1076 |
-
|
| 1077 |
-
max_score = max(p.score for p in jugaron)
|
| 1078 |
-
empatados = [p for p in jugaron if p.score == max_score]
|
| 1079 |
-
|
| 1080 |
-
if len(empatados) == 1:
|
| 1081 |
-
campeon = empatados[0]
|
| 1082 |
-
torneo.ganador_id = campeon.user_id
|
| 1083 |
-
torneo.estado = "terminado"
|
| 1084 |
-
|
| 1085 |
-
iglesia = get_iglesia_usuario(campeon.user_id, db)
|
| 1086 |
-
if iglesia:
|
| 1087 |
-
liga = db.query(PuntuacionLiga).filter(
|
| 1088 |
-
PuntuacionLiga.user_id == campeon.user_id,
|
| 1089 |
-
PuntuacionLiga.iglesia_id == iglesia.id
|
| 1090 |
-
).first()
|
| 1091 |
-
if liga:
|
| 1092 |
-
liga.puntos_totales += 100
|
| 1093 |
-
|
| 1094 |
-
db.commit()
|
| 1095 |
-
notificar_participantes_torneo(torneo_id, "torneo_updated", db)
|
| 1096 |
-
return {"message": "Torneo resuelto con ganador único", "ganador_id": torneo.ganador_id, "estado": "terminado"}
|
| 1097 |
-
else:
|
| 1098 |
-
empatados_ids = [e.user_id for e in empatados]
|
| 1099 |
-
for p in participantes:
|
| 1100 |
-
if p.user_id not in empatados_ids:
|
| 1101 |
-
p.eliminado = True
|
| 1102 |
-
|
| 1103 |
-
todas = db.query(PreguntaQuiz).all()
|
| 1104 |
-
preguntas_seleccionadas = random.sample(todas, 5)
|
| 1105 |
-
torneo.desempate_preguntas_json = json.dumps([q.id for q in preguntas_seleccionadas])
|
| 1106 |
-
torneo.estado = "desempate"
|
| 1107 |
-
|
| 1108 |
-
for p in participantes:
|
| 1109 |
-
if p.user_id in empatados_ids:
|
| 1110 |
-
p.estado = "desempate_pendiente"
|
| 1111 |
-
p.score_desempate = 0
|
| 1112 |
-
p.tiempo_desempate = 0.0
|
| 1113 |
-
|
| 1114 |
-
db.commit()
|
| 1115 |
-
notificar_participantes_torneo(torneo_id, "torneo_updated", db)
|
| 1116 |
-
return {"message": "Se ha desatado una muerte súbita", "estado": "desempate"}
|
| 1117 |
-
|
| 1118 |
@router.get("/preguntas/infinitas")
|
| 1119 |
def obtener_preguntas_infinitas(
|
| 1120 |
db: Session = Depends(get_db),
|
|
@@ -1123,10 +506,10 @@ def obtener_preguntas_infinitas(
|
|
| 1123 |
todas = db.query(PreguntaQuiz).all()
|
| 1124 |
if not todas:
|
| 1125 |
raise HTTPException(status_code=404, detail="No hay preguntas registradas en el sistema")
|
| 1126 |
-
|
| 1127 |
# Barajarlas
|
| 1128 |
random.shuffle(todas)
|
| 1129 |
-
|
| 1130 |
preguntas_data = []
|
| 1131 |
for q in todas:
|
| 1132 |
try:
|
|
|
|
| 9 |
|
| 10 |
from app.database import get_db
|
| 11 |
from app.models.user import User
|
|
|
|
| 12 |
from app.models.aprendizaje import (
|
| 13 |
+
PlanLectura, DiaLectura, PreguntaQuiz, ProgresoPlan,
|
| 14 |
+
BibliaLibro, BibliaVersiculo
|
| 15 |
)
|
| 16 |
from app.routers.auth import get_current_user
|
| 17 |
from app.routers.iglesia import get_iglesia_usuario
|
| 18 |
|
| 19 |
router = APIRouter(prefix="/aprendizaje", tags=["aprendizaje"])
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
# ──────────────────────────────────────────────────────────
|
| 22 |
# PARSER DE PASAJES BÍBLICOS
|
| 23 |
# Permite convertir "Matthew 1" o "Matthew 1-3" en versículos reales
|
|
|
|
| 131 |
def check_and_reset_streaks(user_id: int, db: Session, fecha_hoy_str: Optional[str] = None):
|
| 132 |
if not fecha_hoy_str:
|
| 133 |
fecha_hoy_str = datetime.utcnow().strftime("%Y-%m-%d")
|
| 134 |
+
|
| 135 |
progresos = db.query(ProgresoPlan).filter(ProgresoPlan.user_id == user_id).all()
|
| 136 |
updated = False
|
| 137 |
for progreso in progresos:
|
| 138 |
if not progreso.ultima_lectura_fecha:
|
| 139 |
continue
|
| 140 |
+
|
| 141 |
try:
|
| 142 |
ultima_fecha = datetime.strptime(progreso.ultima_lectura_fecha, "%Y-%m-%d").date()
|
| 143 |
fecha_hoy = datetime.strptime(fecha_hoy_str, "%Y-%m-%d").date()
|
| 144 |
except ValueError:
|
| 145 |
continue
|
| 146 |
+
|
| 147 |
diff = (fecha_hoy - ultima_fecha).days
|
| 148 |
if diff > 1:
|
| 149 |
if progreso.racha_actual > 0:
|
| 150 |
progreso.racha_actual = 0
|
| 151 |
updated = True
|
| 152 |
+
|
| 153 |
if updated:
|
| 154 |
db.commit()
|
| 155 |
|
|
|
|
| 157 |
# ENDPOINTS
|
| 158 |
# ──────────────────────────────────────────────────────────
|
| 159 |
|
| 160 |
+
def _progreso_plan(db: Session, user_id: int, plan_id: int):
|
| 161 |
+
"""
|
| 162 |
+
El progreso es de la persona, no de una iglesia. Quien cambió de iglesia antes de esta regla
|
| 163 |
+
puede tener varias filas del mismo plan: vale la más avanzada.
|
| 164 |
+
"""
|
| 165 |
+
return db.query(ProgresoPlan).filter(
|
| 166 |
+
ProgresoPlan.user_id == user_id,
|
| 167 |
+
ProgresoPlan.plan_id == plan_id
|
| 168 |
+
).order_by(ProgresoPlan.dia_actual.desc()).first()
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _progresos_usuario(db: Session, user_id: int) -> list:
|
| 172 |
+
"""Un progreso por plan: el más avanzado."""
|
| 173 |
+
por_plan = {}
|
| 174 |
+
for p in db.query(ProgresoPlan).filter(ProgresoPlan.user_id == user_id).all():
|
| 175 |
+
actual = por_plan.get(p.plan_id)
|
| 176 |
+
if actual is None or (p.dia_actual or 0) > (actual.dia_actual or 0):
|
| 177 |
+
por_plan[p.plan_id] = p
|
| 178 |
+
return list(por_plan.values())
|
| 179 |
+
|
| 180 |
+
|
| 181 |
@router.get("/planes")
|
| 182 |
def listar_planes(fecha_local: Optional[str] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 183 |
check_and_reset_streaks(current_user.id, db, fecha_local)
|
|
|
|
|
|
|
| 184 |
planes = db.query(PlanLectura).filter(PlanLectura.nombre != "Desafío de Sabios: Preguntas Avanzadas").all()
|
| 185 |
+
prog_dict = {p.plan_id: p for p in _progresos_usuario(db, current_user.id)}
|
|
|
|
| 186 |
|
| 187 |
resultado = []
|
| 188 |
for plan in planes:
|
|
|
|
| 201 |
|
| 202 |
@router.post("/suscribir/{plan_id}")
|
| 203 |
def suscribir_a_plan(plan_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
plan = db.query(PlanLectura).filter(PlanLectura.id == plan_id).first()
|
| 205 |
if not plan:
|
| 206 |
raise HTTPException(status_code=404, detail="Plan de lectura no encontrado")
|
| 207 |
|
| 208 |
+
progreso = _progreso_plan(db, current_user.id, plan.id)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
if progreso:
|
| 211 |
return {"message": "Ya estás suscrito a este plan", "dia_actual": progreso.dia_actual}
|
|
|
|
| 213 |
nuevo_progreso = ProgresoPlan(
|
| 214 |
user_id=current_user.id,
|
| 215 |
plan_id=plan.id,
|
|
|
|
| 216 |
dia_actual=1,
|
| 217 |
completado=False,
|
| 218 |
racha_actual=0
|
|
|
|
| 223 |
|
| 224 |
@router.post("/cancelar/{plan_id}")
|
| 225 |
def cancelar_plan(plan_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 226 |
+
filas = db.query(ProgresoPlan).filter(
|
|
|
|
|
|
|
| 227 |
ProgresoPlan.user_id == current_user.id,
|
| 228 |
+
ProgresoPlan.plan_id == plan_id
|
| 229 |
+
).all()
|
|
|
|
| 230 |
|
| 231 |
+
if not filas:
|
| 232 |
+
raise HTTPException(status_code=404, detail="No estás suscrito a este plan")
|
| 233 |
|
| 234 |
+
for fila in filas:
|
| 235 |
+
db.delete(fila)
|
| 236 |
db.commit()
|
| 237 |
return {"message": "Plan cancelado exitosamente"}
|
| 238 |
|
| 239 |
@router.get("/dia/{plan_id}")
|
| 240 |
def obtener_dia_lectura(plan_id: int, fecha_local: Optional[str] = None, dia_pedido: Optional[int] = Query(None, alias="dia"), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 241 |
check_and_reset_streaks(current_user.id, db, fecha_local)
|
| 242 |
+
progreso = _progreso_plan(db, current_user.id, plan_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
if not progreso:
|
| 245 |
+
raise HTTPException(status_code=400, detail="No estás suscrito a este plan")
|
| 246 |
|
| 247 |
# Releer un día ya leído (anterior al actual, o cualquiera si el plan está completo).
|
| 248 |
# Antes siempre se devolvía el día actual aunque se pidiera otro.
|
|
|
|
| 273 |
# Obtener los versículos del pasaje
|
| 274 |
versiculos = parse_and_fetch_passage(dia.pasajes, db)
|
| 275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
return {
|
| 277 |
"completado_todo": False,
|
| 278 |
"es_repaso": es_repaso,
|
|
|
|
| 280 |
"pasajes": dia.pasajes,
|
| 281 |
"titulo": dia.titulo or f"Día {dia.dia_numero}",
|
| 282 |
"versiculos": versiculos,
|
| 283 |
+
"preguntas": [] # La sección es solo de lectura; las versiones viejas de las apps aún leen este campo
|
| 284 |
}
|
| 285 |
|
| 286 |
@router.post("/completar-dia")
|
| 287 |
def completar_dia(data: CompletarDiaRequest, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 288 |
+
progreso = _progreso_plan(db, current_user.id, data.plan_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
if not progreso:
|
| 291 |
raise HTTPException(status_code=400, detail="No suscrito al plan")
|
|
|
|
| 302 |
# 1. VALIDACIÓN DE LA RACHA (STREAK)
|
| 303 |
hoy = data.fecha_local # Formato "YYYY-MM-DD"
|
| 304 |
racha_antes = progreso.racha_actual
|
| 305 |
+
|
| 306 |
if progreso.ultima_lectura_fecha == hoy:
|
| 307 |
# Ya leyó hoy, no incrementa racha pero actualiza progreso
|
| 308 |
pass
|
|
|
|
| 310 |
ultima_fecha = datetime.strptime(progreso.ultima_lectura_fecha, "%Y-%m-%d").date()
|
| 311 |
fecha_dispositivo = datetime.strptime(hoy, "%Y-%m-%d").date()
|
| 312 |
diff = (fecha_dispositivo - ultima_fecha).days
|
| 313 |
+
|
| 314 |
if diff == 1:
|
| 315 |
progreso.racha_actual += 1
|
| 316 |
elif diff > 1:
|
|
|
|
| 324 |
|
| 325 |
progreso.ultima_lectura_fecha = hoy
|
| 326 |
|
| 327 |
+
# 2. AVANCE DE DÍA
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
plan = db.query(PlanLectura).filter(PlanLectura.id == data.plan_id).first()
|
| 329 |
if progreso.dia_actual >= plan.dias_totales:
|
| 330 |
progreso.completado = True
|
|
|
|
| 334 |
db.commit()
|
| 335 |
|
| 336 |
return {
|
| 337 |
+
"puntos_ganados": 0, # Sin puntos: se conserva el campo para las versiones viejas de las apps
|
| 338 |
"nueva_racha": progreso.racha_actual,
|
| 339 |
"dia_siguiente": progreso.dia_actual,
|
| 340 |
"completado": progreso.completado
|
| 341 |
}
|
| 342 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
@router.get("/mi-estado")
|
| 344 |
def obtener_mi_estado(fecha_local: Optional[str] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
| 345 |
check_and_reset_streaks(current_user.id, db, fecha_local)
|
| 346 |
iglesia = get_iglesia_usuario(current_user.id, db)
|
| 347 |
+
|
| 348 |
+
progresos = _progresos_usuario(db, current_user.id)
|
| 349 |
racha_maxima = max([p.racha_actual for p in progresos]) if progresos else 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
|
| 351 |
return {
|
| 352 |
"user_id": current_user.id,
|
| 353 |
"racha_actual": racha_maxima,
|
| 354 |
+
"puntos_liga": 0,
|
| 355 |
"tiene_iglesia": iglesia is not None
|
| 356 |
}
|
| 357 |
|
|
|
|
| 362 |
user = db.query(User).filter(User.id == user_id).first()
|
| 363 |
if not user:
|
| 364 |
raise HTTPException(status_code=404, detail="Usuario no encontrado")
|
| 365 |
+
|
| 366 |
+
progresos = _progresos_usuario(db, user_id)
|
| 367 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
planes_info = []
|
| 369 |
racha_maxima = max([p.racha_actual for p in progresos]) if progresos else 0
|
| 370 |
+
|
| 371 |
for p in progresos:
|
| 372 |
plan_obj = db.query(PlanLectura).filter_by(id=p.plan_id).first()
|
| 373 |
if plan_obj:
|
| 374 |
dias_totales = plan_obj.dias_totales
|
| 375 |
dias_leidos = p.dia_actual - 1 if not p.completado else dias_totales
|
| 376 |
dias_faltantes = max(0, dias_totales - dias_leidos)
|
| 377 |
+
|
| 378 |
hoy = datetime.utcnow().strftime("%Y-%m-%d")
|
| 379 |
estado_ritmo = "Al día" if p.ultima_lectura_fecha == hoy else "Atrasado"
|
| 380 |
if p.completado:
|
| 381 |
estado_ritmo = "Completado"
|
| 382 |
+
|
| 383 |
planes_info.append({
|
| 384 |
"plan_id": plan_obj.id,
|
| 385 |
"nombre": plan_obj.nombre,
|
|
|
|
| 392 |
"estado_ritmo": estado_ritmo,
|
| 393 |
"ultima_lectura": p.ultima_lectura_fecha
|
| 394 |
})
|
| 395 |
+
|
| 396 |
return {
|
| 397 |
"user_id": user.id,
|
| 398 |
"username": user.username,
|
| 399 |
"racha_actual": racha_maxima,
|
| 400 |
+
"puntos_liga": 0,
|
| 401 |
"planes": planes_info
|
| 402 |
}
|
| 403 |
|
|
|
|
| 489 |
"message": "Repaso ya completado anteriormente (duplicado silenciado)"
|
| 490 |
}
|
| 491 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 492 |
progreso.repaso_completado_hasta = data.dias_hito
|
| 493 |
db.commit()
|
| 494 |
|
| 495 |
return {
|
| 496 |
+
"puntos_ganados": 0,
|
| 497 |
"nueva_racha": progreso.racha_actual,
|
| 498 |
"repaso_completado_hasta": progreso.repaso_completado_hasta
|
| 499 |
}
|
| 500 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 501 |
@router.get("/preguntas/infinitas")
|
| 502 |
def obtener_preguntas_infinitas(
|
| 503 |
db: Session = Depends(get_db),
|
|
|
|
| 506 |
todas = db.query(PreguntaQuiz).all()
|
| 507 |
if not todas:
|
| 508 |
raise HTTPException(status_code=404, detail="No hay preguntas registradas en el sistema")
|
| 509 |
+
|
| 510 |
# Barajarlas
|
| 511 |
random.shuffle(todas)
|
| 512 |
+
|
| 513 |
preguntas_data = []
|
| 514 |
for q in todas:
|
| 515 |
try:
|
app/routers/iglesia.py
CHANGED
|
@@ -18,7 +18,6 @@ from app.models.iglesia import (
|
|
| 18 |
Iglesia, IglesiaMember, IglesiaRol, Miembro, Calendario,
|
| 19 |
Servicio, Asistencia, Finanza, Momento, RelacionFamiliar, Inventario, DismissedVisita
|
| 20 |
)
|
| 21 |
-
from app.models.aprendizaje import ProgresoPlan, PuntuacionLiga
|
| 22 |
from app.models.user import User
|
| 23 |
from app.routers.auth import get_current_user
|
| 24 |
from app.utils.credits import deduct_credits
|
|
@@ -676,8 +675,6 @@ def eliminar_iglesia(iglesia_id: int, db: Session = Depends(get_db), current_use
|
|
| 676 |
db.query(Momento).filter(Momento.iglesia_id == iglesia_id).delete(synchronize_session=False)
|
| 677 |
db.query(Finanza).filter(Finanza.iglesia_id == iglesia_id).delete(synchronize_session=False)
|
| 678 |
db.query(Inventario).filter(Inventario.iglesia_id == iglesia_id).delete(synchronize_session=False)
|
| 679 |
-
db.query(ProgresoPlan).filter(ProgresoPlan.iglesia_id == iglesia_id).delete(synchronize_session=False)
|
| 680 |
-
db.query(PuntuacionLiga).filter(PuntuacionLiga.iglesia_id == iglesia_id).delete(synchronize_session=False)
|
| 681 |
|
| 682 |
# 6. Miembros, Membresías de usuario y Roles de iglesia
|
| 683 |
db.query(Miembro).filter(Miembro.iglesia_id == iglesia_id).delete(synchronize_session=False)
|
|
|
|
| 18 |
Iglesia, IglesiaMember, IglesiaRol, Miembro, Calendario,
|
| 19 |
Servicio, Asistencia, Finanza, Momento, RelacionFamiliar, Inventario, DismissedVisita
|
| 20 |
)
|
|
|
|
| 21 |
from app.models.user import User
|
| 22 |
from app.routers.auth import get_current_user
|
| 23 |
from app.utils.credits import deduct_credits
|
|
|
|
| 675 |
db.query(Momento).filter(Momento.iglesia_id == iglesia_id).delete(synchronize_session=False)
|
| 676 |
db.query(Finanza).filter(Finanza.iglesia_id == iglesia_id).delete(synchronize_session=False)
|
| 677 |
db.query(Inventario).filter(Inventario.iglesia_id == iglesia_id).delete(synchronize_session=False)
|
|
|
|
|
|
|
| 678 |
|
| 679 |
# 6. Miembros, Membresías de usuario y Roles de iglesia
|
| 680 |
db.query(Miembro).filter(Miembro.iglesia_id == iglesia_id).delete(synchronize_session=False)
|
init_supabase_db.py
CHANGED
|
@@ -16,7 +16,7 @@ from app.models.iglesia import (
|
|
| 16 |
)
|
| 17 |
from app.models.aprendizaje import (
|
| 18 |
BibliaLibro, BibliaVersiculo, PlanLectura, DiaLectura,
|
| 19 |
-
PreguntaQuiz, ProgresoPlan
|
| 20 |
)
|
| 21 |
from app.models.lyrics import Group, UserGroup, Lyric, Repertorio, RepertorioLyric, Invitation
|
| 22 |
from app.models.midi import PartituraMidi
|
|
|
|
| 16 |
)
|
| 17 |
from app.models.aprendizaje import (
|
| 18 |
BibliaLibro, BibliaVersiculo, PlanLectura, DiaLectura,
|
| 19 |
+
PreguntaQuiz, ProgresoPlan
|
| 20 |
)
|
| 21 |
from app.models.lyrics import Group, UserGroup, Lyric, Repertorio, RepertorioLyric, Invitation
|
| 22 |
from app.models.midi import PartituraMidi
|