from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy.orm import Session from sqlalchemy import func, cast, Date from datetime import date, datetime, timedelta, timezone from typing import Optional import io import openpyxl from fastapi.responses import StreamingResponse from app.core.database import get_db from app.core.security import verify_password from app.dependencies.developer import require_developer from app.models.user import User from app.models.account import Account from app.models.plan import Plan from app.models.attendance import Attendance from app.models.entrance_log import EntranceLog from app.models.audit_log import AuditLog from app.models.enrollment import Enrollment from app.models.teacher_section import TeacherSection from app.models.teacher_subject import TeacherSubject from app.models.section_subject import SectionSubject from app.models.section_schedule import SectionSchedule from app.models.card_template import CardTemplate from app.models.holiday import Holiday from app.models.user_permission import UserPermission from app.models.section import Section from app.models.subject import Subject from app.models.face_encoding import FaceEncoding from app.models.system_log import SystemLog from app.schemas.auth import PurgeDemoRequest router = APIRouter(prefix="/developer", tags=["developer"]) @router.get("/dashboard") def developer_dashboard( dev: User = Depends(require_developer), db: Session = Depends(get_db), ): total_accounts = db.query(func.count(Account.id)).scalar() or 0 active_accounts = db.query(func.count(Account.id)).filter(Account.is_active == True).scalar() or 0 trial_accounts = db.query(func.count(Account.id)).filter(Account.trial_end_date.isnot(None)).scalar() or 0 total_users = db.query(func.count(User.id)).scalar() or 0 today = date.today() thirty_days_ago = today - timedelta(days=30) accounts_by_date = ( db.query( func.date(Account.created_at).label("day"), func.count(Account.id).label("cnt"), ) .filter(Account.created_at.isnot(None), Account.created_at >= thirty_days_ago) .group_by(func.date(Account.created_at)) .order_by(func.date(Account.created_at)) .all() ) errors_trend = ( db.query( func.date(SystemLog.created_at).label("day"), func.count(SystemLog.id).label("cnt"), ) .filter(SystemLog.created_at >= thirty_days_ago) .group_by(func.date(SystemLog.created_at)) .order_by(func.date(SystemLog.created_at)) .all() ) accounts_detail = ( db.query( Account.id, Account.organization_name, Account.is_active, Account.trial_end_date, Plan.name.label("plan_name"), func.count(User.id).label("user_count"), ) .outerjoin(User, User.account_id == Account.id) .join(Plan, Plan.id == Account.plan_id) .group_by(Account.id, Plan.name) .order_by(Account.id) .all() ) return { "total_accounts": total_accounts, "active_accounts": active_accounts, "trial_accounts": trial_accounts, "total_users": total_users, "accounts_by_date": [ {"date": r.day.isoformat(), "count": r.cnt} for r in accounts_by_date ], "errors_trend": [ {"date": r.day.isoformat(), "count": r.cnt} for r in errors_trend ], "accounts": [ { "id": r.id, "name": r.organization_name, "is_active": r.is_active, "trial_end_date": r.trial_end_date.isoformat() if r.trial_end_date else None, "plan": r.plan_name, "user_count": r.user_count, } for r in accounts_detail ], } @router.get("/accounts") def list_accounts( search: Optional[str] = None, dev: User = Depends(require_developer), db: Session = Depends(get_db), ): query = ( db.query( Account.id, Account.organization_name, Account.is_active, Account.trial_end_date, Account.created_at, Plan.name.label("plan_name"), func.count(User.id).label("user_count"), ) .outerjoin(User, User.account_id == Account.id) .join(Plan, Plan.id == Account.plan_id) .group_by(Account.id, Plan.name) ) if search: query = query.filter(Account.organization_name.like(f"%{search}%")) accounts = query.order_by(Account.id).all() return [ { "id": r.id, "name": r.organization_name, "is_active": r.is_active, "trial_end_date": r.trial_end_date.isoformat() if r.trial_end_date else None, "created_at": r.created_at.isoformat() if hasattr(r, 'created_at') and r.created_at else None, "plan": r.plan_name, "user_count": r.user_count, } for r in accounts ] @router.put("/accounts/{account_id}/toggle-active") def toggle_account_active( account_id: int, dev: User = Depends(require_developer), db: Session = Depends(get_db), ): account = db.query(Account).filter(Account.id == account_id).first() if not account: raise HTTPException(status_code=404, detail="Account not found") account.is_active = not account.is_active db.commit() return {"id": account.id, "is_active": account.is_active} @router.put("/accounts/{account_id}/trial") def set_account_trial( account_id: int, days: int = Query(..., ge=1, le=365), dev: User = Depends(require_developer), db: Session = Depends(get_db), ): account = db.query(Account).filter(Account.id == account_id).first() if not account: raise HTTPException(status_code=404, detail="Account not found") account.trial_end_date = datetime.now(timezone.utc) + timedelta(days=days) db.commit() return { "id": account.id, "trial_end_date": account.trial_end_date.isoformat(), } @router.get("/logs") def system_logs( page: int = Query(1, ge=1), per_page: int = Query(20, ge=1, le=100), level: Optional[str] = None, dev: User = Depends(require_developer), db: Session = Depends(get_db), ): query = db.query(SystemLog) if level: query = query.filter(SystemLog.level == level) total = query.count() offset = (page - 1) * per_page logs = query.order_by(SystemLog.created_at.desc()).offset(offset).limit(per_page).all() return { "items": [ { "id": r.id, "level": r.level, "message": r.message, "traceback": r.traceback, "endpoint": r.endpoint, "method": r.method, "account_id": r.account_id, "user_id": r.user_id, "ip_address": r.ip_address, "created_at": r.created_at.isoformat() if r.created_at else None, } for r in logs ], "total": total, "page": page, "per_page": per_page, "total_pages": (total + per_page - 1) // per_page if total > 0 else 1, } @router.get("/logs/trend") def logs_trend( days: int = Query(30, ge=1, le=365), dev: User = Depends(require_developer), db: Session = Depends(get_db), ): today = date.today() start = today - timedelta(days=days - 1) rows = ( db.query( func.date(SystemLog.created_at).label("day"), func.count(SystemLog.id).label("cnt"), ) .filter(SystemLog.created_at >= start) .group_by(func.date(SystemLog.created_at)) .order_by(func.date(SystemLog.created_at)) .all() ) trend_map = {r.day: r.cnt for r in rows} result = [] for i in range(days): d = start + timedelta(days=i) result.append({"date": d.isoformat(), "count": trend_map.get(d, 0)}) return result @router.get("/users-by-account") def users_by_account( dev: User = Depends(require_developer), db: Session = Depends(get_db), ): rows = ( db.query( Account.organization_name, Account.id, func.count(User.id).label("user_count"), ) .outerjoin(User, User.account_id == Account.id) .group_by(Account.id, Account.organization_name) .order_by(Account.id) .all() ) return [ {"account_name": r.organization_name, "account_id": r.id, "user_count": r.user_count} for r in rows ] @router.get("/export") def export_report( dev: User = Depends(require_developer), db: Session = Depends(get_db), ): wb = openpyxl.Workbook() ws_accounts = wb.active ws_accounts.title = "Cuentas" ws_accounts.append(["ID", "Nombre", "Plan", "Activa", "Prueba hasta", "Usuarios"]) accounts = ( db.query( Account.id, Account.organization_name, Account.is_active, Account.trial_end_date, Plan.name, ) .join(Plan, Plan.id == Account.plan_id) .all() ) for a in accounts: user_count = db.query(func.count(User.id)).filter(User.account_id == a.id).scalar() or 0 ws_accounts.append([ a.id, a.organization_name, a.name, "Sí" if a.is_active else "No", a.trial_end_date.strftime("%Y-%m-%d") if a.trial_end_date else "", user_count, ]) ws_logs = wb.create_sheet("Errores") ws_logs.append(["ID", "Nivel", "Mensaje", "Endpoint", "Método", "Fecha"]) logs = ( db.query(SystemLog) .order_by(SystemLog.created_at.desc()) .limit(500) .all() ) for l in logs: ws_logs.append([ l.id, l.level, l.message[:200], l.endpoint, l.method, l.created_at.strftime("%Y-%m-%d %H:%M") if l.created_at else "", ]) output = io.BytesIO() wb.save(output) output.seek(0) return StreamingResponse( iter([output.getvalue()]), media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", headers={"Content-Disposition": "attachment; filename=reporte_desarrollador.xlsx"}, ) @router.post("/purge-demo") def purge_demo_data( payload: PurgeDemoRequest, dev: User = Depends(require_developer), db: Session = Depends(get_db), ): # 1) Verify the developer's password (re-auth confirmation). # Use 400 (not 401) so the global axios interceptor doesn't treat this as # a session-expired error and force a logout. The developer is authenticated # — they just gave a wrong supplemental password. if not verify_password(payload.password, dev.password_hash): raise HTTPException(status_code=400, detail="Contraseña incorrecta") # 2) Locate the demo account demo_acc = db.query(Account).filter(Account.is_demo.is_(True)).first() if not demo_acc: raise HTTPException(status_code=404, detail="No hay cuenta demo configurada") aid = demo_acc.id # 3) Safety: refuse if the developer running the purge is IN the demo account if dev.account_id == aid: raise HTTPException( status_code=400, detail="No puedes purgar desde la propia cuenta demo. Inicia sesión con otro developer.", ) # 4) Delete child rows in dependency order. All models filtered by account_id == aid. counts: dict[str, int] = {} # Tables with explicit account_id: counts["attendances"] = db.query(Attendance).filter(Attendance.account_id == aid).delete(synchronize_session=False) counts["entrance_logs"] = db.query(EntranceLog).filter(EntranceLog.account_id == aid).delete(synchronize_session=False) counts["audit_logs"] = db.query(AuditLog).filter(AuditLog.account_id == aid).delete(synchronize_session=False) counts["enrollments"] = db.query(Enrollment).filter(Enrollment.account_id == aid).delete(synchronize_session=False) counts["teacher_sections"] = db.query(TeacherSection).filter(TeacherSection.account_id == aid).delete(synchronize_session=False) counts["teacher_subjects"] = db.query(TeacherSubject).filter(TeacherSubject.account_id == aid).delete(synchronize_session=False) counts["section_subjects"] = db.query(SectionSubject).filter(SectionSubject.account_id == aid).delete(synchronize_session=False) counts["section_schedules"] = db.query(SectionSchedule).filter(SectionSchedule.account_id == aid).delete(synchronize_session=False) counts["card_templates"] = db.query(CardTemplate).filter(CardTemplate.account_id == aid).delete(synchronize_session=False) counts["holidays"] = db.query(Holiday).filter(Holiday.account_id == aid).delete(synchronize_session=False) counts["user_permissions"] = db.query(UserPermission).filter(UserPermission.account_id == aid).delete(synchronize_session=False) counts["sections"] = db.query(Section).filter(Section.account_id == aid).delete(synchronize_session=False) counts["subjects"] = db.query(Subject).filter(Subject.account_id == aid).delete(synchronize_session=False) # Records depending on users (no direct account_id): counts["face_encodings"] = db.query(FaceEncoding).filter( FaceEncoding.user_id.in_(db.query(User.id).filter(User.account_id == aid)) ).delete(synchronize_session=False) # Users: clear self-referencing parent_id first (so parent rows can be deleted in any order) db.query(User).filter(User.account_id == aid).update({"parent_id": None}, synchronize_session=False) counts["users"] = db.query(User).filter(User.account_id == aid).delete(synchronize_session=False) # Stamp the purge timestamp so the admin sees the banner on next login demo_acc.last_purged_at = datetime.now(timezone.utc) demo_acc.last_purge_acknowledged_at = None # reset prior ack so banner shows again db.commit() db.close() # release before seed() opens its own session # 5) Re-seed via seed_demo.seed() from seed_demo import seed seed() return { "success": True, "demo_account_id": aid, "deleted": counts, "reseeded": True, }