Spaces:
Runtime error
Runtime error
File size: 13,013 Bytes
49888b0 |
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 |
"""
Admin Service Layer for ThutoAI
Handles admin authentication and school management operations
"""
from models import DatabaseManager
import hashlib
import json
from datetime import datetime
class AdminService:
def __init__(self):
self.db = DatabaseManager()
def authenticate_admin(self, username, password):
"""Authenticate admin user"""
conn = self.db.get_connection()
cursor = conn.cursor()
password_hash = hashlib.sha256(password.encode()).hexdigest()
cursor.execute('''
SELECT id, username, full_name, email, role, is_active
FROM admin_users
WHERE username = ? AND password_hash = ? AND is_active = 1
''', (username, password_hash))
admin = cursor.fetchone()
if admin:
# Update last login
cursor.execute('''
UPDATE admin_users SET last_login = CURRENT_TIMESTAMP WHERE id = ?
''', (admin[0],))
conn.commit()
conn.close()
return {
'id': admin[0],
'username': admin[1],
'full_name': admin[2],
'email': admin[3],
'role': admin[4],
'is_active': bool(admin[5])
}
conn.close()
return None
# Announcement Management
def create_announcement(self, title, content, priority='normal', target_audience='all', expires_at=None, created_by='admin'):
"""Create a new announcement"""
conn = self.db.get_connection()
cursor = conn.cursor()
cursor.execute('''
INSERT INTO announcements (title, content, priority, target_audience, expires_at)
VALUES (?, ?, ?, ?, ?)
''', (title, content, priority, target_audience, expires_at))
announcement_id = cursor.lastrowid
conn.commit()
conn.close()
return announcement_id
def update_announcement(self, announcement_id, title=None, content=None, priority=None, target_audience=None, expires_at=None):
"""Update an existing announcement"""
conn = self.db.get_connection()
cursor = conn.cursor()
updates = []
params = []
if title:
updates.append("title = ?")
params.append(title)
if content:
updates.append("content = ?")
params.append(content)
if priority:
updates.append("priority = ?")
params.append(priority)
if target_audience:
updates.append("target_audience = ?")
params.append(target_audience)
if expires_at:
updates.append("expires_at = ?")
params.append(expires_at)
if updates:
params.append(announcement_id)
cursor.execute(f'''
UPDATE announcements SET {", ".join(updates)} WHERE id = ?
''', params)
conn.commit()
conn.close()
return True
def delete_announcement(self, announcement_id):
"""Delete an announcement"""
conn = self.db.get_connection()
cursor = conn.cursor()
cursor.execute('UPDATE announcements SET is_active = 0 WHERE id = ?', (announcement_id,))
conn.commit()
conn.close()
return True
def get_all_announcements(self):
"""Get all announcements for admin management"""
conn = self.db.get_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT id, title, content, priority, target_audience, created_at, expires_at, is_active
FROM announcements
ORDER BY created_at DESC
''')
announcements = cursor.fetchall()
conn.close()
return [
{
'id': ann[0],
'title': ann[1],
'content': ann[2],
'priority': ann[3],
'target_audience': ann[4],
'created_at': ann[5],
'expires_at': ann[6],
'is_active': bool(ann[7])
}
for ann in announcements
]
# Syllabus Management
def create_syllabus(self, subject, grade_level, chapter_number, chapter_title, topics,
learning_objectives=None, duration_weeks=None, resources=None,
assessment_methods=None, created_by='admin'):
"""Create a new syllabus entry"""
conn = self.db.get_connection()
cursor = conn.cursor()
# Convert lists to JSON strings
topics_json = json.dumps(topics) if isinstance(topics, list) else topics
resources_json = json.dumps(resources) if isinstance(resources, list) else resources
cursor.execute('''
INSERT INTO syllabus (subject, grade_level, chapter_number, chapter_title, topics,
learning_objectives, duration_weeks, resources, assessment_methods, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (subject, grade_level, chapter_number, chapter_title, topics_json,
learning_objectives, duration_weeks, resources_json, assessment_methods, created_by))
syllabus_id = cursor.lastrowid
conn.commit()
conn.close()
return syllabus_id
def get_syllabus(self, subject=None, grade_level=None):
"""Get syllabus data"""
conn = self.db.get_connection()
cursor = conn.cursor()
query = '''
SELECT id, subject, grade_level, chapter_number, chapter_title, topics,
learning_objectives, duration_weeks, resources, assessment_methods,
created_by, created_at, updated_at
FROM syllabus
WHERE is_active = 1
'''
params = []
if subject:
query += ' AND subject = ?'
params.append(subject)
if grade_level:
query += ' AND grade_level = ?'
params.append(grade_level)
query += ' ORDER BY subject, grade_level, chapter_number'
cursor.execute(query, params)
syllabus_data = cursor.fetchall()
conn.close()
return [
{
'id': syl[0],
'subject': syl[1],
'grade_level': syl[2],
'chapter_number': syl[3],
'chapter_title': syl[4],
'topics': json.loads(syl[5]) if syl[5] else [],
'learning_objectives': syl[6],
'duration_weeks': syl[7],
'resources': json.loads(syl[8]) if syl[8] else [],
'assessment_methods': syl[9],
'created_by': syl[10],
'created_at': syl[11],
'updated_at': syl[12]
}
for syl in syllabus_data
]
def update_syllabus(self, syllabus_id, **kwargs):
"""Update syllabus entry"""
conn = self.db.get_connection()
cursor = conn.cursor()
# Convert lists to JSON if needed
if 'topics' in kwargs and isinstance(kwargs['topics'], list):
kwargs['topics'] = json.dumps(kwargs['topics'])
if 'resources' in kwargs and isinstance(kwargs['resources'], list):
kwargs['resources'] = json.dumps(kwargs['resources'])
updates = []
params = []
for key, value in kwargs.items():
if key in ['subject', 'grade_level', 'chapter_number', 'chapter_title', 'topics',
'learning_objectives', 'duration_weeks', 'resources', 'assessment_methods', 'is_active']:
updates.append(f"{key} = ?")
params.append(value)
if updates:
updates.append("updated_at = CURRENT_TIMESTAMP")
params.append(syllabus_id)
cursor.execute(f'''
UPDATE syllabus SET {", ".join(updates)} WHERE id = ?
''', params)
conn.commit()
conn.close()
return True
# Timetable Management
def create_timetable_entry(self, class_section, day_of_week, period_number, start_time,
end_time, subject, teacher_name=None, room_number=None, created_by='admin'):
"""Create a new timetable entry"""
conn = self.db.get_connection()
cursor = conn.cursor()
cursor.execute('''
INSERT INTO timetable (class_section, day_of_week, period_number, start_time, end_time,
subject, teacher_name, room_number, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (class_section, day_of_week, period_number, start_time, end_time,
subject, teacher_name, room_number, created_by))
timetable_id = cursor.lastrowid
conn.commit()
conn.close()
return timetable_id
def get_timetable(self, class_section=None, day_of_week=None):
"""Get timetable data"""
conn = self.db.get_connection()
cursor = conn.cursor()
query = '''
SELECT id, class_section, day_of_week, period_number, start_time, end_time,
subject, teacher_name, room_number, created_by, created_at
FROM timetable
WHERE is_active = 1
'''
params = []
if class_section:
query += ' AND class_section = ?'
params.append(class_section)
if day_of_week:
query += ' AND day_of_week = ?'
params.append(day_of_week)
query += ' ORDER BY class_section, day_of_week, period_number'
cursor.execute(query, params)
timetable_data = cursor.fetchall()
conn.close()
return [
{
'id': tt[0],
'class_section': tt[1],
'day_of_week': tt[2],
'period_number': tt[3],
'start_time': tt[4],
'end_time': tt[5],
'subject': tt[6],
'teacher_name': tt[7],
'room_number': tt[8],
'created_by': tt[9],
'created_at': tt[10]
}
for tt in timetable_data
]
def update_timetable_entry(self, timetable_id, **kwargs):
"""Update timetable entry"""
conn = self.db.get_connection()
cursor = conn.cursor()
updates = []
params = []
for key, value in kwargs.items():
if key in ['class_section', 'day_of_week', 'period_number', 'start_time', 'end_time',
'subject', 'teacher_name', 'room_number']:
updates.append(f"{key} = ?")
params.append(value)
if updates:
updates.append("updated_at = CURRENT_TIMESTAMP")
params.append(timetable_id)
cursor.execute(f'''
UPDATE timetable SET {", ".join(updates)} WHERE id = ?
''', params)
conn.commit()
conn.close()
return True
def delete_timetable_entry(self, timetable_id):
"""Delete timetable entry"""
conn = self.db.get_connection()
cursor = conn.cursor()
cursor.execute('UPDATE timetable SET is_active = 0 WHERE id = ?', (timetable_id,))
conn.commit()
conn.close()
return True
# Dashboard Statistics
def get_admin_dashboard_stats(self):
"""Get statistics for admin dashboard"""
conn = self.db.get_connection()
cursor = conn.cursor()
stats = {}
# Count active announcements
cursor.execute('SELECT COUNT(*) FROM announcements WHERE is_active = 1')
stats['active_announcements'] = cursor.fetchone()[0]
# Count syllabus entries
cursor.execute('SELECT COUNT(*) FROM syllabus WHERE is_active = 1')
stats['syllabus_entries'] = cursor.fetchone()[0]
# Count timetable entries
cursor.execute('SELECT COUNT(*) FROM timetable WHERE is_active = 1')
stats['timetable_entries'] = cursor.fetchone()[0]
# Count students
cursor.execute('SELECT COUNT(*) FROM students')
stats['total_students'] = cursor.fetchone()[0]
# Count upcoming exams
cursor.execute('SELECT COUNT(*) FROM examinations WHERE exam_date >= date("now")')
stats['upcoming_exams'] = cursor.fetchone()[0]
conn.close()
return stats
# Initialize admin service
admin_service = AdminService() |