Spaces:
Sleeping
Sleeping
| from flask import Flask, render_template_string, request, redirect, url_for | |
| import json | |
| import os | |
| import logging | |
| import threading | |
| import time | |
| from datetime import datetime | |
| from huggingface_hub import HfApi, hf_hub_download | |
| from huggingface_hub.utils import RepositoryNotFoundError | |
| from werkzeug.utils import secure_filename | |
| app = Flask(__name__) | |
| DATA_FILE = 'data.json' | |
| REPO_ID = "Kgshop/teenager" | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN") | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") | |
| LOGO_URL = "https://huggingface.co/spaces/Teenagerkg/optom/resolve/main/PXL_20250419_062456154~2.jpg" | |
| logging.basicConfig(level=logging.DEBUG) | |
| def load_data(): | |
| try: | |
| download_db_from_hf() | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info("Данные успешно загружены из JSON") | |
| if not isinstance(data, dict) or 'products' not in data or 'categories' not in data: | |
| logging.warning("Структура JSON неверна, инициализация...") | |
| if isinstance(data, list): | |
| return {'products': [], 'categories': data} | |
| else: | |
| return {'products': [], 'categories': []} | |
| if 'categories' not in data or not isinstance(data['categories'], list): | |
| data['categories'] = [] | |
| if 'products' not in data or not isinstance(data['products'], list): | |
| data['products'] = [] | |
| return data | |
| except FileNotFoundError: | |
| logging.warning("Локальный файл базы данных не найден.") | |
| return {'products': [], 'categories': []} | |
| except json.JSONDecodeError: | |
| logging.error("Ошибка: Невозможно декодировать JSON файл.") | |
| return {'products': [], 'categories': []} | |
| except RepositoryNotFoundError: | |
| logging.warning("Репозиторий HF не найден. Используется/создается локальная база.") | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| if not isinstance(data, dict) or 'products' not in data or 'categories' not in data: | |
| if isinstance(data, list): | |
| return {'products': [], 'categories': data} | |
| else: | |
| return {'products': [], 'categories': []} | |
| if 'categories' not in data or not isinstance(data['categories'], list): | |
| data['categories'] = [] | |
| if 'products' not in data or not isinstance(data['products'], list): | |
| data['products'] = [] | |
| return data | |
| except (FileNotFoundError, json.JSONDecodeError): | |
| logging.warning("Локальный файл также не найден или поврежден.") | |
| return {'products': [], 'categories': []} | |
| except Exception as e: | |
| logging.error(f"Произошла ошибка при загрузке данных: {e}") | |
| return {'products': [], 'categories': []} | |
| def save_data(data): | |
| if not isinstance(data, dict): | |
| logging.error("Попытка сохранить данные не в формате словаря. Сохранение отменено.") | |
| return | |
| if 'products' not in data or not isinstance(data['products'], list): | |
| data['products'] = [] | |
| logging.warning("Ключ 'products' отсутствует или не является списком. Инициализирован как пустой список.") | |
| if 'categories' not in data or not isinstance(data['categories'], list): | |
| data['categories'] = [] | |
| logging.warning("Ключ 'categories' отсутствует или не является списком. Инициализирован как пустой список.") | |
| try: | |
| with open(DATA_FILE, 'w', encoding='utf-8') as file: | |
| json.dump(data, file, ensure_ascii=False, indent=4) | |
| logging.info("Данные успешно сохранены в JSON") | |
| upload_db_to_hf() | |
| except Exception as e: | |
| logging.error(f"Ошибка при сохранении данных: {e}") | |
| def upload_db_to_hf(): | |
| if not HF_TOKEN_WRITE: | |
| logging.warning("HF_TOKEN_WRITE не установлен. Загрузка на Hugging Face пропущена.") | |
| return | |
| if not os.path.exists(DATA_FILE): | |
| logging.warning(f"Файл {DATA_FILE} не найден для загрузки на Hugging Face.") | |
| return | |
| try: | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=DATA_FILE, | |
| path_in_repo=DATA_FILE, | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Автоматическое резервное копирование базы данных {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" | |
| ) | |
| logging.info("Резервная копия JSON базы успешно загружена на Hugging Face.") | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке резервной копии: {e}") | |
| def download_db_from_hf(): | |
| if not HF_TOKEN_READ: | |
| logging.warning("HF_TOKEN_READ не установлен. Скачивание с Hugging Face пропущено.") | |
| return | |
| try: | |
| hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=DATA_FILE, | |
| repo_type="dataset", | |
| token=HF_TOKEN_READ, | |
| local_dir=".", | |
| local_dir_use_symlinks=False, | |
| force_download=True | |
| ) | |
| logging.info("JSON база успешно скачана из Hugging Face.") | |
| except RepositoryNotFoundError as e: | |
| logging.error(f"Репозиторий не найден: {e}") | |
| raise | |
| except Exception as e: | |
| logging.error(f"Ошибка при скачивании JSON базы: {e}") | |
| def periodic_backup(): | |
| while True: | |
| time.sleep(800) | |
| logging.info("Запуск периодического резервного копирования...") | |
| upload_db_to_hf() | |
| def catalog(): | |
| data = load_data() | |
| products = sorted(data.get('products', []), key=lambda x: x.get('added_at', ''), reverse=True) | |
| categories = data.get('categories', []) | |
| catalog_html = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>TeenAger - детская одежда оптом </title> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css"> | |
| <style> | |
| :root { | |
| --primary-color: #FFA726; | |
| --secondary-color: #FFCA28; | |
| --text-color: #333; | |
| --bg-color: #FFF8E1; | |
| --light-text: #fff; | |
| --shadow-color: rgba(0, 0, 0, 0.1); | |
| --accent-color: #D84315; | |
| --hover-primary-color: #FB8C00; | |
| --hover-secondary-color: #FFA000; | |
| } | |
| * { | |
| margin: 0; | |
| padding: 0; | |
| box-sizing: border-box; | |
| } | |
| body { | |
| font-family: 'Poppins', sans-serif; | |
| background-color: var(--bg-color); | |
| color: var(--text-color); | |
| line-height: 1.6; | |
| transition: background-color 0.3s, color 0.3s; | |
| } | |
| .container { | |
| max-width: 1300px; | |
| margin: 0 auto; | |
| padding: 20px; | |
| } | |
| .header { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| padding: 15px 0; | |
| border-bottom: 1px solid var(--primary-color); | |
| } | |
| .header-logo { | |
| width: 60px; | |
| height: 60px; | |
| border-radius: 50%; | |
| object-fit: cover; | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| transition: transform 0.3s ease, box-shadow 0.3s ease; | |
| } | |
| .header-logo:hover { | |
| transform: scale(1.1); | |
| box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3); | |
| } | |
| .header h1 { | |
| font-size: 1.5rem; | |
| font-weight: 600; | |
| margin-left: 15px; | |
| color: var(--primary-color); | |
| } | |
| .filters-container { | |
| margin: 20px 0; | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| justify-content: center; | |
| } | |
| .search-container { | |
| margin: 20px 0; | |
| text-align: center; | |
| } | |
| #search-input { | |
| width: 90%; | |
| max-width: 600px; | |
| padding: 12px 18px; | |
| font-size: 1rem; | |
| border: 1px solid var(--secondary-color); | |
| border-radius: 8px; | |
| outline: none; | |
| box-shadow: 0 2px 5px var(--shadow-color); | |
| transition: all 0.3s ease; | |
| } | |
| #search-input:focus { | |
| border-color: var(--primary-color); | |
| box-shadow: 0 4px 15px rgba(255, 167, 38, 0.3); | |
| } | |
| .category-filter { | |
| padding: 8px 16px; | |
| border: 1px solid var(--secondary-color); | |
| border-radius: 8px; | |
| background-color: var(--light-text); | |
| color: var(--text-color); | |
| cursor: pointer; | |
| transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); | |
| font-size: 0.9rem; | |
| font-weight: 400; | |
| } | |
| .category-filter.active, .category-filter:hover { | |
| background-color: var(--primary-color); | |
| color: var(--light-text); | |
| border-color: var(--primary-color); | |
| box-shadow: 0 2px 10px rgba(255, 167, 38, 0.4); | |
| } | |
| .products-grid { | |
| display: grid; | |
| grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); | |
| gap: 20px; | |
| padding: 10px; | |
| } | |
| @media (min-width: 600px) { | |
| .products-grid { | |
| grid-template-columns: repeat(2, minmax(200px, 1fr)); | |
| } | |
| } | |
| @media (min-width: 900px) { | |
| .products-grid { | |
| grid-template-columns: repeat(3, minmax(200px, 1fr)); | |
| } | |
| } | |
| @media (min-width: 1200px) { | |
| .products-grid { | |
| grid-template-columns: repeat(4, minmax(200px, 1fr)); | |
| } | |
| } | |
| .product { | |
| background: var(--light-text); | |
| border-radius: 15px; | |
| padding: 15px; | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; | |
| overflow: hidden; | |
| display: flex; | |
| flex-direction: column; | |
| height: 100%; | |
| } | |
| .product:hover { | |
| transform: translateY(-5px) scale(1.02); | |
| box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15); | |
| } | |
| .product-image { | |
| width: 100%; | |
| aspect-ratio: 1 / 1.1; | |
| background-color: #fff; | |
| border-radius: 10px; | |
| overflow: hidden; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| margin-bottom: 10px; | |
| } | |
| .product-image img { | |
| max-width: 100%; | |
| max-height: 100%; | |
| object-fit: contain; | |
| transition: transform 0.3s ease; | |
| } | |
| .product-image img:hover { | |
| transform: scale(1.1); | |
| } | |
| .product h2 { | |
| font-size: 1rem; | |
| font-weight: 600; | |
| margin: 10px 0 5px 0; | |
| text-align: center; | |
| white-space: normal; | |
| overflow: hidden; | |
| } | |
| .product-price { | |
| font-size: 1.1rem; | |
| color: var(--accent-color); | |
| font-weight: 700; | |
| text-align: center; | |
| margin: 5px 0; | |
| } | |
| .product-description { | |
| font-size: 0.8rem; | |
| color: #718096; | |
| text-align: center; | |
| margin-bottom: 15px; | |
| overflow: hidden; | |
| text-overflow: ellipsis; | |
| white-space: nowrap; | |
| flex-grow: 1; | |
| } | |
| .product-buttons { | |
| margin-top: auto; | |
| display: flex; | |
| flex-direction: column; | |
| gap: 5px; | |
| } | |
| .product-button { | |
| display: block; | |
| width: 100%; | |
| padding: 8px; | |
| border: none; | |
| border-radius: 8px; | |
| background-color: var(--primary-color); | |
| color: var(--light-text); | |
| font-size: 0.8rem; | |
| font-weight: 500; | |
| cursor: pointer; | |
| transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); | |
| text-align: center; | |
| text-decoration: none; | |
| } | |
| .product-button:hover { | |
| background-color: var(--hover-primary-color); | |
| box-shadow: 0 4px 15px rgba(251, 140, 0, 0.4); | |
| transform: translateY(-2px); | |
| } | |
| .add-to-cart { | |
| background-color: var(--secondary-color); | |
| } | |
| .add-to-cart:hover { | |
| background-color: var(--hover-secondary-color); | |
| box-shadow: 0 4px 15px rgba(255, 160, 0, 0.4); | |
| } | |
| #cart-button { | |
| position: fixed; | |
| bottom: 20px; | |
| right: 20px; | |
| background-color: var(--primary-color); | |
| color: var(--light-text); | |
| border: none; | |
| border-radius: 50%; | |
| width: 50px; | |
| height: 50px; | |
| font-size: 1.2rem; | |
| cursor: pointer; | |
| display: none; | |
| box-shadow: 0 4px 15px rgba(255, 167, 38, 0.4); | |
| transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); | |
| z-index: 1000; | |
| align-items: center; | |
| justify-content: center; | |
| } | |
| #cart-button:hover { | |
| background-color: var(--hover-primary-color); | |
| } | |
| .modal { | |
| display: none; | |
| position: fixed; | |
| z-index: 1001; | |
| left: 0; | |
| top: 0; | |
| width: 100%; | |
| height: 100%; | |
| background-color: rgba(0,0,0,0.5); | |
| backdrop-filter: blur(5px); | |
| } | |
| .modal-content { | |
| background: var(--light-text); | |
| margin: 5% auto; | |
| padding: 20px; | |
| border-radius: 15px; | |
| width: 90%; | |
| max-width: 700px; | |
| box-shadow: 0 10px 30px rgba(0,0,0,0.2); | |
| animation: slideIn 0.3s ease-out; | |
| max-height: 85vh; | |
| overflow-y: auto; | |
| display: flex; | |
| flex-direction: column; | |
| } | |
| #modalContent, #cartContent { | |
| overflow-y: auto; | |
| flex-grow: 1; | |
| padding-right: 10px; | |
| } | |
| #cartContent { | |
| max-height: 60vh; | |
| margin-bottom: 15px; | |
| } | |
| @keyframes slideIn { | |
| from { transform: translateY(-50px); opacity: 0; } | |
| to { transform: translateY(0); opacity: 1; } | |
| } | |
| .close { | |
| float: right; | |
| font-size: 1.5rem; | |
| color: #718096; | |
| cursor: pointer; | |
| transition: color 0.3s; | |
| align-self: flex-end; | |
| margin-bottom: 10px; | |
| } | |
| .close:hover { | |
| color: var(--primary-color); | |
| } | |
| .cart-item { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| padding: 15px 0; | |
| border-bottom: 1px solid var(--secondary-color); | |
| gap: 10px; | |
| } | |
| .cart-item-details { | |
| display: flex; | |
| align-items: center; | |
| gap: 15px; | |
| flex-grow: 1; | |
| } | |
| .cart-item img { | |
| width: 50px; | |
| height: 50px; | |
| object-fit: contain; | |
| border-radius: 8px; | |
| flex-shrink: 0; | |
| } | |
| .cart-item-info { | |
| font-size: 0.9rem; | |
| } | |
| .cart-item-info strong { | |
| display: block; | |
| margin-bottom: 3px; | |
| } | |
| .cart-item-total { | |
| font-weight: bold; | |
| white-space: nowrap; | |
| flex-shrink: 0; | |
| } | |
| .quantity-input, .color-select { | |
| width: 100%; | |
| max-width: 150px; | |
| padding: 8px; | |
| border: 1px solid var(--secondary-color); | |
| border-radius: 8px; | |
| font-size: 1rem; | |
| margin: 5px 0; | |
| } | |
| .clear-cart { | |
| background-color: #ef4444; | |
| } | |
| .clear-cart:hover { | |
| background-color: #dc2626; | |
| box-shadow: 0 4px 15px rgba(220, 38, 38, 0.4); | |
| } | |
| .order-button { | |
| background-color: var(--secondary-color); | |
| } | |
| .order-button:hover { | |
| background-color: var(--hover-secondary-color); | |
| box-shadow: 0 4px 15px rgba(255, 160, 0, 0.4); | |
| } | |
| .modal-footer { | |
| margin-top: auto; | |
| padding-top: 15px; | |
| text-align: right; | |
| border-top: 1px solid var(--secondary-color); | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| gap: 10px; | |
| } | |
| .modal-footer strong { | |
| margin-right: auto; | |
| } | |
| @media (max-width: 768px) { | |
| .header h1 { | |
| font-size: 1.2rem; | |
| } | |
| #search-input { | |
| padding: 10px 15px; | |
| } | |
| .category-filter { | |
| padding: 6px 12px; | |
| font-size: 0.8rem; | |
| } | |
| .product h2 { | |
| font-size: 0.9rem; | |
| } | |
| .product-price { | |
| font-size: 1rem; | |
| } | |
| .product-description { | |
| font-size: 0.75rem; | |
| } | |
| .product-button { | |
| padding: 6px; | |
| font-size: 0.75rem; | |
| } | |
| #cart-button { | |
| width: 45px; | |
| height: 45px; | |
| font-size: 1.1rem; | |
| } | |
| .modal-content { | |
| padding: 15px; | |
| max-height: 90vh; | |
| } | |
| #cartContent { | |
| max-height: 65vh; | |
| } | |
| .cart-item { | |
| flex-wrap: wrap; | |
| } | |
| .cart-item-details { | |
| flex-basis: 100%; | |
| margin-bottom: 5px; | |
| } | |
| } | |
| @media (max-width: 480px) { | |
| .header { | |
| flex-direction: column; | |
| align-items: center; | |
| text-align: center; | |
| } | |
| .header h1 { | |
| margin-left: 0; | |
| margin-top: 10px; | |
| } | |
| .filters-container { | |
| justify-content: flex-start; | |
| gap: 5px; | |
| } | |
| .category-filter { | |
| padding: 5px 10px; | |
| } | |
| .modal-footer { | |
| flex-direction: column; | |
| align-items: flex-end; | |
| } | |
| .modal-footer strong { | |
| margin-bottom: 10px; | |
| align-self: flex-start; | |
| } | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <img src="''' + LOGO_URL + '''" alt="Logo" class="header-logo"> | |
| <h1>Каталог</h1> | |
| </div> | |
| <div class="filters-container"> | |
| <button class="category-filter active" data-category="all">Все категории</button> | |
| {% for category in categories %} | |
| <button class="category-filter" data-category="{{ category }}">{{ category }}</button> | |
| {% endfor %} | |
| </div> | |
| <div class="search-container"> | |
| <input type="text" id="search-input" placeholder="Поиск товаров..."> | |
| </div> | |
| <div class="products-grid" id="products-grid"> | |
| {% for product in products %} | |
| <div class="product" | |
| data-name="{{ product['name']|lower }}" | |
| data-description="{{ product['description']|lower }}" | |
| data-category="{{ product.get('category', 'Без категории')|lower }}"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <div class="product-image"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" | |
| alt="{{ product['name'] }}" | |
| loading="lazy"> | |
| </div> | |
| {% endif %} | |
| <h2>{{ product['name'] }}</h2> | |
| <div class="product-price">{{ product['price'] }} с</div> | |
| <p class="product-description">{{ product['description'][:50] }}{% if product['description']|length > 50 %}...{% endif %}</p> | |
| <div class="product-buttons"> | |
| <button class="product-button" onclick="openModal({{ loop.index0 }})">Подробнее</button> | |
| <button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})">В корзину</button> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| </div> | |
| <div id="productModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('productModal')">×</span> | |
| <div id="modalContent"></div> | |
| </div> | |
| </div> | |
| <div id="quantityModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('quantityModal')">×</span> | |
| <h2>Укажите количество и цвет</h2> | |
| <input type="number" id="quantityInput" class="quantity-input" min="1" value="1"> | |
| <select id="colorSelect" class="color-select"></select> | |
| <div class="modal-footer" style="border-top: none; padding-top: 10px;"> | |
| <button class="product-button" style="margin-top: 0;" onclick="confirmAddToCart()">Добавить</button> | |
| </div> | |
| </div> | |
| </div> | |
| <div id="cartModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('cartModal')">×</span> | |
| <h2>Корзина</h2> | |
| <div id="cartContent"></div> | |
| <div class="modal-footer"> | |
| <strong>Итого: <span id="cartTotal">0</span> с</strong> | |
| <div> | |
| <button class="product-button clear-cart" onclick="clearCart()">Очистить</button> | |
| <button class="product-button order-button" onclick="orderViaWhatsApp()">Заказать</button> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <button id="cart-button" onclick="openCartModal()"><i class="fas fa-shopping-cart"></i></button> | |
| <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> | |
| <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script> | |
| <script> | |
| const products = {{ products|tojson }}; | |
| let selectedProductIndex = null; | |
| function openModal(index) { | |
| loadProductDetails(index); | |
| document.getElementById('productModal').style.display = "block"; | |
| } | |
| function closeModal(modalId) { | |
| document.getElementById(modalId).style.display = "none"; | |
| } | |
| function loadProductDetails(index) { | |
| fetch('/product/' + index) | |
| .then(response => { | |
| if (!response.ok) { | |
| throw new Error('Network response was not ok ' + response.statusText); | |
| } | |
| return response.text(); | |
| }) | |
| .then(data => { | |
| document.getElementById('modalContent').innerHTML = data; | |
| initializeSwiper(); | |
| }) | |
| .catch(error => { | |
| console.error('Ошибка загрузки деталей продукта:', error); | |
| document.getElementById('modalContent').innerHTML = '<p>Не удалось загрузить детали продукта.</p>'; | |
| }); | |
| } | |
| function initializeSwiper() { | |
| if (document.querySelector('.swiper-container') && document.querySelector('.swiper-container').swiper) { | |
| document.querySelector('.swiper-container').swiper.destroy(true, true); | |
| } | |
| new Swiper('.swiper-container', { | |
| slidesPerView: 1, | |
| spaceBetween: 20, | |
| loop: true, | |
| grabCursor: true, | |
| pagination: { el: '.swiper-pagination', clickable: true }, | |
| navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, | |
| zoom: { maxRatio: 3 }, | |
| observer: true, | |
| observeParents: true | |
| }); | |
| } | |
| function openQuantityModal(index) { | |
| selectedProductIndex = index; | |
| const product = products[index]; | |
| if (!product) { | |
| console.error("Product not found at index:", index); | |
| alert("Ошибка: товар не найден."); | |
| return; | |
| } | |
| const colorSelect = document.getElementById('colorSelect'); | |
| colorSelect.innerHTML = ''; | |
| const availableColors = product.colors && product.colors.length > 0 ? product.colors : ['Нет информации']; | |
| availableColors.forEach(color => { | |
| const option = document.createElement('option'); | |
| option.value = color; | |
| option.text = color; | |
| colorSelect.appendChild(option); | |
| }); | |
| document.getElementById('quantityModal').style.display = 'block'; | |
| document.getElementById('quantityInput').value = 1; | |
| } | |
| function confirmAddToCart() { | |
| if (selectedProductIndex === null) return; | |
| const quantity = parseInt(document.getElementById('quantityInput').value) || 1; | |
| const color = document.getElementById('colorSelect').value; | |
| if (quantity <= 0) { | |
| alert("Укажите количество больше 0"); | |
| return; | |
| } | |
| let cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const product = products[selectedProductIndex]; | |
| if (!product) { | |
| console.error("Product not found at index:", selectedProductIndex); | |
| alert("Ошибка: товар не найден при добавлении в корзину."); | |
| return; | |
| } | |
| const cartItemId = `${product.name}-${color}`; | |
| const existingItemIndex = cart.findIndex(item => item.id === cartItemId); | |
| if (existingItemIndex > -1) { | |
| cart[existingItemIndex].quantity += quantity; | |
| } else { | |
| cart.push({ | |
| id: cartItemId, | |
| name: product.name, | |
| price: product.price, | |
| photo: product.photos && product.photos.length > 0 ? product.photos[0] : '', | |
| quantity: quantity, | |
| color: color | |
| }); | |
| } | |
| localStorage.setItem('cart', JSON.stringify(cart)); | |
| closeModal('quantityModal'); | |
| updateCartButton(); | |
| openCartModal(); | |
| } | |
| function updateCartButton() { | |
| const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const cartButton = document.getElementById('cart-button'); | |
| cartButton.style.display = cart.length > 0 ? 'flex' : 'none'; | |
| } | |
| function openCartModal() { | |
| const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const cartContent = document.getElementById('cartContent'); | |
| let total = 0; | |
| cartContent.innerHTML = cart.length === 0 ? '<p>Корзина пуста</p>' : cart.map(item => { | |
| const price = parseFloat(item.price) || 0; | |
| const quantity = parseInt(item.quantity) || 0; | |
| const itemTotal = price * quantity; | |
| total += itemTotal; | |
| return ` | |
| <div class="cart-item"> | |
| <div class="cart-item-details"> | |
| ${item.photo ? `<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}" alt="${item.name}">` : '<div style="width:50px; height: 50px; background: #eee; border-radius: 8px;"></div>'} | |
| <div class="cart-item-info"> | |
| <strong>${item.name}</strong> | |
| <span>${price.toFixed(1)} с × ${quantity} (Цвет: ${item.color})</span> | |
| </div> | |
| </div> | |
| <span class="cart-item-total">${itemTotal.toFixed(1)} с</span> | |
| </div> | |
| `; | |
| }).join(''); | |
| document.getElementById('cartTotal').textContent = total.toFixed(1); | |
| document.getElementById('cartModal').style.display = 'block'; | |
| cartContent.scrollTop = 0; | |
| } | |
| function orderViaWhatsApp() { | |
| const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| if (cart.length === 0) { | |
| alert("Корзина пуста!"); | |
| return; | |
| } | |
| let total = 0; | |
| let orderText = "Здравствуйте! Хочу сделать заказ:%0A%0A"; | |
| cart.forEach((item, index) => { | |
| const price = parseFloat(item.price) || 0; | |
| const quantity = parseInt(item.quantity) || 0; | |
| const itemTotal = price * quantity; | |
| total += itemTotal; | |
| orderText += `${index + 1}. ${item.name}%0A`; | |
| orderText += ` Цвет: ${item.color}%0A`; | |
| orderText += ` Кол-во: ${quantity}%0A`; | |
| orderText += ` Цена: ${price.toFixed(1)} с%0A`; | |
| orderText += ` Сумма: ${itemTotal.toFixed(1)} с%0A%0A`; | |
| }); | |
| orderText += `*Итого: ${total.toFixed(1)} с*`; | |
| const whatsappUrl = `https://api.whatsapp.com/send?phone=996704667878&text=${orderText}`; | |
| window.open(whatsappUrl, '_blank'); | |
| } | |
| function clearCart() { | |
| localStorage.removeItem('cart'); | |
| closeModal('cartModal'); | |
| updateCartButton(); | |
| } | |
| window.onclick = function(event) { | |
| const modals = document.querySelectorAll('.modal'); | |
| modals.forEach(modal => { | |
| if (event.target == modal) { | |
| modal.style.display = "none"; | |
| } | |
| }); | |
| } | |
| document.getElementById('search-input').addEventListener('input', filterProducts); | |
| document.querySelectorAll('.category-filter').forEach(filter => { | |
| filter.addEventListener('click', function() { | |
| document.querySelectorAll('.category-filter').forEach(f => f.classList.remove('active')); | |
| this.classList.add('active'); | |
| filterProducts(); | |
| }); | |
| }); | |
| function filterProducts() { | |
| const searchTerm = document.getElementById('search-input').value.toLowerCase().trim(); | |
| const activeCategory = document.querySelector('.category-filter.active').dataset.category.toLowerCase(); | |
| const grid = document.getElementById('products-grid'); | |
| const matchedProducts = []; | |
| products.forEach((product, index) => { | |
| const name = product.name.toLowerCase(); | |
| const description = product.description.toLowerCase(); | |
| const category = product.category ? product.category.toLowerCase() : 'без категории'; | |
| const matchesSearch = searchTerm === '' || name.includes(searchTerm) || description.includes(searchTerm); | |
| const matchesCategory = activeCategory === 'all' || category === activeCategory; | |
| if (matchesSearch && matchesCategory) { | |
| matchedProducts.push(` | |
| <div class="product" | |
| data-name="${name}" | |
| data-description="${description}" | |
| data-category="${category}"> | |
| ${product.photos && product.photos.length > 0 ? ` | |
| <div class="product-image"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${product.photos[0]}" | |
| alt="${product.name}" | |
| loading="lazy"> | |
| </div>` : ''} | |
| <h2>${product.name}</h2> | |
| <div class="product-price">${product.price} с</div> | |
| <p class="product-description">${product.description.substring(0, 50)}${product.description.length > 50 ? '...' : ''}</p> | |
| <div class="product-buttons"> | |
| <button class="product-button" onclick="openModal(${index})">Подробнее</button> | |
| <button class="product-button add-to-cart" onclick="openQuantityModal(${index})">В корзину</button> | |
| </div> | |
| </div>`); | |
| } | |
| }); | |
| grid.innerHTML = matchedProducts.join(''); | |
| } | |
| updateCartButton(); | |
| filterProducts(); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| return render_template_string(catalog_html, products=products, categories=categories, repo_id=REPO_ID) | |
| def product_detail(index): | |
| data = load_data() | |
| products = sorted(data.get('products', []), key=lambda x: x.get('added_at', ''), reverse=True) | |
| try: | |
| product = products[index] | |
| except IndexError: | |
| logging.error(f"Product index {index} out of range after sorting.") | |
| return "Продукт не найден", 404 | |
| except Exception as e: | |
| logging.error(f"Error retrieving product at index {index}: {e}") | |
| return "Ошибка при загрузке продукта", 500 | |
| detail_html = ''' | |
| <div style="font-family: 'Poppins', sans-serif; color: #333;"> | |
| <h2 style="font-size: 1.8rem; font-weight: 600; margin-bottom: 20px; color: #FFA726; text-align: center;">{{ product['name'] }}</h2> | |
| <div class="swiper-container" style="max-width: 400px; margin: 0 auto 20px; --swiper-navigation-color: #FFA726; --swiper-pagination-color: #FFA726; border-radius: 10px; overflow: hidden;"> | |
| <div class="swiper-wrapper"> | |
| {% set photos = product.get('photos', []) %} | |
| {% if photos and photos|length > 0 %} | |
| {% for photo in photos %} | |
| <div class="swiper-slide" style="background-color: #fff; display: flex; justify-content: center; align-items: center;"> | |
| <div class="swiper-zoom-container"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" | |
| alt="{{ product['name'] }}" | |
| style="max-width: 100%; max-height: 350px; object-fit: contain; display: block;"> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <div class="swiper-slide" style="background-color: #eee; display: flex; justify-content: center; align-items: center; height: 350px;"> | |
| <span style="color: #999;">Нет изображения</span> | |
| </div> | |
| {% endif %} | |
| </div> | |
| {% if photos and photos|length > 1 %} | |
| <div class="swiper-pagination"></div> | |
| <div class="swiper-button-next"></div> | |
| <div class="swiper-button-prev"></div> | |
| {% endif %} | |
| </div> | |
| <div style="background: #FFF8E1; padding: 15px; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);"> | |
| <p style="margin-bottom: 10px;"><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> | |
| <p style="margin-bottom: 10px;"><strong>Цена:</strong> <span style="color: #D84315; font-weight: bold;">{{ product['price'] }} с</span></p> | |
| <p style="margin-bottom: 10px; white-space: pre-wrap;"><strong>Описание:</strong> {{ product['description'] }}</p> | |
| <p><strong>Доступные цвета:</strong> {{ product.get('colors', ['Нет информации'])|join(', ') if product.get('colors') else 'Нет информации' }}</p> | |
| </div> | |
| </div> | |
| ''' | |
| return render_template_string(detail_html, product=product, repo_id=REPO_ID) | |
| def admin(): | |
| data = load_data() | |
| products = sorted(data.get('products', []), key=lambda p: p.get('added_at', ''), reverse=True) | |
| categories = data.get('categories', []) | |
| if request.method == 'POST': | |
| action = request.form.get('action') | |
| if action == 'add_category': | |
| category_name = request.form.get('category_name', '').strip() | |
| if category_name and category_name not in categories: | |
| categories.append(category_name) | |
| save_data({'products': products, 'categories': categories}) | |
| return redirect(url_for('admin')) | |
| elif category_name in categories: | |
| return "Ошибка: Категория с таким названием уже существует.", 400 | |
| else: | |
| return "Ошибка: Название категории не может быть пустым.", 400 | |
| elif action == 'delete_category': | |
| try: | |
| category_index = int(request.form.get('category_index')) | |
| if 0 <= category_index < len(categories): | |
| deleted_category = categories.pop(category_index) | |
| for product in products: | |
| if product.get('category') == deleted_category: | |
| product['category'] = 'Без категории' | |
| save_data({'products': products, 'categories': categories}) | |
| return redirect(url_for('admin')) | |
| else: | |
| return "Ошибка: Неверный индекс категории.", 400 | |
| except (ValueError, TypeError, IndexError): | |
| return "Ошибка: Неверный индекс категории.", 400 | |
| elif action == 'add': | |
| name = request.form.get('name', '').strip() | |
| price_str = request.form.get('price', '').strip() | |
| description = request.form.get('description', '').strip() | |
| category = request.form.get('category') | |
| photos_files = request.files.getlist('photos') | |
| colors = [c.strip() for c in request.form.getlist('colors') if c.strip()] | |
| photos_list = [] | |
| if not name or not price_str or not description: | |
| return "Ошибка: Заполните все обязательные поля (Название, Цена, Описание).", 400 | |
| try: | |
| price = float(price_str.replace(',', '.')) | |
| if price < 0: | |
| return "Ошибка: Цена не может быть отрицательной.", 400 | |
| except ValueError: | |
| return "Ошибка: Неверный формат цены. Используйте число (например, 150 или 150.50).", 400 | |
| if photos_files: | |
| uploads_dir = 'uploads' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| for photo in photos_files[:10]: | |
| if photo and photo.filename: | |
| base, ext = os.path.splitext(secure_filename(photo.filename)) | |
| photo_filename = f"{base}_{int(time.time())}{ext}" | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| try: | |
| photo.save(temp_path) | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=temp_path, | |
| path_in_repo=f"photos/{photo_filename}", | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Добавлено фото для товара {name}" | |
| ) | |
| photos_list.append(photo_filename) | |
| logging.info(f"Загружено фото: photos/{photo_filename}") | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке фото {photo_filename}: {e}") | |
| finally: | |
| if os.path.exists(temp_path): | |
| try: | |
| os.remove(temp_path) | |
| except OSError as e: | |
| logging.error(f"Ошибка при удалении временного файла {temp_path}: {e}") | |
| new_product = { | |
| 'name': name, | |
| 'price': price, | |
| 'description': description, | |
| 'category': category if category in categories else 'Без категории', | |
| 'photos': photos_list, | |
| 'colors': colors, | |
| 'added_at': datetime.now().isoformat() | |
| } | |
| products.append(new_product) | |
| save_data({'products': products, 'categories': categories}) | |
| return redirect(url_for('admin')) | |
| elif action == 'edit': | |
| try: | |
| index = int(request.form.get('index')) | |
| if not 0 <= index < len(products): | |
| return "Ошибка: Неверный индекс товара для редактирования.", 400 | |
| except (ValueError, TypeError): | |
| return "Ошибка: Неверный индекс товара.", 400 | |
| name = request.form.get('name', '').strip() | |
| price_str = request.form.get('price', '').strip() | |
| description = request.form.get('description', '').strip() | |
| category = request.form.get('category') | |
| photos_files = request.files.getlist('photos') | |
| colors = [c.strip() for c in request.form.getlist('colors') if c.strip()] | |
| if not name or not price_str or not description: | |
| return "Ошибка: Заполните все обязательные поля (Название, Цена, Описание).", 400 | |
| try: | |
| price_float = float(price_str.replace(',', '.')) | |
| if price_float < 0: | |
| return "Ошибка: Цена не может быть отрицательной.", 400 | |
| except ValueError: | |
| return "Ошибка: Неверный формат цены. Используйте число (например, 150 или 150.50).", 400 | |
| new_photos_list = products[index].get('photos', []) | |
| if photos_files and any(f.filename for f in photos_files): | |
| new_photos_list = [] | |
| uploads_dir = 'uploads' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| for photo in photos_files[:10]: | |
| if photo and photo.filename: | |
| base, ext = os.path.splitext(secure_filename(photo.filename)) | |
| photo_filename = f"{base}_{int(time.time())}{ext}" | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| try: | |
| photo.save(temp_path) | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=temp_path, | |
| path_in_repo=f"photos/{photo_filename}", | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Обновлено фото для товара {name}" | |
| ) | |
| new_photos_list.append(photo_filename) | |
| logging.info(f"Загружено (обновление) фото: photos/{photo_filename}") | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке фото {photo_filename} при редактировании: {e}") | |
| finally: | |
| if os.path.exists(temp_path): | |
| try: | |
| os.remove(temp_path) | |
| except OSError as e: | |
| logging.error(f"Ошибка при удалении временного файла {temp_path} при редактировании: {e}") | |
| products[index]['name'] = name | |
| products[index]['price'] = price_float | |
| products[index]['description'] = description | |
| products[index]['category'] = category if category in categories else 'Без категории' | |
| products[index]['photos'] = new_photos_list | |
| products[index]['colors'] = colors | |
| save_data({'products': products, 'categories': categories}) | |
| return redirect(url_for('admin')) | |
| elif action == 'delete': | |
| try: | |
| index = int(request.form.get('index')) | |
| if not 0 <= index < len(products): | |
| return "Ошибка: Неверный индекс товара для удаления.", 400 | |
| del products[index] | |
| save_data({'products': products, 'categories': categories}) | |
| except (ValueError, TypeError): | |
| return "Ошибка: Неверный индекс товара.", 400 | |
| except Exception as e: | |
| logging.error(f"Ошибка при удалении товара: {e}") | |
| return "Ошибка при удалении товара", 500 | |
| return redirect(url_for('admin')) | |
| admin_html = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Админ-панель</title> | |
| <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <style> | |
| :root { | |
| --primary-color: #FFA726; | |
| --secondary-color: #FFCA28; | |
| --text-color: #333; | |
| --bg-color: #FFF8E1; | |
| --light-text: #fff; | |
| --shadow-color: rgba(0, 0, 0, 0.1); | |
| --accent-color: #D84315; | |
| --hover-primary-color: #FB8C00; | |
| --hover-secondary-color: #FFA000; | |
| --delete-color: #ef4444; | |
| --delete-hover-color: #dc2626; | |
| --edit-bg-color: #fffaf0; | |
| } | |
| body { | |
| font-family: 'Poppins', sans-serif; | |
| background: var(--bg-color); | |
| color: var(--text-color); | |
| padding: 20px; | |
| margin: 0; | |
| } | |
| .container { | |
| max-width: 1200px; | |
| margin: 0 auto; | |
| } | |
| .header { | |
| display: flex; | |
| align-items: center; | |
| padding: 15px 0; | |
| border-bottom: 1px solid var(--primary-color); | |
| margin-bottom: 30px; | |
| } | |
| .header-logo { | |
| width: 60px; | |
| height: 60px; | |
| border-radius: 50%; | |
| object-fit: cover; | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| transition: transform 0.3s ease, box-shadow 0.3s ease; | |
| margin-right: 15px; | |
| } | |
| .header-logo:hover { | |
| transform: scale(1.1); | |
| box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3); | |
| } | |
| h1, h2 { | |
| font-weight: 600; | |
| margin-top: 0; | |
| margin-bottom: 20px; | |
| color: var(--primary-color); | |
| } | |
| h1 { font-size: 1.8rem; } | |
| h2 { font-size: 1.5rem; margin-top: 30px; } | |
| form { | |
| background: var(--light-text); | |
| padding: 25px; | |
| border-radius: 15px; | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| margin-bottom: 30px; | |
| } | |
| label { | |
| font-weight: 500; | |
| margin-top: 15px; | |
| display: block; | |
| color: #555; | |
| font-size: 0.9rem; | |
| } | |
| input[type="text"], | |
| input[type="number"], | |
| textarea, | |
| select, | |
| input[type="file"] { | |
| width: 100%; | |
| padding: 12px; | |
| margin-top: 8px; | |
| border: 1px solid var(--secondary-color); | |
| border-radius: 8px; | |
| font-size: 1rem; | |
| transition: all 0.3s ease; | |
| box-sizing: border-box; | |
| } | |
| input:focus, textarea:focus, select:focus { | |
| border-color: var(--primary-color); | |
| box-shadow: 0 0 8px rgba(255, 167, 38, 0.3); | |
| outline: none; | |
| } | |
| textarea { | |
| resize: vertical; | |
| min-height: 80px; | |
| white-space: pre-wrap; | |
| } | |
| input[type="file"] { | |
| padding: 10px; | |
| background-color: #fff; | |
| } | |
| input[type="file"]::file-selector-button { | |
| padding: 8px 15px; | |
| border: none; | |
| border-radius: 6px; | |
| background-color: var(--secondary-color); | |
| color: var(--text-color); | |
| font-weight: 500; | |
| cursor: pointer; | |
| transition: background-color 0.3s ease; | |
| margin-right: 10px; | |
| } | |
| input[type="file"]::file-selector-button:hover { | |
| background-color: var(--hover-secondary-color); | |
| color: var(--light-text); | |
| } | |
| button[type="submit"], button[type="button"] { | |
| padding: 12px 25px; | |
| border: none; | |
| border-radius: 8px; | |
| background-color: var(--primary-color); | |
| color: var(--light-text); | |
| font-weight: 600; | |
| font-size: 1rem; | |
| cursor: pointer; | |
| transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); | |
| margin-top: 20px; | |
| margin-right: 10px; | |
| } | |
| button[type="submit"]:hover, button[type="button"]:hover { | |
| background-color: var(--hover-primary-color); | |
| box-shadow: 0 4px 15px rgba(251, 140, 0, 0.4); | |
| transform: translateY(-2px); | |
| } | |
| .delete-button { | |
| background-color: var(--delete-color); | |
| } | |
| .delete-button:hover { | |
| background-color: var(--delete-hover-color); | |
| box-shadow: 0 4px 15px rgba(220, 38, 38, 0.4); | |
| } | |
| .add-color-btn { | |
| background-color: var(--secondary-color); | |
| color: var(--text-color); | |
| } | |
| .add-color-btn:hover { | |
| background-color: var(--hover-secondary-color); | |
| color: var(--light-text); | |
| box-shadow: 0 4px 15px rgba(255, 160, 0, 0.4); | |
| } | |
| .product-list, .category-list { | |
| display: grid; | |
| gap: 25px; | |
| } | |
| .product-item, .category-item { | |
| background: var(--light-text); | |
| padding: 25px; | |
| border-radius: 15px; | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| transition: box-shadow 0.3s ease; | |
| } | |
| .product-item:hover, .category-item:hover { | |
| box-shadow: 0 6px 20px rgba(0,0,0,0.15); | |
| } | |
| .category-item { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| } | |
| .category-item h3 { | |
| margin: 0; | |
| color: var(--text-color); | |
| font-weight: 500; | |
| word-break: break-all; | |
| margin-right: 15px; | |
| } | |
| .category-item form { | |
| background: none; | |
| padding: 0; | |
| box-shadow: none; | |
| margin: 0; | |
| flex-shrink: 0; | |
| } | |
| .category-item button { | |
| margin: 0; | |
| } | |
| .product-item h3 { | |
| margin-top: 0; | |
| margin-bottom: 15px; | |
| color: var(--accent-color); | |
| } | |
| .product-item p { | |
| margin-bottom: 8px; | |
| font-size: 0.9rem; | |
| line-height: 1.5; | |
| word-break: break-word; | |
| } | |
| .product-item p strong { | |
| color: #555; | |
| display: inline-block; | |
| margin-right: 5px; | |
| } | |
| .product-item p:has(> strong)::before { | |
| } | |
| .product-item .product-photos { | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| margin-top: 15px; | |
| margin-bottom: 15px; | |
| } | |
| .product-item .product-photos img { | |
| max-width: 100px; | |
| height: 100px; | |
| object-fit: cover; | |
| border-radius: 10px; | |
| border: 1px solid #eee; | |
| } | |
| .product-item details { | |
| margin-top: 20px; | |
| } | |
| .product-item summary { | |
| cursor: pointer; | |
| font-weight: 500; | |
| color: var(--primary-color); | |
| padding: 8px 0; | |
| outline: none; | |
| display: inline-block; | |
| } | |
| .product-item summary:hover { | |
| color: var(--hover-primary-color); | |
| } | |
| .product-item summary::marker { | |
| color: var(--primary-color); | |
| } | |
| .product-item details[open] > summary { | |
| margin-bottom: 10px; | |
| } | |
| .edit-form { | |
| margin-top: 15px; | |
| padding: 20px; | |
| background: var(--edit-bg-color); | |
| border-radius: 10px; | |
| border: 1px solid #eee; | |
| } | |
| .color-input-container { | |
| margin-top: 10px; | |
| margin-bottom: 10px; | |
| } | |
| .color-input-group { | |
| display: flex; | |
| gap: 10px; | |
| margin-bottom: 10px; | |
| align-items: center; | |
| } | |
| .color-input-group input { | |
| margin-top: 0; | |
| flex-grow: 1; | |
| } | |
| .color-input-group .remove-color-btn { | |
| padding: 5px 10px; | |
| font-size: 0.8rem; | |
| background-color: #ddd; | |
| color: #333; | |
| border: none; | |
| border-radius: 50%; | |
| margin-top: 0; | |
| min-width: 25px; | |
| height: 25px; | |
| line-height: 1; | |
| cursor: pointer; | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| flex-shrink: 0; | |
| } | |
| .color-input-group .remove-color-btn:hover { | |
| background-color: #ccc; | |
| transform: none; | |
| box-shadow: none; | |
| } | |
| .button-group { | |
| margin-top: 20px; | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| } | |
| .button-group form, | |
| .button-group details { | |
| background: none; | |
| padding: 0; | |
| margin: 0; | |
| box-shadow: none; | |
| } | |
| .button-group button, | |
| .button-group summary { | |
| margin-top: 0; | |
| } | |
| button > i.fas { | |
| margin-right: 8px; | |
| } | |
| .add-color-btn i.fas, | |
| .delete-button i.fas { | |
| margin-right: 5px; | |
| } | |
| .edit-form button[type="submit"] i.fas, | |
| details > summary i.fas { | |
| margin-right: 8px; | |
| } | |
| @media (max-width: 768px) { | |
| .product-list, .category-list { | |
| grid-template-columns: 1fr; | |
| } | |
| .header { | |
| flex-direction: column; | |
| align-items: flex-start; | |
| } | |
| .header h1 { | |
| margin-top: 10px; | |
| } | |
| form { | |
| padding: 20px; | |
| } | |
| } | |
| @media (max-width: 480px) { | |
| .category-item { | |
| flex-direction: column; | |
| align-items: flex-start; | |
| gap: 10px; | |
| } | |
| .category-item form { | |
| align-self: flex-end; | |
| } | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <img src="''' + LOGO_URL + '''" alt="Logo" class="header-logo"> | |
| <h1>Админ-панель</h1> | |
| </div> | |
| <h2>Добавить новый товар</h2> | |
| <form method="POST" enctype="multipart/form-data"> | |
| <input type="hidden" name="action" value="add"> | |
| <label for="add-name">Название товара:</label> | |
| <input type="text" id="add-name" name="name" required> | |
| <label for="add-price">Цена (с):</label> | |
| <input type="text" inputmode="decimal" id="add-price" name="price" required placeholder="Например: 150.50"> | |
| <label for="add-description">Описание:</label> | |
| <textarea id="add-description" name="description" rows="4" required></textarea> | |
| <label for="add-category">Категория:</label> | |
| <select id="add-category" name="category"> | |
| <option value="Без категории">Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category }}">{{ category }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="add-photos">Фотографии (до 10, JPG/PNG/WEBP):</label> | |
| <input type="file" id="add-photos" name="photos" accept="image/jpeg, image/png, image/webp" multiple> | |
| <label>Доступные цвета:</label> | |
| <div id="add-color-inputs" class="color-input-container"> | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" placeholder="Например: Красный"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)" style="display: none;">X</button> | |
| </div> | |
| </div> | |
| <button type="button" class="add-color-btn" onclick="addColorInput('add-color-inputs')"><i class="fas fa-plus"></i> Добавить цвет</button> | |
| <button type="submit"><i class="fas fa-plus-circle"></i> Добавить товар</button> | |
| </form> | |
| <h2>Управление категориями</h2> | |
| <form method="POST"> | |
| <input type="hidden" name="action" value="add_category"> | |
| <label for="category-name">Название новой категории:</label> | |
| <input type="text" id="category-name" name="category_name" required> | |
| <button type="submit"><i class="fas fa-plus"></i> Добавить категорию</button> | |
| </form> | |
| <h3>Список категорий</h3> | |
| <div class="category-list"> | |
| {% for category in categories %} | |
| <div class="category-item"> | |
| <h3>{{ category }}</h3> | |
| <form method="POST" onsubmit="return confirm('Вы уверены, что хотите удалить категорию \'{{ category }}\'? Товары этой категории станут \'Без категории\'.');"> | |
| <input type="hidden" name="action" value="delete_category"> | |
| <input type="hidden" name="category_index" value="{{ loop.index0 }}"> | |
| <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button> | |
| </form> | |
| </div> | |
| {% else %} | |
| <p>Нет добавленных категорий.</p> | |
| {% endfor %} | |
| </div> | |
| <h2>Управление базой данных</h2> | |
| <div class="button-group"> | |
| <form method="POST" action="{{ url_for('backup') }}"> | |
| <button type="submit"><i class="fas fa-cloud-upload-alt"></i> Создать резервную копию</button> | |
| </form> | |
| <form method="GET" action="{{ url_for('download') }}"> | |
| <button type="submit" class="add-color-btn"><i class="fas fa-cloud-download-alt"></i> Скачать актуальную базу</button> | |
| </form> | |
| </div> | |
| <h2>Список товаров</h2> | |
| <div class="product-list"> | |
| {% for product in products %} | |
| <div class="product-item"> | |
| <h3>{{ product['name'] }}</h3> | |
| <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> | |
| <p><strong>Цена:</strong> {{ product['price'] }} с</p> | |
| <p style="white-space: pre-wrap;"><strong>Описание:</strong> {{ product['description'] }}</p> | |
| <p><strong>Цвета:</strong> {{ product.get('colors', [])|join(', ') if product.get('colors') else 'Нет цветов' }}</p> | |
| <p><small><strong>Добавлено:</strong> {{ product.get('added_at', 'N/A') }}</small></p> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <div class="product-photos"> | |
| {% for photo in product['photos'] %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}?download=true" | |
| alt="Фото {{ product['name'] }}" | |
| loading="lazy"> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p><small>Нет фотографий</small></p> | |
| {% endif %} | |
| <div class="button-group"> | |
| <details> | |
| <summary><i class="fas fa-edit"></i> Редактировать</summary> | |
| <form method="POST" enctype="multipart/form-data" class="edit-form"> | |
| <input type="hidden" name="action" value="edit"> | |
| <input type="hidden" name="index" value="{{ loop.index0 }}"> | |
| <label for="edit-name-{{ loop.index0 }}">Название:</label> | |
| <input type="text" id="edit-name-{{ loop.index0 }}" name="name" value="{{ product['name'] }}" required> | |
| <label for="edit-price-{{ loop.index0 }}">Цена (с):</label> | |
| <input type="text" inputmode="decimal" id="edit-price-{{ loop.index0 }}" name="price" value="{{ product['price'] }}" required> | |
| <label for="edit-description-{{ loop.index0 }}">Описание:</label> | |
| <textarea id="edit-description-{{ loop.index0 }}" name="description" rows="4" required>{{ product['description'] }}</textarea> | |
| <label for="edit-category-{{ loop.index0 }}">Категория:</label> | |
| <select id="edit-category-{{ loop.index0 }}" name="category"> | |
| <option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="edit-photos-{{ loop.index0 }}">Заменить фотографии (до 10):</label> | |
| <input type="file" id="edit-photos-{{ loop.index0 }}" name="photos" accept="image/jpeg, image/png, image/webp" multiple> | |
| <label>Доступные цвета:</label> | |
| <div id="edit-color-inputs-{{ loop.index0 }}" class="color-input-container"> | |
| {% set colors = product.get('colors', []) %} | |
| {% if colors %} | |
| {% for color in colors %} | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" value="{{ color }}"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)">X</button> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" placeholder="Например: Синий"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)" style="display: none;">X</button> | |
| </div> | |
| {% endif %} | |
| </div> | |
| <button type="button" class="add-color-btn" onclick="addColorInput('edit-color-inputs-{{ loop.index0 }}')"><i class="fas fa-plus"></i> Добавить цвет</button> | |
| <button type="submit"><i class="fas fa-save"></i> Сохранить изменения</button> | |
| </form> | |
| </details> | |
| <form method="POST" onsubmit="return confirm('Вы уверены, что хотите удалить товар \'{{ product['name'] }}\'?');"> | |
| <input type="hidden" name="action" value="delete"> | |
| <input type="hidden" name="index" value="{{ loop.index0 }}"> | |
| <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить товар</button> | |
| </form> | |
| </div> | |
| </div> | |
| {% else %} | |
| <p>В базе пока нет товаров.</p> | |
| {% endfor %} | |
| </div> | |
| </div> | |
| <script> | |
| function addColorInput(containerId) { | |
| const container = document.getElementById(containerId); | |
| if (!container) return; | |
| const newInputGroup = document.createElement('div'); | |
| newInputGroup.className = 'color-input-group'; | |
| newInputGroup.innerHTML = ` | |
| <input type="text" name="colors" placeholder="Еще один цвет"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)">X</button> | |
| `; | |
| container.querySelectorAll('.remove-color-btn').forEach(btn => btn.style.display = 'inline-flex'); | |
| container.appendChild(newInputGroup); | |
| } | |
| function removeColorInput(button) { | |
| const inputGroup = button.closest('.color-input-group'); | |
| const container = button.closest('.color-input-container'); | |
| if (!inputGroup || !container) return; | |
| inputGroup.remove(); | |
| const remainingGroups = container.querySelectorAll('.color-input-group'); | |
| if (remainingGroups.length === 1) { | |
| const lastRemoveBtn = remainingGroups[0].querySelector('.remove-color-btn'); | |
| if(lastRemoveBtn) lastRemoveBtn.style.display = 'none'; | |
| } else if (remainingGroups.length === 0) { | |
| addColorInput(container.id); | |
| const firstGroup = container.querySelector('.color-input-group'); | |
| if (firstGroup) { | |
| const firstRemoveBtn = firstGroup.querySelector('.remove-color-btn'); | |
| if (firstRemoveBtn) firstRemoveBtn.style.display = 'none'; | |
| } | |
| } | |
| } | |
| document.querySelectorAll('.color-input-container').forEach(container => { | |
| const groups = container.querySelectorAll('.color-input-group'); | |
| if (groups.length === 1) { | |
| const removeBtn = groups[0].querySelector('.remove-color-btn'); | |
| if (removeBtn) removeBtn.style.display = 'none'; | |
| } else if (groups.length === 0) { | |
| addColorInput(container.id); | |
| const firstGroup = container.querySelector('.color-input-group'); | |
| if (firstGroup) { | |
| const firstRemoveBtn = firstGroup.querySelector('.remove-color-btn'); | |
| if (firstRemoveBtn) firstRemoveBtn.style.display = 'none'; | |
| } | |
| } else { | |
| groups.forEach(group => { | |
| const removeBtn = group.querySelector('.remove-color-btn'); | |
| if(removeBtn) removeBtn.style.display = 'inline-flex'; | |
| }); | |
| } | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| return render_template_string(admin_html, products=products, categories=categories, repo_id=REPO_ID) | |
| def backup(): | |
| try: | |
| save_data(load_data()) | |
| return "Резервная копия успешно создана и загружена на Hugging Face.", 200 | |
| except Exception as e: | |
| logging.error(f"Ошибка при ручном создании резервной копии: {e}") | |
| return f"Ошибка при создании резервной копии: {e}", 500 | |
| def download(): | |
| try: | |
| download_db_from_hf() | |
| load_data() | |
| return "Актуальная база данных успешно скачана из Hugging Face и загружена в приложение.", 200 | |
| except RepositoryNotFoundError: | |
| return "Ошибка: Репозиторий Hugging Face не найден.", 404 | |
| except Exception as e: | |
| logging.error(f"Ошибка при ручном скачивании базы данных: {e}") | |
| return f"Ошибка при скачивании базы данных: {e}", 500 | |
| if __name__ == '__main__': | |
| os.makedirs('uploads', exist_ok=True) | |
| if HF_TOKEN_WRITE: | |
| backup_thread = threading.Thread(target=periodic_backup, daemon=True) | |
| backup_thread.start() | |
| logging.info("Поток периодического резервного копирования запущен.") | |
| else: | |
| logging.warning("HF_TOKEN_WRITE не установлен, периодическое резервное копирование отключено.") | |
| try: | |
| load_data() | |
| except Exception as e: | |
| logging.warning(f"Не удалось первоначально загрузить/скачать базу данных: {e}. Приложение запустится с пустыми/старыми локальными данными.") | |
| port = int(os.environ.get("PORT", 7860)) | |
| logging.info(f"Запуск Flask приложения на хосте 0.0.0.0 и порту {port}") | |
| app.run(debug=False, host='0.0.0.0', port=port) |