commit 7300f1319503873cfe2a07fe161cc023e2f28b40 Author: Ksusha Date: Sat Dec 5 14:35:57 2026 +0300 feat: initial phone store application diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..7112b24 --- /dev/null +++ b/.env.example @@ -0,0 +1 @@ +SECRET_KEY=replace_with_a_random_secret_key diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c748cbe --- /dev/null +++ b/.gitignore @@ -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 diff --git a/Procfile b/Procfile new file mode 100644 index 0000000..ef4bee3 --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: python init_db.py && gunicorn app:app diff --git a/README.md b/README.md new file mode 100644 index 0000000..1e7514a --- /dev/null +++ b/README.md @@ -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) + +## Автор + +Учебный проект (лабораторная работа) diff --git a/app.py b/app.py new file mode 100644 index 0000000..f245233 --- /dev/null +++ b/app.py @@ -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/') +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/', 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/', 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) diff --git a/init_db.py b/init_db.py new file mode 100644 index 0000000..7217f97 --- /dev/null +++ b/init_db.py @@ -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() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..7eb63e4 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +Flask==3.0.3 +gunicorn==21.2.0 +python-dotenv==1.2.4 diff --git a/runtime.txt b/runtime.txt new file mode 100644 index 0000000..546f3c8 --- /dev/null +++ b/runtime.txt @@ -0,0 +1 @@ +python-3.11.9 diff --git a/static/css/style.css b/static/css/style.css new file mode 100644 index 0000000..e8522ef --- /dev/null +++ b/static/css/style.css @@ -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; + } +} diff --git a/static/images/a55.jpg b/static/images/a55.jpg new file mode 100644 index 0000000..edea6d2 Binary files /dev/null and b/static/images/a55.jpg differ diff --git a/static/images/gt6.jpg b/static/images/gt6.jpg new file mode 100644 index 0000000..db1559f Binary files /dev/null and b/static/images/gt6.jpg differ diff --git a/static/images/iphone14.jpg b/static/images/iphone14.jpg new file mode 100644 index 0000000..4b1daa9 Binary files /dev/null and b/static/images/iphone14.jpg differ diff --git a/static/images/iphone15pro.jpg b/static/images/iphone15pro.jpg new file mode 100644 index 0000000..bca7526 Binary files /dev/null and b/static/images/iphone15pro.jpg differ diff --git a/static/images/magic6pro.jpg b/static/images/magic6pro.jpg new file mode 100644 index 0000000..8b4b837 Binary files /dev/null and b/static/images/magic6pro.jpg differ diff --git a/static/images/note13pro.jpg b/static/images/note13pro.jpg new file mode 100644 index 0000000..c95d2ae Binary files /dev/null and b/static/images/note13pro.jpg differ diff --git a/static/images/pixel8pro.jpg b/static/images/pixel8pro.jpg new file mode 100644 index 0000000..bec8605 Binary files /dev/null and b/static/images/pixel8pro.jpg differ diff --git a/static/images/s24ultra.jpg b/static/images/s24ultra.jpg new file mode 100644 index 0000000..66a50f2 Binary files /dev/null and b/static/images/s24ultra.jpg differ diff --git a/static/images/x9b.jpg b/static/images/x9b.jpg new file mode 100644 index 0000000..c82a10c Binary files /dev/null and b/static/images/x9b.jpg differ diff --git a/static/images/xiaomi14.jpg b/static/images/xiaomi14.jpg new file mode 100644 index 0000000..9fc3aaf Binary files /dev/null and b/static/images/xiaomi14.jpg differ diff --git a/static/js/script.js b/static/js/script.js new file mode 100644 index 0000000..aacf9c4 --- /dev/null +++ b/static/js/script.js @@ -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); + }); + } +}); diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..bb0ad54 --- /dev/null +++ b/templates/base.html @@ -0,0 +1,71 @@ + + + + + + {% block title %}Phone Store{% endblock %} — Интернет-магазин смартфонов + + + + + + + +
+ +
+ + + {% with messages = get_flashed_messages(with_categories=true) %} + {% if messages %} +
+ {% for category, message in messages %} +
+ {{ message }} + +
+ {% endfor %} +
+ {% endif %} + {% endwith %} + + +
+ {% block content %}{% endblock %} +
+ + +
+
+ +
+
+ + + {% block scripts %}{% endblock %} + + diff --git a/templates/cart.html b/templates/cart.html new file mode 100644 index 0000000..0437c0a --- /dev/null +++ b/templates/cart.html @@ -0,0 +1,73 @@ +{% extends "base.html" %} + +{% block title %}Корзина{% endblock %} + +{% block content %} +
+
+

Корзина

+ + {% if items %} +
+
+ {% for item in items %} +
+
+ {{ item.name }} +
+
+

{{ item.name }}

+

{{ "{:,.0f}".format(item.price).replace(',', ' ') }} ₽

+
+
+
+ + +
+ {{ item.quantity }} +
+ + +
+
+
+ {{ "{:,.0f}".format(item.price * item.quantity).replace(',', ' ') }} ₽ +
+
+ + +
+
+ {% endfor %} +
+ +
+

Итого

+
+ Товаров: + {{ cart_count }} +
+
+ Сумма: + {{ "{:,.0f}".format(total).replace(',', ' ') }} ₽ +
+ + Оформить заказ + +
+ +
+
+
+ {% else %} +
+
🛒
+

Ваша корзина пуста

+ Перейти в каталог +
+ {% endif %} +
+
+{% endblock %} diff --git a/templates/checkout.html b/templates/checkout.html new file mode 100644 index 0000000..ba58379 --- /dev/null +++ b/templates/checkout.html @@ -0,0 +1,61 @@ +{% extends "base.html" %} + +{% block title %}Оформление заказа{% endblock %} + +{% block content %} +
+
+

Оформление заказа

+ +
+
+
+
+ + +
+ +
+ + +
+ +
+ + +
+ + +
+
+ +
+

Ваш заказ

+
    + {% for item in items %} +
  • + {{ item.name }} × {{ item.quantity }} + {{ "{:,.0f}".format(item.price * item.quantity).replace(',', ' ') }} ₽ +
  • + {% endfor %} +
+
+ Итого: + {{ "{:,.0f}".format(total).replace(',', ' ') }} ₽ +
+
+
+
+
+{% endblock %} diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..268d589 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,130 @@ +{% extends "base.html" %} + +{% block title %}Каталог{% endblock %} + +{% block content %} + +
+
+
+

Смартфоны для каждого

+

Большой выбор моделей от ведущих производителей. Быстрая доставка и гарантия качества.

+
+
+
+ + +
+
+
+
+
🚚
+

Быстрая доставка

+

Доставим заказ в течение 1–3 дней

+
+
+
✅
+

Официальная гарантия

+

Все товары с гарантией производителя

+
+
+
💳
+

Удобная оплата

+

Оплата при получении или онлайн

+
+
+
🔄
+

Легкий возврат

+

14 дней на возврат без вопросов

+
+
+
+
+ + +
+
+
+

Каталог смартфонов

+
+ + +
+
+ +
+ +
+ +
+ +
+ +
+ + + {% if search or selected_brand or sort %} + Сбросить + {% endif %} +
+ + + {% if products %} +
+ {% for product in products %} +
+ +
+ {{ product.name }} +
+
+
+ {{ product.brand }} + + {{ product.name }} + +
+ {{ product.storage }} + {{ product.ram }} ОЗУ + {{ product.screen }} +
+ +
+
+ {% endfor %} +
+ {% else %} +
+

По вашему запросу ничего не найдено

+ Показать все товары +
+ {% endif %} +
+
+{% endblock %} diff --git a/templates/product.html b/templates/product.html new file mode 100644 index 0000000..5ceeb91 --- /dev/null +++ b/templates/product.html @@ -0,0 +1,72 @@ +{% extends "base.html" %} + +{% block title %}{{ product.name }}{% endblock %} + +{% block content %} +
+
+ + +
+
+ {{ product.name }} +
+ +
+ {{ product.brand }} +

{{ product.name }}

+
+ {{ "{:,.0f}".format(product.price).replace(',', ' ') }} ₽ +
+ +
+

{{ product.description }}

+
+ +
+

Характеристики

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Производитель{{ product.brand }}
Память{{ product.storage }}
Оперативная память{{ product.ram }}
Диагональ экрана{{ product.screen }}
Аккумулятор{{ product.battery }}
Особенности{{ product.features }}
+
+ +
+ + +
+
+
+
+
+{% endblock %}