-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviews.py
More file actions
2002 lines (1689 loc) · 80.2 KB
/
views.py
File metadata and controls
2002 lines (1689 loc) · 80.2 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 ast import Pass
import io
from optparse import Option
import time
import pandas as pd
import pyqrcode
import png
import tempfile
# from captcha.image import ImageCaptcha
from PIL import Image
from itertools import product
import os
from tokenize import String
from werkzeug.utils import secure_filename
import random
import math
import secrets
import string
import docx
from io import BytesIO
from docx2pdf import convert
import json
from sqlite3 import IntegrityError
from sqlalchemy.exc import IntegrityError
from flask import Flask, make_response,render_template,abort,session,redirect,send_file, request,flash,jsonify,Response,url_for
from jinja2 import Template
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import inspect,text,func
import uuid
from flask_mail import Mail
import cv2
from sqlalchemy.orm import load_only
from PIL import ImageEnhance,Image,ImageFilter
import base64
from docxtpl import DocxTemplate
import re
import xlwt
import requests
import xml.etree.ElementTree as ET
import xmltodict
from __init__ import app,db
from payments.ccavutil import encrypt,decrypt
from payments.ccavResponseHandler import res
from string import Template
# google login
import pathlib
from google.oauth2 import id_token
from google_auth_oauthlib.flow import Flow
from pip._vendor import cachecontrol
import google.auth.transport.requests
from models import *
import json
with open("config.json","r") as c:
params=json.load(c)['params']
with open("config.json","r") as d:
directories=json.load(d)['directories']
with open("config.json","r") as e:
ecxp=json.load(e)['EcomExpress']
with open("config.json","r") as p:
paygate=json.load(p)['paymentGateway']
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
GOOGLE_CLIENT_ID = "423572210681-ig2sv7oikb9e03b4flq4k553d5ftj9bk.apps.googleusercontent.com"
client_secrets_file = os.path.join(pathlib.Path(__file__).parent, "client_secret.json")
flow = Flow.from_client_secrets_file(
client_secrets_file=client_secrets_file,
scopes=["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email", "openid"],
redirect_uri="http://127.0.0.1:2000/callback"
)
def login_is_required(function):
def wrapper(*args, **kwargs):
if "google_id" not in session:
return abort(401) # Authorization required
else:
return function()
return wrapper
@app.route("/login/auth/google")
def login_google():
authorization_url, state = flow.authorization_url()
session["state"] = state
return redirect(authorization_url)
@app.route("/callback")
def callback():
# try:
flow.fetch_token(authorization_response=request.url)
if not session["state"] == request.args["state"]:
abort(500) # State does not match!
credentials = flow.credentials
# print(credentials)
# return credentials
request_session = requests.session()
cached_session = cachecontrol.CacheControl(request_session)
token_request = google.auth.transport.requests.Request(session=cached_session)
id_info = id_token.verify_oauth2_token(
id_token=credentials._id_token,
request=token_request,
audience=GOOGLE_CLIENT_ID
)
sub= id_info.get("sub")
name = id_info.get("name")
email = id_info.get("email")
mobile = id_info.get("mobile")
loggedFrom="google"
pswd=sub
# return id_info
data=Customers.query.filter_by(email=email).first()
if data is None:
publicId = uuid.uuid4().hex
cred=Customers(publicId=publicId,name=name,mobile=mobile,email=email,pswd=pswd,loggedFrom=loggedFrom,date=datetime.now())
try:
db.session.add(cred)
db.session.commit()
mainstr="login"
session["user"]=publicId
return redirect("/google/auth")
except:
flash("Some error occured please reload page")
session["user"]=data.publicId
# flash("Account already exists")
return redirect("/login/auth")
# except:
# return redirect("/login/auth")
# ***************************************Login and logout******************************************
# login and signups
@app.route("/<string:mainstr>/auth",methods=['GET','POST'])
def login(mainstr):
if 'user' in session:
mobile=request.form.get("mobile")
pswd=request.form.get("pswd")
if mainstr=="google":
user=Customers.query.filter_by(publicId=session['user']).first()
if "redirect_to" in session:
return redirect(session["redirect_to"])
return redirect("/")
elif mainstr=="whatsapp":
mobile=request.form.get("mobile")
pswd=request.form.get("pswd")
name=request.form.get("name")
user=Customers.query.filter_by(mobile=mobile).first()
loggedFrom="whatsapp"
if user:
session['user']=user.publicId
return {
"code":200,
"msg":"You logged in as %s" %name,
"redirect_url":"/login/auth"
}
else:
publicId = uuid.uuid4().hex
cred=Customers(publicId=publicId,name=name,mobile=mobile,pswd=pswd,loggedFrom=loggedFrom,date=datetime.now())
try:
db.session.add(cred)
db.session.commit()
session['user']=publicId
return {
"code":200,
"msg":"You logged in as %s" %name,
"redirect_url":"/login/auth"
}
except:
flash("Some error occured please reload page")
# user=Customers.query.filter_by(publicId=session['user']).first()
if "redirect_to" in session:
return redirect(session["redirect_to"])
return redirect("/")
else:
mobile=request.form.get("mobile")
pswd=request.form.get("pswd")
loggedFrom="self"
if request.method=="POST" and mainstr=="signup":
name=request.form.get("username")
email=request.form.get("email")
user=Customers.query.filter_by(mobile=mobile).first()
if user:
flash("Account already exists!")
else:
publicId = uuid.uuid4().hex
cred=Customers(publicId=publicId,name=name,mobile=mobile,email=email,pswd=pswd,loggedFrom=loggedFrom,date=datetime.now())
try:
db.session.add(cred)
db.session.commit()
mainstr="login"
session['user']=publicId
if "redirect_to" in session:
return redirect(session["redirect_to"])
else:
return redirect("/")
except:
flash("Some error occured please reload page")
elif request.method=="POST" and mainstr=="login":
user=Customers.query.filter((Customers.mobile == mobile) | (Customers.email == mobile)).first()
if user and pswd==user.pswd:
session['user']=user.publicId
if "redirect_to" in session:
return redirect(session["redirect_to"])
else:
return redirect("/")
elif user and pswd!=user.pswd:
flash("You have entered wrong password!")
else:
flash("Account doesn't exists!")
return render_template("login2.html", page=mainstr)
@app.route("/logout")
def logout():
session.clear()
return redirect("/")
# *********************************CUSTOMERS***************************************************
#home page
@app.route("/",methods=['GET'])
def home():
session.permanent = True
carousel=Customize.query.all()
# for key in directories:
# print(directories.get(key))
carousel=Templates.query.filter_by(carousel=True).all()
if 'admin' in session:
return render_template("admin_home.html")
orders=Orders.query.order_by(Orders.id.desc()).all()
return render_template("index.html",params=params,orders=orders,carousel=carousel)
#get template categories (api)
@app.route("/get/templates/categories")
def getCategory():
temp2=[]
cat=[]
t=Templates.query.order_by(Templates.price).all()
for k in t:
cat.append(k.category)
for key in set(cat):
temp=Templates.query.filter_by(category=key).first()
temp2.append(temp.toDict())
return jsonify(temp2)
# get started
@app.route('/about')
def about():
return render_template('about.html')
# get started
@app.route('/getStarted')
def getStarted():
return render_template('getStarted.html')
#choose cutomize by and displays tshirts
@app.route("/customize/<string:types>=ty/<string:category>=<string:seperator>",methods=['GET'])
def customize(types,category,seperator):
load=None
if types=="default":
load="templates"
elif types=="cust":
load="editor"
tshirts=Tshirts.query.filter_by(type="Demo",status="Active").all()
return render_template("customize_type.html",seperator=seperator,types=types,tshirts=tshirts,load=load,category=category)
# ************************************************************************************
#1) customize by memerkida
# shows templates
@app.route("/templates/<string:tshirtId>=t//<string:category>=cat",methods=['GET'])
def templates(tshirtId,category):
# print(category)
if category=="all" or category=="All":
templates=Templates.query.order_by(Templates.id.desc()).all()
else:
templates=Templates.query.order_by(Templates.id.desc()).filter_by(category=category).all()
return render_template("templates.html",params=params,tshirtId=tshirtId,templates=templates)
# ************************************************************************************
# 2) customize by yourself
# opens editor
@app.route("/editor/<string:tshirtId>=t/<string:category>=cat",methods=['GET'])
def edits(tshirtId,category):
tshirt=Tshirts.query.filter_by(publicId=tshirtId).first()
if 'user' in session:
return render_template("edit123.html",tshirt=tshirt)
else:
flash("You need to Login First..")
session["redirect_to"]="/editor/%s=t/%s=cat" %(tshirtId,category)
return redirect("/login/auth")
# saves edited img (api)
@app.route("/saveImg/<string:sortStr>=type",methods=['GET','POST'])
def saveImg(sortStr):
if "user" in session:
if request.method=="POST":
sorter=sortStr
data=Customers.query.filter_by(publicId=session['user']).first()
tshirtImg= request.files.get('tshirtImg')
printImg= request.files.get('printImg')
tshirtId= request.form.get('tshirtId')
uploads=Edituploads.query.filter_by(custId=session['user']).all()
if printImg and tshirtImg:
app.config['UPLOAD_FOLDER']= os.path.abspath("../"+params['editImagesUpload'])
printImg = Image.open(printImg.stream)
printImgName="cust"+str(data.publicId)+"No"+str(len(uploads))+"Images.png"
printImg.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(printImgName) ))
printImg=secure_filename(printImgName)
app.config['UPLOAD_FOLDER']= os.path.abspath("../"+params['editTshirtUpload'])
tshirtImg= Image.open(tshirtImg.stream)
tshirtImgName="cust"+str(data.publicId)+"No"+str(len(uploads))+"Tshirt.png"
tshirtImg.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(tshirtImgName) ))
tshirtImg=secure_filename(tshirtImgName)
publicId = uuid.uuid4().hex
# print( publicId)
try:
cred=Edituploads(publicId=publicId,custId=data.publicId,sorter=sorter,tshirtId=tshirtId,tshirtImg=secure_filename(tshirtImg), printImg=secure_filename(printImg),details="ok",date=datetime.now())
db.session.add(cred)
db.session.commit()
flash("%s has been saved successfully..." %sorter)
imgUp=Edituploads.query.filter_by(custId=session["user"]).order_by(Edituploads.id.desc()).first()
id=imgUp.publicId
return {
"status":"ok",
"uploaded":"all",
"tshirtId":tshirtId,
"printId":id
}
except:
flash("%s has not been saved..." %sorter)
return {
"status":"failed",
"uploaded":"nothing" ,
"tshirtId":0,
"printId":0
}
# *************************************ORDER PROCEDURE**********************************************
# order
@app.route("/<string:tshirtId>=t/<string:printId>=p/<string:type>/<string:source>/order",methods=['GET','POST'])
def orderNow(tshirtId,printId,type,source):
if 'user' in session:
data=Customers.query.filter_by(publicId=session['user']).first()
if request.method=="POST":
tshirtImg=0
printImg=0
theme=0
paymentId=0
quantity=request.form.get("quantity")
colour= request.form.get("colour")
theme= request.form.get("theme")
size=request.form.get("size")
price=request.form.get("price")
details=request.form.get("details")
if source=="noCart":
if type=="default":
tshirt=Tshirts.query.filter_by(publicId=tshirtId,type="Demo",status="Active").first()
if tshirt:
tshirtImg=tshirt.img
template=Templates.query.filter_by(publicId=printId).first()
if theme=="dark":
printImg=template.darkTemplate
elif theme=="light":
printImg=template.lightTemplate
price=int(quantity)* int( template.price)
# print(price)
elif type =="customize":
uploads=Edituploads.query.filter_by(custId=session['user'],publicId=printId).first()
if uploads:
tshirtImg=uploads.tshirtImg
printImg=uploads.printImg
elif source=="cart":
cartId=tshirtId
# print(cartId)
cart=Carts.query.filter_by(custId=data.publicId,publicId=cartId).first()
if cart is None:
return render_template('page_not_found.html'), 404
tshirtId=cart.tshirtId
if type=="default":
tshirt=Tshirts.query.filter_by(publicId=cart.tshirtId,type="Demo",status="Active").first()
if tshirt:
tshirtImg=tshirt.img
template=Templates.query.filter_by(publicId=printId).first()
if cart.theme=="dark":
printImg=template.darkTemplate
elif cart.theme=="light":
printImg=template.lightTemplate
elif type=="customize":
uploads=Edituploads.query.filter_by(custId=data.publicId,publicId=cart.printId).first()
if uploads:
tshirtImg=uploads.tshirtImg
printImg=uploads.printImg
size=cart.size
price=cart.price
colour=cart.colour
quantity=cart.quantity
price=cart.price
type=cart.type
theme=cart.theme
publicId = uuid.uuid4()
status="Pls Complete Order"
order=Orders.query.filter_by(custId=data.publicId,status=status,quantity=quantity,colour=colour,size=size,tshirtImg=tshirtImg,type=type,theme=theme,printImg=printImg,price=price,delivered=False).first()
if order:
print(order)
flash("This Order has been already placed..")
orderId=order.publicId
source="cart"
# return redirect("/%s/payments" %(orderId))
else:
cred=Orders(publicId=publicId,custId=data.publicId,status=status,quantity=quantity,colour=colour,size=size,tshirtImg=tshirtImg,type=type,theme=theme,printImg=printImg,details=details,price=price,delivered=False,date=datetime.now())
# try:
db.session.add(cred)
flash("Pls confirm your order by providing details..")
orderId=publicId
db.session.commit()
try:
addtoCart("remove",data.publicId,cartId)
except:
pass
return redirect("/%s/address" %(orderId))
# except IntegrityError:
# flash("Some error occured. Please reload page and try again..")
return redirect("/%s=t/%s=p/%s/%s/order" %(tshirtId,printId,type,source))
if source=="noCart":
theme=""
cartId=0
quantity=1
dark_post_name=None
if type=="default":
template=Templates.query.filter_by(publicId=printId).first()
post=template.lightTemplate
post_name=template.lightTshirt
dark_post_name=template.darkTshirt
price=template.price
tshirt=Tshirts.query.filter_by(publicId=tshirtId).first()
# return render_template("address.html",post_name=data0.que,tshirtId=tshirtId,printId=printId,postId=postId,type="default",source="noCart")
else:
uploads=Edituploads.query.filter_by(custId=session['user'],publicId=printId).first()
tshirt=Tshirts.query.filter_by(publicId=tshirtId).first()
if uploads:
tshirtId= uploads.tshirtId
printId=printId
post_name=uploads.tshirtImg
price=tshirt.price
if tshirt:
colour=re.sub(' +', '', tshirt.colour).capitalize().split(",")
size=re.sub(' +', '', tshirt.size).upper().split(",")
description=tshirt.description
title=tshirt.name
sleeve=tshirt.sleeve
neck=tshirt.neck
# print("colour :",colour,"size:",size,"price:",price)
else:
# try:
# cart=Carts.query.filter_by(custId=data.publicId ,tshirtId=tshirtId ,printId=printId,type=type).first()
# except:
cart=Carts.query.filter_by(custId=data.publicId ,publicId=tshirtId).first()
if cart is None:
return redirect("/error")
tshirt=Tshirts.query.filter_by(publicId=cart.tshirtId,type="Demo",status="Active").first()
dark_post_name=None
if type=="default":
if tshirt:
tshirtImg=tshirt.img
template=Templates.query.filter_by(publicId=printId).first()
if cart.theme=="dark":
printImg=template.darkTemplate
post=template.darkTemplate
post_name=template.darkTshirt
elif cart.theme=="light":
printImg=template.lightTemplate
post=template.lightTemplate
post_name=template.lightTshirt
price=template.price
elif type=="customize":
uploads=Edituploads.query.filter_by(custId=data.publicId,publicId=cart.printId).first()
if uploads:
tshirtImg=uploads.tshirtImg
post_name=uploads.tshirtImg
printImg=uploads.printImg
price=cart.price
size=cart.size
colour=cart.colour
title=cart.details
description=tshirt.description
cartId=cart.publicId
quantity=cart.quantity
sleeve=tshirt.sleeve
neck=tshirt.neck
theme=cart.theme
return render_template("orderNow.html",dark_post_name=dark_post_name,theme=theme,neck=neck,sleeve=sleeve,
cartId=cartId,colour=colour,size=size, quantity=quantity, price=price,tshirtId=tshirtId,
post_name=post_name,printId=printId,type=type,source=source,title=title,description=description)
else:
session["redirect_to"]="/%s=t/%s=p/default/noCart/order" %(tshirtId,printId)
return redirect("/login/auth")
# similar post (api)
@app.route("/get/<string:id>/<string:types>/similar",methods=['GET'])
def similar_post(id,types):
if 'user' in session:
similar_templates=[]
data=Customers.query.filter_by(publicId=session['user']).first()
try:
if types=="default":
# if source=="cart":
# cart=Carts.query.filter_by(publicId=id).first()
# id=cart.printId
template=Templates.query.filter_by(publicId=id).first()
category=template.category
keywords=template.keywords.capitalize().split(" ")
else:
category="Marathi"
keywords=["couple","anime","avenger","game","marathi","fashion","chai","sigma"]
similar= Templates.query.filter_by(category=category).all()
for key in keywords:
similar+= Templates.query.filter(Templates.keywords.contains(key)).all()
for key in set(similar):
similar_templates.append(key.toDict())
except:
return {"code":404,
"total":len(similar_templates),
"response":similar_templates
}
return{
"code":200,
"total":len(similar_templates),
"response":similar_templates
}
return{
"code":404,
"total":0,
"response":[]
}
# modifies address
@app.route("/<string:orderId>/address",methods=['GET','POST'])
def address(orderId):
if 'user' in session:
data=Customers.query.filter_by(publicId=session['user']).first()
if request.method=="POST" and data:
name=request.form.get("name")
mobile=request.form.get("mobile")
email=request.form.get("email")
address1=request.form.get("address1")
address2=request.form.get("address2")
city=request.form.get("city")
state=request.form.get("state")
zip=request.form.get("zip")
checkMob=Customers.query.filter_by(mobile=mobile).first()
# if checkMob:
# flash("Mobile Number already exists pls try with another number")
# return redirect("/%s/address" %orderId)
try:
data.username=name
data.mobile=mobile
data.address1=address1
data.city=city
data.state=state
data.zip=zip
if address2:
data.address2=address2
if email:
data.email=email
db.session.commit()
except:
flash("Mobile Number already exists pls try with another number")
return redirect("/%s/address" %orderId)
return redirect("/%s/checkout" %(orderId))
# flash("Pls confirm your order by providing details..")
indian_states = [ "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chhattisgarh", "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jharkhand", "Karnataka", "Kerala", "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Punjab", "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal", "Andaman and Nicobar Islands", "Chandigarh", "Dadra and Nagar Haveli and Daman and Diu", "Lakshadweep", "Delhi", "Puducherry", "Jammu and Kashmir", "Ladakh"]
return render_template("address.html",orderId=orderId,indian_states=indian_states)
else:
session["redirect_to"]="%s/address" %orderId
return redirect("/login/auth")
# checkout
@app.route("/<string:orderId>/checkout",methods=['GET','POST'])
def checkout(orderId):
if 'user' in session:
data=Customers.query.filter_by(publicId=session['user']).first()
order=Orders.query.filter_by(custId=data.publicId,publicId=orderId).first()
print(order.printImg)
if order.type=="default":
template=Templates.query.filter_by(lightTemplate=order.printImg).first()
check={}
if order and data:
check["name"]=data.name
check["mobile"]=data.mobile
check["email"]=data.email
check["address1"]=data.address1
check["address2"]=data.address2
check["city"]=data.city
check["state"]=data.state
check["zip"]=data.zip
check["printImg"]=template.lightTemplate if order.type=="default" else order.printImg
check["tshirtImg"]=template.lightTshirt if order.type=="default" else order.tshirtImg
check["order"]=order
# check["payMethods"]="cod"
check["subtotal"]=order.price
check["shipping"]=0 # 25 if str(check["state"]).lower()=="maharashtra" else 40
check["cod"]=0 #25 if check["payMethods"]=="cod" else 0
check["total"]=int(check["shipping"])+int(check["subtotal"])+ int(check["cod"])
if request.method=="POST" and data and order:
name=check["name"]
mobile=check["mobile"]
address1=check["address1"]
address2=check["address2"]
city=check["city"]
state=check["state"]
zip=check["zip"]
subtotal=check["subtotal"]
charges=int(check["shipping"])+ int(check["cod"])
total=int(check["shipping"])+int(check["subtotal"])+ int(check["cod"])
payMethods=request.form.get("payMethods")
orderId=order.publicId
custId=data.publicId
publicId = uuid.uuid4()
status="pending"
payment=Payments.query.filter_by(orderId=orderId).first()
if payment is None:
try:
cred=Payments(publicId=publicId,custId=custId,orderId=orderId,payMethods=payMethods,status=status,subtotal=subtotal,charges=charges,total=total,name=name,mobile=mobile,address1=address1,address2=address2,city=city,state=state,zip=zip,date=datetime.now())
db.session.add(cred)
order=Orders.query.filter_by(publicId=orderId).first()
order.paymentId=publicId
order.status="Order Received and will be Dispatched soon"
db.session.commit()
if payMethods=="online":
return redirect("/ccavRequestHandler/%s" %(orderId))
flash("Your order is successfully placed..")
title="You recieved Order on "+params['mainTitle']
msg= "Your received new order kindly check it.."
to="22devendrabijwe@gmail.com", "vitthaltangade6@gmail.com"
try:
sendMail(title,msg,to)
except:
pass
return redirect("/order/%s/success"%(orderId))
except:
flash("order already placed")
elif payment.payMethods=="online" and payment.transactionId is None :
if payMethods=="online":
return redirect("/ccavRequestHandler/%s" %(orderId))
else:
flash("Do not change payment methods")
else:
flash("This order is already in Queue")
return render_template("checkout.html",check=check)
else:
session["redirect_to"]="%s/checkout" %orderId
return redirect("/login/auth")
@app.route('/order/<string:orderId>/success',methods=['GET','POST'])
def order_success(orderId):
if 'user' in session:
user=Customers.query.filter_by(publicId=session['user']).first()
if request.method=="POST":
accessCode = paygate['access_code']
workingKey = paygate['working_key']
plainText = res(request.form['encResp'],workingKey)
# order_id=plainText["order_id"]
# name=plainText["billing_ name"]
# tracking_id=plainText["tracking_id"]
# bank_ref_no=plainText["bank_ref_no"]
# order_status=plainText["order_status"]
# failure_message=plainText["failure_message"]
# payment_mode=plainText["payment_mode"]
# order_id=plainText["order_id"]
# amount=plainText["amount"]
# currency=plainText["currency"]
# custId=session["user"]
# publicId = uuid.uuid4().hex
# trans=Transaction.query.filter_by(custId=session["user"],orderId=order_id).first()
# if trans is None or (trans.order_status).lower() is not "success":
# cred=Transaction(publicId=publicId,custId=custId,orderId=order_id,name=name,tracking_id=tracking_id,bank_ref_no=bank_ref_no,amount=amount,order_status=order_status,currency=currency,payment_mode=payment_mode,failure_message=failure_message,date=datetime.now())
# db.session.add(cred)
# db.session.commit()
return plainText
if user:
ord=Orders.query.filter_by(custId=user.publicId,publicId=orderId).first()
if ord:
pay=Payments.query.filter_by(orderId=ord.publicId).first()
if user and ord and pay:
if pay.payMethods=="online":
payMethods="You already paid Online."
else:
payMethods="Cash on Delivery"
data={
"name" :user.name,
"orderId":ord.publicId,
"address":pay.address1+", "+pay.address2+ ", "+pay.city+ ", "+pay.state+ ", "+str(pay.zip)+".",
"payMethods":payMethods
}
return render_template("order_success.html" ,ordData=data)
return redirect("/error")
# get address of customer (api)
@app.route('/order/get/address',methods=['GET'])
def getAddress():
if 'user' in session:
user=Customers.query.filter_by(publicId=session['user']).first()
if user:
return {
"code":200,
"name":user.name,
"address1":user.address1,
"address2":user.address2,
"city":user.city,
"state":user.state,
"zip":user.zip,
}
return{
"code":400
}
# track item (api)
@app.route("/get/tracking/<string:orderId>")
def tracking(orderId):
Arr = {"code":400}
if "user" in session:
order=Orders.query.filter_by(custId=session["user"],publicId=orderId).first()
if order:
url="https://plapi.ecomexpress.in/track_me/api/mawbd/?username=%s&password=%s&awb=%s" %(ecxp["username"],ecxp["password"],order.trackingId)
response = requests.get(url = url)
try:
xml_data = response.content
root = ET.fromstring(xml_data)
Arr["code"]=200
for key in root[0]:
if key.findall("[@name='expected_date']"):
Arr["expected_date"]=key.text
if key.findall("[@name='status']"):
Arr["status"]=key.text
if key.findall("[@name='awb_number']"):
Arr["awb_number"]=key.text
if key.findall("[@name='scans']"):
Arr2=[]
for key2 in key:
for key3 in key2:
if key3.findall("[@name='updated_on']"):
updated_on=key3.text
if key3.findall("[@name='status']"):
status=key3.text
if key3.findall("[@name='reason_code']"):
reason_code=key3.text
if key3.findall("[@name='updated_on']"):
updated_on=key3.text
if key3.findall("[@name='scan_status']"):
scan_status=key3.text
if key3.findall("[@name='location']"):
location=key3.text
if key3.findall("[@name='location_city']"):
location_city=key3.text
if key3.findall("[@name='city_name']"):
city_name=key3.text
if key3.findall("[@name='location_type']"):
location_type=key3.text
if key3.findall("[@name='Employee']"):
Employee=key3.text
if key3.findall("[@name='reason_code_number']"):
reason_code_number=key3.text
Arr2.append({"updated_on":updated_on,"reason_code_number":reason_code_number,"Employee":Employee,"location_type":location_type,
"scan_status":scan_status,"city_name":city_name,"location":location,"status":status,
"location_city":location_city,"reason_code":reason_code})
Arr["tracking"]=Arr2
except :
pass
else:
Arr["code"]=400
return Arr
#*********************************************Payment Gateways****************************************************************************
@app.route('/ccavResponseHandler/', methods=['GET', 'POST'])
def ccavResponseHandler():
accessCode = paygate['access_code']
workingKey = paygate['working_key']
plainText = res(request.form['encResp'],workingKey)
order_id=plainText["order_id"]
name=plainText["billing_ name"]
tracking_id=plainText["tracking_id"]
bank_ref_no=plainText["bank_ref_no"]
order_status=plainText["order_status"]
failure_message=plainText["failure_message"]
payment_mode=plainText["payment_mode"]
order_id=plainText["order_id"]
amount=plainText["amount"]
currency=plainText["currency"]
return plainText
@app.route('/ccavRequestHandler/<string:orderId>', methods=['GET', 'POST'])
def handlePayReq(orderId):
accessCode = paygate['access_code']
workingKey = paygate['working_key']
if "user" in session:
data=Customers.query.filter_by(publicId=session["user"]).first()
ord=Orders.query.filter_by(custId=data.publicId,publicId=orderId).first()
pay=Payments.query.filter_by(orderId=ord.publicId).first()
if pay.transactionId :
flash("alraedy done payment")
return redirect("%s/checkout"%(orderId))
p_merchant_id = paygate['merchant_id']
p_order_id = ord.publicId
p_currency = paygate['currency']
p_amount = str(pay.total)
p_redirect_url = paygate['base_url']+"/order/%s/success"%(orderId)
p_cancel_url = paygate['cancel_url']+"/%s/checkout" %(orderId)
p_language = paygate['language']
p_billing_name = data.name
p_billing_address =data.address1+" "+data.address2
p_billing_city = data.city
p_billing_state = data.state
p_billing_zip = str(data.zip)
p_billing_country = "India"
p_billing_tel = str(data.mobile)
P_billing_email=data.email
p_merchant_param1 ="7666230646"
p_merchant_param2 = "22devendrabijwe@gmail.com"
p_merchant_param3 = "9370899965"
p_customer_identifier = data.publicId
print(p_merchant_id,accessCode,workingKey)
merchant_data='merchant_id='+p_merchant_id+'&'+'order_id='+p_order_id + '&' + "currency=" + p_currency + '&' + 'amount=' + p_amount+'&'+'redirect_url='+p_redirect_url+'&'+'cancel_url='+p_cancel_url+'&'+'language='+p_language+'&'+'billing_name='+p_billing_name+'&'+'billing_address='+p_billing_address+'&'+'billing_city='+p_billing_city+'&'+'billing_state='+p_billing_state+'&'+'billing_zip='+p_billing_zip+'&'+'billing_country='+p_billing_country+'&'+'billing_tel='+p_billing_tel+'&'+'billing_email'+P_billing_email+'&'+'merchant_param1='+p_merchant_param1+'&'+'merchant_param2='+p_merchant_param2+'&'+'merchant_param3='+p_merchant_param3+'&'+'customer_identifier='+p_customer_identifier+'&'
encryption = encrypt(merchant_data,workingKey)
html = '''\
<html>
<head>
<title>Sub-merchant checkout page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="nonseamless" method="post" name="redirect" action="https://test.ccavenue.com/transaction/transaction.do?command=initiateTransaction" >
<input type="hidden" id="encRequest" name="encRequest" value=$encReq>
<input type="hidden" name="access_code" id="access_code" value=$xscode>
<script language='javascript'>document.redirect.submit();</script>
</form>
</body>
</html>
'''
fin = Template(html).safe_substitute(encReq=encryption,xscode=accessCode)
return fin
# **********************************CARTS***********************************************
# shows cart
@app.route("/carts",methods=['GET','POST'])
def carts():
if 'user' in session:
Arr=[]
tshirtImg, printImg=None,None
data=Customers.query.filter_by(publicId=session['user']).first()
carts=Carts.query.order_by(Carts.date.desc()).filter_by(custId=data.publicId).all()
for key in carts: