File size: 14,354 Bytes
6aa6081
 
 
4a12934
6aa6081
 
 
 
 
 
ddae258
6aa6081
 
 
 
 
ddae258
 
 
 
 
 
 
 
 
 
6aa6081
 
ddae258
6aa6081
ddae258
6aa6081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a12934
6aa6081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddae258
 
 
 
 
 
 
 
a3df693
 
 
 
ddae258
a3df693
ddae258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5f2d1b
 
 
 
ddae258
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
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,
    }