示例#1
0
def delete_class():
    if request.method == "GET":
        return render_template('delete_class.html', portfolio_class=session.get('portfolio_class'))

    if request.method == "POST":
        # for test account - don't do anything
        if session.get('userid') == test_account_userid: return redirect("/class_and_tickers")

        classname = request.form.get("classname")

        # check that user select real class
        if classname == "":
            return error_page("ERROR!\nYou should choose class for deletion.")

        # change classname to None for all tickers in this class
        portfolio_ticker = session.get('portfolio_ticker')
        not_string = ""
        for ticker in portfolio_ticker:
            if portfolio_ticker[ticker]['classname'] == classname:
                not_string += " " + ticker
                ticker_db.query.filter_by(userid=session.get('userid'), ticker=ticker).update({
                    'classname': 'None'})
                db.session.commit()

        # delete this class from db
        class_db.query.filter_by(userid=session.get('userid'),classname=classname).delete(synchronize_session='evaluate')
        db.session.commit()

        # reload info in session
        load_portfolio_info(session.get('userid'), ticker_db, cash_db, class_db, user_db, False)

        if len(not_string) >= 1:
            return error_page('Class has been deleted.\n Class deletion resulted in None class for next tickers:' + not_string)
        return redirect('/class_and_tickers')
示例#2
0
def download_diary():
    username = request.form.get('username')
    date = request.form.get('date')
    if not (username and date):
        return apology('something went wrong')
    info = db.execute(
        'SELECT id, visibility FROM users WHERE username = :username', {
            'username': username
        }).fetchone()
    if not info:
        return error_page("User doesn't exist")
    if username != session['username'] and info['visibility'] == '0':
        return error_page(
            "This user's diaries are private or user doesn't exist")
    diary = db.execute(
        'SELECT * FROM diaries WHERE user_id = :id AND date = :date', {
            'id': info['id'],
            'date': date
        }).fetchone()
    if not diary:
        return error_page("Diary doesn't exist")
    with open('diary.md', 'w') as d:
        header = f"{diary['title']}\nby {username}.\n{diary['date']}\nThat day was {diary['rating']}.\n"
        d.write(header)
        d.write(diary['diary'])
    return send_file('diary.md', as_attachment=True)
示例#3
0
def diary_page(username, date):
    """Shows a diary"""

    if username == session['username']:
        diary = db.execute(
            'SELECT * FROM diaries WHERE user_id = :id AND date = :date', {
                'id': session['user_id'],
                'date': date
            }).fetchone()
        if diary:
            return render_template('diary_page.html',
                                   diary=diary,
                                   username=session['username'])
        else:
            return error_page("Diary doesn't exist")
    else:
        visibility = db.execute(
            'SELECT visibility FROM users WHERE username = :username', {
                'username': username
            }).fetchone()
        if not visibility or visibility[0] == '0':
            return error_page("Access denied or user doesn't exist.")
        else:
            diary = db.execute(
                """SELECT * FROM diaries JOIN users ON diaries.user_id = users.id WHERE users.username = :username AND date = :date""",
                {
                    'username': session['username'],
                    'date': date
                }).fetchone()
            return render_template('diary_page.html',
                                   diary=diary,
                                   username=username)
示例#4
0
def add_class():
    if request.method == "GET":
        return render_template('add_class.html')

    if request.method == "POST":
        # for testoaccount - don't do anything
        if session.get('userid') == test_account_userid: return redirect("/class_and_tickers")

        classname = request.form.get("classname")

        # check: is it new name for class
        if session.get('portfolio_class') is not None:
            for name in session.get('portfolio_class'):
                if name == classname:
                    return error_page('ERROR.\nSuch class exists! Choose another name.')

        # check for spaces in the name
        for i in classname:
            if ord(i) == 32:
                return error_page('ERROR.\nPlease, do not use space in the name!')

        # #check, that name consists of letters only
        # if classname.isalpha() == False:
        #     return error_page('Class name should consist of letters only!')
        #
        # # check that name consist of english letter only
        # eng_alphabet=("abcdefghijklmnopqrstuvwxyz")
        # for one_char in classname.lower():
        #     if one_char not in eng_alphabet:
        #         return error_page('Use only latin letters!')

        # load last id from class_db and put new id by hand (to avoid IntegrityError duplicate key violates unique-constraint)
        max_id = class_db.query.order_by(class_db.id.desc()).first().id

        # change portfolio
        new_row = class_db(id=max_id+1, userid=session.get('userid'), classname=classname,
                           fraction=0, diapason=0,
                           activeticker="None")

        db.session.add(new_row)
        db.session.commit()

        # reload  new portfolio in session
        if session.get('portfolio_ticker') is None:
            # load new prices
            load_portfolio_info(session.get('userid'), ticker_db, cash_db, class_db, user_db, True)
        else:
            # use prices from session
            load_portfolio_info(session.get('userid'), ticker_db, cash_db, class_db, user_db, False)

        return redirect("/class_and_tickers")
示例#5
0
def add_ticker():
    if request.method == "GET":
        return render_template('add_ticker.html',
                               portfolio_class=session.get('portfolio_class')
                               )

    if request.method == "POST":
        # for test account - don't do anything
        if session.get('userid') == test_account_userid: return redirect("/class_and_tickers")

        # check new ticker and load ticker price
        ticker = request.form.get("newticker")

        ticker_info = apiprice(ticker)

        if  ticker_info['price'] == 0:
            print("apology")
            return error_page("Error! Could not load price for such ticker. Probably, ticker name is not correct!")

        # load other info about this ticker
        if session.get('portfolio_class') is not None:
            classname = request.form.get("classname")
        else:
            classname = 'None'

        currency = request.form.get('currency')

        # check that this ticker is not in portfolio
        datas = ticker_db.query.filter_by(userid=session.get('userid'),ticker=ticker).all()
        print(f"check the db for such ticker {datas}")

        if len(datas) != 0:
            return error_page("You already have such ticker!")

        # load last id from ticker_db and put new id by hand (to avoid IntegrityError duplicate key violates unique-constraint)
        max_id = ticker_db.query.order_by(ticker_db.id.desc()).first().id

        # change portfolio
        new_row = ticker_db(id=max_id+1, userid=session.get('userid'),
                            ticker=ticker, number=0,classname=classname,currency=currency )

        db.session.add(new_row)
        db.session.commit()

        # reload  new portfolio in session
        load_portfolio_info(session.get('userid'), ticker_db, cash_db, class_db, user_db, True)

    return redirect("/class_and_tickers")
示例#6
0
def forgot_password():
    if request.method == "GET":
        return render_template('forgot_password.html')

    if request.method == "POST":
        # check that this email in user_db
        email = request.form.get("email")
        datas = user_db.query.filter_by(email=email).all()
        if len(datas) == 0:
            return error_page('There is no user with email ' + email)

        # generate new password
        new_password = secrets.token_hex(16)

        # send password to user
        text = 'Dear ' + datas[0].name + '\nhere is your new password:\n' + new_password
        text += '\nPlease, change this password as soon as possible. \n\nRebalanceMe'
        topic = 'RebalanceMe: your new password'

        send_email(email, text, topic, app)
        print(f"new password has been created and send to {email}")

        # save this password in user_db
        user_db.query.filter_by(email=email).update({
            'hash' : generate_password_hash(new_password)
        })
        db.session.commit()

        return redirect('/login')
示例#7
0
def delete_ticker():
    if request.method == "GET":
        return render_template('delete_ticker.html',
                               portfolio_ticker=session.get('portfolio_ticker'))

    if request.method == "POST":
        # for test account - don't do anything
        if session.get('userid') == test_account_userid: return redirect("/class_and_tickers")

        # load ticker name
        ticker = request.form.get("ticker")

        #  check for empty input field
        if ticker == "":
            return error_page("ERROR!\nYou should choose ticker for deletion.")

        # check if it is active ticker for some class
        portfolio_class = session.get('portfolio_class')

        for classname in portfolio_class:
            if portfolio_class[classname]['activeticker']==ticker:
                # put None in active ticker cell for this class
                class_db.query.filter_by(userid=session.get('userid'), classname=classname).update({
                    'activeticker': 'None'})
                db.session.commit()

        # delete this ticker from db
        ticker_db.query.filter_by(userid=session.get('userid'),ticker=ticker).delete(synchronize_session='evaluate')
        db.session.commit()

        # reload info in session
        load_portfolio_info(session.get('userid'), ticker_db, cash_db, class_db, user_db, False)

        return redirect('/class_and_tickers')
示例#8
0
def add_diary():
    diary = request.form.get('diary')
    date = request.form.get('today_date')
    rating = request.form.get('rating')
    title = request.form.get('title')
    if not (diary and date and rating):
        return apology('please fill the form')
    if not title:
        title = 'Untitled'
    diaries_dates = db.execute(
        'SELECT date FROM diaries WHERE user_id = :id AND date >= :date', {
            'id': session['user_id'],
            'date': date
        }).fetchall()
    if diaries_dates:
        return error_page('You already wrote a diary for today.')
    db.execute(
        'INSERT INTO diaries (user_id, diary, date, title, rating) VALUES (:id, :diary, :date, :title, :rating)',
        {
            'id': session['user_id'],
            'diary': diary,
            'date': date,
            'title': title,
            'rating': rating
        })
    db.commit()
    flash('Diary Added!')
    return redirect(f"/diaries/{session['username']}/{date}")
示例#9
0
def cash():
    if request.method == "GET":
        # check user in session
        if session.get('userid') is None:
            return render_template("index_intro.html")

        return render_template('cash.html', portfolio_cash=session.get('portfolio_cash'),
                           exchange=session.get('exchange')
                           )

    if request.method == "POST":
        # for test account - don't do anything
        if session.get('userid') == test_account_userid: return redirect("/cash")

        if request.form.get('cashvalue') == "":
            return error_page('Input window was empty.')

        print('get new cash values from user')

        # value from cash page
        cash = float(request.form.get('cashvalue'))
        currency = request.form.get('currency')

        # value from cash in session
        oldcash = session.get('portfolio_cash')
        print(f"old cash is {oldcash}")
        newcash = 100*(oldcash[currency] + cash)

        # in case of decreasing of cash - check do we have such money
        if newcash < 0:
            return error_page("You don't have enough cash.")

        # change cash db
        cash_db.query.filter_by(userid=session.get('userid')).update({currency:newcash})
        db.session.commit()

        # reload portfolio
        load_portfolio_info(session.get('userid'), ticker_db, cash_db, class_db, user_db, False)

        return redirect('/cash')
示例#10
0
def registration():
    if request.method == "GET":
        # Forget any user_id
        session.clear()

        return render_template('registration.html')

    if request.method == "POST":
        email = request.form.get("email")

        # hash password
        hashed = generate_password_hash(request.form.get("password"))

        # Query database for username
        datas = user_db.query.filter_by(email=email).all()

        if len(datas) != 0:
            return error_page("User with email " + email + " already exists.")

        # load last id from user_db
        max_id = user_db.query.order_by(user_db.userid.desc()).first().userid
        user_id = max_id + 1
        print(f'last userid is {max_id}')

        # create new row in user_db
        new_user = user_db(userid=user_id, name=request.form.get("username"), email=email, hash=hashed,
                           currency='USD', minsum=0)
        db.session.add(new_user)

        # create new row in cash_db
        new_cash_row = cash_db(userid=user_id, RUB=0, USD=0, EUR=0)
        db.session.add(new_cash_row)

        # create new row in week_db
        new_week_row = week_db(userid=user_id, monday=False, tuesday=False,wednesday=False,
                               thursday=False,friday=False,saturday=False,sunday=False)
        db.session.add(new_week_row)

        db.session.commit()

        # save in user in session
        session["userid"] = user_id
        session["username"] = request.form.get("username")

        return redirect('/')
示例#11
0
def settings():
    if request.method == "GET":
        # check user in session
        if session.get('userid') is None:
            return render_template("index_intro.html")

        user_settings = load_user_settings(user_db, week_db, session.get('userid'))

        if user_settings == False:
            return error_page("Can't find such user in db")

        return render_template('settings.html', user_settings=user_settings)

    if request.method == "POST":
        if request.form.get("send") is not None:
            # for test account - don't do anything
            if session.get('userid') == test_account_userid: return redirect("/settings")

            # send test email
            datas = user_db.query.filter_by(userid=session.get('userid')).all()

            topic = 'Test message from REBALANCEme'
            text = 'It is test email from REBALANCEme app.'

            send_email(datas[0].email, text, topic, app)

            return redirect("/settings")

        if request.form.get("delete") is not None:
            # for test account - don't do anything
            if session.get('userid') == test_account_userid: return redirect("/")

            # delete user from all db: week, cash, ticker, class, user
            week_db.query.filter_by(userid=session.get('userid')).delete(synchronize_session='evaluate')
            class_db.query.filter_by(userid=session.get('userid')).delete(synchronize_session='evaluate')
            ticker_db.query.filter_by(userid=session.get('userid')).delete(synchronize_session='evaluate')
            cash_db.query.filter_by(userid=session.get('userid')).delete(synchronize_session='evaluate')
            user_db.query.filter_by(userid=session.get('userid')).delete(synchronize_session='evaluate')

            db.session.commit()

            # clear session
            session.clear()

            return redirect("/")
示例#12
0
def change_password():
    if request.method == "GET":
        return render_template('change_password.html')

    if request.method == "POST":
        userid = session.get('userid')
        datas = user_db.query.filter_by(userid=userid).all()

        # check old password
        if check_password_hash(datas[0].hash, request.form.get("old")) is False:
            return error_page('ERROR.\nYour old password is not correct.')

        # save new hashed password
        user_db.query.filter_by(userid=userid).update(
            {
                'hash':generate_password_hash(request.form.get("new"))
            })
        db.session.commit()

        return redirect('/')
示例#13
0
def  change_settings():
    if request.method == "GET":
        # check user in session
        if session.get('userid') is None:
            return render_template("index_intro.html")

        # load user settings from db
        user_settings = load_user_settings(user_db, week_db, session.get('userid'))
        if user_settings == False:
            return error_page("Can't find such user in db")

        return render_template('settings_change.html',
                               user_settings=user_settings,
                               week_day=['Monday', 'Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'])


    if request.method == "POST":
        # for test account - don't do anything
        if session.get('userid') == test_account_userid: return redirect("/settings")

        print(f"load report_day {request.form.getlist('report_day') }")

        # change values in user db
        user_db.query.filter_by(userid=session.get('userid')).update({
                    'name': request.form.get('name'),
                    'email': request.form.get('email'),
                    'currency':request.form.get('currency'),
                    'minsum':request.form.get('minimal_operation_sum')
                })

        # change values in week_db
        for week_day in ['Monday', 'Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']:
            week_db.query.filter_by(userid=session.get('userid')).update({week_day.lower(): False})

            for report_day in request.form.getlist('report_day'):
                if week_day == report_day:
                    week_db.query.filter_by(userid=session.get('userid')).update({week_day.lower(): True})

        db.session.commit()

        return redirect("/settings")
示例#14
0
def login():
    if request.method == "GET":
        # Forget any user_id
        session.clear()

        return render_template('login.html')

    if request.method == "POST":
        email = request.form.get("email")

        # Query database for username
        datas = user_db.query.filter_by(email=email).all()

        # Ensure username exists and password is correct
        if len(datas) != 1 or not check_password_hash(datas[0].hash, request.form.get("password")):
            return error_page("invalid username and/or password")

        # Remember which user has logged in
        session["userid"] = datas[0].userid
        session["username"] = datas[0].name

        return redirect('/')
示例#15
0
def change_class_info():
    if request.method == "GET":
        portfolio_class = session.get('portfolio_class')

        # create dict of id : classname +_realfraction /fraction_diap / active ticker
        ids = {}
        idtag = ['fraction','diapason','activeticker','name']
        for key in portfolio_class:
            ids[key] = {}
            for tag in idtag:
                ids[key].update({tag: tag + "_" + key})

        print(ids)
        return render_template('classes_change.html', portfolio_class=portfolio_class,
                               portfolio_ticker=session.get('portfolio_ticker'),
                               ids = ids
                               )

    if request.method == "POST":
        if request.form.get("submit") is not None:
            # for test account - don't do anything
            if session.get('userid') == test_account_userid: return redirect("/class_and_tickers")

            portfolio_class = session.get("portfolio_class")

            for classname in portfolio_class:
                # load classname from website
                tag = 'name_' + classname
                new_classname = request.form.get(tag)

                if new_classname != classname:
                    # check for spaces in the name
                    for i in new_classname:
                        if ord(i) == 32:
                            return error_page('Please, do not use space in the name!')

                    # check: is it new name for class
                    if session.get('portfolio_class') is not None:
                        for name in session.get('portfolio_class'):
                            if name == new_classname:
                                return error_page('Such class exists! Choose another name.')

                    # change classname in ticker db
                    ticker_db.query.filter_by(userid=session.get('userid'), classname=classname).update({
                        'classname': new_classname
                    })

                # load new fraction from website
                tag = 'fraction_' + classname
                new_fraction = request.form.get(tag)

                #load new diapason from website
                tag = 'diapason_' + classname
                new_diapason = request.form.get(tag)

                # load new active ticker
                tag = 'activeticker_' + classname
                new_activeticker = request.form.get(tag)

                # save new values in db
                class_db.query.filter_by(userid=session.get('userid'),classname=classname).update({
                    'classname': new_classname,
                    'fraction': new_fraction,
                    'diapason' : new_diapason,
                    'activeticker' : new_activeticker
                })
                db.session.commit()

        # reload portfolio
        load_portfolio_info(session.get('userid'), ticker_db, cash_db, class_db, user_db, False)
        return redirect("/class_and_tickers")