|
|
|
|
| from flask import Flask, render_template_string, request, redirect, url_for, session, send_file |
| 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 |
| |
| from dotenv import load_dotenv |
|
|
| |
| load_dotenv() |
|
|
| app = Flask(__name__) |
| app.secret_key = 'your_unique_secret_key_soola_cosmetics_67890' |
| 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, format='%(asctime)s - %(levelname)s - %(message)s') |
|
|
| |
|
|
| def load_data(): |
| """Загрузка данных о товарах и категориях.""" |
| try: |
| |
| download_db_from_hf() |
| 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'] = [] |
| if 'categories' not in data: |
| data['categories'] = [] |
| return data |
| except FileNotFoundError: |
| logging.warning(f"Локальный файл {DATA_FILE} не найден. Попытка скачать с HF.") |
| try: |
| |
| |
| if not os.path.exists(DATA_FILE): |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'products': [], 'categories': []}, f) |
| logging.info(f"Создан пустой файл {DATA_FILE}") |
| return {'products': [], 'categories': []} |
| else: |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: |
| data = json.load(file) |
| logging.info(f"Данные успешно загружены из {DATA_FILE} после попытки скачивания.") |
| if not isinstance(data, dict): return {'products': [], 'categories': []} |
| if 'products' not in data: data['products'] = [] |
| if 'categories' not in data: data['categories'] = [] |
| return data |
| except (FileNotFoundError, RepositoryNotFoundError) as e: |
| logging.warning(f"Файл {DATA_FILE} не найден локально и ошибка при доступе к репозиторию HF ({e}). Создание пустой структуры.") |
| if not os.path.exists(DATA_FILE): |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'products': [], 'categories': []}, f) |
| return {'products': [], 'categories': []} |
| except json.JSONDecodeError: |
| logging.error(f"Ошибка декодирования JSON в {DATA_FILE} после попытки скачивания.") |
| return {'products': [], 'categories': []} |
| except Exception as e: |
| logging.error(f"Неизвестная ошибка при загрузке данных после попытки скачивания: {e}") |
| return {'products': [], 'categories': []} |
| except json.JSONDecodeError: |
| logging.error(f"Ошибка декодирования JSON в локальном {DATA_FILE}. Файл может быть поврежден. Возврат пустой структуры.") |
| |
| return {'products': [], 'categories': []} |
| except Exception as e: |
| logging.error(f"Неизвестная ошибка при загрузке данных ({DATA_FILE}): {e}", exc_info=True) |
| 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(specific_file=DATA_FILE) |
| except Exception as e: |
| logging.error(f"Ошибка при сохранении данных в {DATA_FILE}: {e}", exc_info=True) |
| |
| |
|
|
| def load_users(): |
| """Загрузка данных пользователей.""" |
| try: |
| |
| |
| with open(USERS_FILE, 'r', encoding='utf-8') as file: |
| users = json.load(file) |
| logging.info(f"Данные пользователей успешно загружены из {USERS_FILE}") |
| return users if isinstance(users, dict) else {} |
| except FileNotFoundError: |
| logging.warning(f"Локальный файл {USERS_FILE} не найден. Попытка скачать с HF.") |
| try: |
| download_db_from_hf(specific_file=USERS_FILE) |
| |
| with open(USERS_FILE, 'r', encoding='utf-8') as file: |
| users = json.load(file) |
| logging.info(f"Данные пользователей загружены из {USERS_FILE} после скачивания.") |
| return users if isinstance(users, dict) else {} |
| except (FileNotFoundError, RepositoryNotFoundError): |
| logging.warning(f"Файл {USERS_FILE} не найден локально и в репозитории HF. Создание пустого файла.") |
| |
| with open(USERS_FILE, 'w', encoding='utf-8') as f: json.dump({}, f) |
| return {} |
| except json.JSONDecodeError: |
| logging.error(f"Ошибка декодирования JSON в {USERS_FILE} после скачивания.") |
| return {} |
| except Exception as e: |
| logging.error(f"Неизвестная ошибка при загрузке пользователей после скачивания: {e}", exc_info=True) |
| return {} |
| except json.JSONDecodeError: |
| logging.error(f"Ошибка декодирования JSON в локальном {USERS_FILE}. Файл может быть поврежден. Возврат пустого словаря.") |
| return {} |
| except Exception as e: |
| logging.error(f"Неизвестная ошибка при загрузке пользователей ({USERS_FILE}): {e}", exc_info=True) |
| 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(specific_file=USERS_FILE) |
| except Exception as e: |
| logging.error(f"Ошибка при сохранении данных пользователей в {USERS_FILE}: {e}", exc_info=True) |
|
|
| |
|
|
| def upload_db_to_hf(specific_file=None): |
| """Загрузка файлов данных на Hugging Face. |
| Если specific_file указан, загружает только его. |
| """ |
| if not HF_TOKEN_WRITE: |
| logging.warning("Переменная окружения HF_TOKEN (для записи) не установлена. Загрузка на Hugging Face пропущена.") |
| return |
| try: |
| api = HfApi() |
| files_to_upload = [specific_file] if specific_file else SYNC_FILES |
| logging.info(f"Начало загрузки файлов {files_to_upload} на HF репозиторий {REPO_ID}...") |
|
|
| for file_name in files_to_upload: |
| if os.path.exists(file_name): |
| try: |
| 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"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" |
| ) |
| logging.info(f"Файл {file_name} успешно загружен на Hugging Face.") |
| except Exception as e: |
| logging.error(f"Ошибка при загрузке файла {file_name} на Hugging Face: {e}") |
| |
| else: |
| logging.warning(f"Файл {file_name} не найден локально, пропуск загрузки.") |
| logging.info("Загрузка файлов на HF завершена.") |
| except Exception as e: |
| logging.error(f"Общая ошибка при инициализации или загрузке на Hugging Face: {e}", exc_info=True) |
|
|
| def download_db_from_hf(specific_file=None): |
| """Скачивание файлов данных с Hugging Face. |
| Если specific_file указан, скачивает только его. |
| """ |
| if not HF_TOKEN_READ: |
| |
| logging.warning("Переменная окружения HF_TOKEN_READ не установлена. Попытка скачивания с Hugging Face без токена (может не сработать для приватных репо).") |
| |
|
|
| files_to_download = [specific_file] if specific_file else SYNC_FILES |
| logging.info(f"Начало скачивания файлов {files_to_download} с HF репозитория {REPO_ID}...") |
| downloaded_files_count = 0 |
| try: |
| |
| |
| |
|
|
| for file_name in files_to_download: |
| try: |
| |
| local_path = 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 в {local_path}.") |
| downloaded_files_count += 1 |
| except RepositoryNotFoundError: |
| logging.error(f"Репозиторий {REPO_ID} не найден на Hugging Face. Скачивание прервано.") |
| break |
| except Exception as e: |
| |
| |
| if "404" in str(e) or isinstance(e, FileNotFoundError): |
| logging.warning(f"Файл {file_name} не найден в репозитории {REPO_ID} или ошибка доступа. Пропуск скачивания этого файла.") |
| else: |
| |
| logging.error(f"Ошибка при скачивании файла {file_name} с Hugging Face: {e}", exc_info=True) |
| logging.info(f"Скачивание файлов с HF завершено. Скачано файлов: {downloaded_files_count}/{len(files_to_download)}.") |
| except RepositoryNotFoundError: |
| |
| logging.error(f"Репозиторий {REPO_ID} не найден на Hugging Face. Скачивание не выполнено.") |
| except Exception as e: |
| |
| logging.error(f"Общая ошибка при попытке скачивания с Hugging Face: {e}", exc_info=True) |
| |
|
|
|
|
| def periodic_backup(): |
| """Периодическая загрузка данных на HF.""" |
| backup_interval = 1800 |
| logging.info(f"Настройка периодического резервного копирования каждые {backup_interval} секунд.") |
| while True: |
| time.sleep(backup_interval) |
| logging.info("Запуск периодического резервного копирования...") |
| upload_db_to_hf() |
| logging.info("Периодическое резервное копирование завершено.") |
|
|
|
|
| |
|
|
| @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: #f9f9f9; color: #333; line-height: 1.6; transition: background 0.3s, color 0.3s; } |
| body.dark-mode { background: #1a202c; 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 #eee; } |
| body.dark-mode .header { border-bottom-color: #4a5568; } |
| .header h1 { font-size: 1.8rem; font-weight: 600; color: #e53e3e; } /* Логотип Soola */ |
| .auth-links { display: flex; gap: 15px; align-items: center; } |
| .auth-links a { color: #3b82f6; text-decoration: none; font-weight: 500; } |
| .auth-links a:hover { text-decoration: underline; } |
| body.dark-mode .auth-links a { color: #63b3ed; } |
| .auth-links span { font-weight: 500; } |
| body.dark-mode .auth-links span { color: #cbd5e0;} |
| .theme-toggle { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #718096; transition: color 0.3s ease; } |
| .theme-toggle:hover { color: #3b82f6; } |
| body.dark-mode .theme-toggle { color: #a0aec0; } |
| body.dark-mode .theme-toggle:hover { color: #63b3ed; } |
| .store-address { padding: 15px; text-align: center; background-color: #fff; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); font-size: 1rem; color: #555; } |
| body.dark-mode .store-address { background-color: #2d3748; color: #cbd5e0; } |
| .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 #e2e8f0; 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: #2d3748; border-color: #4a5568; color: #e2e8f0; } |
| #search-input:focus { border-color: #e53e3e; box-shadow: 0 0 0 3px rgba(229, 62, 62, 0.2); } |
| body.dark-mode #search-input:focus { border-color: #fc8181; box-shadow: 0 0 0 3px rgba(252, 129, 129, 0.3); } |
| .category-filter { padding: 8px 16px; border: 1px solid #e2e8f0; 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: #2d3748; border-color: #4a5568; color: #cbd5e0; } |
| .category-filter.active, .category-filter:hover { background-color: #e53e3e; color: white; border-color: #e53e3e; box-shadow: 0 2px 10px rgba(229, 62, 62, 0.3); } |
| body.dark-mode .category-filter.active, body.dark-mode .category-filter:hover { background-color: #fc8181; border-color: #fc8181; color: #1a202c; box-shadow: 0 2px 10px rgba(252, 129, 129, 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(auto-fill, minmax(250px, 1fr)); } } |
| .product { background: #fff; border-radius: 15px; padding: 0; /* Убираем основной padding */ 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; height: 100%; } |
| body.dark-mode .product { background: #2d3748; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); } |
| .product:hover { transform: translateY(-5px) scale(1.02); 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.3); } |
| .product-image { width: 100%; aspect-ratio: 1 / 1; /* Делаем квадратным */ background-color: #fff; border-radius: 10px 10px 0 0; /* Скругление только сверху */ overflow: hidden; display: flex; justify-content: center; align-items: center; margin-bottom: 0; /* Убираем отступ снизу */ } |
| .product-image img { max-width: 100%; max-height: 100%; object-fit: contain; transition: transform 0.3s ease; } |
| .product-image img:hover { transform: scale(1.08); } |
| .product-info { padding: 15px; flex-grow: 1; display: flex; flex-direction: column; justify-content: center; /* Центрируем контент */ } |
| .product h2 { font-size: 1.1rem; font-weight: 600; margin: 0 0 8px 0; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #333; } |
| body.dark-mode .product h2 { color: #e2e8f0; } |
| .product-price { font-size: 1.2rem; color: #e53e3e; font-weight: 700; text-align: center; margin: 5px 0; } |
| body.dark-mode .product-price { color: #fc8181; } |
| .product-description { font-size: 0.85rem; color: #718096; text-align: center; margin-bottom: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } |
| body.dark-mode .product-description { color: #a0aec0; } |
| .product-actions { padding: 0 15px 15px 15px; /* Отступы только для кнопок */ display: flex; flex-direction: column; gap: 8px; } |
| .product-button { display: block; width: 100%; padding: 10px; border: none; border-radius: 8px; background-color: #e53e3e; color: white; font-size: 0.9rem; 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: #c53030; box-shadow: 0 4px 15px rgba(197, 48, 48, 0.4); transform: translateY(-2px); } |
| .product-button i { margin-right: 5px; } |
| .add-to-cart { background-color: #38a169; } /* Зеленый для корзины */ |
| .add-to-cart:hover { background-color: #2f855a; box-shadow: 0 4px 15px rgba(47, 133, 90, 0.4); } |
| #cart-button { position: fixed; bottom: 25px; right: 25px; background-color: #e53e3e; color: white; border: none; border-radius: 50%; width: 55px; height: 55px; font-size: 1.5rem; cursor: pointer; display: none; /* Скрыта по умолчанию */ align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(229, 62, 62, 0.4); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1000; } |
| #cart-button .fa-shopping-cart { margin-right: 0; } /* Убрать отступ у иконки */ |
| #cart-button span { position: absolute; top: -5px; right: -5px; background-color: #38a169; color: white; border-radius: 50%; padding: 2px 6px; font-size: 0.7rem; font-weight: bold; } |
| .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.3s ease-out; position: relative; } |
| body.dark-mode .modal-content { background: #2d3748; color: #e2e8f0; } |
| @keyframes slideIn { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } } |
| .close { position: absolute; top: 15px; right: 15px; font-size: 1.8rem; color: #aaa; cursor: pointer; transition: color 0.3s; line-height: 1; } |
| .close:hover { color: #333; } |
| body.dark-mode .close { color: #718096; } |
| body.dark-mode .close:hover { color: #cbd5e0; } |
| .modal-content h2 { margin-top: 0; margin-bottom: 20px; color: #e53e3e; display: flex; align-items: center; gap: 10px;} |
| body.dark-mode .modal-content h2 { color: #fc8181; } |
| .cart-item { display: grid; grid-template-columns: auto 1fr auto auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #eee; } |
| body.dark-mode .cart-item { border-bottom-color: #4a5568; } |
| .cart-item:last-child { border-bottom: none; } |
| .cart-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #fff; padding: 5px; grid-column: 1; } |
| .cart-item-details { grid-column: 2; } |
| .cart-item-details strong { display: block; margin-bottom: 5px; } |
| .cart-item-price { font-size: 0.9rem; color: #555; } |
| body.dark-mode .cart-item-price { color: #a0aec0; } |
| .cart-item-total { font-weight: bold; text-align: right; grid-column: 3; } |
| .cart-item-remove { grid-column: 4; background:none; border:none; color:#f56565; cursor:pointer; font-size: 1.3em; padding: 5px; line-height: 1; } |
| .cart-item-remove:hover { color: #c53030; } |
| .quantity-input, .color-select { width: 100%; max-width: 180px; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 1rem; margin: 10px 0; box-sizing: border-box; } |
| body.dark-mode .quantity-input, body.dark-mode .color-select { background-color: #1a202c; border-color: #4a5568; color: #e2e8f0; } |
| .cart-summary { margin-top: 20px; text-align: right; border-top: 1px solid #eee; padding-top: 15px; } |
| body.dark-mode .cart-summary { border-top-color: #4a5568; } |
| .cart-summary strong { font-size: 1.2rem; } |
| .cart-actions { margin-top: 25px; display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; } |
| .cart-actions .product-button { width: auto; flex-grow: 1; } /* Кнопки растягиваются */ |
| .clear-cart { background-color: #718096; } |
| .clear-cart:hover { background-color: #4a5568; box-shadow: 0 4px 15px rgba(74, 85, 104, 0.4); } |
| .order-button { background-color: #38a169; } |
| .order-button:hover { background-color: #2f855a; box-shadow: 0 4px 15px rgba(47, 133, 90, 0.4); } |
| .notification { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background-color: #38a169; color: white; padding: 10px 20px; border-radius: 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); z-index: 1002; opacity: 0; transition: opacity 0.5s ease; font-size: 0.9rem;} |
| .notification.show { opacity: 1;} |
| .no-results-message { grid-column: 1 / -1; text-align: center; padding: 40px; font-size: 1.1rem; color: #777; } |
| body.dark-mode .no-results-message { color: #a0aec0; } |
| </style> |
| </head> |
| <body> |
| <div class="container"> |
| <div class="header"> |
| <h1>Soola Cosmetics</h1> |
| <div class="auth-links"> |
| {% if is_authenticated %} |
| <span>Привет, {{ session.get('user_info', {}).get('first_name', session['user']) }}!</span> |
| <a href="{{ url_for('logout') }}">Выйти</a> |
| {% else %} |
| <a href="{{ url_for('login') }}">Войти</a> |
| {% endif %} |
| </div> |
| <button class="theme-toggle" onclick="toggleTheme()" aria-label="Переключить тему"> |
| <i class="fas fa-moon"></i> |
| </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['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['name'] }}" |
| loading="lazy"> |
| {% else %} |
| <img src="https://via.placeholder.com/250x250.png?text=No+Image" alt="No Image" loading="lazy"> |
| {% endif %} |
| </div> |
| <div class="product-info"> |
| <h2>{{ product['name'] }}</h2> |
| {% if is_authenticated %} |
| <div class="product-price">{{ "%.2f"|format(product['price']) }} {{ currency_code }}</div> |
| {% else %} |
| <div class="product-price">Цена доступна после входа</div> |
| {% endif %} |
| <p class="product-description">{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}</p> |
| </div> |
| <div class="product-actions"> |
| <button class="product-button" onclick="openModal({{ loop.index0 }})">Подробнее</button> |
| {% if is_authenticated %} |
| <button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})"> |
| <i class="fas fa-cart-plus"></i> В корзину |
| </button> |
| {% endif %} |
| </div> |
| </div> |
| {% endfor %} |
| {# Сообщение, если нет товаров ПОСЛЕ фильтрации, будет добавлено через JS #} |
| {% if not products %} |
| <p class="no-results-message">Товары пока не добавлены.</p> |
| {% endif %} |
| </div> |
| </div> |
| |
| <!-- Product Modal --> |
| <div id="productModal" class="modal"> |
| <div class="modal-content"> |
| <span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span> |
| <div id="modalContent">Загрузка...</div> |
| </div> |
| </div> |
| |
| <!-- Quantity and Color Modal --> |
| <div id="quantityModal" class="modal"> |
| <div class="modal-content"> |
| <span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">×</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> |
| <button class="product-button add-to-cart" onclick="confirmAddToCart()"><i class="fas fa-check"></i> Добавить в корзину</button> |
| </div> |
| </div> |
| |
| <!-- Cart Modal --> |
| <div id="cartModal" class="modal"> |
| <div class="modal-content"> |
| <span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span> |
| <h2><i class="fas fa-shopping-cart"></i> Ваша корзина</h2> |
| <div id="cartContent"><p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p></div> |
| <div class="cart-summary"> |
| <strong>Итого: <span id="cartTotal">0.00</span> {{ currency_code }}</strong> |
| </div> |
| <div class="cart-actions"> |
| <button class="product-button clear-cart" onclick="clearCart()"> |
| <i class="fas fa-trash"></i> Очистить корзину |
| </button> |
| <button class="product-button order-button" onclick="orderViaWhatsApp()"> |
| <i class="fab fa-whatsapp"></i> Заказать через WhatsApp |
| </button> |
| </div> |
| </div> |
| </div> |
| |
| <!-- Cart Floating Button --> |
| <button id="cart-button" onclick="openCartModal()" aria-label="Открыть корзину"> |
| <i class="fas fa-shopping-cart"></i> |
| <span id="cart-count">0</span> |
| </button> |
| |
| <!-- Notification Placeholder --> |
| <div id="notification-placeholder"></div> |
| |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script> |
| <script> |
| // --- Global Variables --- |
| const products = {{ products|tojson }}; |
| const repoId = '{{ repo_id }}'; |
| const currencyCode = '{{ currency_code }}'; |
| const isAuthenticated = {{ is_authenticated|tojson }}; |
| let selectedProductIndex = null; |
| let cart = JSON.parse(localStorage.getItem('soolaCart') || '[]'); |
| |
| // --- Theme --- |
| function toggleTheme() { |
| document.body.classList.toggle('dark-mode'); |
| const icon = document.querySelector('.theme-toggle i'); |
| const isDarkMode = document.body.classList.contains('dark-mode'); |
| icon.classList.toggle('fa-moon', !isDarkMode); |
| icon.classList.toggle('fa-sun', isDarkMode); |
| localStorage.setItem('soolaTheme', isDarkMode ? 'dark' : 'light'); |
| } |
| |
| function applyInitialTheme() { |
| const savedTheme = localStorage.getItem('soolaTheme'); |
| if (savedTheme === 'dark') { |
| document.body.classList.add('dark-mode'); |
| const icon = document.querySelector('.theme-toggle i'); |
| if (icon) icon.classList.replace('fa-moon', 'fa-sun'); |
| } |
| } |
| |
| // --- Auto Login --- |
| function attemptAutoLogin() { |
| const storedUser = localStorage.getItem('soolaUser'); |
| if (storedUser && !isAuthenticated) { |
| 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, reloading...'); |
| window.location.reload(); |
| } else { |
| response.text().then(text => console.log(`Auto-login failed: ${response.status} ${text}`)); |
| localStorage.removeItem('soolaUser'); |
| } |
| }) |
| .catch(error => { |
| console.error('Auto-login fetch error:', error); |
| localStorage.removeItem('soolaUser'); |
| }); |
| } |
| } |
| |
| // --- Modals --- |
| function openModal(index) { |
| loadProductDetails(index); |
| const modal = document.getElementById('productModal'); |
| if (modal) { |
| modal.style.display = "block"; |
| document.body.style.overflow = 'hidden'; |
| } |
| } |
| |
| function closeModal(modalId) { |
| const modal = document.getElementById(modalId); |
| if (modal) { |
| modal.style.display = "none"; |
| } |
| const anyModalOpen = document.querySelector('.modal[style*="display: block"]'); |
| if (!anyModalOpen) { |
| document.body.style.overflow = 'auto'; |
| } |
| } |
| |
| function loadProductDetails(index) { |
| const modalContent = document.getElementById('modalContent'); |
| if (!modalContent) return; |
| modalContent.innerHTML = '<p style="text-align:center; padding: 40px;">Загрузка...</p>'; |
| fetch('/product/' + index) |
| .then(response => { |
| if (!response.ok) throw new Error(`Ошибка ${response.status}: ${response.statusText}`); |
| return response.text(); |
| }) |
| .then(data => { |
| modalContent.innerHTML = data; |
| initializeSwiper(); |
| }) |
| .catch(error => { |
| console.error('Ошибка загрузки деталей продукта:', error); |
| modalContent.innerHTML = `<p style="color: red; text-align:center; padding: 40px;">Не удалось загрузить информацию о товаре. ${error.message}</p>`; |
| }); |
| } |
| |
| function initializeSwiper() { |
| const swiperContainer = document.querySelector('#productModal .swiper-container'); |
| if (swiperContainer) { |
| new Swiper(swiperContainer, { |
| 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, containerClass: 'swiper-zoom-container' }, |
| autoplay: { delay: 5000, disableOnInteraction: true, }, // Автопрокрутка |
| }); |
| } |
| } |
| |
| // --- Cart Logic --- |
| function openQuantityModal(index) { |
| if (!isAuthenticated) { |
| alert('Пожалуйста, войдите в систему, чтобы добавить товар в корзину.'); |
| window.location.href = '/login'; |
| return; |
| } |
| selectedProductIndex = index; |
| const product = products[index]; |
| if (!product) { |
| console.error("Product not found for index:", index); |
| alert("Ошибка: товар не найден."); |
| return; |
| } |
| |
| const colorSelect = document.getElementById('colorSelect'); |
| const colorLabel = document.querySelector('label[for="colorSelect"]'); |
| colorSelect.innerHTML = ''; // Clear previous options |
| |
| const validColors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : []; |
| |
| if (validColors.length > 0) { |
| validColors.forEach(color => { |
| const option = document.createElement('option'); |
| option.value = color.trim(); |
| option.text = color.trim(); |
| colorSelect.appendChild(option); |
| }); |
| colorSelect.style.display = 'block'; |
| if(colorLabel) colorLabel.style.display = 'block'; |
| } else { |
| colorSelect.style.display = 'none'; |
| if(colorLabel) colorLabel.style.display = 'none'; |
| } |
| |
| document.getElementById('quantityInput').value = 1; |
| const modal = document.getElementById('quantityModal'); |
| if(modal) { |
| modal.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.style.display !== 'none' && colorSelect.value ? colorSelect.value : 'N/A'; |
| |
| if (isNaN(quantity) || quantity <= 0) { |
| alert("Пожалуйста, укажите корректное количество (больше 0)."); |
| quantityInput.focus(); |
| return; |
| } |
| |
| const product = products[selectedProductIndex]; |
| if (!product) { |
| 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] : null, |
| quantity: quantity, |
| color: color |
| }); |
| } |
| |
| localStorage.setItem('soolaCart', JSON.stringify(cart)); |
| closeModal('quantityModal'); |
| updateCartButton(); |
| showNotification(`${product.name} добавлен в корзину!`); |
| } |
| |
| function updateCartButton() { |
| const cartCountElement = document.getElementById('cart-count'); |
| const cartButton = document.getElementById('cart-button'); |
| if (!cartCountElement || !cartButton) return; |
| |
| let totalItems = 0; |
| cart.forEach(item => { totalItems += item.quantity; }); |
| |
| if (totalItems > 0) { |
| cartCountElement.textContent = totalItems; |
| cartButton.style.display = 'flex'; |
| } else { |
| cartCountElement.textContent = '0'; |
| cartButton.style.display = 'none'; |
| } |
| } |
| |
| function openCartModal() { |
| const cartContent = document.getElementById('cartContent'); |
| const cartTotalElement = document.getElementById('cartTotal'); |
| if (!cartContent || !cartTotalElement) return; |
| |
| let total = 0; |
| |
| if (cart.length === 0) { |
| cartContent.innerHTML = '<p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p>'; |
| cartTotalElement.textContent = '0.00'; |
| } else { |
| cartContent.innerHTML = cart.map(item => { |
| const itemTotal = item.price * item.quantity; |
| total += itemTotal; |
| const photoUrl = item.photo |
| ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` |
| : 'https://via.placeholder.com/60x60.png?text=N/A'; |
| const colorText = item.color !== 'N/A' ? ` (Цвет: ${item.color})` : ''; |
| |
| return ` |
| <div class="cart-item"> |
| <img src="${photoUrl}" alt="${item.name}"> |
| <div class="cart-item-details"> |
| <strong>${item.name}${colorText}</strong> |
| <p class="cart-item-price">${item.price.toFixed(2)} ${currencyCode} × ${item.quantity}</p> |
| </div> |
| <span class="cart-item-total">${itemTotal.toFixed(2)} ${currencyCode}</span> |
| <button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="Удалить товар">×</button> |
| </div> |
| `; |
| }).join(''); |
| cartTotalElement.textContent = total.toFixed(2); |
| } |
| const modal = document.getElementById('cartModal'); |
| if (modal) { |
| modal.style.display = 'block'; |
| document.body.style.overflow = 'hidden'; |
| } |
| } |
| |
| function removeFromCart(itemId) { |
| cart = cart.filter(item => item.id !== itemId); |
| localStorage.setItem('soolaCart', JSON.stringify(cart)); |
| openCartModal(); // Refresh cart modal content |
| updateCartButton(); // Refresh cart icon |
| } |
| |
| function clearCart() { |
| if (confirm("Вы уверены, что хотите очистить корзину?")) { |
| cart = []; |
| localStorage.removeItem('soolaCart'); |
| openCartModal(); // Update modal to show empty cart message |
| updateCartButton(); |
| // closeModal('cartModal'); // Можно закрыть или оставить открытой |
| } |
| } |
| |
| function orderViaWhatsApp() { |
| if (cart.length === 0) { |
| alert("Корзина пуста! Добавьте товары перед заказом."); |
| return; |
| } |
| let total = 0; |
| let orderText = "Новый Заказ от Soola Cosmetics:%0A%0A"; |
| cart.forEach((item, index) => { |
| const itemTotal = item.price * item.quantity; |
| total += itemTotal; |
| const colorText = item.color !== 'N/A' ? ` (Цвет: ${item.color})` : ''; |
| orderText += `${index + 1}. ${item.name}${colorText} - ${item.price.toFixed(2)} ${currencyCode} × ${item.quantity} = ${itemTotal.toFixed(2)} ${currencyCode}%0A`; |
| }); |
| orderText += `%0A*Итого: ${total.toFixed(2)} ${currencyCode}*%0A%0A`; |
| |
| const userInfo = {{ session.get('user_info', {})|tojson }}; |
| if (userInfo && userInfo.login) { |
| orderText += `Заказчик: ${userInfo.get('first_name', '')} ${userInfo.get('last_name', '')}%0A`; |
| orderText += `Логин: ${userInfo.login}%0A`; |
| orderText += `Страна: ${userInfo.get('country', 'Не указана')}%0A`; |
| orderText += `Город: ${userInfo.get('city', 'Не указан')}%0A`; |
| } else { |
| orderText += `Заказчик: (Не авторизован)%0A`; |
| } |
| |
| // Добавляем текущую дату и время |
| const now = new Date(); |
| const dateTimeString = now.toLocaleString('ru-RU'); |
| orderText += `%0AДата заказа: ${dateTimeString}`; |
| |
| |
| // Номер WhatsApp - убедитесь, что он правильный |
| const whatsappNumber = "996555360556"; |
| const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${encodeURIComponent(orderText)}`; // Используем encodeURIComponent для текста |
| window.open(whatsappUrl, '_blank'); |
| } |
| |
| // --- Filtering and Search --- |
| 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'; |
| const grid = document.getElementById('products-grid'); |
| let visibleProducts = 0; |
| |
| // Удаляем старое сообщение "не найдено", если оно есть |
| const existingNoResults = grid.querySelector('.no-results-message'); |
| if (existingNoResults) existingNoResults.remove(); |
| |
| 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; |
| |
| if (matchesSearch && matchesCategory) { |
| productElement.style.display = 'flex'; |
| visibleProducts++; |
| } else { |
| productElement.style.display = 'none'; |
| } |
| }); |
| |
| // Показать сообщение "товары не найдены", если 0 видимых товаров и был поиск/фильтр |
| if (visibleProducts === 0 && (searchTerm || activeCategory !== 'all')) { |
| const p = document.createElement('p'); |
| p.className = 'no-results-message'; |
| p.textContent = 'По вашему запросу товары не найдены.'; |
| grid.appendChild(p); |
| } |
| } |
| |
| function setupFilters() { |
| const searchInput = document.getElementById('search-input'); |
| const categoryFilters = document.querySelectorAll('.category-filter'); |
| |
| if(searchInput) searchInput.addEventListener('input', filterProducts); |
| |
| categoryFilters.forEach(filter => { |
| filter.addEventListener('click', function() { |
| categoryFilters.forEach(f => f.classList.remove('active')); |
| this.classList.add('active'); |
| filterProducts(); |
| }); |
| }); |
| } |
| |
| // --- Notifications --- |
| function showNotification(message, duration = 3000) { |
| const placeholder = document.getElementById('notification-placeholder'); |
| if (!placeholder) return; |
| |
| const notification = document.createElement('div'); |
| notification.className = 'notification'; |
| notification.textContent = message; |
| placeholder.appendChild(notification); |
| |
| // Trigger transition |
| setTimeout(() => { notification.classList.add('show'); }, 10); |
| |
| // Remove after duration |
| setTimeout(() => { |
| notification.classList.remove('show'); |
| setTimeout(() => { notification.remove(); }, 500); // Remove from DOM after fade out |
| }, duration); |
| } |
| |
| // --- Event Listeners and Initial Setup --- |
| document.addEventListener('DOMContentLoaded', () => { |
| applyInitialTheme(); |
| attemptAutoLogin(); // Try auto-login first |
| updateCartButton(); // Initialize cart button state |
| setupFilters(); // Setup search and category filters |
| |
| // Global click listener for closing modals |
| window.addEventListener('click', function(event) { |
| if (event.target.classList.contains('modal')) { |
| closeModal(event.target.id); |
| } |
| }); |
| |
| // Global keydown listener for closing modals with Escape key |
| window.addEventListener('keydown', function(event) { |
| if (event.key === 'Escape') { |
| document.querySelectorAll('.modal[style*="display: block"]').forEach(modal => { |
| closeModal(modal.id); |
| }); |
| } |
| }); |
| }); |
| |
| </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): |
| """Отдает HTML с деталями одного продукта для модального окна.""" |
| data = load_data() |
| products = data.get('products', []) |
| is_authenticated = 'user' in session |
| try: |
| product = products[index] |
| except IndexError: |
| logging.warning(f"Попытка доступа к несуществующему продукту с индексом {index}") |
| return "Товар не найден", 404 |
|
|
| detail_html = ''' |
| {# Используем Jinja комментарий #} |
| <div style="padding: 10px;"> |
| <h2 style="font-size: 1.6rem; font-weight: 600; margin-bottom: 15px; text-align: center; color: #e53e3e;">{{ product['name'] }}</h2> |
| {# Swiper Slider for Photos #} |
| <div class="swiper-container" style="max-width: 450px; margin: 0 auto 20px; border-radius: 10px; overflow: hidden; background-color: #fff;"> |
| <div class="swiper-wrapper"> |
| {% if product.get('photos') and product['photos']|length > 0 %} |
| {% for photo in product['photos'] %} |
| <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center; padding: 10px;"> |
| <div class="swiper-zoom-container"> {# Контейнер для зума #} |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" |
| alt="{{ product['name'] }} - фото {{ loop.index }}" |
| style="max-width: 100%; max-height: 400px; object-fit: contain; display: block; margin: auto; cursor: grab;"> |
| </div> |
| </div> |
| {% endfor %} |
| {% else %} |
| <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center;"> |
| <img src="https://via.placeholder.com/400x400.png?text=No+Image" alt="Изображение отсутствует" style="max-width: 100%; max-height: 400px; object-fit: contain;"> |
| </div> |
| {% endif %} |
| </div> |
| {# Элементы управления Swiper (показываем только если фото больше 1) #} |
| {% if product.get('photos') and product['photos']|length > 1 %} |
| <div class="swiper-pagination" style="position: relative; bottom: 5px;"></div> |
| <div class="swiper-button-next" style="color: #e53e3e;"></div> |
| <div class="swiper-button-prev" style="color: #e53e3e;"></div> |
| {% endif %} |
| </div> |
| |
| {# Product Details #} |
| <div style="margin-top: 20px; font-size: 1rem; line-height: 1.7;"> |
| <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> |
| {% if is_authenticated %} |
| <p style="font-size: 1.2rem; font-weight: bold; color: #e53e3e;"><strong>Цена:</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p> |
| {% else %} |
| <p><strong>Цена:</strong> <a href="{{ url_for('login') }}" style="color: #3b82f6; text-decoration: underline;">Доступна после входа</a></p> |
| {% endif %} |
| {# Используем safe фильтр для рендеринга <br> тегов из описания #} |
| <p><strong>Описание:</strong><br> {{ product.get('description', 'Описание отсутствует.')|replace('\n', '<br>')|safe }}</p> |
| {% set colors = product.get('colors', []) %} |
| {% if colors and colors|select('ne', '')|list|length > 0 %} {# Проверяем, что список не пуст и не содержит только пустые строки #} |
| <p><strong>Доступные цвета/варианты:</strong> {{ colors|select('ne', '')|join(', ') }}</p> |
| {% endif %} |
| </div> |
| </div> |
| ''' |
| return render_template_string( |
| detail_html, |
| product=product, |
| repo_id=REPO_ID, |
| is_authenticated=is_authenticated, |
| currency_code=CURRENCY_CODE |
| ) |
|
|
| |
|
|
| |
| 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, #fce3e3, #ffebeb); display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 20px; } |
| .container { max-width: 400px; width: 100%; background: #fff; padding: 30px 40px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.1); text-align: center; } |
| h2 { color: #e53e3e; margin-bottom: 25px; font-weight: 600; } |
| label { display: block; text-align: left; margin: 15px 0 5px; font-weight: 500; color: #555; } |
| input[type="text"], input[type="password"] { width: 100%; padding: 12px; margin-bottom: 15px; border: 1px solid #ddd; border-radius: 8px; box-sizing: border-box; font-size: 1rem; } |
| input:focus { border-color: #e53e3e; outline: none; box-shadow: 0 0 0 2px rgba(229, 62, 62, 0.2); } |
| button { width: 100%; padding: 12px; background-color: #e53e3e; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 1rem; font-weight: 600; transition: background-color 0.3s ease; margin-top: 10px; } |
| button:hover { background-color: #c53030; } |
| .error { color: #c53030; background-color: #ffebeb; border: 1px solid #f5c6cb; padding: 10px; border-radius: 8px; margin-bottom: 15px; font-size: 0.9rem; text-align: left;} |
| .back-link { display: inline-block; margin-top: 20px; color: #3b82f6; text-decoration: none; font-size: 0.9rem; } |
| .back-link:hover { text-decoration: underline; } |
| </style> |
| </head> |
| <body> |
| <div class="container"> |
| <h2>Вход в Soola Cosmetics</h2> |
| {% if error %} |
| <p class="error">{{ error }}</p> |
| {% endif %} |
| <form method="POST"> |
| <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> |
| </body> |
| </html> |
| ''' |
|
|
| @app.route('/login', methods=['GET', 'POST']) |
| def login(): |
| """Страница входа пользователя.""" |
| if request.method == 'POST': |
| login = request.form.get('login') |
| password = request.form.get('password') |
| if not login or not password: |
| return render_template_string(LOGIN_TEMPLATE, error="Логин и пароль не могут быть пустыми."), 400 |
|
|
| users = load_users() |
|
|
| |
| |
| |
| |
| |
| if login in users and users[login].get('password') == password: |
| user_info = users[login] |
| session['user'] = login |
| session['user_info'] = { |
| 'login': login, |
| 'first_name': user_info.get('first_name', ''), |
| 'last_name': user_info.get('last_name', ''), |
| 'country': user_info.get('country', ''), |
| 'city': user_info.get('city', '') |
| } |
| logging.info(f"Пользователь {login} успешно вошел в систему.") |
| login_response_html = f''' |
| <!DOCTYPE html><html><head><title>Перенаправление...</title></head><body> |
| <script> |
| try {{ localStorage.setItem('soolaUser', '{login}'); }} catch (e) {{ console.error("Ошибка сохранения в localStorage:", e); }} |
| window.location.href = "{url_for('catalog')}"; |
| </script> |
| <p>Вход выполнен успешно. Перенаправление в <a href="{url_for('catalog')}">каталог</a>...</p> |
| </body></html> |
| ''' |
| return login_response_html |
| else: |
| logging.warning(f"Неудачная попытка входа для пользователя {login}.") |
| error_message = "Неверный логин или пароль." |
| return render_template_string(LOGIN_TEMPLATE, error=error_message), 401 |
|
|
| |
| return render_template_string(LOGIN_TEMPLATE, error=None) |
|
|
|
|
| @app.route('/auto_login', methods=['POST']) |
| def auto_login(): |
| """Попытка автоматического входа по логину из localStorage.""" |
| data = request.get_json() |
| if not data or 'login' not in data: |
| logging.warning("Запрос auto_login без данных или логина.") |
| return "Неверный запрос", 400 |
|
|
| login = data.get('login') |
| if not login: |
| logging.warning("Попытка auto_login с пустым логином.") |
| return "Логин не предоставлен", 400 |
|
|
| users = load_users() |
| if login in users: |
| |
| |
| user_info = users[login] |
| session['user'] = login |
| session['user_info'] = { |
| 'login': login, |
| 'first_name': user_info.get('first_name', ''), |
| 'last_name': user_info.get('last_name', ''), |
| 'country': user_info.get('country', ''), |
| 'city': user_info.get('city', '') |
| } |
| logging.info(f"Автоматический вход для пользователя {login} выполнен.") |
| return "OK", 200 |
| else: |
| logging.warning(f"Неудачная попытка автоматического входа для несуществующего пользователя {login}.") |
| |
| |
| return "Ошибка авто-входа", 400 |
|
|
| @app.route('/logout') |
| def logout(): |
| """Выход пользователя из системы.""" |
| logged_out_user = session.get('user') |
| session.pop('user', None) |
| session.pop('user_info', None) |
| if logged_out_user: |
| logging.info(f"Пользователь {logged_out_user} вышел из системы.") |
| |
| logout_response_html = ''' |
| <!DOCTYPE html><html><head><title>Выход...</title></head><body> |
| <script> |
| try { localStorage.removeItem('soolaUser'); } catch (e) { console.error("Ошибка удаления из localStorage:", e); } |
| window.location.href = "/"; |
| </script> |
| <p>Выход выполнен. Перенаправление на <a href="/">главную страницу</a>...</p> |
| </body></html> |
| ''' |
| return logout_response_html |
|
|
| |
| |
| ADMIN_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"> |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> |
| <style> |
| body { font-family: 'Poppins', sans-serif; background-color: #f4f7f6; color: #333; padding: 20px; line-height: 1.6; } |
| .container { max-width: 1200px; margin: 0 auto; background-color: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.05); } |
| .header { padding-bottom: 15px; margin-bottom: 25px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;} |
| h1, h2, h3 { font-weight: 600; color: #e53e3e; margin-bottom: 15px; } |
| h1 { font-size: 1.8rem; } |
| h2 { font-size: 1.5rem; margin-top: 30px; display: flex; align-items: center; gap: 8px; } |
| h3 { font-size: 1.2rem; color: #c53030; margin-top: 20px; } |
| .section { margin-bottom: 30px; padding: 20px; background-color: #fdfdfe; border: 1px solid #eee; border-radius: 8px; } |
| form { margin-bottom: 20px; } |
| label { font-weight: 500; margin-top: 10px; display: block; color: #555; font-size: 0.9rem;} |
| input[type="text"], input[type="number"], input[type="password"], textarea, select { width: 100%; padding: 10px 12px; margin-top: 5px; border: 1px solid #ddd; border-radius: 6px; font-size: 0.95rem; box-sizing: border-box; transition: border-color 0.3s ease; } |
| input:focus, textarea:focus, select:focus { border-color: #e53e3e; outline: none; box-shadow: 0 0 0 2px rgba(229, 62, 62, 0.1); } |
| textarea { min-height: 80px; resize: vertical; } |
| input[type="file"] { padding: 8px; background-color: #f9f9f9; cursor: pointer;} |
| input[type="file"]::file-selector-button { padding: 5px 10px; border-radius: 4px; background-color: #eee; border: 1px solid #ccc; cursor: pointer; margin-right: 10px;} |
| button, .button { padding: 10px 18px; border: none; border-radius: 6px; background-color: #e53e3e; color: white; font-weight: 500; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease; margin-top: 15px; font-size: 0.95rem; display: inline-flex; align-items: center; gap: 5px; text-decoration: none; line-height: 1.2;} |
| button:hover, .button:hover { background-color: #c53030; } |
| button:active, .button:active { transform: scale(0.98); } |
| button[type="submit"] { min-width: 120px; justify-content: center; } |
| .delete-button { background-color: #718096; } |
| .delete-button:hover { background-color: #4a5568; } |
| .add-button { background-color: #38a169; } |
| .add-button:hover { background-color: #2f855a; } |
| .item-list { display: grid; gap: 20px; } |
| .item { background: #fff; padding: 15px 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.07); border: 1px solid #eee; } |
| .item p { margin: 5px 0; font-size: 0.9rem; color: #444; } |
| .item strong { color: #333; } |
| .item .description { font-size: 0.85rem; color: #666; max-height: 60px; overflow: hidden; text-overflow: ellipsis; } |
| .item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; } |
| .edit-form-container { margin-top: 15px; padding: 20px; background: #f9fafb; border: 1px dashed #ddd; border-radius: 6px; display: none; /* Скрыто по умолчанию */ } |
| details { background-color: #fdfdfe; border: 1px solid #eee; border-radius: 8px; margin-bottom: 20px; } |
| details > summary { cursor: pointer; font-weight: 600; color: #4a5568; display: block; padding: 15px; border-bottom: 1px solid #eee; list-style: none; /* Убрать стандартный маркер */ position: relative; } |
| details > summary::after { content: '\\f078'; /* FontAwesome chevron-down */ font-family: 'Font Awesome 6 Free'; font-weight: 900; position: absolute; right: 20px; top: 50%; transform: translateY(-50%); transition: transform 0.2s ease; } |
| details[open] > summary::after { transform: translateY(-50%) rotate(180deg); } |
| details[open] > summary { border-bottom: 1px solid #eee; } |
| details .form-content { padding: 20px; } |
| .color-input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; } |
| .color-input-group input { flex-grow: 1; margin: 0; } |
| .remove-color-btn { background-color: #f56565; padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; } |
| .remove-color-btn:hover { background-color: #e53e3e; } |
| .photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #eee; object-fit: cover;} |
| .sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; } |
| .flex-container { display: flex; flex-wrap: wrap; gap: 20px; } |
| .flex-item { flex: 1; min-width: 350px; /* Минимальная ширина колонки */ } |
| .message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; font-size: 0.9rem;} |
| .message.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;} |
| .message.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;} |
| </style> |
| </head> |
| <body> |
| <div class="container"> |
| <div class="header"> |
| <h1><i class="fas fa-tools"></i> Админ-панель Soola Cosmetics</h1> |
| <a href="{{ url_for('catalog') }}" class="button" style="background-color: #3b82f6;"><i class="fas fa-store"></i> Перейти в каталог</a> |
| </div> |
| |
| {# Сообщения об успехе/ошибке #} |
| {% with messages = get_flashed_messages(with_categories=true) %} |
| {% if messages %} |
| {% for category, message in messages %} |
| <div class="message {{ category }}">{{ message }}</div> |
| {% endfor %} |
| {% endif %} |
| {% endwith %} |
| |
| <div class="section"> |
| <h2><i class="fas fa-sync-alt"></i> Синхронизация с Hugging Face</h2> |
| <div class="sync-buttons"> |
| <form method="POST" action="{{ url_for('force_upload') }}" style="display: inline;" onsubmit="return confirm('Вы уверены, что хотите принудительно загрузить локальные данные на сервер? Это перезапишет данные на сервере.');"> |
| <button type="submit" class="button" title="Загрузить локальные файлы на Hugging Face"><i class="fas fa-upload"></i> Загрузить на HF</button> |
| </form> |
| <form method="POST" action="{{ url_for('force_download') }}" style="display: inline;" onsubmit="return confirm('Вы уверены, что хотите принудительно скачать данные с сервера? Это перезапишет ваши локальные файлы.');"> |
| <button type="submit" class="button delete-button" title="Скачать файлы с Hugging Face (перезапишет локальные)"><i class="fas fa-download"></i> Скачать с HF</button> |
| </form> |
| </div> |
| <p style="font-size: 0.85rem; color: #666;">Резервное копирование на Hugging Face происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.</p> |
| </div> |
| |
| |
| <div class="flex-container"> |
| <div class="flex-item"> {# Колонка Категории #} |
| <div class="section"> |
| <h2><i class="fas fa-tags"></i> Управление категориями</h2> |
| <details> |
| <summary><i class="fas fa-plus-circle"></i> Добавить новую категорию</summary> |
| <div class="form-content"> |
| <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" class="add-button"><i class="fas fa-plus"></i> Добавить</button> |
| </form> |
| </div> |
| </details> |
| |
| <h3>Существующие категории:</h3> |
| {% if categories %} |
| <div class="item-list"> |
| {% for category in categories %} |
| <div class="item" style="display: flex; justify-content: space-between; align-items: center;"> |
| <span>{{ category }}</span> |
| <form method="POST" style="margin: 0;" onsubmit="return confirm('Вы уверены, что хотите удалить категорию \'{{ category }}\'? Товары этой категории будут помечены как \'Без категории\'.');"> |
| <input type="hidden" name="action" value="delete_category"> |
| <input type="hidden" name="category_name" value="{{ category }}"> |
| <button type="submit" class="delete-button" style="padding: 5px 10px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button> |
| </form> |
| </div> |
| {% endfor %} |
| </div> |
| {% else %} |
| <p>Категорий пока нет.</p> |
| {% endif %} |
| </div> |
| </div> |
| |
| <div class="flex-item"> {# Колонка Пользователи #} |
| <div class="section"> |
| <h2><i class="fas fa-users"></i> Управление пользователями</h2> |
| <details> |
| <summary><i class="fas fa-user-plus"></i> Добавить нового пользователя</summary> |
| <div class="form-content"> |
| <form method="POST"> |
| <input type="hidden" name="action" value="add_user"> |
| <label for="login">Логин *:</label> |
| <input type="text" id="login" name="login" required> |
| <label for="password">Пароль *:</label> |
| <input type="password" id="password" name="password" required title="Пароль будет сохранен в открытом виде. Рекомендуется использовать менеджер паролей."> |
| <p style="font-size: 0.8rem; color: #777;">Внимание: пароль хранится в незашифрованном виде.</p> |
| <label for="first_name">Имя:</label> |
| <input type="text" id="first_name" name="first_name"> |
| <label for="last_name">Фамилия:</label> |
| <input type="text" id="last_name" name="last_name"> |
| <label for="country">Страна:</label> |
| <input type="text" id="country" name="country"> |
| <label for="city">Город:</label> |
| <input type="text" id="city" name="city"> |
| <button type="submit" class="add-button"><i class="fas fa-save"></i> Сохранить пользователя</button> |
| </form> |
| </div> |
| </details> |
| |
| <h3>Список пользователей:</h3> |
| {% if users %} |
| <div class="item-list"> |
| {% for login, user_data in users.items() %} |
| <div class="item"> |
| <p><strong>Логин:</strong> {{ login }}</p> |
| <p><strong>Имя:</strong> {{ user_data.get('first_name', 'N/A') }} {{ user_data.get('last_name', '') }}</p> |
| <p><strong>Локация:</strong> {{ user_data.get('city', 'N/A') }}, {{ user_data.get('country', 'N/A') }}</p> |
| <div class="item-actions"> |
| <form method="POST" style="margin: 0;" onsubmit="return confirm('Вы уверены, что хотите удалить пользователя \'{{ login }}\'?');"> |
| <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-slash"></i> Удалить</button> |
| </form> |
| {# Можно добавить кнопку редактирования пользователя, если нужно #} |
| </div> |
| </div> |
| {% endfor %} |
| </div> |
| {% else %} |
| <p>Пользователей пока нет.</p> |
| {% endif %} |
| </div> |
| </div> |
| </div> |
| |
| |
| <div class="section"> {# Секция Товары #} |
| <h2><i class="fas fa-box-open"></i> Управление товарами</h2> |
| <details> |
| <summary><i class="fas fa-plus-circle"></i> Добавить новый товар</summary> |
| <div class="form-content"> |
| <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"></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)"><i class="fas fa-times"></i></button> |
| </div> |
| </div> |
| <button type="button" class="button add-button" style="margin-top: 5px; background-color: #63b3ed;" onclick="addColorInput('add-color-inputs')"><i class="fas fa-palette"></i> Добавить поле для цвета/варианта</button> |
| <br> |
| <button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Добавить товар</button> |
| </form> |
| </div> |
| </details> |
| |
| <h3>Список товаров:</h3> |
| {% if products %} |
| <div class="item-list"> |
| {% for product in products %} |
| <div class="item"> |
| <div style="display: flex; gap: 15px; align-items: flex-start;"> |
| {# Превью первого фото #} |
| <div class="photo-preview" style="flex-shrink: 0;"> |
| {% if product.get('photos') %} |
| <a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" target="_blank" title="Посмотреть первое фото"> |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" alt="Фото"> |
| </a> |
| {% else %} |
| <img src="https://via.placeholder.com/70x70.png?text=N/A" alt="Нет фото"> |
| {% endif %} |
| </div> |
| {# Информация о товаре #} |
| <div style="flex-grow: 1;"> |
| <h3 style="margin-top: 0; margin-bottom: 5px; color: #333;">{{ product['name'] }}</h3> |
| <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> |
| <p><strong>Цена:</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p> |
| <p class="description" title="{{ product.get('description', '') }}"><strong>Описание:</strong> {{ product.get('description', 'N/A')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}</p> |
| {% set colors = product.get('colors', []) %} |
| <p><strong>Цвета/Вар-ты:</strong> {{ colors|select('ne', '')|join(', ') if colors|select('ne', '')|list|length > 0 else 'Нет' }}</p> |
| {% if product.get('photos') and product['photos']|length > 1 %} |
| <p style="font-size: 0.8rem; color: #666;">(Всего фото: {{ product['photos']|length }})</p> |
| {% endif %} |
| </div> |
| </div> |
| |
| <div class="item-actions"> |
| <button type="button" class="button" onclick="toggleEditForm('edit-form-{{ loop.index0 }}')"><i class="fas fa-edit"></i> Редактировать</button> |
| <form method="POST" style="margin:0;" onsubmit="return confirm('Вы уверены, что хотите удалить товар \'{{ product['name'] }}\'?');"> |
| <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 id="edit-form-{{ loop.index0 }}" class="edit-form-container"> |
| <h4><i class="fas fa-edit"></i> Редактирование: {{ product['name'] }}</h4> |
| <form method="POST" enctype="multipart/form-data"> |
| <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['name'] }}" required> |
| <label>Цена ({{ currency_code }}) *:</label> |
| <input type="number" name="price" step="0.01" min="0" value="{{ product['price'] }}" required> |
| <label>Описание:</label> |
| <textarea name="description" rows="4">{{ 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>Заменить фотографии (выберите новые файлы, до 10 шт.):</label> |
| <input type="file" name="photos" accept="image/*" multiple> |
| {% if product.get('photos') %} |
| <p style="font-size: 0.85rem; margin-top: 5px;">Текущие фото:</p> |
| <div class="photo-preview"> |
| {% for photo in product['photos'] %} |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="Фото {{ loop.index }}"> |
| {% endfor %} |
| </div> |
| {% endif %} |
| <label>Цвета/Варианты:</label> |
| <div id="edit-color-inputs-{{ loop.index0 }}"> |
| {% set current_colors = product.get('colors', []) %} |
| {% if current_colors and current_colors|select('ne', '')|list|length > 0 %} |
| {% for color in current_colors %} |
| {% if color.strip() %} {# Отображаем только не пустые #} |
| <div class="color-input-group"> |
| <input type="text" name="colors" value="{{ color }}"> |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> |
| </div> |
| {% endif %} |
| {% endfor %} |
| {% else %} |
| {# Добавляем одно пустое поле, если цветов нет #} |
| <div class="color-input-group"> |
| <input type="text" name="colors" placeholder="Например: Красный"> |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> |
| </div> |
| {% endif %} |
| </div> |
| <button type="button" class="button add-button" style="margin-top: 5px; background-color: #63b3ed;" onclick="addColorInput('edit-color-inputs-{{ loop.index0 }}')"><i class="fas fa-palette"></i> Добавить поле для цвета</button> |
| <br> |
| <button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Сохранить изменения</button> |
| </form> |
| </div> |
| </div> |
| {% endfor %} |
| </div> |
| {% else %} |
| <p>Товаров пока нет.</p> |
| {% endif %} |
| </div> |
| |
| </div> |
| |
| <script> |
| function toggleEditForm(formId) { |
| const formContainer = document.getElementById(formId); |
| if (formContainer) { |
| formContainer.style.display = formContainer.style.display === 'none' || formContainer.style.display === '' ? 'block' : 'none'; |
| } |
| } |
| |
| 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)"><i class="fas fa-times"></i></button> |
| \`; |
| container.appendChild(newInputGroup); |
| // Установить фокус на новый инпут |
| const newInput = newInputGroup.querySelector('input[name="colors"]'); |
| if (newInput) { |
| newInput.focus(); |
| } |
| } |
| } |
| |
| function removeColorInput(button) { |
| // Ищем ближайший родительский элемент с классом 'color-input-group' |
| const group = button.closest('.color-input-group'); |
| if (group) { |
| const container = group.parentNode; |
| group.remove(); |
| // Опционально: если удалили последний, можно добавить новый пустой |
| // if (container && container.children.length === 0) { |
| // addColorInput(container.id); |
| // } |
| } else { |
| console.warn("Не удалось найти родительский .color-input-group для кнопки удаления"); |
| } |
| } |
| </script> |
| </body> |
| </html> |
| ''' |
|
|
| @app.route('/admin', methods=['GET', 'POST']) |
| def admin(): |
| """Админ-панель для управления товарами, категориями и пользователями.""" |
| |
| |
| |
|
|
| data = load_data() |
| products = data.get('products', []) |
| categories = data.get('categories', []) |
| users = load_users() |
|
|
| 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}' добавлена.") |
| flash(f"Категория '{category_name}' успешно добавлена.", 'success') |
| elif not category_name: |
| logging.warning("Попытка добавить пустую категорию.") |
| flash("Название категории не может быть пустым.", 'error') |
| else: |
| logging.warning(f"Категория '{category_name}' уже существует.") |
| flash(f"Категория '{category_name}' уже существует.", 'error') |
|
|
| 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) |
| |
| updated_count = 0 |
| for product in products: |
| if product.get('category') == category_to_delete: |
| product['category'] = 'Без категории' |
| updated_count += 1 |
| save_data(data) |
| logging.info(f"Категория '{category_to_delete}' удалена. Обновлено товаров: {updated_count}.") |
| flash(f"Категория '{category_to_delete}' удалена.", 'success') |
| else: |
| logging.warning(f"Попытка удалить несуществующую или пустую категорию: {category_to_delete}") |
| flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error') |
|
|
|
|
| elif action == 'add_product': |
| name = request.form.get('name', '').strip() |
| price_str = request.form.get('price', '').replace(',', '.') |
| 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: |
| flash("Название и цена товара обязательны.", 'error') |
| return redirect(url_for('admin')) |
|
|
| try: |
| price = round(float(price_str), 2) |
| if price < 0: price = 0 |
| except ValueError: |
| flash("Неверный формат цены.", 'error') |
| return redirect(url_for('admin')) |
|
|
| photos_list = [] |
| if photos_files and HF_TOKEN_WRITE: |
| uploads_dir = 'uploads_temp' |
| os.makedirs(uploads_dir, exist_ok=True) |
| api = HfApi() |
| photo_limit = 10 |
| uploaded_count = 0 |
| for photo in photos_files: |
| if uploaded_count >= photo_limit: |
| logging.warning(f"Достигнут лимит фото ({photo_limit}), остальные фото проигнорированы.") |
| flash(f"Загружено только первые {photo_limit} фото.", "warning") |
| break |
| if photo and photo.filename: |
| try: |
| |
| ext = os.path.splitext(photo.filename)[1] |
| photo_filename = secure_filename(f"{name.replace(' ','_')}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}") |
| temp_path = os.path.join(uploads_dir, photo_filename) |
| photo.save(temp_path) |
| logging.info(f"Загрузка фото {photo_filename} на HF для товара {name}...") |
| 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"Add photo for product {name}" |
| ) |
| photos_list.append(photo_filename) |
| logging.info(f"Фото {photo_filename} успешно загружено.") |
| os.remove(temp_path) |
| uploaded_count += 1 |
| except Exception as e: |
| logging.error(f"Ошибка загрузки фото {photo.filename} на HF: {e}", exc_info=True) |
| flash(f"Ошибка при загрузке фото {photo.filename}.", 'error') |
| elif photo and not photo.filename: |
| logging.warning("Получен пустой объект файла фото при добавлении товара.") |
|
|
| new_product = { |
| 'name': name, 'price': price, 'description': description, |
| 'category': category if category in categories else 'Без категории', |
| 'photos': photos_list, 'colors': colors |
| } |
| products.append(new_product) |
| |
| products.sort(key=lambda x: x.get('name', '').lower()) |
| save_data(data) |
| logging.info(f"Товар '{name}' добавлен.") |
| flash(f"Товар '{name}' успешно добавлен.", 'success') |
|
|
| elif action == 'edit_product': |
| index_str = request.form.get('index') |
| if index_str is None: |
| flash("Ошибка редактирования: индекс товара не передан.", 'error') |
| return redirect(url_for('admin')) |
|
|
| try: |
| index = int(index_str) |
| if not (0 <= index < len(products)): raise IndexError("Индекс вне диапазона") |
| product_to_edit = products[index] |
| original_name = product_to_edit.get('name', 'N/A') |
| except (ValueError, IndexError): |
| flash(f"Ошибка редактирования: неверный индекс товара '{index_str}'.", 'error') |
| return redirect(url_for('admin')) |
|
|
| |
| product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip() |
| price_str = request.form.get('price', str(product_to_edit['price'])).replace(',', '.') |
| product_to_edit['description'] = request.form.get('description', product_to_edit['description']).strip() |
| category = request.form.get('category') |
| product_to_edit['category'] = category if category in categories else 'Без категории' |
| product_to_edit['colors'] = [c.strip() for c in request.form.getlist('colors') if c.strip()] |
|
|
| try: |
| price = round(float(price_str), 2) |
| if price < 0: price = 0 |
| product_to_edit['price'] = price |
| except ValueError: |
| logging.warning(f"Неверный формат цены '{price_str}' при редактировании товара {original_name}. Цена не изменена.") |
| flash(f"Неверный формат цены для товара '{original_name}'. Цена не изменена.", 'warning') |
|
|
| |
| photos_files = request.files.getlist('photos') |
| if photos_files and any(f.filename for f in photos_files) and HF_TOKEN_WRITE: |
| uploads_dir = 'uploads_temp' |
| os.makedirs(uploads_dir, exist_ok=True) |
| api = HfApi() |
| new_photos_list = [] |
| photo_limit = 10 |
| uploaded_count = 0 |
| logging.info(f"Загрузка новых фото для товара {product_to_edit['name']}...") |
| for photo in photos_files: |
| if uploaded_count >= photo_limit: |
| logging.warning(f"Достигнут лимит фото ({photo_limit}), остальные фото проигнорированы.") |
| flash(f"Загружено только первые {photo_limit} фото.", "warning") |
| break |
| if photo and photo.filename: |
| try: |
| ext = os.path.splitext(photo.filename)[1] |
| photo_filename = secure_filename(f"{product_to_edit['name'].replace(' ','_')}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}") |
| temp_path = os.path.join(uploads_dir, photo_filename) |
| photo.save(temp_path) |
| logging.info(f"Загрузка нового фото {photo_filename} на HF...") |
| 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"Update photo for product {product_to_edit['name']}") |
| new_photos_list.append(photo_filename) |
| logging.info(f"Новое фото {photo_filename} успешно загружено.") |
| os.remove(temp_path) |
| uploaded_count += 1 |
| except Exception as e: |
| logging.error(f"Ошибка загрузки нового фото {photo.filename}: {e}", exc_info=True) |
| flash(f"Ошибка при загрузке нового фото {photo.filename}.", 'error') |
|
|
| |
| if new_photos_list: |
| logging.info(f"Список фото для товара {product_to_edit['name']} обновлен.") |
| |
| product_to_edit['photos'] = new_photos_list |
| flash("Фотографии товара успешно обновлены.", "success") |
| elif uploaded_count == 0 and any(f.filename for f in photos_files): |
| flash("Не удалось загрузить новые фотографии.", "error") |
|
|
| |
| products.sort(key=lambda x: x.get('name', '').lower()) |
| save_data(data) |
| logging.info(f"Товар '{original_name}' (индекс {index}) обновлен на '{product_to_edit['name']}'.") |
| flash(f"Товар '{product_to_edit['name']}' успешно обновлен.", 'success') |
|
|
|
|
| elif action == 'delete_product': |
| index_str = request.form.get('index') |
| if index_str is None: |
| flash("Ошибка удаления: индекс товара не передан.", 'error') |
| return redirect(url_for('admin')) |
| try: |
| index = int(index_str) |
| if not (0 <= index < len(products)): raise IndexError("Индекс вне диапазона") |
| deleted_product = products.pop(index) |
| |
| save_data(data) |
| product_name = deleted_product.get('name', 'N/A') |
| logging.info(f"Товар '{product_name}' (индекс {index}) удален.") |
| flash(f"Товар '{product_name}' удален.", 'success') |
| except (ValueError, IndexError): |
| flash(f"Ошибка удаления: неверный индекс товара '{index_str}'.", 'error') |
|
|
|
|
| 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: |
| flash("Логин и пароль пользователя обязательны.", 'error') |
| return redirect(url_for('admin')) |
| if login in users: |
| flash(f"Пользователь с логином '{login}' уже существует.", 'error') |
| return redirect(url_for('admin')) |
|
|
| |
| |
| |
| |
| users[login] = { |
| 'password': password, |
| 'first_name': first_name, 'last_name': last_name, |
| 'country': country, 'city': city |
| } |
| save_users(users) |
| logging.info(f"Пользователь '{login}' добавлен.") |
| flash(f"Пользователь '{login}' успешно добавлен.", 'success') |
|
|
| elif action == 'delete_user': |
| login_to_delete = request.form.get('login') |
| if login_to_delete and login_to_delete in users: |
| del users[login_to_delete] |
| save_users(users) |
| logging.info(f"Пользователь '{login_to_delete}' удален.") |
| flash(f"Пользователь '{login_to_delete}' удален.", 'success') |
| else: |
| logging.warning(f"Попытка удалить несуществующего или пустого пользователя: {login_to_delete}") |
| flash(f"Не удалось удалить пользователя '{login_to_delete}'.", 'error') |
|
|
| else: |
| logging.warning(f"Получено неизвестное действие в админ-панели: {action}") |
| flash(f"Неизвестное действие: {action}", 'warning') |
|
|
| |
| return redirect(url_for('admin')) |
|
|
| except Exception as e: |
| logging.error(f"Ошибка при обработке действия '{action}' в админ-панели: {e}", exc_info=True) |
| flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'. Подробности в логе сервера.", 'error') |
| return redirect(url_for('admin')) |
|
|
| |
| |
| products.sort(key=lambda x: x.get('name', '').lower()) |
| |
| categories.sort() |
| |
| sorted_users = dict(sorted(users.items())) |
|
|
| return render_template_string( |
| ADMIN_TEMPLATE, |
| products=products, |
| categories=categories, |
| users=sorted_users, |
| repo_id=REPO_ID, |
| currency_code=CURRENCY_CODE |
| ) |
|
|
| |
| |
| from flask import flash |
|
|
| @app.route('/force_upload', methods=['POST']) |
| def force_upload(): |
| |
| logging.info("Запущена принудительная загрузка данных на Hugging Face...") |
| try: |
| upload_db_to_hf() |
| flash("Данные успешно загружены на Hugging Face.", 'success') |
| except Exception as e: |
| logging.error(f"Ошибка при принудительной загрузке: {e}", exc_info=True) |
| flash(f"Ошибка при загрузке на Hugging Face: {e}", 'error') |
| return redirect(url_for('admin')) |
|
|
| @app.route('/force_download', methods=['POST']) |
| def force_download(): |
| |
| logging.info("Запущено принудительное скачивание данных с Hugging Face...") |
| try: |
| download_db_from_hf() |
| flash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success') |
| except Exception as e: |
| logging.error(f"Ошибка при принудительном скачивании: {e}", exc_info=True) |
| flash(f"Ошибка при скачивании с Hugging Face: {e}", 'error') |
| return redirect(url_for('admin')) |
|
|
|
|
| |
|
|
| if __name__ == '__main__': |
| |
| 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 или HF_TOKEN_WRITE не установлена).") |
|
|
| |
| 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) |
|
|
|
|