-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1835 lines (1385 loc) · 70.1 KB
/
main.py
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
# Paper - Digital Attendance Management System
# Copyright (C) 2022-2023 Saurabh Kumar
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# Contact: Saurabh Kumar <[email protected]>
#
import os.path
import subprocess
from csv import writer
from sys import exit
from time import strftime
try:
import mysql.connector as server
from PyQt6 import QtWidgets, QtCore, uic, QtGui
from pyqtgraph import *
except ImportError:
from tkinter import Tk, messagebox
root = Tk()
root.attributes("-topmost", True)
root.overrideredirect(True)
root.withdraw()
messagebox.showerror(title="Paper - Cannot run app",
message="One or all of the following modules required to run the app were not found:\n\n"
"PyQt6\n"
"pyqtgraph\n"
"mysql.connector\n\n"
"If Python is added to Path, type: pip install <module> in your terminal " \
"to install the modules.")
exit()
data_server = server.connect(
host="localhost",
user="root",
password="password"
)
data_server.autocommit = True
data_cursor = data_server.cursor(buffered=True)
def create_information_database():
"""Creates database to store all the information used by the app."""
create_query = "CREATE DATABASE paper_information_database"
data_cursor.execute(create_query)
use_information_database()
def use_information_database():
"""Sets the working database to paper_information_database."""
use_query = "USE paper_information_database"
data_cursor.execute(use_query)
def create_attendance_database():
"""Creates database to store all the attendance records."""
create_query = "CREATE DATABASE paper_attendance_database"
data_cursor.execute(create_query)
use_attendance_database()
def use_attendance_database():
"""Sets the working database to paper_attendance_database."""
use_query = "USE paper_attendance_database"
data_cursor.execute(use_query)
def create_reports_database():
"""Creates database to store all the attendance reports."""
create_query = "CREATE DATABASE paper_reports_database"
data_cursor.execute(create_query)
use_reports_database()
def use_reports_database():
"""Sets the working database to paper_reports_database."""
use_query = "USE paper_reports_database"
data_cursor.execute(use_query)
def create_data_table():
"""Creates table to store the PIN and Class Name provided by the user."""
use_information_database()
create_query = "CREATE TABLE paper_data_table (" \
"pin varchar(4), " \
"class_name varchar(20)" \
")"
data_cursor.execute(create_query)
def create_student_list_table():
"""Creates table to store the name of all the students of a class."""
use_information_database()
create_table_query = "CREATE TABLE paper_student_list_table (" \
"name varchar(40) PRIMARY KEY" \
")"
data_cursor.execute(create_table_query)
def create_settings_table():
"""Creates table to store all the setting values."""
use_information_database()
create_query = "CREATE TABLE paper_settings_table (" \
"check_present varchar(1), " \
"minimum_attendance int(3), " \
"backup_frequency int(1), " \
"backup_date date" \
")"
data_cursor.execute(create_query)
set_default_settings_query = "INSERT INTO paper_settings_table " \
"VALUES ('N', 75, 2, date_add(curdate(), interval 30 day))"
data_cursor.execute(set_default_settings_query)
def create_attendance_table(date: str):
"""
Creates table to store the daily attendance record.
:param date: Date for creating attendance table.
"""
use_attendance_database()
create_query = f"CREATE TABLE {date} (" \
"name varchar(40) PRIMARY KEY, " \
"state varchar(1)" \
")"
data_cursor.execute(create_query)
def create_student_report_table():
"""Creates table to store individual student attendance report."""
use_reports_database()
create_query = "CREATE TABLE paper_student_report_table (" \
"name varchar(40) PRIMARY KEY, " \
"total_days int(3), " \
"days_present int(3)" \
")"
data_cursor.execute(create_query)
def create_daily_report_table():
"""Creates table to store daily attendance report."""
use_reports_database()
create_query = "CREATE TABLE paper_daily_report_table (" \
"id int AUTO_INCREMENT PRIMARY KEY, " \
"date varchar(10) UNIQUE, " \
"present int(3), " \
"absent int(3), " \
"attendance_percentage decimal(4, 1)" \
")"
data_cursor.execute(create_query)
def set_class_name(class_name: str):
"""Updates the Class Name when it is renamed."""
use_information_database()
set_class_name_query = f"UPDATE paper_data_table SET class_name = '{class_name}'"
data_cursor.execute(set_class_name_query)
def get_class_name() -> str or None:
"""
Gets the name of the Class.
:return: Class name.
"""
use_information_database()
try:
get_class_name_query = "SELECT class_name FROM paper_data_table"
data_cursor.execute(get_class_name_query)
class_name = data_cursor.fetchone()[0]
return class_name
except TypeError:
return None
def get_date() -> tuple[str, list[int]]:
"""
Makes the current date available in 'DD_MM_YYYY' and [DD, MM, YYYY] format.
:return: A tuple containing today's date in string and list format.
"""
raw_date = strftime("%d-%m-%Y")
raw_date = raw_date.split("-")
# raw_date is used to set date on date_edit UI elements
raw_date = [int(raw_date[i]) for i in range(len(raw_date))]
date = "_".join(str(i) for i in raw_date)
return date, raw_date
def get_pin() -> str or None:
"""
Gets the current pin if it is available.
:return: The current pin, if available, else None.
"""
use_information_database()
try:
get_pin_query = "SELECT pin FROM paper_data_table"
data_cursor.execute(get_pin_query)
pin = data_cursor.fetchone()[0]
return pin
except TypeError:
return None
def get_settings() -> dict:
"""
Prepares list of current values for the application settings.
:return: Dictionary containing settings and their corresponding values.
"""
use_information_database()
# Try to get settings.
try:
get_settings_query = "SELECT * FROM paper_settings_table"
data_cursor.execute(get_settings_query)
# If an error occurs, it means that the table does not exist.
# So create the settings table and get settings.
except server.ProgrammingError:
create_settings_table()
get_settings_query = "SELECT * FROM paper_settings_table"
data_cursor.execute(get_settings_query)
settings = data_cursor.fetchall()
current_settings = {
"check present": settings[0][0],
"minimum attendance": settings[0][1],
"backup frequency": settings[0][2],
"backup date": settings[0][3]
}
return current_settings
def get_student_list(date: str = None) -> list:
"""
Prepares list of students studying in the Class on the provided date.
:param date: Date for preparing student list.
:return: List of students.
"""
student_list = list()
# date = None means: get student list for today's date.
if date is None:
# Try to get the list of students.
try:
use_information_database()
get_student_list_query = "SELECT * FROM paper_student_list_table"
data_cursor.execute(get_student_list_query)
data = data_cursor.fetchall()
# If an error occurs, it means that the table is not created till now.
# So return the empty student list.
except server.ProgrammingError:
return student_list
else:
# Try to get student list from past attendance records.
try:
use_attendance_database()
get_student_list_from_records_query = f"SELECT name FROM {date}"
data_cursor.execute(get_student_list_from_records_query)
data = data_cursor.fetchall()
# If an error occurs, it means that the attendance record for the
# provided date does not exist.
# So return the empty student list.
except server.ProgrammingError:
return student_list
# If no error occurred, prepare student list from the data received from the database.
for student in data:
student_list.append(student[0])
return student_list
def get_past_attendance_records() -> list:
"""
Prepares list of all the tables present inside "paper_attendance_database".
Each table is a day's attendance record.
:return: List of all past attendance record tables.
"""
attendance_records = list()
# Get the list of all tables present inside the "paper_attendance_database" database.
get_table_list_query = 'SELECT table_name FROM information_schema.tables ' \
'WHERE table_schema = "paper_attendance_database"'
data_cursor.execute(get_table_list_query)
data = data_cursor.fetchall()
for record in data:
attendance_records.append(record[0])
return attendance_records
def rename_student_in_past_records(old_name: str, new_name: str):
"""
Renames student in past attendance records after a naming change.
:param old_name: Old name of the student.
:param new_name: New name of the student.
"""
# Try renaming student in today's attendance record.
try:
use_attendance_database()
today = get_date()[0]
update_query = f"UPDATE {today} SET name = '{new_name}' WHERE name = '{old_name}'"
data_cursor.execute(update_query)
# If an error occurs, it means that the attendance has not been recorded for the day.
# Do nothing.
except server.ProgrammingError:
pass
# Rename the student in past attendance records.
attendance_records = get_past_attendance_records()
for record in attendance_records:
# Try renaming the student in all the past attendance records.
try:
update_name_in_past_record_table_query = f"UPDATE {record} " \
f"SET name = '{new_name}' " \
f"WHERE name = '{old_name}'"
data_cursor.execute(update_name_in_past_record_table_query)
# If an error occurs, it means that the student was not a part of the class till the
# corresponding date.
# Do nothing.
except server.ProgrammingError:
pass
def export_data():
"""Exports attendance data to external file on hard-disk."""
export_data_dialog = ExportDataDialog()
export_data_dialog.exec()
def write_daily_report(date: str):
"""
Prepares/ updates attendance report for the provided date.
:param date: The date for which report should be prepared.
"""
use_attendance_database()
# Get the number of students present on the provided date.
get_present_count_query = f"SELECT count(*) FROM {date} WHERE state = 'P'"
data_cursor.execute(get_present_count_query)
present_count = data_cursor.fetchone()[0]
# Get the number of students absent on the provided date.
get_absent_count_query = f"SELECT count(*) FROM {date} WHERE state = 'A'"
data_cursor.execute(get_absent_count_query)
absent_count = data_cursor.fetchone()[0]
# The total number of students is calculated as (present_count + absent_count) to get
# the total number of students on the provided date.
# Current total number of students may not always match with total number of students
# on a given date back in time.
# This is done to facilitate displaying report of a past date.
attendance_percentage = round((present_count / (present_count + absent_count)) * 100, 2)
# Try creating the daily report table.
try:
create_daily_report_table()
# If an error occurs, it means that the table already exists.
# Do nothing.
except server.ProgrammingError:
pass
use_reports_database()
# Try writing report with the given parameters for the provided date.
try:
write_report_query = "INSERT INTO paper_daily_report_table(date, present, absent, attendance_percentage) " \
f"VALUES ('{date}', {present_count}, {absent_count}, {attendance_percentage})"
data_cursor.execute(write_report_query)
# If an error occurs, it means that report data already exists for the provided date.
# So update the data for the provided date.
except server.IntegrityError:
update_report_query = f"UPDATE paper_daily_report_table " \
f"SET present = {present_count}, absent = {absent_count}, " \
f"attendance_percentage = {attendance_percentage} " \
f"WHERE date = '{date}'"
data_cursor.execute(update_report_query)
def write_student_report(attendance_record: dict):
"""
Prepares/ updates individual student attendance report.
:param attendance_record: The attendance record for the day.
"""
for student in attendance_record:
if attendance_record[student] == "P":
# Try adding report data for a "present" student. This will be done only when the student
# is a new admit.
try:
add_record_query = f"INSERT INTO paper_student_report_table VALUES ('{student}', 1, 1)"
data_cursor.execute(add_record_query)
# If an error occurs, it means that the student is an old student.
# So update her/ his report data.
except server.IntegrityError:
update_present_student_record_query = "UPDATE paper_student_report_table " \
"SET total_days = total_days + 1, " \
"days_present = days_present + 1 " \
f"WHERE name = '{student}'"
data_cursor.execute(update_present_student_record_query)
else:
# Try adding report data for an "absent" student. This will be done only when the student
# is a new admit.
try:
add_record_query = f"INSERT INTO paper_student_report_table VALUES ('{student}', 1, 0)"
data_cursor.execute(add_record_query)
# If an error occurs, it means that the student is an old student.
# So update her/ his report data.
except server.IntegrityError:
update_absent_student_record_query = "UPDATE paper_student_report_table " \
"SET total_days = total_days + 1 " \
f"WHERE name = '{student}'"
data_cursor.execute(update_absent_student_record_query)
class CreatePINDialog(QtWidgets.QDialog):
def __init__(self):
super().__init__()
uic.loadUi("src/layout/CreatePINDialog_ui.ui", self)
self._created = False
self.cancel_button.clicked.connect(self.close)
self.save_button.clicked.connect(self.set_pin)
def is_pin_created(self) -> bool:
"""
Tells whether the PIN is created or not.
:return: True if PIN is created, else False.
"""
return self._created
def set_pin(self):
"""Stores the provided PIN in database."""
provided_pin = self.create_pin_line_edit.text().strip()
if len(provided_pin) == 4:
use_information_database()
set_pin_query = f"INSERT INTO paper_data_table(PIN) VALUES ('{provided_pin}')"
data_cursor.execute(set_pin_query)
self._created = True
self.close()
pin_saved_message_dialog = PINSavedMessageDialog()
pin_saved_message_dialog.exec()
class UnlockAppDialog(QtWidgets.QDialog):
def __init__(self):
super().__init__()
uic.loadUi("src/layout/UnlockAppDialog_ui.ui", self)
self._valid = False
self.cancel_button.clicked.connect(self.close)
self.unlock_button.clicked.connect(self.check_pin)
def is_pin_valid(self) -> bool:
"""
Tells whether the entered PIN is authorized or not.
:return: True is PIN is authorized, else False.
"""
return self._valid
def check_pin(self):
"""Checks if the PIN provided by the user is correct."""
pin = get_pin()
provided_pin = self.enter_pin_line_edit.text().strip()
if provided_pin == pin:
self._valid = True
self.close()
else:
incorrect_pin_illustration = QtGui.QPixmap("src/drawables/icons8-wrong-pincode-96.png")
self.pin_check_illustration.setPixmap(incorrect_pin_illustration)
self.pinCheck_label.setText("Incorrect PIN")
class PINSavedMessageDialog(QtWidgets.QDialog):
def __init__(self):
super().__init__()
uic.loadUi("src/layout/PINSavedMessageDialog_ui.ui", self)
self.close_button.clicked.connect(self.close)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi("src/layout/MainWindow_ui.ui", self)
self.show()
self.today = get_date()[0]
# Try creating the "paper_information_database" database.
# Try creating the "paper_data_table" table within the database.
# This will be done only on the first run of the application.
try:
create_information_database()
create_data_table()
# If an error occurs, it means that the application was run before and
# the corresponding database and table exists.
# Do nothing.
except server.DatabaseError:
pass
# As the PIN is not created/ verified till now, disable:
# 1. Create Class button
# 2. Attendance tab
# 3. Reports tab
# 4. Settings tab
self.create_class_button.setEnabled(False)
self.options_tabWidget.setTabEnabled(1, False)
self.options_tabWidget.setTabEnabled(2, False)
self.options_tabWidget.setTabEnabled(3, False)
self.setup_about_screen()
# Authorize the user with the correct PIN.
self.authorize()
# If class name is not none, it means that a class is created.
# So set up the application to work.
if get_class_name() is not None:
self.setup()
def authorize(self):
"""Authorize user with correct PIN."""
pin = get_pin()
if pin is None:
create_pin_dialog = CreatePINDialog()
create_pin_dialog.exec()
pin_created = create_pin_dialog.is_pin_created()
if pin_created:
self.create_class_button.setEnabled(True)
self.create_class_button.clicked.connect(self.create_class)
else:
unlock_app_dialog = UnlockAppDialog()
unlock_app_dialog.exec()
is_valid_pin = unlock_app_dialog.is_pin_valid()
if is_valid_pin:
self.create_class_button.setEnabled(True)
self.create_class_button.clicked.connect(self.create_class)
def setup(self):
"""Performs all the necessary tasks after the PIN is verified and application starts."""
self.classTab_stackedWidget.setCurrentIndex(1)
self.options_tabWidget.setTabEnabled(1, True)
self.options_tabWidget.setTabEnabled(2, True)
self.options_tabWidget.setTabEnabled(3, True)
# Check whether the student list is empty or not.
if get_student_list():
# If student list is not empty, set the start up tab as the
# "Attendance" tab to mark attendance.
self.options_tabWidget.setCurrentIndex(1)
else:
# If it is empty, it means that no student is added in the class.
# In this case, set the start up tab as the "Class" tab to add
# students in the class.
self.options_tabWidget.setCurrentIndex(0)
self.setup_class_screen()
self.setup_attendance_screen()
self.setup_reports_screen()
self.setup_settings_screen()
# Try to set "paper_attendance_database" as the current working database.
# If no error occurs, it means that the database exists along with attendance
# records. So leave "Edit Data" and "Export Data" buttons in enabled state.
try:
use_attendance_database()
# If an error occurs, it means that the database does not exist.
# Hence, there are no attendance records.
# So disable "Edit Data" and "Export Data" buttons.
except server.ProgrammingError:
self.edit_data_button.setEnabled(False)
self.export_data_button.setEnabled(False)
def setup_class_screen(self):
"""Setup all the visual elements on "Class" screen."""
self.students_tree_widget.setHeaderLabels(["Roll", "Name"])
self.students_tree_widget.setColumnWidth(0, 40)
self.students_tree_widget.setColumnWidth(1, 80)
self.class_name_label.setText(get_class_name())
self.populate_student_list_on_class_screen()
self.set_student_count()
self.search_student_class_line_edit.textChanged.connect(self.search_student_in_student_list)
self.rename_class_button.clicked.connect(self.rename_class)
self.delete_class_button.clicked.connect(self.confirm_delete)
self.edit_class_button.clicked.connect(self.edit_class)
self.export_data_button.clicked.connect(export_data)
self.backup_data()
def setup_attendance_screen(self):
"""Setup all the visual elements on Attendance screen."""
self.search_student_attendance_line_edit.textChanged.connect(self.search_student_in_attendance_list)
self.edit_data_button.clicked.connect(self.show_edit_attendance_data_dialog)
self.edit_attendance_button.clicked.connect(self.show_edit_attendance_data_dialog)
self.date_label.setText(strftime("%d %B, %Y"))
# Try to get all data from today's attendance record.
# If no error occurs, set the "Attendance" tab to show
# that the attendance has been recorded for the day.
try:
use_attendance_database()
test_for_table_query = f"SELECT * FROM {self.today}"
data_cursor.execute(test_for_table_query)
self.attendance_stackedWidget.setCurrentIndex(1)
# If an error occurs, it means that the attendance has not been recorded for the day.
# So set the "Attendance" tab to take attendance.
except server.ProgrammingError:
self.attendance_stackedWidget.setCurrentIndex(0)
self.populate_student_list_on_attendance_screen()
self.mark_attendance_tree_widget.setHeaderLabels(["Present", "Roll", "Name"])
self.mark_attendance_tree_widget.setColumnWidth(0, 50)
self.mark_attendance_tree_widget.setColumnWidth(1, 40)
self.mark_attendance_tree_widget.setColumnWidth(2, 80)
self.save_button.clicked.connect(self.save_attendance)
self.clear_button.clicked.connect(self.clear_student_list_attendance_screen)
def setup_reports_screen(self):
"""Setup all the visual elements on Reports screen."""
self.graph_widget.setBackground("w")
self.graph_widget.setLabel("left", "Attendance Percentage")
self.graph_widget.setLabel("bottom", "Days")
self.graph_widget.showGrid(x=True, y=True)
self.graph_widget.setMenuEnabled(False)
self.graph_widget.setLimits(xMin=0, xMax=365, yMin=0, yMax=105, minXRange=10,
maxXRange=31, minYRange=10, maxYRange=105)
self.graph_widget.setRange(xRange=(1, 10), yRange=(1, 105))
self.graph_widget.setTitle("Class Attendance Percentage Over The Past Days", size="12pt")
raw_date = get_date()[1]
self.report_date_date_edit.setDate(QtCore.QDate(raw_date[2], raw_date[1], raw_date[0]))
self.get_report_button.clicked.connect(self.display_report)
self.display_report()
self.display_graph()
self.populate_individual_student_report_list()
def setup_settings_screen(self):
"""Setup all the visual elements on Settings screen."""
settings = get_settings()
if settings["check present"] == "Y":
self.check_present_check_box.setCheckState(QtCore.Qt.CheckState.Checked)
self.minimum_attendance_spin_box.setValue(settings["minimum attendance"])
self.save_new_pin_button.clicked.connect(self.save_new_pin)
self.backup_frequency_combo_box.addItems(["Daily", "Weekly", "Monthly"])
self.backup_frequency_combo_box.setCurrentIndex(settings["backup frequency"])
self.save_settings_button.clicked.connect(self.save_settings)
self.reset_to_default_button.clicked.connect(self.reset_settings)
def setup_about_screen(self):
"""Setup all the visual elements on About screen."""
self.credits_button.clicked.connect(self.display_credits)
self.license_button.clicked.connect(self.display_license)
def populate_student_list_on_class_screen(self):
"""Populates the list of students on Class screen."""
self.students_tree_widget.clear()
student_list = get_student_list()
for i in range(len(student_list)):
student_name = student_list[i]
self.students_tree_widget.addTopLevelItem(
QtWidgets.QTreeWidgetItem([str(i + 1), student_name])
)
self.set_student_count()
def get_children_of_students_tree_widget(self) -> list:
"""
Prepares the list of children present inside the parent element
of the students_tree_widget.
Here, children refers to the sub-elements of the primary element
(parent - the invisible root item) inside the students_tree_widget.
:return: List containing children of the parent element.
"""
parent = self.students_tree_widget.invisibleRootItem()
child_count = parent.childCount()
children = list()
for i in range(child_count):
children.append(parent.child(i))
return children
def search_student_in_student_list(self):
"""Searches and displays the required student in student list on Class screen."""
children = self.get_children_of_students_tree_widget()
for child in children:
if self.search_student_class_line_edit.text().lower().strip() == child.text(0).lower() \
or self.search_student_class_line_edit.text().lower().strip() in child.text(1).lower():
child.setHidden(False)
else:
child.setHidden(True)
def set_student_count(self):
"""Sets the number of students on Class screen."""
student_count = self._get_student_count()
if student_count == 1:
self.student_count_label.setText(str(student_count) + " student")
else:
self.student_count_label.setText(str(student_count) + " students")
def _get_student_count(self) -> int:
"""
Helper function for set_student_count().
:return: Total number of students in Class.
"""
return self.students_tree_widget.topLevelItemCount()
def create_class(self):
"""Displays the dialog to create a new empty class."""
create_class_dialog = CreateClassDialog()
create_class_dialog.exec()
self.setup()
def rename_class(self):
"""Displays the dialog to rename class."""
rename_class_dialog = RenameClassDialog()
rename_class_dialog.exec()
self.class_name_label.setText(get_class_name())
@staticmethod
def confirm_delete():
"""Asks for confirmation before deleting the class."""
delete_class_confirmation_dialog = DeleteClassConfirmationDialog()
delete_class_confirmation_dialog.exec()
def edit_class(self):
"""Displays the dialog to add, remove and rename students in the class."""
edit_class_dialog = EditClassDialog()
edit_class_dialog.exec()
if edit_class_dialog.get_action() == "add":
self.populate_student_list_on_class_screen()
self.populate_student_list_on_attendance_screen()
elif edit_class_dialog.get_action() == "remove":
self.populate_student_list_on_class_screen()
self.populate_student_list_on_attendance_screen()
self.populate_individual_student_report_list()
elif edit_class_dialog.get_action() == "rename":
self.populate_student_list_on_class_screen()
self.populate_student_list_on_attendance_screen()
self.display_report()
self.populate_individual_student_report_list()
@staticmethod
def backup_data():
"""Exports attendance data to the required files and updates the backup date."""
settings = get_settings()
if strftime("%Y-%m-%d") == str(settings["backup date"]):
export_data()
use_information_database()
update_backup_date_query = "UPDATE paper_settings_table " \
"SET backup_date = date_add(" \
f"curdate(), interval {settings['backup frequency']} day" \
")"
data_cursor.execute(update_backup_date_query)
def populate_student_list_on_attendance_screen(self):
"""Populates and displays the list of students on the Attendance screen."""
student_list = get_student_list()
settings = get_settings()
self.mark_attendance_tree_widget.clear()
# If the student list is not empty, enable the "Save" and "Clear" buttons.
if student_list:
self.save_button.setEnabled(True)
self.clear_button.setEnabled(True)
# If the student list is empty, then there is no use of the "Save" and "Clear"
# buttons. So disable them.
else:
self.save_button.setEnabled(False)
self.clear_button.setEnabled(False)
# If the user has enabled the setting to "show all students marked as present", then
# populate the student list on attendance screen with all checkboxes checked.
if settings["check present"] == "Y":
for i in range(len(student_list)):
student_name = student_list[i]
item = QtWidgets.QTreeWidgetItem(
self.mark_attendance_tree_widget,
["", str(i + 1), student_name]
)
# Check all the checkboxes.
item.setCheckState(0, QtCore.Qt.CheckState.Checked)
self.mark_attendance_tree_widget.addTopLevelItem(item)
# If the setting is disabled, then populate the student list with all checkboxes unchecked.
else:
for i in range(len(student_list)):
student_name = student_list[i]
item = QtWidgets.QTreeWidgetItem(self.mark_attendance_tree_widget, ["", str(i + 1), student_name])
# Uncheck all the checkboxes.
item.setCheckState(0, QtCore.Qt.CheckState.Unchecked)
self.mark_attendance_tree_widget.addTopLevelItem(item)
def get_children_of_attendance_tree_widget(self) -> list:
"""
Prepares the list of children present inside the parent element
of the mark_attendance_tree_widget.
Here, children refers to the sub-elements of the primary element
(parent - the invisible root item) inside the mark_attendance_tree_widget.
:return: List containing children of the parent element.
"""
parent = self.mark_attendance_tree_widget.invisibleRootItem()
child_count = parent.childCount()
children = list()
for i in range(child_count):
children.append(parent.child(i))
return children
def search_student_in_attendance_list(self):
"""Searches and displays the required student in attendance list on Attendance screen."""
children = self.get_children_of_attendance_tree_widget()
for child in children:
if self.search_student_attendance_line_edit.text().lower().strip() == child.text(1).lower() \
or self.search_student_attendance_line_edit.text().lower().strip() in child.text(2).lower():
child.setHidden(False)
else:
child.setHidden(True)
def clear_student_list_attendance_screen(self):
"""Clears the recorded attendance to start over."""
student_list = get_student_list()
self.mark_attendance_tree_widget.clear()
for i in range(len(student_list)):
student_name = student_list[i]
item = QtWidgets.QTreeWidgetItem(self.mark_attendance_tree_widget, ["", str(i + 1), student_name])
item.setCheckState(0, QtCore.Qt.CheckState.Unchecked)
self.mark_attendance_tree_widget.addTopLevelItem(item)
def save_attendance(self):
"""Saves the recorded attendance data for the day."""
save_attendance_confirmation_dialog = SaveAttendanceConfirmationDialog()
save_attendance_confirmation_dialog.exec()
action = save_attendance_confirmation_dialog.get_action()
if action == "save":
date = get_date()[0]
# Try creating the database "paper_attendance_database". This will be done
# only when the attendance is recorded for the first time.
try:
create_attendance_database()
# If an error occurs, it means that the database already exists and this is
# not the first attendance record.
# Do nothing.
except server.DatabaseError:
pass
# Try creating a table inside "paper_attendance_database" with
# today's date in DD_MM_YYYY format as name.
try:
create_attendance_table(date)
# If an error occurs, it means that the table already exists and the user
# is editing today's attendance data.
except server.ProgrammingError:
pass
parent = self.mark_attendance_tree_widget.invisibleRootItem()
children = parent.childCount()
attendance_record = dict()
for i in range(children):
current_child = parent.child(i)
if current_child.checkState(0) == QtCore.Qt.CheckState.Checked:
attendance_record[current_child.text(2)] = "P"
else:
attendance_record[current_child.text(2)] = "A"
for student in attendance_record:
use_attendance_database()
record_attendance_query = f"INSERT INTO {self.today} " \
f"VALUES ('{student}', '{attendance_record[student]}')"
data_cursor.execute(record_attendance_query)
self.write_attendance_report(attendance_record)
self.attendance_stackedWidget.setCurrentIndex(1)
def show_edit_attendance_data_dialog(self):
"""Displays the dialog for editing attendance data."""
edit_attendance_data_dialog = EditAttendanceDataDialog()
edit_attendance_data_dialog.exec()
action = edit_attendance_data_dialog.get_action()
if action == "edit attendance":
self.display_report()
self.display_graph()
self.populate_individual_student_report_list()
def write_attendance_report(self, attendance_record):
"""Writes all attendance reports to the database."""
# Try to set "paper_reports_database" as the current working database.
try:
use_reports_database()
# If an error occurs, it means that the database does not exist.
# So create the database. Inside the database, create the
# "paper_student_report_table" table.
# This will be done only when the attendance is recorded for
# the first time.