Skip to content

Commit

Permalink
Updated and fixed flask app logic
Browse files Browse the repository at this point in the history
  • Loading branch information
jhustles committed Oct 5, 2020
1 parent 6a4cc86 commit e264e45
Show file tree
Hide file tree
Showing 16 changed files with 235 additions and 128 deletions.
33 changes: 18 additions & 15 deletions application.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,17 +67,19 @@ def index():
"""Show portfolio of stocks"""

user_id=session["user_id"]
# Add key user_id to userInfo dictionary
userInfo['user_id'] = user_id # global object

items = db.execute("WITH indexSetup AS ( SELECT u.username, c.symbol, c.name, t.c_id, t.ordertype, SUM(t.quantity) as quantity, SUM(t.quantity * t.price) AS total FROM transactions t JOIN companies c ON t.c_id = c.id JOIN users u ON t.user_id = u.id WHERE user_id =:user_id GROUP BY u.username, c.symbol, c.name, t.c_id, t.ordertype), sell as (SELECT username, symbol, name, c_id, SUM(quantity) as quantity , SUM(total) AS costBasis FROM indexSetup WHERE ordertype = 'SELL' GROUP BY 1, 2, 3, 4), buy AS ( SELECT username, symbol, name, c_id, SUM(quantity) as quantity , SUM(total) AS costBasis FROM indexSetup WHERE ordertype = 'BUY' GROUP BY 1, 2, 3, 4) SELECT username, symbol, name, c_id, COALESCE(SUM(b.quantity - s.quantity), b.quantity) as quantity, COALESCE(SUM(b.costBasis - s.CostBasis), b.costBasis) AS total FROM buy b LEFT JOIN sell s USING(username, symbol, name, c_id) GROUP BY 1, 2, 3, 4 ORDER BY name", user_id=userInfo['user_id'])
userCash = db.execute("SELECT username, cash FROM users WHERE id = :user_id", user_id=userInfo['user_id']) #[0]["username"]
userInfo['username'] = userCash[0]['username']
availableCash = userCash[0]["cash"]

if not items:
return render_template("index.html", message="Portfolio is currently empty")
return render_template("index.html", username=userCash[0]['username'],message="Portfolio is currently empty", availableCash=usd(availableCash), user_id=user_id, current_datetime=current_datetime)

users = [i['username'] for i in items][0]
userInfo['username'] = users
# Set the username key to the actual username value


portfolioSymbols = [i['symbol'] for i in items]
portfolioQuantities = [i['quantity'] for i in items]
Expand Down Expand Up @@ -128,7 +130,7 @@ def quote():

if request.method == "GET":
return render_template("quote1.html",
username=userInfo['username'],
username=results[0]['username'],
availableCash=usd(availableCash),
current_datetime=current_datetime)
else: # else if POST
Expand All @@ -151,14 +153,14 @@ def quote():
# LookUp symbol to ensure it's valid on POST
if not lookup(tickerInput):
message = "Invalid Ticker Symbol. Please try another."
return render_template("quote1.html", username=userInfo['username'], availableCash=usd(availableCash), current_datetime=current_datetime, message=message)
return render_template("quote1.html", username=results[0]['username'], availableCash=usd(availableCash), current_datetime=current_datetime, message=message)

# Increment the search counter for a successful search
searchCounter += 1

lookUpResults = {
'search_id' : searchCounter,
'username' : userInfo['username'],
'username' : results[0]['username'],
'availableCash' : availableCash,
'current_datetime': current_datetime,
'companyName' : quote["name"],
Expand All @@ -175,7 +177,7 @@ def quote():
}
searchResultsHistory.append(lookUpResults)

return render_template("buy.html",username=userInfo['username'],
return render_template("buy.html",username=results[0]['username'],
current_datetime=current_datetime,
availableCash=usd(results[0]['cash']),
companyName=searchResultsHistory[-1]['companyName'].upper(),
Expand Down Expand Up @@ -469,12 +471,13 @@ def register():
first_name = request.form.get("firstName")
last_name = request.form.get("lastName")
username = request.form.get("username")
emailAddress = request.form.get("emailAddress")
password = request.form.get("password")
password_confirmation = request.form.get("passwordConfirm")

"""Register user"""
if request.method == "GET": #Render the register.html page
return render_template("register.html", message="")
return render_template("registerdraft.html", message="")

else: # else if, you're already on the page, and want to submit results back to the API, use method = "POST"
if not first_name:
Expand All @@ -495,16 +498,18 @@ def register():
if password != password_confirmation:
return render_template("register.html", message="Your passwords must match before we proceed.")

# Check for Duplicate username
username_result = db.execute("SELECT username FROM users WHERE username = :username", username=request.form.get("username"))
# Check for Duplicate username and email address
username_result = db.execute("SELECT username FROM users WHERE username = :username", username=username)
email_result = db.execute("SELECT email_address FROM names WHERE email_address = :emailAddress", emailAddress=emailAddress)
if len(username_result) >= 1:
return render_template("register.html", message="Sorry this username is already taken.")

elif len(email_result) >= 1:
return render_template("register.html", message="Sorry this email address is already taken. Perhaps you forogt your password?")
else:
hash_pass = generate_password_hash(password)
db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=username, hash=hash_pass)
user_id = db.execute("SELECT id FROM users WHERE username = :username", username=username)
db.execute("INSERT INTO names (first_name, last_name) VALUES (:first_name, :last_name)", first_name=first_name, last_name=last_name)
user_id = db.execute("SELECT id FROM users WHERE username = :username", username=username)[0]['id']
db.execute("INSERT INTO names (first_name, last_name, email_address) VALUES (:first_name, :last_name, :emailAddress)", first_name=first_name, last_name=last_name, emailAddress=emailAddress)
db.execute("INSERT INTO cash (datetime, debit, credit, trans_id, user_id) VALUES(:datetime, :debit, :credit, :trans_id, :user_id)",
datetime=current_datetime,
debit=10000,
Expand All @@ -525,7 +530,6 @@ def sellEstimator():
counter = 0
if counter == 0:
try:

items = db.execute("WITH indexSetup AS ( SELECT u.username, c.symbol, c.name, t.c_id, t.ordertype, SUM(t.quantity) as quantity, SUM(t.quantity * t.price) AS total FROM transactions t JOIN companies c ON t.c_id = c.id JOIN users u ON t.user_id = u.id WHERE user_id =:user_id GROUP BY u.username, c.symbol, c.name, t.c_id, t.ordertype), sell as (SELECT username, symbol, name, c_id, SUM(quantity) as quantity , SUM(total) AS costBasis FROM indexSetup WHERE ordertype = 'SELL' GROUP BY 1, 2, 3, 4), buy AS ( SELECT username, symbol, name, c_id, SUM(quantity) as quantity , SUM(total) AS costBasis FROM indexSetup WHERE ordertype = 'BUY' GROUP BY 1, 2, 3, 4) SELECT username, symbol, name, c_id, COALESCE(SUM(b.quantity - s.quantity), b.quantity) as quantity, COALESCE(SUM(b.costBasis - s.CostBasis), b.costBasis) AS total FROM buy b LEFT JOIN sell s USING(username, symbol, name, c_id) GROUP BY 1, 2, 3, 4 ORDER BY name", user_id=userInfo['user_id'])
# users = [i['username'] for i in items][0]
global portfolioSymbols
Expand All @@ -535,7 +539,6 @@ def sellEstimator():
cnames = [i['name'] for i in items]
marketPrices = [lookup(i)['price'] for i in portfolioSymbols]
time.sleep(2)

except Exception as e:
print(e)

Expand Down
Binary file modified finance.db
Binary file not shown.
Binary file modified static/.DS_Store
Binary file not shown.
2 changes: 1 addition & 1 deletion static/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ h1, h2, h3, h4, h5, h6 {

#hero {
width: 100%;
height: 100vh;
height: 96vh;
/* padding-top: 8%; */
/* padding-bottom: 8%; */
background: url("../img/hero-bg.jpg") top right;
Expand Down
Binary file added static/finance.db
Binary file not shown.
Binary file added static/img/piggy.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
130 changes: 65 additions & 65 deletions static/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@
$(this).closest('li').addClass('active');
}

if ($('body').hasClass('mobile-nav-active')) {
$('body').removeClass('mobile-nav-active');
$('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close');
$('.mobile-nav-overly').fadeOut();
}
return false;
// if ($('body').hasClass('mobile-nav-active')) {
// $('body').removeClass('mobile-nav-active');
// $('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close');
// $('.mobile-nav-overly').fadeOut();
// }
// return false;
}
}
});
Expand All @@ -62,32 +62,32 @@
var $mobile_nav = $('.nav-menu').clone().prop({
class: 'mobile-nav d-lg-none'
});
$('body').append($mobile_nav);
$('body').prepend('<button type="button" class="mobile-nav-toggle d-lg-none"><i class="icofont-navigation-menu"></i></button>');
$('body').append('<div class="mobile-nav-overly"></div>');

$(document).on('click', '.mobile-nav-toggle', function(e) {
$('body').toggleClass('mobile-nav-active');
$('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close');
$('.mobile-nav-overly').toggle();
});
// $('body').append($mobile_nav);
// $('body').prepend('<button type="button" class="mobile-nav-toggle d-lg-none"><i class="icofont-navigation-menu"></i></button>');
// $('body').append('<div class="mobile-nav-overly"></div>');

// $(document).on('click', '.mobile-nav-toggle', function(e) {
// $('body').toggleClass('mobile-nav-active');
// $('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close');
// $('.mobile-nav-overly').toggle();
// });

$(document).on('click', '.mobile-nav .drop-down > a', function(e) {
e.preventDefault();
$(this).next().slideToggle(300);
$(this).parent().toggleClass('active');
});

$(document).click(function(e) {
var container = $(".mobile-nav, .mobile-nav-toggle");
if (!container.is(e.target) && container.has(e.target).length === 0) {
if ($('body').hasClass('mobile-nav-active')) {
$('body').removeClass('mobile-nav-active');
$('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close');
$('.mobile-nav-overly').fadeOut();
}
}
});
// $(document).click(function(e) {
// var container = $(".mobile-nav, .mobile-nav-toggle");
// if (!container.is(e.target) && container.has(e.target).length === 0) {
// if ($('body').hasClass('mobile-nav-active')) {
// $('body').removeClass('mobile-nav-active');
// $('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close');
// $('.mobile-nav-overly').fadeOut();
// }
// }
// });
} else if ($(".mobile-nav, .mobile-nav-toggle").length) {
$(".mobile-nav, .mobile-nav-toggle").hide();
}
Expand Down Expand Up @@ -118,50 +118,50 @@
});

// jQuery counterUp
$('[data-toggle="counter-up"]').counterUp({
delay: 10,
time: 1000
});

// Testimonials carousel (uses the Owl Carousel library)
$(".testimonials-carousel").owlCarousel({
autoplay: true,
dots: true,
loop: true,
items: 1
});
// $('[data-toggle="counter-up"]').counterUp({
// delay: 10,
// time: 1000
// });

// // Testimonials carousel (uses the Owl Carousel library)
// $(".testimonials-carousel").owlCarousel({
// autoplay: true,
// dots: true,
// loop: true,
// items: 1
// });

// Porfolio isotope and filter
$(window).on('load', function() {
var portfolioIsotope = $('.portfolio-container').isotope({
itemSelector: '.portfolio-item'
});

$('#portfolio-flters li').on('click', function() {
$("#portfolio-flters li").removeClass('filter-active');
$(this).addClass('filter-active');

portfolioIsotope.isotope({
filter: $(this).data('filter')
});
aos_init();
});

// Initiate venobox (lightbox feature used in portofilo)
$(document).ready(function() {
$('.venobox').venobox({
'share': false
});
});
});
// $(window).on('load', function() {
// var portfolioIsotope = $('.portfolio-container').isotope({
// itemSelector: '.portfolio-item'
// });

// $('#portfolio-flters li').on('click', function() {
// $("#portfolio-flters li").removeClass('filter-active');
// $(this).addClass('filter-active');

// portfolioIsotope.isotope({
// filter: $(this).data('filter')
// });
// aos_init();
// });

// // Initiate venobox (lightbox feature used in portofilo)
// // $(document).ready(function() {
// // $('.venobox').venobox({
// // 'share': false
// // });
// // });
// });

// Portfolio details carousel
$(".portfolio-details-carousel").owlCarousel({
autoplay: true,
dots: true,
loop: true,
items: 1
});
// $(".portfolio-details-carousel").owlCarousel({
// autoplay: true,
// dots: true,
// loop: true,
// items: 1
// });

// Init AOS
function aos_init() {
Expand Down
4 changes: 2 additions & 2 deletions templates/buy.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
<thead class="table-borderless th">
<tr>
<th scope="col"style="height: 50px; width: 50%;">User: {{ username }}</th>
<th scope="col"></th>
<th scope="col"></th>
<!-- <th></th>
<th></th> -->
<th scope="col"style="text-align:right"> {{ current_datetime }}</th>
</tr>
</thead>
Expand Down
4 changes: 2 additions & 2 deletions templates/buyExecute.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
<thead class="table-borderless th">
<tr>
<th scope="col"style="height: 50px; width: 50%;">User: {{ username }}</th>
<th scope="col"></th>
<th scope="col"></th>
<!-- <th scope="col"></th> -->
<!-- <th scope="col"></th> -->
<th scope="col"style="text-align:right"> {{ current_datetime }}</th>
</tr>
</thead>
Expand Down
1 change: 1 addition & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ <h2 style="color: deeppink;">Indvidual Brokerage Account</h3>
</div>
<div>
<h2>{{ current_datetime }}</h2>
<!-- <h2>{{ user_id }}</h2> -->
</div>
</div>

Expand Down
Loading

0 comments on commit e264e45

Please sign in to comment.