-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCandyShop.py
More file actions
1621 lines (1247 loc) · 53 KB
/
CandyShop.py
File metadata and controls
1621 lines (1247 loc) · 53 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, flash, session, abort, g, Markup
import shelve
from Candy import Candy
from CandyCart import CandyCart
from Forms import CreateFeedbackForm, CreateCheckoutForm, NewEmail, SearchCheckoutInformation, UpdateDeliveryForm, StaffLogin, CreateStaff, UpdateStaff, CreateSupplierForm, UpdateSupplierForm, CreateOrderForm, UpdateOrderForm, CreateCandy, UpdateCandy, CustomerLogin, CreateCustomer, UpdateCustomer, CustomerChange, ManagePoints, LoginForm, s_CreateCustomer
from Feedback import Feedback
from datetime import date, timedelta
from CheckoutInformation import CheckoutInformation
from flask_mail import Mail, Message
from User import User, Login
from Customer import Customer
from Staff import Staff
from Supplier import Supplier
from Order import Order
from wtforms import SelectField, validators
from loginUser import loginUser
app = Flask(__name__)
app.config['SECRET_KEY'] = '123456'
app.config.update(
# email settings
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=465,
MAIL_USE_SSL=True,
MAIL_USERNAME='sugaricandyshop@gmail.com',
MAIL_PASSWORD='Sugari12345',
)
mail = Mail(app)
@app.route('/', methods=['GET', 'POST'])
def homepage():
return render_template('homepage.html')
@app.route('/addtocart/<int:candyID>/', methods=['GET', 'POST'])
def addtocart(candyID):
cartDict = {}
candyDict = {}
subtotal = 0
db = shelve.open('storage.db', 'c')
try:
candyDict = db['Candy']
except:
print('Error in retrieving candy object from storage.db')
try:
cartDict = db['shoppingCart']
except:
print('Error in retrieving cart items from storage.db')
candy = candyDict.get(candyID)
quantity = int(request.form['quantity'])
number = int(request.form['quantity'])
if number > candy.get_candyStockLevel():
flash('Quantity exceeds stock level. We only have ' + str(candy.get_candyStockLevel()))
return redirect(url_for('homepage'))
candy_cart = CandyCart(candy.get_candyName(), candy.get_candyStockLevel(), candy.get_candyRetailPrice(),
candy.get_candyCostPrice(), candy.get_candyCategory(), candy.get_candyImage(),
candy.get_candyKeyInformation(), candy.get_candyIngredients(), candy.get_candyCountry(), candy.get_candySupplier())
candy_cart.set_quantity(quantity)
subtotal = float(candy.get_candyRetailPrice()) * quantity
subtotal = "{:.2f}".format(float(subtotal))
candy_cart.set_subtotal(subtotal)
cartDict[candy_cart.get_candyName()] = candy_cart
db['shoppingCart'] = cartDict
db.close()
return redirect(url_for('shoppingcart'))
@app.route('/shoppingcart', methods=['GET', 'POST'])
def shoppingcart():
cartDict = {}
subtotal = 0
total = 0
try:
db = shelve.open('storage.db', 'r')
cartDict = db['shoppingCart']
db.close()
except:
print('Error in retrieving cart items from storage.db')
db = shelve.open('storage.db', 'c')
db.close()
cartList = []
for key in cartDict:
candy = cartDict.get(key)
cartList.append(candy)
subtotal = float(candy.get_subtotal())
total = float(total)
total += subtotal
total = "{:.2f}".format(total)
'''
if request.method == "POST":
# Add quantity
if request.form["cart_button"] == "+":
print('+')
# Deduct quantity
elif request.form["cart_button"] == "-":
print('-')
return redirect(url_for('shoppingcart'))
'''
return render_template('shoppingcart.html', cartList=cartList, total=total)
@app.route('/emptycart', methods=['GET', 'POST'])
def emptycart():
cartDict = {}
total = 0
db = shelve.open('storage.db', 'w')
try:
cartDict = db['shoppingCart']
except:
print('Error in retrieving cart items from storage.db')
cartDict.clear()
db['shoppingCart'] = cartDict
db.close()
return render_template('shoppingcart.html', total=total)
@app.route('/s_menu', methods=['GET', 'POST'])
def s_menu():
return render_template('s_menu.html')
@app.route('/s_inventory', methods=['GET', 'POST']) # retrieve candies
def s_inventory():
candyDict = {}
try:
db = shelve.open('storage.db', 'r')
candyDict = db['Candy']
db.close()
except:
db = shelve.open('storage.db', 'c')
db.close()
candyList = []
for key in candyDict:
candyitem = candyDict.get(key)
candyList.append(candyitem)
return render_template('s_inventory.html', candyList=candyList, count=len(candyList))
@app.route('/createCandy', methods=['GET', 'POST'])
def createCandy():
supplierDict = {}
list = []
try:
db2 = shelve.open('storage.db', 'w')
supplierDict = db2['Suppliers']
except:
print('Error in retrieving suppliers from storage.db')
flash('There are no suppliers. You need a supplier to create a candy.')
flash(Markup('Click <a href="/s_createsupplier" class="alert-link">here</a> to create a supplier.'))
return redirect(url_for('s_inventory'))
for key in supplierDict: # prob
s = supplierDict.get(key)
item = (s.get_companyName(), s.get_companyName())
list.append(item)
CreateCandy.supplier = SelectField('', [validators.DataRequired()], choices=list, default='')
createCandy = CreateCandy(request.form)
if request.method == 'POST' and createCandy.validate():
candyDict = {}
db = shelve.open("storage.db", "c") # Create, read and write
try:
candyDict = db["Candy"]
Candy.countID = db["CandyCountID"]
except:
print("Error in retrieving candies from storage.db")
# Create an instance of class User
candy = Candy(createCandy.name.data, 0, createCandy.retailprice.data, createCandy.costprice.data,
createCandy.category.data, createCandy.image.data, createCandy.supplier.data, createCandy.keyinformation.data, createCandy.ingredients.data, createCandy.country.data)
# Save the user instance in usersDict, using userID as the key
candyDict[candy.get_candyID()] = candy
# Save dictionary to db
db["Candy"] = candyDict
# After create the user, save the countID to shelve/persistance
db["CandyCountID"] = Candy.countID
# Module / file Name.ClassName.class_attribute
selectlist = []
return redirect(url_for('s_inventory'))
return render_template('s_createcandy.html', form=createCandy)
@app.route('/deleteCandy/<int:id>/', methods=["POST"])
def deleteCandy(id):
candyDict = {}
# retrieve from persistence
db = shelve.open("storage.db", "w")
candyDict = db["Candy"]
# delete the record from the list
candyDict.pop(id)
# save the list
db["Candy"] = candyDict
db.close()
return redirect(url_for("s_inventory"))
@app.route('/updateCandy/<int:id>/', methods=['GET', 'POST'])
def updateCandy(id):
updateCandy = UpdateCandy(request.form)
if request.method == 'POST' and updateCandy.validate():
candyDict = {}
db = shelve.open('storage.db', 'w')
candyDict = db["Candy"]
candy = candyDict.get(id)
candy.set_candyName(updateCandy.name.data)
candy.set_candyStockLevel(updateCandy.stock.data)
candy.set_candyRetailPrice(updateCandy.retailprice.data)
candy.set_candyCostPrice(updateCandy.costprice.data)
candy.set_candyCategory(updateCandy.category.data)
candy.set_candyKeyInformation(updateCandy.keyinformation.data)
candy.set_candyIngredients(updateCandy.ingredients.data)
candy.set_candyCountry(updateCandy.country.data)
if updateCandy.image.data != "":
candy.set_candyImage(updateCandy.image.data)
db["Candy"] = candyDict
db.close()
return redirect(url_for('s_inventory'))
else:
candyDict = {}
db = shelve.open('storage.db', 'r')
candyDict = db["Candy"]
# name, stock, price, category
candy = candyDict.get(id)
updateCandy.name.data = candy.get_candyName()
updateCandy.stock.data = candy.get_candyStockLevel()
updateCandy.retailprice.data = candy.get_candyRetailPrice()
updateCandy.costprice.data = candy.get_candyCostPrice()
updateCandy.category.data = candy.get_candyCategory()
updateCandy.image.field = candy.get_candyImage()
updateCandy.keyinformation.data = candy.get_candyKeyInformation()
updateCandy.ingredients.data = candy.get_candyIngredients()
updateCandy.country.data = candy.get_candyCountry()
updateCandy.supplier.data = candy.get_candySupplier()
return render_template('s_updatecandy.html', form=updateCandy)
@app.route('/checkout', methods=['GET', 'POST'])
def checkout():
createCheckoutForm = CreateCheckoutForm(request.form)
cartDict = {}
subtotal = 0
totalsubtotal = 0
total = 0
db = shelve.open('storage.db', 'r')
try:
cartDict = db['shoppingCart']
db.close()
except:
print('Error in retrieving cart items from storage.db')
cartList = []
for key in cartDict:
candy = cartDict.get(key)
print(candy)
cartList.append(candy)
subtotal = float(candy.get_subtotal())
totalsubtotal += subtotal
total = float(total)
total += subtotal
total = "{:.2f}".format(float(total))
if len(cartList) == 0:
flash("Shopping cart is empty!")
return redirect(url_for('shoppingcart'))
# Click on the Submit button
if request.method == 'POST' and createCheckoutForm.validate():
checkoutDict = {}
candyDict = {}
db = shelve.open('storage.db', 'c')
db1 = shelve.open('storage.db', 'w')
candyDict = db1['Candy']
total = float(total)
try:
checkoutDict = db['Checkouts']
CheckoutInformation.count = db['CheckoutCountID']
except:
print("Error in retrieving Users from storage.db.")
if createCheckoutForm.shippingMethod.data == 'regular':
deliveryDate = date.today() + timedelta(days=14)
shippingFee = 0
elif createCheckoutForm.shippingMethod.data == 'express':
deliveryDate = date.today() + timedelta(days=5)
shippingFee = 3.50
total += 3.50
CardType = request.form['CardType']
CardNumber = request.form['CardNumber']
checkoutInformation = CheckoutInformation(createCheckoutForm.firstName.data,
createCheckoutForm.lastName.data, createCheckoutForm.phone.data,
createCheckoutForm.email.data, createCheckoutForm.address.data,
createCheckoutForm.postalCode.data,
createCheckoutForm.shippingMethod.data, CardType, CardNumber,
createCheckoutForm.expiryDate.data,
createCheckoutForm.cardVerificationNumber.data, deliveryDate, 'p')
checkoutInformation.set_total(total)
checkoutDict[checkoutInformation.get_checkoutID()] = checkoutInformation
db['Checkouts'] = checkoutDict
db['CheckoutCountID'] = CheckoutInformation.count
# remove inventory
for key in candyDict:
candy = candyDict.get(key)
stock = candy.get_candyStockLevel()
for cart in cartDict:
cart = cartDict.get(cart)
if candy.get_candyName() == cart.get_candyName():
quantity = cart.get_quantity()
stock -= quantity
candy.set_candyStockLevel(stock)
db['shoppingCart'] = cartDict
db1['Candy'] = candyDict
db1.close()
db.close()
# for receipt
checkoutList = []
checkoutList.append(checkoutInformation)
name = " " + createCheckoutForm.firstName.data + " " + createCheckoutForm.lastName.data
id = str(checkoutInformation.get_checkoutID())
try:
msg = Message("Receipt Number", sender="sugaricandyshop@gmail.com",
recipients=[createCheckoutForm.email.data]) # rmb set back createCheckoutForm.email.data
msg.body = "Dear" + name + ",\n\nThank you for shopping with us!\nYour receipt number is: " + id + "\n\nDo be reminded that you can print a copy of the receipt page and keep it as a reference if necessary.\n\nBest regards,\nSugari Team"
mail.send(msg)
print('Email has been sent')
except:
print('Email not found')
return render_template('receipt.html', checkoutList=checkoutList, cartList=cartList, shippingFee=shippingFee,
totalsubtotal=totalsubtotal, total=total)
# Get (first load the page) or when validation fails
return render_template('checkout.html', form=createCheckoutForm, cartList=cartList, total=total)
@app.route('/resendemail/<int:id>/', methods=['GET', 'POST'])
def resendemail(id):
# cart information
cartDict = {}
subtotal = 0
totalsubtotal = 0
total = 0
db = shelve.open('storage.db', 'r')
try:
cartDict = db['shoppingCart']
db.close()
except:
print('Error in retrieving cart items from storage.db')
cartList = []
for key in cartDict:
candy = cartDict.get(key)
print(candy)
cartList.append(candy)
subtotal = float(candy.get_subtotal())
totalsubtotal += subtotal
total = float(total)
total += subtotal
total = "{:.2f}".format(float(total))
# sending email
checkoutDict = {}
db = shelve.open('storage.db', 'w')
checkoutDict = db['Checkouts']
checkout = checkoutDict.get(id)
checkoutList = [checkout]
name = " " + checkout.get_firstName() + " " + checkout.get_lastName()
id = str(id)
total = float(total)
if checkout.get_shippingMethod() == 'regular':
deliveryDate = date.today() + timedelta(days=14)
shippingFee = 0
elif checkout.get_shippingMethod() == 'express':
deliveryDate = date.today() + timedelta(days=5)
shippingFee = 3.50
total += 3.50
name = " " + checkout.get_firstName() + " " + checkout.get_lastName()
id = str(id)
try:
msg = Message("Receipt Number", sender="sugaricandyshop@gmail.com",
recipients=[checkout.get_email()]) # rmb set back createCheckoutForm.email.data
msg.body = "Dear" + name + ",\n\nThank you for shopping with us!\nYour receipt number is: " + id + "\n\nDo be reminded that you can print a copy of the receipt page and keep it as a reference if necessary.\n\nBest regards,\nSugari Team"
mail.send(msg)
print('Email has been sent')
except:
print('Email not found')
return render_template('receipt.html', checkoutList=checkoutList, cartList=cartList, shippingFee=shippingFee,
totalsubtotal=totalsubtotal, total=total)
@app.route('/clear', methods=['GET', 'POST'])
def clear():
# clear shopping cart after checkout
cartDict = {}
db = shelve.open('storage.db', 'w')
cartDict = db['shoppingCart']
cartDict = {}
db['shoppingCart'] = cartDict
db.close()
return redirect(url_for('homepage'))
@app.route('/aboutus', methods=['GET', 'POST'])
def aboutus():
return render_template('aboutus.html')
@app.route('/s_deliveryorders', methods=['GET', 'POST'])
def s_deliveryorders():
checkoutDict = {}
checkoutList = []
try:
db = shelve.open('storage.db', 'r')
checkoutDict = db['Checkouts']
db.close()
except:
db = shelve.open('storage.db', 'c')
db.close()
for key in checkoutDict:
checkout = checkoutDict.get(key)
checkoutList.append(checkout)
return render_template('s_deliveryorders.html', checkoutList=checkoutList)
@app.route('/s_updatedeliveryorders/<int:id>/', methods=['GET', 'POST'])
def s_updatedeliveryorders(id):
updateDeliveryForm = UpdateDeliveryForm(request.form)
if request.method == 'POST' and updateDeliveryForm.validate():
checkoutDict = {}
db = shelve.open('storage.db', 'w')
checkoutDict = db['Checkouts']
order = checkoutDict.get(id)
order.set_phone(updateDeliveryForm.phone.data)
order.set_email(updateDeliveryForm.email.data)
order.set_address(updateDeliveryForm.address.data)
order.set_postalCode(updateDeliveryForm.postalCode.data)
order.set_deliveryStatus((updateDeliveryForm.deliveryStatus.data))
db['Checkouts'] = checkoutDict
db.close()
return redirect(url_for('s_deliveryorders'))
else:
checkoutDict = {}
db = shelve.open('storage.db', 'r')
checkoutDict = db['Checkouts']
db.close()
order = checkoutDict.get(id)
print(order.get_firstName(), order.get_lastName(), order.get_phone())
# name, stock, price, category
updateDeliveryForm.firstName.data = order.get_firstName()
updateDeliveryForm.lastName.data = order.get_lastName()
updateDeliveryForm.phone.data = order.get_phone()
updateDeliveryForm.email.data = order.get_email()
updateDeliveryForm.address.data = order.get_address()
updateDeliveryForm.postalCode.data = order.get_postalCode()
updateDeliveryForm.shippingMethod.data = order.get_shippingMethod()
updateDeliveryForm.deliveryStatus.data = order.get_deliveryStatus()
return render_template('s_updatedeliveryorders.html', form=updateDeliveryForm)
@app.route('/create_feedback', methods=['GET', 'POST'])
def create_feedback():
createFeedbackForm = CreateFeedbackForm(request.form)
if request.method == 'POST' and createFeedbackForm.validate():
feedbackDict = {}
db = shelve.open('storage.db', 'c')
try:
feedbackDict = db['Feedbacks']
feedback_id = db["feedback_id"]
feedback_id += 1
db["feedback_id"] = feedback_id
except:
print("Error in retrieving feedback from Feedback.db.")
feedback_id = 1
db["feedback_id"] = 1
feedback = Feedback(feedback_id, createFeedbackForm.firstName.data, createFeedbackForm.lastName.data,
createFeedbackForm.email.data, createFeedbackForm.phone.data,
createFeedbackForm.region.data, createFeedbackForm.surveyOne.data,
createFeedbackForm.surveyTwo.data, createFeedbackForm.improvements.data)
feedbackDict[feedback.get_feedbackID()] = feedback
db['Feedbacks'] = feedbackDict
db.close()
return redirect(url_for('feedbacksubmission'))
return render_template('create_feedback.html', form=createFeedbackForm)
@app.route('/retrieve_feedback')
def retrieve_feedback():
feedbackDict = {}
try:
db = shelve.open('storage.db', 'r')
feedbackDict = db['Feedbacks']
db.close()
except:
db = shelve.open('storage.db', 'c')
db.close()
feedbackList = []
for key in feedbackDict:
feedback = feedbackDict.get(key)
feedbackList.append(feedback)
return render_template('retrieve_feedback.html', feedbackList=feedbackList, count=len(feedbackList))
@app.route('/deleteFeedback/<int:id>/', methods=['POST'])
def deleteFeedback(id):
feedbackDict = {}
# retrieve from persistance
db = shelve.open('storage.db', 'w')
feedbackDict = db['Feedbacks']
# delete the record from the list
feedbackDict.pop(id)
# save the list
db['Feedbacks'] = feedbackDict
db.close()
return redirect(url_for('retrieve_feedback'))
@app.route('/view_feedback/<int:id>', methods=['POST'])
def view_feedback(id):
feedbackDict = {}
db = shelve.open('storage.db', 'r')
feedbackDict = db['Feedbacks']
db.close()
feedbackList = []
feedback = feedbackDict.get(id)
feedbackList.append(feedback)
return render_template('view_feedback.html', feedbackList=feedbackList, count=len(feedbackList))
@app.route('/feedbacksubmission', methods=['GET', 'POST'])
def feedbacksubmission():
return render_template('feedbacksubmission.html')
@app.route('/customerdetails', methods=['GET', 'POST'])
def customerdetails():
customerChange = CustomerChange(request.form)
print(request.method)
if request.method == 'POST':
db = shelve.open('storage.db', 'w')
customerDict = db["Customers"]
logincustomer = ""
logincustomer=loginUser.user
print("UPDATINGGG")
customer = customerDict.get(logincustomer)
customer.set_firstName(customerChange.firstname.data)
customer.set_lastName(customerChange.lastname.data)
customer.set_gender(customerChange.gender.data)
customer.set_email(customerChange.email.data)
if customerChange.password.data != "":
print("CUSTOMER CHANGE")
print(customerChange.password.data)
usersDict = {}
usersDict = db["Users"]
user=usersDict.get(logincustomer)
db["Users"] = usersDict
customer.set_password(customerChange.password.data)
print(user)
user.set_password(customerChange.password.data)
customer.set_contactNo(customerChange.contactNo.data)
db["Users"] = usersDict
db["Customers"] = customerDict
db.close()
return redirect(url_for('dropsession'))
else:
customerDict = {}
logincustomer = ""
db2 = shelve.open('storage.db', 'r')
#id = db2['User']
customerDict = db2["Customers"]
logincustomer=loginUser.user
db2.close()
print("LOGIN CUSTOMER")
print(logincustomer)
customer = customerDict.get(loginUser.user)
print("LOGIN USER STUFF")
print(customer)
print(customerDict)
customerChange.firstname.data = customer.get_firstName()
customerChange.lastname.data = customer.get_lastName()
customerChange.gender.data = customer.get_gender()
customerChange.email.data = customer.get_email()
customerChange.password.data = customer.get_password()
customerChange.contactNo.data = customer.get_contactNo()
customerChange.membStatus.data = customer.get_membStatus()
customerChange.membPoints.data = customer.get_membPoints()
return render_template('customerdetails.html', form=customerChange, id=logincustomer)
@app.route("/create_membership", methods=["GET", "POST"])
def create_membership():
createMemberForm = CreateCustomer(request.form)
try:
db2 = shelve.open('storage.db', 'w')
staffDict = db2['Staff']
except:
print('Error in retrieving staff from storage.db')
flash('There is no staff. You need a staff to sign up.')
flash(Markup('Click <a href="/create_staff" class="alert-link">here</a> to create a staff.'))
return redirect(url_for('login'))
if request.method == "POST" and createMemberForm.validate():
customersDict = {}
usersDict = {}
db = shelve.open('storage.db', 'c')
try:
customersDict = db["Customers"]
usersDict = db["Users"]
User.countID = db["UserID"]
except:
print("Error in retrieving Members from storage.db.")
customer = Customer(createMemberForm.firstname.data, createMemberForm.lastname.data,
createMemberForm.gender.data, createMemberForm.email.data,
createMemberForm.password.data,createMemberForm.contactNo.data, 0)
customer.set_accumulation()
customer.set_membStatus()
customer.set_type("C")
customerlogin = Login(customer.get_userID(), createMemberForm.password.data, customer.get_type())
print("created customer login")
customersDict[customer.get_userID()] = customer
print("BEFORE")
print(usersDict)
usersDict[customer.get_userID()] = customerlogin
print("AFTER")
print(usersDict)
db["Customers"] = customersDict
db["UserID"] = User.countID
db["Users"] = usersDict
db.close()
return redirect(url_for("homepage"))
return render_template("signup.html", form=createMemberForm)
@app.route("/s_create_membership", methods=["GET", "POST"])
def s_create_membership():
createMemberForm = s_CreateCustomer(request.form)
if request.method == "POST" and createMemberForm.validate():
customersDict = {}
usersDict = {}
db = shelve.open('storage.db', 'w')
try:
customersDict = db["Customers"]
User.countID = db["UserID"]
print('C1:')
print(User.countID)
except:
print("Error in retrieving Members from storage.db.")
try:
usersDict = db["Users"]
except:
print("DOES NOT EXIST")
customer = Customer(createMemberForm.firstname.data, createMemberForm.lastname.data,
createMemberForm.gender.data, createMemberForm.email.data,
createMemberForm.password.data, createMemberForm.contactNo.data,createMemberForm.membPoints.data)
customer.set_accumulation()
customer.set_membStatus()
customer.set_type("C")
customerlogin = Login(customer.get_userID(), createMemberForm.password.data, customer.get_type())
customersDict[customer.get_userID()] = customer
usersDict[customer.get_userID()] = customerlogin
print(usersDict)
db["Customers"] = customersDict
db["UserID"] = User.countID
db["Users"] = usersDict
db.close()
return redirect(url_for("s_membershiplist"))
return render_template("s_createcustomer.html", form=createMemberForm)
@app.route("/s_membershiplist")
def s_membershiplist():
customersDict = {}
try:
db = shelve.open('storage.db', 'r')
customersDict = db["Customers"]
db.close()
except:
db = shelve.open('storage.db', 'c')
db.close()
customersList = []
for key in customersDict:
customer = customersDict.get(key)
customersList.append(customer)
return render_template("s_membershiplist.html", customersList=customersList, count=len(customersList))
@app.route('/managePoints/<int:id>', methods=['GET', 'POST'])
def managePoints(id):
managePoints = ManagePoints(request.form)
if request.method == "POST" and managePoints.validate():
customerDict = {}
db = shelve.open('storage.db', 'w')
customerDict = db["Customers"]
customer = customerDict.get(id)
if managePoints.type.data == "A": #ADD
customer.add_points(managePoints.value.data)
elif managePoints.type.data == "D": #DEDUCT
if customer.get_membPoints() >= managePoints.value.data:
customer.deduct_points(managePoints.value.data)
elif customer.get_membPoints() < managePoints.value.data:
flash('Not enough points to deduct.')
return redirect(url_for("s_membershiplist"))
customer.set_membStatus()
db["Customers"] = customerDict
db.close()
return redirect(url_for("s_membershiplist"))
return render_template("s_managepoints.html", form=managePoints)
@app.route('/updateMember/<int:id>', methods=['GET', 'POST'])
def updateMember(id):
updateCustomer = UpdateCustomer(request.form)
if request.method == 'POST' and updateCustomer.validate():
customerDict = {}
db = shelve.open('storage.db', 'w')
customerDict = db["Customers"]
customer = customerDict.get(id)
customer.set_firstName(updateCustomer.firstname.data)
customer.set_lastName(updateCustomer.lastname.data)
customer.set_gender(updateCustomer.gender.data)
customer.set_email(updateCustomer.email.data)
if updateCustomer.password.data != "":
print(updateCustomer.password.data)
usersDict = {}
usersDict = db["Users"]
user=usersDict.get(id)
user.set_password(updateCustomer.password.data)
db["Users"] = usersDict
customer.set_password(updateCustomer.password.data)
customer.set_contactNo(updateCustomer.contactNo.data)
customer.set_membPoints(updateCustomer.membPoints.data)
db["Customers"] = customerDict
db.close()
return redirect(url_for('s_membershiplist'))
else:
customerDict = {}
db = shelve.open('storage.db', 'r')
customerDict = db["Customers"]
db.close()
customer = customerDict.get(id)
updateCustomer.firstname.data = customer.get_firstName()
updateCustomer.lastname.data = customer.get_lastName()
updateCustomer.gender.data = customer.get_gender()
updateCustomer.email.data = customer.get_email()
updateCustomer.password.data = customer.get_password()
updateCustomer.contactNo.data = customer.get_contactNo()
updateCustomer.membStatus.data = customer.get_membStatus()
updateCustomer.membPoints.data = customer.get_membPoints()
return render_template('s_updatecustomer.html', form=updateCustomer, id=id)
@app.route('/deleteMember/<int:id>', methods=['POST'])
def deleteMember(id):
customersDict = {}
usersDict = {}
db = shelve.open('storage.db', 'w')
usersDict = db["Users"]
customersDict = db["Customers"]
customersDict.pop(id)
usersDict.pop(id)
db["Customers"] = customersDict
db["Users"] = usersDict
db.close()
return redirect(url_for('s_membershiplist'))
@app.route('/create_staff', methods=['GET', 'POST'])
def create_staff():
createstaff = CreateStaff(request.form)
if request.method == 'POST' and createstaff.validate():
staffDict = {}
usersDict = {}
db = shelve.open("storage.db", "c") # Create, read and write
try:
staffDict = db["Staff"]
usersDict = db["Users"]
User.countID = db["UserID"]
print('S1:')
print(User.countID)
except:
print("Error in retrieving staff from storage.db")
# Create an instance of class User
staff = Staff(createstaff.firstname.data, createstaff.lastname.data, createstaff.gender.data,
createstaff.email.data, createstaff.password.data)
staff.set_type("S")
stafflogin = Login(staff.get_userID(), createstaff.password.data, staff.get_type())
print("BEFORE STAFF")
print(usersDict)
# Save the user instance in usersDict, using userID as the key
staffDict[staff.get_userID()] = staff
usersDict[staff.get_userID()] = stafflogin
print("AFTER STAFF")
print(usersDict)
# Save dictionary to db
db["Staff"] = staffDict
db["Users"] = usersDict
print("DATABASE")
print(db["Users"])
# After create the user, save the countID to shelve/persistance
db["UserID"] = User.countID
print('S2:')
print(User.countID)
# Module / file Name.ClassName.class_attribute
db.close()
return redirect(url_for('s_stafflist'))
return render_template('s_createstaff.html', form=createstaff)
@app.route('/s_stafflist', methods=['GET', 'POST']) # retrieve candies
def s_stafflist():
staffDict = {}
db = shelve.open('storage.db', 'r')
staffDict = db['Staff']
db.close()
staffList = []
for key in staffDict:
staff = staffDict.get(key)
staffList.append(staff)
hidden = "*" * len(staff.get_password())
return render_template('s_stafflist.html', staffList=staffList, count=len(staffList))
@app.route('/updateStaff/<int:id>/', methods=['GET', 'POST'])
def updateStaff(id):
updateStaff = UpdateStaff(request.form)
db = shelve.open("storage.db", "r")
User.countID = db["UserID"]
db.close()
if request.method == 'POST' and updateStaff.validate():
staffDict = {}
usersDict = {}
db = shelve.open('storage.db', 'w')
staffDict = db["Staff"]
usersDict = db["Users"]
staff = staffDict.get(id)
user = usersDict.get(id)
staff.set_firstName(updateStaff.firstname.data)
staff.set_lastName(updateStaff.lastname.data)
staff.set_gender(updateStaff.gender.data)
staff.set_email(updateStaff.email.data)
if updateStaff.password.data != "":
print("NEW PASSWORD")
print(updateStaff.password.data)