-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApplication.py
2499 lines (2139 loc) · 95.1 KB
/
Application.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 shelve, string, random
from flask import Flask, render_template, request, redirect, url_for
from Forms import *
from StorageClass import *
from Functions import *
from User import *
from deliveryDetails import *
from Discount import *
from feedback import *
from datetime import date
import re
from decimal import Decimal
# Image download
from werkzeug.utils import secure_filename
import os
from pathlib import Path
# Graphing
import json, plotly
import pandas as pd
import numpy as np
import plotly.graph_objs as go
import flask_excel as excel
# Flask mail
from flask_mail import Mail, Message
import sys
import asyncio
from threading import Thread
#Saving the transaction data temporarily before confirmation
import pickle
# print('MAIL_PASSWORD' in os.environ)
app = Flask(__name__, static_url_path='/static')
app.config.update(
MAIL_SERVER= 'smtp.office365.com',
MAIL_PORT= 587,
MAIL_USE_TLS= True,
MAIL_USE_SSL= False,
MAIL_USERNAME = '[email protected]',
# MAIL_PASSWORD = os.environ["MAIL_PASSWORD"],
MAIL_DEBUG = True,
MAIL_SUPPRESS_SEND = False,
MAIL_ASCII_ATTACHMENTS = True
)
# Getting valid discount codes and checking if they are expired
# db = shelve.open('storage.db','c')
# try:
# valid_discount = db["Valid Discount"]
# except:
# print("Either we got none or like we can't get discounts stuffy")
# AmountDiscount = valid_discount["Amount"]
# PercentageDiscount = valid_discount["Percentage"]
# amount_discount = {}
# percentage_discount = {}
# updated_discount = {}
# for code in AmountDiscount:
# if AmountDiscount[code].get_start_date() < date.today() and AmountDiscount[code].get_expiry_date() > date.today():
# amount_discount[code] = AmountDiscount[code]
# for code in PercentageDiscount:
# if PercentageDiscount[code].get_start_date() < date.today() and PercentageDiscount[code].get_expiry_date() > date.today():
# percentage_discount[code] = PercentageDiscount[code]
# updated_discount["Amount"] = amount_discount
# updated_discount["Percentage"] = percentage_discount
# db["Valid Discount"] = updated_discount
# db.close()
# def checkfordiscounts():
# db = shelve.open('storage.db', 'c')
# try:
# valid_discount = db["Valid Discount"]
# except:
# print("bchscbweucw")
# amount_discounts = valid_discount["Amount"]
# percentage_discounts = valid_discount["Percentage"]
# valid_amount_discounts = {}
# valid_percentage_discounts = {}
# for code in amount_discounts:
# if amount_discounts[code].get_start_date() < date.today() and amount_discounts[code].get_expiry_date() > date.today():
# valid_amount_discounts[code] = amount_discounts[code]
#
# for code in percentage_discounts:
# if percentage_discounts[code].get_start_date() < date.today() and percentage_discounts[code].get_expiry_date() > date.today():
# valid_percentage_discounts[code] = percentage_discounts[code]
#
# valid_discount["Amount"] = valid_amount_discounts
# valid_discount["Percentage"] = valid_percentage_discounts
# db["Valid Discount"] =valid_discount
#
# db.close()
# return valid_discount
def checkfordiscounts():
db = shelve.open('storage.db', 'c')
valid_discount = {}
discount_master =[]
try:
valid_discount = db["Valid Discount"]
# expired_discount = db["Expired"]
discount_master = db["Discount Master"]
except:
print("bchscbweucw")
amount_discounts = valid_discount["Amount"]
percentage_discounts = valid_discount["Percentage"]
valid_amount_discounts = {}
valid_percentage_discounts = {}
for code in amount_discounts:
if amount_discounts[code].get_start_date() < date.today() and amount_discounts[code].get_expiry_date() > date.today():
valid_amount_discounts[code] = amount_discounts[code]
status = "active"
elif amount_discounts[code].get_start_date() < date.today() and amount_discounts[code].get_expiry_date() <date.today():
status = "expired"
else:
status = "inactive"
for discount in discount_master:
if discount == amount_discounts[code]:
discount.set_status(status)
break
amount_discounts[code].set_status(status)
for code in percentage_discounts:
if percentage_discounts[code].get_start_date() < date.today() and percentage_discounts[code].get_expiry_date() > date.today():
valid_percentage_discounts[code] = percentage_discounts[code]
status = "active"
elif percentage_discounts[code].get_start_date() < date.today() and percentage_discounts[code].get_expiry_date() <date.today():
status = "expired"
else:
status = "inactive"
for discount in discount_master:
if discount == percentage_discounts[code]:
discount.set_status(status)
percentage_discounts[code].set_status(status)
valid_discount["Amount"] = valid_amount_discounts
valid_discount["Percentage"] = valid_percentage_discounts
db["Valid Discount"] = valid_discount
db["Discount Master"] = discount_master
db.close()
return valid_discount
checkfordiscounts()
mail = Mail(app)
def searchBar():
return SearchBar(request.form)
def testing():
productDict = {}
db = shelve.open('storage.db', 'c')
productDict = db['Products']
print(productDict)
for product in productDict:
productDict[product].increase_purchases(random.randint(1,50))
for x in range(random.randint(40,150)):
productDict[product].increase_views()
db['Products'] = productDict
db.close()
def discount_box(user):
amount_show = {}
percentage_show = {}
show = {}
amount_dont = []
percentage_dont = []
db = shelve.open('storage.db', 'r')
try:
valid_discount = db['Valid Discount']
except:
valid_discount = False
amount_discounts = valid_discount.get("Amount")
percentage_discounts = valid_discount.get("Percentage")
# print(amount_discounts)
db.close()
if user is False:
show["Amount"] = amount_discounts
show["Amount"] = amount_discounts
else:
users_codes = user.get_discount_codes()
print(users_codes)
if valid_discount is not False and bool(users_codes) is True:
if bool(amount_discounts) is True:
amount_show = amount_discounts
for user_code in users_codes:
for stored_code in amount_discounts:
if user_code.get_code() == stored_code:
print("HERE BIVH")
amount_dont.append(stored_code)
if bool(amount_dont) is True:
for code in amount_dont:
del amount_show[code]
print(amount_show)
if bool(percentage_discounts) is True:
percentage_show = percentage_discounts
for user_code in users_codes:
for stored_code in percentage_discounts:
if user_code.get_code() == stored_code:
# dont_show.append(user_code)
percentage_dont.append(stored_code)
if bool(percentage_dont):
for code in percentage_dont:
del percentage_show[code]
print(percentage_show)
elif valid_discount is not False and bool(users_codes) is False:
if bool(amount_discounts) is True:
amount_show = amount_discounts
if bool(percentage_discounts) is True:
percentage_show = percentage_discounts
show["Amount"] = amount_show
show["Percentage"] = percentage_show
return show
@app.route('/search/<searchString>/<category>/<order>', methods=['GET', 'POST'])
def search(searchString, category, order):
searchString = searchString.lower()
cart=[]
db = shelve.open('storage.db', 'r')
try:
Products = db["Products"]
except:
print("Error in retrieving products from shelve")
try:
current = db["Current User"]
cart = current.get_shopping_cart()
Items = len(cart)
except:
print("Error in retrieving current user")
current = False
Items = 0
products = []
for id in Products:
product = Products[id]
if searchString in product.get_product_name().lower() or searchString in product.get_brand().lower():
if product.get_activated() == True:
products.append(product)
products = sort_by(products, category, order)
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
return redirect('/search/' + searchForm.search_input.data + '/view/descending')
return render_template('search.html', productList=products, searchString=searchString, productCount=len(products), searchForm=searchForm, current=current, Items=len(cart))
# Homepage
@app.route('/home', methods=['GET', 'POST'])
def home():
checkfordiscounts()
productDict = {}
db = shelve.open('storage.db', 'c')
try:
current = db["Current User"]
cart = current.get_shopping_cart()
Items = len(cart)
except:
print("Error while retrieving current user: user not logged in")
current = False
Items = 0
try:
productDict = db['Products']
db.close()
except:
print('Error in retrieving Products from storage.db.')
productList = []
for key in productDict:
product = productDict[key]
productList.append(product)
purchasesList = sort_by(productList, 'purchase', 'descending')[:6]
viewsList = sort_by(productList,'view','descending')[:6]
show = discount_box(current)
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
return redirect('/search/' + searchForm.search_input.data + '/view/descending')
return render_template("home.html", current=current, searchForm=searchForm, purchasesList=purchasesList, viewsList=viewsList, Items=Items, show=show)
# Profile/Username
@app.route('/my-account/<username>', methods=['GET', 'POST'])
def view_profile(username):
db = shelve.open("storage.db", "c")
try:
usersDict = db["Users"]
namesDict = db["Usernames"]
current = db["Current User"]
cart = current.get_shopping_cart()
Items = len(cart)
except:
print("Error while retrieving usersDict")
return redirect(url_for("home"))
editProfileForm = EditProfileForm(request.form)
if editProfileForm.address.data or editProfileForm.phone.data != "":
activate_disabled_btn = True
invalid_phone_num_error = False
edit_email_valid = False
empty_username_error = False
if not editProfileForm.username.data.isalnum():
if editProfileForm.username.data == "":
empty_username_error = True
if request.method == "POST":
current_id = current.get_user_id()
del namesDict[current.get_username()]
if empty_username_error:
print("Username cannot be left blank.")
else:
current.set_username(editProfileForm.username.data)
current.set_address(editProfileForm.address.data)
# check for valid phone number
try:
number = str(editProfileForm.phone.data)
print("\n\n\n\n\n")
if number[0] == "6" or number[0] == "8" or number[0] == "9":
if (len(number) == 8):
current.set_phone(editProfileForm.phone.data)
else:
current.set_phone("None")
invalid_phone_num_error = True;
else:
current.set_phone("None")
invalid_phone_num_error = True;
except:
current.set_phone("None")
#check for valid email
try:
regexEmail = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
if (re.search(regexEmail,editProfileForm.email.data)):
#email is valid
edit_email_valid = True
current.set_email(editProfileForm.email.data)
else:
edit_email_valid = False
print("Email is incorrect format/cannot be left blank.")
except:
current.set_email("None")
print(current.get_password())
if current.get_password() == editProfileForm.password.data:
if editProfileForm.newpassword.data != "":
current.set_password(editProfileForm.newpassword.data)
print("New password set for user " + current.get_username() + ", " + editProfileForm.newpassword.data + ".")
elif editProfileForm.newpassword.data == "":
print("New password field was left empty.")
print("No new password was set.")
elif editProfileForm.newpassword.data != editProfileForm.password.data:
if editProfileForm.password.data == "":
print("Current password field was left empty.")
else:
print("Current user password was incorrect.")
else:
print("\n\n\nAn unexpected error has occured.\n\n\n")
usersDict[current_id] = current
namesDict[current.get_username()] = current_id
db["Users"] = usersDict
db["Usernames"] = namesDict
db["Current User"] = current
# edit_email_valid = True
# empty_username_error = True
# invalid_phone_num_error = True
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
print(searchForm.search_input.data)
db.close()
return render_template('my-account.html', current=current, edit_email_valid=edit_email_valid, empty_username_error=empty_username_error, invalid_phone_num_error=invalid_phone_num_error, name=current.get_username(), address=current.get_address(), phone=current.get_phone(), email=current.get_email(), searchForm=searchForm, Items=Items)
else:
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
print(searchForm.search_input.data)
db.close()
return render_template('my-account.html', current=current,edit_email_valid=True, empty_username_error=False, invalid_phone_num_error=False, name=current.get_username(), address=current.get_address(), phone=current.get_phone(), email=current.get_email(), searchForm=searchForm, Items=Items)
@app.route('/my-account/delete_account')
def deleteUser():
db = shelve.open("storage.db", "c")
try:
usersDict = db["Users"]
namesDict = db["Usernames"]
current = db["Current User"]
except:
print("Error while retrieving usersDict")
current_id = current.get_user_id()
print("\n\n\n")
print(f"{usersDict[current_id].get_username()} is deleted.")
print("\n\n\n")
del usersDict[current_id]
db["Users"] = usersDict
del namesDict[current.get_username()]
db["Usernames"] = namesDict
db["Current User"] = ""
db.close()
return redirect(url_for("home"))
# Login/Register
@app.route('/login', methods=['GET', 'POST'])
def login():
db = shelve.open("storage.db", "c")
try:
current = db["Current User"]
except:
current = ""
print("Error in retrieving current user")
if current == "":
loginForm = LoginForm(request.form)
registrationForm = RegistrationForm(request.form)
if request.method == "POST" and registrationForm.validate():
db = shelve.open('storage.db', 'c')
namesDict = {}
usersDict = {}
try:
usersDict = db['Users']
except:
print('Error while retrieving usersDict')
try:
namesDict = db['Usernames']
except:
print("Error while retrieving namesDict")
unique_email = True
unique_username = True
valid_email_registration = True
secure_pwd = True
regexEmail = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
for user in usersDict.values():
#check email is correct format
if not(re.search(regexEmail, registrationForm.email.data)):
print("Invalid Email")
valid_email_registration = False
break
#check for registered username in system
if registrationForm.username.data == user.get_username():
unique_username = False
print("Username in use, you cannot create an account with the same username.")
break
#check for registered email in system
if registrationForm.email.data == user.get_email():
unique_email = False
print("Email in use, you cannot create an account with the same email.")
break
#check password meets minimum requirement for strong pwd
if len(registrationForm.password.data) < 6:
print('length should be at least 6')
secure_pwd= False
break
if not any(char.isdigit() for char in registrationForm.password.data):
print('Password should have at least one numeral')
secure_pwd = False
break
if not any(char.isupper() for char in registrationForm.password.data):
print('Password should have at least one uppercase letter')
secure_pwd = False
break
if not any(char.islower() for char in registrationForm.password.data):
print('Password should have at least one lowercase letter')
secure_pwd = False
break
# if not any(char in SpecialSym for char in registrationForm.password.data):
# print('Password should have at least one of the symbols $@#')
# secure_pwd = False
break
if unique_email and valid_email_registration and secure_pwd and unique_username:
U = User(registrationForm.username.data, registrationForm.password.data, registrationForm.email.data)
usersDict[U.get_user_id()] = U
namesDict[U.get_username()] = U.get_user_id()
db['Users'] = usersDict
db['Usernames'] = namesDict
db.close()
print("User created with name", U.get_username(), "id", U.get_user_id(),
"Password", U.get_password(), "and Email", U.get_email())
else:
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
print(searchForm.search_input.data)
return render_template("login.html", edit_email_valid=True, empty_username_error=False, invalid_phone_num_error=False, unique_email=unique_email, unique_username=unique_username, valid_email_registration=valid_email_registration, secure_pwd = secure_pwd, form=loginForm, form2=registrationForm, searchForm=searchForm)
if request.method =="POST" and loginForm.validate():
usersDict = {}
namesDict = {}
db = shelve.open('storage.db', 'r')
try:
usersDict = db["Users"]
except:
print("Error while retrieving usersDict")
try:
namesDict = db["Usernames"]
except:
print("Error while retrieving namesDict")
if loginForm.username.data == "admin" and loginForm.password.data == "admin":
return redirect('/dashboard/1')
username_exist = False
login_correct = False
success_login = False
for name in namesDict:
if name == loginForm.username.data:
username_exist = True
username_id = namesDict[loginForm.username.data]
break
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
print(searchForm.search_input.data)
if username_exist:
user_obj = usersDict[username_id]
if user_obj.get_password() == loginForm.password.data:
success_login = True
db["Current User"] = user_obj
print("User successfully logged in")
return redirect(url_for("home"))
else:
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
print(searchForm.search_input.data)
print("Credentials are incorrect.")
return render_template('login.html', username_correct=False, edit_email_valid=True, empty_username_error=False, invalid_phone_num_error=False, unique_email=True, unique_username=True, valid_email_registration=True, secure_pwd = True, form=loginForm, form2=registrationForm, searchForm=searchForm)
else:
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
print(searchForm.search_input.data)
print("User does not exist.")
return render_template('login.html', username_correct=False, edit_email_valid=True, empty_username_error=False, invalid_phone_num_error=False, unique_email=True, unique_username=True, valid_email_registration=True, secure_pwd = True, form=loginForm, form2=registrationForm, searchForm=searchForm)
else:
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
print(searchForm.search_input.data)
return render_template('login.html', username_correct=True, edit_email_valid=True, empty_username_error=False, invalid_phone_num_error=False, unique_email=True, unique_username=True, valid_email_registration=True, secure_pwd = True, form=loginForm, form2=registrationForm, searchForm=searchForm)
print("Exception Error: navigating home.html to login.html")
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
return redirect('/search/' + searchForm.search_input.data + '/view/descending')
return render_template('login.html', username_correct=True, edit_email_valid=True, empty_username_error = False, invalid_phone_num_error=False, unique_email=True, unique_username=True, valid_email_registration=True, secure_pwd = True, form=loginForm, form2=registrationForm, searchForm=searchForm)
else:
return redirect(url_for("home"))
@app.route('/logout')
# @login_required
def logout():
db = shelve.open("storage.db", "c")
db["Current User"] = ""
print("User logged out successfully")
return redirect(url_for('home'))
# return render_template("home.html", current="", logged_out=True)
@app.route('/FAQ')
def viewFAQ():
db = shelve.open("storage.db", "r")
current = db["Current User"]
cart = current.get_shopping_cart()
Items = len(cart)
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
return redirect('/search/' + searchForm.search_input.data + '/view/descending')
return render_template("FAQ.html", current=current, searchForm=searchForm, Items=Items)
@app.route('/orderHistory', methods=['GET'])
def orderHistory():
db = shelve.open("storage.db", "r")
transactions ={}
# try:
current = db["Current User"]
cart = current.get_shopping_cart()
Items = len(cart)
transactions = db["Transactions"]
current_transac_list = current.get_transactions()
print("\n\n\n")
for transaction in current_transac_list:
obj = transactions[transaction]
print(transaction) #prints order ID
print(obj.get_date_of_order())
date_of_order = obj.get_date_of_order()
print(obj) #prints object
items = obj.get_items()
print("\n\n\n")
searchForm = searchBar()
return render_template('orderHistory.html', date_of_order=date_of_order, transaction=obj, current_transac_list=current_transac_list, searchForm=searchForm, Items=Items, current=current, items=transactions)
@app.route('/mainCategory/<mainCategory>/<category>/<order>/', methods=['GET', 'POST'])
def mainCategory(mainCategory, category, order):
checkfordiscounts()
db = shelve.open('storage.db', 'r')
try:
Products = db["Products"]
except:
print("Error in retrieving products from shelve")
try:
current = db["Current User"]
Items = len(current.get_shopping_cart())
except:
print("Error in retrieving current user, subcat")
current = False
Items = 0
show = discount_box(current)
db.close()
products = []
for id in Products:
product = Products[id]
if get_main_category(product.get_sub_category()).replace(' ','') == mainCategory:
if product.get_activated() == True:
products.append(product)
products = sort_by(products, category, order)
mainCategory = get_name_with_space(mainCategory)
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
return redirect('/search/' + searchForm.search_input.data + '/view/descending')
return render_template('mainCategory.html', productList=products, productCount=len(products), mainCategory=mainCategory, searchForm=searchForm, current=current, Items=Items, show=show)
# Supplements(one of the subsections)
@app.route('/subCategory/<subCategory>/<category>/<order>/', methods=['GET', 'POST'])
def subCategory(subCategory, category, order):
checkfordiscounts
db = shelve.open('storage.db', 'r')
try:
Products = db["Products"]
except:
print("Error in retrieving products from shelve")
try:
current = db["Current User"]
Items = len(current.get_shopping_cart())
except:
print("Error in retrieving current user, subcat")
current = False
Items = 0
show = discount_box(current)
db.close()
products = []
for id in Products:
product = Products[id]
if product.get_sub_category() == subCategory:
if product.get_activated() == True:
products.append(product)
mainCategory = get_main_category(subCategory)
bmainCat = mainCategory.replace(' ', '')
products = sort_by(products, category, order)
subCategory = get_name_with_space(subCategory)
searchForm = searchBar()
if request.method == "POST" and searchForm.validate():
return redirect('/search/' + searchForm.search_input.data + '/view/descending')
return render_template('subCategory.html', bmainCat=bmainCat, productList=products, subCategory=subCategory, productCount=len(products), mainCategory=mainCategory, searchForm=searchForm, current=current, Items=Items, show=show)
# Ribena(one of the products)
@app.route('/IndItem/<serialNo>', methods=['GET', 'POST'])
def IndItem(serialNo):
checkfordiscounts()
db = shelve.open('storage.db','w')
try:
products = db['Products']
except:
print("Error while retrieving products from storage.")
try:
current = db['Current User']
Items = len(current.get_shopping_cart())
except:
current = False
print("Unable to get the current dude!")
Items = 0
show = discount_box(current)
IndItem = products[serialNo]
IndItem.increase_views()
class QuantityForm(Form):
quantity = IntegerField("Quantity", [validators.NumberRange(min=1, max=IndItem.get_quantity(), message="Please select a valid quantity. There are only " + str(IndItem.get_quantity()) + " of this product currently.")])
Quantity = QuantityForm(request.form)
try:
wishlist = current.get_wishlist()
taken = False
for serial_no in wishlist:
if serial_no == serialNo:
taken = True
break
except:
taken = False
try:
cart = current.get_shopping_cart()
bought = False
amount = 0
for serial_no in cart:
if serial_no == serialNo:
bought = True
amount = cart[serial_no]
break
except:
bought = False
amount = 0
db['Products'] = products
db.close()
subCategory = IndItem.get_sub_category()
mainCategory = get_main_category(subCategory).replace(' ','')
relatedProducts = []
for serial_no in products:
if get_main_category(products[serial_no].get_sub_category()) == mainCategory:
relatedProducts.append(products[serial_no])
relatedProducts.remove(IndItem)
related = []
for i in range(4):
max = len(relatedProducts)
if max <= 1:
break
max -= 1
number = random.randint(0,max)
related.append(relatedProducts[number])
relatedProducts.pop(number)
searchForm = searchBar()
# if request.method == "POST" and searchForm.validate():
# return redirect('/search/' + searchForm.search_input.data + '/view/descending')
if request.method == "POST" and Quantity.validate():
quantity = Quantity.quantity.data
return redirect(url_for('addToCart', name = IndItem.get_product_name(), quantity = quantity))
return render_template('IndItem.html', product=IndItem, mainCategory=mainCategory, searchForm=searchForm, current=current, taken=taken, related=related, Items=Items, QuantityForm = Quantity, Bought = bought, amount = amount,show=show)
# Shopping Cart
@app.route('/cart', methods=['GET', 'POST'])
def cart():
checkfordiscounts()
deducted=0
discount= ''
new_total = 0
Delivery = NoCollectForm(request.form)
Discount = DiscountForm(request.form)
db = shelve.open('storage.db','r')
current_discount = ''
try:
current = db['Current User']
products = db["Products"]
except:
print('Error reading Current User.')
current = False
products = {}
show = discount_box(current)
cart = current.get_shopping_cart()
db.close()
cartList = []
totalCost = 0
for serial_no in cart:
product = products[serial_no]
totalCost += float(product.get_price())*int(cart[serial_no])
product.set_quantity(cart[serial_no])
cartList.append(product)
totalCost = '%.2f' %float(totalCost)
Items = len(cartList)
current_discount = current.get_current_discount()
print(current_discount)
empty = not bool(current_discount)
if empty == False:
print("vcgashjkl")
deducted = current_discount["deducted"]
discount = current_discount["discount"]
new_total = float(current_discount["amt_after"])
if request.method == "POST" and Delivery.validate():
print("HIIIIIIIIII")
NoCollect = Delivery.home_delivery.data
if NoCollect == True:
return redirect(url_for('checkout',delivery=NoCollect))
else:
searchForm = searchBar()
# if request.method == "POST" and searchForm.validate():
# return redirect('/search/' + searchForm.search_input.data + '/view/descending')
return redirect(url_for('checkout', delivery=False))
#
# if request.method == "POST" and Discount.validate():
# code = Discount.discount_code.data
searchForm = searchBar()
# discount = ''
# if request.method == "POST" and searchForm.validate():
# return redirect('/search/' + searchForm.search_input.data + '/view/descending')
# return render_template('cart.html', cartList=cartList, totalCost=totalCost, searchForm=searchForm, current=current, NoCollectForm = Delivery, Discount=Discount, codes=codes, Items = Items, discount=discount)
new_total = totalCost
return render_template('cart.html', cartList=cartList, totalCost=totalCost, searchForm=searchForm, current=current, NoCollectForm = Delivery, Discount=Discount, Items = Items, discount=discount, new_total= new_total, current_discount=current_discount, deducted = deducted, show=show)
@app.route('/useDiscount', methods=['POST'])
def useDiscount():
checkfordiscounts()
searchForm = searchBar()
Delivery = NoCollectForm(request.form)
Discount = DiscountForm(request.form)
discount= ''
current = ""
valid_discount = {}
users_codes = []
new_total =0
deducted = 0
error_msg=''
current_discount = ''
if request.method == "POST" and Discount.validate():
print("YOOOOOOOOOOOOOOOOOOOOO")
code = Discount.discount_code.data
db = shelve.open('storage.db', 'c')
valid_discount = {}
try:
print("Get current")
current = db["Current User"]
except:
print("Error in retrieving current user from storage.db")
show = discount_box(current)
users_codes = current.get_discount_codes()
try:
print("gettinng valid discounts")
valid_discount = db["Valid Discount"]
except:
print("Error in retrieving valid discounts from storage.db")
try:
print("gettinng Products cuz we need em now")
products = db["Products"]
except:
print("Error in retrieving valid discounts from storage.db")
cart = current.get_shopping_cart()
users_codes = current.get_discount_codes()
print(users_codes)
cartList = []
totalCost = 0
for product in cart:
item = products[product]
totalCost += float(item.get_price()) * int(cart[product])
cartList.append(item)
totalCost = '%.2f' %float(totalCost)
Items = len(cartList)
#check use
check_used = False
empty = not bool(users_codes)
if empty == True:
print("check empty")
check_used = False
else:
for object in users_codes:
if object.get_code() == code:
print(object.get_code())
check_used = True
error_msg = "You have already used " + code+ "!"
db.close()
return render_template('cart.html', cartList=cartList, totalCost=totalCost, current=current, NoCollectForm = Delivery, Discount=Discount, Items=Items, error_msg=error_msg, discount=discount, new_total=new_total , searchForm=searchForm, current_discount = current_discount, deducted = deducted, show=show)
# return render_template('cart.html', cartList=cartList, totalCost=totalCost, searchForm=searchForm, current=current, NoCollectForm = Delivery, Discount=Discount, Items = Items)
amount_discounts = {}
percentage_discounts = {}
amount_empty = not bool(valid_discount["Amount"])
percentage_empty = not bool(valid_discount["Percentage"])
valid = False
if amount_empty is False:
amount_discounts = valid_discount["Amount"]
for key in amount_discounts:
if key == code:
valid = True
type = "amount"
condition = float(amount_discounts[key].get_condition())
discount_in_storage = amount_discounts[key]
break
if percentage_empty is False:
percentage_discounts = valid_discount["Percentage"]
for key in percentage_discounts:
if key == code:
valid = True
type = "percentage"
condition = float(percentage_discounts[key].get_condition())
discount_in_storage = percentage_discounts[key]
break
error_msg = "Invalid discount code."
if valid == False:
db.close()
error_msg = "Invalid discount code."
return render_template('cart.html', cartList=cartList, totalCost=totalCost, current=current, NoCollectForm = Delivery, Discount=Discount, Items=Items, error_msg=error_msg, discount=discount, new_total=new_total, searchForm=searchForm, current_discount=current_discount, deducted = deducted, show=show)
if valid is True and check_used==False and float(totalCost) >= condition:
print("TRUUUUU")
discount = discount_in_storage
print(discount)
print(users_codes)
current_discount = current.get_current_discount()
current_discount["discount"] = discount
totalCost = '%.2f' %float(totalCost)
current_discount["amt_before"] = totalCost
# totalCost = totalCost
condition = discount.get_condition()
if float(totalCost) >= (condition):
totalCost = Decimal(format(float(totalCost), '.2f'))
if isinstance(discount, AmountDiscount):
print("its here")
amount = discount.get_discount_amount()
deducted = amount
new_total = totalCost - Decimal(format(float(amount), '.2f'))
current_discount["amt_after"] = Decimal(format(new_total, '.2f'))
current_discount["deducted"] = amount
else:
percentage = discount.get_discount_percentage()
new_total = totalCost - totalCost * (percentage /100)
current_discount["amt_after"] = Decimal(format(new_total, '.2f'))
current_discount["deducted"] = Decimal(format(totalCost * percentage/100 , '.2f'))
deducted = current_discount["deducted"]
totalCost = '%.2f' %float(totalCost)
new_total = Decimal(format(new_total, '.2f'))
current.set_current_discount(current_discount)
db["Current User"] = current
db.close()
return render_template('cart.html', cartList=cartList, totalCost=totalCost, current=current, NoCollectForm = Delivery, Discount=Discount, Items=Items, error_msg=error_msg, discount=discount,new_total=new_total, searchForm=searchForm, current_discount=current_discount, deducted = deducted, show=show)
else:
db.close()
error_msg = code + " not applicable"
print(error_msg)
return render_template('cart.html', cartList=cartList, totalCost=totalCost, current=current, NoCollectForm = Delivery, Discount=Discount, Items=Items, error_msg=error_msg, discount=discount,new_total=new_total, searchForm=searchForm, current_discount=current_discount, deducted = deducted, show=show)
@app.route("/removeUseDiscount", methods=["POST"])
def removeUseDiscount():
print("remocve")
current = ''
db = shelve.open('storage.db', 'c')
try:
current = db["Current User"]
except:
print('Error in retrieving current user from storage.db.')
empty = {}
current.set_current_discount(empty)
db["Current User"] = current
db.close()
return redirect(url_for('cart'))
@app.route("/addToCart/<name>/<quantity>", methods=['GET', 'POST'])
def addToCart(name, quantity):
current_user = ""
productsDict= {}
db = shelve.open('storage.db', 'c')
try:
current_user = db["Current User"]
except:
print('Error in retrieving current user from storage.db.')
try:
productsDict = db["Products"]
except:
print('Error in retrieving current products from storage.db.')
for thing in productsDict:
if productsDict[thing].get_product_name() == name: