-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
377 lines (291 loc) · 13.3 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
372
373
374
375
376
377
from flask import Flask, render_template, flash, redirect, url_for, session, request, logging
from flask_wtf import Form, FlaskForm
from flask_mysqldb import MySQL
from wtforms import Form, StringField, TextAreaField, PasswordField, validators, DateField, IntegerField
from passlib.hash import sha256_crypt
from functools import wraps
import datetime
app = Flask(__name__)
# Config MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'myflaskapp'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
# init MYSQL
mysql = MySQL(app)
# Index
@app.route('/')
def index():
return render_template('home.html')
# About
@app.route('/about')
def about():
return render_template('about.html')
# Register Form Class
class RegisterForm(Form):
username = StringField('Username', [validators.Length(min=4, max=25)])
password = PasswordField('Password', [
validators.DataRequired(),
validators.EqualTo('confirm', message='Passwords do not match')
])
confirm = PasswordField('Confirm Password')
# User Register
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if request.method == 'POST' and form.validate():
username = form.username.data
password = sha256_crypt.encrypt(str(form.password.data))
privelege = request.form.get('priv')
# Create cursor
cur = mysql.connection.cursor()
# Get user by username
result = cur.execute("SELECT * FROM users WHERE username = %s", [username])
if result > 0:
flash('Username is already in use', 'danger')
return redirect(url_for('register'))
# Execute query
cur.execute("INSERT INTO users(username, password, type) VALUES(%s, %s, %s)", (username, password, privelege))
# Commit to DB
mysql.connection.commit()
# Close connection
cur.close()
flash('You are now registered and can log in', 'success')
return redirect(url_for('login'))
return render_template('register.html', form=form)
# User login
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Get Form Fields
username = request.form['username']
password_candidate = request.form['password']
# Create cursor
cur = mysql.connection.cursor()
# Get user by username
result = cur.execute("SELECT * FROM users WHERE username = %s", [username])
if result > 0:
# Get stored hash
data = cur.fetchone()
password = data['password']
# Compare Passwords
if sha256_crypt.verify(password_candidate, password):
# Passed
session['logged_in'] = True
session['username'] = username
session['userid1'] = data['id']
session['type'] = data['type']
flash('You are now logged in', 'success')
return redirect(url_for('about')) if data['type'] == 0 else redirect(url_for('companydashboard'))
else:
error = 'Invalid login'
return render_template('login.html', error=error)
# Close connection
cur.close()
else:
error = 'Username not found'
return render_template('login.html', error=error)
return render_template('login.html')
# Check if user logged in
def is_logged_in(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('Unauthorized, Please login', 'danger')
return redirect(url_for('login'))
return wrap
# Logout
@app.route('/logout')
@is_logged_in
def logout():
session.clear()
flash('You are now logged out', 'success')
return redirect(url_for('login'))
# Quote History
@app.route('/history', methods=['GET'])
@is_logged_in
def dashboard():
# Create cursors
cur = mysql.connection.cursor()
# Get quotes
result = cur.execute("select * from fuelquote where userid = %s" % str(session['userid1']))
articles = cur.fetchall()
if result > 0:
return render_template('dashboard.html', articles=articles)
else:
msg = 'No Articles Found'
return render_template('dashboard.html', msg=msg)
# Close connection
cur.close()
class ChangePriceForm(Form):
pricechange = IntegerField('Change Price: ', [validators.NumberRange(min=1, max=10000)])
# About
@app.route('/companydashboard', methods=['GET', 'POST'])
def companydashboard():
form = ChangePriceForm(request.form)
# Create cursors
cur = mysql.connection.cursor()
result = cur.execute("select * from currentPrice;")
article = cur.fetchone()
form.pricechange.data = article['price']
# Get quotes
result = cur.execute(" select users.fullname,fuelquote.gallonsrequested, fuelquote.amountdue, fuelquote.date from users right join fuelquote on users.id=fuelquote.userid where fullname is not null;")
articles = cur.fetchall()
if request.method == 'POST':
price = request.form['pricechange']
result = cur.execute("update currentPrice set price=%s where id=1" % (price))
# Commit to DB
mysql.connection.commit()
#Close connection
cur.close()
flash("Price Updated", "success")
return render_template('companydashboard.html', form=form, articles=articles)
return render_template('companydashboard.html', form=form, articles=articles)
@app.route('/deleteuser', methods=['GET'])
def deleteUser():
cur = mysql.connection.cursor()
cur.execute("delete from users where username='hiepLy'")
mysql.connection.commit()
cur.close()
return redirect(url_for('register'))
@app.route('/deletehistory', methods=['GET'])
def deleteHistory():
cur = mysql.connection.cursor()
cur.execute("delete from fuelquote where gallonsrequested=1236")
mysql.connection.commit()
cur.close()
return redirect(url_for('quotes'))
class FuelForm(Form):
gallons_requested = IntegerField('Gallons Requested: ', [validators.NumberRange(min=1, max=10000), validators.Required()])
dt = DateField('Delivery Date',[validators.Required()], format="%m/%d/%Y")
# Fuel quotes
@app.route('/quotes', methods=['GET', 'POST', 'PUT'])
@is_logged_in
def quotes():
form = FuelForm(request.form)
# Create cursor
cur = mysql.connection.cursor()
# Get article by id
result = cur.execute("SELECT * FROM users WHERE id = %s" % str(session['userid1']))
article = cur.fetchone()
cur.close()
PricePerGallon=0
Transportation=0
clientratehistory=0
SeasonFluctuation=0
profitMargin=0
FuelPrice=0
gallonsrequested=0
ppgalon =0
GallonsRequestedFactor=0
SuggestedPrice=0
if request.method == 'POST':
gallonsrequested = request.form['gallons_requested']
if not gallonsrequested.isdigit():
flash('Gallons Requested needs to be a numeric value', 'danger')
return render_template('fuelquoteform.html',SuggestedPrice=SuggestedPrice, form=form,Transportation=Transportation, article=article, PricePerGallon=PricePerGallon, FuelPrice=FuelPrice, profitMargin=profitMargin, SeasonFluctuation=SeasonFluctuation, clientratehistory=clientratehistory, gallonsrequested=gallonsrequested, ppgalon=ppgalon, GallonsRequestedFactor=GallonsRequestedFactor)
dt = request.form['dt']
date = datetime.datetime.strptime(dt, '%m/%d/%Y').strftime('%Y/%m/%d')
FuelPrice, PricePerGallon, Transportation, clientratehistory, SeasonFluctuation, profitMargin, GallonsRequestedFactor,SuggestedPrice = pricingModule(gallonsrequested, dt)
ppgalon = float(gallonsrequested) * float(PricePerGallon)
if request.form['action'] == 'SubmitQuote':
# Create Cursor
cur = mysql.connection.cursor()
cur.execute ("insert into fuelquote(userid, gallonsrequested, suggestedprice, amountdue, date) values(%s, %s, %s, %s, %s);",(str(session['userid1']), gallonsrequested, SuggestedPrice, FuelPrice, date))
# Commit to DB
mysql.connection.commit()
flash ("Quote Saved", 'success')
#Close connection
cur.close()
return render_template('fuelquoteform.html',SuggestedPrice=SuggestedPrice, form=form,Transportation=Transportation, article=article, PricePerGallon=PricePerGallon, FuelPrice=FuelPrice, profitMargin=profitMargin, SeasonFluctuation=SeasonFluctuation, clientratehistory=clientratehistory, gallonsrequested=gallonsrequested, ppgalon=ppgalon, GallonsRequestedFactor=GallonsRequestedFactor)
return render_template('fuelquoteform.html',SuggestedPrice=SuggestedPrice, form=form,Transportation=Transportation, article=article, PricePerGallon=PricePerGallon, FuelPrice=FuelPrice, profitMargin=profitMargin, SeasonFluctuation=SeasonFluctuation, clientratehistory=clientratehistory, gallonsrequested=gallonsrequested, ppgalon=ppgalon, GallonsRequestedFactor=GallonsRequestedFactor)
def pricingModule(gallonsrequested, date):
FuelPrice = 0
Transportation = 0.0
clientratehistory = 0
SeasonFluctuation = 0
PricePerGallon = 0
# Create cursor
cur = mysql.connection.cursor()
result = cur.execute("SELECT * FROM users where id=%s" % str(session['userid1']))
article = cur.fetchone()
Transportation = 0.02 if article['state'] == 'TX' else 0.04
result = cur.execute("SELECT * FROM currentPrice;")
article = cur.fetchone()
PricePerGallon = article['price']
month = date[0:2:]
SeasonFluctuation = 0.03 if month == '09' or month == '10' or month == '11' or month == '12' or month == '01' or month == '02' else 0.04
# Get article by id
result = cur.execute("SELECT * FROM fuelquote WHERE userid = %s" % str(session['userid1']))
clientratehistory = 0.01 if result >= 1 else 0.0
cur.close()
profitMargin = 0.10
GallonsRequestedFactor = 0.02 if gallonsrequested > 1000 else 0.03
SuggestedPrice = PricePerGallon + (Transportation - clientratehistory + GallonsRequestedFactor + profitMargin + SeasonFluctuation) * PricePerGallon
FuelPrice = float(gallonsrequested) * float(SuggestedPrice)
return FuelPrice, PricePerGallon, Transportation, clientratehistory, SeasonFluctuation, profitMargin, GallonsRequestedFactor, SuggestedPrice
# Article Form Class
class ProfileManager(Form):
fullname = StringField('Full Name', [validators.Required(), validators.Length(min=1, max=50)])
address1 = StringField('Address 1', [validators.Required(), validators.Length(min=1, max=100)])
address2 = StringField('Address 2', [validators.Length(min=0, max=100)])
city = StringField('City', [validators.Required(), validators.Length(min=1, max=100)])
zipcode = StringField('Zip Code', [validators.Required(), validators.Length(min=5, max=9)])
def LengthError(string, minimum, maximum):
return len(string) < minimum or len(string) > maximum
# Edit Profile
@app.route('/profile', methods=['GET', 'POST'])
@is_logged_in
def profileManager():
# Create cursor
cur = mysql.connection.cursor()
# Get article by id
result = cur.execute("SELECT * FROM users WHERE id = %s" % str(session['userid1']))
article = cur.fetchone()
cur.close()
# Get form
form = ProfileManager(request.form)
# Populate article form fields
form.fullname.data = article['fullname']
form.address1.data = article['address1']
form.address2.data = article['address2']
form.city.data = article['city']
form.zipcode.data = article['zipcode']
session['state1'] = article['state']
# Validate profile form and update
if request.method == 'POST':
fname = request.form['fullname']
if LengthError(fname, 1, 50):
flash('Full Name needs to be between 1 and 50 characters', 'danger')
return render_template('profilemanager.html', form=form, article=article)
add1 = request.form['address1']
if LengthError(add1, 1, 100):
flash('Address 1 needs to be between 1 and 100 characters', 'danger')
return render_template('profilemanager.html', form=form, article=article)
add2 = request.form['address2']
cty = request.form['city']
if LengthError(cty, 1, 100):
flash('City needs to be between 1 and 100 characters', 'danger')
return render_template('profilemanager.html', form=form, article=article)
st = request.form.get('state')
session['state1'] = st
zp = request.form['zipcode']
if LengthError(zp, 5, 9):
flash('Zip Code needs to be between 5 and 9 characters', 'danger')
return render_template('profilemanager.html', form=form, article=article)
# Create Cursor
cur = mysql.connection.cursor()
cur.execute ("UPDATE users SET fullname=%s, address1=%s, address2=%s, city=%s, state=%s, zipcode=%s WHERE id=%s",(fname, add1, add2,cty, st,zp, str(session['userid1'])))
# Commit to DB
mysql.connection.commit()
#Close connection
cur.close()
flash('User Updated', 'success')
return redirect(url_for('profileManager'))
return render_template('profilemanager.html', form=form, article=article)
if __name__ == '__main__':
app.secret_key='secret123'
app.run(debug=True)