-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.py
840 lines (617 loc) · 26.7 KB
/
routes.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
from app import app,db,mail
from flask import render_template, redirect, url_for, request, flash, session
from models import *
from werkzeug.utils import secure_filename
import bcrypt
import re
import razorpay
from flask_mail import Message
# extensions for product images
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
# ========================== Validations =======================================
class Validation:
def validate_username(self, username):
# pattern for username check
pattern = r"^[A-Z][a-zA-Z0-9]{5,10}$"
return bool(re.match(pattern, username))
def validate_password(self, password):
# pattern for password check
pattern = r"^[a-zA-Z0-9#$@]{8,20}$"
return bool(re.match(pattern, password))
def validate_mobile_num(self, mobile_num):
# pattern for password check
pattern = r"^[0-9]{10}$"
return bool(re.match(pattern, mobile_num))
def validate_email(self, email):
# pattern for email check
pattern = r"^[a-zA-Z0-9\.]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,}$"
return bool(re.match(pattern, email))
# creating object of class Validation
validation = Validation()
# ============================================================================
# get all products of search query
def search_products(query):
try:
product_results = Product.query.filter(Product.product_name.ilike(f'%{query}%')).all()
# filtering category of all search products
products = []
categories = []
for product in product_results:
products.append(product.product_id)
categories.append(Category.query.filter_by(category_id = product.category_id).first())
# get all products
all_products = {}
# creating dict of category and products as key value pair
for cat in categories:
cat_products = Product.query.filter(Product.category_id==cat.category_id, Product.product_id.in_(products)).all()
all_products[cat.category_name] = cat_products
return all_products
except Exception as e:
return None
# Rentee home Page
@app.route('/')
def index():
try:
category = Category.query.all()
all_products = {}
# creating dict of category and products as key value pair
for cat in category:
cat_products = Product.query.filter_by(category_id=cat.category_id).all()
all_products[cat.category_name] = cat_products
search = request.args.get('search')
if search:
all_products = search_products(search)
return render_template('index.html', all_products=all_products)
except Exception as e:
flash('Something went wrong. Please try again !','danger')
return redirect(url_for('index'))
# Renter home Page
@app.route('/renter')
def renter():
# check if user is in or not
if 'username' in session:
try:
user = User.query.filter_by(username=session['username']).first()
# if user is renter redirect it to renter home page
if user.is_renter:
products = Product.query.filter_by(user_id=user.user_id).all()
categories = Category.query.all()
orders = Order.query.all()
return render_template('renter.html', products=products, categories=categories, orders = orders, user = user)
else:
# if user is not renter then redirect it to login page
flash('Kindly login as renter !!', 'danger')
return redirect(url_for('login'))
except Exception as e:
flash('Something went wrong. Please login again!', 'danger')
return redirect(url_for('login'))
else:
# if user not in session redirect it to login page
flash('Session expired ! Please login again.','danger')
return redirect(url_for('login'))
# Renter (add category) session
@app.route('/add_category', methods=['GET', 'POST'])
def add_category():
if 'username' in session:
if request.method == 'POST':
try:
category_name = request.form.get('category_name')
category = Category.query.filter_by(category_name=category_name).first()
# check if category already exists or not
if not category:
category = Category(category_name=category_name)
db.session.add(category)
db.session.commit()
flash(f'Category "{category.category_name}" added successfully !!', 'success')
return redirect(url_for('renter'))
else:
flash(f'{category.category_name} already exists !!', 'danger')
return redirect(url_for('renter'))
except Exception as e:
flash('Something went wrong. Please try to add category again!', 'danger')
return redirect(url_for('renter'))
else:
flash('Session expired ! Please login again.','danger')
return redirect(url_for('login'))
# image file check
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# image validator
def image_validator(product_image):
# check if the post request has the file
if not product_image:
return False
# If the user does not select a file, the browser submits an
# empty file without a filename.
if product_image.filename == '':
return False
# check file format
if product_image and not allowed_file(product_image.filename):
return False
return True
# Renter (add products) session
@app.route('/add_products', methods=['GET', 'POST'])
def add_products():
if 'username' in session:
if request.method == 'POST':
product_name = request.form.get('product_name')
product_price = request.form.get('product_price')
product_desc = request.form.get('product_desc')
product_image = request.files['product_image']
category_name = request.form.get('category_name')
try:
# valid image
if image_validator(product_image):
img_filename = secure_filename(product_image.filename)
product_image.save('static/images/products/' + img_filename)
else:
flash(
f"Please provide file in {ALLOWED_EXTENSIONS} format.", 'danger')
return redirect(url_for('renter'))
category = Category.query.filter_by(
category_name=category_name).first()
user = User.query.filter_by(username=session['username']).first()
product = Product(product_name=product_name, product_price=product_price,
product_desc=product_desc, product_image=img_filename, category_id=category.category_id, user_id=user.user_id)
db.session.add(product)
db.session.commit()
return redirect(url_for('renter'))
except Exception as e:
flash('Something went wrong. Please try to add product again!', 'danger')
return redirect(url_for('renter'))
else:
flash('Please login for adding products', 'danger')
return redirect(url_for('login'))
# update existing product
@app.route('/update_product/<int:product_id>', methods=['POST', 'GET'])
def update_product(product_id):
if 'username' in session:
try:
# fetching product by id
product = Product.query.filter_by(product_id=product_id).first()
if request.method == 'POST':
product.product_name = request.form.get('product_name')
product.product_price = request.form.get('product_price')
product.product_desc = request.form.get('product_desc')
category_id = request.form.get('category_id')
category = Category.query.get_or_404(category_id)
product.category_id = category.category_id
product_image = request.files['product_image']
# valid image
if image_validator(product_image):
img_filename = secure_filename(product_image.filename)
product_image.save('static/images/products/' + img_filename)
product.product_image = img_filename
else:
flash(
f"Please provide file in {ALLOWED_EXTENSIONS} format.", 'danger')
return redirect(url_for('renter'))
db.session.commit()
return redirect('/renter')
categories = Category.query.all()
return render_template('update_product.html', product=product, categories=categories)
except Exception as e:
flash('Something went wrong. Please try to update again!', 'danger')
return redirect(url_for('renter'))
else:
flash('Please login for updating products', 'danger')
return redirect(url_for('login'))
# delete product
@app.route('/delete_product/<int:product_id>', methods=['POST', 'GET'])
def delete_product(product_id):
if 'username' in session:
try:
product = Product.query.filter_by(product_id=product_id).first()
db.session.delete(product)
db.session.commit()
return redirect('/renter')
except Exception as e:
flash('Something went wrong. Please try to delete again!', 'danger')
return redirect(url_for('renter'))
else:
flash('Session expired ! Please login again.','danger')
return redirect(url_for('login'))
# Registration session
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
# get all values of post request
username = request.form.get('username')
if not validation.validate_username(username):
flash(
'Please fill username in right format (User097) and length should be of 6 or more', 'danger')
return redirect('register')
password = request.form.get('password')
if not validation.validate_password(password):
flash('Please fill password in right format (Pass@097F)', 'danger')
return redirect('register')
first_name = request.form.get('first_name')
last_name = request.form.get('last_name')
mobile_number = request.form.get('mobile_number')
if not validation.validate_mobile_num(mobile_number):
flash('Please enter valid mobile number', 'danger')
return redirect('register')
email = request.form.get('email')
if not validation.validate_email(email):
flash('Please enter valid email id', 'danger')
return redirect('register')
is_renter = request.form.get('is_renter')
is_rentee = request.form.get('is_rentee')
if is_renter is None and is_rentee is None:
flash('Please select one of the option (is_renter or is_rentee)', 'danger')
return redirect('register')
# check if username already taken
if User.query.filter_by(username=username).first():
flash("Username already exists !", 'danger')
return redirect(url_for('register'))
# Encrypt the password using bcrypt
hashed_password = bcrypt.hashpw(
password.encode('utf-8'), bcrypt.gensalt())
try:
# create new user
new_user = User(
username=username,
password=hashed_password,
first_name=first_name,
last_name=last_name,
mobile_number=mobile_number,
email=email,
is_renter=is_renter,
is_rentee=is_rentee
)
# add user to database
db.session.add(new_user)
db.session.commit()
flash('User registered successfully!', 'success')
return redirect(url_for('login'))
except Exception as e:
flash('Something went wrong. Please fill proper details!', 'danger')
return redirect(url_for('register'))
return render_template('register.html')
# Login session
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Process the login form data
username = request.form.get('username')
password = request.form.get('password')
try:
# Retrieve the user from the database
user = User.query.filter_by(username=username).first()
if user and bcrypt.checkpw(password.encode('utf-8'), user.password):
if user.is_renter == True:
session['username'] = username
session.permanent = True
flash('Login as renter sucessfully!', 'success')
return redirect(url_for('renter'))
else:
session['username'] = username
session.permanent = True
flash('Login as rentee sucessfully!', 'success')
return redirect(url_for('index'))
else:
flash("Invalid username or password", 'danger')
return redirect(url_for('login'))
except Exception as e:
flash('Something went wrong. Please login again!', 'danger')
return redirect(url_for('login'))
return render_template('login.html')
# Logout session
@app.route('/logout')
def logout():
if 'username' in session:
session.pop('username', None)
return redirect(url_for('login'))
else:
flash('User already logout!', 'danger')
return redirect(url_for('login'))
# product view page
@app.route('/product_view_page/<int:product_id>')
def product_view_page(product_id):
try:
product = Product.query.get_or_404(product_id)
similar_products = Product.query.filter(
Product.category_id == product.category_id, Product.product_id != product_id).all()
return render_template('product_view_page.html', product=product, similar_products=similar_products)
except Exception as e:
flash('Something went wrong. Try again!', 'danger')
return redirect(url_for('index'))
# cart page
@app.route('/cart')
def cart():
if 'username' in session:
try:
user = User.query.filter_by(username=session['username']).first()
cart_items = CartItem.query.filter_by(user_id=user.user_id).all()
# to get total cart amount
total_cart_amount = 0
for item in cart_items:
total_rent = item.quantity * item.product.product_price
total_deposit = 2 * item.quantity * item.product.product_price
total_cart_amount += total_deposit + total_rent
return render_template('cart.html', cart_items=cart_items, total_cart_amount=total_cart_amount)
except Exception as e:
flash('Something went wrong !', 'danger')
return redirect(url_for('index'))
else:
flash('Please login to access cart !!', 'danger')
return redirect(url_for('login'))
# cart item
@app.context_processor
def cart_item_count():
if 'username' in session:
try:
user = User.query.filter_by(username=session['username']).first()
cart_items = CartItem.query.filter_by(user_id=user.user_id).all()
count = len(cart_items)
return {'cart_item_count': count}
except Exception as e:
return {'cart_item_count': 0}
else:
return {'cart_item_count': 0}
# add to cart
@app.route('/add_to_cart/<int:product_id>')
def add_to_cart(product_id):
if 'username' in session:
try:
user = User.query.filter_by(username=session['username']).first()
# Check if the user already has the product in their cart
cart_item = CartItem.query.filter_by(
user_id=user.user_id, product_id=product_id).first()
if cart_item:
# increment the quantity
cart_item.quantity += 1
else:
# add product to cart
cart_item = CartItem(user_id=user.user_id, product_id=product_id)
# save to db
db.session.add(cart_item)
db.session.commit()
return redirect('/cart')
except Exception as e:
flash('Something went wrong. Try to add to cart again!', 'danger')
return redirect(url_for('index'))
else:
flash('Please login to add product to cart !!', 'danger')
return redirect(url_for('login'))
# increment quantity
@app.route('/add_quantity/<int:cart_id>')
def add_quantity(cart_id):
try:
# get cart item
cart_item = CartItem.query.get_or_404(cart_id)
# update quantity
cart_item.quantity += 1
db.session.commit()
return redirect('/cart')
except Exception as e:
flash('Please try to add quantity again!', 'danger')
return redirect(url_for('cart'))
# decrement quantity
@app.route('/sub_quantity/<int:cart_id>')
def sub_quantity(cart_id):
try:
# get cart item
cart_item = CartItem.query.get_or_404(cart_id)
# if quantity = 1 then delete product from cart
if cart_item.quantity == 1:
db.session.delete(cart_item)
db.session.commit()
else:
cart_item.quantity -= 1
db.session.commit()
return redirect('/cart')
except Exception as e:
flash('Please try to decrease quantity again!', 'danger')
return redirect(url_for('cart'))
# delete cart item
@app.route('/delete_cart_item/<int:cart_id>')
def delete_cart_item(cart_id):
try:
cart = CartItem.query.get_or_404(cart_id)
db.session.delete(cart)
db.session.commit()
return redirect('/cart')
except Exception as e:
flash('Something went wrong. Please try to delete again!', 'danger')
return redirect(url_for('cart'))
# delete category
@app.route('/delete_category/<int:id>')
def delete_category(id):
try:
category = Category.query.filter_by(category_id = id).first()
db.session.delete(category)
db.session.commit()
return redirect('/renter')
except Exception as e:
flash("Something went wrong !!","danger")
return redirect('/renter')
# checkout page
@app.route('/checkout/',methods=['POST','GET'])
def checkout():
if 'username' in session:
try:
user = User.query.filter_by(username = session['username']).first()
cart = CartItem.query.filter_by(user_id = user.user_id).all()
# to get total cart amount
total_cart_amount = 0
for item in cart:
total_rent = item.quantity * item.product.product_price
total_deposit = 2 * item.quantity * item.product.product_price
total_cart_amount += total_deposit + total_rent
if request.method == 'POST':
full_name = request.form.get('full_name')
email = request.form.get('email')
mobile_number = request.form.get('mobile_number')
address = request.form.get('address')
pincode = request.form.get('pincode')
total_rent = sum(item.quantity * item.product.product_price for item in cart)
total_deposit = sum(2 * item.quantity * item.product.product_price for item in cart)
total_amount = int(request.form.get('total_amount'))
products = []
for item in cart:
products.append(item.product)
order = Order(
user_id = user.user_id,
full_name = full_name,
email = email,
mobile_number = mobile_number,
address = address,
pincode = pincode,
total_rent = total_rent,
total_deposit = total_deposit,
total_amount = total_amount,
products = products
)
# save order
db.session.add(order)
db.session.commit()
# delete entire cart after order request
for item in cart:
db.session.delete(item)
db.session.commit()
return redirect(url_for('payment'))
return render_template('checkout.html', user = user, total_cart_amount = total_cart_amount, cart = cart)
except Exception as e:
flash('Something went wrong. Please try again to place order!', 'danger')
return redirect(url_for('checkout'))
else:
flash('Session expired ! Please login again.','danger')
return redirect(url_for('login'))
# payment section
@app.route('/payment',methods=['POST','GET'])
def payment():
if 'username' in session:
try:
user = User.query.filter_by(username = session['username']).first()
order = Order.query.filter_by(user_id = user.user_id).first()
# creating razorpay client object
client = razorpay.Client(auth=('rzp_test_UjALlxSGoBRkey', 'HeStkBCqNkdeZ7JQEdCnDuqD'))
DATA = {
"amount": (int(order.total_amount) * 100),
"currency": "INR",
"payment_capture": "1"
}
payment = client.order.create(data=DATA)
# store in database
paymentStatus = Payment(
user_id = user.user_id,
order_id = order.order_id,
razorpay_order_id = payment['id'],
amount = payment['amount'],
payment_status = payment['status']
)
db.session.add(paymentStatus)
db.session.commit()
return render_template('payment.html', payment = payment, user = user)
except Exception as e:
flash('Something went wrong. Please try again!', 'danger')
return redirect(url_for('payment'))
else:
flash('Session expired ! Please login again.','danger')
return redirect(url_for('login'))
@app.route('/success',methods=['POST','GET'])
def success():
if 'username' in session:
try:
user = User.query.filter_by(username = session['username']).first()
payment = Payment.query.filter_by(user_id = user.user_id).first()
payment.payment_status = 'Completed'
db.session.commit()
# send mail after payment
subject = f'Your Order has been placed | Order ID : {payment.razorpay_order_id}'
recipient = str(user.email)
sender = app.config['MAIL_USERNAME']
message_body = f'''
Hi {user.first_name} {user.last_name},
Your Order has been placed successfully !!
Order ID : {payment.razorpay_order_id}
Amount : {payment.amount//100}
Payment Status : {payment.payment_status}
Thanks & Regards,
PRW
'''
message = Message(subject=subject, recipients=[recipient], body=message_body, sender = sender)
mail.send(message)
flash("Email sent successfully!",'success')
return render_template('success.html', payment = payment)
except Exception as e:
flash("Something went wrong!",'danger')
return redirect(url_for('success'))
else:
flash('Session expired ! Please login again.','danger')
return redirect(url_for('login'))
# admin section
@app.route('/admin_panel')
def admin_panel():
users = User.query.all()
return render_template('admin_panel.html', users = users)
# delete user
@app.route('/delete_user/<int:id>')
def delete_user(id):
try:
user = User.query.filter_by(user_id = id).first()
db.session.delete(user)
db.session.commit()
return redirect('/admin_panel')
except Exception as e:
flash("Something went wrong !!","danger")
return redirect('/admin_panel')
# testing code
@app.route('/delete_all')
def delete_all():
Payment.query.delete()
Order.query.delete()
db.session.query(order_product_association).filter_by(order_id=2).delete()
db.session.commit()
return redirect(url_for('login'))
# order section
@app.route('/order', methods=['POST','GET'])
def order():
if 'username' in session:
try:
user = User.query.filter_by(username = session['username']).first()
if request.method == 'POST':
razorpay_order_id = request.form.get('razorpay_order_id')
payment = Payment.query.filter_by(razorpay_order_id = razorpay_order_id).first()
order = Order.query.filter_by(order_id = payment.order_id).first()
return render_template('order.html', order = order, payment = payment, user = user)
return render_template('order.html', payment = None)
except Exception as e:
flash('Something went wrong. Please try again!', 'danger')
return redirect(url_for('order'))
else:
flash('Session expired ! Please login again.','danger')
return redirect(url_for('login'))
# about section
@app.route('/about')
def about():
return render_template('about.html')
# contact section
@app.route('/contact', methods=['POST','GET'])
def contact():
if 'username' in session:
if request.method == 'POST':
name = request.form.get('name')
email = request.form.get('email')
mobile = request.form.get('mobile')
message = request.form.get('message')
try:
contact = Contact(
name = name,
email = email,
mobile = mobile,
message = message
)
db.session.add(contact)
db.session.commit()
flash('Form has been submitted successfully!!','success')
return redirect(url_for('contact'))
except Exception as e:
flash('Form not submitted. Please try again !','danger')
return redirect(url_for('contact'))
else:
return render_template('contact.html')
else:
flash('Session expired ! Please login again.','danger')
return redirect(url_for('login'))