forked from UWIBestGroupEver/Comp3613Assignment2
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwsgi.py
More file actions
1724 lines (1461 loc) · 67.6 KB
/
wsgi.py
File metadata and controls
1724 lines (1461 loc) · 67.6 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
import re
import click
import pytest
import sys
from datetime import datetime
from flask.cli import with_appcontext, AppGroup
import warnings
from rich.table import Table
from rich.console import Console
warnings.filterwarnings("ignore", message="pkg_resources is deprecated")
from App.main import create_app
from App.database import db, get_migrate
from App.models import Student, Staff, RequestHistory, LoggedHoursHistory
from App.controllers import get_all_users, initialize
from App.controllers.loggedHoursHistory_controller import *
from App.controllers.student_controller import *
from App.controllers.staff_controller import *
from App.controllers.milestone_controller import *
from App.controllers.app_controller import *
from App.controllers.activityhistory_controller import *
from App.controllers.request_controller import *
from App.controllers.accolade_controller import *
from App.controllers.date_controller import *
from App.controllers.leaderboard_controller import *
# Your Flask app code here
'''APP COMMANDS(TESTING PURPOSES)'''
# This commands file allow you to create convenient CLI commands for testing controllers
app = create_app()
migrate = get_migrate(app)
# This command creates and initializes the database
@app.cli.command("init", help="Creates and initializes the database")
def init():
initialize()
print('database initialized')
'''USER COMMANDS'''
user_cli = AppGroup('user', help='User management commands')
# List all users in the database
@user_cli.command("list", help="List all users in the database")
def list_users():
print("\n")
try:
users = get_all_users()
if not users:
print("No users found.")
return
console = Console()
table = Table(title="All Users")
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Username", style="magenta")
table.add_column("Email", style="green")
table.add_column("Type", style="yellow")
for user in users:
try:
if user.role == 'student':
user_type = "Student"
user_id = user.student_id
elif user.role == 'staff':
user_type = "Staff"
user_id = user.staff_id
else:
user_type = "Unknown"
user_id = user.user_id
table.add_row(
str(user_id),
user.username if hasattr(user, 'username') else "N/A",
user.email if hasattr(user, 'email') else "N/A",
user_type
)
except:
# Handle case where specific record is deleted but user remains
table.add_row(
str(user.user_id),
user.username if hasattr(user, 'username') else "N/A",
user.email if hasattr(user, 'email') else "N/A",
f"Deleted {user.role.capitalize()}"
)
console.print(table)
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
app.cli.add_command(user_cli)
'''STUDENT COMMANDS'''
student_cli = AppGroup('student', help='Student object commands')
#Command to create a new student (name, email)
@student_cli.command("create", help="Create a new student")
@click.argument("username", type=str)
@click.argument("email", type=str)
@click.argument("password", type=str)
def create_student(username, email, password):
print("\n")
try:
if "@" not in email:
raise ValueError("Invalid email address.")
student = register_student(username, email, password)
console = Console()
table = Table(title="Student Created Successfully")
table.add_column("Field", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("ID", str(student.student_id))
table.add_row("Username", student.username)
table.add_row("Email", student.email)
table.add_row("Role", "student")
console.print(table)
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
# Command to search students by field (name, email, or ID)
@student_cli.command("search", help="Search for a student by name, email, or ID")
@click.argument("query")
def search_student(query):
print("\n")
try:
student = query_router(query)
if not student:
print("No student found.")
return
console = Console()
table = Table(title="Student Search Result")
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Username", style="magenta")
table.add_column("Email", style="green")
table.add_row(
str(student.student_id),
student.username if hasattr(student, 'username') else "N/A",
student.email if hasattr(student, 'email') else "N/A"
)
console.print(table)
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
#Command to update a student's information (student_id, name, email, password) via CLI options
@student_cli.command("update", help="Update a student's information")
@click.argument("student_id", type=int)
@click.option("--username", type=str, default=None, help="New username for the student")
@click.option("--email", type=str, default=None, help="New email for the student")
@click.option("--password", type=str, default=None, help="New password for the student")
def update_student_command(student_id, username, email, password):
print("\n")
try:
student = Student.query.get(student_id)
if not student:
print(f"Error: Student with ID {student_id} not found.")
print("\n")
return
updated_student = update_student_info(
student_id,
username if username else None,
email if email else None,
password if password else None
)
console = Console()
table = Table(title="Student Updated Successfully")
table.add_column("Field", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("ID", str(updated_student.student_id))
table.add_row("Username", updated_student.username)
table.add_row("Email", updated_student.email)
table.add_row("Role", "student")
console.print(table)
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
#Command to view total hours for a student (student_id)
@student_cli.command("hours", help="View total hours for a student")
@click.argument("student_id", type=int)
def hours(student_id):
print("\n")
try:
student = get_hours(student_id)
name,total_hours = student
print(f"Total hours for {name}: {total_hours}")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
# List all students in the database
@student_cli.command("list", help="List all students in the database")
def list_students():
print("\n")
try:
students = get_all_users()
if not students:
print("No students found.")
return
console = Console()
table = Table(title="All Students")
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Username", style="magenta")
table.add_column("Email", style="green")
for user in students:
if user.role == 'student':
try:
table.add_row(
str(user.student_id),
user.username if hasattr(user, 'username') else "N/A",
user.email if hasattr(user, 'email') else "N/A"
)
except:
# Skip if student record deleted
pass
console.print(table)
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
app.cli.add_command(student_cli) # add the group to the cli
#Command to delete a student by id (student_id)
@student_cli.command("delete", help="Delete a student by ID")
@click.argument("student_id", type=int)
def delete_student_command(student_id):
try:
delete_student(student_id)
print(f"Student with ID {student_id} has been deleted.")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
#Command to delete ALL students (for testing purposes)
@student_cli.command("droptable", help="Delete ALL students (testing purposes only)")
@click.confirmation_option(prompt="⚠️ Are you sure you want to delete ALL students? This action cannot be undone.")
def delete_all_students_command():
try:
print("Nuking all students... 💣")
num_deleted = delete_all_students()
print(f"All {num_deleted} students are gone. 💥")
except Exception as e:
print(f"An error occurred: {e}")
'''STAFF COMMANDS'''
staff_cli = AppGroup('staff', help='Staff object commands')
#Command to create a new staff member (name, email)
@staff_cli.command("create", help="Create a new staff member")
@click.argument("username", type=str)
@click.argument("email", type=str)
@click.argument("password", type=str)
def create_staff(username, email, password):
print("\n")
try:
if "@" not in email:
raise ValueError("Invalid email address.")
staff = register_staff(username, email, password)
console = Console()
table = Table(title="Staff Member Created Successfully")
table.add_column("Field", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("ID", str(staff.staff_id))
table.add_row("Username", staff.username)
table.add_row("Email", staff.email)
table.add_row("Role", "staff")
console.print(table)
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
# Command to search staff by field (name, email, or ID)
@staff_cli.command("search", help="Search for a staff member by name, email, or ID")
@click.argument("query")
def search_staff(query):
print("\n")
try:
staff = staff_query_router(query)
if not staff:
print("No staff member found.")
return
console = Console()
table = Table(title="Staff Search Result")
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Username", style="magenta")
table.add_column("Email", style="green")
table.add_row(
str(staff.staff_id),
staff.username if hasattr(staff, 'username') else "N/A",
staff.email if hasattr(staff, 'email') else "N/A"
)
console.print(table)
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
# Command to update a staff member's information (staff_id, name, email, password) via CLI options
@staff_cli.command("update", help="Update a staff member's information")
@click.argument("staff_id", type=int)
@click.option("--username", type=str, default=None, help="New username for the staff member")
@click.option("--email", type=str, default=None, help="New email for the staff member")
@click.option("--password", type=str, default=None, help="New password for the staff member")
def update_staff_command(staff_id, username, email, password):
print("\n")
try:
staff_obj = Staff.query.get(staff_id)
if not staff_obj:
print(f"Error: Staff with ID {staff_id} not found.")
print("\n")
return
updated_staff = update_staff_info(
staff_id,
username if username else None,
email if email else None,
password if password else None
)
console = Console()
table = Table(title="Staff Member Updated Successfully")
table.add_column("Field", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("ID", str(updated_staff.staff_id))
table.add_row("Username", updated_staff.username)
table.add_row("Email", updated_staff.email)
table.add_row("Role", "staff")
console.print(table)
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
# List all staff in the database
@staff_cli.command("list", help="List all staff in the database")
def list_staff():
print("\n")
try:
staff_list = get_all_users()
if not staff_list:
print("No staff members found.")
return
console = Console()
table = Table(title="All Staff Members")
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Username", style="magenta")
table.add_column("Email", style="green")
for user in staff_list:
if user.role == 'staff':
try:
table.add_row(
str(user.staff_id),
user.username if hasattr(user, 'username') else "N/A",
user.email if hasattr(user, 'email') else "N/A"
)
except:
# Skip if staff record deleted
pass
console.print(table)
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
app.cli.add_command(staff_cli) # add the group to the cli
# Command to delete a staff member by id (staff_id)
@staff_cli.command("delete", help="Delete a staff member by ID")
@click.argument("staff_id", type=int)
def delete_staff_command(staff_id):
try:
delete_staff(staff_id)
print(f"Staff member with ID {staff_id} has been deleted.")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
# Command to delete ALL staff members (for testing purposes)
@staff_cli.command("droptable", help="Delete ALL staff members (testing purposes only)")
@click.confirmation_option(prompt="⚠️ Are you sure you want to delete ALL staff members? This action cannot be undone.")
def delete_all_staff_command():
try:
print("Nuking all staff members... 💣")
num_deleted = delete_all_staff()
print(f"All {num_deleted} staff members are gone. 💥")
except Exception as e:
print(f"An error occurred: {e}")
'''REQUEST COMMANDS'''
request_cli = AppGroup('request', help='Request object commands')
#Command to create a new request for a student (student_id, service, staff_id, hours, date_completed)
@request_cli.command("create", help="Create a new service hour request via command line options")
@click.argument("student_id", type=int)
@click.argument("service", type=str)
@click.argument("staff_id", type=int)
@click.argument("hours", type=float)
@click.argument("date", type=str)
@with_appcontext
def create_request_command_options(student_id, service, staff_id, hours, date):
print("\n")
try:
request, message = create_request(student_id, service, staff_id, hours, date)
if request:
console = Console()
table = Table(title="Request Created Successfully")
table.add_column("Field", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("Request ID", str(request.id))
table.add_row("Service", request.service if hasattr(request, 'service') else "N/A")
table.add_row("Hours", str(request.hours))
table.add_row("Status", request.status)
table.add_row("Message", message)
console.print(table)
else:
print(f"Error: {message}")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
# Command to search requests by student_id, service, date, staff_id, or status
@request_cli.command("search", help="Search requests by student_id, service, date_completed, staff_id, or status")
@click.option("--student_id", type=int, default=None, help="Student ID to filter requests")
@click.option("--service", type=str, default=None, help="Service description to search for")
@click.option("--date", type=str, default=None, help="Date completed (YYYY-MM-DD) to filter requests")
@click.option("--staff_id", type=int, default=None, help="Staff ID to filter requests")
@click.option("--status", type=click.Choice(["pending", "approved", "denied"], case_sensitive=False), default=None, help="Status to filter requests (pending, approved, denied)")
@with_appcontext
def search_request_command(student_id, service, date, staff_id, status):
try:
if student_id is None and service is None and date is None and staff_id is None and status is None:
print("Error: At least one search criterion (--student_id, --service, --date, --staff_id, or --status) must be provided.")
return
requests, error = search_requests(student_id=student_id, service=service, date=date, staff_id=staff_id, status=status)
if error:
print(f"Error: {error}")
return
if not requests:
print("No requests found matching the criteria.")
return
console = Console()
table = Table(title="Search Results")
table.add_column("Request ID", style="cyan", no_wrap=True)
table.add_column("Student", style="magenta")
table.add_column("Service", style="green")
table.add_column("Hours", style="yellow")
table.add_column("Status", style="blue")
table.add_column("Staff ID", style="white")
table.add_column("Date", style="red")
for req in requests:
student = Student.query.get(req.student_id)
student_name = student.username if student else "Unknown"
staff = Staff.query.get(req.staff_id)
staff_name = staff.username if staff else f"Staff {req.staff_id}"
table.add_row(
str(req.id),
student_name,
req.service if hasattr(req, 'service') else "N/A",
str(req.hours),
req.status,
staff_name,
str(req.date_completed.date()) if hasattr(req, 'date_completed') else "N/A"
)
console.print(table)
except Exception as e:
print(f"An error occurred during search: {e}")
@request_cli.command("update", help="Update a request's attributes (student_id, service, hours, staff_id)")
@click.argument("request_id", type=int)
@click.option("--student_id", type=int, default=None, help="New Student ID")
@click.option("--service", type=str, default=None, help="New Service description")
@click.option("--hours", type=float, default=None, help="New Hours value")
@click.option("--staff_id", type=int, default=None, help="New Staff ID")
@with_appcontext
def update_request_command(request_id, student_id, service, hours, staff_id):
print("\n")
if not student_id and not service and not hours and not staff_id:
print("Error: At least one attribute (--student_id, --service, --hours, --staff_id) must be provided.")
print("\n")
return
try:
req = RequestHistory.query.get(request_id)
if not req:
print(f"Error: Request with ID {request_id} not found.")
print("\n")
return
request, message = update_request_entry(request_id, student_id, service, hours, staff_id=staff_id)
if request:
console = Console()
table = Table(title="Request Updated Successfully")
table.add_column("Field", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("Request ID", str(request.id))
table.add_row("Service", request.service if hasattr(request, 'service') else "N/A")
table.add_row("Hours", str(request.hours))
table.add_row("Status", request.status)
table.add_row("Message", message)
console.print(table)
else:
print(f"Error: {message}")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
#Command for staff to approve a student's request (staff_id, request_id)
#Once approved it is added to logged hours database
@request_cli.command("approve", help="Staff approves a student's request")
@click.argument("staff_id", type=int)
@click.argument("request_id", type=int)
def approveRequest(staff_id, request_id):
print("\n")
try:
results = process_request_approval(staff_id, request_id)
req=results['request']
student_name=results['student_name']
staff_name=results['staff_name']
logged=results['logged_hours']
if logged:
console = Console()
table = Table(title="Request Approved Successfully")
table.add_column("Field", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("Request ID", str(request_id))
table.add_row("Hours", str(req.hours))
table.add_row("Student", student_name)
table.add_row("Approved by", f"{staff_name} (ID: {staff_id})")
table.add_row("Logged Hours ID", str(logged.id))
console.print(table)
else:
print(f"Request {request_id} for {req.hours} hours made by {student_name} could not be approved (Already Processed).")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
# Command for staff to deny a student's request (staff_id, request_id)
#change request status to denied, no logged hours created
@request_cli.command("deny", help="Staff denies a student's request")
@click.argument("staff_id", type=int)
@click.argument("request_id", type=int)
def denyRequest(staff_id, request_id):
print("\n")
try:
results = process_request_denial(staff_id, request_id)
req=results['request']
student_name=results['student_name']
staff_name=results['staff_name']
success=results['denial_successful']
if success:
print(f"Request {request_id} for {req.hours} hours made by {student_name} denied by Staff {staff_name} (ID: {staff_id}).")
else:
print(f"Request {request_id} for {req.hours} hours made by {student_name} could not be denied (Already Processed).")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
# List requests in the database with optional status filter
@request_cli.command("list", help="List requests in the database (optionally filter by status)")
@click.option("--status", type=click.Choice(["all", "approved", "pending", "denied"], case_sensitive=False), default="all", help="Filter by request status (default: all)")
def list_requests(status):
print("\n")
try:
if status.lower() == "all":
requests = RequestHistory.query.all()
title = "All Requests"
else:
requests = RequestHistory.query.filter_by(status=status.lower()).all()
title = f"{status.capitalize()} Requests"
if not requests:
print(f"No {title.lower()} found.")
return
console = Console()
table = Table(title=title)
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Student ID", style="magenta")
table.add_column("Service", style="green")
table.add_column("Hours", style="yellow")
table.add_column("Status", style="blue")
table.add_column("Date", style="white")
for request in requests:
table.add_row(
str(request.id),
str(request.student_id),
request.service if hasattr(request, 'service') else "N/A",
str(request.hours),
request.status,
str(request.date_completed.date()) if hasattr(request, 'date_completed') else "N/A"
)
console.print(table)
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
app.cli.add_command(request_cli)
# Command to delete a request by ID
@request_cli.command("delete", help="Delete a service hour request by ID")
@click.argument("request_id", type=int)
def delete_request(request_id):
print("\n")
try:
success, message = delete_request_entry(request_id)
if success:
print(f"Success: {message}")
else:
print(f"Error: {message}")
except ValueError:
print("Error: Request ID must be an integer.")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
#Command to drop request table (all request records and associated activity records)
@request_cli.command("droptable", help="Drops all request records from the database (WARNING: IRREVERSIBLE)")
@click.confirmation_option(prompt="Are you sure you want to delete ALL request records? This cannot be undone")
@with_appcontext
def drop_request_table_command():
print("\n")
try:
result, error = drop_request_table()
if error:
print(f"Error: {error}")
print("\n")
return
print(f"Request table dropped successfully!")
print(f"Requests deleted: {result['requests_deleted']}")
print(f"Associated activity records cleaned up")
print(f"\nAll request records have been permanently removed from the database.")
except Exception as e:
print(f"An error occurred during drop operation: {e}")
print("\n")
'''LOGGED HOURS COMMANDS'''
logged_hours_cli = AppGroup('loggedhours', help='Logged hours commands')
# Command to create a logged hours entry
@logged_hours_cli.command("create", help="Create a logged hours entry")
@click.argument("student_id", type=int)
@click.argument("staff_id", type=int)
@click.argument("hours", type=float)
@click.argument("service", type=str)
@click.argument("date_completed", type=str)
def create_logged_hours_command(student_id, staff_id, hours, service, date_completed):
print("\n")
try:
# create_logged_hours now requires (student_id, staff_id, hours, service, date_completed)
log = create_logged_hours(student_id, staff_id, hours, service, date_completed)
console = Console()
table = Table(title="Logged Hours Entry Created Successfully")
table.add_column("Field", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("ID", str(log.id))
table.add_row("Student ID", str(log.student_id))
table.add_row("Staff ID", str(log.staff_id))
table.add_row("Hours", str(log.hours))
table.add_row("Service", log.service)
table.add_row("Date Completed", str(log.date_completed))
console.print(table)
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
# Command to search logged hours by student-id, staff-id, or date
@logged_hours_cli.command("search", help="Search logged hours by student-id, staff-id, date or service string. Dates follow YYYY-MM-DD format. Date ranges use YYYY-MM-DD:YYYY-MM-DD format.")
@click.argument("query")
def search_logged_hours_command(query):
search_type = detect_query_type(query)
try:
results = search_logged_hours(query, search_type)
if not results:
print(f"No logged hours entries found for {search_type} '{query}'.")
return
console = Console()
table = Table(title=f"Search Results - {search_type}: {query}")
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Student ID", style="magenta")
table.add_column("Staff ID", style="green")
table.add_column("Hours", style="yellow")
table.add_column("Service", style="white")
table.add_column("Date Completed", style="blue")
for log in results:
table.add_row(
str(log.id),
str(log.student_id),
str(log.staff_id),
str(log.hours),
log.service if hasattr(log, 'service') and log.service else "N/A",
str(log.date_completed.date()) if hasattr(log, 'date_completed') else "N/A"
)
console.print(table)
except Exception as e:
print(f"An error occurred: {e}")
# Command to update a logged hours entry by ID
@logged_hours_cli.command("update", help="Update a logged hours entry by ID")
@click.argument("log_id", type=int)
@click.option("--student_id", type=int, default=None, help="New student ID")
@click.option("--staff_id", type=int, default=None, help="New staff ID")
@click.option("--hours", type=float, default=None, help="New hours")
@click.option("--status", type=str, default=None, help="New status")
def update_logged_hours_command(log_id, student_id, staff_id, hours, status):
print("\n")
try:
log, error = update_logged_hours(log_id, student_id=student_id, staff_id=staff_id, hours=hours, status=status)
if error:
print(f"Error: {error}")
else:
console = Console()
table = Table(title="Logged Hours Entry Updated Successfully")
table.add_column("Field", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("ID", str(log.id))
table.add_row("Student ID", str(log.student_id))
table.add_row("Staff ID", str(log.staff_id))
table.add_row("Hours", str(log.hours))
table.add_row("Service", log.service)
table.add_row("Date Completed", str(log.date_completed))
console.print(table)
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
app.cli.add_command(logged_hours_cli)
# List all logged hours in the database
@logged_hours_cli.command("list", help="List all logged hours in the database")
def list_logged_hours():
print("\n")
try:
logged_hours = LoggedHoursHistory.query.all()
if not logged_hours:
print("No logged hours found.")
return
console = Console()
table = Table(title="All Logged Hours")
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Student ID", style="magenta")
table.add_column("Staff ID", style="green")
table.add_column("Hours", style="yellow")
table.add_column("Service", style="white")
table.add_column("Date Completed", style="blue")
for log in logged_hours:
table.add_row(
str(log.id),
str(log.student_id),
str(log.staff_id),
str(log.hours),
log.service if hasattr(log, 'service') and log.service else "N/A",
str(log.date_completed.date()) if hasattr(log, 'date_completed') else "N/A"
)
console.print(table)
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
# Command to delete a logged hours entry by ID
@logged_hours_cli.command("delete", help="Delete a logged hours entry by ID")
@click.argument("log_id", type=int)
def delete_logged_hours_command(log_id):
try:
delete_logged_hours(log_id)
print(f"Logged hours entry with ID {log_id} has been deleted.")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
# Command to delete ALL logged hours entries (for testing purposes)
@logged_hours_cli.command("droptable", help="Delete ALL logged hours entries (testing purposes only)")
@click.confirmation_option(prompt="⚠️ Are you sure you want to delete ALL logged hours entries? This action cannot be undone.")
def delete_all_logged_hours_command():
try:
print ("Nuking all logged hours entries... 💣")
num_deleted = delete_all_logged_hours()
print(f"All {num_deleted} logged hours entries have been deleted. 💥")
except Exception as e:
print(f"An error occurred: {e}")
'''ACCOLADE COMMANDS'''
accolade_cli = AppGroup('accolade', help='Accolade search commands')
#Command to create a new accolade (staff_id, description)
@accolade_cli.command("create", help="Create a new accolade")
@click.argument("staff_id", type=int)
@click.argument("description", type=str)
@with_appcontext
def create_accolade_command(staff_id, description):
print("\n")
try:
staff_obj = Staff.query.get(staff_id)
if not staff_obj:
print(f"Error: Staff with ID {staff_id} not found.")
print("\n")
return
accolade, error = create_accolade(staff_id, description)
if error:
print(f"Error: {error}")
else:
console = Console()
table = Table(title="Accolade Created Successfully")
table.add_column("Field", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("ID", str(accolade.id))
table.add_row("Description", description)
table.add_row("Created by Staff ID", str(staff_id))
console.print(table)
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
print("\n")
#Command to search accolades by id, staff_id, description, or student_id
@accolade_cli.command("search", help="Search accolades by id, staff_id, description, or student_id")
@click.option("--accolade_id", type=int, default=None, help="Accolade ID to search for")
@click.option("--staff_id", type=int, default=None, help="Staff ID who created the accolade")
@click.option("--description", type=str, default=None, help="Text to match in accolade description")
@click.option("--student_id", type=int, default=None, help="Student ID to filter accolades for")
@with_appcontext
def search_accolade_command(accolade_id, staff_id, description, student_id):
try:
accolades, error = search_accolades(
accolade_id=accolade_id,
staff_id=staff_id,
description=description,
student_id=student_id
)
if error:
print(f"Error: {error}")
return
if not accolades:
print("No accolades found matching the criteria.")
return
# If only student_id is provided, display just the descriptions in a table
if student_id is not None and accolade_id is None and staff_id is None and description is None:
console = Console()
table = Table(title=f"Accolades for Student {student_id}")
table.add_column("Description", style="magenta")
for accolade in accolades:
table.add_row(accolade.description)
console.print(table)
return
console = Console()
table = Table(title="Accolade Search Results")
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Description", style="magenta")
table.add_column("Staff ID", style="green")
table.add_column("Students Assigned", style="yellow")
for accolade in accolades:
num_students = len(accolade.students) if hasattr(accolade, 'students') else 0
table.add_row(
str(accolade.id),
accolade.description,
str(accolade.staff_id),
str(num_students)
)
console.print(table)
except Exception as e:
print(f"An error occurred during search: {e}")
#Command to update an accolade's attributes (staff_id, description)
@accolade_cli.command("update", help="Update an accolade's attributes")
@click.argument("accolade_id", type=int)
@click.option("--staff_id", type=int, default=None, help="New staff ID")
@click.option("--description", type=str, default=None, help="New description")
@with_appcontext
def update_accolade_command(accolade_id, staff_id, description):
print("\n")
if staff_id is None and description is None: