-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.py
1728 lines (1489 loc) · 66.9 KB
/
run.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
from logging import INFO, WARNING
from operator import add
from flask import Flask, jsonify, abort, make_response, request, render_template, url_for, redirect
from flask_cors.core import serialize_option
from flask_mail import Message, Mail
import os
import json
from dotenv import load_dotenv
import datetime
import random
import string
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask_bcrypt import Bcrypt
from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, jwt_refresh_token_required, create_refresh_token, get_jwt_identity, get_jwt_claims)
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey
from flask_cors import CORS
import stripe
# # --- INFO: LOAD CONFIG VARIABLES ---
# with open('config.json') as config_file:
# config = json.load(config_file)
# --- INFO: APP CONFIGURATION ---
load_dotenv()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
app.config['JWT_SECRET_KEY'] = os.environ.get('JWT_SECRET_KEY')
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(days=7)
app.config['JWT_REFRESH_TOKEN_EXPIRES'] = datetime.timedelta(days=7)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER')
app.config['MAIL_PORT'] = os.environ.get('MAIL_PORT')
app.config['MAIL_USE_TLS'] = os.environ.get('MAIL_USE_TLS')
db = SQLAlchemy(app)
mail = Mail(app)
bcrypt = Bcrypt(app)
jwt = JWTManager(app)
cors = CORS(app, resources={r"/api/*": {"origins": "https://antoine.ratat.xyz"}})
stripe.api_key = os.environ.get('SRIPE_API_KEY')
# --- INFO: DATABASE MODEL ---
class User(db.Model):
user_id = Column(Integer, primary_key=True)
email = Column(String(40), unique=True, nullable=False)
password = Column(String(200), nullable=False)
role = Column(Integer, nullable=False, default=0)
first_name = Column(String(40), nullable=False)
last_name = Column(String(40), nullable=False)
profile_picture = Column(String(250), nullable=True, default='default.jpg')
def __repr__(self):
return "ID: {}, email: {}, role: {}, first_name: {}, last_name: {}, profile_picture".format(self.user_id, self.email, self.role, self.first_name, self.last_name, self.profile_picture)
def get_reset_token(self, expires_seconds=1800):
s = Serializer(app.config['SECRET_KEY'], expires_seconds)
return s.dumps({'user_id': self.user_id}).decode('utf-8')
@staticmethod
def verify_reset_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
user_id = s.loads(token)['user_id']
except:
return None
return User.query.get(user_id)
@property
def serialize(self):
return {
'user_id': self.user_id,
'email': self.email,
'first_name': self.first_name,
'last_name': self.last_name,
'profile_picture': self.profile_picture,
}
class UserDetails(db.Model):
user_details_id= Column(Integer, primary_key=True)
address = Column(String(100), nullable=True)
city = Column(String(40), nullable=True)
state = Column(String(50), nullable=True)
postcode = Column(String(40), nullable=True)
country = Column(String(40), nullable=True)
phone = Column(String(40), nullable=True)
user_id = Column(Integer, ForeignKey(User.user_id), nullable=False)
def __repr__(self):
return "user_details_id: {}, address: {}, city: {} state: {}, postcode: {}, country: {}, phone: {}, user_id: {}".format(self.user_details_id, self.address, self.city, self.state, self.postcode, self.country, self.phone, self.user_id)
@property
def serialize(self):
return {
'user_details_id': self.user_details_id,
'address': self.address,
'city': self.city,
'state': self.state,
'postcode': self.postcode,
'country': self.country,
'phone': self.phone,
'user_id': self.user_id
}
class Order(db.Model):
order_id = Column(Integer, primary_key=True)
order_number = Column(String(40), nullable=True)
order_details = Column(String(100), nullable=True)
user_id = Column(Integer, ForeignKey(User.user_id), nullable=False)
def __repr__(self):
return "order_id: {}, order_number: {}, order_details: {}, user_id: {}".format(self.order_id, self.order_number, self.order_details, self.user_id)
@property
def serialize(self):
return {
'order_id': self.order_id,
'order_number': self.order_number,
'order_details': self.order_details,
'user_id': self.user_id,
}
class Delivery(db.Model):
delivery_id = Column(Integer, primary_key=True)
status = Column(String(40), nullable=True)
company = Column(String(40), nullable=True)
phone = Column(String(40), nullable=True)
order_id = Column(Integer, ForeignKey(Order.order_id), nullable=False)
def __repr__(self):
return "delivery_id: {}, status: {}, company: {}, phone: {}, order_id: {}".format(self.delivery_id, self.status, self.company, self.phone, self.order_id)
@property
def serialize(self):
return {
'delivery_id': self.delivery_id,
'status': self.status,
'company': self.company,
'phone': self.phone,
'order_id': self.order_id,
}
class Payment(db.Model):
payment_id = Column(Integer, primary_key=True)
payment_stripe_number = Column(String(40), nullable=True)
payment_method = Column(String(40), nullable=True)
payment_method_number = Column(String(40), nullable=True)
payment_date = Column(DateTime, nullable=False, default=datetime.datetime.utcnow)
amount = Column(Float, nullable=True)
currency = Column(String(40), nullable=True)
status = Column(String(40), nullable=True)
order_id = Column(Integer, ForeignKey(Order.order_id), nullable=False)
def __repr__(self):
return "payment_id: {}, payment_method: {}, payment_date: {}, order_id: {}".format(self.payment_id, self.payment_method, self.payment_date, self.order_id)
@property
def serialize(self):
return {
'payment_id': self.payment_id,
'payment_method': self.payment_method,
'payment_method_number': self.payment_method_number,
'payment_date': self.payment_date,
'amount': self.amount,
'currency': self.currency,
'status': self.status,
'order_id': self.order_id,
}
class Category(db.Model):
category_id = Column(Integer, primary_key=True)
name = Column(String(40), nullable=True)
gender = Column(String(40), nullable=True)
description = Column(String(100), nullable=True)
def __repr__(self):
return "category_id: {}, name: {}, description: {}, gender: {}".format(self.category_id, self.name, self.description, self.gender)
@property
def serialize(self):
return {
'category_id': self.category_id,
'name': self.name,
'description': self.description,
'gender': self.gender,
}
class Product(db.Model):
product_id = Column(Integer, primary_key=True)
product_name = Column(String(40), nullable=True)
product_description = Column(String(100), nullable=True)
price = Column(Float, nullable=True)
stock = Column(Integer, nullable=True)
images_url = Column(String(1000), nullable=True)
category_id = Column(Integer, ForeignKey(Category.category_id), nullable=False)
def __repr__(self):
return "product_id: {}, product_name: {}, product_description: {}, price: {}, stock: {}, image_url: {}, category_id: {}".format(self.product_id, self.product_name, self.product_description, self.price, self.stock, self.images_url, self.category_id)
@property
def serialize(self):
category = Category.query.get(self.category_id)
category_name = category.name
category_description = category.description
return {
'product_id': self.product_id,
'product_name': self.product_name,
'product_description': self.product_description,
'price': self.price,
'stock': self.stock,
'images_url': self.images_url,
'category_id': self.category_id,
'category_name': category_name,
'category_description': category_description,
}
class OrderDetails(db.Model):
order_details_id = Column(Integer, primary_key=True)
quantity = Column(Integer, nullable=True)
total = Column(Float, nullable=True)
product_id = Column(Integer, ForeignKey(Product.product_id), nullable=False)
order_id = Column(Integer, ForeignKey(Order.order_id), nullable=False)
def __repr__(self):
return "order_details_id: {}, quantity: {}, total: {}, product_id: {}, order_id: {}".format(self.order_details_id, self.quantity, self.total, self.product_id, self.order_id)
@property
def serialize(self):
return {
'order_details_id': self.order_details_id,
'quantity': self.quantity,
'total': self.total,
'product_id': self.product_id,
'order_id': self.order_id,
}
class CartDetails(db.Model):
cart_id = Column(Integer, primary_key=True)
quantity = Column(Integer, nullable=True)
total = Column(Integer, nullable=True)
product_id = Column(Integer, ForeignKey(Product.product_id), nullable=False)
user_id = Column(Integer, ForeignKey(User.user_id), nullable=False)
def __repr__(self):
return "cart_id: {}, quantity: {}, total: {}, product_id: {}, user_id: {}".format(self.cart_id, self.quantity, self.total, self.product_id, self.user_id)
@property
def serialize(self):
return {
'cart_id': self.cart_id,
'quantity': self.quantity,
'total': self.total,
'product_id': self.product_id,
'user_id': self.user_id
}
# --- INFO: ADMIN FUNCTIONS ---
# UTILS FUNCTIONS
def isAdmin():
current_user = get_jwt_identity()
if not current_user == '[email protected]':
return jsonify({'message': "Unauthorized Admin only"}), 403
# CRUD FUNCTIONS CATEGORY
def getAdminCategories():
categories = Category.query.all()
return jsonify(categories=[category.serialize for category in categories])
def postAdminCategory(name, description):
category_existing = Category.query.filter_by(name=name).first()
if category_existing:
return jsonify({'message': 'Category already existing'}), 400
category = Category(name=name, description=description)
db.session.add(category)
db.session.commit()
return jsonify(category=category.serialize)
def getAdminCategory(id):
category = Category.query.get(id)
if not category:
return jsonify({'message': 'Category doesn\'t exist'}), 404
return jsonify(category=category.serialize)
def updateAdminCategory(id, name, description):
category = Category.query.get(id)
if not category:
return jsonify({'message': 'Category doesn\'t exist'}), 404
if name:
category_existing = Category.query.filter_by(name=name).first()
if category_existing:
if int(category_existing.category_id) != int(id):
return jsonify({'message': 'Category already existing'}), 400
category.name = name
if description:
category.description = description
db.session.add(category)
db.session.commit()
return make_response(jsonify({'message': 'Updated category with ID: {}'.format(id)}), 200)
def deleteAdminCategory(id):
category = Category.query.get(id)
if not category:
return jsonify({'message': 'Category doesn\'t exist'}), 404
db.session.delete(category)
db.session.commit()
return make_response(jsonify({'message': 'Removed category with ID {}'.format(id)}), 200)
# CRUD FUNCTIONS PRODUCT
def getAdminProducts():
products = Product.query.all()
return jsonify(products=[product.serialize for product in products])
def postAdminProduct(product_name, product_description, price, stock, images_url, category_id):
product_existing = Product.query.filter_by(product_name=product_name).first()
if product_existing:
return jsonify({'message': 'Product already existing'}), 400
category = Category.query.filter_by(category_id=category_id).first()
if not category:
return jsonify({'message': 'Category doesn\'t exist'}), 400
product = Product(product_name=product_name, product_description=product_description, price=price, stock=stock, images_url=images_url, category_id=category_id)
db.session.add(product)
db.session.commit()
return jsonify(product=product.serialize)
def getAdminProduct(id):
product = Product.query.get(id)
if not product:
return jsonify({'message': 'Product doesn\'t exist'}), 404
return jsonify(product=product.serialize)
def updateAdminProduct(id, product_name, product_description, price, stock, images_url, category_id):
product = Product.query.get(id)
if not product:
return jsonify({'message': 'Product doesn\'t exist'}), 404
if product_name:
product_existing = Product.query.filter_by(product_name=product_name).first()
if product_existing:
if int(product_existing.product_id) != int(id):
return jsonify({'message': 'Product already existing'}), 400
product.product_name = product_name
if product_description:
product.product_description = product_description
if price:
product.price = price
if stock:
product.stock = stock
if images_url:
product.images_url = images_url
if category_id:
category = Category.query.filter_by(category_id=category_id).first()
if not category:
return jsonify({'message': 'Category doesn\'t exist}'}), 400
product.category_id = category_id
db.session.add(product)
db.session.commit()
return make_response(jsonify({'message': 'Updated product with ID: {}'.format(id)}), 200)
def deleteAdminProduct(id):
product = Product.query.get(id)
if not product:
return jsonify({'message': 'Product doesn\'t exist'}), 404
db.session.delete(product)
db.session.commit()
return make_response(jsonify({'message': 'Removed product with ID {}'.format(id)}), 200)
# CRUD FUNCTIONS DELIVERY
def getAdminDeliverys():
deliveries = Delivery.query.all()
return jsonify(deliveries=[shipper.serialize for shipper in deliveries])
def postAdminDelivery(status, company, phone, order_id):
order_id_existing = Order.query.get(order_id)
if not order_id_existing:
return jsonify({'message': 'Order ID doesn\'t exist'}), 404
order_id_delivery_existing = Delivery.query.get(order_id)
if order_id_delivery_existing:
return jsonify({'message': 'Delivery Order ID already exists'}), 400
delivery = Delivery(status=status, company=company, phone=phone, order_id=order_id)
db.session.add(delivery)
db.session.commit()
return jsonify(delivery=delivery.serialize)
def getAdminDelivery(id):
delivery = Delivery.query.get(id)
if not delivery:
return jsonify({'message': 'Delivery doesn\'t exist'}), 404
return jsonify(delivery=delivery.serialize)
def updateAdminDelivery(id, status, company, phone, order_id):
delivery = Delivery.query.get(id)
if not delivery:
return jsonify({'message': 'Delivery doesn\'t exist'}), 404
if status:
delivery.status = status
if company:
delivery.company = company
if phone:
delivery.phone = phone
if order_id:
order_id_existing = Order.query.get(order_id)
if not order_id_existing:
return jsonify({'message': 'Order ID doesn\'t exist'}), 404
order_id_delivery_existing = Delivery.query.filter_by(order_id=order_id).first()
if order_id_delivery_existing:
return jsonify({'message': 'Delivery Order ID already exists'}), 400
delivery.order_id = order_id
db.session.add(delivery)
db.session.commit()
return make_response(jsonify({'message': 'Updated delivery with ID: {}'.format(id)}), 200)
def deleteAdminDelivery(id):
shipper = Delivery.query.get(id)
if not shipper:
return jsonify({'message': 'Delivery doesn\'t exist'}), 404
db.session.delete(shipper)
db.session.commit()
return make_response(jsonify({'message': 'Removed shipper with ID {}'.format(id)}), 200)
# CRUD FUNCTIONS USER
def getAdminUsers():
users = User.query.all()
return jsonify(users=[user.serialize for user in users])
def postAdminUser(email, password, first_name, last_name, role, profile_picture, address, city, state, postcode, country, phone):
user_existing = User.query.filter_by(email=email).first()
if user_existing:
return jsonify({'message': 'User already existing'}), 400
hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
user = User(email=email, password=hashed_password, first_name=first_name, last_name=last_name, role=role, profile_picture=profile_picture)
db.session.add(user)
db.session.commit()
userdetails = UserDetails(address=address, city=city, state=state, postcode=postcode, country=country, phone=phone, user_id=user.user_id)
db.session.add(userdetails)
db.session.commit()
return jsonify(user=user.serialize)
def getAdminUser(id):
user = User.query.get(id)
if not user:
return jsonify({'message': 'User doesn\'t exist'}), 404
return jsonify(user=user.serialize)
def updateAdminUser(id, email, password, first_name, last_name, role, profile_picture, address, city, state, postcode, country, phone):
user = User.query.get(id)
if not user:
return jsonify({'message': 'User doesn\'t exist'}), 404
userdetails = UserDetails.query.filter_by(user_id=user.user_id).first()
if not userdetails:
return jsonify({'message': 'User Details doesn\'t exist'}), 404
if email:
existing_email = User.query.filter_by(email=email).first()
if existing_email:
if int(existing_email.user_id) != int(id):
return jsonify({'message': 'Email already existing'}), 400
user.email = email
if password:
hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
user.password = hashed_password
if first_name:
user.first_name = first_name
if last_name:
user.last_name = last_name
if role:
user.role = role
if profile_picture:
user.profile_picture = profile_picture
if address:
userdetails.address = address
if city:
userdetails.city = city
if state:
userdetails.state = state
if postcode:
userdetails.postcode = postcode
if country:
userdetails.country = country
if phone:
userdetails.phone = phone
db.session.add(user)
db.session.add(userdetails)
db.session.commit()
return make_response(jsonify({'message': 'Updated user with ID: {}'.format(id)}), 200)
def deleteAdminUser(id):
user = User.query.get(id)
if not user:
return jsonify({'message': 'User doesn\'t exist'}), 404
userdetails = UserDetails.query.filter_by(user_id=id)
if userdetails:
for userdetail in userdetails:
db.session.delete(userdetail)
db.session.delete(user)
db.session.commit()
return make_response(jsonify({'message': 'Removed user with ID: {}'.format(id)}), 200)
# CRUD FUNCTIONS USERDETAILS
def getAdminUserDetails():
userdetails = UserDetails.query.all()
return jsonify(userdetails=[userdetail.serialize for userdetail in userdetails])
def getAdminUserDetail(id):
userdetail = UserDetails.query.get(id)
if not userdetail:
return jsonify({'message': 'UserDetails doesn\'t exist'}), 404
return jsonify(userdetail=userdetail.serialize)
# CRUD FUNCTIONS ORDERS
def getAdminOrders():
orders = Order.query.all()
return jsonify(orders=[order.serialize for order in orders])
def postAdminOrder(order_number, order_details, user_id):
order_existing = Order.query.filter_by(order_number=order_number).first()
if order_existing:
return jsonify({'message': 'Order already existing'}), 400
user_id_existing = User.query.get(user_id)
if not user_id_existing:
return jsonify({'message': 'User ID doesn\'t exist'}), 400
order = Order(order_number=order_number, order_details=order_details, user_id=user_id)
db.session.add(order)
db.session.commit()
return jsonify(order=order.serialize)
def getAdminOrder(id):
order = Order.query.get(id)
if not order:
return jsonify({'message': 'Order doesn\'t exist'}), 404
return jsonify(order=order.serialize)
def updateAdminOrder(id, order_number, order_details, user_id):
order = Order.query.get(id)
if not order:
return jsonify({'message': 'Order doesn\'t exist'}), 400
if order_number:
order_existing = Order.query.filter_by(order_number=order_number).first()
if order_existing:
return jsonify({'message': 'Order already existing'}), 400
order.order_number = order_number
if order_details:
order.order_details = order_details
if user_id:
user_id_existing = User.query.get(user_id)
if not user_id_existing:
return jsonify({'message': 'User ID doesn\'t exist'}), 400
order.user_id = user_id
db.session.add(order)
db.session.commit()
return make_response(jsonify({'message': 'Updated Order with ID: {}'.format(id)}), 200)
def deleteAdminOrder(id):
order = Order.query.get(id)
if not order:
return jsonify({'message': 'Order doesn\'t exist'}), 404
orderdetails = OrderDetails.query.filter_by(order_id=order.order_id)
if orderdetails:
for orderdetail in orderdetails:
db.session.delete(orderdetail)
db.session.delete(order)
# db.session.delete(orderdetails)
db.session.commit()
return make_response(jsonify({'message': 'Removed order with ID {}'.format(id)}), 200)
# CRUD FUNCTIONS ORDERDETAILS
def getAdminOrderDetails():
orderdetails = OrderDetails.query.all()
return jsonify(orderdetails=[orderdetail.serialize for orderdetail in orderdetails])
def postAdminOrderDetails(quantity, product_id, order_id):
product_id_existing = Product.query.get(product_id)
if not product_id_existing:
return jsonify({'message': 'Product ID does\'t exist'}), 400
order_id_existing = Order.query.get(order_id)
if not order_id_existing:
return jsonify({'message': 'Order ID does\'t exist'}), 400
product = Product.query.get(product_id)
product.stock = int(product.stock) - int(quantity)
if product.stock < 0:
return jsonify({'message': 'Not in stock'}), 400
db.session.add(product)
total = product.price * int(quantity)
orderdetails = OrderDetails(quantity=quantity, total=total, product_id=product_id, order_id=order_id)
db.session.add(orderdetails)
db.session.commit()
return jsonify(orderdetails=orderdetails.serialize)
def getAdminOrderDetail(id):
orderdetail = OrderDetails.query.get(id)
if not orderdetail:
return jsonify({'message': 'Order Detail doesn\'t exist'}), 404
return jsonify(orderdetail=orderdetail.serialize)
def updateAdminOrderDetails(id, quantity, product_id, order_id):
orderdetail = OrderDetails.query.get(id)
if not orderdetail:
return jsonify({'message': 'OrderDetails doesn\'t exist'}), 400
if quantity:
if not quantity.isdigit():
return jsonify({"message": "Quantity should be an integer"}), 400
previous_quantity = orderdetail.quantity
delta = int(previous_quantity) - int(quantity)
if delta > 0:
product = Product.query.get(orderdetail.product_id)
product.stock = int(product.stock) - int(delta)
db.session.add(product)
elif delta < 0:
product = Product.query.get(orderdetail.product_id)
product.stock = int(product.stock) + int(delta)
db.session.add(product)
orderdetail.quantity = quantity
product = Product.query.get(orderdetail.product_id)
orderdetail.total = product.price * int(quantity)
if product_id:
product_id_existing = Product.query.get(product_id)
if not product_id_existing:
return jsonify({'message': 'Product ID does\'t exist'}), 400
orderdetail.product_id = product_id
if order_id:
order_id_existing = Order.query.get(order_id)
if not order_id_existing:
return jsonify({'message': 'Order ID does\'t exist'}), 400
orderdetail.order_id = order_id
db.session.add(orderdetail)
db.session.commit()
return make_response(jsonify({'message': 'Updated Order Details with ID: {}'.format(id)}), 200)
def deleteAdminOrderDetails(id):
orderdetail = OrderDetails.query.get(id)
if not orderdetail:
return jsonify({'message': 'OrderDetails doesn\'t exist'}), 404
db.session.delete(orderdetail)
db.session.commit()
return make_response(jsonify({'message': 'Removed Order Detail with ID {}'.format(id)}), 200)
# CRUD FUNCTION PAYMENTS
def getAdminPayments():
payments = Payment.query.all()
return jsonify(payments=[payment.serialize for payment in payments])
def postAdminPayment(payment_method, order_id):
payment_id_existing = Payment.query.get(order_id)
if payment_id_existing:
return jsonify({'message': "Order ID already exist in Payment"}), 400
order_id_existing = Order.query.get(order_id)
if not order_id_existing:
return jsonify({'message': "Order ID doesn\'t exist in Order"}), 400
payment = Payment(payment_method=payment_method, order_id=order_id)
db.session.add(payment)
db.session.commit()
return jsonify(payment=payment.serialize)
def getAdminPayment(id):
payment = Payment.query.get(id)
if not payment:
return jsonify({'message': 'Payment doesn\'t exist'}), 404
return jsonify(payment=payment.serialize)
def updateAdminPayment(id, payment_method, order_id):
payment = Payment.query.get(id)
if not payment:
return jsonify({'message': 'Payment doesn\'t exist'}), 400
if payment_method:
payment.payment_method = payment_method
if order_id:
order_id_existing = Order.query.get(order_id)
if order_id_existing:
return jsonify({'message': 'Order ID already exist'}), 400
payment.order_id = order_id
db.session.add(payment)
db.session.commit()
return make_response(jsonify({'message': 'Updated Payment with ID: {}'.format(id)}), 200)
def deleteAdminPayment(id):
payment = Payment.query.get(id)
if not payment:
return jsonify({'message': 'Payment doesn\'t exist'}), 404
db.session.delete(payment)
db.session.commit()
return make_response(jsonify({'message': 'Removed Payment with ID {}'.format(id)}), 200)
# CRUD FUNCTION CARTDETAILS
def getAdminCartDetails():
cartdetails = CartDetails.query.all()
return jsonify(cartdetails=[cartdetail.serialize for cartdetail in cartdetails])
def postAdminCartDetails(quantity, product_id, user_id):
product_id_existing = Product.query.get(product_id)
if not product_id_existing:
return jsonify({'message': 'Product ID does\'t exist'}), 400
user_id_existing = User.query.get(user_id)
if not user_id_existing:
return jsonify({'message': 'User ID does\'t exist'}), 400
cartdetails_existing = CartDetails.query.filter_by(product_id=product_id, user_id=user_id).first()
if cartdetails_existing:
cartdetails_existing.quantity = int(cartdetails_existing.quantity) + int(quantity)
total = cartdetails_existing.quantity * product_id_existing.price
cartdetails_existing.total = total
db.session.add(cartdetails_existing)
db.session.commit()
return jsonify(cartdetails_existing=cartdetails_existing.serialize)
total = int(quantity) * product_id_existing.price
cartdetails = CartDetails(quantity=quantity, total=total, product_id=product_id, user_id=user_id)
db.session.add(cartdetails)
db.session.commit()
return jsonify(cartdetails=cartdetails.serialize)
def getAdminCartDetail(id):
cartdetail = CartDetails.query.get(id)
if not cartdetail:
return jsonify({'message': 'Cart Detail doesn\'t exist'}), 404
return jsonify(cartdetail=cartdetail.serialize)
def updateAdminCartDetail(id, quantity, product_id, user_id):
cartdetail = CartDetails.query.get(id)
if not cartdetail:
return jsonify({'message': 'Cart Detail doesn\'t exist'}), 400
if quantity:
delta = int(cartdetail.quantity) - int(quantity)
if delta > 0:
product = Product.query.get(cartdetail.product_id)
product.stock = int(product.stock) - int(delta)
db.session.add(product)
total = int(quantity) * product.price
cartdetail.total = total
elif delta <0:
product = Product.query.get(cartdetail.product_id)
product.stock = int(product.stock) + int(delta)
db.session.add(product)
total = int(quantity) * product.price
cartdetail.total = total
cartdetail.quantity = quantity
if product_id:
cartdetail.product_id = product_id
if user_id:
cartdetail.user_id = user_id
db.session.add(cartdetail)
db.session.commit()
def deleteAdminCartDetail(id):
cartdetail = CartDetails.query.get(id)
if not cartdetail:
return jsonify({'message': 'Cart Details doesn\'texist'}), 404
db.session.delete(cartdetail)
db.session.commit()
return make_response(jsonify({'message': 'Removed Cart Details with ID {}'.format(id)}), 200)
# --- INFO: REACT FUNCTIONS ---
@jwt.user_claims_loader
def add_claims_to_access_token(identity):
user = User.query.filter_by(email=identity).first()
userdetails = UserDetails.query.filter_by(user_id=user.user_id).first()
return {
'email': user.email,
'first_name' : user.first_name,
'last_name' : user.last_name,
'profile_picture' : user.profile_picture,
'address' : userdetails.address,
'city' : userdetails.city,
'state' : userdetails.state,
'postcode' : userdetails.postcode,
'country' : userdetails.country,
'phone' : userdetails.phone,
}
def login(email, password):
if not email:
return jsonify({"message": "Missing Email"}), 400
if not password:
return jsonify({"message": "Missing Password"}), 400
user = User.query.filter_by(email=email).first()
if not user:
return jsonify({"message": "User not found"}), 404
if user.password == '':
return jsonify({"message": "Account not active, Check your Emails"}), 401
if not bcrypt.check_password_hash(user.password, password):
return jsonify({"message": "Bad email or password"}), 401
ret = {
'access_token': create_access_token(identity=email),
}
return jsonify(ret), 201
def register(email, first_name, last_name):
user = User.query.filter_by(email=email).first()
if user:
if user.password == '':
db.session.delete(user)
db.session.commit()
else:
return jsonify({"message": "Email already existing"}), 400
user = User(email=email, password='', first_name=first_name, last_name=last_name)
db.session.add(user)
db.session.commit()
userdetail = UserDetails(user_id=user.user_id)
db.session.add(userdetail)
db.session.commit()
send_set_email(user)
return jsonify({"message": "Check " + email + " to set your password"})
def send_set_email(user):
token = user.get_reset_token()
msg = Message('Account Activation', sender='[email protected]', recipients=[user.email])
msg.body = f'''Hello and welcome to our shop,
To activate your account, please visit the following link:
{'https://react-shop-application.herokuapp.com/auth/set/' + token}
Luxury Shop
'''
try:
mail.send(msg)
except:
return jsonify({"message": "Mailbox unavailable invalid SMTP"}), 401
def send_reset_email(user):
token = user.get_reset_token()
msg = Message('Password Reset Request', sender='[email protected]', recipients=[user.email])
msg.body = f'''To reset your password, please visit the following link:
{ 'https://react-shop-application.herokuapp.com/auth/set/' + token}
If you did not make this request, simply ignore this email and no changes would be made.
Luxury Shop
'''
try:
mail.send(msg)
except:
return jsonify({"message": "Mailbox unavailable invalid SMTP"}), 401
def user_info(email):
user = User.query.filter_by(email=email).first()
if not user:
return jsonify({"message": "User not found"}), 404
return jsonify(user.serialize)
def update(email, content):
user = User.query.filter_by(email=email).first()
password = content.get("password", None)
first_name = content.get("first_name", None)
last_name = content.get("last_name", None)
profile_picture = content.get("profile_picture", None)
if password:
user.password = bcrypt.generate_password_hash(password).decode('utf-8')
if first_name:
user.first_name = first_name
if last_name:
user.last_name = last_name
if profile_picture:
user.profile_picture = profile_picture
db.session.add(user)
db.session.commit()
return jsonify({"message": "{} updated".format(email)}), 200
def delete(email):
user = User.query.filter_by(email=email).first()
if not user:
return jsonify({"message": "User not found"}), 401
userdetails = UserDetails.query.filter_by(user_id=user.user_id).all()
for userdetail in userdetails:
db.session.delete(userdetail)
db.session.delete(user)
db.session.commit()
return make_response(jsonify({'Deleted': 'Removed user {}'.format(email)}), 200)
# --- INFO: ROUTES ---
@app.route('/')
def home():
return render_template('documentation.html', title='Documentation')
# --- INFO: ADMIN ROUTES ---
# CRUD ROUTES CATEGORY
@app.route('/api/admin/categories', methods=['GET', 'POST'])
@jwt_required
def adminCategories():
isAdmin()
if request.method == 'GET':
return getAdminCategories()
if request.method == 'POST':
if not request.is_json:
return jsonify({"message": "Missing JSON in request"}), 400
content = request.get_json(force=True)
name = content.get("name", None)
description = content.get("description", None)
if not name:
return jsonify({'message': 'Missing Name'})
if not description:
return jsonify({'message': 'Missing Description'})
return postAdminCategory(name, description)
@app.route('/api/admin/category/<id>', methods=['GET', 'PUT', 'DELETE'])
@jwt_required
def adminCategory(id):
isAdmin()
if not id:
return jsonify({"message": "Missing ID Parameter"}), 404
if request.method == 'GET':
return getAdminCategory(id)
if request.method == 'PUT':
if not request.is_json:
return jsonify({"message": "Missing JSON in request"}), 400
content = request.get_json(force=True)
name = content['name'] if 'name' in content.keys() else ''
description = content['description'] if 'description' in content.keys() else ''
return updateAdminCategory(id, name, description)
if request.method == 'DELETE':
return deleteAdminCategory(id)
# CRUD ROUTES PRODUCT
@app.route('/api/admin/products', methods=['GET', 'POST'])
@jwt_required
def adminProducts():
isAdmin()
if request.method == 'GET':
return getAdminProducts()
if request.method == 'POST':
if not request.is_json:
return jsonify({"message": "Missing JSON in request"}), 400
content = request.get_json(force=True)
product_name = content.get("product_name", None)
product_description = content.get("product_description", None)
price = content.get("price", None)
stock = content.get("stock", None)
images_url = content.get("images_url", None)
category_id = content.get("category_id", None)
if not product_name:
return jsonify({'message': 'Missing Product name'})
if not product_description:
return jsonify({'message': 'Missing Product description'})
if not price:
return jsonify({'message': 'Missing Price'})
if not stock:
return jsonify({'message': 'Missing Stock'})
if not category_id:
return jsonify({'message': 'Missing Category ID'})
return postAdminProduct(product_name, product_description, price, stock, images_url, category_id)
@app.route('/api/admin/product/<id>', methods=['GET', 'PUT', 'DELETE'])
@jwt_required
def adminProduct(id):
isAdmin()
if not id:
return jsonify({"message": "Missing ID Parameter"}), 404
if request.method == 'GET':
return getAdminProduct(id)
if request.method == 'PUT':
if not request.is_json:
return jsonify({"message": "Missing JSON in request"}), 400
content = request.get_json(force=True)
product_name = content['product_name'] if 'product_name' in content.keys() else ''
product_description = content['product_description'] if 'product_description' in content.keys() else ''
price = content['price'] if 'price' in content.keys() else ''
stock = content['stock'] if 'stock' in content.keys() else ''
images_url = content['images_url'] if 'images_url' in content.keys() else ''
category_id = content['category_id'] if 'category_id' in content.keys() else ''
return updateAdminProduct(id, product_name, product_description, price, stock, images_url, category_id)
if request.method == 'DELETE':
return deleteAdminProduct(id)
# CRUD ROUTES SHIPPER
@app.route('/api/admin/deliveries', methods=['GET', 'POST'])
@jwt_required
def adminDeliverys():