forked from msrathore-69781/Database-project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1313 lines (1088 loc) · 53.9 KB
/
app.py
File metadata and controls
1313 lines (1088 loc) · 53.9 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
from flask import Flask, render_template, request, redirect, url_for, session, flash , jsonify, redirect
import mysql.connector
# import re
from datetime import datetime
from authlib.integrations.flask_client import OAuth
from oauthlib.oauth2 import WebApplicationClient
app = Flask(__name__)
app.secret_key = 'xyzsdfg'
# MySQL Configuration
mysql_config = {
'host': 'localhost',
'user': 'root',
'password': 'Your_Password', #Enter ur password for root
'database': 'CLUB_MS'
}
try:
conn = mysql.connector.connect(**mysql_config)
print("Connected to MySQL database successfully!")
except mysql.connector.Error as e:
print(f"Error connecting to MySQL database: {e}")
conn = mysql.connector.connect(**mysql_config)
# app.config['SERVER_NAME'] = 'localhost:5000'
oauth = OAuth(app)
@app.route('/google/')
def google():
# Google Oauth Config
# Get client_id and client_secret from environment variables
# For developement purpose you can directly put it here inside double quotes
GOOGLE_CLIENT_ID = "134133495392-9i6jrrg4abg2q4qlmhptcl2t9nfclmj9.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET = "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"
CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'
oauth.register(
name='google',
client_id=GOOGLE_CLIENT_ID,
client_secret=GOOGLE_CLIENT_SECRET,
server_metadata_url=CONF_URL,
client_kwargs={
'scope': 'openid email profile'
}
)
# Redirect to google_auth function
redirect_uri = url_for('google_auth', _external=True)
return oauth.google.authorize_redirect(redirect_uri)
@app.route('/google/auth/')
def google_auth():
token = oauth.google.authorize_access_token()
nonce = request.args.get('nonce') # Retrieve the nonce from the request
user = oauth.google.parse_id_token(token, nonce=nonce)
email = user.get('email') # Retrieve email from user info
session['email'] = email # Store email in session
print(" Google User ", user)
return redirect('/register')
@app.route('/', methods=['GET', 'POST'])
def login():
# message = None
if "message" in session:
message = session["message"]
else:
message = None
# session["message"] = None
session.clear()
''' Log-in for Students '''
if request.method == 'POST' and 'email_student' in request.form and 'password_student' in request.form:
email = request.form['email_student']
roll_no = request.form['password_student']
print("Received email:", email) # Debugging print statement
print("Received roll number:", roll_no) # Debugging print statement
cursor = conn.cursor(dictionary=True)
try:
# cursor.execute('SELECT * FROM STUDENTS WHERE EMAIL = %s AND ROLL_NO = %s', (email, roll_no))
cursor.execute('SELECT * FROM STUDENTS WHERE EMAIL = %s', (email,))
user = cursor.fetchone()
print("User:", user) # Debugging print statement
if user:
# Password check
query = "SELECT PASSWORD FROM PASSWORDS WHERE EMAIL = %s"
cursor.execute(query, (email,))
password = cursor.fetchone()
# if roll_no != email.split("@")[0]:
if int(roll_no) != password:
print("Incorrect Student Password")
# flash("Incorrect Student Password", 'error') # Flash error message
message = "Incorrect Student Password"
else:
session['loggedin'] = "Student"
session['userid'] = user['ROLL_NO']
session['name'] = user['FIRST_NAME']
session['email'] = user['EMAIL']
session['user_info'] = user
cursor.execute('SELECT COUNCIL_NAME FROM COUNCIL_MEMBERS WHERE ROLLS_NO = %s AND POSITION = "Secretary"', (roll_no,))
council_secy = cursor.fetchone()
session["council_secretary"] = None
if council_secy:
session["council_secretary"] = council_secy['COUNCIL_NAME']
else:
cursor.execute('SELECT CLUBS_NAME FROM CLUB_MEMBERS WHERE ROLLS_NO = %s AND POSITION = "Secretary"', (roll_no,))
club_secy = cursor.fetchone()
session["club_secretary"] = None
if club_secy:
session["club_secretary"] = club_secy['CLUBS_NAME']
# return render_template('studentInfo.html', studentInfo=user)
return redirect(url_for('student_info'))
else:
print('User not found (incorrect email)') # Debugging print statement
# flash("User not found (incorrect email)", 'error')
message = 'User not found (incorrect email)'
except Exception as e:
flash("An error occurred. Please try again later.", 'error') # Flash error message
print('Error:', e) # Debugging print statement
message = "An error occurred. Please try again later."
finally:
cursor.close() # Always close the cursor
''' Log-in for Employees '''
if request.method == 'POST' and 'email_employee' in request.form and 'password_employee' in request.form:
email = request.form['email_employee']
employee_id = request.form['password_employee']
# print(type(request.form['password_employee']))
print("Received email:", email) # Debugging print statement
print("Received employee id:", employee_id) # Debugging print statement
cursor = conn.cursor(dictionary=True)
try:
# cursor.execute('SELECT * FROM STUDENTS WHERE EMAIL = %s AND EMPLOYEE_ID = %s', (email, employee_id))
cursor.execute('SELECT * FROM EMPLOYEE WHERE EMAIL = %s', (email,))
user = cursor.fetchone()
print("User:", user) # Debugging print statement
if user:
# password-check
query = "SELECT PASSWORD FROM PASSWORDS WHERE EMAIL = %s"
cursor.execute(query, (email,))
password = cursor.fetchone()
# if int(employee_id) != user['EMPLOYEE_ID']:
if int(employee_id) != password:
print("Incorrect Employee Password")
message = "Incorrect Employee Password"
else:
session['loggedin'] = "Employee"
session['userid'] = user['EMPLOYEE_ID']
session['name'] = user['FIRST_NAME']
session['email'] = user['EMAIL']
session['user_info'] = user
message = 'Logged in successfully !'
cursor.execute('SELECT COUNT(*) FROM VENUE WHERE EMPLOYEE_ID = %s', (employee_id,))
result = cursor.fetchone()
exists_in_venue = result['COUNT(*)'] > 0
session["Venue-in-charge"] = None
if exists_in_venue:
session["Venue-in-charge"] = True
cursor.execute('SELECT COUNCIL_NAME FROM COUNCIL WHERE EMPLOYEE_ID = %s', (employee_id,))
result = cursor.fetchone()
session["council_advisor"] = None
if result:
session["council_advisor"] = result['COUNCIL_NAME']
cursor.execute('SELECT CLUB_NAME FROM OVERSEER WHERE EMPLOYEE_ID = %s', (employee_id,))
result = cursor.fetchone()
session["club_overseer"] = None
if result:
session["club_overseer"] = result['CLUB_NAME']
# Page you want to navigate to if logged in successfully
# return render_template('employeeInfo.html', employeeInfo = user)
return redirect(url_for('employee_info'))
else:
print('User not found (incorrect email)') # Debugging print statement
message = 'User not found (incorrect email)'
except Exception as e:
print('Error:', e) # Debugging print statement
message = 'An error occurred during login.'
''' Log-in for Admin '''
if request.method == 'POST' and 'email_admin' in request.form and 'password_admin' in request.form:
email = request.form['email_admin']
pw = request.form['password_admin']
print("Received email:", email) # Debugging print statement
print("Received password:", pw) # Debugging print statement
cursor = conn.cursor(dictionary=True)
query = "SELECT ROLE, PASSWORD FROM PASSWORDS WHERE EMAIL = %s"
cursor.execute(query, (email,))
result = cursor.fetchone()
try:
# if email == "admin@iitgn.ac.in":
# password-check
# if pw != "manudb":
if result:
print(result)
role, stored_password = result["ROLE"], result["PASSWORD"]
print(role, stored_password) # Debugging print statement
if role != 'Admin':
message = "You do not have admin privileges"
print("This user is not an admin.")
else:
if pw != stored_password:
print("Incorrect Password")
message = "Incorrect Password"
else:
session['loggedin'] = "Admin"
session['userid'] = 0
session['name'] = "admin"
session['email'] = "admin@iitgn.ac.in"
message = 'Logged in successfully !'
# Page you want to navigate to if logged in successfully
# return render_template('admin.html')
return redirect(url_for('admin_panel'))
else:
print('User not found (incorrect email)') # Debugging print statement
message = 'User not found (incorrect email)'
except Exception as e:
print('Error:', e) # Debugging print statement
message = 'An error occurred during login.'
finally:
cursor.close()
# we want to show the login page by default
return render_template('login.html', message=message)
@app.route('/register', methods=['GET', 'POST'])
def register():
email = session.get('email') # Retrieve email from session
print(email)
if email is None:
return render_template('login.html', message = "Sign-in your with your IITGN email id to register.")
''' Register for Students '''
if request.method == 'POST' and 'userID_student' in request.form and 'password_student' in request.form and 'name_student' in request.form:
password = request.form['password_student']
roll_no = request.form['userID_student']
first_name = request.form['name_student']
if not roll_no.isnumeric():
return render_template("registration.html", email=email, message="Roll number should be numeric.")
if len(roll_no) != 7:
return render_template("registration.html", email=email, message="Roll number should be 7 digits long.")
if int(roll_no)<2000000:
return render_template("registration.html", email=email, message="Invalid Roll number. Should be greater than 2000000.")
cursor = conn.cursor(dictionary=True)
try:
cursor.execute('SELECT * FROM STUDENTS WHERE ROLL_NO = %s', (roll_no,))
user = cursor.fetchone()
if user:
return render_template("registration.html", email=email, message="User already exists.")
else:
# Constant values for the fields
contact_no = '1234567890'
middle_name = None
last_name = None
street = '123 Street'
city = 'City'
state = 'State'
pincode = '123456'
dob = '2000-01-01'
age = 21
programme = 'BTech'
discipline = 'CSE'
year = '2022'
cursor.execute('INSERT INTO STUDENTS (ROLL_NO, EMAIL, CONTACT_NO, FIRST_NAME, MIDDLE_NAME, LAST_NAME, STREET, CITY, STATE, PINCODE, DATE_OF_BIRTH, AGE, PROGRAMME, DISCIPLINE, YEAR) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', (roll_no, email, contact_no, first_name, middle_name, last_name, street, city, state, pincode, dob, age, programme, discipline, year))
cursor.execute('INSERT INTO PASSWORDS (EMAIL, PASSWORD, ROLE) VALUES (%s, %s, %s)', (email, password, 'Student'))
conn.commit()
return redirect(url_for('login'))
except Exception as e:
print('Error:', e)
return render_template("registration.html", email=email, message=e)
finally:
cursor.close()
''' Register for Employees '''
if request.method == 'POST' and 'userID_employee' in request.form and 'password_employee' in request.form and 'name_employee' in request.form:
password = request.form['password_employee']
employee_id = request.form['userID_employee']
first_name = request.form['name_employee']
if not employee_id.isnumeric():
return render_template("registration.html", email=email, message="Employee ID should be numeric.")
if int(employee_id)<1000:
return render_template("registration.html", email=email, message="Invalid Employee ID. Should be less than 1000.")
cursor = conn.cursor(dictionary=True)
try:
cursor.execute('SELECT * FROM EMPLOYEES WHERE EMPLOYEE_ID = %s', (employee_id,))
user = cursor.fetchone()
if user:
return render_template("registration.html", email=email, message="User already exists.")
else:
# Constant values for the fields
middle_name = None
last_name = None
phone_number = '1234567890'
department = 'Computer Science'
designation = 'PROFESSOR'
cursor.execute('INSERT INTO EMPLOYEES (EMPLOYEE_ID, EMAIL, FIRST_NAME, MIDDLE_NAME, LAST_NAME, PHONE_NUMBER, DEPARTMENT, DESIGNATION) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)', (employee_id, email, first_name, middle_name, last_name, phone_number, department, designation))
cursor.execute('INSERT INTO PASSWORDS (EMAIL, PASSWORD, ROLE) VALUES (%s, %s, %s)', (email, password, 'Employee'))
conn.commit()
return redirect(url_for('login'))
except Exception as e:
print('Error:', e)
return render_template("registration.html", email=email, message=e)
finally:
cursor.close()
return render_template("registration.html", email=email)
@app.route('/logout')
@app.route('/council_members/logout')
@app.route('/clubs/logout')
@app.route('/fetch_club_member/logout')
def logout():
session.clear()
return redirect(url_for('login'))
@app.route('/studentInfo')
def student_info():
# Check if the user is logged in, if not redirect to login page
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] == "Admin" or session["loggedin"] == "Employee":
session["message"] = "Log-in as student to access Student-Info page."
return redirect(url_for('login'))
return render_template('studentInfo.html', studentInfo = session['user_info'])
@app.route('/employeeInfo')
def employee_info():
# Check if the user is logged in, if not redirect to login page
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] == "Admin" or session["loggedin"] == "Student":
session["message"] = "Log-in as employee to access Employee-Info page."
return redirect(url_for('login'))
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor(dictionary=True)
employee_id = session['userid']
records_v = None
if session["Venue-in-charge"]:
query = """
SELECT pt.*
FROM PLACE_AND_TIME pt
JOIN VENUE v ON pt.name = v.address
WHERE v.employee_id = %s
"""
cursor.execute(query, (employee_id,))
records_v = cursor.fetchall()
# Convert datetime.timedelta objects to strings
for record in records_v:
record['START_TIME'] = str(record['START_TIME'])
record['END_TIME'] = str(record['END_TIME'])
print(records_v)
query = """
SELECT a.EVENT_NAME, a.EDITION, e.BUDGET, a.APPROVAL_STATUS
FROM Approval a
JOIN Event e ON a.EVENT_NAME = e.EVENT_NAME AND a.EDITION = e.EDITION
WHERE a.EMPLOYEE_ID = %s
"""
cursor.execute(query, (employee_id,))
records_b = cursor.fetchall()
print(records_b)
# Store the modified records in the session
session["venues"] = records_v
return render_template('employeeInfo.html', employeeInfo = session['user_info'], venues=session["venues"], events=records_b)
@app.route('/approval_update', methods=['POST'])
def approval_update():
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
# Get the selected event status and approval status from the form
event_status = request.form.get('event_status')
status = request.form.get('status')
# Split the event status into event name and edition
event_name, edition = event_status.split(',')
# Update the approval status in the database
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor()
try:
query = """
UPDATE Approval
SET APPROVAL_STATUS = %s
WHERE EVENT_NAME = %s AND EDITION = %s
"""
cursor.execute(query, (status, event_name, edition))
conn.commit()
query = """
SELECT a.EVENT_NAME, a.EDITION, e.BUDGET, a.APPROVAL_STATUS
FROM Approval a
JOIN Event e ON a.EVENT_NAME = e.EVENT_NAME AND a.EDITION = e.EDITION
WHERE a.EMPLOYEE_ID = %s
"""
cursor.execute(query, (session['userid'],))
records_b = cursor.fetchall()
print(records_b)
conn.close()
# Redirect back to the employee info page
return redirect(url_for('employee_info', employeeInfo = session['user_info'], venues=session["venues"], events=records_b))
except mysql.connector.Error as e:
message=f"Error retrieving information: {e}"
return render_template(url_for('employee_info', employeeInfo = session['user_info'], venues=session["venues"], events=[], message=message))
#this is used to display council details
@app.route('/councils')
def council():
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] != "Student" and session["loggedin"] != "Employee":
session["message"] = "Log-in as student or employee to view."
return redirect(url_for('login'))
try:
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor(dictionary=True)
# Query to retrieve club information
# this query joins the two table(council, COUNCIL_MEMBER) to find out number of member in a council
cursor.execute(' Select council.COUNCIL_NAME ,council.DESCRIPTION, count(COUNCIL_MEMBERS.ROLLS_NO) as "TOTAL_MEMBERS" from council , COUNCIL_MEMBERS where council.COUNCIL_NAME = COUNCIL_MEMBERS.COUNCIL_NAME group by COUNCIL_MEMBERS.COUNCIL_NAME ')
councils = cursor.fetchall()
print(councils)
# session['councilName']= councils[0]['COUNCIL_NAME']
# print(session['councilName'])
cursor.execute('''
SELECT clubs.CLUB_NAME, clubs.DESCRIPTION, COUNT(CLUB_MEMBERS.ROLLS_NO) AS "TOTAL_MEMBERS"
FROM clubs
JOIN CLUB_MEMBERS ON clubs.CLUB_NAME = CLUB_MEMBERS.CLUBS_NAME
WHERE clubs.COUNCIL_NAME IS NULL
GROUP BY clubs.CLUB_NAME, clubs.DESCRIPTION
''')
hobby_groups = cursor.fetchall()
print(hobby_groups)
# Render the template with club information
return render_template('councils.html', councils=councils, clubs=hobby_groups)
except mysql.connector.Error as e:
message=f"Error retrieving information: {e}"
return render_template('councils.html', councils=[], clubs=[], message=message)
finally:
# Close database connection
cursor.close()
conn.close()
@app.route('/fetch_council_member/events', methods = ['GET'])
@app.route('/events', methods = ['GET'])
def events():
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] == "Admin" or session["loggedin"] == "Employee":
session["message"] = "Log-in as student to access Events page."
return redirect(url_for('login'))
try:
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor(dictionary=True)
# Query to retrieve club information
# this query joins the two table(council, COUNCIL_MEMBER) to find out number of member in a council
cursor.execute(f"select PLACE_AND_TIME.EVENTS_NAME, PLACE_AND_TIME.EDITIONS, PLACE_AND_TIME.DATE, EVENT.DESCRIPTION from PLACE_AND_TIME , EVENT where PLACE_AND_TIME.EVENTS_NAME = EVENT.EVENT_NAME and PLACE_AND_TIME.EDITIONS = EVENT.EDITION and DATE > '{datetime.now().date()}' order by PLACE_AND_TIME.DATE DESC;")
events = cursor.fetchall()
# Render the template with club information
return render_template('events.html',e=events)
except mysql.connector.Error as e:
message=f"Error retrieving information: {e}"
render_template('events.html',e=[],message=message)
finally:
# Close database connection
cursor.close()
conn.close()
@app.route('/event/<ev>/<ed>', methods = ['POST','GET'])
def event(ev,ed):
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] == "Admin" or session["loggedin"] == "Employee":
session["message"] = "Log-in as student to access Events page."
return redirect(url_for('login'))
try:
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor(dictionary=True)
# Query to retrieve club information
# this query joins the two table(council, COUNCIL_MEMBER) to find out number of member in a council
cursor.execute(f"select * from EVENT left join PLACE_AND_TIME on EVENTS_NAME = EVENT_NAME and EDITIONS = EDITION where EVENT_NAME= '{ev}' and EDITION= {ed};")
event = cursor.fetchall()
# Render the template with club information
cursor.close()
return render_template('event.html',event=event[0])
except mysql.connector.Error as e:
message=f"Error retrieving information: {e}"
render_template('events.html',message=message)
@app.route('/participate/<ev>/<ed>', methods = ['GET'])
def participate(ev,ed):
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] == "Admin" or session["loggedin"] == "Employee":
session["message"] = "Log-in as student to participate."
return redirect(url_for('login'))
if (ed[0].isdigit()):
return render_template('participation.html',ev=ev,ed=ed)
else:
return redirect(url_for('event',ev=ev,ed=ed))
@app.route('/participation/<ev>/<ed>', methods = ['GET','POST'])
def participation(ev,ed):
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] == "Admin" or session["loggedin"] == "Employee":
session["message"] = "Log-in as student to participate."
return redirect(url_for('login'))
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor(dictionary=True)
name = request.form['teamname']
# Get the list of roll values from the form
captain = request.form['Captain']
message = None
try:
cursor.execute(f"INSERT INTO PARTICIPATION VALUES ('{ev}', {ed}, {captain}, '{name}', {1});")
conn.commit()
message = "Participation added"
except mysql.connector.Error as e:
message = e
return render_template('participation.html',ev=ev,ed=ed,message=message)
if request.form.getlist('roll'):
rolls = request.form.getlist('roll')
# Iterate over the rolls and insert them into the PARTICIPATION table
for roll in rolls:
query = f"INSERT INTO PARTICIPATION VALUES ('{ev}', {ed}, {roll}, '{name}', {0});"
try:
cursor.execute(query)
conn.commit()
message = "Participation added"
except mysql.connector.Error as e:
message = e
return render_template('participation.html',ev=ev,ed=ed,message=message)
cursor.close()
conn.close()
return render_template('participation.html',ev=ev,ed=ed,message=message)
@app.route('/council_members/<council_name>')
def council_members(council_name):
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] != "Student" and session["loggedin"] != "Employee":
session["message"] = "Log-in as student or employee to view."
return redirect(url_for('login'))
show_form = session.get("council_secretary") == council_name
print(show_form)
cursor = conn.cursor(dictionary=True)
try:
cursor.execute('''
SELECT clubs.CLUB_NAME, clubs.DESCRIPTION, COUNT(CLUB_MEMBERS.ROLLS_NO) AS "TOTAL_MEMBERS"
FROM clubs
JOIN CLUB_MEMBERS ON clubs.CLUB_NAME = CLUB_MEMBERS.CLUBS_NAME
WHERE clubs.COUNCIL_NAME = %s
GROUP BY clubs.CLUB_NAME, clubs.DESCRIPTION;''',(council_name,))
clubs = cursor.fetchall()
return render_template('council_members.html', council_name=council_name, show_form=show_form, clubs=clubs)
except mysql.connector.Error as e:
message=f"Error retrieving info {e}"
return render_template('council_members.html', council_name=council_name, show_form=show_form, clubs=clubs)
@app.route('/clubs/<club_name>')
def clubs(club_name):
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] != "Student" and session["loggedin"] != "Employee":
session["message"] = "Log-in as student or employee to view."
return redirect(url_for('login'))
show_form = session.get("club_secretary") == club_name
print(show_form)
event_info = None
if show_form:
try:
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor(dictionary=True)
query = '''
SELECT
e.EVENT_NAME,
e.EDITION,
e.BUDGET,
a.APPROVAL_STATUS,
a.EMPLOYEE_ID AS Overseer,
o.ROLL_NO AS Event_Lead
FROM
event e
INNER JOIN
conducts c ON e.EVENT_NAME = c.EVENTS_NAME AND e.EDITION = c.EDITIONS
LEFT JOIN
approval a ON e.EVENT_NAME = a.EVENT_NAME AND e.EDITION = a.EDITION
LEFT JOIN
organizers o ON e.EVENT_NAME = o.EVENTS_NAME AND e.EDITION = o.EDITIONS
WHERE
c.CLUB_NAME = %s
AND o.RESPONSIBILITY = 'Event Lead'
'''
cursor.execute(query, (club_name,))
event_info = cursor.fetchall()
print(event_info)
except mysql.connector.Error as e:
message= f"Error retrieving club information: {e}"
return render_template('clubs.html', club_name=club_name, show_form=show_form, event_info=[],message=message)
finally:
# Close database connection
cursor.close()
conn.close()
return render_template('clubs.html', club_name=club_name, show_form=show_form, event_info=event_info)
@app.route('/fetch_council_member/<council_name>', methods=['POST'])
def fetch_council_members(council_name):
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] != "Student" and session["loggedin"] != "Employee":
session["message"] = "Log-in as student or employee to view."
return redirect(url_for('login'))
option = request.form['option']
show_form = session.get("council_secretary") == council_name
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor(dictionary=True)
# Query to fetch data based on the selected option and council name
if option == 'All member':
query = f"SELECT STUDENTS.ROLL_NO, STUDENTS.EMAIL, STUDENTS.CONTACT_NO, STUDENTS.FIRST_NAME, COUNCIL_MEMBERS.POSITION FROM STUDENTS, COUNCIL_MEMBERS WHERE COUNCIL_MEMBERS.ROLLS_NO = STUDENTS.ROLL_NO AND COUNCIL_MEMBERS.COUNCIL_NAME = '{council_name}';"
elif option == 'General Members only':
query = f"SELECT STUDENTS.ROLL_NO, STUDENTS.EMAIL, STUDENTS.CONTACT_NO, STUDENTS.FIRST_NAME, COUNCIL_MEMBERS.POSITION FROM STUDENTS, COUNCIL_MEMBERS WHERE COUNCIL_MEMBERS.ROLLS_NO = STUDENTS.ROLL_NO AND COUNCIL_MEMBERS.POSITION = 'GENERAL MEMBER' AND COUNCIL_MEMBERS.COUNCIL_NAME = '{council_name}';"
elif option =='Coordinators':
query = f"SELECT STUDENTS.ROLL_NO, STUDENTS.EMAIL, STUDENTS.CONTACT_NO, STUDENTS.FIRST_NAME, COUNCIL_MEMBERS.POSITION FROM STUDENTS, COUNCIL_MEMBERS WHERE COUNCIL_MEMBERS.ROLLS_NO = STUDENTS.ROLL_NO AND COUNCIL_MEMBERS.POSITION = 'COORDINATOR' AND COUNCIL_MEMBERS.COUNCIL_NAME = '{council_name}';"
elif option == 'Secretary':
query = f"SELECT STUDENTS.ROLL_NO, STUDENTS.EMAIL, STUDENTS.CONTACT_NO, STUDENTS.FIRST_NAME, COUNCIL_MEMBERS.POSITION FROM STUDENTS, COUNCIL_MEMBERS WHERE COUNCIL_MEMBERS.ROLLS_NO = STUDENTS.ROLL_NO AND COUNCIL_MEMBERS.POSITION = 'SECRETARY' AND COUNCIL_MEMBERS.COUNCIL_NAME = '{council_name}';"
try:
cursor.execute(query)
data = cursor.fetchall()
cursor.execute('''
SELECT clubs.CLUB_NAME, clubs.DESCRIPTION, COUNT(CLUB_MEMBERS.ROLLS_NO) AS "TOTAL_MEMBERS"
FROM clubs
JOIN CLUB_MEMBERS ON clubs.CLUB_NAME = CLUB_MEMBERS.CLUBS_NAME
WHERE clubs.COUNCIL_NAME = %s
GROUP BY clubs.CLUB_NAME, clubs.DESCRIPTION;''',(council_name,))
clubs = cursor.fetchall()
conn.close()
return render_template('council_members.html', data=data, council_name=council_name, show_form=show_form, clubs=clubs)
except mysql.connector.Error as e:
message=f"Error retrieving information: {e}"
render_template('council_members.html', data=[], council_name=council_name, show_form=show_form, clubs=[])
@app.route('/update_council_members/<council_name>', methods=['POST'])
def update_council_members(council_name):
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] != "Student" and session["loggedin"] != "Employee":
session["message"] = "Log-in as student or employee to view."
return redirect(url_for('login'))
option = request.form['option2']
r = request.form['r']
show_form = session.get("council_secretary") == council_name
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor(dictionary=True)
# Query to perform operations based on the selected option and council name
if option == 'Add member':
query = f"INSERT INTO COUNCIL_MEMBERS (COUNCIL_NAME, ROLLS_NO, POSITION) VALUES ('{council_name}', {r}, 'General Member');"
elif option == 'Remove Member':
query = f"DELETE FROM COUNCIL_MEMBERS WHERE ROLLS_NO = {r} AND POSITION = 'General Member' AND COUNCIL_NAME = '{council_name}';"
elif option =='Add coordinator':
query = f"INSERT INTO COUNCIL_MEMBERS (COUNCIL_NAME, ROLLS_NO, POSITION) VALUES ('{council_name}', {r}, 'Coordinator');"
elif option == 'Remove coordinator':
query = f"DELETE FROM COUNCIL_MEMBERS WHERE ROLLS_NO = {r} AND POSITION = 'Coordinator' AND COUNCIL_NAME = '{council_name}';"
try:
cursor.execute(query)
conn.commit()
cursor.execute('''
SELECT clubs.CLUB_NAME, clubs.DESCRIPTION, COUNT(CLUB_MEMBERS.ROLLS_NO) AS "TOTAL_MEMBERS"
FROM clubs
JOIN CLUB_MEMBERS ON clubs.CLUB_NAME = CLUB_MEMBERS.CLUBS_NAME
WHERE clubs.COUNCIL_NAME = %s
GROUP BY clubs.CLUB_NAME, clubs.DESCRIPTION;''',(council_name,))
clubs = cursor.fetchall()
conn.close()
return render_template('council_members.html', council_name=council_name, show_form=show_form, clubs=clubs)
except mysql.connector.IntegrityError as e:
message=f"Error : {e}"
render_template('council_members.html', council_name=council_name, show_form=show_form, clubs=[], message=message)
@app.route('/fetch_club_member/<club_name>', methods=['POST'])
def fetch_club_members(club_name):
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] != "Student" and session["loggedin"] != "Employee":
session["message"] = "Log-in as student or employee to view."
return redirect(url_for('login'))
show_form = session.get("club_secretary") == club_name
event_info = None
if show_form:
try:
conn_ = mysql.connector.connect(**mysql_config)
cursor_ = conn_.cursor(dictionary=True)
query = '''
SELECT
e.EVENT_NAME,
e.EDITION,
e.BUDGET,
a.APPROVAL_STATUS,
a.EMPLOYEE_ID AS Overseer,
o.ROLL_NO AS Event_Lead
FROM
event e
INNER JOIN
conducts c ON e.EVENT_NAME = c.EVENTS_NAME AND e.EDITION = c.EDITIONS
LEFT JOIN
approval a ON e.EVENT_NAME = a.EVENT_NAME AND e.EDITION = a.EDITION
LEFT JOIN
organizers o ON e.EVENT_NAME = o.EVENTS_NAME AND e.EDITION = o.EDITIONS
WHERE
c.CLUB_NAME = %s
AND o.RESPONSIBILITY = 'Event Lead'
'''
cursor_.execute(query, (club_name,))
event_info = cursor_.fetchall()
print(event_info)
except mysql.connector.Error as e:
message=f"Error : {e}"
return render_template('clubs.html', data=[], club_name=club_name, show_form=show_form, event_info=[], message=message)
finally:
# Close database connection
cursor_.close()
conn_.close()
option = request.form['option']
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor()
query=""
# Query to fetch data based on the selected option and club name
if option == 'All member':
query = f"SELECT STUDENTS.ROLL_NO, STUDENTS.EMAIL, STUDENTS.CONTACT_NO, STUDENTS.FIRST_NAME, CLUB_MEMBERS.POSITION FROM STUDENTS, CLUB_MEMBERS WHERE CLUB_MEMBERS.ROLLS_NO = STUDENTS.ROLL_NO AND CLUB_MEMBERS.CLUBS_NAME = '{club_name}';"
elif option == 'General Members only':
query = f"SELECT STUDENTS.ROLL_NO, STUDENTS.EMAIL, STUDENTS.CONTACT_NO, STUDENTS.FIRST_NAME, CLUB_MEMBERS.POSITION FROM STUDENTS, CLUB_MEMBERS WHERE CLUB_MEMBERS.ROLLS_NO = STUDENTS.ROLL_NO AND CLUB_MEMBERS.POSITION = 'GENERAL MEMBER' AND CLUB_MEMBERS.CLUBS_NAME = '{club_name}';"
elif option =='Coordinators':
query = f"SELECT STUDENTS.ROLL_NO, STUDENTS.EMAIL, STUDENTS.CONTACT_NO, STUDENTS.FIRST_NAME, CLUB_MEMBERS.POSITION FROM STUDENTS, CLUB_MEMBERS WHERE CLUB_MEMBERS.ROLLS_NO = STUDENTS.ROLL_NO AND CLUB_MEMBERS.POSITION = 'COORDINATOR' AND CLUB_MEMBERS.CLUBS_NAME = '{club_name}';"
elif option == 'Secretary':
query = f"SELECT STUDENTS.ROLL_NO, STUDENTS.EMAIL, STUDENTS.CONTACT_NO, STUDENTS.FIRST_NAME, CLUB_MEMBERS.POSITION FROM STUDENTS, CLUB_MEMBERS WHERE CLUB_MEMBERS.ROLLS_NO = STUDENTS.ROLL_NO AND CLUB_MEMBERS.POSITION = 'SECRETARY' AND CLUB_MEMBERS.CLUBS_NAME = '{club_name}';"
try:
cursor.execute(query)
data = cursor.fetchall()
except mysql.connector.Error as e:
message=f"Error : {e}"
render_template('clubs.html', data=[], club_name=club_name, show_form=show_form, event_info=event_info)
print(data)
conn.close()
return render_template('clubs.html', data=data, club_name=club_name, show_form=show_form, event_info=event_info)
@app.route('/update_club_members/<club_name>', methods=['POST'])
def update_club_members(club_name):
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] != "Student" and session["loggedin"] != "Employee":
session["message"] = "Log-in as student or employee to view."
return redirect(url_for('login'))
show_form = session.get("club_secretary") == club_name
event_info = None
if show_form:
try:
conn_ = mysql.connector.connect(**mysql_config)
cursor_ = conn_.cursor(dictionary=True)
query = '''
SELECT
e.EVENT_NAME,
e.EDITION,
e.BUDGET,
a.APPROVAL_STATUS,
a.EMPLOYEE_ID AS Overseer,
o.ROLL_NO AS Event_Lead
FROM
event e
INNER JOIN
conducts c ON e.EVENT_NAME = c.EVENTS_NAME AND e.EDITION = c.EDITIONS
LEFT JOIN
approval a ON e.EVENT_NAME = a.EVENT_NAME AND e.EDITION = a.EDITION
LEFT JOIN
organizers o ON e.EVENT_NAME = o.EVENTS_NAME AND e.EDITION = o.EDITIONS
WHERE
c.CLUB_NAME = %s
AND o.RESPONSIBILITY = 'Event Lead'
'''
cursor_.execute(query, (club_name,))
event_info = cursor_.fetchall()
print(event_info)
except mysql.connector.Error as e:
message=f"Error : {e}"
render_template('clubs.html', club_name=club_name, show_form=show_form, event_info=[], message=message)
finally:
# Close database connection
cursor_.close()
conn_.close()
option = request.form['option2']
r = request.form['r']
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor()
# Query to perform operations based on the selected option and club name
if option == 'Add member':
query = f"INSERT INTO CLUB_MEMBERS (CLUBS_NAME, ROLLS_NO, POSITION) VALUES ('{club_name}', {r}, 'General Member');"
elif option == 'Remove Member':
query = f"DELETE FROM CLUB_MEMBERS WHERE ROLLS_NO = {r} AND POSITION = 'General Member' AND CLUBS_NAME = '{club_name}';"
elif option =='Add coordinator':
query = f"INSERT INTO CLUB_MEMBERS (CLUBS_NAME, ROLLS_NO, POSITION) VALUES ('{club_name}', {r}, 'Coordinator');"
elif option == 'Remove coordinator':
query = f"DELETE FROM CLUB_MEMBERS WHERE ROLLS_NO = {r} AND POSITION = 'Coordinator' AND CLUBS_NAME = '{club_name}';"
try:
cursor.execute(query)
conn.commit()
conn.close()
except mysql.connector.Error as e:
message=f"Error : {e}"
render_template('clubs.html', club_name=club_name, show_form=show_form, event_info=event_info, message=message)
return render_template('clubs.html', club_name=club_name, show_form=show_form, event_info=event_info)
# Function to fetch all table names from MySQL
def get_table_names():
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor()
try:
cursor.execute("SHOW TABLES")
tables = [table[0] for table in cursor.fetchall()]
# print(tables)
# tables.remove("passwords")
cursor.close()
conn.close()
return tables
except mysql.connector.Error as e:
message=f"Error : {e}"
return message
@app.route('/admin')
def admin_panel():
if 'loggedin' not in session:
session["message"] = "Please log in first."
return redirect(url_for('login'))
print(session["loggedin"])
if session["loggedin"] == "Employee" or session["loggedin"] == "Student":
session["message"] = "Only admins can access Admin page."
return redirect(url_for('login'))
tables = get_table_names()
if type(tables)==str: