TelegramAktienBot/api/app/blueprints/portfolio.py

42 lines
1.5 KiB
Python

import os
from apiflask import APIBlueprint
from app.models import SharePrice
from app.auth import auth
from app.db import database as db
from app.helper_functions import make_response, get_email_or_abort_401
from app.schema import PortfolioResponseSchema
portfolio_blueprint = APIBlueprint('portfolio', __name__, url_prefix='/api')
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
@portfolio_blueprint.route('/portfolio', methods=['GET'])
@portfolio_blueprint.output(PortfolioResponseSchema(many=True), 200)
@portfolio_blueprint.auth_required(auth)
@portfolio_blueprint.doc(summary="Returns portfolio", description="Returns all shares of current user")
def get_portfolio():
email = get_email_or_abort_401()
return_portfolio = []
transactions = db.session.execute("SELECT symbol, SUM(count), SUM(price), MAX(time) FROM `transactions` WHERE email = '" + email + "' GROUP BY symbol;").all()
if transactions is not None:
for row in transactions:
data = {
"symbol": row[0],
"count": row[1],
# "calculated_price": row[2],
"last_transaction": row[3],
'current_price': 0
}
query_share_price = db.session.query(SharePrice).filter_by(symbol=row[0]).first()
if query_share_price is not None:
data['current_price'] = query_share_price.as_dict()['price']
return_portfolio.append(data)
return make_response(return_portfolio, 200, "Successfully loaded symbols")