예제 #1
0
def leaderboard():
    if request.method == 'GET':
        db_conn, db_curs = get_db()
        db_curs.execute('SELECT * FROM horseracing_user ORDER BY amount DESC')
        u = db_curs.fetchall()

    return render_template('leaderboard/leaderboard.html', users=u)
예제 #2
0
def race(race_id):
    closed = False
    db_conn, db_curs = get_db()
    if request.method == 'GET':
        db_curs.execute('SELECT * FROM race WHERE number = %s',
                        (str(race_id), ))
        r = db_curs.fetchone()

        db_curs.execute(
            'SELECT horse.id, horse.name, horse.number, horse.odds, horse.race_id, result.place FROM horse LEFT JOIN result ON result.horse_id = horse.id WHERE horse.race_id = %s ORDER BY result.place is null, result.place, horse.number ASC',
            (str(r['id']), ))
        h = db_curs.fetchall()

        db_curs.execute(
            'SELECT bet.id, bet.amount, bet.each_way, bet.horseracing_user_id, bet.amount_won, horse.name AS horsename, horseracing_user.username FROM bet INNER JOIN horseracing_user ON horseracing_user.id = bet.horseracing_user_id INNER JOIN horse ON horse.id = bet.horse_id WHERE bet.race_id = %s ORDER BY bet.created DESC',
            (str(race_id), ))
        b = db_curs.fetchall()

        if r['open'] == RaceState.CLOSED.value:
            closed = True

        return render_template('race/race.html',
                               race=r,
                               horses=h,
                               bets=b,
                               race_state=RaceState,
                               race_finished=closed)
예제 #3
0
def load_logged_in_user():
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        db_conn, db_curs = get_db()
        db_curs.execute('SELECT * FROM horseracing_user WHERE id = %s',
                        (user_id, ))
        g.user = db_curs.fetchone()
예제 #4
0
def load_logged_in_admin():
    admin_id = session.get('admin_id')

    if admin_id is None:
        g.admin = None
    else:
        db_conn, db_curs = get_db()
        db_curs.execute('SELECT * FROM horseracing_admin WHERE id = %s',
                        (admin_id, ))
        g.admin = db_curs.fetchone()
예제 #5
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        db_conn, db_curs = get_db()
        error = login_user(username, db_curs)

        if error is None:
            return redirect(url_for('index'))
        flash(error)

    return render_template('auth/login.html')
예제 #6
0
def add_results(race_number):
    db_conn, db_curs = get_db()

    db_curs.execute('SELECT * FROM race WHERE number = %s',
                    (str(race_number), ))
    r = db_curs.fetchone()

    db_curs.execute(
        'SELECT * FROM horse WHERE race_id = %s ORDER BY number ASC',
        (r['id'], ))
    h = db_curs.fetchall()

    if request.method == 'POST':
        horse_numbers = {
            1: request.form['horse1'].split(" - ")[0],
            2: request.form['horse2'].split(" - ")[0],
            3: request.form['horse3'].split(" - ")[0]
        }

        if len(horse_numbers.values()) > len(set(horse_numbers.values())):
            return render_template(
                'admin/failure.html',
                message="Failed to add results: horses not unique")

        # Register results into db.
        try:
            for place, hnum in horse_numbers.items():
                db_curs.execute(
                    'SELECT * FROM horse WHERE number = %s AND race_id = %s',
                    (hnum, r['id']))
                hse = db_curs.fetchone()
                db_curs.execute(
                    'INSERT INTO result (horse_id, race_id, place) VALUES (%s, %s, %s)',
                    (hse['id'], r['id'], str(place)))
            db_conn.commit()
        except psycopg2.Error as e:
            return render_template('admin/failure.html',
                                   message="Failed to add results: %s" % e)

        err = calculate_and_store_bets(r['id'])
        if err is not None:
            return err

        return render_template('admin/success.html', message="Results added")

    return render_template('admin/add_results.html',
                           race_number=r['number'],
                           horses=h)
예제 #7
0
def bet():
    db_conn, db_curs = get_db()
    horse_id = request.args.get('id', None)
    error = None
    db_curs.execute('SELECT * FROM horse WHERE id = %s', (horse_id, ))
    h = db_curs.fetchone()

    db_curs.execute('SELECT * FROM race WHERE id = %s', (h['race_id'], ))
    r = db_curs.fetchone()

    if r['open'] != RaceState.OPEN.value:
        error = "Race is closed"
        flash(error)
    elif g.user['amount'] <= 0:
        error = "You don't have the money to place this bet"
        flash(error)

    if request.method == 'POST' and error is None:
        amount = request.form['amount']
        eachway = 0
        if 'eachway' in request.form.keys(
        ) and request.form['eachway'] == 'on':
            eachway = 1
        if not amount:
            error = 'Amount is required.'

        new_wallet = g.user['amount'] - resolveStake(float(amount), eachway)
        if new_wallet < 0:
            error = "You don't have enough money for this bet"

        if error is None:
            db_curs.execute(
                'INSERT INTO bet (horse_id, race_id, horseracing_user_id, amount, each_way) VALUES (%s, %s, %s, %s, %s)',
                (horse_id, h['race_id'], g.user['id'], amount, eachway))

            db_curs.execute(
                'UPDATE horseracing_user SET amount = %s WHERE id = %s',
                (new_wallet, g.user['id']))
            db_conn.commit()

            return redirect(url_for('race.race', race_id=h['race_id']))

        flash(error)

    return render_template('bet/bet.html', horse=h)
예제 #8
0
def calculate_and_store_bets(race_id):
    db_conn, db_curs = get_db()

    db_curs.execute('SELECT * FROM bet WHERE race_id = %s', (race_id, ))
    bets = db_curs.fetchall()

    # Get the results
    db_curs.execute(
        'SELECT result.place, result.horse_id, horse.name AS horsename, horse.odds AS horseodds FROM result INNER JOIN horse ON horse.id = result.horse_id WHERE result.race_id = %s',
        (race_id, ))
    results = db_curs.fetchall()

    to_store = {}

    for bet in bets:
        # if the bets horse_id in results
        result = get_result_for_horse(bet['horse_id'], results)
        if result:
            # calculate bet + store
            # total_stake = resolveStake(bet['amount'], bet['each_way'])
            calc = resolveBetValue(result['place'], bet['amount'],
                                   result['horseodds'], bet['each_way'])
            to_store[bet['id']] = (calc, bet['horseracing_user_id'])

    try:
        for id, val in to_store.items():
            db_curs.execute('UPDATE bet SET amount_won = %s WHERE id = %s',
                            (val[0], id))
            db_curs.execute(
                'SELECT horseracing_user.amount FROM horseracing_user WHERE id = %s',
                (val[1], ))
            wallet = db_curs.fetchone()

            new_wallet = wallet['amount'] + val[0]

            db_curs.execute(
                'UPDATE horseracing_user SET amount = %s WHERE id = %s',
                (new_wallet, val[1]))

        db_conn.commit()
    except psycopg2.Error as e:
        return render_template('admin/failure.html',
                               message="Failed to update bets: %s" % e)
예제 #9
0
def delete_bet(bet_id):
    db_conn, db_curs = get_db()

    db_curs.execute('SELECT * FROM bet WHERE id = %s', (bet_id, ))
    bet = db_curs.fetchone()
    race_id = bet['race_id']

    if bet['horseracing_user_id'] != g.user['id']:
        abort(403)

    amount = g.user['amount'] + resolveStake(float(bet['amount']),
                                             bet['each_way'])

    db_curs.execute('DELETE FROM bet WHERE id = %s', (bet['id'], ))
    db_curs.execute('UPDATE horseracing_user SET amount = %s WHERE id = %s',
                    (amount, g.user['id']))
    db_conn.commit()

    return redirect(url_for('race.race', race_id=race_id))
예제 #10
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db_conn, db_curs = get_db()
        error = None
        db_curs.execute('SELECT * FROM horseracing_admin WHERE username = %s',
                        (username, ))
        admin = db_curs.fetchone()
        if admin is None:
            error = 'Incorrect username.'
        elif not check_password_hash(admin['password'], password):
            error = 'Incorrect password.'

        if error is None:
            session.clear()
            session['admin_id'] = admin['id']
            return redirect(url_for('admin.admin_index'))

        flash(error)

    return render_template('admin/login.html')
예제 #11
0
def register():
    if request.method == 'POST':
        username = request.form['username']
        db_conn, db_curs = get_db()
        error = None

        # Check if user already exists and if so, redirect to login page.
        if not username:
            error = 'Username is required.'

        db_curs.execute('SELECT id FROM horseracing_user WHERE username = %s',
                        (username, ))
        exists = db_curs.fetchone()
        if exists is not None:
            error = 'User {} is already registered. Please log in.'.format(
                username)

        if error is not None:
            flash(error)
            return redirect(url_for('auth.login'))

        # Register user and then log them in.
        try:
            db_curs.execute(
                'INSERT INTO horseracing_user (username) VALUES (%s)',
                ((username, )))
            db_conn.commit()
            error = login_user(username, db_curs)
            if error is None:
                return redirect(url_for('index'))
        except psycopg2.Error as e:
            error = 'Something went wrong when doing database transactions: %s', e

        flash(error)

    return render_template('auth/register.html')
예제 #12
0
def admin_index():
    db_conn, db_curs = get_db()

    if request.method == 'POST':
        if 'modify_race_state' in request.form.keys():
            db_curs.execute('SELECT * FROM race WHERE number = %s',
                            (request.form['race_number'], ))
            r = db_curs.fetchone()
            return modify_race_state(
                r['id'], get_race_state(request.form['race_state']), db_conn,
                db_curs)
        elif 'modify_user_state' in request.form.keys():
            modify_user_state(request.form['usernames'],
                              request.form['user_actions'], db_conn, db_curs)
        else:
            return render_template('admin/failure.html',
                                   message="Something went wrong!")

    db_curs.execute('SELECT * FROM race ORDER BY number')
    r = db_curs.fetchall()

    db_curs.execute('SELECT * FROM horseracing_user ORDER BY id')
    u = db_curs.fetchall()
    return render_template('admin/admin.html', races=r, users=u)