-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
359 lines (340 loc) · 13.5 KB
/
app.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
from flask import Flask, render_template, request, redirect, session, url_for, flash
import json
from datetime import timedelta
import time
import pyrebase
import firebase_admin as firebase
from firebase_admin import firestore, storage
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os
from datetime import date
from pyzbar.pyzbar import decode, ZBarSymbol
import cv2
import numpy as np
import random
import string
#FOR FIRESTORE
# cred = firebase.credentials.Certificate("firebaseKey.json")
# keyFile = open('pyrebaseKey.json','r')
# keyJson = keyFile.read()
# key = json.loads(keyJson)
if os.name == 'nt':
cred = firebase.credentials.Certificate("firebaseKey.json")
keyFile = open('pyrebaseKey.json','r')
keyJson = keyFile.read()
key = json.loads(keyJson)
else:
cred = firebase.credentials.Certificate(json.loads(os.environ.get('FIREBASE')))
key = json.loads(os.environ.get('PYREBASE'))
firebase.initialize_app(cred,{'storageBucket':'selfcheckout-8b125.appspot.com'})
db = firestore.client() #For database
bucket = storage.bucket()
auth = pyrebase.initialize_app(key).auth() #For authentication
#FIRESTORE COMMANDS
# db.collection('collectionName').document('documentID').set(data(as a dictionary)) -- To create/edit document
# db.collection('collectionName').document('documentID').get() -- To get document
# db.collection('collectionName').where('LHS','relational operator','RHS').stream() -- To get documents based on condition, eg .where('name','==','Varun'). to get all documents just remove the .where
# db.collection('collectionName').order_by('name of field').limit('number of docs').stream() -- To limit the number of docs fetched or to order them. can also use along with .where
# db.collection('collectionName').document('documentID').get().to_dict() -- To get document as dictionary (used most often)
# db.collection('collectionName').document('documentID').delete() -- To delete document
#AUTH COMMANDS
# auth.create_user_with_email_and_password(email, password) -- Make a user
# auth.sign_in_with_email_and_password(email, password) -- Sign in a user, returns a session key that expires in 60 mins I think.
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
app.secret_key = "(SHITTU_CANNOT_CODE)-1"
def sendEmail(email, html, text):
senderAddress = "selfcheckoutsample@gmail.com"
senderPassword = "@Sample123"
server = 'smtp.gmail.com:587'
recieverAddress = email
message = MIMEMultipart("alternative", None, [MIMEText(text), MIMEText(html,'html')])
message['Subject'] = "Self-Checkout | Admin"
message['From'] = senderAddress
message['To'] = recieverAddress
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(senderAddress, senderPassword)
server.sendmail(senderAddress, recieverAddress, message.as_string())
print('Email Sent')
server.quit()
@app.route('/')
def home():
if 'token' in session:
# print(session['token'])
# email = session['email']
# billDetails = db.collection('bills').document(email).get().to_dict()
# print(billDetails)
return render_template('home.html')
else:
return redirect(url_for('login'))
@app.route('/login', methods=['GET','POST'])
def login():
if 'token' not in session:
message = ""
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
try:
userData = auth.sign_in_with_email_and_password(username,password)
userDetails = db.collection('users').document(username).get().to_dict()
print(userDetails)
session['name'] = userDetails['name']
session['email'] = userDetails['email']
session['phoneNumber'] = userDetails['phoneNumber']
session['age'] = userDetails['age']
session['address'] = userDetails['address']
session['token'] = userData['idToken']
print(dict(session))
return redirect('/')
except Exception as e:
error = ""
error = json.loads(e.args[1])['error']['message']
message = error.replace('_',' ')
return render_template('login.html',message=message)
else:
return redirect('/')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
phoneNumber = request.form['phoneNumber']
age = request.form['age']
address = request.form['address']
password = request.form['pwd1']
print(name,email,phoneNumber,age,address,password)
text = """
Dear %s,
Thank you for signing-up on self-checkout!
Your account has been activated!
Happy shopping!
Thanks & Regards,
Admin,
Self-Checkout
""" %name
html = """
<html>
<head>
</head>
<body>
<p>Dear %s,</p>
<p>Thank you for signing up on Self-Checkout!<br/>
Your account has been activated!<br/>
Happy Shopping!</p><br/>
<p>Thanks & Regards,<br/>
<p>Admin,<br/>
<p>Self-Checkout</p>
</body>
</html>
""" %name
sendEmail(email, html, text)
auth.create_user_with_email_and_password(email,password)
db.collection(u'users').document(email).set({
'name':name,
'email':email,
'phoneNumber':phoneNumber,
'age':age,
'address':address,
'billQuantity':0
})
userData = auth.sign_in_with_email_and_password(email,password)
session['name'] = name
session['email'] = email
session['phoneNumber'] = phoneNumber
session['age'] = age
session['address'] = address
session['token'] = userData['idToken']
return redirect(url_for('home'))
return render_template("register.html")
@app.route('/guestLogin', methods=['GET', 'POST'])
def guestLogin():
if request.method=="POST":
target = os.path.join(APP_ROOT, 'uploadFolder/')
if not os.path.isdir(target):
os.mkdir(target)
qrCode = request.files['file']
letters = string.ascii_lowercase
fileName=''.join(random.choice(letters) for i in range(10))
fileName=fileName+'.png'
destination = "/".join([target,fileName])
qrCode.save(destination)
img = cv2.imread('uploadFolder/temp1.png', cv2.IMREAD_GRAYSCALE)
codes = decode(img)
print('DECODED', codes[0][0].decode("utf-8"))
decoded = codes[0][0].decode("utf-8")
number=0
for i in decoded:
if i.isdigit():
number=i
return redirect(url_for('viewGuestBill', id=str(i)))
return render_template("guestLogin.html")
@app.route('/contact', methods=['GET','POST'])
def contact():
if request.method=="POST":
subject = request.form['subject']
text = """
Dear Customer,
Thank you for contacting us!
We whave recieved your message/query!
One of our teammates will get in tough with you shortly.
Thanks & Regards,
Admin,
Self-Checkout
"""
html = """
<html>
<head>
</head>
<body>
<p>Dear %s,</p>
<p>Thank you for contacting us!<br/>
We whave recieved your message/query!<br/>
One of our teammates will get in tough with you shortly.</p><br/>
<p>Thanks & Regards,<br/>
<p>Admin,<br/>
<p>Self-Checkout</p>
</body>
</html>
""" %name
sendEmail('svsumukh18@gmail.com', html, text)
email = 'svsumukh18@gmail.com'
text = """
You have got a query!
Sender : """ + email + """
Subject : %s
""" %subject
html = """
<html>
<head>
</head>
<body>
<p>You have recieved a query!<br/>
Sender : """ + str(email) + """ <br/>
Subject : %s</p><br/>
</body>
</html>
""" %subject
sendEmail('selfcheckoutsample@gmail.com', html, text)
return render_template("contact.html")
return render_template("contact.html")
@app.route('/viewCurrentBill', methods=['GET','POST'])
def viewCurrentBill():
if 'token' in session:
email = session['email']
userDetails = db.collection('users').document(email).get().to_dict()
currentBillNumber = userDetails['billQuantity']
if currentBillNumber==0:
message = "There are no bills yet"
return render_template('viewCurrentBill.html', date=message,items=[], quantity=[], prices=[], totalPrice=0, leng=0)
documentID = email+str(currentBillNumber)
billDetails = db.collection('bills').document(documentID).get().to_dict()
date=billDetails['date']
totalPrice=billDetails['totalPrice']
number = len(billDetails)
numberOfItems = number-2
items=['0' for i in range(numberOfItems//3)]
quantity=['0' for i in range(numberOfItems)]
prices=['0' for i in range(numberOfItems)]
for key,value in billDetails.items():
if 'item' in key:
for z in key:
if z.isdigit():
items[int(z)-1]=value
elif 'quantity' in key:
for z in key:
if z.isdigit():
quantity[int(z)-1]=value
elif 'price' in key:
for z in key:
if z.isdigit():
prices[int(z)-1]=value
return render_template('viewCurrentBill.html',date=date, items=items, quantity=quantity, prices=prices, totalPrice=totalPrice, leng=len(items))
return render_template("viewCurrentBill.html")
@app.route('/viewCurrentBillFromAllBills/<string:id>', methods=['GET','POST'])
def viewCurrentBillFromAllBills(id):
if 'token' in session:
email = session['email']
userDetails = db.collection('users').document(email).get().to_dict()
documentID = email+id
billDetails = db.collection('bills').document(documentID).get().to_dict()
date=billDetails['date']
totalPrice=billDetails['totalPrice']
number = len(billDetails)
numberOfItems = number-2
items=['0' for i in range(numberOfItems//3)]
quantity=['0' for i in range(numberOfItems)]
prices=['0' for i in range(numberOfItems)]
for key,value in billDetails.items():
if 'item' in key:
for z in key:
if z.isdigit():
items[int(z)-1]=value
elif 'quantity' in key:
for z in key:
if z.isdigit():
quantity[int(z)-1]=value
elif 'price' in key:
for z in key:
if z.isdigit():
prices[int(z)-1]=value
return render_template('viewCurrentBill.html',date=date, items=items, quantity=quantity, prices=prices, totalPrice=totalPrice, leng=len(items))
return render_template("viewCurrentBill.html")
@app.route('/viewGuestBill/<string:id>', methods=['GET','POST'])
def viewGuestBill(id):
documentID = 'guest'+id
billDetails = db.collection('guests').document(documentID).get().to_dict()
date=billDetails['date']
totalPrice=billDetails['totalPrice']
number = len(billDetails)
numberOfItems = number-2
items=['0' for i in range(numberOfItems//3)]
quantity=['0' for i in range(numberOfItems)]
prices=['0' for i in range(numberOfItems)]
for key,value in billDetails.items():
if 'item' in key:
for z in key:
if z.isdigit():
items[int(z)-1]=value
elif 'quantity' in key:
for z in key:
if z.isdigit():
quantity[int(z)-1]=value
elif 'price' in key:
for z in key:
if z.isdigit():
prices[int(z)-1]=value
return render_template('viewCurrentBill.html',date=date, items=items, quantity=quantity, prices=prices, totalPrice=totalPrice, leng=len(items))
@app.route('/viewAllBills', methods=['GET','POST'])
def viewAllBills():
if 'token' in session:
email = session['email']
userDetails = db.collection('users').document(email).get().to_dict()
currentBillNumber=userDetails['billQuantity']
documentIDs=[]
for i in range(currentBillNumber):
documentIDs.append(email+str(i+1))
dates=[]
for i in range(len(documentIDs)):
billDetails = db.collection('bills').document(documentIDs[i]).get().to_dict()
date=billDetails['date']
dates.append(date)
return render_template("viewAllBills.html", dates=dates, leng=len(dates))
return render_template("viewAllBills.html")
@app.route('/logout')
def logout():
if 'token' in session:
session.pop('token')
session.pop('name')
session.pop('email')
session.pop('phoneNumber')
session.pop('age')
session.pop('address')
return redirect(url_for('login'))
if __name__ == "__main__":
app.run(debug=True)