feat: initial phone store application
@@ -0,0 +1 @@
|
||||
SECRET_KEY=replace_with_a_random_secret_key
|
||||
@@ -0,0 +1,32 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.pyo
|
||||
|
||||
# Virtual environments
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
|
||||
# Environment variables and secrets
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Databases and local data
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# Backups
|
||||
*_backup_*/
|
||||
*.bak
|
||||
*.backup
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,85 @@
|
||||
# Phone Store — Интернет-магазин мобильных телефонов
|
||||
|
||||
Полноценное web-приложение на Flask + SQLite для лабораторной работы.
|
||||
|
||||
## Возможности
|
||||
|
||||
- Каталог из 10 смартфонов (Apple, Samsung, Xiaomi, HONOR, Google, realme)
|
||||
- Поиск по названию и бренду
|
||||
- Фильтрация по производителю
|
||||
- Сортировка по цене (возрастание / убывание)
|
||||
- Карточка товара с подробными характеристиками
|
||||
- Корзина: добавление, изменение количества, удаление, очистка
|
||||
- Оформление заказа с валидацией
|
||||
- Сохранение заказов в SQLite
|
||||
- Современный адаптивный дизайн
|
||||
|
||||
## Структура проекта
|
||||
|
||||
```
|
||||
phone_store/
|
||||
├── app.py # Основное Flask-приложение
|
||||
├── init_db.py # Скрипт создания и заполнения БД
|
||||
├── requirements.txt # Зависимости
|
||||
├── templates/ # HTML-шаблоны
|
||||
│ ├── base.html
|
||||
│ ├── index.html
|
||||
│ ├── product.html
|
||||
│ ├── cart.html
|
||||
│ └── checkout.html
|
||||
└── static/
|
||||
├── css/style.css
|
||||
├── js/script.js
|
||||
└── images/ # Изображения товаров
|
||||
```
|
||||
|
||||
## Установка и запуск
|
||||
|
||||
Требуется Python 3.11 или новее.
|
||||
|
||||
1. Создайте и активируйте виртуальное окружение:
|
||||
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
|
||||
2. Установите зависимости:
|
||||
|
||||
python -m pip install -r requirements.txt
|
||||
|
||||
3. Создайте файл `.env` на основе примера:
|
||||
|
||||
cp .env.example .env
|
||||
|
||||
Замените значение `SECRET_KEY` в `.env` случайным секретным ключом.
|
||||
Например, его можно сгенерировать командой:
|
||||
|
||||
python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
|
||||
4. Запустите приложение:
|
||||
|
||||
python app.py
|
||||
|
||||
5. Откройте в браузере:
|
||||
|
||||
http://127.0.0.1:5000
|
||||
|
||||
При первом запуске база данных создаётся автоматически.
|
||||
Повторный запуск `python init_db.py` не удаляет существующие товары и заказы.
|
||||
|
||||
Для локальной демонстрации можно использовать встроенный сервер Flask.
|
||||
Для постоянного размещения рекомендуется запуск через Gunicorn.
|
||||
|
||||
В Spyder можно открыть `app.py` и нажать Run (F5).
|
||||
|
||||
## Технологии
|
||||
|
||||
- **HTML5** — структура страниц
|
||||
- **CSS3** — современный адаптивный дизайн
|
||||
- **JavaScript** — интерактивность, валидация, анимации
|
||||
- **Python 3 + Flask** — серверная логика
|
||||
- **SQLite** — хранение товаров и заказов
|
||||
- **Jinja2** — шаблонизатор (входит в Flask)
|
||||
|
||||
## Автор
|
||||
|
||||
Учебный проект (лабораторная работа)
|
||||
@@ -0,0 +1,359 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Phone Store — интернет-магазин мобильных телефонов
|
||||
Flask-приложение с SQLite
|
||||
"""
|
||||
|
||||
from flask import (Flask, render_template, request, redirect, url_for,
|
||||
session, flash, jsonify)
|
||||
import sqlite3
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Путь к базе данных и настройкам
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
load_dotenv(os.path.join(BASE_DIR, '.env'))
|
||||
|
||||
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
|
||||
if not app.config['SECRET_KEY']:
|
||||
raise RuntimeError("Не задан SECRET_KEY. Создайте файл .env.")
|
||||
|
||||
DB_PATH = os.path.join(BASE_DIR, 'database.db')
|
||||
|
||||
def is_safe_redirect_url(target):
|
||||
"""Разрешает перенаправление только внутри текущего сайта."""
|
||||
if not target or '\\' in target:
|
||||
return False
|
||||
|
||||
try:
|
||||
parsed = urlsplit(target)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
if parsed.scheme or parsed.netloc:
|
||||
return (
|
||||
parsed.scheme in ('http', 'https')
|
||||
and parsed.netloc == request.host
|
||||
)
|
||||
|
||||
return target.startswith('/') and not target.startswith('//')
|
||||
|
||||
|
||||
def get_db_connection():
|
||||
"""Создаёт соединение с базой данных"""
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row # доступ к колонкам по имени
|
||||
return conn
|
||||
|
||||
|
||||
def get_cart():
|
||||
# Корзина хранит только ID товаров и количество.
|
||||
raw_cart = session.get('cart', {})
|
||||
if not isinstance(raw_cart, dict):
|
||||
raw_cart = {}
|
||||
|
||||
cart = {}
|
||||
|
||||
for product_id, value in raw_cart.items():
|
||||
try:
|
||||
pid = str(int(product_id))
|
||||
if int(pid) <= 0:
|
||||
continue
|
||||
|
||||
# Поддержка старого формата сессии.
|
||||
quantity = value.get('quantity') if isinstance(value, dict) else value
|
||||
quantity = int(quantity)
|
||||
except (TypeError, ValueError, AttributeError):
|
||||
continue
|
||||
|
||||
if quantity > 0:
|
||||
cart[pid] = min(quantity, 99)
|
||||
|
||||
if cart != raw_cart:
|
||||
session['cart'] = cart
|
||||
session.modified = True
|
||||
|
||||
return cart
|
||||
|
||||
|
||||
def save_cart(cart):
|
||||
session['cart'] = cart
|
||||
session.modified = True
|
||||
|
||||
|
||||
def get_cart_items():
|
||||
# Загружаем актуальные данные товаров из базы.
|
||||
cart = get_cart()
|
||||
if not cart:
|
||||
return []
|
||||
|
||||
conn = get_db_connection()
|
||||
try:
|
||||
placeholders = ','.join('?' for _ in cart)
|
||||
rows = conn.execute(
|
||||
f'SELECT id, name, price, image FROM products '
|
||||
f'WHERE id IN ({placeholders})',
|
||||
tuple(int(pid) for pid in cart)
|
||||
).fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
products = {str(row['id']): dict(row) for row in rows}
|
||||
items = []
|
||||
valid_cart = {}
|
||||
|
||||
for pid, quantity in cart.items():
|
||||
product = products.get(pid)
|
||||
if product is None:
|
||||
continue
|
||||
|
||||
product['quantity'] = quantity
|
||||
items.append(product)
|
||||
valid_cart[pid] = quantity
|
||||
|
||||
if valid_cart != cart:
|
||||
save_cart(valid_cart)
|
||||
|
||||
return items
|
||||
|
||||
|
||||
def get_cart_count():
|
||||
return sum(get_cart().values())
|
||||
|
||||
|
||||
def get_cart_total():
|
||||
return sum(
|
||||
item['price'] * item['quantity']
|
||||
for item in get_cart_items()
|
||||
)
|
||||
|
||||
|
||||
@app.context_processor
|
||||
def inject_cart_info():
|
||||
"""Добавляет актуальную информацию о корзине во все шаблоны."""
|
||||
items = get_cart_items()
|
||||
return {
|
||||
'cart_count': sum(item['quantity'] for item in items),
|
||||
'cart_total': sum(
|
||||
item['price'] * item['quantity'] for item in items
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
"""Главная страница с каталогом"""
|
||||
search = request.args.get('search', '').strip()
|
||||
brand = request.args.get('brand', '').strip()
|
||||
sort = request.args.get('sort', '')
|
||||
|
||||
conn = get_db_connection()
|
||||
query = 'SELECT * FROM products WHERE 1=1'
|
||||
params = []
|
||||
|
||||
if search:
|
||||
query += ' AND (name LIKE ? OR brand LIKE ?)'
|
||||
params.extend([f'%{search}%', f'%{search}%'])
|
||||
|
||||
if brand:
|
||||
query += ' AND brand = ?'
|
||||
params.append(brand)
|
||||
|
||||
if sort == 'price_asc':
|
||||
query += ' ORDER BY price ASC'
|
||||
elif sort == 'price_desc':
|
||||
query += ' ORDER BY price DESC'
|
||||
else:
|
||||
query += ' ORDER BY id ASC'
|
||||
|
||||
products = conn.execute(query, params).fetchall()
|
||||
|
||||
# Список брендов для фильтра
|
||||
brands = conn.execute(
|
||||
'SELECT DISTINCT brand FROM products ORDER BY brand'
|
||||
).fetchall()
|
||||
conn.close()
|
||||
|
||||
return render_template(
|
||||
'index.html',
|
||||
products=products,
|
||||
brands=brands,
|
||||
search=search,
|
||||
selected_brand=brand,
|
||||
sort=sort
|
||||
)
|
||||
|
||||
|
||||
@app.route('/product/<int:product_id>')
|
||||
def product_detail(product_id):
|
||||
"""Страница подробной информации о товаре"""
|
||||
conn = get_db_connection()
|
||||
product = conn.execute(
|
||||
'SELECT * FROM products WHERE id = ?', (product_id,)
|
||||
).fetchone()
|
||||
conn.close()
|
||||
|
||||
if product is None:
|
||||
flash('Товар не найден', 'error')
|
||||
return redirect(url_for('index'))
|
||||
|
||||
return render_template('product.html', product=product)
|
||||
|
||||
|
||||
@app.route('/add_to_cart/<int:product_id>', methods=['POST'])
|
||||
def add_to_cart(product_id):
|
||||
"""Добавление товара в корзину"""
|
||||
conn = get_db_connection()
|
||||
product = conn.execute(
|
||||
'SELECT * FROM products WHERE id = ?', (product_id,)
|
||||
).fetchone()
|
||||
conn.close()
|
||||
|
||||
if product is None:
|
||||
flash('Товар не найден', 'error')
|
||||
return redirect(url_for('index'))
|
||||
|
||||
cart = get_cart()
|
||||
pid = str(product_id)
|
||||
|
||||
if cart.get(pid, 0) >= 99:
|
||||
flash('Достигнуто максимальное количество товара в корзине (99)', 'error')
|
||||
else:
|
||||
cart[pid] = cart.get(pid, 0) + 1
|
||||
save_cart(cart)
|
||||
flash(f'«{product["name"]}» добавлен в корзину', 'success')
|
||||
|
||||
# Возврат только на безопасный адрес внутри сайта.
|
||||
next_url = request.form.get('next') or request.referrer
|
||||
if not is_safe_redirect_url(next_url):
|
||||
next_url = url_for('index')
|
||||
|
||||
return redirect(next_url)
|
||||
|
||||
|
||||
@app.route('/cart')
|
||||
def cart():
|
||||
"""Страница корзины"""
|
||||
items = get_cart_items()
|
||||
total = sum(item['price'] * item['quantity'] for item in items)
|
||||
return render_template('cart.html', items=items, total=total)
|
||||
|
||||
|
||||
@app.route('/update_cart/<int:product_id>', methods=['POST'])
|
||||
def update_cart(product_id):
|
||||
"""Изменение количества товара в корзине"""
|
||||
action = request.form.get('action')
|
||||
cart = get_cart()
|
||||
pid = str(product_id)
|
||||
|
||||
if pid in cart:
|
||||
if action == 'increase':
|
||||
if cart[pid] < 99:
|
||||
cart[pid] += 1
|
||||
else:
|
||||
flash('Достигнуто максимальное количество товара в корзине (99)', 'error')
|
||||
elif action == 'decrease':
|
||||
cart[pid] -= 1
|
||||
if cart[pid] <= 0:
|
||||
del cart[pid]
|
||||
flash('Товар удалён из корзины', 'info')
|
||||
elif action == 'remove':
|
||||
del cart[pid]
|
||||
flash('Товар удалён из корзины', 'info')
|
||||
|
||||
save_cart(cart)
|
||||
|
||||
return redirect(url_for('cart'))
|
||||
|
||||
|
||||
@app.route('/clear_cart', methods=['POST'])
|
||||
def clear_cart():
|
||||
"""Очистка корзины"""
|
||||
session.pop('cart', None)
|
||||
flash('Корзина очищена', 'info')
|
||||
return redirect(url_for('cart'))
|
||||
|
||||
|
||||
@app.route('/checkout', methods=['GET', 'POST'])
|
||||
def checkout():
|
||||
# Загружаем товары и актуальные цены из базы.
|
||||
items = get_cart_items()
|
||||
if not items:
|
||||
flash('Корзина пуста', 'error')
|
||||
return redirect(url_for('cart'))
|
||||
|
||||
total = sum(item['price'] * item['quantity'] for item in items)
|
||||
|
||||
if request.method == 'POST':
|
||||
name = request.form.get('name', '').strip()
|
||||
phone = request.form.get('phone', '').strip()
|
||||
address = request.form.get('address', '').strip()
|
||||
|
||||
errors = []
|
||||
if not name or len(name) < 2:
|
||||
errors.append('Укажите корректное имя')
|
||||
if not phone or len(phone) < 10:
|
||||
errors.append('Укажите корректный номер телефона')
|
||||
if not address or len(address) < 5:
|
||||
errors.append('Укажите адрес доставки')
|
||||
|
||||
if errors:
|
||||
for err in errors:
|
||||
flash(err, 'error')
|
||||
return render_template(
|
||||
'checkout.html', items=items, total=total,
|
||||
name=name, phone=phone, address=address
|
||||
)
|
||||
|
||||
# Повторно загружаем товары перед сохранением заказа.
|
||||
items = get_cart_items()
|
||||
if not items:
|
||||
flash('Товары в корзине больше недоступны', 'error')
|
||||
return redirect(url_for('cart'))
|
||||
|
||||
total = sum(item['price'] * item['quantity'] for item in items)
|
||||
|
||||
items_str = '; '.join(
|
||||
f"{item['name']} x{item['quantity']}" for item in items
|
||||
)
|
||||
|
||||
conn = get_db_connection()
|
||||
try:
|
||||
conn.execute(
|
||||
'INSERT INTO orders (customer_name, phone, address, total, items) '
|
||||
'VALUES (?, ?, ?, ?, ?)',
|
||||
(name, phone, address, total, items_str)
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
session.pop('cart', None)
|
||||
flash('Заказ успешно оформлен! Мы свяжемся с вами в ближайшее время.', 'success')
|
||||
return redirect(url_for('index'))
|
||||
|
||||
return render_template('checkout.html', items=items, total=total)
|
||||
|
||||
|
||||
@app.route('/api/cart_count')
|
||||
def api_cart_count():
|
||||
"""API для получения количества товаров в корзине (для JS)"""
|
||||
return jsonify({'count': get_cart_count()})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Инициализация БД при первом локальном запуске.
|
||||
if not os.path.exists(DB_PATH):
|
||||
from init_db import init_db
|
||||
init_db()
|
||||
|
||||
print('=' * 50)
|
||||
print('Phone Store — интернет-магазин мобильных телефонов')
|
||||
print('Запуск сервера: http://127.0.0.1:5000')
|
||||
print('=' * 50)
|
||||
port = int(os.environ.get('PORT', 5000))
|
||||
app.run(host='0.0.0.0', port=port, debug=False)
|
||||
@@ -0,0 +1,192 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Скрипт инициализации базы данных для интернет-магазина Phone Store.
|
||||
Создаёт таблицы и заполняет каталог тестовыми данными.
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
DB_PATH = os.path.join(os.path.dirname(__file__), 'database.db')
|
||||
|
||||
def init_db():
|
||||
# Создаём базу, не удаляя существующие данные.
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Таблица товаров
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS products (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
brand TEXT NOT NULL,
|
||||
price REAL NOT NULL,
|
||||
storage TEXT NOT NULL,
|
||||
ram TEXT NOT NULL,
|
||||
screen TEXT NOT NULL,
|
||||
battery TEXT NOT NULL,
|
||||
description TEXT,
|
||||
image TEXT,
|
||||
features TEXT
|
||||
)
|
||||
''')
|
||||
|
||||
# Таблица заказов
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
customer_name TEXT NOT NULL,
|
||||
phone TEXT NOT NULL,
|
||||
address TEXT NOT NULL,
|
||||
total REAL NOT NULL,
|
||||
items TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
''')
|
||||
|
||||
# Тестовые данные — 10 смартфонов
|
||||
products = [
|
||||
(
|
||||
'iPhone 15 Pro',
|
||||
'Apple',
|
||||
129990,
|
||||
'256 ГБ',
|
||||
'8 ГБ',
|
||||
'6.1"',
|
||||
'3274 мА·ч',
|
||||
'Флагманский смартфон Apple с титановым корпусом, чипом A17 Pro и превосходной камерой.',
|
||||
'iphone15pro.jpg',
|
||||
'Чип A17 Pro, Dynamic Island, USB-C, 48 Мп основная камера, 5x оптический зум'
|
||||
),
|
||||
(
|
||||
'Samsung Galaxy S24 Ultra',
|
||||
'Samsung',
|
||||
119990,
|
||||
'512 ГБ',
|
||||
'12 ГБ',
|
||||
'6.8"',
|
||||
'5000 мА·ч',
|
||||
'Премиальный смартфон с S Pen, мощным процессором Snapdragon 8 Gen 3 и ИИ-функциями.',
|
||||
's24ultra.jpg',
|
||||
'S Pen, Snapdragon 8 Gen 3, 200 Мп камера, 100x Space Zoom, Galaxy AI'
|
||||
),
|
||||
(
|
||||
'Xiaomi 14',
|
||||
'Xiaomi',
|
||||
69990,
|
||||
'256 ГБ',
|
||||
'12 ГБ',
|
||||
'6.36"',
|
||||
'4610 мА·ч',
|
||||
'Компактный флагман с камерой Leica и быстрой зарядкой 90 Вт.',
|
||||
'xiaomi14.jpg',
|
||||
'Камера Leica, Snapdragon 8 Gen 3, 90 Вт зарядка, HyperOS'
|
||||
),
|
||||
(
|
||||
'HONOR Magic6 Pro',
|
||||
'HONOR',
|
||||
89990,
|
||||
'512 ГБ',
|
||||
'12 ГБ',
|
||||
'6.8"',
|
||||
'5600 мА·ч',
|
||||
'Смартфон с выдающейся автономностью и передовой системой камер.',
|
||||
'magic6pro.jpg',
|
||||
'Snapdragon 8 Gen 3, 5600 мА·ч, 80 Вт зарядка, Falcon Camera System'
|
||||
),
|
||||
(
|
||||
'Google Pixel 8 Pro',
|
||||
'Google',
|
||||
99990,
|
||||
'256 ГБ',
|
||||
'12 ГБ',
|
||||
'6.7"',
|
||||
'5050 мА·ч',
|
||||
'Лучший смартфон для фотографии с чистым Android и мощным ИИ.',
|
||||
'pixel8pro.jpg',
|
||||
'Tensor G3, 50 Мп основная камера, 7 лет обновлений, Magic Editor'
|
||||
),
|
||||
(
|
||||
'Samsung Galaxy A55',
|
||||
'Samsung',
|
||||
39990,
|
||||
'256 ГБ',
|
||||
'8 ГБ',
|
||||
'6.6"',
|
||||
'5000 мА·ч',
|
||||
'Отличный среднебюджетный смартфон с защитой IP67 и хорошей камерой.',
|
||||
'a55.jpg',
|
||||
'Exynos 1480, IP67, 50 Мп камера, 45 Вт зарядка'
|
||||
),
|
||||
(
|
||||
'Xiaomi Redmi Note 13 Pro',
|
||||
'Xiaomi',
|
||||
27990,
|
||||
'256 ГБ',
|
||||
'8 ГБ',
|
||||
'6.67"',
|
||||
'5100 мА·ч',
|
||||
'Популярный смартфон с отличным соотношением цены и качества.',
|
||||
'note13pro.jpg',
|
||||
'MediaTek Dimensity 7200, 200 Мп камера, 67 Вт зарядка, AMOLED 120 Гц'
|
||||
),
|
||||
(
|
||||
'iPhone 14',
|
||||
'Apple',
|
||||
74990,
|
||||
'128 ГБ',
|
||||
'6 ГБ',
|
||||
'6.1"',
|
||||
'3279 мА·ч',
|
||||
'Надёжный смартфон Apple с отличной камерой и длительной поддержкой.',
|
||||
'iphone14.jpg',
|
||||
'Чип A15 Bionic, Dual 12 Мп камера, Ceramic Shield, 5G'
|
||||
),
|
||||
(
|
||||
'realme GT 6',
|
||||
'realme',
|
||||
49990,
|
||||
'256 ГБ',
|
||||
'12 ГБ',
|
||||
'6.78"',
|
||||
'5500 мА·ч',
|
||||
'Игровой флагман с ярким экраном и быстрой зарядкой 120 Вт.',
|
||||
'gt6.jpg',
|
||||
'Snapdragon 8s Gen 3, 120 Гц AMOLED, 50 Мп Sony LYTIA, 120 Вт'
|
||||
),
|
||||
(
|
||||
'HONOR X9b',
|
||||
'HONOR',
|
||||
24990,
|
||||
'256 ГБ',
|
||||
'8 ГБ',
|
||||
'6.8"',
|
||||
'5800 мА·ч',
|
||||
'Смартфон с ультрапрочным экраном и огромным аккумулятором.',
|
||||
'x9b.jpg',
|
||||
'Snapdragon 6 Gen 1, 5800 мА·ч, 35 Вт, Anti-Drop Ultra Curved Display'
|
||||
),
|
||||
]
|
||||
|
||||
existing_products = cursor.execute(
|
||||
'SELECT COUNT(*) FROM products'
|
||||
).fetchone()[0]
|
||||
|
||||
if existing_products == 0:
|
||||
cursor.executemany('''
|
||||
INSERT INTO products (name, brand, price, storage, ram, screen, battery, description, image, features)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', products)
|
||||
print(f'Добавлено демонстрационных товаров: {len(products)}')
|
||||
else:
|
||||
print(
|
||||
f'Каталог уже содержит товаров: {existing_products}. '
|
||||
'Повторное заполнение пропущено.'
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f'База данных готова: {DB_PATH}')
|
||||
|
||||
if __name__ == '__main__':
|
||||
init_db()
|
||||
@@ -0,0 +1,3 @@
|
||||
Flask==3.0.3
|
||||
gunicorn==21.2.0
|
||||
python-dotenv==1.2.4
|
||||
@@ -0,0 +1 @@
|
||||
python-3.11.9
|
||||
@@ -0,0 +1,914 @@
|
||||
/* ===== Phone Store — Современный дизайн ===== */
|
||||
|
||||
:root {
|
||||
--primary: #1e3a5f;
|
||||
--primary-dark: #0f2744;
|
||||
--accent: #3b82f6;
|
||||
--accent-hover: #2563eb;
|
||||
--bg: #f0f4f8;
|
||||
--card-bg: #ffffff;
|
||||
--text: #1e293b;
|
||||
--text-muted: #64748b;
|
||||
--border: #e2e8f0;
|
||||
--success: #10b981;
|
||||
--error: #ef4444;
|
||||
--info: #3b82f6;
|
||||
--shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.07), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
|
||||
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.08), 0 4px 6px -4px rgba(0, 0, 0, 0.05);
|
||||
--radius: 12px;
|
||||
--transition: 0.2s ease;
|
||||
}
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
line-height: 1.6;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 0 20px;
|
||||
}
|
||||
|
||||
/* ===== Header ===== */
|
||||
.header {
|
||||
background: var(--card-bg);
|
||||
border-bottom: 1px solid var(--border);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.header-inner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
height: 70px;
|
||||
}
|
||||
|
||||
.logo {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
text-decoration: none;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.logo-icon {
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
.logo-text {
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.5px;
|
||||
}
|
||||
|
||||
.logo-accent {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
text-decoration: none;
|
||||
color: var(--text);
|
||||
font-weight: 500;
|
||||
font-size: 15px;
|
||||
transition: color var(--transition);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.nav-link:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.cart-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cart-badge {
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
padding: 2px 7px;
|
||||
border-radius: 20px;
|
||||
min-width: 22px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* ===== Flash messages ===== */
|
||||
.flash-container {
|
||||
position: fixed;
|
||||
top: 80px;
|
||||
right: 20px;
|
||||
z-index: 200;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
max-width: 360px;
|
||||
}
|
||||
|
||||
.flash {
|
||||
padding: 14px 18px;
|
||||
border-radius: var(--radius);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
box-shadow: var(--shadow-lg);
|
||||
animation: slideIn 0.3s ease;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from { transform: translateX(100%); opacity: 0; }
|
||||
to { transform: translateX(0); opacity: 1; }
|
||||
}
|
||||
|
||||
.flash-success { background: #ecfdf5; color: #065f46; border: 1px solid #a7f3d0; }
|
||||
.flash-error { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; }
|
||||
.flash-info { background: #eff6ff; color: #1e40af; border: 1px solid #bfdbfe; }
|
||||
|
||||
.flash-close {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
color: inherit;
|
||||
opacity: 0.6;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.flash-close:hover { opacity: 1; }
|
||||
|
||||
/* ===== Main ===== */
|
||||
.main {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ===== Hero ===== */
|
||||
.hero {
|
||||
background: linear-gradient(135deg, var(--primary) 0%, #2563eb 100%);
|
||||
color: white;
|
||||
padding: 60px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.hero h1 {
|
||||
font-size: 36px;
|
||||
font-weight: 700;
|
||||
margin-bottom: 12px;
|
||||
letter-spacing: -0.5px;
|
||||
}
|
||||
|
||||
.hero p {
|
||||
font-size: 17px;
|
||||
opacity: 0.9;
|
||||
max-width: 500px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* ===== Advantages ===== */
|
||||
.advantages {
|
||||
padding: 40px 0;
|
||||
margin-top: -30px;
|
||||
}
|
||||
|
||||
.advantages-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.advantage-card {
|
||||
background: var(--card-bg);
|
||||
border-radius: var(--radius);
|
||||
padding: 24px 20px;
|
||||
text-align: center;
|
||||
box-shadow: var(--shadow);
|
||||
transition: transform var(--transition), box-shadow var(--transition);
|
||||
}
|
||||
|
||||
.advantage-card:hover {
|
||||
transform: translateY(-4px);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
.advantage-icon {
|
||||
font-size: 32px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.advantage-card h3 {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.advantage-card p {
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* ===== Catalog ===== */
|
||||
.catalog {
|
||||
padding: 20px 0 60px;
|
||||
}
|
||||
|
||||
.catalog-header {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.catalog-header h2 {
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* Filters */
|
||||
.filters {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
margin-bottom: 32px;
|
||||
align-items: center;
|
||||
background: var(--card-bg);
|
||||
padding: 16px 20px;
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.search-group {
|
||||
flex: 1;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
width: 100%;
|
||||
padding: 10px 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
transition: border-color var(--transition);
|
||||
}
|
||||
|
||||
.search-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.filter-select {
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
background: white;
|
||||
cursor: pointer;
|
||||
min-width: 160px;
|
||||
}
|
||||
|
||||
.filter-select:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
/* Products grid */
|
||||
.products-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.product-card {
|
||||
background: var(--card-bg);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
box-shadow: var(--shadow);
|
||||
transition: transform var(--transition), box-shadow var(--transition);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.product-card:hover {
|
||||
transform: translateY(-6px);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
.product-image-link {
|
||||
display: block;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.product-image {
|
||||
aspect-ratio: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.product-image img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.product-card:hover .product-image img {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.product-info {
|
||||
padding: 16px 18px 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.product-brand {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.product-name {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
margin-bottom: 8px;
|
||||
display: block;
|
||||
transition: color var(--transition);
|
||||
}
|
||||
|
||||
.product-name:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.product-specs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.product-specs span {
|
||||
font-size: 12px;
|
||||
background: var(--bg);
|
||||
padding: 3px 8px;
|
||||
border-radius: 6px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.product-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: auto;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.product-price {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
color: var(--primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 10px 18px;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
font-family: inherit;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
transition: all var(--transition);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.btn-outline {
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.btn-outline:hover {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.btn-cart {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
padding: 8px 14px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.btn-cart:hover {
|
||||
background: var(--primary-dark);
|
||||
}
|
||||
|
||||
.btn-large {
|
||||
padding: 14px 28px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.btn-block {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ===== Product detail ===== */
|
||||
.product-detail {
|
||||
padding: 30px 0 60px;
|
||||
}
|
||||
|
||||
.breadcrumb {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 24px;
|
||||
font-size: 14px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.breadcrumb a {
|
||||
color: var(--accent);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.breadcrumb a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.product-detail-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 48px;
|
||||
background: var(--card-bg);
|
||||
border-radius: var(--radius);
|
||||
padding: 40px;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.product-detail-image {
|
||||
background: #f8fafc;
|
||||
border-radius: var(--radius);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 30px;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
|
||||
.product-detail-image img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.product-title {
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
margin: 8px 0 16px;
|
||||
}
|
||||
|
||||
.product-price-large {
|
||||
font-size: 32px;
|
||||
font-weight: 700;
|
||||
color: var(--primary);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.product-description {
|
||||
margin-bottom: 24px;
|
||||
color: var(--text-muted);
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.specs-table {
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.specs-table h3 {
|
||||
font-size: 16px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.specs-table table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.specs-table td {
|
||||
padding: 10px 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.specs-table td:first-child {
|
||||
color: var(--text-muted);
|
||||
width: 40%;
|
||||
}
|
||||
|
||||
.specs-table td:last-child {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* ===== Cart ===== */
|
||||
.cart-section, .checkout-section {
|
||||
padding: 30px 0 60px;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.cart-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 320px;
|
||||
gap: 28px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.cart-items {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.cart-item {
|
||||
background: var(--card-bg);
|
||||
border-radius: var(--radius);
|
||||
padding: 20px;
|
||||
display: grid;
|
||||
grid-template-columns: 80px 1fr auto auto auto;
|
||||
gap: 16px;
|
||||
align-items: center;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.cart-item-image {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
background: #f8fafc;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.cart-item-image img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.cart-item-info h3 {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.cart-item-price {
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.cart-item-qty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.qty-form {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.qty-btn {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 1px solid var(--border);
|
||||
background: white;
|
||||
border-radius: 6px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all var(--transition);
|
||||
}
|
||||
|
||||
.qty-btn:hover {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.qty-value {
|
||||
font-weight: 600;
|
||||
min-width: 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.cart-item-total {
|
||||
font-weight: 700;
|
||||
font-size: 16px;
|
||||
min-width: 100px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.btn-remove {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 22px;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
padding: 4px 8px;
|
||||
transition: color var(--transition);
|
||||
}
|
||||
|
||||
.btn-remove:hover {
|
||||
color: var(--error);
|
||||
}
|
||||
|
||||
.cart-summary {
|
||||
background: var(--card-bg);
|
||||
border-radius: var(--radius);
|
||||
padding: 24px;
|
||||
box-shadow: var(--shadow);
|
||||
position: sticky;
|
||||
top: 90px;
|
||||
}
|
||||
|
||||
.cart-summary h3 {
|
||||
font-size: 18px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.summary-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 10px;
|
||||
font-size: 14px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.total-row {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
border-top: 1px solid var(--border);
|
||||
padding-top: 12px;
|
||||
margin-top: 8px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.total-price {
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
/* ===== Checkout ===== */
|
||||
.checkout-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 340px;
|
||||
gap: 28px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.checkout-form-wrapper {
|
||||
background: var(--card-bg);
|
||||
border-radius: var(--radius);
|
||||
padding: 32px;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.form-group input,
|
||||
.form-group textarea {
|
||||
width: 100%;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font-size: 15px;
|
||||
font-family: inherit;
|
||||
transition: border-color var(--transition);
|
||||
}
|
||||
|
||||
.form-group input:focus,
|
||||
.form-group textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.order-summary {
|
||||
background: var(--card-bg);
|
||||
border-radius: var(--radius);
|
||||
padding: 24px;
|
||||
box-shadow: var(--shadow);
|
||||
position: sticky;
|
||||
top: 90px;
|
||||
}
|
||||
|
||||
.order-summary h3 {
|
||||
font-size: 18px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.order-items {
|
||||
list-style: none;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.order-items li {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 10px 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 14px;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.order-items li span:last-child {
|
||||
white-space: nowrap;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.order-total {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
/* ===== Empty state ===== */
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 60px 20px;
|
||||
background: var(--card-bg);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.empty-icon {
|
||||
font-size: 48px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.empty-state p {
|
||||
font-size: 18px;
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
/* ===== Footer ===== */
|
||||
.footer {
|
||||
background: var(--primary);
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
padding: 40px 0;
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.footer-content {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.footer-brand .logo-text {
|
||||
color: white;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.footer-brand p {
|
||||
font-size: 13px;
|
||||
margin-top: 6px;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.footer-info {
|
||||
text-align: right;
|
||||
font-size: 13px;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
/* ===== Responsive ===== */
|
||||
@media (max-width: 900px) {
|
||||
.advantages-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
|
||||
.product-detail-grid {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 24px;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.cart-layout,
|
||||
.checkout-layout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.cart-item {
|
||||
grid-template-columns: 70px 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.cart-item-qty,
|
||||
.cart-item-total {
|
||||
grid-column: 2;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.hero h1 {
|
||||
font-size: 26px;
|
||||
}
|
||||
|
||||
.advantages-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.filters {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.filter-select {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.header-inner {
|
||||
height: 60px;
|
||||
}
|
||||
|
||||
.logo-text {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.footer-content {
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.footer-info {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.products-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 8.1 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 8.6 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 9.4 KiB |
|
After Width: | Height: | Size: 8.9 KiB |
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Phone Store — клиентский JavaScript
|
||||
* Интерактивные элементы интерфейса
|
||||
*/
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
// Автоматическое скрытие flash-сообщений через 4 секунды
|
||||
const flashes = document.querySelectorAll('.flash');
|
||||
flashes.forEach(function (flash) {
|
||||
setTimeout(function () {
|
||||
flash.style.transition = 'opacity 0.4s ease, transform 0.4s ease';
|
||||
flash.style.opacity = '0';
|
||||
flash.style.transform = 'translateX(30px)';
|
||||
setTimeout(function () {
|
||||
flash.remove();
|
||||
}, 400);
|
||||
}, 4000);
|
||||
});
|
||||
|
||||
// Подтверждение очистки корзины
|
||||
const clearForms = document.querySelectorAll('form[action*="clear_cart"]');
|
||||
clearForms.forEach(function (form) {
|
||||
form.addEventListener('submit', function (e) {
|
||||
if (!confirm('Вы уверены, что хотите очистить корзину?')) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Валидация формы оформления заказа на клиенте
|
||||
const checkoutForm = document.getElementById('checkout-form');
|
||||
if (checkoutForm) {
|
||||
checkoutForm.addEventListener('submit', function (e) {
|
||||
const name = document.getElementById('name').value.trim();
|
||||
const phone = document.getElementById('phone').value.trim();
|
||||
const address = document.getElementById('address').value.trim();
|
||||
|
||||
let errors = [];
|
||||
|
||||
if (name.length < 2) {
|
||||
errors.push('Имя должно содержать не менее 2 символов');
|
||||
}
|
||||
if (phone.length < 10) {
|
||||
errors.push('Введите корректный номер телефона');
|
||||
}
|
||||
if (address.length < 5) {
|
||||
errors.push('Адрес должен содержать не менее 5 символов');
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
e.preventDefault();
|
||||
alert(errors.join('\n'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Плавное появление карточек товаров
|
||||
const cards = document.querySelectorAll('.product-card');
|
||||
if (cards.length > 0 && 'IntersectionObserver' in window) {
|
||||
const observer = new IntersectionObserver(function (entries) {
|
||||
entries.forEach(function (entry) {
|
||||
if (entry.isIntersecting) {
|
||||
entry.target.style.opacity = '1';
|
||||
entry.target.style.transform = 'translateY(0)';
|
||||
observer.unobserve(entry.target);
|
||||
}
|
||||
});
|
||||
}, { threshold: 0.1 });
|
||||
|
||||
cards.forEach(function (card, index) {
|
||||
card.style.opacity = '0';
|
||||
card.style.transform = 'translateY(20px)';
|
||||
card.style.transition = 'opacity 0.4s ease ' + (index * 0.05) + 's, transform 0.4s ease ' + (index * 0.05) + 's';
|
||||
observer.observe(card);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}Phone Store{% endblock %} — Интернет-магазин смартфонов</title>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<!-- Шапка сайта -->
|
||||
<header class="header">
|
||||
<div class="container header-inner">
|
||||
<a href="{{ url_for('index') }}" class="logo">
|
||||
<span class="logo-icon">📱</span>
|
||||
<span class="logo-text">Phone<span class="logo-accent">Store</span></span>
|
||||
</a>
|
||||
|
||||
<nav class="nav">
|
||||
<a href="{{ url_for('index') }}" class="nav-link">Каталог</a>
|
||||
<a href="{{ url_for('cart') }}" class="nav-link cart-link">
|
||||
Корзина
|
||||
{% if cart_count > 0 %}
|
||||
<span class="cart-badge" id="cart-badge">{{ cart_count }}</span>
|
||||
{% endif %}
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Сообщения (flash) -->
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
<div class="flash-container">
|
||||
{% for category, message in messages %}
|
||||
<div class="flash flash-{{ category }}">
|
||||
<span>{{ message }}</span>
|
||||
<button class="flash-close" onclick="this.parentElement.remove()">×</button>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<!-- Основной контент -->
|
||||
<main class="main">
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
|
||||
<!-- Подвал -->
|
||||
<footer class="footer">
|
||||
<div class="container">
|
||||
<div class="footer-content">
|
||||
<div class="footer-brand">
|
||||
<span class="logo-text">Phone<span class="logo-accent">Store</span></span>
|
||||
<p>Ваш надёжный магазин смартфонов</p>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<p>© 2024 Phone Store. Учебный проект.</p>
|
||||
<p>Все цены указаны в рублях.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
|
||||
{% block scripts %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,73 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Корзина{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="cart-section">
|
||||
<div class="container">
|
||||
<h1 class="page-title">Корзина</h1>
|
||||
|
||||
{% if items %}
|
||||
<div class="cart-layout">
|
||||
<div class="cart-items">
|
||||
{% for item in items %}
|
||||
<div class="cart-item">
|
||||
<div class="cart-item-image">
|
||||
<img src="{{ url_for('static', filename='images/' + item.image) }}"
|
||||
alt="{{ item.name }}"
|
||||
onerror="this.src='https://via.placeholder.com/100x100?text=Phone'">
|
||||
</div>
|
||||
<div class="cart-item-info">
|
||||
<h3>{{ item.name }}</h3>
|
||||
<p class="cart-item-price">{{ "{:,.0f}".format(item.price).replace(',', ' ') }} ₽</p>
|
||||
</div>
|
||||
<div class="cart-item-qty">
|
||||
<form action="{{ url_for('update_cart', product_id=item.id) }}" method="POST" class="qty-form">
|
||||
<input type="hidden" name="action" value="decrease">
|
||||
<button type="submit" class="qty-btn">−</button>
|
||||
</form>
|
||||
<span class="qty-value">{{ item.quantity }}</span>
|
||||
<form action="{{ url_for('update_cart', product_id=item.id) }}" method="POST" class="qty-form">
|
||||
<input type="hidden" name="action" value="increase">
|
||||
<button type="submit" class="qty-btn">+</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="cart-item-total">
|
||||
{{ "{:,.0f}".format(item.price * item.quantity).replace(',', ' ') }} ₽
|
||||
</div>
|
||||
<form action="{{ url_for('update_cart', product_id=item.id) }}" method="POST">
|
||||
<input type="hidden" name="action" value="remove">
|
||||
<button type="submit" class="btn-remove" title="Удалить">×</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<div class="cart-summary">
|
||||
<h3>Итого</h3>
|
||||
<div class="summary-row">
|
||||
<span>Товаров:</span>
|
||||
<span>{{ cart_count }}</span>
|
||||
</div>
|
||||
<div class="summary-row total-row">
|
||||
<span>Сумма:</span>
|
||||
<span class="total-price">{{ "{:,.0f}".format(total).replace(',', ' ') }} ₽</span>
|
||||
</div>
|
||||
<a href="{{ url_for('checkout') }}" class="btn btn-primary btn-large btn-block">
|
||||
Оформить заказ
|
||||
</a>
|
||||
<form action="{{ url_for('clear_cart') }}" method="POST" style="margin-top: 12px;">
|
||||
<button type="submit" class="btn btn-outline btn-block">Очистить корзину</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon">🛒</div>
|
||||
<p>Ваша корзина пуста</p>
|
||||
<a href="{{ url_for('index') }}" class="btn btn-primary">Перейти в каталог</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,61 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Оформление заказа{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="checkout-section">
|
||||
<div class="container">
|
||||
<h1 class="page-title">Оформление заказа</h1>
|
||||
|
||||
<div class="checkout-layout">
|
||||
<div class="checkout-form-wrapper">
|
||||
<form method="POST" class="checkout-form" id="checkout-form">
|
||||
<div class="form-group">
|
||||
<label for="name">Имя покупателя *</label>
|
||||
<input type="text" id="name" name="name" required
|
||||
value="{{ name or '' }}"
|
||||
placeholder="Иван Иванов"
|
||||
minlength="2">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="phone">Номер телефона *</label>
|
||||
<input type="tel" id="phone" name="phone" required
|
||||
value="{{ phone or '' }}"
|
||||
placeholder="+7 (999) 123-45-67"
|
||||
minlength="10">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="address">Адрес доставки *</label>
|
||||
<textarea id="address" name="address" required
|
||||
rows="3"
|
||||
placeholder="Город, улица, дом, квартира"
|
||||
minlength="5">{{ address or '' }}</textarea>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary btn-large btn-block">
|
||||
Подтвердить заказ
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="order-summary">
|
||||
<h3>Ваш заказ</h3>
|
||||
<ul class="order-items">
|
||||
{% for item in items %}
|
||||
<li>
|
||||
<span>{{ item.name }} × {{ item.quantity }}</span>
|
||||
<span>{{ "{:,.0f}".format(item.price * item.quantity).replace(',', ' ') }} ₽</span>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
<div class="order-total">
|
||||
<span>Итого:</span>
|
||||
<span>{{ "{:,.0f}".format(total).replace(',', ' ') }} ₽</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,130 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Каталог{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<!-- Hero-блок -->
|
||||
<section class="hero">
|
||||
<div class="container">
|
||||
<div class="hero-content">
|
||||
<h1>Смартфоны для каждого</h1>
|
||||
<p>Большой выбор моделей от ведущих производителей. Быстрая доставка и гарантия качества.</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Преимущества -->
|
||||
<section class="advantages">
|
||||
<div class="container">
|
||||
<div class="advantages-grid">
|
||||
<div class="advantage-card">
|
||||
<div class="advantage-icon">🚚</div>
|
||||
<h3>Быстрая доставка</h3>
|
||||
<p>Доставим заказ в течение 1–3 дней</p>
|
||||
</div>
|
||||
<div class="advantage-card">
|
||||
<div class="advantage-icon">✅</div>
|
||||
<h3>Официальная гарантия</h3>
|
||||
<p>Все товары с гарантией производителя</p>
|
||||
</div>
|
||||
<div class="advantage-card">
|
||||
<div class="advantage-icon">💳</div>
|
||||
<h3>Удобная оплата</h3>
|
||||
<p>Оплата при получении или онлайн</p>
|
||||
</div>
|
||||
<div class="advantage-card">
|
||||
<div class="advantage-icon">🔄</div>
|
||||
<h3>Легкий возврат</h3>
|
||||
<p>14 дней на возврат без вопросов</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Каталог -->
|
||||
<section class="catalog">
|
||||
<div class="container">
|
||||
<div class="catalog-header">
|
||||
<h2>Каталог смартфонов</h2>
|
||||
</div>
|
||||
|
||||
<!-- Фильтры и поиск -->
|
||||
<form class="filters" method="GET" action="{{ url_for('index') }}">
|
||||
<div class="filter-group search-group">
|
||||
<input type="text" name="search" placeholder="Поиск по названию или бренду..."
|
||||
value="{{ search }}" class="search-input">
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<select name="brand" class="filter-select">
|
||||
<option value="">Все бренды</option>
|
||||
{% for b in brands %}
|
||||
<option value="{{ b.brand }}" {% if selected_brand == b.brand %}selected{% endif %}>
|
||||
{{ b.brand }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<select name="sort" class="filter-select">
|
||||
<option value="">Сортировка</option>
|
||||
<option value="price_asc" {% if sort == 'price_asc' %}selected{% endif %}>
|
||||
Цена: по возрастанию
|
||||
</option>
|
||||
<option value="price_desc" {% if sort == 'price_desc' %}selected{% endif %}>
|
||||
Цена: по убыванию
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary">Применить</button>
|
||||
{% if search or selected_brand or sort %}
|
||||
<a href="{{ url_for('index') }}" class="btn btn-outline">Сбросить</a>
|
||||
{% endif %}
|
||||
</form>
|
||||
|
||||
<!-- Сетка товаров -->
|
||||
{% if products %}
|
||||
<div class="products-grid">
|
||||
{% for product in products %}
|
||||
<article class="product-card">
|
||||
<a href="{{ url_for('product_detail', product_id=product.id) }}" class="product-image-link">
|
||||
<div class="product-image">
|
||||
<img src="{{ url_for('static', filename='images/' + product.image) }}"
|
||||
alt="{{ product.name }}"
|
||||
onerror="this.src='https://via.placeholder.com/300x300?text={{ product.brand }}'">
|
||||
</div>
|
||||
</a>
|
||||
<div class="product-info">
|
||||
<span class="product-brand">{{ product.brand }}</span>
|
||||
<a href="{{ url_for('product_detail', product_id=product.id) }}" class="product-name">
|
||||
{{ product.name }}
|
||||
</a>
|
||||
<div class="product-specs">
|
||||
<span>{{ product.storage }}</span>
|
||||
<span>{{ product.ram }} ОЗУ</span>
|
||||
<span>{{ product.screen }}</span>
|
||||
</div>
|
||||
<div class="product-footer">
|
||||
<span class="product-price">{{ "{:,.0f}".format(product.price).replace(',', ' ') }} ₽</span>
|
||||
<form action="{{ url_for('add_to_cart', product_id=product.id) }}" method="POST">
|
||||
<input type="hidden" name="next" value="{{ request.url }}">
|
||||
<button type="submit" class="btn btn-cart" title="Добавить в корзину">
|
||||
В корзину
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="empty-state">
|
||||
<p>По вашему запросу ничего не найдено</p>
|
||||
<a href="{{ url_for('index') }}" class="btn btn-primary">Показать все товары</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,72 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}{{ product.name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="product-detail">
|
||||
<div class="container">
|
||||
<nav class="breadcrumb">
|
||||
<a href="{{ url_for('index') }}">Каталог</a>
|
||||
<span>/</span>
|
||||
<span>{{ product.name }}</span>
|
||||
</nav>
|
||||
|
||||
<div class="product-detail-grid">
|
||||
<div class="product-detail-image">
|
||||
<img src="{{ url_for('static', filename='images/' + product.image) }}"
|
||||
alt="{{ product.name }}"
|
||||
onerror="this.src='https://via.placeholder.com/500x500?text={{ product.brand }}'">
|
||||
</div>
|
||||
|
||||
<div class="product-detail-info">
|
||||
<span class="product-brand">{{ product.brand }}</span>
|
||||
<h1 class="product-title">{{ product.name }}</h1>
|
||||
<div class="product-price-large">
|
||||
{{ "{:,.0f}".format(product.price).replace(',', ' ') }} ₽
|
||||
</div>
|
||||
|
||||
<div class="product-description">
|
||||
<p>{{ product.description }}</p>
|
||||
</div>
|
||||
|
||||
<div class="specs-table">
|
||||
<h3>Характеристики</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Производитель</td>
|
||||
<td>{{ product.brand }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Память</td>
|
||||
<td>{{ product.storage }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Оперативная память</td>
|
||||
<td>{{ product.ram }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Диагональ экрана</td>
|
||||
<td>{{ product.screen }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Аккумулятор</td>
|
||||
<td>{{ product.battery }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Особенности</td>
|
||||
<td>{{ product.features }}</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<form action="{{ url_for('add_to_cart', product_id=product.id) }}" method="POST" class="add-to-cart-form">
|
||||
<input type="hidden" name="next" value="{{ url_for('product_detail', product_id=product.id) }}">
|
||||
<button type="submit" class="btn btn-primary btn-large">
|
||||
Добавить в корзину
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||