-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
2470 lines (2113 loc) · 104 KB
/
__init__.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
import json
from flask import Flask, render_template, request, redirect, url_for, session, jsonify, g, send_file, flash
import shelve
# import dbm.gnu
import sys
import os
from datetime import datetime, timedelta
import time
import stripe
from dataclasses import dataclass, field
# sys.path.remove(main_dir)
import requests
import sendgrid
from sendgrid.helpers.mail import Mail, From, To
#from flask_wtf.recaptcha import RecaptchaField
from markupsafe import Markup
# current_dir = os.path.dirname(os.path.abspath(__file__))
# main_dir = os.path.dirname(current_dir)
# sys.path.append(main_dir)
# Importing Objects
from Objects.transaction.Product import Product # it does work
from Objects.transaction.onlineCourses import onlineCourse
from Objects.transaction.Order import Order
from Objects.transaction.Review import Review
from Objects.transaction.code import Code
from Objects.transaction.cart import Cart, CartItem
from Objects.transaction.wishlist import Wishlist, WishlistItem
from Objects.CustomerService.Record import Record
from Objects.account.Admin import Admin
from Objects.account.Customer import User
from Objects.account.Forms import DelimitedNumberInput, createUser, createCourse, userLogin, userEditInfo, userChangePassword, userPaymentMethod, createAdmin, adminLogin, editAdminAccount
#from Objects.blog.blog import Post, Comments, Likes
# sys.path.remove(main_dir)
WeiHeng_Domain = "https://congenial-disco-5g444v96pv537v7x-5000.app.github.dev/"
# WeiHeng_Domain = "http://127.0.0.1:5000/"
Public_key = ""
Private_key = ""
cartobj = Cart()
wishlistobj = Wishlist()
Domain = WeiHeng_Domain
Public_key = "6LdgM_8nAAAAAA5r2dkOXO5Fn3tnZaXPODjXLRMs"
Private_key = "6LdgM_8nAAAAADidEavxieoxm7ivfa8mdcP5bdRc"
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key_here'
app.config['SENDGRID_API_KEY'] = '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'
app.secret_key = 'your_secret_key_here' # Replace with your own secret key
app.config['RECAPTCHA_PUBLIC_KEY'] = Public_key
app.config['RECAPTCHA_PRIVATE_KEY'] = Private_key
#app.config['RECAPTCHA_VERIFY_URL'] = 'https://www.google.com/recaptcha/api/siteverify'
# Replace with your own secret key
stripe.api_key = 'sk_test_51NbJAUL0EO5j7e8js0jOonkCjFkHksaoITSyuD8YR34JLHMBkX3Uy4SwejTVr6XAvL8amqm4kMjmXtedg2I1oNTI00wnaqFYJJ'
# Account
def generate_time_for_timeseries():
return str(datetime.;;;now().replace(minute=0, second= 0, microsecond=0))
def send_verification_email(email):
sg = sendgrid.SendGridAPIClient(api_key=app.config['SENDGRID_API_KEY'])
verification_link = f"{Domain}verify_email?email={email}"
message = Mail(
from_email=From('[email protected]'),
to_emails=To(email),
subject='Email Verification',
html_content=f'Thank you for registering an account for our Healthy Living Website.<br>If this was not done by you, please ignore this email.<br><br>Please click this to <a href="{verification_link}">verify</a> your account.<br><br>Best Regards,<br> FashionHub Accounts Department<br><img src="https://thumbs.dreamstime.com/z/sustainable-fashion-logo-eco-friendly-production-label-icon-badge-clothes-hanger-green-leaves-natural-recycling-215122758.jpg" width="120" height="120"></img>'
)
try:
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e)
@app.route('/verify_email', methods=['GET'])
def verify_email():
email = request.args.get('email')
# Add code to verify the email address and update userVerified column accordingly in your database.
# For simplicity, we'll just set userVerified to 1 here.
db = shelve.open('Objects/account/user.db', 'w')
users_dict = db.get('users', {})
for user in users_dict.values():
if user.get_userEmail() == email:
userVerified = 1
user.set_userVerified(userVerified)
db['users'] = users_dict
db.close()
return render_template('/Customer/verifiedEmailThankYou.html')
db.close()
return "Email verification failed. User not found."
@app.route('/Logout', methods=['GET','POST'])
def Logout():
session.clear()
return render_template('/Customer/homepage.html')
# User side
@app.route('/Login', methods=['GET','POST'])
def Login():
create_user_form = userLogin(request.form)
if request.method == "POST" and create_user_form.validate():
user_db_path = 'Objects/account/user.db'
if not os.path.exists(user_db_path):
print("we have no user.db")
db = shelve.open(user_db_path, 'c')
db['users'] = {}
db['admins'] = {}
db.close()
db = shelve.open(user_db_path, 'w')
users_dict = db.get('users', {}) # Use a default empty dict if 'users' doesn't exist yet
email = create_user_form.userEmail.data
password = create_user_form.userPassword.data
print(users_dict)
for key, user_data in users_dict.items():
print(key, user_data.get_userPassword, user_data.get_userEmail())
if user_data.get_userEmail() == email and user_data.get_userPassword() == password:
if user_data.get_userVerified() == 1:
session['id'] = key
session['userfullname'] = user_data.get_userFullName()
session['username'] = user_data.get_userName()
session['useremail'] = user_data.get_userEmail()
session['useraddress'] = user_data.get_userAddress()
session['userpostalcode'] = user_data.get_userPostalCode()
session['user_role'] = user_data.get_userRole()
session['user_logged_in'] = True
db.close()
print("User successfully saved.")
if session["user_role"] == "teacher":
return redirect(url_for('TeacherHomepage'))
else:
return redirect(url_for('CustomerHomepage'))
else:
#flash("Please verify/create your account.", category="danger")
return render_template('/Customer/account/LoginPage.html', form=create_user_form)
admin_dict = db.get('admins', {})
print(admin_dict)
if admin_dict == {}:
print("we have an empty admin_dict")
admin = Admin("admin", "admin", "admin", "admin", "[email protected]", "admin", "12345678")
print("admin is created", admin.get_adminEmail(), admin.get_adminPassword())
users_dict[admin.get_admin_id()] = admin #users_dict[3] = user // user_dict = {1:user, 3:user}
db['admins'] = users_dict #put everything back
db.close()
# Handle admin login here (similar to user login)
admin_email = create_user_form.userEmail.data #It doesn't matter as it is borrowing the fields not the
#corresponding assigned "variable" in forms.py Programming essential
admin_password = create_user_form.userPassword.data
# Check if the admin credentials are valid (you can implement your admin login logic here)
for key, admin_data in admin_dict.items():
if admin_data.get_adminEmail() == admin_email and admin_data.get_adminPassword() == admin_password:
if admin_data.get_adminVerified() == 'deactivated':
#flask.flash("Your account has been deactivated. Please contact an administrator to reactivate your account.", category="danger")
return render_template('/Customer/account/LoginPage.html', form=create_user_form)
else:
session['id'] = key
session['adminfname'] = admin_data.get_adminFirstName()
session['adminlname'] = admin_data.get_adminLastName()
session['adminusername'] = admin_data.get_adminUserName()
session['adminemail'] = admin_data.get_adminEmail()
session['phonenumber'] = admin_data.get_adminPhoneNumber()
session['admin_logged_in'] = True
db.close()
return redirect(url_for('ahome'))
return render_template('/Customer/account/LoginPage.html', form=create_user_form)
@app.route('/Teachers/CreateAccount')
def TeacherHomepage():
return render_template('/Teachers/teacherLoggedInHome.html')
@app.route('/teacher/add_course', methods=['GET', 'POST'])
def add_course():
create_course_form = createCourse(request.form)
if request.method == "POST":
db = shelve.open('Objects/transaction/course.db', 'c')
# course_dict = {}
# try:
# course_dict = db['course']
# except:
# db["course"] = course_dict
# print("Error in retrieving course from course.db")
course = onlineCourse(create_course_form.courseId.data, create_course_form.name.data, create_course_form.videos.data,
create_course_form.price.data, create_course_form.image.data,
create_course_form.studentPurchaseList.data, create_course_form.refundDescription.data,
create_course_form.courseContent.data, create_course_form.requirements.data,
create_course_form.description.data, create_course_form.courseForWho.data,
create_course_form.instructor.data)
db[course.courseId] = course
# print("dATA", create_course_form.courseId.data, create_course_form.name.data)
# print("Course is created", course)
# print("Course Name", course.name)
course_list = []
for key in db.keys():
print("keys: ", key)
print("values: ", db[key])
course_list.append(db[key])
print(course_list)
db.close()
for course in course_list:
print("Course Name", course.name)
print("Course ID", course.courseId)
print("Course Price", course.price)
return render_template('/Teachers/teacherLoggedInHome.html', course_list=course_list, form=create_course_form)
return render_template('/Teachers/teacherLoggedInHome.html', course_list=course_list, form=create_course_form)
@app.route('/')
def CustomerHomepage():
try:
login = session['user_logged_in']
except KeyError:
session['user_logged_in'] = False
return render_template('/Customer/homepage.html')
@app.route('/blog')
def Blog():
return render_template('/Customer/blog.html')
@app.route('/UserRegistrationPage', methods=['GET', 'POST'])
def UserRegistrationPage():
create_user_form = createUser(request.form)
if request.method == "POST":
db = shelve.open('Objects/account/user.db', 'c')
users_dict = {}
try:
users_dict = db['users'] #user_dict = {1:UserObject, 2:UserObject} #take everything out
except:
db["users"] = users_dict
print("Error in retrieving Users from user.db")
userPassword = create_user_form.userPassword.data
userCfmPassword = create_user_form.userCfmPassword.data
if not userPassword == userCfmPassword:
# flash("Password and Confirm Password does not match.", category="danger")
return redirect("/UserRegistration")
user = User(create_user_form.userFullName.data, create_user_form.userName.data, create_user_form.userPassword.data,
create_user_form.userEmail.data, create_user_form.userCfmPassword.data,
create_user_form.userAddress.data, create_user_form.userPostalCode.data, create_user_form.userRole.data)
print("User is created", user)
users_dict[user.get_user_id()] = user #users_dict[3] = user // user_dict = {1:user, 3:user}
db['users'] = users_dict #put everything back
db.close()
send_verification_email(create_user_form.userEmail.data)
#flash('A verification email has been sent. Please check your inbox.', category='success')
session["email_success"] = "A verification email has been sent. Please check your inbox."
#time.sleep(2)
#return redirect("/Login")
return "<script>alert('A verification email has been sent. Please check your inbox.');window.location.href='/Login';</script>"
return render_template('/Customer/account/CustomerRegistration.html', form=create_user_form)
@app.route('/EditCustomerAccount/<int:id>/', methods=['GET', 'POST']) #refer to usersettings "href"
def EditCustomerAccount(id):
edit_user_form = userEditInfo(request.form)
if request.method == 'POST' and edit_user_form.validate():
db = shelve.open('Objects/account/user.db', 'c')
users_dict = {}
try:
users_dict = db['users'] # user_dict = {1:UserObject, 2:UserObject} #take everything out
except:
db["users"] = users_dict
print("Error in retrieving Users from user.db")
tempUser = users_dict[id]
tempUser.set_userFullName(edit_user_form.userFullName.data)
tempUser.set_userName(edit_user_form.userName.data)
tempUser.set_userEmail(edit_user_form.userEmail.data)
tempUser.set_userAddress(edit_user_form.userAddress.data)
tempUser.set_userPostalCode(edit_user_form.userPostalCode.data)
session['userfullname'] = tempUser.get_userFullName()
session['username'] = tempUser.get_userName()
session['useremail'] = tempUser.get_userEmail()
session['useraddress'] = tempUser.get_userAddress()
session['userpostalcode'] = tempUser.get_userPostalCode()
users_dict[id] = tempUser
db['users'] = users_dict
db.close()
return redirect(url_for('UserProfile'))
else:
db = shelve.open('Objects/account/user.db', 'r')
users_dict = db['users']
db.close()
user = users_dict.get(id)
edit_user_form.userFullName.data = user.get_userFullName()
edit_user_form.userName.data = user.get_userName()
edit_user_form.userEmail.data = user.get_userEmail()
edit_user_form.userAddress.data = user.get_userAddress()
edit_user_form.userPostalCode.data = user.get_userPostalCode()
return render_template('Customer/account/editinfo.html', form=edit_user_form)
@app.route('/CustomerChangePassword/<int:id>/', methods=['GET', 'POST'])
def CustomerChangePassword(id):
edit_user_form = userChangePassword(request.form)
if request.method == 'POST' and edit_user_form.validate():
db = shelve.open('Objects/account/user.db', 'c')
users_dict = {}
try:
users_dict = db['users'] # user_dict = {1:UserObject, 2:UserObject} #take everything out
except:
db["users"] = users_dict
print("Error in retrieving Users from Objects/account/user.db")
tempUser = users_dict[id]
tempUser.set_userPassword(edit_user_form.userPassword.data)
tempUser.set_userCfmPassword(edit_user_form.userCfmPassword.data)
users_dict[id] = tempUser
db['users'] = users_dict
db.close()
return redirect(url_for('UserProfile'))
else:
db = shelve.open('Objects/account/user.db', 'r')
users_dict = db['users']
db.close()
user = users_dict.get(id)
edit_user_form.userPassword.data = user.get_userPassword()
edit_user_form.userCfmPassword.data = user.get_userCfmPassword()
return render_template('Customer/account/changepw.html', form=edit_user_form)
@app.route('/UserDeletion/<int:user_id>', methods=['POST'])
def user_deletion(user_id):
db = shelve.open('Objects/account/user.db', 'w')
users_dict = db.get('users', {})
# Check if the user_id exists in the users_dict
if user_id in users_dict:
users_dict.pop(user_id)
db['users'] = users_dict
db.close()
session.clear()
return redirect(url_for('listCustomerAccounts'))
else:
db.close()
return "User not found."
@app.route('/UserDeactivation/<int:user_id>', methods=['POST'])
def user_deactivation(user_id):
db = shelve.open('Objects/account/user.db', 'w')
users_dict = db.get('users', {})
# Check if the user_id exists in the users_dict
if user_id in users_dict:
# Set the user status to 'deactivated' (or any other value to represent deactivation)
user = users_dict[user_id]
user.set_userVerified("deactivated") # Update the status to "deactivated"
db['users'] = users_dict
db.close()
session.clear()
return render_template('/Customer/homepage.html')
else:
db.close()
return "User not found."
@app.route('/AdminDeletion/<int:admin_id>', methods=['POST'])
def admin_deletion(admin_id):
db = shelve.open('Objects/account/user.db', 'w')
admins_dict = db.get('admins', {})
# Check if the admin_id exists in the admins_dict
if admin_id in admins_dict:
admins_dict.pop(admin_id)
db['admins'] = admins_dict
db.close()
session.clear()
return redirect(url_for('listAdminAccounts'))
else:
db.close()
return "Admin not found."
@app.route('/AdminDeactivation/<int:admin_id>', methods=['POST'])
def admin_deactivation(admin_id):
db = shelve.open('Objects/account/user.db', 'w')
admins_dict = db.get('admins', {})
# Check if the admin_id exists in the admins_dict
if admin_id in admins_dict:
# Set the admin status to 'deactivated' (or any other value to represent deactivation)
admin = admins_dict[admin_id]
admin.set_adminVerified("deactivated") # Update the status to "deactivated"
db['admins'] = admins_dict
db.close()
session.clear()
return redirect(url_for('listAdminAccounts'))
else:
db.close()
return "Admin not found."
@app.route('/payment_methods/<int:id>', methods = ['GET', 'POST'])
def PaymentMethod(id):
create_user_payment = userPaymentMethod(request.form)
if request.method == "POST" and create_user_payment.validate():
address = create_user_payment.userAddress.data
email = create_user_payment.userEmail.data
name = create_user_payment.userFullName.data
expiry_date = create_user_payment.userCardExp.data
number = create_user_payment.userCardNumber.data
cvc = create_user_payment.userCardSec.data
print("retrieved expry date", expiry_date)
expiry_list = expiry_date.split('/')
print("expiry_list", expiry_list)
exp_month = expiry_list[0]
print("expiry_month", exp_month)
exp_year = expiry_list[1]
print('expriry year', exp_month)
stripe.PaymentMethod.create(
type="card",
billing_details = {
"address": address,
"email": email,
"name": name
},
card = {
"exp_month": exp_month,
"exp_year": exp_year,
"number": number,
"cvc": cvc
},
)
db = shelve.open('Objects/account/user.db', 'r')
users_dict = db['users']
db.close()
user = users_dict.get(id)
create_user_payment.userFullName.data = user.get_userFullName()
create_user_payment.userName.data = user.get_userName()
create_user_payment.userEmail.data = user.get_userEmail()
create_user_payment.userAddress.data = user.get_userAddress()
create_user_payment.userPostalCode.data = user.get_userPostalCode()
return render_template('/Customer/account/payment.html', form=create_user_payment)
@app.route('/UserHomepage')
def UserHomepage():
if not os.path.exists(user_db_path):
print("we have no user.db")
db = shelve.open(user_db_path, 'c')
db['users'] = {}
db['admins'] = {}
db.close()
return render_template('/Customer/homepage.html')
# Account
@app.route('/UserProfile')
def UserProfile():
edit_user_form = userEditInfo(request.form)
if request.method == 'POST' and edit_user_form.validate():
db = shelve.open('Objects/account/user.db', 'c')
users_dict = {}
try:
users_dict = db['users'] # user_dict = {1:UserObject, 2:UserObject} #take everything out
except:
db["users"] = users_dict
print("Error in retrieving Users from user.db")
tempUser = users_dict[session['id']]
tempUser.set_userFullName(edit_user_form.userFullName.data)
tempUser.set_userName(edit_user_form.userName.data)
tempUser.set_userEmail(edit_user_form.userEmail.data)
tempUser.set_userAddress(edit_user_form.userAddress.data)
tempUser.set_userPostalCode(edit_user_form.userPostalCode.data)
session['userfullname'] = tempUser.get_userFullName()
session['username'] = tempUser.get_userName()
session['useremail'] = tempUser.get_userEmail()
session['useraddress'] = tempUser.get_userAddress()
session['userpostalcode'] = tempUser.get_userPostalCode()
users_dict[id] = tempUser
db['users'] = users_dict
db.close()
return redirect(url_for('UserProfile'))
else:
db = shelve.open('Objects/account/user.db', 'r')
users_dict = db['users']
db.close()
user = users_dict.get(session['id'])
edit_user_form.userFullName.data = user.get_userFullName()
edit_user_form.userName.data = user.get_userName()
edit_user_form.userEmail.data = user.get_userEmail()
edit_user_form.userAddress.data = user.get_userAddress()
edit_user_form.userPostalCode.data = user.get_userPostalCode()
return render_template('/Customer/account/usersettings.html', form=edit_user_form)
@app.route('/OrderStatus')
def OrderStatus():
return render_template('/Customer/account/orderstatus.html')
@app.route('/OrderHistory')
def OrderHistory():
combined_list = []
products_for_order = []
with shelve.open('Objects/transaction/order.db') as order_db:
with shelve.open('Objects/transaction/product.db') as product_db:
for key in order_db:
orderobj = order_db.get(key)
if orderobj.user_id == session['id']:
products_for_order = [product_db.get(pid) for pid in orderobj.product_id]
combined_list.append({
"order": orderobj,
"products": products_for_order
})
for product in products_for_order:
print(product.__dict__)
return render_template('/Customer/account/orderhistory.html', combined_list=combined_list)
@app.route('/addtowishlist/<product_id>')
def AddToWishList(product_id):
with shelve.open('Objects/transaction/product.db') as productdb:
product = productdb[product_id]
for item in wishlistobj.wishlist_items:
print("item's product id matching with product id", item.product_id, product_id)
if item.product_id == product_id:
return redirect(url_for('product_info', product_id=product.product_id, error="product_alr_in_wishlist"))
wishlistobj.add_to_wishlist(WishlistItem(session['id'], product_id, product.name, product.list_price, product.image))
return redirect(url_for('wishList'))
@app.route('/Wishlist')
def wishList():
return render_template('/Customer/account/wishlist.html', wishlist=wishlistobj.wishlist_items)
@app.route('/CustomerAccountDelete')
def CustomerAccountDelete():
return render_template('/Customer/account/accountdelete.html')
@app.route('/sustainability')
def sustainability():
return render_template('/Customer/sustainability.html')
# Transaction
@app.route('/product')
def products():
product_list = []
db_path = 'Objects/transaction/product.db'
review_db_path = 'Objects/transaction/review.db'
try:
db = shelve.open(db_path, 'r')
review_db = shelve.open(review_db_path, 'r')
# Get the filter options from request parameters
category_filter = request.args.get('category')
rating_filter = request.args.get('rating')
for key in db:
product = db[key] #retrieve a COPY of data at key (raise KeyError if no such key)
product_reviews = [review for review in review_db.values(
) if review.product_id == product.product_id]
num_reviews = len(product_reviews)
if num_reviews > 0:
total_rating = sum(review.rating for review in product_reviews)
average_rating = total_rating / num_reviews
else:
average_rating = 0
# Round the average_rating to display in stars
rounded_rating = round(average_rating)
# Add the average_rating and num_reviews to the product object
product.average_rating = rounded_rating
product.num_reviews = num_reviews
# Apply filters if they are selected
if category_filter and category_filter not in product.category:
continue
if rating_filter and int(rating_filter) > rounded_rating:
continue
product_list.append(product)
db.close()
review_db.close()
except:
product_list = []
# Create a list of unique categories from the product_list
categories = list(set(product.category for product in product_list))
# Sort the lists by alphabetical order
sorted_product_list = sorted(product_list, key=lambda product: product.name)
sorted_categories = sorted(categories)
return render_template('/Customer/transaction/Product.html', product_list=sorted_product_list, count=len(product_list), categories=sorted_categories)
@app.route('/product/<product_id>')
def product_info(product_id):
error = request.args.get('error')
error_message=None
if error == "stock_limit_exceeded":
error_message = "You've exceeded the available stock for this product."
elif error == "product_alr_in_wishlist":
error_message = "Product already in wishlist."
review_list = []
pdb_path = 'Objects/transaction/product.db'
db_path = 'Objects/transaction/review.db'
try:
pdb = shelve.open(pdb_path, 'r')
if product_id in pdb.keys():
productobj = pdb[product_id]
pdb.close()
except:
productobj = None
try:
db = shelve.open(db_path, 'r')
for key in db:
review = db[key]
if review.product_id == product_id:
review_list.append(review)
db.close()
except:
review_list = []
# Calculate average rating
total_rating = sum(review.rating for review in review_list)
total_reviews = len(review_list)
average_rating = total_rating / total_reviews if total_reviews > 0 else 0
# Round the average rating up to the nearest whole number
rounded_rating = round(average_rating)
# Create a list of unique colors from the productobj object.
color_options = ', '.join(productobj.color_options)
# Create a list of unique sizes from the productobj object.
size_options = ', '.join(productobj.size_options)
return render_template('/Customer/transaction/ProductInfo.html', productobj=productobj,
review_list=review_list, count=len(review_list), rounded_rating=rounded_rating,
size_options=size_options, color_options=color_options, error_message=error_message)
# for courses
@app.route('/course', methods=['POST', 'GET'])
def courses():
coursesList = []
db_path = 'Objects/transaction/course.db'
review_db_path = 'Objects/transaction/review.db'
try:
db = shelve.open(db_path, 'r')
review_db = shelve.open(review_db_path, 'r')
# Get the filter options from request parameters
category_filter = request.args.get('category')
rating_filter = request.args.get('rating')
for key in db:
course = db[key]
course_reviews = [review for review in review_db.values(
) if review.product_id == course.courseId]
num_reviews = len(course_reviews)
if num_reviews > 0:
total_rating = sum(review.rating for review in course_reviews)
average_rating = total_rating / num_reviews
else:
average_rating = 0
# Round the average_rating to display in stars
rounded_rating = round(average_rating)
# Add the average_rating and num_reviews to the product object
course.average_rating = rounded_rating
course.num_reviews = num_reviews
# Apply filters if they are selected
if category_filter and category_filter not in course.category:
continue
if rating_filter and int(rating_filter) > rounded_rating:
continue
coursesList.append(course)
db.close()
review_db.close()
except:
coursesList = []
#return redirect(url_for('onlineCourse', courseId=courseId))
return render_template('/Customer/transaction/Course.html', course_list=coursesList, count=len(coursesList))
@app.route('/course/<course_id>')
def course_info(course_id):
# error = request.args.get('error')
# error_message=None
# if error == "stock_limit_exceeded":
# error_message = "You've exceeded the available stock for this product."
# elif error == "product_alr_in_wishlist":
# error_message = "Product already in wishlist."
review_list = []
cdb_path = 'Objects/transaction/course.db'
# db_path = 'Objects/transaction/review.db'
try:
cdb = shelve.open(cdb_path, 'r')
if course_id in cdb.keys():
courseobj = cdb[course_id]
cdb.close()
except:
courseobj = None
# try:
# db = shelve.open(db_path, 'r')
# for key in db:
# review = db[key]
# if review.product_id == course_id:
# review_list.append(review)
# db.close()
# except:
# review_list = []
# Calculate average rating
total_rating = sum(review.rating for review in review_list)
total_reviews = len(review_list)
average_rating = total_rating / total_reviews if total_reviews > 0 else 0
# Round the average rating up to the nearest whole number
rounded_rating = round(average_rating)
return render_template('/Customer/transaction/CourseInfo.html', courseobj=courseobj,
)
#create course
@app.route('/admin/courses')
def course_admin():
course_list = []
course_dict = {}
db_path = 'Objects/transaction/course.db'
if not os.path.exists(db_path):
placeholder_data = [
{
"courseId": "C1",
"videos": "https://www.youtube.com/watch?v=XFjzTttyrv8",
"image": "http://www.healthtransformation.net/wp-content/uploads/2015/12/Human-Body-and-Mind-3D-Illustration.jpg",
"price": 15,
"studentPurchaseList": [],
"refundDescription": "30 days maximum",
'name': 'Duality of Body and Mind',
"courseContent": {
'Basic Nutrition Module 1 - Getting started': {
'video':'https://youtu.be/eVBWHnHEX6I?si=PWb9nw5dN0fztcZV',
'article':'https://www.nutrition.gov/about-us#:~:text=Nutrition.gov%20is%20a%20USDA,and%20food%20safety%20for%20consumers',
'image': 'https://247wallst.com/wp-content/uploads/2020/04/imageForEntry9-bbt.jpg',
'quiz': {
1: {
'Question 1': 'Name an example of an fruit','options': ['a) Apple','b) Fish', 'c) Ginger', 'd) Carrot'],'correct_answer': 'a'
},
2: {
'Question 2': 'Which of the following food we have to eat sparingly?', 'options': ['a) French Fries','b) BBQ Chicken', 'c) A plate of chicken bolognese', 'd) Koko Crunch'],
'correct_answer': 'a'
},
3: {
'Question 3': 'What cannot be considered as a measuring tool in your serving size?', 'options': ['a) Hands','b) Measuring Cup', 'c) Measuring Cylinder', 'd) Measuring Spoon'],
'correct_answer': 'c'
}
}
},
'What is Mental Health? Module 2': {
'video':'https://www.youtube.com/embed/G0zJGDokyWQ?si=rKBjzmha55fR9Ov9',
'article':'https://www.cdc.gov/mentalhealth/learn/index.htm',
'image': 'http://www.pickthebrain.com/blog/wp-content/uploads/2014/01/mental-fitness.jpg',
'quiz': {
1: {
'Question 1': 'Name one example of mental disorder', 'options': ['a) Fatigue','b) Excitement', 'c) Anxiety', 'd) Sadness'],
'correct_answer': 'c'
},
2: {
'Question 2': 'Which one is not an example of States of Positive Mental Health?', 'options': ['a) Thriving','b) Content', 'c) Fufilled', 'd) Depression'],
'correct_answer': 'd'
},
3: {
'Question 3': 'What happens if you do not treat mental disorders?', 'options': ['a) You will be happier','b) You will definitely age gracefully', 'c) You will have increased disability', 'd) None of the above'],
'correct_answer': 'c'
}
}
},
'Motivation and What Really Drives Human Behavior? Module 3': {
'video':'https://www.youtube.com/watch?v=IhEcX3226pM',
'article':'https://positivepsychology.com/motivation-human-behavior/',
'image':'https://1.bp.blogspot.com/-w7NNijz2U_o/VZhnyAGnYKI/AAAAAAAAAHU/CMXUZbX4itk/s1600/school-of-psychology-2.jpg',
'quiz': {
1: {
'Question 1': 'What is the 3 ideal solutions to solve complex things coming from your background?', 'options': ['a) Change your behavior, Comparing your personal truth with others positively, Behave your way to success','b) Stop rewarding bad behavior, Comparing your personal truth with others positively, Behave your way to success', 'c) Change your behavior, Stop rewarding bad behavior, Comparing your personal truth with others positively', 'd) Change your behavior, Stop rewarding bad behavior, Behave your way to success'],
'correct_answer': 'd'
},
2: {
'Question 2': 'What is a possible way to improve your results in life?', 'options': ['a) Fix your personal truth','b) Researching more on a topic', 'c) Change your social circle', 'd) Fix your personal weakness'],
'correct_answer': 'a'
},
3: {
'Question 3': 'What is Drive Motivation?', 'options': ['a) When you want to do something.','b) When talking about motivation, the topic of goals inevitably comes up.', 'c) When the sympathetic nervous system produces epinephrine and norepinephrine, it creates energy for action.', 'd) None of the above'],
'correct_answer': 'c'
}
}
},
'How To Set SMART Goals for Better Health and Wellness? Module 4': {
'video':'https://www.youtube.com/watch?v=IzuGj8hKGTc',
'article':'https://www.noomii.com/articles/13906-smart-goal-method',
'image':'http://www.boardandlife.com/wp-content/uploads/2019/10/why-is-goal-setting-important-organizations.jpg',
'quiz': {
1: {
'Question 1': 'Which one is the acronym for SMART Goals?', 'options': ['a) Measurable','b) Monetary', 'c) Meaningful', 'd) Mortified'],
'correct_answer': 'a'
},
2: {
'Question 2': 'What is an example Achievable Goal?', 'options': ['a) Should I eat 3 vegetables a day?','b) I will eat 2 vegetables a day, 2 times a week.', 'c) I will eat 200 vegetables a day, 2 times a week.', 'd) I will go to the gym 30 times a day.'],
'correct_answer': 'b'
},
3: {
'Question 3': 'How to create a SMART Goal Map?', 'options': ['a) Identify your long-term vision','b) Develop work-life balance', 'c) Creating a scehdule', 'd) None of the above'],
'correct_answer': 'a'
}
}
}
},
"requirements": "Compulsory to attend at least one module",
"description": "Here in this course, we will cover 2 different areas related to both the human body and the human mind! With 4 modules, this comprehensive course leaves no stone unturned! This course includes quizzes, videos and articles. introduction: 20 mins, module 1 : 30 mins, module 2 : 15 mins, module 3 : 25 mins, module 4 : 30 mins, total time taken: 2 hours",
"courseForWho": "For anyone aged above 12 years old",
"instructor": "Chen Wei Jie"
}
]
db = shelve.open(db_path, 'c')
for data in placeholder_data:
course = onlineCourse(
data["courseId"],
data["name"],
data["videos"],
data["price"],
data["image"],
data["studentPurchaseList"],
data["refundDescription"],
data["courseContent"],
data["requirements"],
data["description"],
data["courseForWho"],
data["instructor"],
)
db[course.courseId] = course
db.close()
course_list = []
db = shelve.open(db_path, 'r')
# open the db and retrieve the dictionary
for course_id, course_obj in db.items():
course_list.append(course_obj)
db.close()
# prints out all the products and their info
for course in course_list:
print(course.courseId, course.videos, course.price, course.name, course.studentPurchaseList, course.refundDescription, course.courseContent, course.requirements, course.description, course.courseForWho, course.instructor)
print("Course ID: ", course.courseId, "\n", "Product video: ", course.videos, "\n", "\n", "Course Price: ", course.price, "\n", "Course Name", course.name, "\n", "Student Purchase List: ", course.studentPurchaseList, "\n", "Refund Description: ", course.refundDescription, "\n", "Course Content: ", course.courseContent, "\n", "Requirements: ", course.requirements, "\n", "Description:", course.description, "\n", "Course For Who:", course.courseForWho, "\n", "Instructor: ", course.instructor)
course_form = createCourse(request.form)
return render_template('/Teachers/teacherLoggedInHome.html', course_list=course_list, count=len(course_list), form=course_form)
#688 - 822
@app.route('/review/<product_id>', methods=['POST'])
def add_review(product_id):
db_path = 'Objects/transaction/review.db'
# Retrieve the form data
customer_name = request.form['customer_name']
rating = int(request.form['rating'])
review_comment = request.form['review_comment']
try:
db = shelve.open(db_path, 'w') # Open the review.db in read-write mode
except:
db = shelve.open(db_path, 'c')
# Generate a new review_id by finding the highest review_id and incrementing it by 1
max_review_id = 0
if db:
# Check if the db is not empty before calculating the max_review_id
max_review_id = max((int(review_id[1:]) for review_id in db.keys(
) if review_id.startswith('R')), default=0)
new_review_id = "R" + str(max_review_id + 1)
# user_id = session['id']
user_id = 0
# Create a new Review object
review = Review(new_review_id, product_id, user_id,
customer_name, rating, review_comment)
# Save the review to the review_db
db[new_review_id] = review
db.close()
return redirect(url_for('product_info', product_id=product_id))
@app.context_processor
def cart_items_processor():
num_items_in_cart = sum(item.quantity for item in cartobj.get_cart_items())
return {'num_items_in_cart': num_items_in_cart}
@app.context_processor
def wishlist_items_processor():
num_items_in_wishlist = len(wishlistobj.wishlist_items)
return {'num_items_in_wishlist': num_items_in_wishlist}
@app.route('/product', methods=['POST'])
def add_to_cart():
product_id = request.form['product_id']
# Fetch the product details from the database
db_path = 'Objects/transaction/product.db'
db = shelve.open(db_path, 'r')
product = db.get(product_id)
default_quantity = 1
default_color = None
default_size = None
if product.color_options != [] or product.size_options != []:
default_color = product.color_options[0]
default_size = product.size_options[0]
db.close()
quantity = int(request.form.get('quantity', default_quantity))
size = default_size
color = default_color
if product.color_options != [] or product.size_options != []:
size = request.form.get('size', default_size)
color = request.form.get('color', default_color)
# Fetch the current quantity of the product in the cart
current_quantity_in_cart = 0
for item in cartobj.get_cart_items():
if item.product_id == product_id:
current_quantity_in_cart = item.quantity
break
# Check the total desired quantity against the stock
if current_quantity_in_cart + quantity > product.stock:
# Handle the scenario where desired quantity exceeds available stock
quantity = product.stock - current_quantity_in_cart
return redirect(url_for('product_info', product_id=product.product_id, error="stock_limit_exceeded"))
# Create an item object with the product details and the selected quantity