|
|
|
|
| from flask import Flask, render_template_string, request, redirect, url_for, session, send_from_directory |
| 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 |
| import shutil |
|
|
| app = Flask(__name__) |
| app.secret_key = 'your_unique_secret_key_soola_cosmetics_7890' |
| DATA_FILE = 'data_soola.json' |
| USERS_FILE = 'users_soola.json' |
| |
|
|
| |
| SYNC_FILES = [DATA_FILE, USERS_FILE] |
|
|
| |
| REPO_ID = "Kgshop/Soola" |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN") |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") |
|
|
| |
| STORE_ADDRESS = "Рынок Дордой, Джунхай, терминал, 38" |
|
|
| |
| CURRENCY_CODE = 'KGS' |
| CURRENCY_NAME = 'Кыргызский сом (с)' |
|
|
| |
| logging.basicConfig(level=logging.INFO) |
|
|
| |
|
|
| def load_data(): |
| """Загружает данные товаров и категорий.""" |
| try: |
| |
| download_db_from_hf() |
| except RepositoryNotFoundError: |
| logging.warning(f"Репозиторий {REPO_ID} не найден на Hugging Face. Используется локальная версия, если есть.") |
| except Exception as e: |
| logging.warning(f"Ошибка при скачивании файлов с Hugging Face: {e}. Используется локальная версия, если есть.") |
|
|
| try: |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: |
| data = json.load(file) |
| logging.info(f"Данные успешно загружены из {DATA_FILE}") |
| |
| if not isinstance(data, dict): |
| logging.warning(f"{DATA_FILE} не является словарем. Сброс к формату по умолчанию.") |
| return {'products': [], 'categories': []} |
| if 'products' not in data: |
| data['products'] = [] |
| logging.warning(f"Ключ 'products' отсутствовал в {DATA_FILE}. Добавлен пустой список.") |
| if 'categories' not in data: |
| data['categories'] = [] |
| logging.warning(f"Ключ 'categories' отсутствовал в {DATA_FILE}. Добавлен пустой список.") |
| return data |
| except FileNotFoundError: |
| logging.warning(f"Локальный файл {DATA_FILE} не найден. Создание структуры по умолчанию.") |
| return {'products': [], 'categories': []} |
| except json.JSONDecodeError: |
| logging.error(f"Ошибка: Невозможно декодировать JSON из {DATA_FILE}. Возврат структуры по умолчанию.") |
| |
| try: |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") |
| shutil.copyfile(DATA_FILE, f"{DATA_FILE}.corrupted_{timestamp}") |
| logging.info(f"Создана резервная копия поврежденного файла: {DATA_FILE}.corrupted_{timestamp}") |
| except Exception as copy_e: |
| logging.error(f"Не удалось создать резервную копию поврежденного файла {DATA_FILE}: {copy_e}") |
| return {'products': [], 'categories': []} |
| except Exception as e: |
| logging.error(f"Непредвиденная ошибка при загрузке данных из {DATA_FILE}: {e}") |
| return {'products': [], 'categories': []} |
|
|
| def save_data(data): |
| """Сохраняет данные товаров и категорий.""" |
| try: |
| with open(DATA_FILE, 'w', encoding='utf-8') as file: |
| json.dump(data, file, ensure_ascii=False, indent=4) |
| logging.info(f"Данные успешно сохранены в {DATA_FILE}") |
| |
| upload_db_to_hf() |
| except Exception as e: |
| logging.error(f"Ошибка при сохранении данных в {DATA_FILE}: {e}") |
| |
| |
|
|
| def load_users(): |
| """Загружает данные пользователей.""" |
| try: |
| |
| download_db_from_hf() |
| except RepositoryNotFoundError: |
| logging.warning(f"Репозиторий {REPO_ID} не найден на Hugging Face. Используется локальная версия users_soola.json, если есть.") |
| except Exception as e: |
| logging.warning(f"Ошибка при скачивании users_soola.json с Hugging Face: {e}. Используется локальная версия, если есть.") |
|
|
| try: |
| with open(USERS_FILE, 'r', encoding='utf-8') as file: |
| users = json.load(file) |
| logging.info(f"Данные пользователей успешно загружены из {USERS_FILE}") |
| if not isinstance(users, dict): |
| logging.warning(f"{USERS_FILE} не является словарем. Возвращается пустой словарь.") |
| return {} |
| return users |
| except FileNotFoundError: |
| logging.warning(f"Локальный файл {USERS_FILE} не найден. Возвращается пустой словарь.") |
| return {} |
| except json.JSONDecodeError: |
| logging.error(f"Ошибка: Невозможно декодировать JSON из {USERS_FILE}. Возвращается пустой словарь.") |
| |
| try: |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") |
| shutil.copyfile(USERS_FILE, f"{USERS_FILE}.corrupted_{timestamp}") |
| logging.info(f"Создана резервная копия поврежденного файла: {USERS_FILE}.corrupted_{timestamp}") |
| except Exception as copy_e: |
| logging.error(f"Не удалось создать резервную копию поврежденного файла {USERS_FILE}: {copy_e}") |
| return {} |
| except Exception as e: |
| logging.error(f"Непредвиденная ошибка при загрузке данных из {USERS_FILE}: {e}") |
| return {} |
|
|
| def save_users(users): |
| """Сохраняет данные пользователей.""" |
| try: |
| with open(USERS_FILE, 'w', encoding='utf-8') as file: |
| json.dump(users, file, ensure_ascii=False, indent=4) |
| logging.info(f"Данные пользователей успешно сохранены в {USERS_FILE}") |
| |
| upload_db_to_hf() |
| except Exception as e: |
| logging.error(f"Ошибка при сохранении данных пользователей в {USERS_FILE}: {e}") |
|
|
|
|
| def upload_db_to_hf(): |
| """Загружает файлы данных на Hugging Face.""" |
| if not HF_TOKEN_WRITE: |
| logging.warning("HF_TOKEN (токен для записи) не установлен. Загрузка на Hugging Face отключена.") |
| return |
| try: |
| api = HfApi() |
| logging.info(f"Попытка загрузки файлов {SYNC_FILES} в репозиторий {REPO_ID}...") |
| for file_name in SYNC_FILES: |
| if os.path.exists(file_name): |
| api.upload_file( |
| path_or_fileobj=file_name, |
| path_in_repo=file_name, |
| repo_id=REPO_ID, |
| repo_type="dataset", |
| token=HF_TOKEN_WRITE, |
| commit_message=f"Автоматическое резервное копирование {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" |
| ) |
| logging.info(f"Файл {file_name} успешно загружен на Hugging Face.") |
| else: |
| logging.warning(f"Файл {file_name} не найден локально, пропуск загрузки.") |
| except Exception as e: |
| logging.error(f"Ошибка при загрузке файлов на Hugging Face: {e}") |
|
|
| def download_db_from_hf(): |
| """Скачивает файлы данных с Hugging Face.""" |
| if not HF_TOKEN_READ: |
| logging.warning("HF_TOKEN_READ (токен для чтения) не установлен. Скачивание с Hugging Face отключено.") |
| |
| return |
| try: |
| api = HfApi() |
| logging.info(f"Попытка скачивания файлов {SYNC_FILES} из репозитория {REPO_ID}...") |
| for file_name in SYNC_FILES: |
| try: |
| hf_hub_download( |
| repo_id=REPO_ID, |
| filename=file_name, |
| repo_type="dataset", |
| token=HF_TOKEN_READ, |
| local_dir=".", |
| local_dir_use_symlinks=False, |
| force_download=True |
| ) |
| logging.info(f"Файл {file_name} успешно скачан из Hugging Face.") |
| except RepositoryNotFoundError as repo_e: |
| logging.error(f"Репозиторий {REPO_ID} не найден на Hugging Face: {repo_e}") |
| raise |
| except Exception as file_e: |
| |
| logging.error(f"Ошибка при скачивании файла {file_name}: {file_e}") |
| except RepositoryNotFoundError: |
| |
| raise |
| except Exception as e: |
| |
| logging.error(f"Общая ошибка при скачивании файлов с Hugging Face: {e}") |
| |
|
|
| def periodic_backup(): |
| """Периодически загружает данные на Hugging Face.""" |
| while True: |
| logging.info("Запуск периодического резервного копирования...") |
| upload_db_to_hf() |
| logging.info("Периодическое резервное копирование завершено. Следующий запуск через 800 секунд.") |
| time.sleep(800) |
|
|
| |
|
|
| @app.route('/') |
| def catalog(): |
| """Главная страница каталога.""" |
| data = load_data() |
| products = data.get('products', []) |
| categories = data.get('categories', []) |
| is_authenticated = 'user' in session |
|
|
| catalog_html = ''' |
| <!DOCTYPE html> |
| <html lang="ru"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>Soola Cosmetics - Каталог</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> |
| /* Стили остаются в основном такими же, как в оригинале */ |
| * { margin: 0; padding: 0; box-sizing: border-box; } |
| body { |
| font-family: 'Poppins', sans-serif; |
| background: linear-gradient(135deg, #fde2e4, #fad2e1); /* Примерная палитра Soola */ |
| color: #4a4a4a; /* Темно-серый для текста */ |
| line-height: 1.6; |
| transition: background 0.3s, color 0.3s; |
| } |
| body.dark-mode { |
| background: linear-gradient(135deg, #2d0b0e, #4a1d2e); /* Темная палитра */ |
| color: #e2e8f0; |
| } |
| .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 rgba(0,0,0,0.1); } |
| body.dark-mode .header { border-bottom: 1px solid rgba(255,255,255,0.1); } |
| .header h1 { font-size: 1.8rem; font-weight: 600; color: #d6336c; } /* Розовый акцент */ |
| body.dark-mode .header h1 { color: #f783ac; } |
| .auth-links { display: flex; gap: 15px; align-items: center; } |
| .auth-links span { font-weight: 500; } |
| .auth-links a { color: #d6336c; text-decoration: none; font-weight: 500; } |
| body.dark-mode .auth-links a { color: #f783ac; } |
| .auth-links a:hover { text-decoration: underline; } |
| .theme-toggle { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #868e96; transition: color 0.3s ease; } |
| body.dark-mode .theme-toggle { color: #adb5bd; } |
| .theme-toggle:hover { color: #d6336c; } |
| body.dark-mode .theme-toggle:hover { color: #f783ac; } |
| .store-address { padding: 15px; text-align: center; font-size: 1rem; color: #555; background-color: rgba(255, 255, 255, 0.5); border-radius: 8px; margin: 15px 0; } |
| body.dark-mode .store-address { color: #ccc; background-color: rgba(0, 0, 0, 0.2); } |
| .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 #e9ecef; border-radius: 25px; outline: none; box-shadow: 0 2px 5px rgba(0,0,0,0.05); transition: all 0.3s ease; } |
| body.dark-mode #search-input { background-color: #495057; border-color: #5a6167; color: #fff; } |
| #search-input:focus { border-color: #d6336c; box-shadow: 0 0 0 3px rgba(214, 51, 108, 0.2); } |
| body.dark-mode #search-input:focus { border-color: #f783ac; box-shadow: 0 0 0 3px rgba(247, 131, 172, 0.3); } |
| .category-filter { padding: 8px 16px; border: 1px solid #f1f3f5; border-radius: 20px; background-color: #fff; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.9rem; font-weight: 400; } |
| body.dark-mode .category-filter { background-color: #495057; border-color: #5a6167; color: #e9ecef; } |
| .category-filter.active, .category-filter:hover { background-color: #d6336c; color: white; border-color: #d6336c; box-shadow: 0 2px 10px rgba(214, 51, 108, 0.3); } |
| body.dark-mode .category-filter.active, body.dark-mode .category-filter:hover { background-color: #f783ac; border-color: #f783ac; color: #111; } |
| .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(auto-fill, minmax(220px, 1fr)); } } |
| @media (min-width: 900px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); } } |
| .product { background: #fff; border-radius: 15px; padding: 15px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; } |
| body.dark-mode .product { background: #343a40; color: #fff; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3); } |
| .product:hover { transform: translateY(-5px); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12); } |
| body.dark-mode .product:hover { box-shadow: 0 6px 20px rgba(0, 0, 0, 0.5); } |
| .product-image { width: 100%; aspect-ratio: 1; background-color: #f8f9fa; border-radius: 10px; overflow: hidden; display: flex; justify-content: center; align-items: center; margin-bottom: 10px; } |
| body.dark-mode .product-image { background-color: #495057; } |
| .product-image img { max-width: 100%; max-height: 100%; object-fit: contain; transition: transform 0.3s ease; } |
| .product-image img:hover { transform: scale(1.05); } |
| .product h2 { font-size: 1rem; font-weight: 600; margin: 10px 0 5px; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } |
| .product-price { font-size: 1.1rem; color: #d6336c; font-weight: 700; text-align: center; margin: 5px 0; } |
| body.dark-mode .product-price { color: #f783ac; } |
| .product-description { font-size: 0.8rem; color: #6c757d; text-align: center; margin-bottom: 15px; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; height: 2.4em; } /* Ограничение 2 строками */ |
| body.dark-mode .product-description { color: #adb5bd; } |
| .product-button { display: block; width: 100%; padding: 10px; border: none; border-radius: 8px; background-color: #d6336c; color: white; font-size: 0.9rem; font-weight: 500; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); margin-top: 5px; text-align: center; text-decoration: none; } |
| body.dark-mode .product-button { background-color: #f783ac; color: #212529; } |
| .product-button:hover { background-color: #c2255c; box-shadow: 0 4px 15px rgba(194, 37, 92, 0.4); transform: translateY(-2px); } |
| body.dark-mode .product-button:hover { background-color: #f46a9b; } |
| .add-to-cart { background-color: #4dabf7; } /* Голубой для корзины */ |
| body.dark-mode .add-to-cart { background-color: #74c0fc; } |
| .add-to-cart:hover { background-color: #339af0; box-shadow: 0 4px 15px rgba(51, 154, 240, 0.4); } |
| body.dark-mode .add-to-cart:hover { background-color: #a5d8ff; } |
| #cart-button { position: fixed; bottom: 20px; right: 20px; background-color: #d6336c; color: white; border: none; border-radius: 50%; width: 55px; height: 55px; font-size: 1.5rem; cursor: pointer; display: none; /* Показывается JS */ box-shadow: 0 4px 15px rgba(214, 51, 108, 0.5); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1000; display: flex; justify-content: center; align-items: center; } |
| body.dark-mode #cart-button { background-color: #f783ac; } |
| .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); backdrop-filter: blur(5px); overflow-y: auto; } |
| .modal-content { background: #fff; margin: 5% auto; padding: 25px; border-radius: 15px; width: 90%; max-width: 700px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); animation: slideIn 0.4s ease-out; position: relative; } |
| body.dark-mode .modal-content { background: #343a40; color: #e9ecef; } |
| @keyframes slideIn { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } } |
| .close { position: absolute; top: 15px; right: 20px; font-size: 2rem; color: #adb5bd; cursor: pointer; transition: color 0.3s; line-height: 1; } |
| .close:hover { color: #495057; } |
| body.dark-mode .close { color: #868e96; } |
| body.dark-mode .close:hover { color: #ced4da; } |
| .modal h2 { margin-bottom: 20px; color: #d6336c; } |
| body.dark-mode .modal h2 { color: #f783ac; } |
| .cart-item { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; border-bottom: 1px solid #e9ecef; } |
| body.dark-mode .cart-item { border-bottom: 1px solid #495057; } |
| .cart-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; margin-right: 15px; background: #f8f9fa; padding: 5px;} |
| body.dark-mode .cart-item img { background: #495057; } |
| .cart-item-details { flex-grow: 1; } |
| .cart-item-details p { margin: 2px 0; font-size: 0.9rem; } |
| .cart-item-total { font-weight: bold; min-width: 80px; text-align: right; } |
| .quantity-input, .color-select { width: 100%; max-width: 150px; padding: 8px 12px; border: 1px solid #dee2e6; border-radius: 8px; font-size: 1rem; margin: 10px 0; } |
| body.dark-mode .quantity-input, body.dark-mode .color-select { background-color: #495057; border-color: #5a6167; color: #fff; } |
| .modal-buttons { display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px; } |
| .clear-cart { background-color: #fa5252; } /* Красный для очистки */ |
| body.dark-mode .clear-cart { background-color: #ff6b6b; } |
| .clear-cart:hover { background-color: #f03e3e; box-shadow: 0 4px 15px rgba(240, 62, 62, 0.4); } |
| body.dark-mode .clear-cart:hover { background-color: #ff8787; } |
| .order-button { background-color: #38d9a9; } /* Зеленый для заказа */ |
| body.dark-mode .order-button { background-color: #63e6be; } |
| .order-button:hover { background-color: #20c997; box-shadow: 0 4px 15px rgba(32, 201, 151, 0.4); } |
| body.dark-mode .order-button:hover { background-color: #96f2d7; } |
| /* Swiper styles */ |
| .swiper-container { max-width: 450px; margin: 0 auto 20px; border-radius: 10px; overflow: hidden; } |
| .swiper-slide { background-color: #f8f9fa; display: flex; justify-content: center; align-items: center; aspect-ratio: 1; } |
| body.dark-mode .swiper-slide { background-color: #495057; } |
| .swiper-slide img { max-width: 90%; max-height: 90%; object-fit: contain; } |
| .swiper-pagination-bullet-active { background: #d6336c; } |
| body.dark-mode .swiper-pagination-bullet-active { background: #f783ac; } |
| .swiper-button-next, .swiper-button-prev { color: #d6336c; } |
| body.dark-mode .swiper-button-next, body.dark-mode .swiper-button-prev { color: #f783ac; } |
| /* Product Detail Styles */ |
| .product-detail-content p { margin-bottom: 10px; line-height: 1.7; } |
| .product-detail-content strong { font-weight: 600; color: #343a40; } |
| body.dark-mode .product-detail-content strong { color: #ced4da; } |
| .product-detail-content .price { font-size: 1.4rem; color: #d6336c; font-weight: 700; margin-bottom: 15px; } |
| body.dark-mode .product-detail-content .price { color: #f783ac; } |
| </style> |
| </head> |
| <body> |
| <div class="container"> |
| <div class="header"> |
| <h1>Soola Cosmetics</h1> |
| <div class="auth-links"> |
| {% if is_authenticated %} |
| <span>Добро пожаловать, {{ session['user'] }}!</span> |
| <a href="{{ url_for('logout') }}">Выйти</a> |
| {% else %} |
| <a href="{{ url_for('login') }}">Войти</a> |
| <!-- Ссылка на регистрацию убрана --> |
| {% endif %} |
| </div> |
| <button class="theme-toggle" onclick="toggleTheme()"> |
| <i class="fas fa-moon"></i> <!-- Иконка будет меняться JS --> |
| </button> |
| </div> |
| |
| <div class="store-address">{{ store_address }}</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.get('name', 'Без названия')|lower }}" |
| data-description="{{ product.get('description', '')|lower }}" |
| data-category="{{ product.get('category', 'Без категории') }}"> |
| |
| <div class="product-image"> |
| {% if product.get('photos') and product['photos']|length > 0 %} |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" |
| alt="{{ product.get('name', 'Фото товара') }}" |
| loading="lazy"> |
| {% else %} |
| <i class="fas fa-image" style="font-size: 4rem; color: #dee2e6;"></i> <!-- Placeholder Icon --> |
| {# <img src="https://via.placeholder.com/200?text=No+Image" alt="Нет изображения" loading="lazy"> #} |
| {% endif %} |
| </div> |
| |
| <div> <!-- Дополнительный div для текста и кнопок --> |
| <h2>{{ product.get('name', 'Без названия') }}</h2> |
| <div class="product-price">{{ "%.2f"|format(product.get('price', 0)) }} {{ currency_code }}</div> |
| <p class="product-description">{{ product.get('description', '') }}</p> |
| <button class="product-button" onclick="openModal({{ loop.index0 }})">Подробнее</button> |
| {% if is_authenticated %} |
| <button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})">В корзину</button> |
| {% endif %} |
| </div> |
| </div> |
| {% endfor %} |
| </div> |
| </div> |
| |
| <!-- Product Modal --> |
| <div id="productModal" class="modal"> |
| <div class="modal-content"> |
| <span class="close" onclick="closeModal('productModal')">×</span> |
| <div id="modalContent" class="product-detail-content"></div> |
| </div> |
| </div> |
| |
| <!-- Quantity and Color Modal --> |
| <div id="quantityModal" class="modal"> |
| <div class="modal-content"> |
| <span class="close" onclick="closeModal('quantityModal')">×</span> |
| <h2>Укажите количество и цвет/вариант</h2> |
| <label for="quantityInput">Количество:</label> |
| <input type="number" id="quantityInput" class="quantity-input" min="1" value="1"> |
| <label for="colorSelect">Цвет/Вариант:</label> |
| <select id="colorSelect" class="color-select"></select> |
| <div class="modal-buttons"> |
| <button class="product-button" onclick="confirmAddToCart()">Добавить в корзину</button> |
| </div> |
| </div> |
| </div> |
| |
| <!-- Cart Modal --> |
| <div id="cartModal" class="modal"> |
| <div class="modal-content"> |
| <span class="close" onclick="closeModal('cartModal')">×</span> |
| <h2>Корзина</h2> |
| <div id="cartContent"></div> |
| <div style="margin-top: 20px; text-align: right; border-top: 1px solid #e9ecef; padding-top: 15px;"> |
| <strong>Итого: <span id="cartTotal">0.00</span> {{ currency_code }}</strong> |
| </div> |
| <div class="modal-buttons"> |
| <button class="product-button clear-cart" onclick="clearCart()">Очистить</button> |
| <button class="product-button order-button" onclick="orderViaWhatsApp()">Заказать по WhatsApp</button> |
| </div> |
| </div> |
| </div> |
| |
| <!-- Кнопка корзины --> |
| <button id="cart-button" onclick="openCartModal()"> |
| <i class="fas fa-shopping-cart"></i> |
| <span id="cart-count" style="position: absolute; top: 5px; right: 5px; background-color: #fa5252; color: white; border-radius: 50%; width: 20px; height: 20px; font-size: 0.8rem; display: flex; justify-content: center; align-items: center; font-weight: bold;">0</span> |
| </button> |
| |
| <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; |
| const currencyCode = '{{ currency_code }}'; |
| const repoId = '{{ repo_id }}'; // Передаем repo_id в JS |
| |
| // --- Theme --- |
| function toggleTheme() { |
| document.body.classList.toggle('dark-mode'); |
| const isDarkMode = document.body.classList.contains('dark-mode'); |
| localStorage.setItem('theme', isDarkMode ? 'dark' : 'light'); |
| updateThemeIcon(isDarkMode); |
| } |
| |
| function updateThemeIcon(isDarkMode) { |
| const icon = document.querySelector('.theme-toggle i'); |
| if (isDarkMode) { |
| icon.classList.remove('fa-moon'); |
| icon.classList.add('fa-sun'); |
| } else { |
| icon.classList.remove('fa-sun'); |
| icon.classList.add('fa-moon'); |
| } |
| } |
| |
| // Apply theme on load |
| const savedTheme = localStorage.getItem('theme'); |
| const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; |
| if (savedTheme === 'dark' || (!savedTheme && prefersDark)) { |
| document.body.classList.add('dark-mode'); |
| updateThemeIcon(true); |
| } else { |
| updateThemeIcon(false); |
| } |
| |
| // --- Auto Login (using localStorage for convenience after successful login) --- |
| const storedUser = localStorage.getItem('user'); |
| // Check if user is *not* authenticated in session but *is* in localStorage |
| if (storedUser && !{{ is_authenticated|tojson }}) { |
| console.log('Attempting auto-login for:', storedUser); |
| fetch('/auto_login', { |
| method: 'POST', |
| headers: { 'Content-Type': 'application/json' }, |
| body: JSON.stringify({ login: storedUser }) |
| }) |
| .then(response => { |
| if (response.ok) { |
| console.log('Auto-login successful.'); |
| window.location.reload(); // Reload to reflect logged-in state |
| } else { |
| console.log('Auto-login failed, clearing stored user.'); |
| localStorage.removeItem('user'); // Clear invalid stored user |
| } |
| }) |
| .catch(error => { |
| console.error('Error during auto-login fetch:', error); |
| localStorage.removeItem('user'); // Clear on error too |
| }); |
| } |
| |
| |
| // --- Modals --- |
| function openModal(index) { |
| loadProductDetails(index); // Load details via fetch |
| document.getElementById('productModal').style.display = "block"; |
| document.body.style.overflow = 'hidden'; // Prevent background scrolling |
| } |
| |
| function closeModal(modalId) { |
| const modal = document.getElementById(modalId); |
| if (modal) { |
| modal.style.display = "none"; |
| } |
| // Check if any other modals are open before restoring scroll |
| const anyModalOpen = ['productModal', 'quantityModal', 'cartModal'].some(id => { |
| const m = document.getElementById(id); |
| return m && m.style.display === 'block'; |
| }); |
| if (!anyModalOpen) { |
| document.body.style.overflow = 'auto'; |
| } |
| } |
| |
| // Close modal if clicking outside the content |
| window.onclick = function(event) { |
| if (event.target.classList.contains('modal')) { |
| closeModal(event.target.id); |
| } |
| } |
| |
| // Close modal with Escape key |
| document.addEventListener('keydown', function(event) { |
| if (event.key === "Escape") { |
| closeModal('productModal'); |
| closeModal('quantityModal'); |
| closeModal('cartModal'); |
| } |
| }); |
| |
| |
| function loadProductDetails(index) { |
| const modalContent = document.getElementById('modalContent'); |
| modalContent.innerHTML = '<p>Загрузка...</p>'; // Placeholder |
| fetch('/product/' + index) |
| .then(response => { |
| if (!response.ok) { |
| throw new Error('Network response was not ok ' + response.statusText); |
| } |
| return response.text(); |
| }) |
| .then(html => { |
| modalContent.innerHTML = html; |
| // Re-initialize Swiper *after* content is loaded |
| initializeSwiper(); |
| }) |
| .catch(error => { |
| console.error('Ошибка при загрузке деталей продукта:', error); |
| modalContent.innerHTML = '<p>Не удалось загрузить информацию о товаре.</p>'; |
| }); |
| } |
| |
| function initializeSwiper() { |
| // Ensure the container exists before initializing |
| const swiperContainer = document.querySelector('#productModal .swiper-container'); |
| if (swiperContainer) { |
| // Destroy previous instance if exists (important for multiple modal openings) |
| if (swiperContainer.swiper) { |
| swiperContainer.swiper.destroy(true, true); |
| } |
| new Swiper(swiperContainer, { |
| slidesPerView: 1, |
| spaceBetween: 15, |
| loop: true, // Loop if more than one slide |
| grabCursor: true, |
| pagination: { el: '.swiper-pagination', clickable: true }, |
| navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, |
| zoom: { maxRatio: 2.5, containerClass: 'swiper-zoom-container' }, // Enable zoom |
| lazy: { loadPrevNext: true }, // Lazy load images |
| autoplay: { delay: 5000, disableOnInteraction: true, }, // Autoplay example |
| }); |
| } else { |
| console.warn("Swiper container not found in modal content."); |
| } |
| } |
| |
| |
| // --- Cart Logic --- |
| function getCart() { |
| return JSON.parse(localStorage.getItem('cart') || '[]'); |
| } |
| |
| function saveCart(cart) { |
| localStorage.setItem('cart', JSON.stringify(cart)); |
| updateCartButton(); |
| // If cart modal is open, refresh its content |
| if (document.getElementById('cartModal').style.display === 'block') { |
| renderCartModal(); |
| } |
| } |
| |
| function openQuantityModal(index) { |
| selectedProductIndex = index; |
| const product = products[index]; |
| if (!product) { |
| console.error("Product not found for index:", index); |
| alert("Ошибка: Товар не найден."); |
| return; |
| } |
| |
| const colorSelect = document.getElementById('colorSelect'); |
| colorSelect.innerHTML = ''; // Clear previous options |
| |
| const colors = product.colors || []; // Handle case where colors might be missing |
| |
| if (colors.length > 0) { |
| colors.forEach(color => { |
| const option = document.createElement('option'); |
| option.value = color; |
| option.text = color; |
| colorSelect.appendChild(option); |
| }); |
| } else { |
| // Provide a default if no colors are specified |
| const option = document.createElement('option'); |
| option.value = 'Стандартный'; // Or 'Default', 'N/A' etc. |
| option.text = 'Стандартный'; |
| colorSelect.appendChild(option); |
| } |
| |
| document.getElementById('quantityInput').value = 1; // Reset quantity |
| document.getElementById('quantityModal').style.display = 'block'; |
| document.body.style.overflow = 'hidden'; |
| } |
| |
| function confirmAddToCart() { |
| if (selectedProductIndex === null) return; |
| |
| const quantityInput = document.getElementById('quantityInput'); |
| const quantity = parseInt(quantityInput.value); |
| const colorSelect = document.getElementById('colorSelect'); |
| const color = colorSelect.value; // Always get value, even if default |
| |
| if (isNaN(quantity) || quantity <= 0) { |
| alert("Пожалуйста, укажите корректное количество (больше 0)."); |
| quantityInput.focus(); |
| return; |
| } |
| |
| let cart = getCart(); |
| const product = products[selectedProductIndex]; |
| if (!product) { |
| console.error("Product not found during confirmAddToCart for index:", selectedProductIndex); |
| alert("Ошибка добавления товара в корзину."); |
| return; |
| } |
| |
| // Use name and color to uniquely identify items in the cart |
| const cartItemId = `${product.name}-${color}`; |
| const existingItemIndex = cart.findIndex(item => item.id === cartItemId); |
| |
| if (existingItemIndex > -1) { |
| // Update quantity of existing item |
| cart[existingItemIndex].quantity += quantity; |
| } else { |
| // Add new item to cart |
| cart.push({ |
| id: cartItemId, |
| name: product.name, |
| price: product.price, // Price is already in KGS |
| photo: product.photos && product.photos.length > 0 ? product.photos[0] : null, |
| quantity: quantity, |
| color: color // Store selected color/variant |
| }); |
| } |
| |
| saveCart(cart); |
| closeModal('quantityModal'); |
| // Optionally show a confirmation message |
| // alert(`${product.name} (${color}) x ${quantity} добавлен(о) в корзину!`); |
| } |
| |
| function updateCartButton() { |
| const cart = getCart(); |
| const cartButton = document.getElementById('cart-button'); |
| const cartCount = document.getElementById('cart-count'); |
| const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0); |
| |
| if (totalItems > 0) { |
| cartButton.style.display = 'flex'; // Use flex for centering icon |
| cartCount.textContent = totalItems; |
| cartCount.style.display = 'flex'; // Show count bubble |
| } else { |
| cartButton.style.display = 'none'; |
| cartCount.style.display = 'none'; // Hide count bubble |
| } |
| } |
| |
| function openCartModal() { |
| renderCartModal(); // Populate cart content |
| document.getElementById('cartModal').style.display = 'block'; |
| document.body.style.overflow = 'hidden'; |
| } |
| |
| function renderCartModal() { |
| const cart = getCart(); |
| const cartContent = document.getElementById('cartContent'); |
| let total = 0; |
| |
| if (cart.length === 0) { |
| cartContent.innerHTML = '<p>Ваша корзина пуста.</p>'; |
| } else { |
| cartContent.innerHTML = cart.map((item, index) => { |
| const itemPrice = parseFloat(item.price) || 0; // Ensure price is a number |
| const itemTotal = itemPrice * item.quantity; |
| total += itemTotal; |
| const photoUrl = item.photo |
| ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` |
| : 'https://via.placeholder.com/60?text=N/A'; // Placeholder if no photo |
| |
| return ` |
| <div class="cart-item"> |
| <img src="${photoUrl}" alt="${item.name}"> |
| <div class="cart-item-details"> |
| <strong>${item.name}</strong> |
| <p>Вариант: ${item.color}</p> |
| <p>${itemPrice.toFixed(2)} ${currencyCode} × ${item.quantity}</p> |
| <button onclick="removeFromCart(${index})" style="background: none; border: none; color: #fa5252; cursor: pointer; font-size: 0.8rem; padding: 0;">Удалить</button> |
| </div> |
| <span class="cart-item-total">${itemTotal.toFixed(2)} ${currencyCode}</span> |
| </div> |
| `; |
| }).join(''); |
| } |
| |
| document.getElementById('cartTotal').textContent = total.toFixed(2); |
| } |
| |
| function removeFromCart(index) { |
| let cart = getCart(); |
| if (index >= 0 && index < cart.length) { |
| cart.splice(index, 1); // Remove item at index |
| saveCart(cart); // Update localStorage and UI |
| } |
| } |
| |
| function clearCart() { |
| if (confirm("Вы уверены, что хотите очистить корзину?")) { |
| localStorage.removeItem('cart'); |
| saveCart([]); // Trigger UI update with empty cart |
| closeModal('cartModal'); |
| } |
| } |
| |
| function orderViaWhatsApp() { |
| const cart = getCart(); |
| if (cart.length === 0) { |
| alert("Ваша корзина пуста! Добавьте товары для заказа."); |
| return; |
| } |
| |
| let total = 0; |
| let orderText = "Здравствуйте! Хочу сделать заказ:\n\n"; // Приветствие |
| |
| cart.forEach((item, index) => { |
| const itemPrice = parseFloat(item.price) || 0; |
| const itemTotal = itemPrice * item.quantity; |
| total += itemTotal; |
| orderText += `${index + 1}. ${item.name}\n`; |
| orderText += ` Вариант: ${item.color}\n`; |
| orderText += ` Кол-во: ${item.quantity}\n`; |
| orderText += ` Цена: ${itemPrice.toFixed(2)} ${currencyCode}\n`; |
| orderText += ` Сумма: ${itemTotal.toFixed(2)} ${currencyCode}\n\n`; |
| }); |
| |
| orderText += `*Итого: ${total.toFixed(2)} ${currencyCode}*\n\n`; // Выделение итоговой суммы |
| |
| // Добавляем информацию о пользователе из сессии, если доступна |
| const userInfo = { |
| country: "{{ session.get('country', '') }}", // Используем Jinja для получения данных сессии |
| city: "{{ session.get('city', '') }}", |
| user: "{{ session.get('user', 'Гость') }}" |
| }; |
| |
| if (userInfo.user !== 'Гость') { |
| orderText += `Информация о заказчике:\n`; |
| orderText += `Логин: ${userInfo.user}\n`; |
| if (userInfo.country) orderText += `Страна: ${userInfo.country}\n`; |
| if (userInfo.city) orderText += `Город: ${userInfo.city}\n`; |
| } else { |
| orderText += `Пожалуйста, укажите ваши контактные данные для оформления заказа.\n`; |
| } |
| |
| |
| const whatsappNumber = "996555360556"; // Номер WhatsApp |
| // Кодируем текст для URL |
| const encodedText = encodeURIComponent(orderText); |
| // Формируем ссылку |
| const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${encodedText}`; |
| |
| // Открываем WhatsApp в новой вкладке |
| window.open(whatsappUrl, '_blank'); |
| } |
| |
| // --- Filtering and Search --- |
| 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 activeCategoryButton = document.querySelector('.category-filter.active'); |
| const activeCategory = activeCategoryButton ? activeCategoryButton.dataset.category : 'all'; |
| |
| document.querySelectorAll('.products-grid .product').forEach(productElement => { |
| const name = productElement.getAttribute('data-name') || ''; |
| const description = productElement.getAttribute('data-description') || ''; |
| const category = productElement.getAttribute('data-category') || 'Без категории'; |
| |
| const matchesSearch = !searchTerm || name.includes(searchTerm) || description.includes(searchTerm); |
| const matchesCategory = activeCategory === 'all' || category === activeCategory; |
| |
| // Показываем или скрываем товар |
| productElement.style.display = matchesSearch && matchesCategory ? 'flex' : 'none'; // Используем flex т.к. product имеет display:flex |
| }); |
| } |
| |
| // --- Initial Setup --- |
| updateCartButton(); // Initialize cart button state on page load |
| |
| </script> |
| </body> |
| </html> |
| ''' |
| return render_template_string( |
| catalog_html, |
| products=products, |
| categories=categories, |
| repo_id=REPO_ID, |
| is_authenticated=is_authenticated, |
| store_address=STORE_ADDRESS, |
| session=session, |
| currency_code=CURRENCY_CODE |
| |
| ) |
|
|
| @app.route('/product/<int:index>') |
| def product_detail(index): |
| """Отображает детальную информацию о продукте в модальном окне.""" |
| data = load_data() |
| products = data.get('products', []) |
|
|
| try: |
| product = products[index] |
| except IndexError: |
| |
| return "<p>Товар не найден.</p>", 404 |
|
|
| |
| detail_html = ''' |
| <div> {# Обертка для содержимого #} |
| <h2 style="font-size: 1.8rem; font-weight: 600; margin-bottom: 15px; color: #d6336c;">{{ product.get('name', 'Без названия') }}</h2> |
| |
| {# Swiper контейнер для изображений #} |
| <div class="swiper-container"> |
| <div class="swiper-wrapper"> |
| {% if product.get('photos') and product['photos']|length > 0 %} |
| {% for photo in product['photos'] %} |
| <div class="swiper-slide"> |
| <div class="swiper-zoom-container"> {# Обертка для зума #} |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" |
| alt="Фото {{ product.get('name', '') }}" |
| loading="lazy"> {# Ленивая загрузка #} |
| </div> |
| </div> |
| {% endfor %} |
| {% else %} |
| {# Слайд-заглушка, если фото нет #} |
| <div class="swiper-slide"> |
| <i class="fas fa-image" style="font-size: 6rem; color: #dee2e6;"></i> |
| {# <img src="https://via.placeholder.com/400?text=No+Image" alt="Нет изображения"> #} |
| </div> |
| {% endif %} |
| </div> |
| {# Элементы управления Swiper #} |
| {% if product.get('photos') and product['photos']|length > 1 %} {# Показываем пагинацию/навигацию только если больше 1 фото #} |
| <div class="swiper-pagination"></div> |
| <div class="swiper-button-next"></div> |
| <div class="swiper-button-prev"></div> |
| {% endif %} |
| </div> |
| |
| <p style="margin-top: 20px;"><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> |
| <p class="price"><strong>Цена:</strong> {{ "%.2f"|format(product.get('price', 0)) }} {{ currency_code }}</p> |
| <p><strong>Описание:</strong><br>{{ product.get('description', 'Описание отсутствует.')|replace('\n', '<br>')|safe }}</p> {# Заменяем переносы строк на <br> #} |
| |
| {% if product.get('colors') and product['colors']|length > 0 %} |
| <p><strong>Доступные варианты/цвета:</strong> {{ product['colors']|join(', ') }}</p> |
| {% endif %} |
| </div> |
| ''' |
| |
| return render_template_string( |
| detail_html, |
| product=product, |
| repo_id=REPO_ID, |
| currency_code=CURRENCY_CODE |
| |
| ) |
|
|
| |
|
|
| |
|
|
| @app.route('/login', methods=['GET', 'POST']) |
| def login(): |
| """Страница входа пользователя.""" |
| if 'user' in session: |
| return redirect(url_for('catalog')) |
|
|
| if request.method == 'POST': |
| login = request.form.get('login') |
| password = request.form.get('password') |
| users = load_users() |
|
|
| if login in users and users[login].get('password') == password: |
| |
| if users[login].get('status', 'active') == 'active': |
| session['user'] = login |
| session['country'] = users[login].get('country', '') |
| session['city'] = users[login].get('city', '') |
| |
| logging.info(f"Пользователь {login} успешно вошел в систему.") |
| |
| |
| response = redirect(url_for('catalog')) |
| |
| |
| |
| return response |
| else: |
| logging.warning(f"Попытка входа заблокированного пользователя: {login}") |
| error = "Ваш аккаунт неактивен. Обратитесь к администратору." |
| return render_template_string(login_template, error=error) |
|
|
| else: |
| logging.warning(f"Неудачная попытка входа для логина: {login}") |
| error = "Неверный логин или пароль." |
| return render_template_string(login_template, error=error) |
|
|
| |
| return render_template_string(login_template, error=None) |
|
|
| |
| login_template = ''' |
| <!DOCTYPE html> |
| <html lang="ru"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>Вход - Soola Cosmetics</title> |
| <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet"> |
| <style> |
| body { font-family: 'Poppins', sans-serif; background: linear-gradient(135deg, #fde2e4, #fad2e1); display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 20px; } |
| .container { max-width: 400px; width: 100%; background: #fff; padding: 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.1); text-align: center; } |
| h2 { margin-bottom: 25px; color: #d6336c; font-weight: 600; } |
| label { display: block; text-align: left; margin: 10px 0 5px; font-weight: 500; color: #495057; } |
| input[type="text"], input[type="password"] { width: 100%; padding: 12px 15px; margin-bottom: 15px; border: 1px solid #ced4da; border-radius: 8px; font-size: 1rem; } |
| input:focus { border-color: #d6336c; outline: none; box-shadow: 0 0 0 2px rgba(214, 51, 108, 0.2); } |
| button { width: 100%; padding: 12px; background-color: #d6336c; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 1.1rem; font-weight: 500; transition: background-color 0.3s ease; margin-top: 10px; } |
| button:hover { background-color: #c2255c; } |
| .error-message { color: #fa5252; margin-top: 15px; font-weight: 500; } |
| .back-link { display: block; margin-top: 20px; color: #868e96; text-decoration: none; font-size: 0.9rem; } |
| .back-link:hover { text-decoration: underline; color: #495057; } |
| /* Ссылка на регистрацию убрана */ |
| </style> |
| </head> |
| <body> |
| <div class="container"> |
| <h2>Вход в Soola Cosmetics</h2> |
| {% if error %} |
| <p class="error-message">{{ error }}</p> |
| {% endif %} |
| <form method="POST" id="loginForm"> |
| <label for="login">Логин:</label> |
| <input type="text" id="login" name="login" required> |
| <label for="password">Пароль:</label> |
| <input type="password" id="password" name="password" required> |
| <button type="submit">Войти</button> |
| </form> |
| <a href="{{ url_for('catalog') }}" class="back-link">Вернуться в каталог</a> |
| <!-- Ссылка на регистрацию убрана --> |
| </div> |
| <script> |
| // Сохраняем логин в localStorage при успешной отправке формы |
| // Лучше делать это на стороне сервера после успешной аутентификации, |
| // но для простоты демонстрации авто-логина оставим здесь. |
| const loginForm = document.getElementById('loginForm'); |
| if (loginForm) { |
| loginForm.addEventListener('submit', function() { |
| const loginInput = document.getElementById('login'); |
| if (loginInput && loginInput.value) { |
| try { |
| localStorage.setItem('user', loginInput.value); |
| console.log('Login saved to localStorage:', loginInput.value); |
| } catch (e) { |
| console.error("Failed to save login to localStorage:", e); |
| } |
| } |
| }); |
| } |
| </script> |
| </body> |
| </html> |
| ''' |
|
|
| @app.route('/auto_login', methods=['POST']) |
| def auto_login(): |
| """Обрабатывает попытку автоматического входа.""" |
| if 'user' in session: |
| return "Already logged in", 200 |
|
|
| data = request.get_json() |
| if not data or 'login' not in data: |
| return "Missing login", 400 |
|
|
| login = data.get('login') |
| users = load_users() |
|
|
| if login in users: |
| |
| |
| |
| if users[login].get('status', 'active') == 'active': |
| session['user'] = login |
| session['country'] = users[login].get('country', '') |
| session['city'] = users[login].get('city', '') |
| |
| logging.info(f"Пользователь {login} автоматически вошел в систему.") |
| return "OK", 200 |
| else: |
| logging.warning(f"Попытка авто-входа неактивного пользователя: {login}") |
| return "User inactive", 403 |
| else: |
| logging.warning(f"Попытка авто-входа несуществующего пользователя: {login}") |
| return "User not found", 404 |
|
|
| @app.route('/logout') |
| def logout(): |
| """Выход пользователя из системы.""" |
| logged_out_user = session.pop('user', None) |
| session.pop('country', None) |
| session.pop('city', None) |
| |
| if logged_out_user: |
| logging.info(f"Пользователь {logged_out_user} вышел из системы.") |
| |
| |
| response = redirect(url_for('catalog')) |
| |
| |
| return ''' |
| <script> |
| localStorage.removeItem('user'); |
| window.location.href = "{}"; |
| </script> |
| <p>Выход... Перенаправление в <a href="{}">каталог</a>.</p> |
| '''.format(url_for('catalog'), url_for('catalog')) |
| else: |
| return redirect(url_for('catalog')) |
|
|
| |
| @app.route('/admin', methods=['GET', 'POST']) |
| def admin(): |
| """Административная панель.""" |
| |
| |
| users = load_users() |
| is_admin = False |
| if 'user' in session: |
| |
| |
| |
| |
| if session['user'] == 'admin': |
| is_admin = True |
|
|
| if not is_admin: |
| |
| logging.warning(f"Попытка несанкционированного доступа в /admin пользователем: {session.get('user', 'Аноним')}") |
| return redirect(url_for('login')) |
|
|
| |
| data = load_data() |
| products = data.get('products', []) |
| categories = data.get('categories', []) |
| |
|
|
| |
| if request.method == 'POST': |
| action = request.form.get('action') |
| logging.info(f"Admin action received: {action}") |
|
|
| try: |
| 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) |
| categories.sort() |
| save_data(data) |
| logging.info(f"Категория '{category_name}' добавлена.") |
| elif not category_name: |
| logging.warning("Попытка добавить пустую категорию.") |
| else: |
| logging.warning(f"Попытка добавить существующую категорию: {category_name}") |
| return redirect(url_for('admin')) |
|
|
| elif action == 'delete_category': |
| category_to_delete = request.form.get('category_name') |
| if category_to_delete and category_to_delete in categories: |
| categories.remove(category_to_delete) |
| |
| for product in products: |
| if product.get('category') == category_to_delete: |
| product['category'] = 'Без категории' |
| save_data(data) |
| logging.info(f"Категория '{category_to_delete}' удалена.") |
| else: |
| logging.warning(f"Попытка удалить несуществующую или не указанную категорию: {category_to_delete}") |
| return redirect(url_for('admin')) |
|
|
|
|
| elif action == 'add_product': |
| name = request.form.get('name', '').strip() |
| price_str = request.form.get('price', '0').replace(',', '.') |
| description = request.form.get('description', '').strip() |
| category = request.form.get('category', 'Без категории') |
| photos_files = request.files.getlist('photos') |
| |
| colors = list(dict.fromkeys(filter(None, [c.strip() for c in request.form.getlist('colors')]))) |
|
|
| if not name or not description: |
| logging.warning("Попытка добавить товар без имени или описания.") |
| |
| return redirect(url_for('admin')) |
|
|
| try: |
| price = round(float(price_str), 2) |
| if price < 0: price = 0 |
| except ValueError: |
| logging.warning(f"Некорректное значение цены при добавлении товара: {price_str}") |
| price = 0 |
|
|
| photos_list = upload_photos(photos_files, name) |
|
|
| new_product = { |
| 'name': name, |
| 'price': price, |
| 'description': description, |
| 'category': category if category in categories else 'Без категории', |
| 'photos': photos_list, |
| 'colors': colors if colors else [] |
| } |
| products.append(new_product) |
| save_data(data) |
| logging.info(f"Товар '{name}' успешно добавлен.") |
| return redirect(url_for('admin')) |
|
|
| elif action == 'edit_product': |
| index = int(request.form.get('index', -1)) |
| if 0 <= index < len(products): |
| product_to_edit = products[index] |
| name = request.form.get('name', '').strip() |
| price_str = request.form.get('price', '0').replace(',', '.') |
| description = request.form.get('description', '').strip() |
| category = request.form.get('category', 'Без категории') |
| photos_files = request.files.getlist('photos') |
| |
| colors = list(dict.fromkeys(filter(None, [c.strip() for c in request.form.getlist('colors')]))) |
|
|
| if not name or not description: |
| logging.warning(f"Попытка редактирования товара (индекс {index}) с пустым именем или описанием.") |
| return redirect(url_for('admin')) |
|
|
| try: |
| price = round(float(price_str), 2) |
| if price < 0: price = 0 |
| except ValueError: |
| logging.warning(f"Некорректное значение цены при редактировании товара {name}: {price_str}") |
| price = product_to_edit.get('price', 0) |
|
|
| |
| if photos_files and any(f.filename for f in photos_files): |
| |
| |
| new_photos_list = upload_photos(photos_files, name) |
| product_to_edit['photos'] = new_photos_list |
| logging.info(f"Фотографии для товара '{name}' обновлены.") |
| |
|
|
| |
| product_to_edit['name'] = name |
| product_to_edit['price'] = price |
| product_to_edit['description'] = description |
| product_to_edit['category'] = category if category in categories else 'Без категории' |
| product_to_edit['colors'] = colors if colors else [] |
|
|
| save_data(data) |
| logging.info(f"Товар '{name}' (индекс {index}) успешно отредактирован.") |
| else: |
| logging.error(f"Попытка редактирования несуществующего товара с индексом {index}.") |
| return redirect(url_for('admin')) |
|
|
| elif action == 'delete_product': |
| index = int(request.form.get('index', -1)) |
| if 0 <= index < len(products): |
| deleted_product = products.pop(index) |
| |
| |
| save_data(data) |
| logging.info(f"Товар '{deleted_product.get('name', 'Без имени')}' (индекс {index}) удален.") |
| else: |
| logging.error(f"Попытка удаления несуществующего товара с индексом {index}.") |
| return redirect(url_for('admin')) |
|
|
| |
| elif action == 'add_user': |
| login = request.form.get('login', '').strip() |
| password = request.form.get('password', '').strip() |
| first_name = request.form.get('first_name', '').strip() |
| last_name = request.form.get('last_name', '').strip() |
| country = request.form.get('country', '').strip() |
| city = request.form.get('city', '').strip() |
|
|
| if not login or not password or not first_name: |
| logging.warning("Попытка добавить пользователя с неполными данными (логин, пароль, имя обязательны).") |
| |
| return redirect(url_for('admin')) |
|
|
| if login in users: |
| logging.warning(f"Попытка добавить пользователя с существующим логином: {login}") |
| |
| return redirect(url_for('admin')) |
|
|
| users[login] = { |
| 'password': password, |
| 'first_name': first_name, |
| 'last_name': last_name, |
| 'country': country, |
| 'city': city, |
| 'status': 'active' |
| |
| } |
| save_users(users) |
| logging.info(f"Пользователь '{login}' успешно добавлен.") |
| return redirect(url_for('admin')) |
|
|
| elif action == 'delete_user': |
| login_to_delete = request.form.get('login') |
| if login_to_delete == 'admin': |
| logging.warning("Попытка удаления основного администратора.") |
| return redirect(url_for('admin')) |
|
|
| if login_to_delete and login_to_delete in users: |
| del users[login_to_delete] |
| save_users(users) |
| logging.info(f"Пользователь '{login_to_delete}' удален.") |
| else: |
| logging.warning(f"Попытка удалить несуществующего пользователя: {login_to_delete}") |
| return redirect(url_for('admin')) |
|
|
| |
| |
|
|
| except Exception as e: |
| logging.error(f"Ошибка при выполнении действия '{action}' в админ-панели: {e}", exc_info=True) |
| |
| 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>Админ-панель - Soola Cosmetics</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.0.0/css/all.min.css"> |
| <style> |
| body { font-family: 'Poppins', sans-serif; background-color: #f8f9fa; color: #343a40; padding: 20px; font-size: 14px; } |
| .container { max-width: 1300px; margin: 0 auto; } |
| .header { padding-bottom: 15px; margin-bottom: 25px; border-bottom: 1px solid #dee2e6; display: flex; justify-content: space-between; align-items: center; } |
| h1, h2 { font-weight: 600; color: #d6336c; margin-bottom: 15px; } |
| h1 { font-size: 1.8rem; } |
| h2 { font-size: 1.5rem; margin-top: 30px; } |
| form, .item-block { background: #fff; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.07); margin-bottom: 25px; } |
| label { font-weight: 500; margin-top: 10px; display: block; color: #495057; } |
| input[type="text"], input[type="number"], input[type="password"], textarea, select, input[type="file"] { |
| width: 100%; padding: 10px 12px; margin-top: 5px; border: 1px solid #ced4da; border-radius: 6px; font-size: 0.95rem; transition: border-color 0.2s ease; box-sizing: border-box; |
| } |
| input:focus, textarea:focus, select:focus { border-color: #d6336c; outline: none; box-shadow: 0 0 0 2px rgba(214, 51, 108, 0.2); } |
| textarea { min-height: 80px; resize: vertical; } |
| button[type="submit"], button[type="button"], .action-button { |
| padding: 10px 18px; border: none; border-radius: 6px; background-color: #d6336c; color: white; font-weight: 500; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease; margin-top: 15px; font-size: 0.95rem; |
| } |
| button:hover { background-color: #c2255c; } |
| button:active { transform: scale(0.98); } |
| .delete-button { background-color: #fa5252; } |
| .delete-button:hover { background-color: #f03e3e; } |
| .add-color-btn, .save-button { background-color: #38d9a9; margin-left: 5px; } |
| .add-color-btn:hover, .save-button:hover { background-color: #20c997; } |
| .item-list { display: grid; gap: 20px; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); } |
| @media (min-width: 992px) { .item-list { grid-template-columns: repeat(auto-fill, minmax(400px, 1fr)); } } |
| .item-block { padding-bottom: 15px; } |
| .item-block h3 { margin-top: 0; margin-bottom: 10px; color: #495057; font-size: 1.1rem; } |
| .item-block p { margin: 5px 0; font-size: 0.9rem; line-height: 1.5; color: #555; } |
| .item-block p strong { color: #343a40; } |
| .item-block .photos { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; } |
| .item-block .photos img { max-width: 70px; height: 70px; object-fit: cover; border-radius: 6px; border: 1px solid #eee; } |
| .item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; } |
| details { margin-top: 15px; } |
| summary { cursor: pointer; font-weight: 500; color: #007bff; } |
| summary:hover { text-decoration: underline; } |
| .edit-form { margin-top: 10px; padding: 15px; background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; } |
| .color-input-group { display: flex; gap: 10px; align-items: center; margin-top: 5px; } |
| .color-input-group input { flex-grow: 1; } |
| .remove-color-btn { background: none; border: none; color: #fa5252; font-size: 1.1rem; cursor: pointer; padding: 0 5px; } |
| .backup-section form { display: inline-block; margin-right: 10px; } |
| /* Стили для секций */ |
| .section { margin-bottom: 40px; } |
| .section h1, .section h2 { border-bottom: 2px solid #f1f3f5; padding-bottom: 8px; } |
| </style> |
| </head> |
| <body> |
| <div class="container"> |
| <div class="header"> |
| <h1>Админ-панель Soola Cosmetics</h1> |
| <a href="{{ url_for('catalog') }}" class="action-button" style="background-color: #4dabf7;">Перейти в каталог</a> |
| </div> |
| |
| <!-- Раздел Управление Товарами --> |
| <div class="section" id="products-section"> |
| <h2>Управление товарами</h2> |
| |
| <!-- Форма добавления товара --> |
| <h3>Добавить новый товар</h3> |
| <form method="POST" enctype="multipart/form-data"> |
| <input type="hidden" name="action" value="add_product"> |
| <label for="add-name">Название товара:</label> |
| <input type="text" id="add-name" name="name" required> |
| <label for="add-price">Цена ({{ currency_code }}):</label> |
| <input type="number" id="add-price" name="price" step="0.01" min="0" required> |
| <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 шт):</label> |
| <input type="file" id="add-photos" name="photos" accept="image/*" multiple> |
| <label>Варианты/Цвета (каждый вариант с новой строки или через кнопку):</label> |
| <div id="add-color-inputs"> |
| <div class="color-input-group"> |
| <input type="text" name="colors" placeholder="Например: Розовый"> |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)" title="Удалить цвет">×</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"></i> Добавить товар</button> |
| </form> |
| |
| <!-- Список товаров --> |
| <h3>Список существующих товаров ({{ products|length }})</h3> |
| <div class="item-list"> |
| {% for product in products %} |
| <div class="item-block product-item"> |
| <h3>{{ product.get('name', 'Без названия') }}</h3> |
| <p><strong>ID (индекс):</strong> {{ loop.index0 }}</p> |
| <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> |
| <p><strong>Цена:</strong> {{ "%.2f"|format(product.get('price', 0)) }} {{ currency_code }}</p> |
| <p><strong>Описание:</strong> {{ product.get('description', '')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}</p> |
| <p><strong>Варианты:</strong> {{ (product.get('colors')|join(', ')) if product.get('colors') else 'Нет вариантов' }}</p> |
| {% if product.get('photos') %} |
| <div class="photos"> |
| {% for photo in product['photos'] %} |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" |
| alt="Фото {{ product.get('name', '') }}" loading="lazy"> |
| {% endfor %} |
| </div> |
| {% endif %} |
| |
| <div class="item-actions"> |
| <!-- Редактирование в details/summary --> |
| <details> |
| <summary>Редактировать</summary> |
| <form method="POST" enctype="multipart/form-data" class="edit-form"> |
| <input type="hidden" name="action" value="edit_product"> |
| <input type="hidden" name="index" value="{{ loop.index0 }}"> |
| <label>Название:</label> |
| <input type="text" name="name" value="{{ product.get('name', '') }}" required> |
| <label>Цена ({{ currency_code }}):</label> |
| <input type="number" name="price" step="0.01" min="0" value="{{ product.get('price', 0) }}" required> |
| <label>Описание:</label> |
| <textarea name="description" rows="4" required>{{ product.get('description', '') }}</textarea> |
| <label>Категория:</label> |
| <select 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>Фотографии (Заменяет текущие, если выбраны):</label> |
| <input type="file" name="photos" accept="image/*" multiple> |
| <label>Варианты/Цвета:</label> |
| <div id="edit-color-inputs-{{ loop.index0 }}"> |
| {% for color in product.get('colors', []) %} |
| <div class="color-input-group"> |
| <input type="text" name="colors" value="{{ color }}"> |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)" title="Удалить цвет">×</button> |
| </div> |
| {% endfor %} |
| {% if not product.get('colors') %} {# Добавляем пустое поле, если цветов нет #} |
| <div class="color-input-group"> |
| <input type="text" name="colors" placeholder="Например: Красный"> |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)" title="Удалить цвет">×</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" class="save-button"><i class="fas fa-save"></i> Сохранить</button> |
| </form> |
| </details> |
| |
| <!-- Удаление --> |
| <form method="POST" onsubmit="return confirm('Вы уверены, что хотите удалить этот товар?');" style="display: inline;"> |
| <input type="hidden" name="action" value="delete_product"> |
| <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> <!-- /products-section --> |
| |
| <!-- Раздел Управление Категориями --> |
| <div class="section" id="categories-section"> |
| <h2>Управление категориями</h2> |
| |
| <!-- Форма добавления категории --> |
| <h3>Добавить новую категорию</h3> |
| <form method="POST"> |
| <input type="hidden" name="action" value="add_category"> |
| <label for="add-category-name">Название категории:</label> |
| <input type="text" id="add-category-name" name="category_name" required> |
| <button type="submit"><i class="fas fa-plus"></i> Добавить</button> |
| </form> |
| |
| <!-- Список категорий --> |
| <h3>Список существующих категорий ({{ categories|length }})</h3> |
| {% if categories %} |
| <div class="item-list"> |
| {% for category in categories %} |
| <div class="item-block category-item"> |
| <h3>{{ category }}</h3> |
| <div class="item-actions"> |
| <form method="POST" onsubmit="return confirm('Вы уверены, что хотите удалить категорию \'{{ category }}\'? Товары этой категории будут помечены как \'Без категории\'.');" style="display: inline;"> |
| <input type="hidden" name="action" value="delete_category"> |
| <input type="hidden" name="category_name" value="{{ category }}"> {# Передаем имя для удаления #} |
| <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button> |
| </form> |
| </div> |
| </div> |
| {% endfor %} |
| </div> |
| {% else %} |
| <p>Нет созданных категорий.</p> |
| {% endif %} |
| </div> <!-- /categories-section --> |
| |
| |
| <!-- Раздел Управление Пользователями --> |
| <div class="section" id="users-section"> |
| <h2>Управление пользователями</h2> |
| |
| <!-- Форма добавления пользователя --> |
| <h3>Добавить нового пользователя</h3> |
| <form method="POST"> |
| <input type="hidden" name="action" value="add_user"> |
| <label for="add-login">Логин:</label> |
| <input type="text" id="add-login" name="login" required> |
| <label for="add-password">Пароль:</label> |
| <input type="password" id="add-password" name="password" required> |
| <label for="add-first-name">Имя:</label> |
| <input type="text" id="add-first-name" name="first_name" required> |
| <label for="add-last-name">Фамилия:</label> |
| <input type="text" id="add-last-name" name="last_name"> |
| <label for="add-country">Страна:</label> |
| <input type="text" id="add-country" name="country"> |
| <label for="add-city">Город:</label> |
| <input type="text" id="add-city" name="city"> |
| <button type="submit"><i class="fas fa-user-plus"></i> Добавить пользователя</button> |
| </form> |
| |
| <!-- Список пользователей --> |
| <h3>Список зарегистрированных пользователей ({{ users|length }})</h3> |
| <div class="item-list"> |
| {% for login, user_info in users.items() %} |
| <div class="item-block user-item"> |
| <h3>Логин: {{ login }}</h3> |
| <p><strong>Имя:</strong> {{ user_info.get('first_name', 'N/A') }} {{ user_info.get('last_name', '') }}</p> |
| <p><strong>Страна:</strong> {{ user_info.get('country', 'Не указана') }}</p> |
| <p><strong>Город:</strong> {{ user_info.get('city', 'Не указан') }}</p> |
| <p><strong>Статус:</strong> {{ user_info.get('status', 'active') }}</p> |
| {# Добавить хеширование пароля перед отображением или не отображать его вовсе #} |
| {# <p><strong>Пароль:</strong> {{ user_info.get('password', 'N/A') }}</p> #} |
| <div class="item-actions"> |
| {% if login != 'admin' %} {# Защита от удаления основного админа #} |
| <form method="POST" onsubmit="return confirm('Вы уверены, что хотите удалить пользователя \'{{ login }}\'?');" style="display: inline;"> |
| <input type="hidden" name="action" value="delete_user"> |
| <input type="hidden" name="login" value="{{ login }}"> |
| <button type="submit" class="delete-button"><i class="fas fa-user-minus"></i> Удалить</button> |
| </form> |
| {# Можно добавить кнопку для блокировки/разблокировки пользователя #} |
| {# <form method="POST" style="display: inline;"> |
| <input type="hidden" name="action" value="toggle_user_status"> |
| <input type="hidden" name="login" value="{{ login }}"> |
| <button type="submit" class="action-button" style="background-color: #ffc107;"> |
| {{ 'Заблокировать' if user_info.get('status', 'active') == 'active' else 'Разблокировать' }} |
| </button> |
| </form> #} |
| {% else %} |
| <p><small>(Основной администратор)</small></p> |
| {% endif %} |
| </div> |
| </div> |
| {% else %} |
| <p>Нет зарегистрированных пользователей (кроме администратора).</p> |
| {% endfor %} |
| </div> |
| </div> <!-- /users-section --> |
| |
| <!-- Раздел Управление Базой Данных --> |
| <div class="section backup-section" id="backup-section"> |
| <h2>Управление базой данных (Hugging Face)</h2> |
| <form method="POST" action="{{ url_for('backup') }}" onsubmit="alert('Запущено создание резервной копии на Hugging Face...'); return true;"> |
| <button type="submit" class="action-button" style="background-color: #17a2b8;"><i class="fas fa-cloud-upload-alt"></i> Загрузить копию на HF</button> |
| </form> |
| <form method="GET" action="{{ url_for('download') }}" onsubmit="alert('Запущено скачивание базы данных с Hugging Face...'); return true;"> |
| <button type="submit" class="action-button" style="background-color: #28a745;"><i class="fas fa-cloud-download-alt"></i> Скачать копию с HF</button> |
| </form> |
| <p style="margin-top: 10px; font-size: 0.9em; color: #6c757d;"> |
| Примечание: Скачивание перезапишет ваши локальные файлы {{ sync_files_list|join(', ') }} версиями с Hugging Face. |
| Загрузка отправит ваши текущие локальные версии на Hugging Face. |
| Автоматическое резервное копирование происходит периодически. |
| </p> |
| </div> <!-- /backup-section --> |
| |
| <!-- Курс валют убран --> |
| |
| </div> <!-- /container --> |
| |
| <script> |
| function addColorInput(containerId) { |
| const container = document.getElementById(containerId); |
| if (container) { |
| 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)" title="Удалить цвет">×</button> |
| `; |
| container.appendChild(newInputGroup); |
| } |
| } |
| |
| function removeColorInput(button) { |
| const group = button.closest('.color-input-group'); |
| // Не удаляем последнюю строку, чтобы всегда было хотя бы одно поле |
| const container = group.parentElement; |
| if (container.querySelectorAll('.color-input-group').length > 1) { |
| group.remove(); |
| } else { |
| // Очищаем значение в последнем поле вместо удаления |
| const input = group.querySelector('input[name="colors"]'); |
| if (input) input.value = ''; |
| alert("Должен быть хотя бы один вариант/цвет. Поле очищено."); |
| } |
| } |
| </script> |
| </body> |
| </html> |
| ''' |
| |
| return render_template_string( |
| admin_html, |
| products=products, |
| categories=categories, |
| users=users, |
| repo_id=REPO_ID, |
| currency_code=CURRENCY_CODE, |
| sync_files_list=SYNC_FILES |
| |
| ) |
|
|
| def upload_photos(files, product_name): |
| """Загружает фото на HF и возвращает список имен файлов.""" |
| photos_list = [] |
| if not HF_TOKEN_WRITE: |
| logging.warning("HF_TOKEN (токен для записи) не установлен. Загрузка фото отключена.") |
| return photos_list |
|
|
| uploads_dir = 'uploads_temp' |
| os.makedirs(uploads_dir, exist_ok=True) |
| api = HfApi() |
|
|
| for photo in files: |
| if photo and photo.filename: |
| try: |
| |
| original_filename = secure_filename(photo.filename) |
| |
| timestamp = datetime.now().strftime("%Y%m%d%H%M%S%f") |
| unique_filename = f"{timestamp}_{original_filename}" |
| temp_path = os.path.join(uploads_dir, unique_filename) |
|
|
| photo.save(temp_path) |
| logging.info(f"Фото временно сохранено: {temp_path}") |
|
|
| |
| path_in_repo = f"photos/{unique_filename}" |
| api.upload_file( |
| path_or_fileobj=temp_path, |
| path_in_repo=path_in_repo, |
| repo_id=REPO_ID, |
| repo_type="dataset", |
| token=HF_TOKEN_WRITE, |
| commit_message=f"Добавлено/обновлено фото для товара '{product_name}': {unique_filename}" |
| ) |
| photos_list.append(unique_filename) |
| logging.info(f"Фото {unique_filename} успешно загружено в {REPO_ID} как {path_in_repo}") |
|
|
| |
| if os.path.exists(temp_path): |
| os.remove(temp_path) |
| logging.info(f"Временный файл удален: {temp_path}") |
|
|
| except Exception as e: |
| logging.error(f"Ошибка при обработке или загрузке фото {photo.filename}: {e}") |
| |
| if 'temp_path' in locals() and os.path.exists(temp_path): |
| try: |
| os.remove(temp_path) |
| except Exception as remove_e: |
| logging.error(f"Не удалось удалить временный файл {temp_path} после ошибки: {remove_e}") |
|
|
| |
| try: |
| if not os.listdir(uploads_dir): |
| os.rmdir(uploads_dir) |
| except OSError as e: |
| logging.warning(f"Не удалось удалить временную папку {uploads_dir}: {e}") |
|
|
| return photos_list |
|
|
| |
| @app.route('/backup', methods=['POST']) |
| def backup(): |
| """Запускает принудительную загрузку данных на HF.""" |
| |
| if 'user' not in session or session['user'] != 'admin': |
| return "Доступ запрещен", 403 |
| try: |
| logging.info("Запущена принудительная загрузка на Hugging Face...") |
| upload_db_to_hf() |
| logging.info("Принудительная загрузка на Hugging Face завершена.") |
| |
| return "Резервная копия успешно инициирована.", 200 |
| except Exception as e: |
| logging.error(f"Ошибка во время ручного бэкапа: {e}") |
| return f"Ошибка во время создания резервной копии: {e}", 500 |
|
|
| @app.route('/download', methods=['GET']) |
| def download(): |
| """Запускает принудительное скачивание данных с HF.""" |
| |
| if 'user' not in session or session['user'] != 'admin': |
| return "Доступ запрещен", 403 |
| try: |
| logging.info("Запущено принудительное скачивание с Hugging Face...") |
| download_db_from_hf() |
| logging.info("Принудительное скачивание с Hugging Face завершено.") |
| |
| |
| |
| |
| return "База данных успешно скачана с Hugging Face. Может потребоваться перезапуск для применения.", 200 |
| except RepositoryNotFoundError: |
| return f"Ошибка: Репозиторий {REPO_ID} не найден на Hugging Face.", 404 |
| except Exception as e: |
| logging.error(f"Ошибка во время ручного скачивания: {e}") |
| return f"Ошибка во время скачивания базы данных: {e}", 500 |
|
|
| |
| if __name__ == '__main__': |
| |
| if not HF_TOKEN_WRITE: |
| logging.warning("Переменная окружения HF_TOKEN (для записи) не установлена!") |
| if not HF_TOKEN_READ: |
| logging.warning("Переменная окружения HF_TOKEN_READ (для чтения) не установлена! Будет использоваться HF_TOKEN.") |
| |
| HF_TOKEN_READ = HF_TOKEN_WRITE |
| if not HF_TOKEN_READ: |
| logging.error("Токены для чтения и записи на Hugging Face не установлены! Синхронизация не будет работать.") |
|
|
| |
| logging.info("Первоначальная загрузка данных при старте приложения...") |
| try: |
| |
| download_db_from_hf() |
| except RepositoryNotFoundError: |
| logging.error(f"*** Репозиторий {REPO_ID} не найден на Hugging Face! Приложение будет использовать локальные файлы (если есть) или создаст новые. ***") |
| except Exception as e: |
| logging.error(f"*** Ошибка при первоначальном скачивании данных с Hugging Face: {e}. Будут использованы локальные файлы. ***") |
|
|
| |
| load_data() |
| load_users() |
|
|
| |
| if HF_TOKEN_WRITE: |
| backup_thread = threading.Thread(target=periodic_backup, daemon=True) |
| backup_thread.start() |
| logging.info("Поток периодического резервного копирования запущен.") |
| else: |
| logging.warning("Поток периодического резервного копирования НЕ запущен из-за отсутствия HF_TOKEN.") |
|
|
| |
| |
| |
| |
| logging.info("Запуск Flask приложения...") |
| app.run(debug=True, host='0.0.0.0', port=7860) |
|
|
|
|