-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
4329 lines (3687 loc) · 192 KB
/
Copy pathapp.py
File metadata and controls
4329 lines (3687 loc) · 192 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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Read-a-Thon Web Application
Flask-based browser interface for managing and reporting on read-a-thon data
"""
from flask import Flask, render_template, request, jsonify, send_file, Response, session, redirect, url_for
from database import ReadathonDB, ReportGenerator, DatabaseRegistry
from queries import get_grade_level_classes_query, get_grade_aggregations_query, get_school_wide_leaders_query
import scoreboards
import handoff_doc
import csv
import io
import zipfile
from datetime import datetime
import os
import argparse
import json
import sys
from functools import wraps
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
app.secret_key = 'readathon-secret-key-change-in-production' # For session management
# Configuration file for persistent preferences (active database, simple/full view)
CONFIG_FILE = '.readathon_config'
VIEW_MODES = ('full', 'simple')
def load_config():
"""All remembered preferences (empty if the file is missing or unreadable)"""
try:
with open(CONFIG_FILE, 'r') as f:
return json.load(f)
except (OSError, ValueError):
return {}
def save_config(**updates):
"""Update some preferences, keeping the others"""
config = load_config()
config.update(updates)
try:
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=2)
except OSError:
pass # Silently fail if can't write config
def read_config():
"""Read active database ID from config file"""
return load_config().get('active_database_id')
def write_config(db_id, db_filename):
"""Write active database to config file"""
save_config(active_database_id=db_id, active_database_filename=db_filename)
# Temporary compatibility - will be removed when all routes are updated
# Parse command line arguments - HYBRID APPROACH
parser = argparse.ArgumentParser(description='Read-a-Thon Management System')
parser.add_argument('--db',
help='Database to use: display name ("2026 Read-a-Thon"), '
'filename (readathon_2026.db), or alias ("sample"). '
'Case-insensitive.')
view_group = parser.add_mutually_exclusive_group()
view_group.add_argument('--simple', action='store_const', const='simple', dest='view_mode',
help='Simple view: only Upload, Bulletins, Help and the database selector (remembered)')
view_group.add_argument('--full', action='store_const', const='full', dest='view_mode',
help='Full view: every page (remembered)')
args, unknown = parser.parse_known_args()
# Simple view hides everything but the daily job (upload -> scoreboard -> email); toggled in the nav
if args.view_mode:
save_config(view_mode=args.view_mode)
VIEW_MODE = load_config().get('view_mode', 'full')
if VIEW_MODE not in VIEW_MODES:
VIEW_MODE = 'full'
# Initialize registry
registry = DatabaseRegistry()
# Year databases copied into db/ (outside git) are registered automatically
for new_db_filename in registry.register_year_databases():
print(f"🗄️ Registered new database file: db/{new_db_filename}")
# Only one database accepts uploads/deletes (the newest year database until one is chosen in Admin)
editable_db = registry.get_database(registry.get_editable_database_id() or 0)
print(f"✏️ Editable database: {editable_db['display_name'] if editable_db else 'none (all read-only)'}")
# Determine startup database
if args.db:
# Command-line argument provided - match against display_name, filename, or alias
db_match = registry.get_database_by_name(args.db)
if not db_match:
print(f"\n❌ Database not found: {args.db}")
print("\nAvailable databases:")
for db in registry.list_databases():
active_marker = " (ACTIVE)" if db['is_active'] else ""
print(f" - {db['display_name']}{active_marker}")
print(f" Filename: {db['db_filename']}")
sys.exit(1)
DEFAULT_DATABASE_ID = db_match['db_id']
print(f"🗄️ Starting with database: {db_match['display_name']}")
print(f" (Specified via command line: --db {args.db})")
else:
# No CLI arg - check config file or use active database from registry
config_db_id = read_config()
if config_db_id:
# Use database from config file
db_info = registry.get_database(config_db_id)
if db_info:
DEFAULT_DATABASE_ID = config_db_id
print(f"🗄️ Starting with database: {db_info['display_name']}")
print(f" (Using remembered preference from {CONFIG_FILE})")
else:
# Config references non-existent database - fall back to active
active_db = registry.get_active_database()
DEFAULT_DATABASE_ID = active_db['db_id']
print(f"🗄️ Starting with database: {active_db['display_name']}")
print(f" (Config database not found, using active database)")
else:
# No config - use active database from registry
active_db = registry.get_active_database()
if not active_db:
print("\n❌ No active database found in registry!")
sys.exit(1)
DEFAULT_DATABASE_ID = active_db['db_id']
print(f"🗄️ Starting with database: {active_db['display_name']}")
print(f" (No config file found, using active database from registry)")
# Cache for loaded databases
database_cache = {}
def get_database(db_id: int):
"""Load database by ID (with caching)"""
if db_id not in database_cache:
db_info = registry.get_database(db_id)
if not db_info:
raise ValueError(f"Database ID {db_id} not found in registry")
db_path = f"db/{db_info['db_filename']}"
database_cache[db_id] = ReadathonDB(db_path)
return database_cache[db_id]
def current_db_id():
"""Database chosen in this browser session, else the one the app started with.
The session cookie is shared by every copy of the app on 127.0.0.1:5001 (e.g. a second
checkout), so it can hold an ID from another registry - ignore IDs this registry doesn't know.
"""
db_id = session.get('active_database_id')
if db_id is not None and registry.get_database(db_id):
return db_id
session.pop('active_database_id', None)
return DEFAULT_DATABASE_ID
def get_current_db():
"""Get currently active database"""
return get_database(current_db_id())
def get_current_reports():
"""Get report generator for current environment"""
return ReportGenerator(get_current_db())
def format_contest_range(sorted_dates):
"""Format the contest date range (e.g. 'Oct 10-Oct 15, 2026') from the uploaded daily log dates"""
if not sorted_dates:
return "No reading data yet"
start_date = datetime.strptime(sorted_dates[0], '%Y-%m-%d').strftime('%b %d')
end_date = datetime.strptime(sorted_dates[-1], '%Y-%m-%d').strftime('%b %d, %Y')
return f"{start_date}-{end_date}"
def get_setup_tables_timestamp():
"""
When the setup tables (Roster, Class_Info, Grade_Rules) were loaded.
They are loaded once when a database is created, so use the registry's created_timestamp.
"""
db_info = registry.get_database(current_db_id())
if not db_info or not db_info.get('created_timestamp'):
return 'Unknown'
try:
return datetime.fromisoformat(db_info['created_timestamp']).strftime('%m/%d/%Y %I:%M %p')
except ValueError:
return db_info['created_timestamp']
def get_max_contest_days(databases):
"""Number of 'Through Day N' options for database comparison: the longest contest among registered databases"""
return max([db['total_days'] or 0 for db in databases] + [10])
def get_validated_filters(db, dates):
"""
Read date/grade/team filters from the query string, keeping only values that exist in the data.
Several queries interpolate these filters into SQL, so anything unrecognized falls back to 'all'.
"""
grades = {row['grade_level'] for row in db.execute_query("SELECT DISTINCT grade_level FROM Roster")}
teams = {row['team_name'] for row in db.execute_query("SELECT DISTINCT team_name FROM Roster")}
date_filter = request.args.get('date', 'all')
grade_filter = request.args.get('grade', 'all')
team_filter = request.args.get('team', 'all')
return (date_filter if date_filter in dates else 'all',
grade_filter if grade_filter in grades else 'all',
team_filter if team_filter in teams else 'all')
def get_team_color_bonus_summary(db):
"""Most recent team color bonus event date and class count, e.g. '2026-10-13 (12 classes)'"""
result = db.execute_query("""
SELECT event_date, COUNT(*) as class_count
FROM Team_Color_Bonus
GROUP BY event_date
ORDER BY event_date DESC
LIMIT 1
""")
if result and result[0] and result[0]['event_date']:
return f"{result[0]['event_date']} ({result[0]['class_count']} classes)"
return 'No data'
def is_sample_db_info(db_info):
"""True if the registry entry is the sample database (by display name or filename)"""
return 'sample' in db_info['display_name'].lower() or 'sample' in db_info['db_filename'].lower()
def get_current_db_label():
"""Display name of the active database (e.g. '2026 Read-a-Thon'), used in logs and API responses"""
db_info = registry.get_database(current_db_id())
return db_info['display_name'] if db_info else 'unknown'
def is_production_db():
"""True if the active database holds real contest data (anything other than the sample database)"""
db_info = registry.get_database(current_db_id())
return bool(db_info) and not is_sample_db_info(db_info)
def get_editable_database():
"""Registry entry of the one database that accepts uploads and deletes (None if none is editable)"""
db_id = registry.get_editable_database_id()
return registry.get_database(db_id) if db_id else None
def current_db_is_editable():
"""True if the database being viewed is the editable one (all others are read-only)"""
return registry.get_editable_database_id() == current_db_id()
def drawing_winners_per_grade():
"""Daily prize drawing winners per grade (Admin -> Bulletin Settings)"""
return int(registry.get_settings()['drawing_winners_per_grade'])
def require_editable_db(route):
"""Refuse (403) any change to a read-only database, so switching databases can't send data to the wrong year"""
@wraps(route)
def guarded(*args, **kwargs):
if current_db_is_editable():
return route(*args, **kwargs)
editable = get_editable_database()
where = (f"Only '{editable['display_name']}' can be changed; switch to it, or"
if editable else "No database is editable;")
return jsonify({
'success': False,
'read_only': True,
'error': f"🔒 '{get_current_db_label()}' is read-only. {where} "
f"change the editable database in Admin → Database Registry."
}), 403
return guarded
@app.context_processor
def inject_database_info():
"""Inject database information into all templates"""
db_info = registry.get_database(current_db_id())
return {
'current_database': db_info,
'is_sample_database': bool(db_info) and is_sample_db_info(db_info),
'is_read_only_database': not current_db_is_editable(),
'editable_database': get_editable_database(),
'simple_view': VIEW_MODE == 'simple'
}
@app.route('/api/view_mode', methods=['POST'])
def set_view_mode():
"""Switch between simple view (daily job only) and full view; remembered in .readathon_config"""
global VIEW_MODE
mode = (request.json or {}).get('mode')
if mode not in VIEW_MODES:
return jsonify({'success': False, 'error': f'Unknown view: {mode}'}), 400
VIEW_MODE = mode
save_config(view_mode=mode)
return jsonify({'success': True, 'mode': mode})
def get_unified_items():
"""
Get unified list of all items (reports, tables, workflows).
Each item has: id, name, description, groups (list of tags)
Groups use hierarchical naming with periods: workflow.qa, requires.date
"""
items = []
# Main Reports (from /reports route)
items.extend([
{'id': 'q2', 'name': 'Q2: Daily Summary Report', 'description': 'Daily summary by class or team with participation rates', 'groups': ['report', 'daily', 'slides', 'workflow.qa', 'requires.date', 'requires.group_by']},
{'id': 'q3', 'name': 'Q3: Reader Cumulative Enhanced', 'description': 'Complete cumulative stats with class, teacher, team, and participation metrics', 'groups': ['report', 'cumulative', 'export', 'workflow.qa']},
{'id': 'q4', 'name': 'Q4/Slide 4: Prize Drawing', 'description': 'Random prize drawing - winners per grade (Admin setting, default 2) from students who met their goal', 'groups': ['report', 'prize', 'slides', 'workflow.qa', 'workflow.qd', 'workflow.qf', 'requires.date']},
{'id': 'q5', 'name': 'Q5: Student Cumulative Report', 'description': 'Student cumulative stats - Top Readers, Goal Getters, Top Fundraisers', 'groups': ['report', 'cumulative', 'prize', 'workflow.qa', 'workflow.qc']},
{'id': 'q6', 'name': 'Q6: Class Participation Winner', 'description': 'Class participation winner ranked by average daily participation rate', 'groups': ['report', 'cumulative', 'prize', 'workflow.qa', 'workflow.qc']},
{'id': 'q7', 'name': 'Q7: Complete Log', 'description': 'Complete denormalized log for export to Excel/CSV', 'groups': ['report', 'export', 'workflow.qa', 'requires.date']},
{'id': 'q8', 'name': 'Q8: Student Reading Details', 'description': 'Individual student reading details - minutes read and days met goal', 'groups': ['report', 'cumulative', 'export', 'workflow.qa']},
{'id': 'q9', 'name': 'Q9: Most Donations Per Grade', 'description': 'Student with highest donation amount in each grade', 'groups': ['report', 'cumulative', 'prize', 'workflow.qa', 'workflow.qf']},
{'id': 'q10', 'name': 'Q10: Most Minutes Per Grade', 'description': 'Student with most minutes read in each grade', 'groups': ['report', 'cumulative', 'prize', 'workflow.qa', 'workflow.qf']},
{'id': 'q11', 'name': 'Q11: Most Sponsors Per Grade', 'description': 'Student with most sponsors in each grade', 'groups': ['report', 'cumulative', 'prize', 'workflow.qa', 'workflow.qf']},
{'id': 'q12', 'name': 'Q12: Best Class Per Grade', 'description': 'Leading class in each grade by participation rate', 'groups': ['report', 'cumulative', 'prize', 'workflow.qa', 'workflow.qf']},
{'id': 'q13', 'name': 'Q13: Best Class in School', 'description': 'Overall best classroom by participation rate', 'groups': ['report', 'cumulative', 'prize', 'workflow.qa', 'workflow.qf']},
{'id': 'q14', 'name': 'Q14/Slide 3: Team Participation', 'description': 'Team participation winner by average participation rate', 'groups': ['report', 'cumulative', 'slides', 'workflow.qa', 'workflow.qd', 'workflow.qc', 'workflow.qf']},
{'id': 'q15', 'name': 'Q15: Goal Getters', 'description': 'Students who met their reading goal every day', 'groups': ['report', 'cumulative', 'prize', 'workflow.qa', 'workflow.qf']},
{'id': 'q16', 'name': 'Q16: Top Earner Per Team', 'description': 'Student with highest donation on each team', 'groups': ['report', 'cumulative', 'prize', 'workflow.qa', 'workflow.qf']},
{'id': 'q18', 'name': 'Q18/Slide 2: Lead Class by Grade', 'description': 'Leading class in each grade by average daily participation rate', 'groups': ['report', 'cumulative', 'slides', 'workflow.qa', 'workflow.qd', 'workflow.qc']},
{'id': 'q19', 'name': 'Q19/Slide 5: Team Minutes', 'description': 'Total minutes read by each team', 'groups': ['report', 'cumulative', 'slides', 'workflow.qa', 'workflow.qd', 'workflow.qc', 'workflow.qf']},
{'id': 'q20', 'name': 'Q20/Slide 6: Team Donations', 'description': 'Total donations raised by each team', 'groups': ['report', 'cumulative', 'slides', 'workflow.qa', 'workflow.qd', 'workflow.qc']},
{'id': 'q25', 'name': 'Q25: Fundraising by Day', 'description': 'Money raised and sponsors as of each contest day, with the amount added since the previous day (from saved cumulative uploads)', 'groups': ['report', 'cumulative', 'fundraising', 'workflow.qa']},
])
# Admin Reports (from /admin route)
items.extend([
{'id': 'q1', 'name': 'Q1: Table Row Counts', 'description': 'Database table row counts (utility report)', 'groups': ['report', 'utility', 'admin', 'workflow.qa']},
{'id': 'q21', 'name': 'Q21: Data Sync & Minutes Integrity Check', 'description': 'Verify students are synced between tables and daily minutes match cumulative', 'groups': ['report', 'integrity', 'admin', 'workflow.qa']},
{'id': 'q22', 'name': 'Q22: Student Name Sync Check', 'description': 'Verify students in Daily_Logs match Reader_Cumulative', 'groups': ['report', 'integrity', 'admin', 'workflow.qa']},
{'id': 'q23', 'name': 'Q23: Roster Integrity Check', 'description': 'Verify all students exist in Roster table', 'groups': ['report', 'integrity', 'admin', 'workflow.qa']},
{'id': 'q24', 'name': 'Q24: Database_Registry', 'description': 'Multi-year database registry with year, filename, active status, and summary statistics (from central registry database)', 'groups': ['report', 'utility', 'admin', 'workflow.qa', 'database']},
])
# Database Tables (from /tables route)
items.extend([
{'id': 'roster', 'name': 'Roster', 'description': 'All students with their class assignments, teachers, grades, and teams', 'groups': ['table', 'database']},
{'id': 'class_info', 'name': 'Class Info', 'description': 'Summary of each class including home room, teacher, grade, team, and total students', 'groups': ['table', 'database']},
{'id': 'grade_rules', 'name': 'Grade Rules', 'description': 'Minimum and maximum daily reading minutes by grade level', 'groups': ['table', 'database']},
{'id': 'daily_logs', 'name': 'Daily Logs', 'description': 'Daily reading minutes for each student by date (participation tracking)', 'groups': ['table', 'reading']},
{'id': 'reader_cumulative', 'name': 'Reader Cumulative', 'description': 'Cumulative fundraising stats (donations, sponsors) and total minutes for each student', 'groups': ['table', 'fundraising']},
{'id': 'reader_cumulative_history', 'name': 'Reader Cumulative History', 'description': 'Saved copy of the cumulative upload for each contest day (the latest upload for a day replaces it) - used for money raised as of a past day', 'groups': ['table', 'fundraising']},
{'id': 'drawing_winners', 'name': 'Drawing Winners', 'description': 'Daily prize drawing winners saved from the Daily Scoreboard (winners per grade per day set in Admin, default 2) - a saved winner is left out of later drawings', 'groups': ['table']},
{'id': 'team_color_bonus', 'name': 'Team Color Bonus', 'description': 'Special event bonus data: students wearing team colors earn extra participation points and minutes', 'groups': ['table']},
{'id': 'upload_history', 'name': 'Upload History', 'description': 'Complete history of all data uploads with timestamps, file details, and status', 'groups': ['table', 'database']},
{'id': 'complete_log', 'name': 'Q7: Complete Log (Query)', 'description': 'Complete denormalized log combining all data - perfect for export to Excel/CSV', 'groups': ['table', 'export']},
])
# Workflows (from /workflows route)
items.extend([
{'id': 'qd', 'name': 'QD: Daily Slide Update', 'description': 'Dynamically runs all reports tagged with workflow.qd - for daily update presentations', 'groups': ['workflow', 'featured']},
{'id': 'qc', 'name': 'QC: Cumulative Workflow', 'description': 'Dynamically runs all reports tagged with workflow.qc - comprehensive cumulative view', 'groups': ['workflow', 'featured']},
{'id': 'qf', 'name': 'QF: Final Prize Winners', 'description': 'Dynamically runs all reports tagged with workflow.qf - determines all winners and prizes', 'groups': ['workflow', 'featured']},
{'id': 'qa', 'name': 'QA: All Main Reports', 'description': 'Dynamically runs all reports tagged with workflow.qa - comprehensive system report', 'groups': ['workflow', 'featured']},
])
return items
# ========== Group Query Helper Functions ==========
def get_items_by_group(group_tag, items=None):
"""
Get all items that have a specific group tag.
Supports wildcards with startswith (e.g., 'workflow.*')
"""
if items is None:
items = get_unified_items()
if group_tag.endswith('.*'):
# Wildcard: workflow.* matches workflow.qa, workflow.qd, etc.
prefix = group_tag[:-2]
return [item for item in items
if any(g.startswith(prefix + '.') for g in item['groups'])]
else:
return [item for item in items if group_tag in item['groups']]
def get_items_by_groups(group_tags, match_all=False, items=None):
"""
Get items matching multiple group tags.
match_all=False: item has ANY of the tags (OR logic)
match_all=True: item has ALL of the tags (AND logic)
"""
if items is None:
items = get_unified_items()
if match_all:
return [item for item in items
if all(tag in item['groups'] for tag in group_tags)]
else:
return [item for item in items
if any(tag in item['groups'] for tag in group_tags)]
def is_report(item):
"""Check if item is a report"""
return 'report' in item['groups']
def is_workflow(item):
"""Check if item is a workflow"""
return 'workflow' in item['groups']
def is_table(item):
"""Check if item is a table"""
return 'table' in item['groups']
def requires_date(item):
"""Check if item requires date parameter"""
return 'requires.date' in item['groups']
def requires_group_by(item):
"""Check if item requires group_by parameter"""
return 'requires.group_by' in item['groups']
def get_workflow_reports(workflow_id):
"""Get all reports for a workflow by workflow ID"""
items = get_items_by_group(f'workflow.{workflow_id}')
return [item for item in items if is_report(item)]
@app.route('/')
@app.route('/school')
def school_tab():
"""School overview dashboard (landing page)"""
# Simple view opens on the Daily Scoreboard (the daily deliverable)
if request.path == '/' and VIEW_MODE == 'simple':
return redirect(url_for('daily_scoreboard'))
env = get_current_db_label()
db = get_current_db()
reports = get_current_reports()
# Get filter parameter (optional)
date_filter = request.args.get('date', 'all')
# Get all available dates
dates = db.get_all_dates()
# Build WHERE clause based on filter (cumulative through selected date)
date_where = ""
date_where_no_alias = "" # For subqueries without table alias
if date_filter != 'all' and date_filter in dates:
date_where = f"AND dl.log_date <= '{date_filter}'"
date_where_no_alias = f"AND log_date <= '{date_filter}'"
# Get total roster count
roster_query = "SELECT COUNT(*) as total FROM Roster"
roster_result = db.execute_query(roster_query)
total_roster = roster_result[0]['total'] if roster_result else 411
# === METRICS BANNER ===
metrics = {}
# Calculate full contest date range (always shown in dropdown, regardless of filter)
sorted_dates = sorted(dates) # Oldest to newest
total_days = len(sorted_dates) # Total number of days in contest
full_contest_range = format_contest_range(sorted_dates)
# Current day calculation - date-aware
if date_filter != 'all' and date_filter in dates:
# Find position of selected date (1-based)
metrics['current_day'] = sorted_dates.index(date_filter) + 1
metrics['campaign_date'] = date_filter # Store for subtitle display
else:
# Full contest - show total days
metrics['current_day'] = total_days
metrics['campaign_date'] = full_contest_range
metrics['total_days'] = total_days
metrics['total_roster'] = total_roster
# Fundraising metrics
fundraising_query = f"""
SELECT
COALESCE(SUM(rc.donation_amount), 0) as total_fundraising,
COUNT(DISTINCT CASE WHEN rc.donation_amount > 0 THEN rc.student_name END) as fundraising_students
FROM Reader_Cumulative rc
"""
fundraising_result = db.execute_query(fundraising_query)
if fundraising_result and fundraising_result[0]:
metrics['total_fundraising'] = fundraising_result[0]['total_fundraising'] or 0
metrics['fundraising_students'] = fundraising_result[0]['fundraising_students'] or 0
else:
metrics['total_fundraising'] = 0
metrics['fundraising_students'] = 0
metrics['fundraising_pct'] = (metrics['fundraising_students'] / total_roster * 100) if total_roster > 0 else 0
# Reading minutes (capped at 120 per day) + Team Color Bonus
reading_query = f"""
WITH TeamColorBonus AS (
SELECT COALESCE(SUM(bonus_minutes), 0) as total_bonus
FROM Team_Color_Bonus
)
SELECT
SUM(MIN(dl.minutes_read, 120)) as total_minutes_base,
(SELECT total_bonus FROM TeamColorBonus) as bonus_minutes,
COUNT(DISTINCT CASE WHEN dl.minutes_read > 0 THEN dl.student_name END) as participating_students
FROM Daily_Logs dl
WHERE 1=1 {date_where}
"""
reading_result = db.execute_query(reading_query)
if reading_result and reading_result[0]:
base_minutes = int(reading_result[0]['total_minutes_base'] or 0)
bonus_minutes = int(reading_result[0]['bonus_minutes'] or 0)
metrics['total_minutes'] = base_minutes + bonus_minutes
metrics['participating_students'] = reading_result[0]['participating_students'] or 0
else:
metrics['total_minutes'] = 0
metrics['participating_students'] = 0
metrics['total_hours'] = metrics['total_minutes'] // 60
metrics['participation_pct'] = (metrics['participating_students'] / total_roster * 100) if total_roster > 0 else 0
# Average Daily Participation (With Color) - school-wide
# Calculate average daily participation percentage across all students
school_participation_query = f"""
SELECT
AVG(daily_pct) as avg_participation
FROM (
SELECT
dl.log_date,
(COUNT(DISTINCT CASE WHEN dl.minutes_read > 0 THEN dl.student_name END) * 100.0 / {total_roster}) as daily_pct
FROM Daily_Logs dl
WHERE 1=1 {date_where}
GROUP BY dl.log_date
)
"""
school_participation_result = db.execute_query(school_participation_query)
base_school_participation = school_participation_result[0]['avg_participation'] or 0 if school_participation_result and school_participation_result[0] else 0
# Get total color bonus points across all classes
school_color_bonus_query = """
SELECT COALESCE(SUM(bonus_participation_points), 0) as total_bonus
FROM Team_Color_Bonus
"""
school_color_bonus_result = db.execute_query(school_color_bonus_query)
school_color_bonus = school_color_bonus_result[0]['total_bonus'] if school_color_bonus_result and school_color_bonus_result[0] else 0
# Calculate total days in date range for color bonus calculation
total_days_query = f"""
SELECT COUNT(DISTINCT dl.log_date) as total_days
FROM Daily_Logs dl
WHERE 1=1 {date_where}
"""
total_days_result = db.execute_query(total_days_query)
total_days = total_days_result[0]['total_days'] if total_days_result and total_days_result[0] else 1
# Apply color bonus: color points act as "free" participation days
metrics['avg_participation_with_color'] = base_school_participation + (school_color_bonus * 100.0 / (total_roster * total_days)) if total_roster > 0 and total_days > 0 else base_school_participation
# Goals met calculation
goals_met_query = f"""
SELECT
COUNT(DISTINCT dl.student_name) as goals_met_students
FROM Daily_Logs dl
JOIN Roster r ON dl.student_name = r.student_name
JOIN Grade_Rules gr ON r.grade_level = gr.grade_level
WHERE dl.minutes_read >= gr.min_daily_minutes {date_where}
"""
goals_met_result = db.execute_query(goals_met_query)
if goals_met_result and goals_met_result[0]:
metrics['goals_met_students'] = goals_met_result[0]['goals_met_students'] or 0
else:
metrics['goals_met_students'] = 0
metrics['goals_met_pct'] = (metrics['goals_met_students'] / total_roster * 100) if total_roster > 0 else 0
# === TEAM COMPETITION ===
# Get actual team names from database (sorted alphabetically for consistency)
team_names_query = "SELECT DISTINCT team_name FROM Roster ORDER BY team_name"
team_names_result = db.execute_query(team_names_query)
team_names = [row['team_name'] for row in team_names_result] if team_names_result else []
# Ensure we have exactly 2 teams
if len(team_names) != 2:
return jsonify({'error': f'Expected 2 teams, found {len(team_names)}'}), 500
team1_name = team_names[0] # First team alphabetically
team2_name = team_names[1] # Second team alphabetically
teams = {}
# Team 1 (cumulative through selected date)
team1_where = f"AND dl.log_date <= '{date_filter}'" if date_filter != 'all' and date_filter in dates else ""
# Separate query for fundraising to avoid row multiplication from Daily_Logs join
team1_fundraising_query = f"""
SELECT
COALESCE(SUM(rc.donation_amount), 0) as fundraising
FROM Roster r
LEFT JOIN Reader_Cumulative rc ON r.student_name = rc.student_name
WHERE LOWER(r.team_name) = LOWER('{team1_name}')
"""
team1_fundraising_result = db.execute_query(team1_fundraising_query)
team1_fundraising = team1_fundraising_result[0]['fundraising'] if team1_fundraising_result and team1_fundraising_result[0] else 0
# Query for minutes and other stats
team1_query = f"""
WITH TeamBonus AS (
SELECT SUM(tcb.bonus_minutes) as total_bonus
FROM Team_Color_Bonus tcb
INNER JOIN Class_Info ci ON tcb.class_name = ci.class_name
WHERE LOWER(ci.team_name) = LOWER('{team1_name}')
)
SELECT
COUNT(DISTINCT r.class_name) as classes,
COALESCE(SUM(MIN(dl.minutes_read, 120)), 0) as total_minutes_base,
COALESCE((SELECT total_bonus FROM TeamBonus), 0) as bonus_minutes,
COUNT(DISTINCT r.student_name) as students
FROM Roster r
LEFT JOIN Daily_Logs dl ON r.student_name = dl.student_name
WHERE LOWER(r.team_name) = LOWER('{team1_name}') {team1_where}
"""
team1_result = db.execute_query(team1_query)
if team1_result and team1_result[0]:
minutes_base = int(team1_result[0]['total_minutes_base'] or 0)
bonus_min = int(team1_result[0]['bonus_minutes'] or 0)
minutes_with_color = minutes_base + bonus_min
teams[team1_name] = {
'display_name': team1_name.upper(),
'classes': team1_result[0]['classes'] or 0,
'fundraising': team1_fundraising,
'minutes_base': minutes_base,
'bonus_minutes': bonus_min,
'minutes_with_color': minutes_with_color,
'hours_base': minutes_base // 60,
'hours_with_color': minutes_with_color // 60,
'students': team1_result[0]['students'] or 0
}
else:
teams[team1_name] = {'display_name': team1_name.upper(), 'classes': 0, 'fundraising': team1_fundraising, 'minutes_base': 0, 'bonus_minutes': 0, 'minutes_with_color': 0, 'hours_base': 0, 'hours_with_color': 0, 'students': 0}
# Team 2
# Separate query for fundraising to avoid row multiplication from Daily_Logs join
team2_fundraising_query = f"""
SELECT
COALESCE(SUM(rc.donation_amount), 0) as fundraising
FROM Roster r
LEFT JOIN Reader_Cumulative rc ON r.student_name = rc.student_name
WHERE LOWER(r.team_name) = LOWER('{team2_name}')
"""
team2_fundraising_result = db.execute_query(team2_fundraising_query)
team2_fundraising = team2_fundraising_result[0]['fundraising'] if team2_fundraising_result and team2_fundraising_result[0] else 0
# Query for minutes and other stats
team2_query = f"""
WITH TeamBonus AS (
SELECT SUM(tcb.bonus_minutes) as total_bonus
FROM Team_Color_Bonus tcb
INNER JOIN Class_Info ci ON tcb.class_name = ci.class_name
WHERE LOWER(ci.team_name) = LOWER('{team2_name}')
)
SELECT
COUNT(DISTINCT r.class_name) as classes,
COALESCE(SUM(MIN(dl.minutes_read, 120)), 0) as total_minutes_base,
COALESCE((SELECT total_bonus FROM TeamBonus), 0) as bonus_minutes,
COUNT(DISTINCT r.student_name) as students
FROM Roster r
LEFT JOIN Daily_Logs dl ON r.student_name = dl.student_name
WHERE LOWER(r.team_name) = LOWER('{team2_name}') {team1_where}
"""
team2_result = db.execute_query(team2_query)
if team2_result and team2_result[0]:
minutes_base = int(team2_result[0]['total_minutes_base'] or 0)
bonus_min = int(team2_result[0]['bonus_minutes'] or 0)
minutes_with_color = minutes_base + bonus_min
teams[team2_name] = {
'display_name': team2_name.upper(),
'classes': team2_result[0]['classes'] or 0,
'fundraising': team2_fundraising,
'minutes_base': minutes_base,
'bonus_minutes': bonus_min,
'minutes_with_color': minutes_with_color,
'hours_base': minutes_base // 60,
'hours_with_color': minutes_with_color // 60,
'students': team2_result[0]['students'] or 0
}
else:
teams[team2_name] = {'display_name': team2_name.upper(), 'classes': 0, 'fundraising': team2_fundraising, 'minutes_base': 0, 'bonus_minutes': 0, 'minutes_with_color': 0, 'hours_base': 0, 'hours_with_color': 0, 'students': 0}
# Team 1 - Average Daily Participation Percentage (with and without color bonus)
# Get total days and team size for calculations
total_days_query = f"""
SELECT COUNT(DISTINCT log_date) as total_days
FROM Daily_Logs
WHERE 1=1 {team1_where.replace('dl.', '')}
"""
total_days_result = db.execute_query(total_days_query)
total_days = total_days_result[0]['total_days'] if total_days_result and total_days_result[0] else 1
team1_size = teams[team1_name]['students']
team1_participation_query = f"""
SELECT
AVG(daily_pct) as avg_participation
FROM (
SELECT
dl.log_date,
(COUNT(DISTINCT CASE WHEN dl.minutes_read > 0 THEN dl.student_name END) * 100.0 /
(SELECT COUNT(*) FROM Roster WHERE LOWER(team_name) = LOWER('{team1_name}'))) as daily_pct
FROM Daily_Logs dl
JOIN Roster r ON dl.student_name = r.student_name
WHERE LOWER(r.team_name) = LOWER('{team1_name}') {team1_where}
GROUP BY dl.log_date
)
"""
team1_participation_result = db.execute_query(team1_participation_query)
teams[team1_name]['participation_pct'] = team1_participation_result[0]['avg_participation'] or 0 if team1_participation_result and team1_participation_result[0] else 0
# Calculate participation with color bonus for Team 1
team1_bonus_query = f"""
SELECT SUM(tcb.bonus_participation_points) as total_bonus
FROM Team_Color_Bonus tcb
INNER JOIN Class_Info ci ON tcb.class_name = ci.class_name
WHERE LOWER(ci.team_name) = LOWER('{team1_name}')
"""
team1_bonus_result = db.execute_query(team1_bonus_query)
team1_color_bonus = team1_bonus_result[0]['total_bonus'] if team1_bonus_result and team1_bonus_result[0] and team1_bonus_result[0]['total_bonus'] else 0
teams[team1_name]['color_bonus_points'] = team1_color_bonus
teams[team1_name]['participation_pct_with_color'] = teams[team1_name]['participation_pct'] + (team1_color_bonus * 100.0 / (team1_size * total_days)) if team1_size > 0 and total_days > 0 else teams[team1_name]['participation_pct']
# Team 2 - Average Daily Participation Percentage (with and without color bonus)
team2_size = teams[team2_name]['students']
team2_participation_query = f"""
SELECT
AVG(daily_pct) as avg_participation
FROM (
SELECT
dl.log_date,
(COUNT(DISTINCT CASE WHEN dl.minutes_read > 0 THEN dl.student_name END) * 100.0 /
(SELECT COUNT(*) FROM Roster WHERE LOWER(team_name) = LOWER('{team2_name}'))) as daily_pct
FROM Daily_Logs dl
JOIN Roster r ON dl.student_name = r.student_name
WHERE LOWER(r.team_name) = LOWER('{team2_name}') {team1_where}
GROUP BY dl.log_date
)
"""
team2_participation_result = db.execute_query(team2_participation_query)
teams[team2_name]['participation_pct'] = team2_participation_result[0]['avg_participation'] or 0 if team2_participation_result and team2_participation_result[0] else 0
# Calculate participation with color bonus for Team 2
team2_bonus_query = f"""
SELECT SUM(tcb.bonus_participation_points) as total_bonus
FROM Team_Color_Bonus tcb
INNER JOIN Class_Info ci ON tcb.class_name = ci.class_name
WHERE LOWER(ci.team_name) = LOWER('{team2_name}')
"""
team2_bonus_result = db.execute_query(team2_bonus_query)
team2_color_bonus = team2_bonus_result[0]['total_bonus'] if team2_bonus_result and team2_bonus_result[0] and team2_bonus_result[0]['total_bonus'] else 0
teams[team2_name]['color_bonus_points'] = team2_color_bonus
teams[team2_name]['participation_pct_with_color'] = teams[team2_name]['participation_pct'] + (team2_color_bonus * 100.0 / (team2_size * total_days)) if team2_size > 0 and total_days > 0 else teams[team2_name]['participation_pct']
# Determine leader and calculate gaps for each metric
# Note: Different teams may lead different metrics - gaps show which team is ahead in each category
if teams[team1_name]['fundraising'] > teams[team2_name]['fundraising']:
teams['leader'] = team1_name.upper()
teams['fundraising_gap'] = teams[team1_name]['fundraising'] - teams[team2_name]['fundraising']
teams['fundraising_leader'] = team1_name.upper()
else:
teams['leader'] = team2_name.upper()
teams['fundraising_gap'] = teams[team2_name]['fundraising'] - teams[team1_name]['fundraising']
teams['fundraising_leader'] = team2_name.upper()
# Reading gap - base version
if teams[team1_name]['hours_base'] > teams[team2_name]['hours_base']:
teams['reading_gap'] = teams[team1_name]['hours_base'] - teams[team2_name]['hours_base']
teams['reading_leader'] = team1_name.upper()
else:
teams['reading_gap'] = teams[team2_name]['hours_base'] - teams[team1_name]['hours_base']
teams['reading_leader'] = team2_name.upper()
# Reading gap - with color version
if teams[team1_name]['hours_with_color'] > teams[team2_name]['hours_with_color']:
teams['reading_gap_with_color'] = teams[team1_name]['hours_with_color'] - teams[team2_name]['hours_with_color']
teams['reading_leader_with_color'] = team1_name.upper()
else:
teams['reading_gap_with_color'] = teams[team2_name]['hours_with_color'] - teams[team1_name]['hours_with_color']
teams['reading_leader_with_color'] = team2_name.upper()
# Participation gap - base version
if teams[team1_name]['participation_pct'] > teams[team2_name]['participation_pct']:
teams['participation_gap'] = teams[team1_name]['participation_pct'] - teams[team2_name]['participation_pct']
teams['participation_leader'] = team1_name.upper()
else:
teams['participation_gap'] = teams[team2_name]['participation_pct'] - teams[team1_name]['participation_pct']
teams['participation_leader'] = team2_name.upper()
# Participation gap - with color version
if teams[team1_name]['participation_pct_with_color'] > teams[team2_name]['participation_pct_with_color']:
teams['participation_gap_with_color'] = teams[team1_name]['participation_pct_with_color'] - teams[team2_name]['participation_pct_with_color']
teams['participation_leader_with_color'] = team1_name.upper()
else:
teams['participation_gap_with_color'] = teams[team2_name]['participation_pct_with_color'] - teams[team1_name]['participation_pct_with_color']
teams['participation_leader_with_color'] = team2_name.upper()
# Goal Met calculations per team (students who met goal at least once)
# Team 1 goals met
team1_goals_met_query = f"""
SELECT COUNT(DISTINCT dl.student_name) as goals_met_students
FROM Daily_Logs dl
JOIN Roster r ON dl.student_name = r.student_name
JOIN Grade_Rules gr ON r.grade_level = gr.grade_level
WHERE LOWER(r.team_name) = LOWER('{team1_name}')
AND dl.minutes_read >= gr.min_daily_minutes {date_where}
"""
team1_goals_met_result = db.execute_query(team1_goals_met_query)
teams[team1_name]['goals_met_students'] = team1_goals_met_result[0]['goals_met_students'] or 0 if team1_goals_met_result and team1_goals_met_result[0] else 0
teams[team1_name]['goals_met_pct'] = (teams[team1_name]['goals_met_students'] / teams[team1_name]['students'] * 100) if teams[team1_name]['students'] > 0 else 0
# Team 2 goals met
team2_goals_met_query = f"""
SELECT COUNT(DISTINCT dl.student_name) as goals_met_students
FROM Daily_Logs dl
JOIN Roster r ON dl.student_name = r.student_name
JOIN Grade_Rules gr ON r.grade_level = gr.grade_level
WHERE LOWER(r.team_name) = LOWER('{team2_name}')
AND dl.minutes_read >= gr.min_daily_minutes {date_where}
"""
team2_goals_met_result = db.execute_query(team2_goals_met_query)
teams[team2_name]['goals_met_students'] = team2_goals_met_result[0]['goals_met_students'] or 0 if team2_goals_met_result and team2_goals_met_result[0] else 0
teams[team2_name]['goals_met_pct'] = (teams[team2_name]['goals_met_students'] / teams[team2_name]['students'] * 100) if teams[team2_name]['students'] > 0 else 0
# Goals met leader
if teams[team1_name]['goals_met_pct'] > teams[team2_name]['goals_met_pct']:
teams['goals_met_gap'] = teams[team1_name]['goals_met_pct'] - teams[team2_name]['goals_met_pct']
teams['goals_met_leader'] = team1_name.upper()
else:
teams['goals_met_gap'] = teams[team2_name]['goals_met_pct'] - teams[team1_name]['goals_met_pct']
teams['goals_met_leader'] = team2_name.upper()
# Sponsors calculations per team (total sponsors count + students with sponsors)
# Team 1 sponsors
team1_sponsors_query = f"""
SELECT
COALESCE(SUM(rc.sponsors), 0) as total_sponsors,
COUNT(DISTINCT CASE WHEN rc.sponsors > 0 THEN rc.student_name END) as students_with_sponsors
FROM Roster r
LEFT JOIN Reader_Cumulative rc ON r.student_name = rc.student_name
WHERE LOWER(r.team_name) = LOWER('{team1_name}')
"""
team1_sponsors_result = db.execute_query(team1_sponsors_query)
teams[team1_name]['total_sponsors'] = int(team1_sponsors_result[0]['total_sponsors'] or 0) if team1_sponsors_result and team1_sponsors_result[0] else 0
teams[team1_name]['sponsors_students'] = team1_sponsors_result[0]['students_with_sponsors'] or 0 if team1_sponsors_result and team1_sponsors_result[0] else 0
teams[team1_name]['sponsors_pct'] = (teams[team1_name]['sponsors_students'] / teams[team1_name]['students'] * 100) if teams[team1_name]['students'] > 0 else 0
# Team 2 sponsors
team2_sponsors_query = f"""
SELECT
COALESCE(SUM(rc.sponsors), 0) as total_sponsors,
COUNT(DISTINCT CASE WHEN rc.sponsors > 0 THEN rc.student_name END) as students_with_sponsors
FROM Roster r
LEFT JOIN Reader_Cumulative rc ON r.student_name = rc.student_name
WHERE LOWER(r.team_name) = LOWER('{team2_name}')
"""
team2_sponsors_result = db.execute_query(team2_sponsors_query)
teams[team2_name]['total_sponsors'] = int(team2_sponsors_result[0]['total_sponsors'] or 0) if team2_sponsors_result and team2_sponsors_result[0] else 0
teams[team2_name]['sponsors_students'] = team2_sponsors_result[0]['students_with_sponsors'] or 0 if team2_sponsors_result and team2_sponsors_result[0] else 0
teams[team2_name]['sponsors_pct'] = (teams[team2_name]['sponsors_students'] / teams[team2_name]['students'] * 100) if teams[team2_name]['students'] > 0 else 0
# Sponsors leader (team with more total sponsors)
if teams[team1_name]['total_sponsors'] > teams[team2_name]['total_sponsors']:
teams['sponsors_gap'] = teams[team1_name]['total_sponsors'] - teams[team2_name]['total_sponsors']
teams['sponsors_leader'] = team1_name.upper()
else:
teams['sponsors_gap'] = teams[team2_name]['total_sponsors'] - teams[team1_name]['total_sponsors']
teams['sponsors_leader'] = team2_name.upper()
# School-wide sponsors total (for banner display)
metrics['total_sponsors'] = teams[team1_name]['total_sponsors'] + teams[team2_name]['total_sponsors']
metrics['sponsors_students'] = teams[team1_name]['sponsors_students'] + teams[team2_name]['sponsors_students']
metrics['sponsors_pct'] = (metrics['sponsors_students'] / total_roster * 100) if total_roster > 0 else 0
# === TOP PERFORMERS ===
performers = {}
# Fundraising leader(s)
fundraising_leader_query = """
SELECT
rc.student_name,
r.grade_level,
rc.donation_amount
FROM Reader_Cumulative rc
JOIN Roster r ON rc.student_name = r.student_name
WHERE rc.donation_amount = (SELECT MAX(donation_amount) FROM Reader_Cumulative)
ORDER BY rc.student_name
"""
fundraising_leaders = db.execute_query(fundraising_leader_query)
if fundraising_leaders:
if len(fundraising_leaders) <= 3:
names = ", ".join([leader['student_name'] for leader in fundraising_leaders])
else:
names = ", ".join([leader['student_name'] for leader in fundraising_leaders[:3]]) + f" and {len(fundraising_leaders) - 3} others"
grades = set([leader['grade_level'] for leader in fundraising_leaders])
grade_text = f"Grade {fundraising_leaders[0]['grade_level']}" if len(grades) == 1 else "Various"
performers['fundraising'] = {
'names': names,
'grade': grade_text,
'amount': fundraising_leaders[0]['donation_amount'],
'tie_count': len(fundraising_leaders)
}
else:
performers['fundraising'] = {'names': 'N/A', 'grade': '', 'amount': 0, 'tie_count': 1}
# Reading leader(s)
reading_leader_query = f"""
SELECT
dl.student_name,
r.grade_level,
SUM(MIN(dl.minutes_read, 120)) as total_minutes
FROM Daily_Logs dl
JOIN Roster r ON dl.student_name = r.student_name
WHERE 1=1 {date_where}
GROUP BY dl.student_name, r.grade_level
HAVING total_minutes = (
SELECT MAX(total_minutes) FROM (
SELECT SUM(MIN(minutes_read, 120)) as total_minutes
FROM Daily_Logs
WHERE 1=1 {date_where_no_alias}
GROUP BY student_name
)
)
ORDER BY dl.student_name
"""
reading_leaders = db.execute_query(reading_leader_query)
if reading_leaders:
if len(reading_leaders) <= 3:
names = ", ".join([leader['student_name'] for leader in reading_leaders])
else:
names = ", ".join([leader['student_name'] for leader in reading_leaders[:3]]) + f" and {len(reading_leaders) - 3} others"
grades = set([leader['grade_level'] for leader in reading_leaders])
grade_text = f"Grade {reading_leaders[0]['grade_level']}" if len(grades) == 1 else "Various"
performers['reading'] = {
'names': names,
'grade': grade_text,
'minutes': int(reading_leaders[0]['total_minutes']),
'tie_count': len(reading_leaders)
}
else:
performers['reading'] = {'names': 'N/A', 'grade': '', 'minutes': 0, 'tie_count': 1}
# Top class by fundraising
class_fundraising_query = """
SELECT
r.teacher_name,
r.grade_level,
SUM(rc.donation_amount) as total_fundraising
FROM Roster r
LEFT JOIN Reader_Cumulative rc ON r.student_name = rc.student_name
GROUP BY r.teacher_name, r.grade_level
ORDER BY total_fundraising DESC
LIMIT 1
"""
class_fundraising_result = db.execute_query(class_fundraising_query)
if class_fundraising_result and class_fundraising_result[0]:
performers['class_fundraising'] = {
'teacher': class_fundraising_result[0]['teacher_name'],
'grade': class_fundraising_result[0]['grade_level'],
'amount': class_fundraising_result[0]['total_fundraising'] or 0
}
else:
performers['class_fundraising'] = {'teacher': 'N/A', 'grade': '', 'amount': 0}
# Top class by reading (cumulative through selected date, with color bonus)
class_reading_where = f"WHERE dl.log_date <= '{date_filter}'" if date_filter != 'all' and date_filter in dates else ""
class_reading_query = f"""
WITH ClassBonus AS (
SELECT
class_name,
COALESCE(SUM(bonus_minutes), 0) as bonus
FROM Team_Color_Bonus
GROUP BY class_name
)
SELECT
r.teacher_name,
r.grade_level,
COALESCE(SUM(MIN(dl.minutes_read, 120)), 0) as base_minutes,
COALESCE(MAX(cb.bonus), 0) as bonus_minutes,
(COALESCE(SUM(MIN(dl.minutes_read, 120)), 0) + COALESCE(MAX(cb.bonus), 0)) as total_minutes
FROM Roster r
LEFT JOIN Daily_Logs dl ON r.student_name = dl.student_name
LEFT JOIN ClassBonus cb ON r.class_name = cb.class_name
{class_reading_where}
GROUP BY r.teacher_name, r.grade_level
ORDER BY total_minutes DESC
LIMIT 1
"""
class_reading_result = db.execute_query(class_reading_query)
if class_reading_result and class_reading_result[0]:
performers['class_reading'] = {
'teacher': class_reading_result[0]['teacher_name'],
'grade': class_reading_result[0]['grade_level'],
'minutes': int(class_reading_result[0]['total_minutes'] or 0)
}
else:
performers['class_reading'] = {'teacher': 'N/A', 'grade': '', 'minutes': 0}