-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.py
More file actions
973 lines (852 loc) · 33.6 KB
/
Copy pathadmin.py
File metadata and controls
973 lines (852 loc) · 33.6 KB
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
# -*- coding: utf-8 -*-
"""
TutorOps Pro - Admin Dashboard
==============================
Password-protected admin interface for managing the system.
Pure HTML/CSS, no JavaScript frameworks.
"""
import os
import json
import secrets
from datetime import datetime
from pathlib import Path
from typing import Optional
from fastapi import APIRouter, Request, HTTPException, Form, Response
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from dotenv import load_dotenv
import csv
import io
from database import (
get_stats, get_payment_stats, get_pending_payments, get_all_payments,
get_all_students, get_all_messages, search_messages, verify_payment,
reject_payment, export_all_data, get_daily_stats_range, update_student,
create_scheduled_message, get_pending_scheduled_messages, get_all_scheduled_messages,
cancel_scheduled_message, add_student_note, update_student_name, adjust_student_balance
)
from logger import log
from whatsapp_bridge import send_whatsapp_message
load_dotenv()
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin123")
SESSION_SECRET = secrets.token_hex(16)
KNOWLEDGE_FILE = Path(__file__).parent / "center_knowledge.txt"
router = APIRouter(prefix="/admin", tags=["admin"])
active_sessions = set()
# HTML Icons (ASCII-safe)
ICON_HOME = "🏠"
ICON_MSG = "💬"
ICON_MONEY = "💰"
ICON_USERS = "👥"
ICON_BOOK = "📚"
ICON_BROADCAST = "📢"
ICON_CHART = "📈"
ICON_CHECK = "✔"
ICON_CROSS = "✖"
ICON_LOCK = "🔒"
ICON_EXIT = "🚪"
ICON_WARN = "⚠"
ICON_PARTY = "🎉"
ICON_CLOCK = "🕑"
ADMIN_STYLES = """
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg-primary: #0f0f1a;
--bg-secondary: #1a1a2e;
--bg-card: rgba(255,255,255,0.05);
--text-primary: #ffffff;
--text-secondary: rgba(255,255,255,0.7);
--accent: #4ade80;
--accent-hover: #22c55e;
--danger: #ef4444;
--warning: #f59e0b;
--border: rgba(255,255,255,0.1);
}
body {
font-family: 'Segoe UI', system-ui, sans-serif;
background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
color: var(--text-primary);
min-height: 100vh;
line-height: 1.6;
}
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
.nav {
background: var(--bg-card);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--border);
padding: 15px 0;
position: sticky;
top: 0;
z-index: 100;
}
.nav-inner {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.nav-brand { font-size: 1.5rem; font-weight: bold; color: var(--accent); }
.nav-links { display: flex; gap: 15px; flex-wrap: wrap; }
.nav-links a {
color: var(--text-secondary);
text-decoration: none;
padding: 8px 12px;
border-radius: 8px;
transition: all 0.2s;
font-size: 0.9rem;
}
.nav-links a:hover, .nav-links a.active {
color: var(--text-primary);
background: var(--bg-card);
}
.card {
background: var(--bg-card);
backdrop-filter: blur(10px);
border: 1px solid var(--border);
border-radius: 16px;
padding: 24px;
margin-bottom: 20px;
}
.card-title {
font-size: 1.2rem;
font-weight: 600;
margin-bottom: 16px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.stat-card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 12px;
padding: 20px;
text-align: center;
}
.stat-value {
font-size: 2rem;
font-weight: bold;
color: var(--accent);
}
.stat-label {
color: var(--text-secondary);
font-size: 0.85rem;
margin-top: 5px;
}
.table-wrapper { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; }
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid var(--border);
}
th {
color: var(--text-secondary);
font-weight: 500;
font-size: 0.8rem;
text-transform: uppercase;
}
tr:hover { background: var(--bg-card); }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 8px; color: var(--text-secondary); }
input, textarea, select {
width: 100%;
padding: 12px;
background: rgba(0,0,0,0.3);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text-primary);
font-size: 1rem;
}
input:focus, textarea:focus { outline: none; border-color: var(--accent); }
textarea { min-height: 200px; font-family: monospace; resize: vertical; }
.btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 10px 20px;
border: none;
border-radius: 8px;
font-size: 0.95rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
text-decoration: none;
}
.btn-primary {
background: linear-gradient(135deg, var(--accent) 0%, var(--accent-hover) 100%);
color: #000;
}
.btn-primary:hover { transform: translateY(-2px); }
.btn-danger { background: var(--danger); color: white; }
.btn-secondary { background: var(--bg-card); color: var(--text-primary); border: 1px solid var(--border); }
.btn-sm { padding: 6px 12px; font-size: 0.85rem; }
.badge {
display: inline-block;
padding: 4px 10px;
border-radius: 20px;
font-size: 0.8rem;
font-weight: 500;
}
.badge-pending { background: var(--warning); color: #000; }
.badge-verified { background: var(--accent); color: #000; }
.badge-rejected { background: var(--danger); color: white; }
.login-container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.login-card {
background: var(--bg-card);
backdrop-filter: blur(10px);
border: 1px solid var(--border);
border-radius: 20px;
padding: 40px;
width: 100%;
max-width: 400px;
}
.login-title { text-align: center; font-size: 2rem; margin-bottom: 30px; }
.alert { padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; }
.alert-success { background: rgba(74,222,128,0.2); border: 1px solid var(--accent); }
.alert-error { background: rgba(239,68,68,0.2); border: 1px solid var(--danger); }
.page-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
flex-wrap: wrap;
gap: 10px;
}
.page-title { font-size: 1.5rem; }
.search-bar { display: flex; gap: 10px; margin-bottom: 20px; }
.search-bar input { flex: 1; }
</style>
"""
def get_session_token(request: Request) -> Optional[str]:
return request.cookies.get("admin_session")
def is_authenticated(request: Request) -> bool:
token = get_session_token(request)
return token in active_sessions
def render_nav(active: str = "") -> str:
links = [
("", ICON_HOME + " Home"),
("/messages", ICON_MSG + " Messages"),
("/payments", ICON_MONEY + " Payments"),
("/students", ICON_USERS + " Students"),
("/knowledge", ICON_BOOK + " Knowledge"),
("/schedule", ICON_CLOCK + " Schedule"),
("/broadcast", ICON_BROADCAST + " Broadcast"),
("/analytics", ICON_CHART + " Analytics"),
]
nav_links = ""
for path, label in links:
active_class = "active" if active == path else ""
nav_links += f'<a href="/admin{path}" class="{active_class}">{label}</a>'
return f"""
<nav class="nav">
<div class="nav-inner">
<div class="nav-brand">TutorOps Admin</div>
<div class="nav-links">
{nav_links}
<a href="/admin/logout">{ICON_EXIT} Logout</a>
</div>
</div>
</nav>
"""
def render_page(title: str, content: str, active: str = "") -> str:
return f"""<!DOCTYPE html>
<html>
<head>
<title>{title} - TutorOps Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
{ADMIN_STYLES}
</head>
<body>
{render_nav(active)}
<div class="container">{content}</div>
</body>
</html>"""
def fmt_amount(val):
"""Format amount as integer, handling None"""
try:
return int(float(val or 0))
except:
return 0
@router.get("/login", response_class=HTMLResponse)
async def login_page(request: Request, error: str = None):
error_html = f'<div class="alert alert-error">{error}</div>' if error else ""
return f"""<!DOCTYPE html>
<html>
<head>
<title>Admin Login - TutorOps Pro</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
{ADMIN_STYLES}
</head>
<body>
<div class="login-container">
<div class="login-card">
<h1 class="login-title">{ICON_LOCK} Admin Login</h1>
{error_html}
<form method="POST" action="/admin/login">
<div class="form-group">
<label>Password</label>
<input type="password" name="password" placeholder="Enter admin password" required autofocus>
</div>
<button type="submit" class="btn btn-primary" style="width: 100%">Login</button>
</form>
</div>
</div>
</body>
</html>"""
@router.post("/login")
async def do_login(password: str = Form(...)):
if password == ADMIN_PASSWORD:
token = secrets.token_hex(32)
active_sessions.add(token)
response = RedirectResponse(url="/admin", status_code=303)
response.set_cookie("admin_session", token, httponly=True, max_age=86400)
log.info("Admin login successful")
return response
else:
log.warning("Admin login failed - wrong password")
return RedirectResponse(url="/admin/login?error=Invalid password", status_code=303)
@router.get("/logout")
async def logout(request: Request):
token = get_session_token(request)
if token in active_sessions:
active_sessions.remove(token)
response = RedirectResponse(url="/admin/login", status_code=303)
response.delete_cookie("admin_session")
return response
@router.get("", response_class=HTMLResponse)
async def dashboard(request: Request):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
stats = get_stats()
payment_stats = get_payment_stats()
pending = get_pending_payments()
pending_rows = ""
for p in pending[:5]:
pending_rows += f"""<tr>
<td>{p['phone']}</td>
<td><strong>{fmt_amount(p['amount'])} EGP</strong></td>
<td>{p.get('transaction_id') or 'N/A'}</td>
<td>{str(p.get('created_at', ''))[:16]}</td>
<td>
<form method="POST" action="/admin/payments/{p['id']}/verify" style="display:inline">
<button type="submit" class="btn btn-primary btn-sm">{ICON_CHECK}</button>
</form>
<form method="POST" action="/admin/payments/{p['id']}/reject" style="display:inline">
<button type="submit" class="btn btn-danger btn-sm">{ICON_CROSS}</button>
</form>
</td>
</tr>"""
if not pending_rows:
pending_rows = f'<tr><td colspan="5" style="text-align:center;padding:40px">No pending payments {ICON_PARTY}</td></tr>'
content = f"""
<div class="page-header">
<h1 class="page-title">{ICON_CHART} Dashboard</h1>
<a href="/admin/export" class="btn btn-secondary">Export Data</a>
</div>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-value">{stats['messages_today']}</div>
<div class="stat-label">Messages Today</div>
</div>
<div class="stat-card">
<div class="stat-value">{stats['total_messages']}</div>
<div class="stat-label">Total Messages</div>
</div>
<div class="stat-card">
<div class="stat-value">{stats['unique_users']}</div>
<div class="stat-label">Total Users</div>
</div>
<div class="stat-card">
<div class="stat-value">{stats['active_conversations']}</div>
<div class="stat-label">Active Now</div>
</div>
</div>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-value" style="color: #f59e0b;">{payment_stats['pending_count']}</div>
<div class="stat-label">Pending Payments</div>
</div>
<div class="stat-card">
<div class="stat-value">{fmt_amount(payment_stats['today_total'])} EGP</div>
<div class="stat-label">Collected Today</div>
</div>
<div class="stat-card">
<div class="stat-value">{fmt_amount(payment_stats['total_verified'])} EGP</div>
<div class="stat-label">Total Collected</div>
</div>
<div class="stat-card">
<div class="stat-value">{fmt_amount(stats['avg_response_time_ms'])}ms</div>
<div class="stat-label">Avg Response</div>
</div>
</div>
<div class="card">
<div class="card-title">{ICON_WARN} Pending Payments ({len(pending)})</div>
<div class="table-wrapper">
<table>
<thead>
<tr><th>Phone</th><th>Amount</th><th>Transaction ID</th><th>Date</th><th>Actions</th></tr>
</thead>
<tbody>{pending_rows}</tbody>
</table>
</div>
</div>
"""
return render_page("Dashboard", content, "")
@router.get("/messages", response_class=HTMLResponse)
async def messages_page(request: Request, q: str = None):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
messages = search_messages(q) if q else get_all_messages(limit=50)
rows = ""
for m in messages:
ts = str(m.get('timestamp', ''))[:16]
phone = str(m.get('phone', ''))[:15]
content_text = str(m.get('content', ''))[:50]
response_text = str(m.get('response', '') or '')[:50]
rt = m.get('response_time_ms') or 'N/A'
rows += f"<tr><td>{ts}</td><td>{phone}</td><td>{content_text}</td><td>{response_text}</td><td>{rt}</td></tr>"
if not rows:
rows = '<tr><td colspan="5" style="text-align:center;padding:40px">No messages yet</td></tr>'
content = f"""
<div class="page-header">
<h1 class="page-title">{ICON_MSG} Messages</h1>
</div>
<form class="search-bar" method="GET">
<input type="text" name="q" placeholder="Search messages..." value="{q or ''}">
<button type="submit" class="btn btn-primary">Search</button>
</form>
<div class="card">
<div class="table-wrapper">
<table>
<thead><tr><th>Time</th><th>Phone</th><th>Message</th><th>Response</th><th>Time (ms)</th></tr></thead>
<tbody>{rows}</tbody>
</table>
</div>
</div>
"""
return render_page("Messages", content, "/messages")
@router.get("/payments", response_class=HTMLResponse)
async def payments_page(request: Request):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
payments = get_all_payments(limit=100)
def get_badge(status):
return {'pending': 'badge-pending', 'verified': 'badge-verified', 'rejected': 'badge-rejected'}.get(status, '')
rows = ""
for p in payments:
date = str(p.get('created_at', ''))[:10]
actions = '-'
if p['status'] == 'pending':
actions = f'''
<form method="POST" action="/admin/payments/{p['id']}/verify" style="display:inline">
<button type="submit" class="btn btn-primary btn-sm">{ICON_CHECK}</button>
</form>
<form method="POST" action="/admin/payments/{p['id']}/reject" style="display:inline">
<button type="submit" class="btn btn-danger btn-sm">{ICON_CROSS}</button>
</form>'''
rows += f"""<tr>
<td>{date}</td>
<td>{p['phone']}</td>
<td>{p.get('student_name') or 'Unknown'}</td>
<td><strong>{fmt_amount(p['amount'])} EGP</strong></td>
<td><span class="badge {get_badge(p['status'])}">{p['status']}</span></td>
<td>{p.get('transaction_id') or 'N/A'}</td>
<td>{actions}</td>
</tr>"""
if not rows:
rows = '<tr><td colspan="7" style="text-align:center;padding:40px">No payments yet</td></tr>'
content = f"""
<div class="page-header">
<h1 class="page-title">{ICON_MONEY} Payments</h1>
</div>
<div class="card">
<div class="table-wrapper">
<table>
<thead><tr><th>Date</th><th>Phone</th><th>Student</th><th>Amount</th><th>Status</th><th>Transaction ID</th><th>Actions</th></tr></thead>
<tbody>{rows}</tbody>
</table>
</div>
</div>
"""
return render_page("Payments", content, "/payments")
@router.post("/payments/{payment_id}/verify")
async def verify_payment_action(request: Request, payment_id: int):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
verify_payment(payment_id)
log.info(f"Payment {payment_id} verified")
return RedirectResponse(url="/admin/payments", status_code=303)
@router.post("/payments/{payment_id}/reject")
async def reject_payment_action(request: Request, payment_id: int):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
reject_payment(payment_id)
log.info(f"Payment {payment_id} rejected")
return RedirectResponse(url="/admin/payments", status_code=303)
@router.get("/students", response_class=HTMLResponse)
async def students_page(request: Request):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
students = get_all_students()
rows = ""
for s in students:
rows += f"""<tr>
<td>{s.get('name') or 'Unknown'}</td>
<td>{s['phone']}</td>
<td><strong>{fmt_amount(s['balance'])} EGP</strong></td>
<td>{s.get('payment_count', 0)}</td>
<td>{str(s.get('created_at', ''))[:10]}</td>
</tr>"""
if not rows:
rows = '<tr><td colspan="5" style="text-align:center;padding:40px">No students yet</td></tr>'
content = f"""
<div class="page-header">
<h1 class="page-title">{ICON_USERS} Students</h1>
</div>
<div class="card">
<div class="table-wrapper">
<table>
<thead><tr><th>Name</th><th>Phone</th><th>Balance</th><th>Payments</th><th>Joined</th></tr></thead>
<tbody>{rows}</tbody>
</table>
</div>
</div>
"""
return render_page("Students", content, "/students")
@router.get("/knowledge", response_class=HTMLResponse)
async def knowledge_page(request: Request, saved: bool = False):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
try:
knowledge_content = KNOWLEDGE_FILE.read_text(encoding='utf-8')
except:
knowledge_content = ""
saved_msg = '<div class="alert alert-success">Knowledge base saved successfully!</div>' if saved else ''
content = f"""
<div class="page-header">
<h1 class="page-title">{ICON_BOOK} Knowledge Base</h1>
</div>
{saved_msg}
<div class="card">
<form method="POST" action="/admin/knowledge">
<div class="form-group">
<label>Edit center_knowledge.txt</label>
<textarea name="content" style="min-height:300px">{knowledge_content}</textarea>
</div>
<button type="submit" class="btn btn-primary">Save Changes</button>
</form>
</div>
"""
return render_page("Knowledge Base", content, "/knowledge")
@router.post("/knowledge")
async def save_knowledge(request: Request, content: str = Form(...)):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
try:
KNOWLEDGE_FILE.write_text(content, encoding='utf-8')
log.info("Knowledge base updated via admin")
except Exception as e:
log.error(f"Failed to save knowledge base: {e}")
return RedirectResponse(url="/admin/knowledge?saved=true", status_code=303)
@router.get("/broadcast", response_class=HTMLResponse)
async def broadcast_page(request: Request, sent: int = 0):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
students = get_all_students()
sent_msg = f'<div class="alert alert-success">Message sent to {sent} students!</div>' if sent > 0 else ''
rows = ""
for s in students[:20]:
rows += f"<tr><td>{s.get('name') or 'Unknown'}</td><td>{s['phone']}</td></tr>"
if len(students) > 20:
rows += f'<tr><td colspan="2" style="text-align:center">...and {len(students) - 20} more</td></tr>'
content = f"""
<div class="page-header">
<h1 class="page-title">{ICON_BROADCAST} Broadcast Message</h1>
</div>
{sent_msg}
<div class="card">
<div class="card-title">Send Announcement</div>
<form method="POST" action="/admin/broadcast">
<div class="form-group">
<label>Message (will be sent to all students)</label>
<textarea name="message" placeholder="Type your announcement here..." required></textarea>
</div>
<div class="form-group">
<label><input type="checkbox" name="confirm" required> I confirm I want to send this to {len(students)} students</label>
</div>
<button type="submit" class="btn btn-primary">Send Broadcast</button>
</form>
</div>
<div class="card">
<div class="card-title">Recipients ({len(students)})</div>
<div class="table-wrapper" style="max-height:300px;overflow-y:auto">
<table>
<thead><tr><th>Name</th><th>Phone</th></tr></thead>
<tbody>{rows}</tbody>
</table>
</div>
</div>
"""
return render_page("Broadcast", content, "/broadcast")
@router.post("/broadcast")
async def send_broadcast(request: Request, message: str = Form(...)):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
students = get_all_students()
sent_count = 0
for student in students:
try:
if send_whatsapp_message(student['phone'], message):
sent_count += 1
except Exception as e:
log.error(f"Broadcast failed for {student['phone']}: {e}")
log.info(f"Broadcast sent to {sent_count}/{len(students)} students")
return RedirectResponse(url=f"/admin/broadcast?sent={sent_count}", status_code=303)
@router.get("/analytics", response_class=HTMLResponse)
async def analytics_page(request: Request):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
daily_stats = get_daily_stats_range(days=7)
stats = get_stats()
payment_stats = get_payment_stats()
max_msgs = max([d['total_messages'] for d in daily_stats], default=1) or 1
bars_html = ""
for day in reversed(daily_stats):
date_label = day['date'][5:]
messages = day['total_messages']
width_pct = (messages / max_msgs) * 100
bars_html += f"""
<div style="display:flex;align-items:center;margin-bottom:12px">
<div style="width:60px;color:var(--text-secondary)">{date_label}</div>
<div style="flex:1;background:rgba(255,255,255,0.1);border-radius:4px;height:24px;margin-right:10px">
<div style="width:{width_pct}%;background:linear-gradient(90deg,var(--accent),var(--accent-hover));height:100%;border-radius:4px"></div>
</div>
<div style="width:40px;text-align:right;font-weight:bold">{messages}</div>
</div>"""
if not bars_html:
bars_html = '<p style="text-align:center;padding:40px;color:var(--text-secondary)">No data yet</p>'
content = f"""
<div class="page-header">
<h1 class="page-title">{ICON_CHART} Analytics</h1>
</div>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-value">{stats['total_messages']}</div>
<div class="stat-label">Total Messages</div>
</div>
<div class="stat-card">
<div class="stat-value">{stats['unique_users']}</div>
<div class="stat-label">Unique Users</div>
</div>
<div class="stat-card">
<div class="stat-value">{fmt_amount(payment_stats['total_verified'])}</div>
<div class="stat-label">Total Revenue (EGP)</div>
</div>
<div class="stat-card">
<div class="stat-value">{fmt_amount(stats['avg_response_time_ms'])}</div>
<div class="stat-label">Avg Response (ms)</div>
</div>
</div>
<div class="card">
<div class="card-title">Messages Per Day (Last 7 Days)</div>
<div style="padding:20px 0">{bars_html}</div>
</div>
"""
return render_page("Analytics", content, "/analytics")
@router.get("/export")
async def export_data(request: Request):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
data = export_all_data()
filename = f"tutorops_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
return JSONResponse(content=data, headers={"Content-Disposition": f"attachment; filename={filename}"})
# ============== SCHEDULED MESSAGES (Phase 4) ==============
@router.get("/schedule", response_class=HTMLResponse)
async def schedule_page(request: Request, created: bool = False, cancelled: bool = False):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
pending = get_pending_scheduled_messages()
all_msgs = get_all_scheduled_messages(limit=20)
def get_status_badge(status):
return {
'pending': 'badge-pending',
'sent': 'badge-verified',
'cancelled': 'badge-rejected'
}.get(status, '')
# Build pending table
pending_rows = ""
for m in pending:
target = m.get('phone') or 'All Students'
pending_rows += f"""<tr>
<td>{str(m.get('send_at', ''))[:16]}</td>
<td>{target}</td>
<td>{str(m.get('message', ''))[:50]}...</td>
<td>
<form method="POST" action="/admin/schedule/{m['id']}/cancel" style="display:inline">
<button type="submit" class="btn btn-danger btn-sm">{ICON_CROSS} Cancel</button>
</form>
</td>
</tr>"""
if not pending_rows:
pending_rows = '<tr><td colspan="4" style="text-align:center;padding:30px">No pending messages</td></tr>'
# Build history table
history_rows = ""
for m in all_msgs:
target = m.get('phone') or 'All'
status = m.get('status', 'pending')
history_rows += f"""<tr>
<td>{str(m.get('send_at', ''))[:16]}</td>
<td>{target[:15]}</td>
<td>{str(m.get('message', ''))[:40]}...</td>
<td><span class="badge {get_status_badge(status)}">{status}</span></td>
</tr>"""
alert = ""
if created:
alert = '<div class="alert alert-success">Message scheduled successfully!</div>'
if cancelled:
alert = '<div class="alert alert-success">Message cancelled!</div>'
content = f"""
<div class="page-header">
<h1 class="page-title">{ICON_CLOCK} Scheduled Messages</h1>
</div>
{alert}
<div class="card">
<div class="card-title">Create Scheduled Message</div>
<form method="POST" action="/admin/schedule">
<div class="form-group">
<label>Send To</label>
<select name="target">
<option value="all">All Students (Broadcast)</option>
<option value="single">Single Phone Number</option>
</select>
</div>
<div class="form-group">
<label>Phone (only if single)</label>
<input type="text" name="phone" placeholder="+201234567890">
</div>
<div class="form-group">
<label>Message</label>
<textarea name="message" style="min-height:100px" required></textarea>
</div>
<div class="form-group">
<label>Send At (YYYY-MM-DD HH:MM)</label>
<input type="datetime-local" name="send_at" required>
</div>
<button type="submit" class="btn btn-primary">{ICON_CLOCK} Schedule Message</button>
</form>
</div>
<div class="card">
<div class="card-title">{ICON_WARN} Pending Messages ({len(pending)})</div>
<div class="table-wrapper">
<table>
<thead><tr><th>Send At</th><th>Target</th><th>Message</th><th>Actions</th></tr></thead>
<tbody>{pending_rows}</tbody>
</table>
</div>
</div>
<div class="card">
<div class="card-title">History</div>
<div class="table-wrapper">
<table>
<thead><tr><th>Send At</th><th>Target</th><th>Message</th><th>Status</th></tr></thead>
<tbody>{history_rows}</tbody>
</table>
</div>
</div>
"""
return render_page("Schedule", content, "/schedule")
@router.post("/schedule")
async def create_schedule(request: Request, message: str = Form(...), send_at: str = Form(...),
target: str = Form(...), phone: str = Form(None)):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
try:
dt = datetime.strptime(send_at, "%Y-%m-%dT%H:%M")
phone_to_use = phone if target == "single" and phone else None
create_scheduled_message(message, dt, phone_to_use)
log.info(f"Scheduled message created for {dt}")
except Exception as e:
log.error(f"Failed to create scheduled message: {e}")
return RedirectResponse(url="/admin/schedule?created=true", status_code=303)
@router.post("/schedule/{msg_id}/cancel")
async def cancel_schedule(request: Request, msg_id: int):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
cancel_scheduled_message(msg_id)
log.info(f"Scheduled message {msg_id} cancelled")
return RedirectResponse(url="/admin/schedule?cancelled=true", status_code=303)
# ============== CSV EXPORTS (Phase 4) ==============
@router.get("/export/csv/students")
async def export_students_csv(request: Request):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
students = get_all_students()
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(['Name', 'Phone', 'Balance', 'Payments', 'Joined'])
for s in students:
writer.writerow([
s.get('name') or 'Unknown',
s.get('phone', ''),
s.get('balance', 0),
s.get('payment_count', 0),
str(s.get('created_at', ''))[:10]
])
return Response(
content=output.getvalue(),
media_type="text/csv",
headers={"Content-Disposition": "attachment; filename=students.csv"}
)
@router.get("/export/csv/payments")
async def export_payments_csv(request: Request):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
payments = get_all_payments(limit=1000)
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(['Date', 'Phone', 'Amount', 'Status', 'Transaction ID'])
for p in payments:
writer.writerow([
str(p.get('created_at', ''))[:10],
p.get('phone', ''),
p.get('amount', 0),
p.get('status', ''),
p.get('transaction_id') or ''
])
return Response(
content=output.getvalue(),
media_type="text/csv",
headers={"Content-Disposition": "attachment; filename=payments.csv"}
)
@router.get("/export/csv/messages")
async def export_messages_csv(request: Request):
if not is_authenticated(request):
return RedirectResponse(url="/admin/login", status_code=303)
messages = get_all_messages(limit=1000)
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(['Timestamp', 'Phone', 'Message', 'Response', 'Response Time (ms)'])
for m in messages:
writer.writerow([
str(m.get('timestamp', '')),
m.get('phone', ''),
m.get('content', ''),
m.get('response', ''),
m.get('response_time_ms', '')
])
return Response(
content=output.getvalue(),
media_type="text/csv",
headers={"Content-Disposition": "attachment; filename=messages.csv"}
)