Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
4937 lines (4254 loc) · 232 KB
/
Copy pathdatabase.py
File metadata and controls
4937 lines (4254 loc) · 232 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 Database Module
Handles SQLite database creation, initialization, and all data operations
"""
import os
import sqlite3
import csv
import io
from datetime import datetime
from typing import List, Dict, Any, Optional, Tuple
import random
from collections import Counter, defaultdict
from report_metadata import (
COLUMN_METADATA,
get_report_terms,
generate_q21_analysis,
generate_q22_analysis,
generate_q23_analysis
)
from queries import *
from name_matching import NameMatcher, name_key, split_unmatched_label, teacher_key, unmatched_label
DEFAULT_DRAWING_WINNERS_PER_GRADE = 2 # daily prize drawing winners per grade (Admin -> Bulletin Settings)
# Upload CSV column names (lowercase), shared by the column check and the row readers so a file that passes
# the check is also read
NAME_COLUMNS = ('reader name', 'readername', 'student name', 'student_name', 'name')
TEACHER_COLUMNS = ('teacher', 'teacher name', 'teacher_name')
MINUTES_COLUMNS = ('minutes', 'minutes read', 'minutes_read', 'cumulative minutes', 'cumulative_minutes')
RAISED_COLUMNS = ('raised', 'donation amount', 'donation_amount', 'donations')
SPONSORS_COLUMNS = ('sponsors', 'sponsor count', 'sponsor_count')
class DatabaseRegistry:
"""
Central registry for managing multiple read-a-thon databases.
The registry database (readathon_registry.db) tracks all available databases,
which one is active, and maintains summary statistics for each.
"""
def __init__(self, registry_path: str = "db/readathon_registry.db"):
"""Initialize registry database connection"""
self.registry_path = registry_path
self.conn = sqlite3.connect(registry_path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self._ensure_schema()
def _ensure_schema(self):
"""
Create the registry table if missing and seed it with the sample database.
Real contest databases (and the registry itself) are gitignored for privacy,
so a fresh checkout has no registry. Seeding the sample database lets the app
start so a new year's database can be created from the Admin page.
"""
cursor = self.conn.cursor()
cursor.execute(CREATE_TABLE_DATABASE_REGISTRY)
cursor.execute(CREATE_TABLE_APP_SETTINGS)
self.conn.commit()
cursor.execute('SELECT COUNT(*) FROM Database_Registry')
if cursor.fetchone()[0] > 0:
return
sample_path = os.path.join(os.path.dirname(self.registry_path), SAMPLE_DB_FILENAME)
if os.path.exists(sample_path):
db_id = self.register_database(SAMPLE_DB_FILENAME, 'Sample', None,
'Sample database for testing')
self.recalculate_stats_from_file(db_id)
self.set_active_database(db_id)
def register_year_databases(self) -> List[str]:
"""
Register any db/readathon_<YEAR>.db file that is not in the registry yet.
Year databases are copied between computers outside of git, so copying the file
into db/ is enough - it appears in the database dropdown on the next start.
Returns:
Filenames that were newly registered
"""
registry_dir = os.path.dirname(self.registry_path) or '.'
registered = {db['db_filename'] for db in self.list_databases()}
added = []
for filename in sorted(os.listdir(registry_dir)):
match = YEAR_DB_FILENAME_PATTERN.fullmatch(filename)
if not match or filename in registered:
continue
year = int(match.group(1))
db_id = self.register_database(filename, f'{year} Read-a-Thon', year,
f'{year} read-a-thon database')
self.recalculate_stats_from_file(db_id)
added.append(filename)
return added
@staticmethod
def read_database_stats(db_path: str) -> Dict[str, Any]:
"""Summary statistics for the registry, read without modifying the contest database"""
try:
conn = sqlite3.connect(f'file:{db_path}?mode=ro', uri=True)
cursor = conn.cursor()
student_count = cursor.execute('SELECT COUNT(*) FROM Roster').fetchone()[0]
total_days = cursor.execute('SELECT COUNT(DISTINCT log_date) FROM Daily_Logs').fetchone()[0]
total_donations = cursor.execute(
'SELECT COALESCE(SUM(donation_amount), 0) FROM Reader_Cumulative').fetchone()[0]
conn.close()
except sqlite3.Error:
return {'student_count': 0, 'total_days': 0, 'total_donations': 0.0}
return {'student_count': student_count, 'total_days': total_days, 'total_donations': total_donations}
def close(self):
"""Close registry database connection"""
if self.conn:
self.conn.close()
# App-wide settings (Admin -> Actions -> Bulletin Settings). Defaults apply until saved.
SETTING_DEFAULTS = {'school_name': '', 'contest_days': '10',
'drawing_winners_per_grade': str(DEFAULT_DRAWING_WINNERS_PER_GRADE),
# Upload page download links; {date} = the chosen day (YYYY-MM-DD)
'minutes_report_url': 'https://www.read-a-thon.com/admin/date_report/?Date={date}&Type=Minutes',
'readers_report_url': 'https://www.read-a-thon.com/admin/reader_reports/'}
def get_settings(self) -> Dict[str, str]:
"""All app settings, with defaults filled in"""
settings = dict(self.SETTING_DEFAULTS)
for row in self.conn.execute(SELECT_APP_SETTINGS).fetchall():
if row['setting_key'] in self.SETTING_DEFAULTS:
settings[row['setting_key']] = row['setting_value']
return settings
def count_saved_settings(self) -> int:
"""Number of settings saved in App_Settings (defaults aren't stored)"""
return self.conn.execute(SELECT_COUNT_APP_SETTINGS).fetchone()[0]
def set_setting(self, key: str, value: str) -> None:
"""Save one app setting (key must be one of SETTING_DEFAULTS)"""
if key not in self.SETTING_DEFAULTS:
raise ValueError(f'Unknown setting: {key}')
self.conn.execute(UPSERT_APP_SETTING, (key, value, datetime.now().isoformat()))
self.conn.commit()
# The one database that accepts uploads/deletes; independent of the database being viewed
EDITABLE_DATABASE_KEY = 'editable_database_id'
def get_editable_database_id(self) -> Optional[int]:
"""
ID of the editable database (every other database is read-only).
Until one is chosen, the newest year database (readathon_YYYY.db) is picked and saved.
None if the saved choice is no longer registered, or there is no year database yet.
"""
if self.conn.execute('SELECT 1 FROM App_Settings WHERE setting_key = ?', (self.EDITABLE_DATABASE_KEY,)).fetchone():
db_id = self._stored_editable_database_id()
return db_id if db_id and self.get_database(db_id) else None
year_dbs = [db for db in self.list_databases() if YEAR_DB_FILENAME_PATTERN.fullmatch(db['db_filename'])]
if not year_dbs:
return None
newest = max(year_dbs, key=lambda db: db['year'] or 0)
self._save_editable_database_id(newest['db_id'])
return newest['db_id']
def set_editable_database(self, db_id: int) -> Dict[str, Any]:
"""Make one database editable (all others become read-only)"""
db = self.get_database(db_id)
if not db:
return {'success': False, 'error': f'Database ID {db_id} not found'}
self._save_editable_database_id(db_id)
return {'success': True, 'message': f'Editable database: {db["display_name"]}', 'database': db}
def _save_editable_database_id(self, db_id: int) -> None:
self.conn.execute(UPSERT_APP_SETTING, (self.EDITABLE_DATABASE_KEY, str(db_id), datetime.now().isoformat()))
self.conn.commit()
def _stored_editable_database_id(self) -> Optional[int]:
row = self.conn.execute('SELECT setting_value FROM App_Settings WHERE setting_key = ?',
(self.EDITABLE_DATABASE_KEY,)).fetchone()
return int(row['setting_value']) if row and row['setting_value'] else None
def _to_dict(self, row) -> Dict[str, Any]:
"""Registry row as a dict, plus is_editable"""
db = {key: row[key] for key in row.keys()}
db['is_editable'] = db['db_id'] == self._stored_editable_database_id()
return db
def get_database_by_year(self, year: int) -> Optional[Dict[str, Any]]:
"""Registered database for an event year (None if there isn't one)"""
return next((db for db in self.list_databases() if db['year'] == year), None)
def list_databases(self) -> List[Dict[str, Any]]:
"""
Get all registered databases.
Returns:
List of database dictionaries with all fields
"""
cursor = self.conn.cursor()
cursor.execute('''
SELECT db_id, db_filename, display_name, year, description,
is_active, created_timestamp, student_count,
total_days, total_donations
FROM Database_Registry
ORDER BY year DESC, display_name ASC
''')
results = []
for row in cursor.fetchall():
results.append(self._to_dict(row))
return results
def get_database(self, db_id: int) -> Optional[Dict[str, Any]]:
"""
Get a single database by ID.
Args:
db_id: Database ID
Returns:
Database dictionary or None if not found
"""
cursor = self.conn.cursor()
cursor.execute('''
SELECT db_id, db_filename, display_name, year, description,
is_active, created_timestamp, student_count,
total_days, total_donations
FROM Database_Registry
WHERE db_id = ?
''', (db_id,))
row = cursor.fetchone()
if not row:
return None
return self._to_dict(row)
def get_database_by_name(self, name: str) -> Optional[Dict[str, Any]]:
"""
Get database by display_name or filename (case-insensitive).
Args:
name: Display name, filename, or special alias ("sample")
Returns:
Database dictionary or None if not found
"""
cursor = self.conn.cursor()
# Try exact match on display_name or filename (case-insensitive)
cursor.execute('''
SELECT db_id, db_filename, display_name, year, description,
is_active, created_timestamp, student_count,
total_days, total_donations
FROM Database_Registry
WHERE LOWER(display_name) = LOWER(?)
OR db_filename = ?
''', (name, name))
row = cursor.fetchone()
if row:
return self._to_dict(row)
# Special case: "sample" alias matches any database with "sample" in display_name
if name.lower() == 'sample':
cursor.execute('''
SELECT db_id, db_filename, display_name, year, description,
is_active, created_timestamp, student_count,
total_days, total_donations
FROM Database_Registry
WHERE LOWER(display_name) LIKE '%sample%'
LIMIT 1
''')
row = cursor.fetchone()
if row:
return self._to_dict(row)
return None
def get_active_database(self) -> Optional[Dict[str, Any]]:
"""
Get the currently active database.
Returns:
Active database dictionary or None if no active database
"""
cursor = self.conn.cursor()
cursor.execute('''
SELECT db_id, db_filename, display_name, year, description,
is_active, created_timestamp, student_count,
total_days, total_donations
FROM Database_Registry
WHERE is_active = 1
LIMIT 1
''')
row = cursor.fetchone()
if not row:
return None
return self._to_dict(row)
def set_active_database(self, db_id: int) -> Dict[str, Any]:
"""
Set a database as active (deactivates all others).
Args:
db_id: Database ID to activate
Returns:
Result dictionary with success status
"""
cursor = self.conn.cursor()
# Check if database exists
db = self.get_database(db_id)
if not db:
return {'success': False, 'error': f'Database ID {db_id} not found'}
# Deactivate all databases
cursor.execute('UPDATE Database_Registry SET is_active = 0')
# Activate the specified database
cursor.execute('UPDATE Database_Registry SET is_active = 1 WHERE db_id = ?', (db_id,))
self.conn.commit()
return {
'success': True,
'message': f'Activated database: {db["display_name"]}',
'database': db
}
def register_database(self, filename: str, name: str, year: Optional[int],
description: str = '') -> int:
"""
Register a new database in the registry.
Args:
filename: Database filename (e.g., "readathon_2026.db")
name: Display name (e.g., "2026 Read-a-Thon")
year: School year or None for non-year databases
description: Optional description
Returns:
New database ID
"""
cursor = self.conn.cursor()
cursor.execute('''
INSERT INTO Database_Registry
(db_filename, display_name, year, description, is_active, created_timestamp,
student_count, total_days, total_donations)
VALUES (?, ?, ?, ?, 0, ?, 0, 0, 0.0)
''', (filename, name, year, description, datetime.now().isoformat()))
self.conn.commit()
return cursor.lastrowid
def update_stats(self, db_id: int, student_count: int = None,
total_days: int = None, total_donations: float = None) -> Dict[str, Any]:
"""
Update statistics for a database.
Args:
db_id: Database ID
student_count: Number of students (optional)
total_days: Number of contest days (optional)
total_donations: Total fundraising amount (optional)
Returns:
Result dictionary with success status
"""
cursor = self.conn.cursor()
# Check if database exists
db = self.get_database(db_id)
if not db:
return {'success': False, 'error': f'Database ID {db_id} not found'}
# Build update query dynamically based on provided values
updates = []
values = []
if student_count is not None:
updates.append('student_count = ?')
values.append(student_count)
if total_days is not None:
updates.append('total_days = ?')
values.append(total_days)
if total_donations is not None:
updates.append('total_donations = ?')
values.append(total_donations)
if not updates:
return {'success': True, 'message': 'No updates provided'}
values.append(db_id)
query = f"UPDATE Database_Registry SET {', '.join(updates)} WHERE db_id = ?"
cursor.execute(query, values)
self.conn.commit()
return {'success': True, 'message': 'Statistics updated'}
def recalculate_stats_from_file(self, db_id: int) -> Dict[str, Any]:
"""
Recalculate statistics by querying the actual contest database file.
This opens the contest database, queries Roster, Daily_Logs, and Reader_Cumulative,
then updates the registry with the calculated values.
Args:
db_id: Database ID
Returns:
Result dictionary with success status and calculated values
"""
# Get database info from registry
db = self.get_database(db_id)
if not db:
return {'success': False, 'error': f'Database ID {db_id} not found'}
db_path = os.path.join(os.path.dirname(self.registry_path), db['db_filename'])
try:
stats = self.read_database_stats(db_path)
student_count = stats['student_count']
total_days = stats['total_days']
total_donations = stats['total_donations']
# Update registry with calculated values
result = self.update_stats(db_id, student_count, total_days, total_donations)
if result['success']:
return {
'success': True,
'message': f'Statistics recalculated for {db["display_name"]}',
'student_count': student_count,
'total_days': total_days,
'total_donations': total_donations,
'display_name': db['display_name']
}
else:
return result
except Exception as e:
return {
'success': False,
'error': f'Failed to recalculate stats: {str(e)}'
}
def delete_database(self, db_id: int) -> Dict[str, Any]:
"""
Delete a database registration (does NOT delete the actual .db file).
Args:
db_id: Database ID
Returns:
Result dictionary with success status
"""
cursor = self.conn.cursor()
# Check if database exists
db = self.get_database(db_id)
if not db:
return {'success': False, 'error': f'Database ID {db_id} not found'}
# Don't allow deleting the active database
if db['is_active']:
return {'success': False, 'error': 'Cannot delete active database. Activate another database first.'}
if db['is_editable']:
return {'success': False, 'error': 'Cannot delete the editable database. Make another database editable first.'}
cursor.execute('DELETE FROM Database_Registry WHERE db_id = ?', (db_id,))
self.conn.commit()
return {
'success': True,
'message': f'Unregistered database: {db["display_name"]} (file not deleted)'
}
class ReadathonDB:
"""Main database class for Read-a-Thon system"""
def __init__(self, db_path: str = "readathon.db"):
self.db_path = db_path
self.conn = None
self.initialize_database()
def get_connection(self):
"""Get database connection"""
if self.conn is None:
self.conn = sqlite3.connect(self.db_path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
return self.conn
def close(self):
"""Close database connection"""
if self.conn:
self.conn.close()
self.conn = None
def initialize_database(self):
"""Create all tables if they don't exist"""
conn = self.get_connection()
cursor = conn.cursor()
# Roster table
cursor.execute(CREATE_TABLE_ROSTER)
# Class_Info table
cursor.execute(CREATE_TABLE_CLASS_INFO)
# Grade_Rules table
cursor.execute(CREATE_TABLE_GRADE_RULES)
# Daily_Logs table (simplified - minutes only)
cursor.execute(CREATE_TABLE_DAILY_LOGS)
# Reader_Cumulative table - cumulative stats per student
cursor.execute(CREATE_TABLE_READER_CUMULATIVE)
# Upload_History table - tracks all uploads with audit trail
cursor.execute(CREATE_TABLE_UPLOAD_HISTORY)
# Add audit columns to existing Upload_History table if they don't exist
cursor.execute(SELECT_TABLE_INFO)
columns = [row[1] for row in cursor.fetchall()]
if 'action_taken' not in columns:
cursor.execute(ALTER_ADD_ACTION_TAKEN)
if 'records_replaced' not in columns:
cursor.execute(ALTER_ADD_RECORDS_REPLACED)
if 'audit_details' not in columns:
cursor.execute(ALTER_ADD_AUDIT_DETAILS)
if 'file_type' not in columns:
cursor.execute(ALTER_ADD_FILE_TYPE)
# Database_Metadata table - tracks year databases for multi-year support
cursor.execute(CREATE_TABLE_DATABASE_METADATA)
# Team_Color_Bonus table - tracks special team color day bonuses
cursor.execute(CREATE_TABLE_TEAM_COLOR_BONUS)
# Reader_Cumulative_History - one copy of the cumulative upload per contest day.
# When first added to an existing database, the current Reader_Cumulative becomes
# the snapshot for the last contest date (gives older years their final totals).
history_is_new = cursor.execute(SELECT_TABLE_EXISTS, ('Reader_Cumulative_History',)).fetchone() is None
cursor.execute(CREATE_TABLE_READER_CUMULATIVE_HISTORY)
if history_is_new:
last_date = cursor.execute(SELECT_LATEST_LOG_DATE).fetchone()[0]
if last_date:
cursor.execute(INSERT_READER_CUMULATIVE_SNAPSHOT, (last_date,))
# Drawing_Winners - daily drawing winners saved from the Daily Scoreboard.
# Older tables allowed one winner per grade: rebuild them with the (date, grade, student) key.
cursor.execute(CREATE_TABLE_DRAWING_WINNERS)
if 'student_name' not in {row[0] for row in cursor.execute(SELECT_DRAWING_WINNERS_PK_COLUMNS)}:
for statement in REBUILD_DRAWING_WINNERS_KEY:
cursor.execute(statement)
# Name_Alias - saved corrections for reader names typed by parents on read-a-thon.com
cursor.execute(CREATE_TABLE_NAME_ALIAS)
conn.commit()
def load_roster_data(self, csv_data: str) -> int:
"""Load roster data from CSV string"""
conn = self.get_connection()
cursor = conn.cursor()
# Clear existing data
cursor.execute(DELETE_ALL_ROSTER)
reader = csv.DictReader(io.StringIO(csv_data))
count = 0
for row in reader:
cursor.execute(INSERT_ROSTER,
(row['student_name'], row['class_name'], row['home_room'],
row['teacher_name'], row['grade_level'], row['team_name']))
count += 1
conn.commit()
return count
def load_class_info_data(self, csv_data: str) -> int:
"""Load class info data from CSV string"""
conn = self.get_connection()
cursor = conn.cursor()
# Clear existing data
cursor.execute(DELETE_ALL_CLASS_INFO)
reader = csv.DictReader(io.StringIO(csv_data))
count = 0
for row in reader:
cursor.execute(INSERT_CLASS_INFO,
(row['class_name'], row['home_room'], row['teacher_name'],
row['grade_level'], row['team_name'], int(row['total_students'])))
count += 1
conn.commit()
return count
def load_grade_rules_data(self, csv_data: str) -> int:
"""Load grade rules data from CSV string"""
conn = self.get_connection()
cursor = conn.cursor()
# Clear existing data
cursor.execute(DELETE_ALL_GRADE_RULES)
reader = csv.DictReader(io.StringIO(csv_data))
count = 0
for row in reader:
cursor.execute(INSERT_GRADE_RULES,
(row['grade_level'], int(row['min_daily_minutes']),
int(row['max_daily_minutes_credit'])))
count += 1
conn.commit()
return count
def load_team_color_bonus_data(self, csv_data: str, event_date: str) -> Dict[str, Any]:
"""Load Team Color Bonus data from CSV string
CSV format: timestamp, class_name, team_name, grade_level, students_count
Example: 10/16/2025 8:46:06, teacher1, team1, 1, 14
Validation:
- class_name must exist in Class_Info (case-insensitive, use lowercase teacher name)
- team_name must match the team for that class (case-insensitive)
- timestamp and grade_level are informational only
"""
conn = self.get_connection()
cursor = conn.cursor()
# Parse CSV (case-insensitive column matching)
reader = csv.DictReader(io.StringIO(csv_data))
# Normalize column names to lowercase for case-insensitive matching
normalized_rows = []
for row in reader:
normalized_row = {k.strip().lower(): v for k, v in row.items()}
normalized_rows.append(normalized_row)
count = 0
errors = []
for row in normalized_rows:
try:
# Extract data from CSV (columns are now lowercase)
csv_class_name = row.get('class_name', '').strip()
csv_team_name = row.get('team_name', '').strip()
students_count = int(row.get('students_count', 0))
if not csv_class_name:
errors.append(f"Missing class_name in row: {row}")
continue
if not csv_team_name:
errors.append(f"Missing team_name in row: {row}")
continue
# Validate class_name exists in Class_Info (case-insensitive)
cursor.execute(SELECT_CLASS_INFO_BY_NAME, (csv_class_name,))
result = cursor.fetchone()
if not result:
errors.append(f"Class not found: '{csv_class_name}'")
continue
db_class_name = result[0] # Use actual database case
db_team_name = result[1]
# Validate team_name matches (case-insensitive)
if db_team_name.upper() != csv_team_name.upper():
errors.append(f"Team mismatch for '{csv_class_name}': CSV has '{csv_team_name}', database has '{db_team_name}'")
continue
# Calculate bonus values
bonus_minutes = students_count * 10
bonus_participation = students_count * 1
# Insert or replace the bonus data
cursor.execute(INSERT_TEAM_COLOR_BONUS,
(event_date, db_class_name, students_count, bonus_minutes, bonus_participation))
count += 1
except ValueError as e:
errors.append(f"Invalid students_count in row {row}: {str(e)}")
except KeyError as e:
errors.append(f"Missing required column {str(e)} in row: {row}")
except Exception as e:
errors.append(f"Error processing row {row}: {str(e)}")
conn.commit()
return {
'success': len(errors) == 0,
'count': count,
'errors': errors
}
def check_existing_upload(self, log_date: str) -> Optional[Dict[str, Any]]:
"""Check if data already exists for this date"""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute(SELECT_EXISTING_UPLOAD, (log_date,))
row = cursor.fetchone()
if row:
return {
'timestamp': row[0],
'filename': row[1],
'students_affected': row[2]
}
return None
def get_upload_history(self, limit: int = 20) -> List[Dict[str, Any]]:
"""Get upload history ordered by most recent first"""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute(SELECT_UPLOAD_HISTORY, (limit,))
columns = [desc[0] for desc in cursor.description]
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return results
def delete_day_data(self, log_date: str) -> Dict[str, Any]:
"""Delete all data for a specific date"""
conn = self.get_connection()
cursor = conn.cursor()
try:
# Check if data exists
cursor.execute(SELECT_COUNT_DAILY_LOGS_BY_DATE, (log_date,))
count = cursor.fetchone()[0]
if count == 0:
return {
'success': False,
'error': f'No data found for date {log_date}'
}
# Get affected student names for audit trail
cursor.execute(SELECT_DISTINCT_STUDENTS_BY_DATE, (log_date,))
affected_students = [row[0] for row in cursor.fetchall()]
# Delete from Daily_Logs
cursor.execute(DELETE_DAY_DATA, (log_date,))
# Delete from Upload_History
cursor.execute(DELETE_UPLOAD_HISTORY_BY_DATE, (log_date,))
# The day's saved drawing winners (they would still keep those students out of other days' drawings).
# Team_Color_Bonus stays: it comes from its own upload, not from the day's minutes file
cursor.execute(DELETE_DRAWING_WINNERS_BY_DATE, (log_date,))
drawing_winners_deleted = cursor.rowcount
conn.commit()
return {
'success': True,
'deleted_records': count,
'drawing_winners_deleted': drawing_winners_deleted,
'log_date': log_date,
'affected_students': affected_students
}
except Exception as e:
conn.rollback()
return {
'success': False,
'error': str(e)
}
def delete_cumulative_data(self) -> Dict[str, Any]:
"""Delete all cumulative data (donations, sponsors, cumulative minutes)"""
conn = self.get_connection()
cursor = conn.cursor()
try:
# Check if data exists
cursor.execute(SELECT_COUNT_READER_CUMULATIVE)
count = cursor.fetchone()[0]
if count == 0:
return {
'success': False,
'error': 'No cumulative data found'
}
# Get affected student names for audit trail
cursor.execute(SELECT_ALL_STUDENTS_READER_CUMULATIVE)
affected_students = [row[0] for row in cursor.fetchall()]
# Delete all cumulative data
cursor.execute(DELETE_ALL_READER_CUMULATIVE)
# Delete cumulative upload history and the per-day snapshots
cursor.execute(DELETE_UPLOAD_HISTORY_CUMULATIVE)
cursor.execute(DELETE_ALL_READER_CUMULATIVE_HISTORY)
conn.commit()
return {
'success': True,
'deleted_records': count,
'affected_students': affected_students
}
except Exception as e:
conn.rollback()
return {
'success': False,
'error': str(e)
}
def delete_upload_history_batch(self, upload_ids: List[int]) -> Dict[str, Any]:
"""Delete multiple upload history records by their IDs"""
conn = self.get_connection()
cursor = conn.cursor()
try:
if not upload_ids:
return {
'success': False,
'error': 'No upload IDs provided'
}
# Delete all specified upload history records
delete_query = get_delete_upload_history_batch_query(upload_ids)
cursor.execute(delete_query, tuple(upload_ids))
deleted_count = cursor.rowcount
conn.commit()
return {
'success': True,
'deleted_count': deleted_count
}
except Exception as e:
conn.rollback()
return {
'success': False,
'error': str(e)
}
def _detect_columns(self, csv_headers: List[str]) -> Dict[str, bool]:
"""
Detect which columns are present in CSV (case-insensitive)
Returns dict with boolean flags for each column type
"""
headers_lower = [h.lower().strip() for h in csv_headers]
return {
'student_name': any(h in headers_lower for h in NAME_COLUMNS),
'minutes': any(h in headers_lower for h in MINUTES_COLUMNS),
'teacher': any(h in headers_lower for h in TEACHER_COLUMNS),
'raised': any(h in headers_lower for h in RAISED_COLUMNS),
'sponsors': any(h in headers_lower for h in SPONSORS_COLUMNS)
}
@staticmethod
def _parse_daily_row(row: Dict[str, str]) -> Tuple[Optional[str], Optional[str], Optional[int]]:
"""(reader name, teacher, minutes) from one daily minutes CSV row (case-insensitive columns)"""
student_name = teacher_name = minutes = None
for key in row.keys():
column = (key or '').lower().strip() # key None = extra values past the last header
if column in NAME_COLUMNS:
student_name = row[key].strip() if row[key] else None
elif column in MINUTES_COLUMNS:
try:
minutes = int(row[key]) if row[key] else 0
except (ValueError, TypeError):
minutes = 0
elif column in TEACHER_COLUMNS:
teacher_name = row[key].strip() if row[key] else None
return student_name, teacher_name, minutes
@staticmethod
def _parse_cumulative_row(row: Dict[str, str]) -> Tuple[Optional[str], Optional[str], float, int, int]:
"""(reader name, teacher, raised, sponsors, minutes) from one cumulative CSV row (case-insensitive columns)"""
student_name = teacher_name = None
donation_amount, sponsors, cumulative_minutes = 0.0, 0, 0
for key in row.keys():
column = (key or '').lower().strip() # key None = extra values past the last header
if column in NAME_COLUMNS:
student_name = row[key].strip() if row[key] else None
elif column in TEACHER_COLUMNS:
teacher_name = row[key].strip() if row[key] else None
elif column in RAISED_COLUMNS:
try:
donation_amount = float(row[key]) if row[key] else 0.0
except (ValueError, TypeError):
donation_amount = 0.0
elif column in SPONSORS_COLUMNS:
try:
sponsors = int(row[key]) if row[key] else 0
except (ValueError, TypeError):
sponsors = 0
elif column in MINUTES_COLUMNS:
try:
cumulative_minutes = int(row[key]) if row[key] else 0
except (ValueError, TypeError):
cumulative_minutes = 0
return student_name, teacher_name, donation_amount, sponsors, cumulative_minutes
# ----- Roster name matching (parent-typed names on read-a-thon.com; see name_matching.py) -----
def get_name_matcher(self) -> NameMatcher:
"""Roster + saved name corrections, for turning uploaded names into roster names"""
return NameMatcher(self.execute_query(SELECT_ROSTER_FOR_NAME_MATCHING), self.get_name_aliases())
def get_name_aliases(self, with_class_students: bool = False) -> List[Dict[str, Any]]:
"""Saved name corrections (student_name None = not a roster student); with_class_students adds the
uploaded teacher's students to each one (choices for changing it on the Upload page)"""
aliases = self.execute_query(SELECT_NAME_ALIASES)
if with_class_students:
matcher = NameMatcher(self.execute_query(SELECT_ROSTER_FOR_NAME_MATCHING))
for alias in aliases:
alias['class_students'] = matcher.class_students(alias['teacher_name'])
return aliases
@staticmethod
def _new_name_fixes() -> Dict[str, Dict[Tuple[str, str], Optional[str]]]:
"""What an upload did with names that aren't exact roster names, per kind (see _report_name_fixes)"""
return {'alias': {}, 'normalized': {}, 'skip': {}, 'unmatched': {}}
@staticmethod
def _note_name_fix(fixes, typed: str, teacher: Optional[str], roster_name: Optional[str], how: str) -> None:
if how in fixes:
fixes[how][(typed, teacher or '')] = roster_name
@staticmethod
def _report_name_fixes(fixes, result: Dict[str, Any]) -> None:
"""Info lines for corrected/left-out names, a warning per unmatched name"""
def who(typed, teacher):
return f"{typed} ({teacher})" if teacher else typed
def names(found):
return f"{len(found)} name{'' if len(found) == 1 else 's'}"
result.setdefault('info', [])
if fixes['alias']:
result['info'].append(f"Corrected {names(fixes['alias'])} using saved name corrections: " +
'; '.join(f"{who(*k)} → {v}" for k, v in fixes['alias'].items()))
if fixes['normalized']:
result['info'].append(f"Matched {names(fixes['normalized'])} that differed only in capitals or spaces: " +
'; '.join(f"{who(*k)} → {v}" for k, v in fixes['normalized'].items()))
if fixes['skip']:
result['info'].append(f"Left out {names(fixes['skip'])} saved as not roster students: " +
'; '.join(who(*k) for k in fixes['skip']))
for typed, teacher in fixes['unmatched']:
result['warnings'].append(f"Student not found in roster (imported anyway): {who(typed, teacher)}")
def check_upload_names(self, upload_type: str, contents: List[str]) -> Dict[str, Any]:
"""Before an upload: the names in the files (daily minutes or cumulative CSV text) that aren't
roster names, with suggested roster students for the Upload page's "Match names to the roster" panel.
Nothing is saved. Names already fixed by a saved correction or by case/spacing are listed in 'corrected'."""
matcher = self.get_name_matcher()
rows = [] # (typed name, teacher, minutes, raised, has any data)
for content in contents:
for row in csv.DictReader(io.StringIO(content)):
if upload_type == 'cumulative':
name, teacher, raised, sponsors, minutes = self._parse_cumulative_row(row)
has_values = bool(raised or sponsors or minutes)
else:
name, teacher, minutes = self._parse_daily_row(row)
raised, has_values = 0.0, bool(minutes)
if name:
rows.append((name, teacher or '', minutes or 0, raised, has_values))
has_data, unmatched, corrected, exact = set(), {}, {}, set()
for name, teacher, minutes, raised, has_values in rows:
roster_name, how = matcher.resolve(name, teacher)
if how == 'exact':
exact.add(name)
if how == 'unmatched':
entry = unmatched.setdefault((name, teacher), {'uploaded_name': name, 'teacher_name': teacher,
'rows': 0, 'minutes': 0, 'raised': 0.0})
entry['rows'] += 1
entry['minutes'] += minutes
entry['raised'] += raised
continue
if roster_name and has_values:
has_data.add(roster_name)