-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
683 lines (612 loc) · 28.5 KB
/
main.py
File metadata and controls
683 lines (612 loc) · 28.5 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
import mysql.connector
from mysql.connector import Error
import datetime as dt
import random
import os
from tabulate import tabulate
# Creating the database
try:
cnx = mysql.connector.connect(user='root', password='root', host='127.0.0.1')
cursor = cnx.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS studytrack")
cnx.commit()
cursor.close()
cnx.close()
except Error as e:
print(f"Error connecting to the server and creating a database: {e.msg}")
# Connection to the database
try:
cnx = mysql.connector.connect(user='root', password='root', host='127.0.0.1', database='studytrack')
cursor = cnx.cursor(buffered=True)
except Error as e:
print(f"Error connecting to the database: {e.msg}")
exit()
# Creating the table if it doesn't exist
tables = {}
tables["study_sessions"] = "CREATE TABLE IF NOT EXISTS study_sessions(Date date, Topic text, Subject varchar(30), TimeStudied float, Completion int, Remarks text);"
tables["tests"] = "CREATE TABLE IF NOT EXISTS tests(ExamDate date, Subject varchar(30), Series char(12), Portions text, Status char(3), MarksObtained int, TotalMarks int);"
tables["assignments"] = "CREATE TABLE IF NOT EXISTS assignments(DueDate date, Subject varchar(30), Topic text, Status char(3));"
tables["syllabus"] = "CREATE TABLE IF NOT EXISTS syllabus(Subject varchar(30) PRIMARY KEY, Chapters text)"
for table in tables:
try:
cursor.execute(tables[table])
cnx.commit()
except Error as e:
print(f"Error creating table {table}: {e.msg}")
# Menu
def menu():
info = fetch_sub()
os.system('cls' if os.name == 'nt' else 'clear')
print("StudyTrack CLI - Main Menu\n")
if info[0] == "N/A":
print("First add the syllabus to get subject suggestions here using the 10th option.")
else:
print("Today's Subject: ", info[0])
if info[1] != "N/A":
print("Upcoming Assignment: ", info[1])
print()
print("1. Progress Report")
print("2. Add Study Session")
print("3. View Study Sessions")
print("4. Add Tests")
print("5. View Upcoming Tests")
print("6. View Completed and Marks Added Tests")
print("7. Add Test Marks")
print("8. Add Assignments")
print("9. View Assignments")
print("10. Add Syllabus (to be done once every semester)")
print("11. View Syllabus")
print("12. Exit\n")
funs = [progress, add_study_session, view_study_sessions, add_test,
view_upcoming_tests, view_all_tests, add_marks, add_assignment, view_assignments, add_syllabus, view_syllabus]
try:
choice = int(input("Select an option (1-12): "))
if choice in range(1, 12):
funs[choice - 1]()
elif choice == 12:
print("\nExiting StudyTrack CLI. Goodbye!")
cursor.close()
cnx.close()
exit()
else:
raise IndexError
except (ValueError, IndexError):
print("\nInvalid Option. Please try again.")
input("Press ENTER to continue... ")
# Progress Report
def progress():
os.system('cls' if os.name == 'nt' else 'clear')
print("Progress Report")
print("\nStudy Sessions Summary:-\n")
try:
cursor.execute("SELECT Subject, SUM(TimeStudied), AVG(Completion) FROM study_sessions GROUP BY Subject")
data = cursor.fetchall()
if data:
print(tabulate(data, headers=["Subject", "Total Time Studied (hrs)", "Avg Completion (%)"], tablefmt="rounded_outline"))
except Error as e:
print(f"Error retrieving study sessions summary: {e.msg}\n")
print("\nTests Summary:-\n")
try:
cursor.execute("SELECT Subject, AVG(MarksObtained / TotalMarks) FROM tests WHERE MarksObtained IS NOT NULL AND TotalMarks IS NOT NULL GROUP BY Subject")
data = cursor.fetchall()
if data:
data = [[row[0], round((float(row[1]) * 100), 2)] for row in data]
print(tabulate(data, headers=["Subject", "Avg Marks (%)"], tablefmt="rounded_outline"))
except Error as e:
print(f"Error retrieving test summary: {e.msg}\n")
print("\nAssignments Summary:-\n")
try:
cursor.execute("SELECT count(*) FROM assignments")
total = cursor.fetchall()[0][0]
if total == 0:
print("No assignments added yet.")
else:
cursor.execute("SELECT count(*) FROM assignments WHERE Status = 'S'")
over = cursor.fetchall()[0][0]
cursor.execute("SELECT count(*) FROM assignments WHERE Status = 'NS' and DueDate < CURDATE()")
overdue = cursor.fetchall()[0][0]
print(f"Assignments Submitted: {over}/{total} | {round((int(over)/int(total))*100, 2)}%")
print("Assignments Overdue:", overdue)
except Error as e:
print(f"Error retrieving assignment summary: {e.msg}\n")
input("\nPress ENTER to return to the main menu... ")
# Add Study Session
def add_study_session():
x = True
while x:
os.system('cls' if os.name == 'nt' else 'clear')
print("Add Study Session\n")
date = input("Date (YYYY-MM-DD) or press ENTER for current date: ")
if date == "":
date = dt.date.today().strftime("%Y-%m-%d")
topic = input("Topic: ")
subject = input("Subject: ").capitalize().strip()
try:
time_studied = int(input("Time Studied (in hours): "))
completion = int(input("Completion (%): "))
except ValueError:
print("\nPlease enter valid numeric values for Time Studied and Completion.")
input("Press ENTER to try again...")
continue
remarks = input("Remarks: ")
add_session = ("INSERT INTO study_sessions "
"(Date, Topic, Subject, TimeStudied, Completion, Remarks) "
"VALUES (%s, %s, %s, %s, %s, %s)")
data_session = (date, topic, subject, time_studied, completion, remarks)
try:
cursor.execute(add_session, data_session)
cnx.commit()
print("\nStudy session added successfully!")
except Error as e:
print(f"\nError adding study session: {e.msg}")
x = False if input("\nPress 1 to add new or Enter to return to the main menu... ") != "1" else True
# View Study Sessions
def view_study_sessions():
os.system('cls' if os.name == 'nt' else 'clear')
print("View Study Sessions\n")
data = []
try:
cursor.execute("SELECT * FROM study_sessions ORDER BY Date DESC")
data = list(cursor.fetchall())[:10]
d = []
for r in range(len(data)):
d.append(list(data[r]))
d[r].insert(0, str(r+1) + ".")
d[r][6] = str(d[r][6])[:20]
print(tabulate(d, headers=["No.", "Date", "Topic", "Subject", "Time Studied (hrs)", "Completion (%)", "Remarks"], tablefmt="rounded_outline"))
except Error as e:
print(f"Error retrieving study sessions: {e.msg}")
c = input("\nPress 1 to UPDATE or ENTER to return to main menu... ")
if c == "1":
try:
ss = int(input("Select the study session (number) to update: "))
if ss in range(1, len(data) + 1):
to_update = data[ss-1]
else:
raise IndexError
except (ValueError, IndexError):
print("\nPlease enter a valid option.")
input("Press ENTER to return...")
os.system('cls' if os.name == 'nt' else 'clear')
print("Update Study Session\n")
choice = input("Do you want to remove this study session? (y/n): ")
if choice == "y":
try:
cursor.execute("DELETE FROM study_sessions WHERE Date = %s AND Topic = %s AND Subject = %s AND Remarks = %s", (to_update[0], to_update[1], to_update[2], to_update[5]))
cnx.commit()
print("\nStudy session removed successfully!")
except Error as e:
print(f"\nError removing study session: {e.msg}")
input("\nPress ENTER to return...")
else:
print("Press ENTER to keep the current value.")
remarks = str(to_update[5])[:20]
print(f"Selected: {to_update[0]} | {to_update[1]} | {to_update[2]} | {to_update[3]} hrs | {to_update[4]}% | {remarks}")
date = input("Date (YYYY-MM-DD): ")
topic = input("Topic: ")
subject = input("Subject: ").capitalize().strip()
time_studied = input("Time Studied (in hours): ")
completion = input("Completion (%): ")
try:
if time_studied != "":
time_studied = int(time_studied)
if completion != "":
completion = int(completion)
except ValueError:
print("\nPlease enter valid numeric values or leave it blank for Time Studied and Completion.")
input("Press ENTER to try again...")
view_study_sessions()
remarks = input("Remarks: ")
query = ("UPDATE study_sessions SET Date = %s, Topic = %s, Subject = %s, TimeStudied = %s, Completion = %s, Remarks = %s WHERE Date = %s AND Topic = %s AND Subject = %s AND Remarks = %s")
data_query = (date if date != "" else to_update[0], topic if topic != "" else to_update[1],
subject if subject != "" else to_update[2], time_studied if time_studied != "" else to_update[3],
completion if completion != "" else to_update[4], remarks if remarks != "" else to_update[5],
to_update[0], to_update[1], to_update[2], to_update[5])
try:
cursor.execute(query, data_query)
cnx.commit()
print("\nStudy Session updated successfully!")
except Error as e:
print(f"\nError updating Study Session: {e.msg}")
input("Press ENTER to return...")
# Add Upcoming Tests
def add_test():
x = True
while x:
os.system('cls' if os.name == 'nt' else 'clear')
print("Add Test\n")
exam_date = input("Exam Date (YYYY-MM-DD): ")
subject = input("Subject: ").capitalize().strip()
series = input("Series: ").upper()
portions = input("Portions (comma-seperated topics): ")
status = input("Status (S/NS/R) [For Studied/Not Studied/Revised]: ").upper()
add_test = ("INSERT INTO tests "
"(ExamDate, Subject, Series, Portions, Status) "
"VALUES (%s, %s, %s, %s, %s)")
data_test = (exam_date, subject, series, portions, status)
try:
cursor.execute(add_test, data_test)
cnx.commit()
print("\nTest added successfully!")
except Error as e:
print(f"\nError adding test: {e.msg}")
x = False if input("\nPress 1 to add new or Enter to return to the main menu... ") != "1" else True
# View Upcoming Tests
def view_upcoming_tests():
os.system('cls' if os.name == 'nt' else 'clear')
print("View Upcoming Tests\n")
today = dt.datetime.now().strftime("%Y-%m-%d")
mon = (dt.datetime.now() + dt.timedelta(days=31)).strftime("%Y-%m-%d")
data = d = []
try:
cursor.execute("SELECT * FROM tests WHERE ExamDate > %s and ExamDate < %s ORDER BY ExamDate", (today, mon))
data = cursor.fetchall()
for r in range(len(data)):
d.append(list(data[r])[:5])
d[r].insert(0, str(r+1) + ".")
d[r][5] = "Studied" if d[r][5] == "S" else "Not Studied" if d[r][5] == "NS" else "Revised"
print(tabulate(d, headers=["No.", "Exam Date", "Subject", "Series", "Portions", "Status"], tablefmt="rounded_outline"))
except Error as e:
print(f"Error retrieving upcoming tests: {e.msg}")
c = input("\nPress 1 to UPDATE or ENTER to return to main menu... ")
if c == "1":
try:
ss = int(input("Select the test (number) to update: "))
if ss in range(1, len(data) + 1):
to_update = data[ss-1]
else:
raise IndexError
except (ValueError, IndexError):
print("\nPlease enter a valid option.")
input("Press ENTER to try again...")
view_upcoming_tests()
os.system('cls' if os.name == 'nt' else 'clear')
print("Update Test\n")
choice = input("Do you want to remove this test? (y/n): ")
if choice == "y":
try:
cursor.execute("DELETE FROM tests WHERE ExamDate = %s AND Subject = %s AND Series = %s", (to_update[0], to_update[1], to_update[2]))
cnx.commit()
print("\nTest removed successfully!")
except Error as e:
print(f"\nError removing test: {e.msg}")
input("\nPress ENTER to return...")
view_upcoming_tests()
print("Press ENTER to keep the current value.")
remarks = "Studied" if to_update[4] == "S" else "Not Studied" if to_update[4] == "NS" else "Revised"
print(f"Selected: {to_update[0]} | {to_update[1]} | {to_update[2]} | {to_update[3]} | {remarks}")
exam_date = input("Exam Date (YYYY-MM-DD): ")
subject = input("Subject: ").capitalize().strip()
series = input("Series: ").upper()
portions = input("Portions (comma-seperated topics): ")
status = input("Status (S/NS/R) [For Studied/Not Studied/Revised]: ").upper()
query = ("UPDATE tests SET ExamDate = %s, Subject = %s, Series = %s, Portions = %s, Status = %s WHERE ExamDate = %s AND Subject = %s AND Series = %s")
data_query = (exam_date if exam_date != "" else to_update[0], subject if subject != "" else to_update[1],
series if series != "" else to_update[2], portions if portions != "" else to_update[3],
status if status != "" else to_update[4],
to_update[0], to_update[1], to_update[2])
try:
cursor.execute(query, data_query)
cnx.commit()
print("\nTest updated successfully!")
except Error as e:
print(f"\nError updating Test: {e.msg}")
input("Press ENTER to return...")
view_upcoming_tests()
# View Completed Tests With Marks
def view_all_tests():
os.system('cls' if os.name == 'nt' else 'clear')
print("View Marks Added Tests\n")
data = d = []
try:
cursor.execute("SELECT * FROM tests WHERE MarksObtained IS NOT NULL ORDER BY ExamDate")
data = cursor.fetchall()
for r in range(len(data)):
d.append(list(data[r][:4]))
d[r].insert(0, str(r+1) + ".")
d[r].append(f"{data[r][5]}/{data[r][6]}")
print(tabulate(d, headers=["No.", "Exam Date", "Subject", "Series", "Portions", "Marks Obtained"], tablefmt="rounded_outline"))
except Error as e:
print(f"Error retrieving tests: {e.msg}")
c = input("\nPress 1 to UPDATE or ENTER to return to main menu... ")
if c == "1":
try:
ss = int(input("Select the test (number) to update: "))
if ss in range(1, len(data) + 1):
to_update = data[ss-1]
else:
raise IndexError
except (ValueError, IndexError):
print("\nPlease enter a valid option.")
input("Press ENTER to try again...")
view_all_tests()
os.system('cls' if os.name == 'nt' else 'clear')
print("Update Test\n")
choice = input("Do you want to remove this test? (y/n): ")
if choice == "y":
try:
cursor.execute("DELETE FROM tests WHERE ExamDate = %s AND Subject = %s AND Series = %s", (to_update[0], to_update[1], to_update[2]))
cnx.commit()
print("\nTest removed successfully!")
except Error as e:
print(f"\nError removing test: {e.msg}")
input("\nPress ENTER to return...")
view_all_tests()
print("Press ENTER to keep the current value.")
print(f"Selected: {to_update[0]} | {to_update[1]} | {to_update[2]} | {to_update[3]} | {to_update[5]}/{to_update[6]} Marks")
exam_date = input("Exam Date (YYYY-MM-DD): ")
subject = input("Subject: ").capitalize().strip()
series = input("Series: ").upper()
portions = input("Portions (comma-seperated topics): ")
o_marks = input("Obtained Marks: ")
t_marks = input("Total Marks (i.e Out of): ")
try:
if o_marks != "":
o_marks = int(o_marks)
if t_marks != "":
t_marks = int(t_marks)
except ValueError:
print("\nPlease enter valid numeric values or leave it blank for marks.")
input("Press ENTER to try again...")
view_all_tests()
query = ("UPDATE tests SET ExamDate = %s, Subject = %s, Series = %s, Portions = %s, MarksObtained = %s, TotalMarks = %s WHERE ExamDate = %s AND Subject = %s AND Series = %s")
data_query = (exam_date if exam_date != "" else to_update[0], subject if subject != "" else to_update[1],
series if series != "" else to_update[2], portions if portions != "" else to_update[3],
o_marks if o_marks != "" else to_update[5], t_marks if t_marks != "" else to_update[6],
to_update[0], to_update[1], to_update[2])
try:
cursor.execute(query, data_query)
cnx.commit()
print("\nTest updated successfully!")
except Error as e:
print(f"\nError updating Test: {e.msg}")
input("Press ENTER to return...")
view_all_tests()
# Add Test Marks
def add_marks():
x = True
while x:
os.system('cls' if os.name == 'nt' else 'clear')
print("Add Test Marks\n")
cursor.execute("SELECT ExamDate, Subject, Series FROM tests WHERE MarksObtained IS NULL and ExamDate < CURDATE() ORDER BY ExamDate")
data = cursor.fetchall()
d = []
for r in range(len(data)):
d.append(list(data[r]))
d[r].insert(0, str(r+1) + ".")
print(tabulate(d, headers=["No.", "Exam Date", "Subject", "Series"], tablefmt="rounded_outline"))
se = input("\nSelect the test to add marks or press ENTER to return to the main menu... ")
if se != "":
try:
se = int(se)
to_add = data[se-1]
except (ValueError, IndexError):
print("\nPlease enter a valid option.")
input("Press ENTER to try again...")
continue
os.system('cls' if os.name == 'nt' else 'clear')
print("Add Test Marks\n")
print(f"Selected: {to_add[0]} | {to_add[1]} | {to_add[2]}\n")
try:
o_marks = int(input("Obtained Marks: "))
t_marks = int(input("Total Marks (i.e Out of): "))
except ValueError:
print("\nPlease enter valid numeric values for marks.")
input("Press ENTER to try again...")
continue
query = ("UPDATE tests SET MarksObtained = %s, TotalMarks = %s, Status = 'C' WHERE ExamDate = %s AND Subject = %s AND Series = %s")
data_query = (o_marks, t_marks, to_add[0], to_add[1], to_add[2])
try:
cursor.execute(query, data_query)
cnx.commit()
print("\nMarks added successfully!")
except Error as e:
print(f"\nError in adding marks: {e.msg}")
x = False if input("\nPress 1 to add another test marks or Enter to return to the main menu... ") != "1" else True
else:
x = False
# Add Assignments
def add_assignment():
x = True
while x:
os.system('cls' if os.name == 'nt' else 'clear')
print("Add Assignment\n")
due_date = input("Due Date (YYYY-MM-DD): ")
subject = input("Subject: ").capitalize().strip()
topic = input("Topic: ")
status = input("Status (S/NS) [For Submitted/Not Submitted]: ").upper()
add_assign = ("INSERT INTO assignments "
"(DueDate, Subject, Topic, Status) "
"VALUES (%s, %s, %s, %s)")
data_assign = (due_date, subject, topic, status)
try:
cursor.execute(add_assign, data_assign)
cnx.commit()
print("\nAssignment added successfully!")
except Error as e:
print(f"\nError adding assignment: {e.msg}")
x = False if input("\nPress 1 to add new or Enter to return to the main menu... ") != "1" else True
# View Assignments
def view_assignments():
os.system('cls' if os.name == 'nt' else 'clear')
print("View Assignments\n")
today = dt.datetime.now().strftime("%Y-%m-%d")
week = (dt.datetime.now() + dt.timedelta(days=7)).strftime("%Y-%m-%d")
oa = data = d = []
loa = 0
try:
cursor.execute("SELECT * FROM assignments WHERE DueDate < %s and status = 'NS' ORDER BY DueDate", (today,))
data = cursor.fetchall()
d = []
if data:
for r in range(len(data)):
d.append(list(data[r][:3]))
d[r].insert(0, str(r+1) + ".")
d[r].append("Not Submitted - **** OVERDUE ****")
print(tabulate(d, headers=["No.", "Due Date", "Subject", "Topic", "Remarks"], tablefmt="rounded_outline"))
print("\n")
except Error as e:
print(f"Error retrieving overdue assignments: {e.msg}\n")
if data:
oa = data
loa = len(oa)
try:
cursor.execute("SELECT * FROM assignments WHERE DueDate > %s and DueDate < %s ORDER BY DueDate", (today, week))
data = cursor.fetchall()
d = []
if data:
for r in range(len(data)):
d.append(list(data[r][:3]))
d[r].insert(0, str(r + loa + 1) + ".")
d[r].append("Submitted" if data[r][3] == "S" else "Not Submitted")
print(tabulate(d, headers=["No.", "Due Date", "Subject", "Topic", "Remarks"], tablefmt="rounded_outline"))
except Error as e:
print(f"Error retrieving assignments: {e.msg}")
if data:
oa.extend(data)
c = input("\nPress 1 to UPDATE or ENTER to return to main menu... ")
if c == "1":
try:
ss = int(input("Select the assignment (number) to update: "))
if ss in range(1, len(oa) + 1):
to_update = oa[ss-1]
else:
raise IndexError
except (ValueError, IndexError):
print("\nPlease enter a valid option.")
input("Press ENTER to try again...")
view_assignments()
os.system('cls' if os.name == 'nt' else 'clear')
print("Update Assignment\n")
choice = input("Do you want to remove this assignment? (y/n): ")
if choice == "y":
try:
cursor.execute("DELETE FROM assignments WHERE DueDate = %s AND Subject = %s AND Topic = %s", (to_update[0], to_update[1], to_update[2]))
cnx.commit()
print("\nAssignment removed successfully!")
except Error as e:
print(f"\nError removing assignment: {e.msg}")
input("\nPress ENTER to return...")
view_assignments()
print("Press ENTER to keep the current value.")
remarks = "Submitted" if to_update[3] == "S" else "Not Submitted"
print(f"Selected: {to_update[0]} | {to_update[1]} | {to_update[2]} | {remarks}")
due_date = input("Due Date (YYYY-MM-DD): ")
subject = input("Subject: ").capitalize().strip()
topic = input("Topic: ")
status = input("Status (S/NS) [For Submitted/Not Submitted]: ").upper()
query = ("UPDATE assignments SET DueDate = %s, Subject = %s, Topic = %s, Status = %s WHERE DueDate = %s AND Subject = %s AND Topic = %s")
data_query = (due_date if due_date != "" else to_update[0], subject if subject != "" else to_update[1],
topic if topic != "" else to_update[2], status if status != "" else to_update[3],
to_update[0], to_update[1], to_update[2])
try:
cursor.execute(query, data_query)
cnx.commit()
print("\nAssignment updated successfully!")
except Error as e:
print(f"\nError updating Assignment: {e.msg}")
input("Press ENTER to return...")
view_assignments()
# Add Syllabus
def add_syllabus():
x = True
print("This function is to be used once every semester (or year) to add the syllabus for all subjects")
print("Add all subjects (syllabus just press ENTER if not known)")
choice = input("Do you want to remove all existing syllabus data? (y/n) [y only in start of year]: ")
if choice == "y":
try:
cursor.execute("DELETE FROM syllabus")
cnx.commit()
print("All existing syllabus data removed.")
except Error as e:
print(f"Error removing existing syllabus data: {e.msg}")
input("Press ENTER to continue... ")
while x:
os.system('cls' if os.name == 'nt' else 'clear')
print("Add Syllabus\n")
subject = input("Subject: ").capitalize().strip()
chapters = input("Chapters (comma-seperated): ")
add_syl = ("INSERT INTO syllabus "
"(Subject, Chapters) "
"VALUES (%s, %s)")
data_syl = (subject, chapters)
try:
cursor.execute(add_syl, data_syl)
cnx.commit()
print("\nSyllabus added successfully!")
except Error as e:
print(f"\nError adding syllabus: {e.msg}")
x = False if input("\nPress 1 to add new or Enter to return to the main menu... ") != "1" else True
# View Syllabus
def view_syllabus():
os.system('cls' if os.name == 'nt' else 'clear')
print("View Syllabus\n")
data = []
try:
cursor.execute("SELECT * FROM syllabus ORDER BY Subject")
data = cursor.fetchall()
d = []
for r in range(len(data)):
d.append(list(data[r]))
d[r].insert(0, str(r+1) + ".")
print(tabulate(d, headers=["No.", "Subject", "Chapters"], tablefmt="rounded_outline"))
except Error as e:
print(f"Error retrieving syllabus: {e.msg}")
c = input("\nPress 1 to UPDATE or ENTER to return to main menu... ")
if c == "1":
try:
ss = int(input("Select the subject (number) to update: "))
if ss in range(1, len(data) + 1):
to_update = data[ss-1]
else:
raise IndexError
except (ValueError, IndexError):
print("\nPlease enter a valid option.")
input("Press ENTER to try again...")
view_syllabus()
os.system('cls' if os.name == 'nt' else 'clear')
print("Update Syllabus\n")
print("Selected Subject:", to_update[0])
print("Current Syllabus:", to_update[1])
chapters = input("New Syllabus (comma-seperated | '' for emptying | /r for removing subject) [Tip: Copy the current and edit]: ")
query = ("UPDATE syllabus SET Chapters = %s WHERE Subject = %s") if chapters != "/r" else ("DELETE FROM syllabus WHERE Subject = %s")
data_query = (chapters, to_update[0]) if chapters != "/r" else to_update[0]
try:
cursor.execute(query, data_query)
cnx.commit()
print("\nSyllabus updated successfully!")
except Error as e:
print(f"\nError updating Syllabus: {e.msg}")
input("Press ENTER to return...")
view_syllabus()
# Fetch Subjects
def fetch_sub():
info = []
try:
cursor.execute("SELECT DISTINCT Subject FROM syllabus")
data = cursor.fetchall()
subs = []
if data:
subs = [row[0] for row in data]
if len(subs) == 0:
info.append("N/A")
else:
d_subs = subs + random.choices(subs, k=7-len(subs)) if len(subs) < 7 else subs
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
d = {days[i]:d_subs[i] for i in range(7)}
info.append(d[dt.datetime.now().strftime("%A")])
except Error as e:
print(f"Error fetching subjects: {e.msg}")
try:
cursor.execute("SELECT DueDate, Subject, Topic FROM assignments WHERE DueDate > CURDATE() and Status = 'NS' ORDER BY DueDate")
data = cursor.fetchone()
if not data:
info += ("N/A",)
else:
info.append(f"{data[1]} - {data[2]} (Due: {data[0]})")
except Error as e:
print(f"Error fetching assignments: {e.msg}")
return info
# Main Loop
while True:
menu()