Ejemplo n.º 1
0
def answer(id):
    db = get_db()
    user_status = db.execute('SELECT status FROM user WHERE Name = ?',
                             [g.user['name']]).fetchone()
    qns = db.execute('SELECT question FROM question_and_answer WHERE id = ?',
                     [id]).fetchone()
    ans = db.execute('SELECT answer FROM question_and_answer WHERE id = ?',
                     [id]).fetchone()
    if request.method == 'POST':
        if request.form['action'] == 'Submit Answer':
            answer = request.form['answer']
            if answer is None or answer == '':
                error = 'No value entered please try again'
                flash(error)
            else:
                db.execute(
                    'UPDATE question_and_answer SET answer= ? WHERE id = ?',
                    (answer, id))
                db.commit()
                queries = db.execute(
                    'SELECT id, question, answer, user FROM question_and_answer'
                ).fetchall()
                return redirect(url_for('user.faq'))

    return render_template('user/answer_faq.html',
                           id=id,
                           qns=qns[0],
                           status=user_status,
                           ans=ans)
Ejemplo n.º 2
0
def edit_faq(id):
    db = get_db()
    qns = db.execute('SELECT question FROM question_and_answer WHERE id = ?',
                     [id]).fetchone()
    ans = db.execute('SELECT answer FROM question_and_answer WHERE id = ?',
                     [id]).fetchone()
    if request.method == 'POST':
        if request.form['action'] == 'Submit Answer':
            answer = request.form['answer']
            if answer is None or answer == '':
                error = 'No value entered please try again'
                flash(error)
            else:
                db.execute(
                    'UPDATE question_and_answer SET answer= ? WHERE id = ?',
                    (answer, id))
                db.commit()
                return redirect(url_for('support.support_faq'))

        elif request.form['action'] == 'Delete Question':
            db.execute('DELETE FROM question_and_answer WHERE id = ?', (id, ))
            db.commit()
            return redirect(url_for('support.support_faq'))

    return render_template('support/edit_faq.html',
                           id=id,
                           qns=qns[0],
                           ans=ans,
                           datetime=datetime)
Ejemplo n.º 3
0
def ban_user():
    db = get_db()
    users = db.execute('SELECT * FROM user').fetchall()
    if request.method == 'POST':
        if request.form['action'] == 'Ban User':
            name = request.form['name']
            db.execute('UPDATE user SET status = ? WHERE name = ?', (1, name))
            db.commit()
            message = 'Banned the user succesfully'
            users = db.execute('SELECT * FROM user').fetchall()
            flash(message, "success")
            return render_template('support/ban_users.html',
                                   users=users,
                                   datetime=datetime)
        elif request.form['action'] == 'Unban User':
            name = request.form['name']
            db.execute('UPDATE user SET status = ? WHERE name = ?', (0, name))
            db.commit()
            message = 'The user is now free to post'
            users = db.execute('SELECT * FROM user').fetchall()
            flash(message, "success")
            return render_template('support/ban_users.html',
                                   users=users,
                                   datetime=datetime)

    return render_template('support/ban_users.html',
                           users=users,
                           datetime=datetime)
Ejemplo n.º 4
0
def load_logged_in_user():
    """If a user id is stored in the session, load the user object from
    the database into ``g.user``."""
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        g.user = get_db().execute('SELECT * FROM user WHERE id = ?',
                                  (user_id, )).fetchone()
Ejemplo n.º 5
0
def edit_food(id):
    """Update a food entry if the current user is the creator"""
    db = get_db()
    food_entry = get_food_entry(id)
    old_food_name = food_entry['food_name']
    old_food_code = food_entry['food_code']

    if request.method == 'POST':
        if request.form['action'] == 'Update Entry':
            code = request.form['code']
            code = code.lower()
            error = None

            if not code:
                error = 'Please enter a code to edit your previous entry'

            elif code == old_food_code:
                error = "You've entered your previous code"

            else:
                for food in food_list:
                    food_code = food.get_code()

                    if code == food_code:
                        food_calories = food.get_calories()
                        food_name = food.get_name()
                        db.execute(
                            'UPDATE food_entry SET food_code = ?, food_name = ?, calories = ? WHERE id = ?',
                            (code, food_name, food_calories, id))
                        db.commit()
                        message = "Updated {0} ({1}) into {2} ({3}) for your food journal!".format(
                            old_food_name, old_food_code, food_name, food_code)
                        flash(message, "success")
                        return redirect(url_for('food.food_journal'))
                    else:
                        error = 'Invalid code entered'

            if error is not None:
                flash(error, "error")

        elif request.form['action'] == 'Remove Food Entry':
            db.execute('DELETE FROM food_entry WHERE id = ?', (id, ))
            db.commit()
            message = "Deleted {0} ({1}) from your food journal!".format(
                old_food_name, old_food_code)
            flash(message, "success")
            return redirect(url_for('food.food_journal'))

        else:
            return redirect(url_for('food.edit_food', id=id))

    return render_template('food/edit_food.html',
                           food_entry=food_entry,
                           datetime=datetime)
Ejemplo n.º 6
0
def app():
    """Create and configure a new app instance for each test."""
    # create a temporary file to isolate the database for each test
    db_fd, db_path = tempfile.mkstemp()
    # create the app with common test config
    app = create_app({
        'TESTING': True,
        'DATABASE': db_path,
    })

    # create the database and load test data
    with app.app_context():
        init_db()
        get_db().executescript(_data_sql)

    yield app

    # close and remove the temporary database
    os.close(db_fd)
    os.unlink(db_path)
Ejemplo n.º 7
0
def support_faq():
    db = get_db()
    queries = db.execute('SELECT * FROM question_and_answer').fetchall()
    if request.method == 'POST':
        if request.form['answer'] == 'Edit':
            qns = db.execute(
                'SELECT question FROM question_and_answer WHERE id = ?',
                id).fetchone()
            return render_template('support/edit_faq.html',
                                   qns=qns,
                                   datetime=datetime)
    return render_template('support/support_faq.html',
                           queries=queries,
                           datetime=datetime)
Ejemplo n.º 8
0
def get_food_entry(id, check_user=True):
    db = get_db()
    food_entry = db.execute(
        'SELECT f.id, creator_id, food_name, datetime(created, "localtime"), calories, food_code, email'
        ' FROM food_entry f JOIN user u ON f.creator_id = u.id'
        ' WHERE f.id = ?',
        (id, ),
    ).fetchone()

    if food_entry is None:
        abort(404, "That food entry (ID: {0}) doesn't exist".format(id))

    if check_user and food_entry['creator_id'] != g.user['id']:
        abort(403)

    return food_entry
Ejemplo n.º 9
0
def search_food(search_date):
    """Search a food entry if the current user is the creator"""
    db = get_db()
    current_date_food = []
    current_date_calories = []
    food_exists = 0

    try:
        display_date = datetime.strptime(search_date,
                                         '%Y-%m-%d').strftime('%d %B %Y (%A)')
        food_items = db.execute(
            'SELECT f.id, creator_id, food_name, datetime(created, "localtime"), calories, food_code, email'
            ' FROM food_entry f JOIN user u ON f.creator_id = u.id'
            ' WHERE f.creator_id = ? AND DATE(f.created) = ?',
            (
                g.user['id'],
                search_date,
            ),
        ).fetchall()

        if food_items != []:
            food_exists = 1

        for food in food_items:
            current_date_food.append(food)
            current_date_calories.append(food['calories'])

        current_date_calories = sum(current_date_calories)

    except ValueError:
        abort(
            404,
            "That date ({0}) is invalid, please enter a date with a valid YYYY-MM-DD format."
            .format(search_date))

    return render_template('food/search_food.html',
                           search_date=search_date,
                           food_exists=food_exists,
                           food_items=food_items,
                           current_date_calories=current_date_calories,
                           display_date=display_date,
                           datetime=datetime)
Ejemplo n.º 10
0
def support():
    db = get_db()
    food_items = db.execute('SELECT * FROM food_entry').fetchall()
    support_data = SupportData()
    for food in food_items:
        support_data.add_food(food)
    food_dict = support_data.get_food_menu()

    sorted_food_list = sorted(food_dict.items(),
                              key=operator.itemgetter(1),
                              reverse=True)
    simplified_food_list = [
        food_pair for food_pair in sorted_food_list if not food_pair[1] == 0
    ]

    common_food_list = simplified_food_list[:3]

    return render_template('support/support_index.html',
                           food_list=simplified_food_list,
                           common_food_list=common_food_list,
                           datetime=datetime)
Ejemplo n.º 11
0
def index():
    """Show all recent meals, most recent first."""
    db = get_db()
    food_items = db.execute(
        'SELECT f.id, creator_id, food_name, datetime(created, "localtime"), calories, food_code, email'
        ' FROM food_entry f JOIN user u ON f.creator_id = u.id'
        ' WHERE f.creator_id = ? AND DATE(f.created) IN'
        ' (SELECT DISTINCT DATE(created) FROM food_entry '
        ' WHERE NOT date(f.created) = date("now") ORDER BY datetime(created) DESC LIMIT 8)'
        ' ORDER BY datetime(created) DESC',
        (g.user['id'], ),
    ).fetchall()

    users = db.execute(
        'SELECT id, name, email, password, height, weight, location'
        ' FROM user'
        ' WHERE id = ?',
        (g.user['id'], ),
    ).fetchall()

    user_info = ProcessUserInfo(food_items, users)
    info = user_info.get_info()

    return render_template('food/index.html',
                           food_dates=info["food_dates"],
                           all_dates=info["all_dates"],
                           calories_list=info["calories_list"],
                           name=info["name"],
                           weight=info["weight"],
                           height=info["height"],
                           bmi=info["bmi"],
                           user_average_calories=info["user_average_calories"],
                           number_of_days=info["number_of_days"],
                           food_exists=info["food_exists"],
                           user_vendors=info["user_vendors"],
                           food_items=info["food_items"],
                           calories_statement=info["calories_statement"],
                           datetime=datetime)
Ejemplo n.º 12
0
def register():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        name = request.form['name']
        height = request.form['height']
        weight = request.form['weight']
        height = height / 100
        db = get_db()
        check_user = db.execute('SELECT id FROM user WHERE email = ?',
                                (email, )).fetchone()
        error = None

        if not email:
            error = 'Please enter your email'
        elif not password:
            error = 'Please enter your password'
        elif not name:
            error = 'Please enter your name'
        elif not weight:
            error = 'Please enter your weight'
        elif not height:
            error = 'Please enter your height'
        elif check_user is not None:
            error = 'This email ({}) is already registered.'.format(email)

        if error is None:
            db.execute(
                'INSERT INTO user (email, password, name, height, weight) VALUES (?, ?, ?, ?, ?)',
                (email, generate_password_hash(password), name, weight,
                 height))
            db.commit()

            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
Ejemplo n.º 13
0
def faq():
    db = get_db()
    user_status = db.execute('SELECT status FROM user WHERE Name = ?',
                             [g.user['name']]).fetchone()
    queries = db.execute(
        'SELECT id, question, answer, user FROM question_and_answer').fetchall(
        )
    if request.method == 'POST':
        if request.form['action'] == 'Submit A Question':
            question = request.form['query']
            print(request.form)
            answer = "No answer given yet, please answer on your own"
            if question is None or question == '':
                error = 'No value entered please try again'
                flash(error)
            else:
                user = g.user['name']
                db.execute(
                    'INSERT INTO question_and_answer (question, answer, user) VALUES (?, ?, ?)',
                    (question, answer, user))
                db.commit()
                queries = db.execute(
                    'SELECT id, question, answer, user FROM question_and_answer'
                ).fetchall()
                return redirect(url_for('user.faq'))
        if request.form['answer'] == 'Answer':
            qns = db.execute(
                'SELECT question FROM question_and_answer WHERE id = ?',
                id).fetchone()
            return render_template('user/answer_faq.html',
                                   qns=qns,
                                   status=user_status)

        # queries = list(map(lambda x: x[0], queries))
        # for row in queries:
    return render_template('user/faq.html',
                           queries=queries,
                           status=user_status)
Ejemplo n.º 14
0
def vendors():
    db = get_db()

    users = db.execute(
        'SELECT id, name, email, password, height, weight, location'
        ' FROM user'
        ' WHERE id = ?',
        (g.user['id'], ),
    ).fetchall()

    for user in users:
        user_location = user['location']

    user_vendors = []
    for vendors in vendor_list:
        vendor = vendor_list[vendors]
        if user_location == vendor.get_area():
            user_vendors.append(vendor)
        else:
            continue

    return render_template("vendors/vendor_page.html",
                           user_vendors=user_vendors,
                           datetime=datetime)
Ejemplo n.º 15
0
def login():
    """Log in a registered user by adding the user id to the session."""
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        db = get_db()
        error = None
        user = db.execute('SELECT * FROM user WHERE email = ?',
                          (email, )).fetchone()

        if user is None:
            error = 'Incorrect email.'
        elif not check_password_hash(user['password'], password):
            error = 'Incorrect email.'

        if error is None:
            # store the user id in a new session and return to the index
            session.clear()
            session['user_id'] = user['id']
            return redirect(url_for('index'))

        flash(error)

    return render_template('auth/login.html')
Ejemplo n.º 16
0
def user_settings():
    db = get_db()
    food_items = db.execute(
        'SELECT f.id, creator_id, food_name, datetime(created, "localtime"), calories, food_code, email'
        ' FROM food_entry f JOIN user u ON f.creator_id = u.id'
        ' WHERE f.creator_id = ? AND DATE(f.created) IN'
        ' (SELECT DISTINCT DATE(created) FROM food_entry '
        ' WHERE NOT date(f.created) = date("now") ORDER BY datetime(created) DESC LIMIT 8)'
        ' ORDER BY datetime(created) DESC',
        (g.user['id'], ),
    ).fetchall()

    users = db.execute(
        'SELECT id, name, email, password, height, weight, location'
        ' FROM user'
        ' WHERE id = ?',
        (g.user['id'], ),
    ).fetchall()

    user_info = ProcessUserInfo(food_items, users)
    info = user_info.get_info()

    if request.method == 'POST':
        new_height = request.form['height']
        new_weight = request.form['weight']
        new_password = request.form['password']
        new_location = request.form.get('new-location')
        old_password = request.form['old-password']
        error = None

        if request.form['action'] == 'Update Settings':
            if new_height:
                if not 0.5 < float(new_height) < 2.5:
                    error = 'Please enter a valid height value in meters'
                elif new_height == info["height"]:
                    error = 'Please enter a new height value'
                else:
                    db.execute('UPDATE user SET height = ? WHERE id = ?',
                               (new_height, info["id"]))

            if new_weight:
                if not 20 < float(new_weight) < 250:
                    error = 'Please enter a valid weight value in kilograms'
                elif new_weight == info["weight"]:
                    error = 'Please enter a new weight value'
                else:
                    db.execute('UPDATE user SET weight = ? WHERE id = ?',
                               (new_weight, info["id"]))

            if new_password:
                if old_password:
                    if check_password_hash(info["password"], old_password):
                        if check_password_hash(info["password"], new_password):
                            error = "You've entered your previous password"
                        elif " " in new_password:
                            error = "Please don't enter whitespaces in your new password"
                        else:
                            db.execute(
                                'UPDATE user SET password = ? WHERE id = ?',
                                (generate_password_hash(new_password),
                                 info["id"]))
                    else:
                        error = "You've entered your current password incorrectly"
                else:
                    error = "Please enter your current password to change your password"

            if new_location != info["user_location"]:
                db.execute('UPDATE user SET location = ? WHERE id = ?',
                           (new_location, info["id"]))

            if not new_height and not new_weight and not new_password and new_location == info[
                    "user_location"]:
                error = "No settings have been changed"

            if error is not None:
                flash(error, "error")
            else:
                message = "You've successfully changed your settings!"
                flash(message, "success")
                db.commit()
                return redirect(url_for('user.user_settings'))

        if request.form['action'] == 'Delete Account':
            db.execute('DELETE FROM user WHERE id = ?', (g.user['id'], ))
            message = "Your account ({}) has been successfully deleted!".format(
                info["email"])
            flash(message, "success")
            db.commit()
            return redirect(url_for('auth.register'))

    return render_template(
        'user/user_settings.html',
        name=info["name"],
        weight=info["weight"],
        height=info["height"],
        email=info["email"],
        password=info["password"],
        user_location=info["user_location"],
        bmi_statement=info["bmi_statement"],
        calories_statement=info["calories_statement"],
        number_of_days=info["number_of_days"],
        user_average_calories=info["user_average_calories"],
        food_exists=info["food_exists"],
        snack_message=info["snack_message"],
        average_breakfast_calories=info["average_breakfast_calories"],
        average_lunch_calories=info["average_lunch_calories"],
        average_dinner_calories=info["average_dinner_calories"],
        average_snack_calories=info["average_snack_calories"])
Ejemplo n.º 17
0
def food_journal():
    """Show all recent meals, most recent first."""
    db = get_db()
    food_items = db.execute(
        'SELECT f.id, creator_id, food_name, datetime(created, "localtime"), calories, food_code, email'
        ' FROM food_entry f JOIN user u ON f.creator_id = u.id'
        ' WHERE f.creator_id = ?'
        ' ORDER BY datetime(created, "localtime") DESC',
        (g.user['id'], ),
    ).fetchall()

    users = db.execute(
        'SELECT id, name, email, password, height, weight, location'
        ' FROM user'
        ' WHERE id = ?',
        (g.user['id'], ),
    ).fetchall()

    user_info = ProcessUserInfo(food_items, users)
    info = user_info.get_info()

    now_utc = datetime.now(timezone('UTC'))
    now_local = now_utc.astimezone(get_localzone())

    if request.method == 'POST':
        error = None
        code_list = []

        if request.form['action'] == 'Save Food':
            code = request.form['code']
            code = code.lower()

            if not code:
                error = 'Code is required'

            else:
                db = get_db()
                for food in food_list:
                    food_code = food.get_code()
                    code_list.append(food_code)

                    if code == food_code:
                        food_calories = food.get_calories()
                        food_name = food.get_name()
                        db.execute(
                            'INSERT INTO food_entry (creator_id, food_code, food_name, calories)'
                            ' VALUES (?, ?, ?, ?)',
                            (g.user['id'], code, food_name, food_calories))
                        db.commit()
                        message = "Added {0} to your food journal!".format(
                            food_name)
                        flash(message, "success")
                        return redirect(url_for('food.food_journal'))

                    else:
                        error = 'Invalid code entered'

        elif request.form['action'] == 'Search Date':
            search_date = request.form['search-date']
            return redirect(
                url_for('food.search_food', search_date=search_date))

        if error is not None:
            flash(error, "error")

    return render_template('food/food_journal.html',
                           food_items=info["food_items"],
                           food_dates=info["food_dates"],
                           all_dates=info["all_dates"],
                           calories_list=info["calories_list"],
                           name=info["name"],
                           weight=info["weight"],
                           height=info["height"],
                           bmi=info["bmi"],
                           user_average_calories=info["user_average_calories"],
                           number_of_days=info["number_of_days"],
                           food_exists=info["food_exists"],
                           now=now_local,
                           datetime=datetime)