Exemplo n.º 1
0
def make_order():
    if email := session.get('logged_in'):
        email = email['email']
        fields = {
            f"{key.removeprefix('prod_number_')}": value
            for key, value in request.form.items()
        }
        if not fields:
            abort(404)
        description = '\n'.join(
            [f"{key} = {value}" for key, value in fields.items()])
        query = f"""
        INSERT INTO orders
        (user_email, description, summary, status)
        VALUES ('{str(email)}', '{description}', 0, 0)
        """
        db_cursor = get_db().cursor()
        db_cursor.execute(query)
        get_db().commit()
        for key, value in fields.items():
            query = f"""
            UPDATE products
            SET quantity = quantity - {value}
            WHERE id == {key}
            """
            db_cursor.execute(query)
        get_db().commit()
        session.clear()
        session['logged_in'] = {'email': email}
        return redirect(url_for('main_app'))
Exemplo n.º 2
0
def order(id_, email):
    if session.get('admin'):
        if request.method == "GET":
            query = f"""
            SELECT name, surname, city, mail_index, email, phone
            FROM users
            WHERE email == '{email}'
            """
            db_cursor = get_db().cursor()
            db_cursor.execute(query)
            user = db_cursor.fetchone()

            query = f"""
            SELECT description, status
            FROM orders
            WHERE id == {id_}
            """
            db_cursor = get_db().cursor()
            db_cursor.execute(query)
            order_ = db_cursor.fetchone()
            archiver_data = order_['description'].split('\n')
            archiver_data = {
                key: value
                for key, value in (item.split(' = ') for item in archiver_data)
            }
            keys = archiver_data.keys()
            query = f"""
            SELECT id, category, name, price
            FROM products
            WHERE id in ({', '.join([item for item in keys])})             
            """
            db_cursor.execute(query)
            products = db_cursor.fetchall()
            order_price = 0
            for item in products:
                item['number'] = int(archiver_data[str(item['id'])])
                item['total'] = item['number'] * item['price']
                order_price += item['total']
            return render_template('order_template.html',
                                   user=user,
                                   products=products,
                                   order_price=order_price,
                                   status=order_['status'],
                                   id_=id_)
        elif request.method == "POST":
            status = request.form['status']
            query = f"""
            UPDATE orders
            SET status={status}
            WHERE id == {id_}
            """
            db_cursor = get_db().cursor()
            db_cursor.execute(query)
            get_db().commit()
            return redirect(url_for('admin.order', id_=id_, email=email))
Exemplo n.º 3
0
def view_order(id_):
    if session.get('logged_in'):
        query = f"""
                    SELECT description, status
                    FROM orders
                    WHERE id == {id_}
                    """
        db_cursor = get_db().cursor()
        db_cursor.execute(query)
        order_ = db_cursor.fetchone()
        archiver_data = order_['description'].split('\n')
        archiver_data = {
            key: value
            for key, value in (item.split(' = ') for item in archiver_data)
        }
        keys = archiver_data.keys()
        query = f"""
                    SELECT id, category, name, price
                    FROM products
                    WHERE id in ({', '.join([item for item in keys])})             
                    """
        db_cursor.execute(query)
        products = db_cursor.fetchall()
        order_price = 0
        for item in products:
            item['number'] = int(archiver_data[str(item['id'])])
            item['total'] = item['number'] * item['price']
            order_price += item['total']
        return render_template('user_order_template.html',
                               products=products,
                               order_price=order_price)
Exemplo n.º 4
0
def user(email):
    if request.method == "GET":
        if session.get('logged_in'):
            if session['logged_in']['email'] == email:
                query = f"""
                SELECT email, phone, name, surname, city, mail_index
                FROM users
                WHERE email == '{email}'
                """
                db_cursor = get_db().cursor()
                db_cursor.execute(query)
                person = db_cursor.fetchone()
                query = f"""
                SELECT id, status
                FROM orders
                WHERE user_email == '{email}'
                """
                db_cursor.execute(query)
                orders = db_cursor.fetchall()
                return render_template('user_template.html',
                                       person=person,
                                       orders=orders)
        else:
            abort(404)
    elif request.method == "POST":
        return render_template(url_for('news'))
Exemplo n.º 5
0
def basket():
    if request.method == "GET":
        selected = dict(session.items())
        selected.pop('logged_in', True)
        selected.pop('admin', True)
        ids = selected.keys()
        query = f"""
        SELECT *
        FROM products
        WHERE id in ({', '.join([item for item in ids])})
        """
        db_cursor = get_db().cursor()
        db_cursor.execute(query)
        products = db_cursor.fetchall()
        for product_ in products:
            product_[
                'image'] = f"{product_['category']}/{product_.get('image', '')}"
            product_['number'] = selected[f'{product_["id"]}']
        return render_template("basket.html",
                               products=products,
                               len=len(products))
    elif request.method == "POST":
        fields = request.form.to_dict()
        value = list(fields.values())[0]
        session.pop(value, None)
        return redirect(url_for('basket'))
Exemplo n.º 6
0
def add_product():
    if session.get('admin'):
        if request.method == "GET":
            return render_template('add_product.html')
        elif request.method == "POST":
            if fields := request.form.to_dict():
                query = f"""
                INSERT INTO products 
                (image, category, name, price, quantity, country, description) 
                VALUES ( '{fields['image']}', '{fields['category']}', '{fields['name']}', {fields['price']}, {fields['quantity']}, '{fields['country']}', '{fields['description']}' )
                """
                db_cursor = get_db().cursor()
                db_cursor.execute(query)
                get_db().commit()
                return redirect(url_for('admin.all_products'))
            else:
                return redirect(url_for('admin.add_product'))
Exemplo n.º 7
0
def news():
    query = """
    SELECT title, image, date, description
    FROM news
    """
    db_cursor = get_db().cursor()
    db_cursor.execute(query)
    posts = db_cursor.fetchall()
    return render_template('news.html', posts=posts)
Exemplo n.º 8
0
def delete_user():
    if email := session.get('logged_in'):
        if request.method == "GET":
            return render_template('delete_pop_up.html')
        elif request.method == "POST":
            query = f"""
            DELETE 
            FROM users
            WHERE email == '{email['email']}'
            """
            db_cursor = get_db().cursor()
            db_cursor.execute(query)
            get_db().commit()
            query = f"""
            DELETE 
            FROM orders
            WHERE user_email == '{email['email']}'
            """
            db_cursor.execute(query)
            get_db().commit()
            session.pop('logged_in')
            return "Ok", 200
Exemplo n.º 9
0
def contact():
    if request.method == "GET":
        return render_template("contacts.html")
    if request.method == "POST":
        if not (request.form.get('name') and request.form.get('phone')
                and request.form.get('email') and request.form.get('message')
                and request.form.get('answer')):
            flash("Введены не все данные! Сообщение не отправлено!")
        elif request.form.get('answer').strip() != "54":
            flash("Проблемы с математикой! Сообщение не отправлено!")
        else:
            query = f"""
            INSERT INTO letters (user_name, user_phone, user_email, description, status)
            VALUES ('{request.form.get('name')}', '{request.form.get('phone')}', '{request.form.get('email')}', '{request.form.get('message')}', 0)
            """
            db_cursor = get_db().cursor()
            db_cursor.execute(query)
            get_db().commit()
            flash(
                "Сообщение успешно отправленно. Наш оператор ответит вам как сможет!"
            )
        return redirect(url_for('contact'))
Exemplo n.º 10
0
def all_products():
    if session.get('admin'):
        if request.method == "GET":
            query = """
            SELECT * 
            FROM products
            """
            db_cursor = get_db().cursor()
            db_cursor.execute(query)
            if not (products := db_cursor.fetchall()):
                products = []
            return render_template('all_products.html', products=products)
        elif request.method == "POST":
            fields = request.form.to_dict()
            db_cursor = get_db().cursor()
            for key, value in fields.items():
                query = f"""
                UPDATE products
                SET quantity = {value}
                WHERE id == {int(key)}
                """
                db_cursor.execute(query)
            get_db().commit()
            return redirect(url_for('admin.all_products'))
Exemplo n.º 11
0
def authorization():
    if request.method == 'GET':
        return redirect(url_for('registration'))
    elif request.method == 'POST':
        fields = request.form.to_dict()
        query = f"""
        SELECT email
        FROM users
        WHERE email = '{fields.get('email')}' and password == '{fields.get('password')}'
        """
        db_cursor = get_db().cursor()
        db_cursor.execute(query)
        if result := db_cursor.fetchone():
            session['logged_in'] = {'email': result['email']}
            return redirect(url_for('user', email=result['email']))
        else:
            flash("Неверные данные!")
Exemplo n.º 12
0
def admin_login():
    if request.method == "GET":
        if session.get('admin'):
            return redirect(url_for('admin.main_admin'))
        return render_template('login.html')
    elif request.method == "POST":
        if fields := request.form.to_dict():
            query = f"""
            SELECT * FROM admins
            WHERE admin_email = '{fields['email']}' and password = '******'password']}'
            """
            db_cursor = get_db().cursor()
            db_cursor.execute(query)
            if db_cursor.fetchone():
                session['admin'] = True
                return redirect(url_for('admin.main_admin'))
            else:
                return redirect(url_for('admin.admin_login'))
        else:
            return redirect(url_for('admin.admin_login'))
Exemplo n.º 13
0
def catalog(product_type):
    query = f"""
    SELECT weight, name 
    FROM filters
    WHERE product == '{product_type}' AND category == 'kind'
    """
    db_cursor = get_db().cursor()
    db_cursor.execute(query)
    kinds = db_cursor.fetchall()

    query = f"""
    SELECT weight, name 
    FROM filters
    WHERE product == '{product_type}' AND category == 'country'
    """
    db_cursor.execute(query)
    countries = db_cursor.fetchall()
    url_catalog = f'/catalog-{product_type}'
    if request.method == "GET":
        query = f"""
        SELECT id, image, name, price
        FROM products
        WHERE category== '{product_type}'
        """
        db_cursor.execute(query)
        products = db_cursor.fetchall()

        for item in products:
            item['image'] = f"{product_type}/{item.get('image', '')}"

        return render_template("catalog_template.html",
                               kinds=kinds,
                               countries=countries,
                               products=products,
                               url_catalog=url_catalog)
    elif request.method == "POST":
        fields = request.form.to_dict()
        if not (lower_price := fields.get('lower_price')):
            lower_price = 0
        if not (upper_price := fields.get('upper_price')):
            upper_price = 99999
Exemplo n.º 14
0
def product(id_):
    if request.method == "GET":
        query = f"""
            SELECT id, image, category ,name, price, quantity, country, description
            FROM products
            WHERE id == '{id_}'
            """
        db_cursor = get_db().cursor()
        db_cursor.execute(query)
        product_ = db_cursor.fetchone()
        product_[
            'image'] = f"{product_['category']}/{product_.get('image', '')}"
        return render_template("product_template.html", product=product_)
    elif request.method == "POST":
        if session.get(f"{id_}"):
            session[f"{id_}"] += int(request.form.get('prod_number'))
            if int(request.form.get(f"{id_}")) <= session[f"{id_}"]:
                session[f"{id_}"] = int(request.form.get(f"{id_}"))
        else:
            session[f"{id_}"] = int(request.form.get('prod_number'))
        return redirect(url_for('product', id_=id_))
Exemplo n.º 15
0
def main_admin():
    if request.method == "GET":
        if session.get('admin'):
            query = """
            SELECT id, user_email, status
            FROM orders
            """
            db_cursor = get_db().cursor()
            db_cursor.execute(query)
            orders = db_cursor.fetchall()
            query = """
            SELECT user_email, description
            FROM letters
            """
            db_cursor.execute(query)
            letters = db_cursor.fetchall()
            return render_template('main_admin.html',
                                   orders=orders,
                                   letters=letters)
        else:
            abort(404)
    elif request.method == "POST":
        pass
Exemplo n.º 16
0
        elif not (email := fields.get('email')) or not Validate.email(email):
            flash("Неверно введена электронная почта!")
        elif not (password :=
                  fields.get('password')) or not Validate.password(password):
            flash(
                "Слабый пароль! Пароль должен содержать минимум 8 символов, из них: 1 заглавная буква, 1 строчная буква, 1 цифра"
            )
        elif password != fields.get('confirmed', ""):
            flash("Неверное подтверждение пароля!")
        else:
            query = f"""
            SELECT email 
            FROM users
            WHERE email == '{email}'
            """
            db_cursor = get_db().cursor()
            db_cursor.execute(query)
            if db_cursor.fetchone():
                flash(f"Пользователь с таким email={email} уже существует")
            else:
                query = f"""
                INSERT INTO users 
                VALUES ('{email}', '{password}', '{phone}', '{name}', '{surname}', '{city}' , '{mail_index}')
                """
                db_cursor.execute(query)
                get_db().commit()
                session['logged_in'] = {'email': email}
                return redirect(url_for('user', email=email))
        return redirect(url_for('registration'))