-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
372 lines (259 loc) · 10.4 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
360
361
362
363
364
365
366
367
368
369
370
371
import os
import re
import io
import base64
import mysql.connector
import qrcode
from flask import Flask, flash, jsonify, redirect, render_template, request, send_file, session, url_for
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from io import BytesIO
from helpers import login_required
from datetime import datetime, timedelta
# export FLASK_APP='app.py'
# Configure application
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Configure MySQL
# Credentials removed for privacy reasons
# Database has been closed
def getconnection():
db = mysql.connector.connect(
host="",
user="",
password="",
database=""
)
return db
@app.route("/")
def index():
db = getconnection()
cur = db.cursor()
cur.execute("SELECT count(*) FROM business")
bcount = (cur.fetchall())[0][0]
cur.execute("SELECT count(*) FROM visitor")
vcount = (cur.fetchall())[0][0]
cur.close()
db.close()
return render_template("index.html", bcount=bcount, vcount=vcount)
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
db = getconnection()
cur = db.cursor()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Query database for password based on user's email
cur.execute("SELECT id, passwordhash FROM business WHERE email = %s", (request.form.get("email"), ))
rows = cur.fetchall()
if len(rows) != 1:
return render_template("login.html", error="Invalid email.")
user_id = rows[0][0]
p_hash = rows[0][1]
if not check_password_hash(p_hash, request.form.get("password")):
return render_template("login.html", error="Invalid password.")
# Remember which user has logged in
session["user_id"] = user_id
# Redirect user to home page
return redirect("/dashboard")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
cur.close()
db.close()
@app.route("/logout")
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/")
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
# Forget any user_id
session.clear()
db = getconnection()
cur = db.cursor()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
cur.execute("SELECT email FROM business")
emails = cur.fetchall()
for email in emails:
if request.form.get("email") == email[0]:
return render_template("register.html", error="Previously entered email is already registered.")
# Creating unique code from business name
name = request.form.get("name").strip()
code = re.sub('[^A-Za-z0-9]+', '', name)
i = 0
while True:
cur.execute("SELECT count(*) FROM business WHERE code = %s", (code, ))
repeat = cur.fetchall()
if repeat[0][0] > 0:
if i > 0:
code = code[:-1]
i += 1
code = code + str(i)
else:
break
time = datetime.now()
# Insert company name, email, and password hash into database
query = "INSERT INTO business (name, code, email, passwordhash, created_at) VALUES (%s, %s, %s, %s, %s)"
values = (name, code, request.form.get("email"), generate_password_hash(request.form.get("password")), time)
cur.execute(query, values)
# Remember that the new user has logged in
session["user_id"] = cur.lastrowid
# Redirect user to home page
return redirect("/qrcode")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("register.html")
cur.close()
db.close()
@app.route("/business/<code>", methods=["GET", "POST"])
def business(code):
"""Customer form"""
db = getconnection()
cur = db.cursor()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
cur.execute("SELECT id FROM business WHERE code = %s", (code, ))
business_id = cur.fetchall()
# determines if business id exists for the passed code
business_id = business_id[0][0]
time = datetime.now()
# Insert name, phone number, email, guests, and time into customers database
query = "INSERT INTO visitor (business_id, name, phone, email, guests, created_at) VALUES (%s, %s, %s, %s, %s, %s)"
values = (business_id, request.form.get("name"), request.form.get("phone"), request.form.get("email"), request.form.get("guests"), time)
cur.execute(query, values)
# Redirect user to home page
try:
if session["user_id"]:
return redirect("/dashboard")
except KeyError:
cur.execute("SELECT name FROM business WHERE code = %s", (code, ))
business_name = (cur.fetchall())[0][0]
return render_template("thankyou.html", name=business_name)
# User reached route via GET (as by clicking a link or via redirect)
else:
cur.execute("SELECT name FROM business WHERE code = %s", (code, ))
name = cur.fetchall()
try:
# passing through business name
name = name[0][0]
return render_template("business.html", name=name, code=code)
except IndexError:
return render_template("business.html")
cur.close()
db.close()
@app.route("/dashboard", methods=["GET"])
@login_required
def dashboard():
db = getconnection()
cur = db.cursor()
cur.execute("SELECT name, phone, email, guests, created_at FROM visitor WHERE business_id = %s AND created_at >= DATE_SUB(NOW(),INTERVAL 1 DAY) ORDER BY created_at DESC", (session["user_id"], ))
today = cur.fetchall()
cur.execute("SELECT name, phone, email, guests, created_at FROM visitor WHERE business_id = %s AND created_at >= DATE_SUB(NOW(),INTERVAL 1 WEEK) ORDER BY created_at DESC", (session["user_id"], ))
week = cur.fetchall()
cur.execute("SELECT name, phone, email, guests, created_at FROM visitor WHERE business_id = %s AND created_at >= DATE_SUB(NOW(),INTERVAL 1 MONTH) ORDER BY created_at DESC", (session["user_id"], ))
month = cur.fetchall()
cur.execute("SELECT name, phone, email, guests, created_at FROM visitor WHERE business_id = %s ORDER BY created_at DESC", (session["user_id"], ))
all_time = cur.fetchall()
cur.execute("SELECT name FROM business WHERE id = %s", (session["user_id"], ))
name = (cur.fetchall())[0][0]
cur.execute("SELECT code FROM business WHERE id = %s", (session["user_id"], ))
code = (cur.fetchall())[0][0]
return render_template("dashboard.html", today=today, week=week, month=month, all_time=all_time, name=name, code=code)
cur.close()
db.close()
# @app.route("/export", methods=["GET"])
# @login_required
# def export():
# db = getconnection()
# cur = db.cursor()
# cur.execute("SELECT name, phone, email, guests, created_at FROM visitor WHERE business_id = %s ORDER BY created_at DESC", (session["user_id"], ))
# rows = cur.fetchall()
# wb = Workbook('customers.xlsx')
# wb.add_worksheet('All Data')
# for item in rows:
# wb.write(item)
# wb.close()
# return send_file('path/to/workbook.xlsx')
# cur.close()
# db.close()
@app.route("/qrcode", methods=["GET"])
@login_required
def qr_code():
db = getconnection()
cur = db.cursor()
cur.execute("SELECT name FROM business WHERE id = %s", (session["user_id"], ))
name = (cur.fetchall())[0][0]
cur.execute("SELECT code FROM business WHERE id = %s", (session["user_id"], ))
code = (cur.fetchall())[0][0]
cur.close()
db.close()
# Generate QR Code
qrimg = qrcode.make('https://ronify.herokuapp.com/business/' + code)
buffered = BytesIO()
qrimg.save(buffered, format='png')
imgstr = base64.b64encode(buffered.getvalue()).decode()
return render_template("qrcode.html", name=name, code=code, imgstr=imgstr)
@app.route("/about", methods=["GET"])
def about():
db = getconnection()
cur = db.cursor()
try:
if session["user_id"]:
cur.execute("SELECT code FROM business WHERE id = %s", (session["user_id"], ))
code = (cur.fetchall())[0][0]
return render_template("about.html", code=code)
except KeyError:
return render_template("about.html")
cur.close()
db.close()
@app.route("/contact", methods=["GET"])
def contact():
db = getconnection()
cur = db.cursor()
try:
if session["user_id"]:
cur.execute("SELECT code FROM business WHERE id = %s", (session["user_id"], ))
code = (cur.fetchall())[0][0]
return render_template("contact.html", code=code)
except KeyError:
return render_template("contact.html")
cur.close()
db.close()
@app.route("/privacy", methods=["GET"])
def privacy():
db = getconnection()
cur = db.cursor()
try:
if session["user_id"]:
cur.execute("SELECT code FROM business WHERE id = %s", (session["user_id"], ))
code = (cur.fetchall())[0][0]
return render_template("privacy.html", code=code)
except KeyError:
return render_template("privacy.html")
cur.close()
db.close()
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404