Spaces:
Running
Running
Update app.py
Browse files123454 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575 unmodified lines636465666768697071727374751 unmodified line777879808182836 unmodified lines909192939495961 unmodified line98991001011021031041051061071081091101111121131141151161171181191201 unmodified line12212312412512612712812913013113213313413513610 unmodified lines14714814915015115215315415515615715815916016116216316416516616716816 unmodified lines1851861871881891901911 unmodified line1931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702715 unmodified lines2772782792802812822832842852862872882892902912922932943 unmodified lines2982993003013023033043053063073083093103113123133143153166 unmodified lines3233243253263273283293303313323333343353363373383393403413423433443452 unmodified lines3483493503513523533543553 unmodified lines3593603613623633643651 unmodified line36736836937037137237337437537637737837938063 unmodified lines4444454464474484494504514524534544554564571 unmodified line4594604614624634644656 unmodified lines47247347447547647747813 unmodified lines4924934944954964974984995005015025035045055065075085091 unmodified line51151251351451551651712 unmodified lines53053153253353453553619 unmodified lines55655755855956056156244 unmodified lines60760860961061161261361461561661761810 unmodified lines629630631632633634635121 unmodified lines7577587597607617627637647657667677687697707717727733 unmodified lines7777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168171 unmodified line81982082182282382482513 unmodified lines83984084184284384484517 unmodified lines8638648658668678688693 unmodified lines87387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290314 unmodified lines9189199209219229239249259269279289299309313 unmodified lines9359369379389399409419429439449459469479489499509519526 unmodified lines9599609619629639649659669679689699709719729739749759769779789799809819829839847 unmodified lines99299399499599699799899910003 unmodified lines100410051006100710081009101010111012101310141015101610171018101918 unmodified lines10381039104010411042104310442 unmodified lines1047104810491050105110521053105410551056105720 unmodified lines10781079108010811082108310841085108610871088108910906 unmodified lines109710981099110011011102110311047 unmodified lines11121113111411151116111711181119112011211122112311241125112611271128112911305 unmodified lines113611371138113911401141114211434 unmodified lines11481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751 unmodified line117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912206 unmodified lines12271228122912301231123212331234123512361 unmodified line12381239124012411242124312443 unmodified lines12481249125012511252125312547 unmodified lines12621263126412651266126712684 unmodified lines127312741275127612771278127914 unmodified lines129412951296129712981299130010 unmodified lines1311131213131314131513161317131813196 unmodified lines132613271328132913301331133219 unmodified lines1352135313541355135613571358135913601361136213634 unmodified lines13681369137013711372137313743 unmodified lines1378137913801381138213831384138513866 unmodified lines13931394139513961397139813991400140114021403140414051406140727 unmodified lines14351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145824 unmodified lines14831484148514861487148814892 unmodified lines1492149314941495149614971498149915001501150215031504150515065 unmodified lines151215131514151515161517151815191520152115221523152415259 unmodified lines15351536153715381539154015418 unmodified lines155015511552155315541555155617 unmodified lines157415751576157715781579158016 unmodified lines15971598159916001601160216031 unmodified line16051606160716081609161016118 unmodified lines16201621162216231624162516267 unmodified lines163416351636163716381639164014 unmodified lines16551656165716581659166016619 unmodified lines167116721673167416751676167725 unmodified lines1703170417051706170717081709171017111712171317141715171617171718171917209 unmodified lines173017311732173317341735173617371738173917401741174211 unmodified lines175417551756175717581759176010 unmodified lines177117721773177417751776177717 unmodified lines17951796179717981799180018011802180318041805180616 unmodified lines1823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718589 unmodified lines18681869187018711872187318748 unmodified lines188318841885188618871888188918901891189218931894189518961 unmodified line189818991900190119021903190419051906190719081909from flask import Flask, render_template_string, request, redirect, url_for, session, send_file, flashimport jsonimport os4 unmodified linesfrom huggingface_hub import HfApi, hf_hub_downloadfrom huggingface_hub.utils import RepositoryNotFoundErrorfrom werkzeug.utils import secure_filename# Импортируем dotenv для загрузки переменных окружения из .env файлаfrom dotenv import load_dotenv# Загружаем переменные окружения из файла .env (если он есть)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]# Настройки Hugging Face# Убедитесь, что REPO_ID соответствует вашему репозиторию на Hugging FaceREPO_ID = "Kgshop/Soola" # Замените на ваш ID, если он другойHF_TOKEN_WRITE = os.getenv("HF_TOKEN")HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") # Может быть тем же, что и HF_TOKEN# Адрес магазинаSTORE_ADDRESS = "Рынок Дордой, Джунхай, терминал, 38" # Единый адрес# Валюта (только KGS)CURRENCY_CODE = 'KGS'CURRENCY_NAME = 'Кыргызский сом (с)'# Настройка логирования# Уровни: DEBUG, INFO, WARNING, ERROR, CRITICALlogging.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': []}5 unmodified linesexcept FileNotFoundError:logging.warning(f"Локальный файл {DATA_FILE} не найден. Попытка скачать с HF.")try:# download_db_from_hf() # Уже вызывали выше, избегаем повторного вызова при первой ошибке# Если скачивание не удалось выше, пытаемся просто создать пустые файлы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: # Если файл появился после download_db_from_hfwith open(DATA_FILE, 'r', encoding='utf-8') as file:data = json.load(file)logging.info(f"Данные успешно загружены из {DATA_FILE} после попытки скачивания.")1 unmodified lineif 'products' not in data: data['products'] = []if 'categories' not in data: data['categories'] = []return dataexcept (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)6 unmodified linesreturn {'products': [], 'categories': []}except json.JSONDecodeError:logging.error(f"Ошибка декодирования JSON в локальном {DATA_FILE}. Файл может быть поврежден. Возврат пустой структуры.")# Можно добавить логику восстановления из бэкапа или HF, если нужноreturn {'products': [], 'categories': []}except Exception as e:logging.error(f"Неизвестная ошибка при загрузке данных ({DATA_FILE}): {e}", exc_info=True)1 unmodified linedef 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}")# Загрузка на HF после сохранения (можно сделать опциональной)upload_db_to_hf(specific_file=DATA_FILE)except Exception as e:logging.error(f"Ошибка при сохранении данных в {DATA_FILE}: {e}", exc_info=True)# В реальном приложении можно добавить механизм повторной попытки или уведомления# raise # Перевыброс исключения может остановить приложение, если не обработан вышеdef load_users():"""Загрузка данных пользователей."""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}")1 unmodified lineexcept 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:10 unmodified linesreturn {}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}")# Загрузка на HF после сохраненияupload_db_to_hf(specific_file=USERS_FILE)except Exception as e:logging.error(f"Ошибка при сохранении данных пользователей в {USERS_FILE}: {e}", exc_info=True)# --- Функции синхронизации с Hugging Face ---def upload_db_to_hf(specific_file=None):"""Загрузка файлов данных на Hugging Face.Если specific_file указан, загружает только его."""if not HF_TOKEN_WRITE:logging.warning("Переменная окружения HF_TOKEN (для записи) не установлена. Загрузка на Hugging Face пропущена.")return16 unmodified lineslogging.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 завершена.")1 unmodified linelogging.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_FILESlogging.info(f"Начало скачивания файлов {files_to_download} с HF репозитория {REPO_ID}...")downloaded_files_count = 0try:# HfApi() не нужен для hf_hub_download, но можно использовать для проверки существования репо# api = HfApi()# api.dataset_info(repo_id=REPO_ID, token=HF_TOKEN_READ) # Проверка доступности репо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 += 1except RepositoryNotFoundError:logging.error(f"Репозиторий {REPO_ID} не найден на Hugging Face. Скачивание прервано.")break # Прерываем цикл, если репозиторий не найденexcept Exception as e: # Ловим исключения для каждого файла отдельно# Проверяем, является ли ошибка 'Not Found' для конкретного файла# hf_hub_download часто возвращает HTTPError или FileNotFoundError внутри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:# Общая ошибка, если не удалось даже инициализировать Api() или что-то глобальноеlogging.error(f"Общая ошибка при попытке скачивания с Hugging Face: {e}", exc_info=True)# Не прерываем работу приложения, будем использовать локальные файлы, если они естьdef periodic_backup():"""Периодическая загрузка данных на HF."""backup_interval = 1800 # 30 минутlogging.info(f"Настройка периодического резервного копирования каждые {backup_interval} секунд.")while True:time.sleep(backup_interval)logging.info("Запуск периодического резервного копирования...")upload_db_to_hf() # Загружает все SYNC_FILESlogging.info("Периодическое резервное копирование завершено.")# --- Маршруты Flask ---@app.route('/')def catalog():"""Главная страница каталога товаров."""data = load_data()products = data.get('products', [])categories = data.get('categories', [])is_authenticated = 'user' in session# Убираем артефакты {/**/} из HTML шаблонаcatalog_html = '''<!DOCTYPE html><html lang="ru">5 unmodified lines<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: #f0f9f4; color: #2d332f; line-height: 1.6; transition: background 0.3s, color 0.3s; }body.dark-mode { background: #1a2b26; color: #c8d8d3; }.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 #d1e7dd; }body.dark-mode .header { border-bottom-color: #2c4a41; }.header h1 { font-size: 1.8rem; font-weight: 600; color: #1C6758; } /* Логотип Soola - Темно-зеленый */.auth-links { display: flex; gap: 15px; align-items: center; }.auth-links a { color: #3D8361; text-decoration: none; font-weight: 500; } /* Ссылки - Средне-зеленый */.auth-links a:hover { text-decoration: underline; }body.dark-mode .auth-links a { color: #55a683; } /* Ссылки в темной теме */.auth-links span { font-weight: 500; }body.dark-mode .auth-links span { color: #b0c8c1;}.theme-toggle { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #7a8d85; transition: color 0.3s ease; }3 unmodified lines.store-address { padding: 15px; text-align: center; background-color: #ffffff; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); font-size: 1rem; color: #44524c; }body.dark-mode .store-address { background-color: #253f37; color: #b0c8c1; }/* Фильтры и поиск */.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 #d1e7dd; 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: #253f37; border-color: #2c4a41; color: #c8d8d3; }#search-input:focus { border-color: #1C6758; box-shadow: 0 0 0 3px rgba(28, 103, 88, 0.2); } /* Фокус - темно-зеленый */body.dark-mode #search-input:focus { border-color: #3D8361; box-shadow: 0 0 0 3px rgba(61, 131, 97, 0.3); } /* Фокус в темной теме */.category-filter { padding: 8px 16px; border: 1px solid #d1e7dd; 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; color: #1C6758; } /* Цвет текста кнопки фильтра */body.dark-mode .category-filter { background-color: #253f37; border-color: #2c4a41; color: #97b7ae; }.category-filter.active, .category-filter:hover { background-color: #1C6758; color: white; border-color: #1C6758; box-shadow: 0 2px 10px rgba(28, 103, 88, 0.3); } /* Активный/ховер фильтр - темно-зеленый */body.dark-mode .category-filter.active, body.dark-mode .category-filter:hover { background-color: #3D8361; border-color: #3D8361; color: #1a2b26; box-shadow: 0 2px 10px rgba(61, 131, 97, 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; 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%; border: 1px solid #e1f0e9;}6 unmodified lines.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: #2d332f; }body.dark-mode .product h2 { color: #c8d8d3; }.product-price { font-size: 1.2rem; color: #1C6758; font-weight: 700; text-align: center; margin: 5px 0; } /* Цена - темно-зеленая */body.dark-mode .product-price { color: #55a683; } /* Цена в темной теме */.product-description { font-size: 0.85rem; color: #7a8d85; text-align: center; margin-bottom: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }body.dark-mode .product-description { color: #8aa39a; }.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: #1C6758; 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: #164B41; box-shadow: 0 4px 15px rgba(22, 75, 65, 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: #1C6758; 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(28, 103, 88, 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: #f8fcfb; 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: #253f37; color: #c8d8d3; }2 unmodified lines.close:hover { color: #333; }body.dark-mode .close { color: #7a8d85; }body.dark-mode .close:hover { color: #b0c8c1; }.modal-content h2 { margin-top: 0; margin-bottom: 20px; color: #1C6758; display: flex; align-items: center; gap: 10px;} /* Заголовок модалки - темно-зеленый */body.dark-mode .modal-content h2 { color: #55a683; } /* Заголовок модалки в темной теме */.cart-item { display: grid; grid-template-columns: auto 1fr auto auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #d1e7dd; }body.dark-mode .cart-item { border-bottom-color: #2c4a41; }.cart-item:last-child { border-bottom: none; }3 unmodified lines.cart-item-price { font-size: 0.9rem; color: #44524c; }body.dark-mode .cart-item-price { color: #8aa39a; }.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 #d1e7dd; 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: #1a2b26; border-color: #2c4a41; color: #c8d8d3; }1 unmodified linebody.dark-mode .cart-summary { border-top-color: #2c4a41; }.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: #7a8d85; } /* Кнопка очистки - серо-зеленый */.clear-cart:hover { background-color: #5e6e68; box-shadow: 0 4px 15px rgba(94, 110, 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: #5e6e68; }body.dark-mode .no-results-message { color: #8aa39a; }63 unmodified lines</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>1 unmodified line</div></div><!-- Quantity and Color Modal --><div id="quantityModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">×</span>6 unmodified lines</div></div><!-- Cart Modal --><div id="cartModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span>13 unmodified lines</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 }}';1 unmodified linelet 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');12 unmodified lines}}// --- Auto Login ---function attemptAutoLogin() {const storedUser = localStorage.getItem('soolaUser');if (storedUser && !isAuthenticated) {19 unmodified lines}}// --- Modals ---function openModal(index) {loadProductDetails(index);const modal = document.getElementById('productModal');44 unmodified linespagination: { 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('Пожалуйста, войдите в систему, чтобы добавить товар в корзину.');10 unmodified linesconst colorSelect = document.getElementById('colorSelect');const colorLabel = document.querySelector('label[for="colorSelect"]');colorSelect.innerHTML = ''; // Clear previous optionsconst validColors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : [];121 unmodified linesfunction removeFromCart(itemId) {cart = cart.filter(item => item.id !== itemId);localStorage.setItem('soolaCart', JSON.stringify(cart));openCartModal(); // Refresh cart modal contentupdateCartButton(); // Refresh cart icon}function clearCart() {if (confirm("Вы уверены, что хотите очистить корзину?")) {cart = [];localStorage.removeItem('soolaCart');openCartModal(); // Update modal to show empty cart messageupdateCartButton();// closeModal('cartModal'); // Можно закрыть или оставить открытой}}3 unmodified linesreturn;}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 = "996997703090"; // Указываем номер без '+' и пробелов// Формируем URL для WhatsApp APIconst whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${encodeURIComponent(orderText)}`;// Открываем WhatsApp в новой вкладке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');1 unmodified lineconst grid = document.getElementById('products-grid');let visibleProducts = 0;// Удаляем старое сообщение "не найдено", если оно естьconst existingNoResults = grid.querySelector('.no-results-message');if (existingNoResults) existingNoResults.remove();13 unmodified lines}});// Показать сообщение "товары не найдены", если 0 видимых товаров и был поиск/фильтрif (visibleProducts === 0 && (searchTerm || activeCategory !== 'all')) {const p = document.createElement('p');p.className = 'no-results-message';17 unmodified lines});}// --- Notifications ---function showNotification(message, duration = 3000) {const placeholder = document.getElementById('notification-placeholder');if (!placeholder) return;3 unmodified linesnotification.textContent = message;placeholder.appendChild(notification);// Trigger transitionsetTimeout(() => { notification.classList.add('show'); }, 10);// Remove after durationsetTimeout(() => {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 firstupdateCartButton(); // Initialize cart button statesetupFilters(); // Setup search and category filters// Global click listener for closing modalswindow.addEventListener('click', function(event) {if (event.target.classList.contains('modal')) {closeModal(event.target.id);}});// Global keydown listener for closing modals with Escape keywindow.addEventListener('keydown', function(event) {if (event.key === 'Escape') {document.querySelectorAll('.modal[style*="display: block"]').forEach(modal => {14 unmodified linesrepo_id=REPO_ID,is_authenticated=is_authenticated,store_address=STORE_ADDRESS,session=session, # session доступен в Jinja2 по умолчанию, но передать явно не помешает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 session3 unmodified lineslogging.warning(f"Попытка доступа к несуществующему продукту с индексом {index}")return "Товар не найден", 404# HTML для деталей продукта с темно-зелеными акцентамиdetail_html = '''{# Используем Jinja комментарий #}<div style="padding: 10px;"><h2 style="font-size: 1.6rem; font-weight: 600; margin-bottom: 15px; text-align: center; color: #1C6758;">{{ 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;">6 unmodified lines</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: #1C6758;"></div> {# Темно-зеленые стрелки #}<div class="swiper-button-prev" style="color: #1C6758;"></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: #1C6758;"><strong>Цена:</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p> {# Темно-зеленая цена #}{% else %}<p><strong>Цена:</strong> <a href="{{ url_for('login') }}" style="color: #3D8361; 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>7 unmodified linescurrency_code=CURRENCY_CODE)# --- Маршруты аутентификации ---# Шаблон для страницы входа с темно-зелеными акцентамиLOGIN_TEMPLATE = '''<!DOCTYPE html><html lang="ru">3 unmodified lines<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, #d1e7dd, #e9f5f0); 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: #1C6758; margin-bottom: 25px; font-weight: 600; } /* Темно-зеленый заголовок */label { display: block; text-align: left; margin: 15px 0 5px; font-weight: 500; color: #44524c; }input[type="text"], input[type="password"] { width: 100%; padding: 12px; margin-bottom: 15px; border: 1px solid #c4d9d1; border-radius: 8px; box-sizing: border-box; font-size: 1rem; }input:focus { border-color: #1C6758; outline: none; box-shadow: 0 0 0 2px rgba(28, 103, 88, 0.2); } /* Фокус - темно-зеленый */button { width: 100%; padding: 12px; background-color: #1C6758; 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: #164B41; } /* Ховер кнопки - темнее */.error { color: #721c24; background-color: #f8d7da; 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: #3D8361; text-decoration: none; font-size: 0.9rem; } /* Ссылка назад - средне-зеленая */.back-link:hover { text-decoration: underline; }</style></head>18 unmodified lines@app.route('/login', methods=['GET', 'POST'])def login():"""Страница входа пользователя."""if request.method == 'POST':login = request.form.get('login')password = request.form.get('password')2 unmodified linesusers = load_users()# Важно: В реальном приложении используйте хеширование паролей!# Пример с хешированием (нужна библиотека passlib):# from passlib.hash import pbkdf2_sha256# if login in users and pbkdf2_sha256.verify(password, users[login].get('password_hash')):# Либо простая проверка для демонстрации:if login in users and users[login].get('password') == password:user_info = users[login]session['user'] = login20 unmodified lineserror_message = "Неверный логин или пароль."return render_template_string(LOGIN_TEMPLATE, error=error_message), 401# GET запрос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 без данных или логина.")6 unmodified linesusers = load_users()if login in users:# Пароль не проверяем при авто-логине, т.к. он не передается# Доверяем только наличию логина в localStorage (умеренная безопасность)user_info = users[login]session['user'] = loginsession['user_info'] = {7 unmodified linesreturn "OK", 200else:logging.warning(f"Неудачная попытка автоматического входа для несуществующего пользователя {login}.")# Важно: Не возвращаем 401 или 404, чтобы не раскрывать существование пользователей# Просто возвращаем ошибку, чтобы JS удалил невалидный логин из localStoragereturn "Ошибка авто-входа", 400 # Или 403 Forbidden@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} вышел из системы.")# Ответ с JS для очистки localStorage и редиректомlogout_response_html = '''<!DOCTYPE html><html><head><title>Выход...</title></head><body><script>5 unmodified lines'''return logout_response_html# --- Админ-панель ---# Шаблон админ-панели с темно-зелеными акцентамиADMIN_TEMPLATE = '''<!DOCTYPE html><html lang="ru">4 unmodified lines<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: #e9f5f0; color: #2d332f; 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 #d1e7dd; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;}h1, h2, h3 { font-weight: 600; color: #1C6758; 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: #164B41; margin-top: 20px; } /* Темнее зеленый для подзаголовков */.section { margin-bottom: 30px; padding: 20px; background-color: #f8fcfb; border: 1px solid #d1e7dd; border-radius: 8px; }form { margin-bottom: 20px; }label { font-weight: 500; margin-top: 10px; display: block; color: #44524c; 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 #c4d9d1; 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: #1C6758; outline: none; box-shadow: 0 0 0 2px rgba(28, 103, 88, 0.1); } /* Фокус - темно-зеленый */textarea { min-height: 80px; resize: vertical; }input[type="file"] { padding: 8px; background-color: #f0f9f4; cursor: pointer; border: 1px solid #c4d9d1;}input[type="file"]::file-selector-button { padding: 5px 10px; border-radius: 4px; background-color: #e0f0e9; border: 1px solid #c4d9d1; cursor: pointer; margin-right: 10px;}button, .button { padding: 10px 18px; border: none; border-radius: 6px; background-color: #1C6758; 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: #164B41; } /* Ховер кнопки - темнее */button:active, .button:active { transform: scale(0.98); }button[type="submit"] { min-width: 120px; justify-content: center; }.delete-button { background-color: #f56565; } /* Удаление - красный */.delete-button:hover { background-color: #e53e3e; }.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 #e1f0e9; }1 unmodified line.item strong { color: #2d332f; }.item .description { font-size: 0.85rem; color: #5e6e68; max-height: 60px; overflow: hidden; text-overflow: ellipsis; }.item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; }/* Кнопка редактирования - основной темно-зеленый */.item-actions button:not(.delete-button) { background-color: #1C6758; }.item-actions button:not(.delete-button):hover { background-color: #164B41; }.edit-form-container { margin-top: 15px; padding: 20px; background: #f0f9f4; border: 1px dashed #c4d9d1; border-radius: 6px; display: none; /* Скрыто по умолчанию */ }details { background-color: #f8fcfb; border: 1px solid #d1e7dd; border-radius: 8px; margin-bottom: 20px; }details > summary { cursor: pointer; font-weight: 600; color: #164B41; display: block; padding: 15px; border-bottom: 1px solid #d1e7dd; list-style: none; /* Убрать стандартный маркер */ position: relative; } /* Заголовок details - темнее зеленый */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; color: #1C6758; } /* Стрелка - темно-зеленая */details[open] > summary::after { transform: translateY(-50%) rotate(180deg); }details[open] > summary { border-bottom: 1px solid #d1e7dd; }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; }/* Кнопка "Добавить поле цвета" - синяя для контраста */.add-color-btn { background-color: #63b3ed; }.add-color-btn:hover { background-color: #4299e1; }.photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #d1e7dd; object-fit: cover;}.sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }/* Кнопка "Скачать с HF" - более мягкий цвет, например, серый */.download-hf-button { background-color: #7a8d85; }.download-hf-button:hover { background-color: #5e6e68; }.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;} /* Ошибка - красный */.message.warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; } /* Предупреждение - желтый */</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: #3D8361;"><i class="fas fa-store"></i> Перейти в каталог</a> {# Средне-зеленая кнопка каталога #}</div>{# Сообщения об успехе/ошибке #}{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}6 unmodified lines<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 download-hf-button" title="Скачать файлы с Hugging Face (перезапишет локальные)"><i class="fas fa-download"></i> Скачать с HF</button> {# Серая кнопка #}</form></div><p style="font-size: 0.85rem; color: #5e6e68;">Резервное копирование на Hugging Face происходит автоматически каждые 30 м��нут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.</p>1 unmodified line<div class="flex-container"><div class="flex-item"> {# Колонка Категории #}<div class="section"><h2><i class="fas fa-tags"></i> Управление категориями</h2><details>3 unmodified lines<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>7 unmodified lines<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 %}4 unmodified lines</div></div><div class="flex-item"> {# Колонка Пользователи #}<div class="section"><h2><i class="fas fa-users"></i> Управление пользователями</h2><details>14 unmodified lines<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>10 unmodified lines<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 %}6 unmodified lines</div><div class="section"> {# Секция Товары #}<h2><i class="fas fa-box-open"></i> Управление товарами</h2><details><summary><i class="fas fa-plus-circle"></i> Добавить но��ый товар</summary>19 unmodified lines<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-color-btn" style="margin-top: 5px;" 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>4 unmodified lines{% 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="Посмотреть первое фото">3 unmodified lines<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: #2d332f;">{{ 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>6 unmodified lines</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">27 unmodified lines{% 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-color-btn" style="margin-top: 5px;" 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>24 unmodified lines<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();2 unmodified lines}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 для кнопки удаления");}5 unmodified lines@app.route('/admin', methods=['GET', 'POST'])def admin():"""Админ-панель для управления товарами, категориями и пользователями."""# Здесь должна быть проверка прав администратора!# Пример: if session.get('user') != 'admin_login': return "Доступ запрещен", 403# Для простоты пока опускаем (В ПРОДАВКШЕНЕ ОБЯЗАТЕЛЬНО ДОБАВИТЬ!)if not session.get('user'): # Простейшая проверка - залогинен ли хоть кто-тоflash("Требуется вход для доступа к админ-панели.", 'warning')return redirect(url_for('login'))# TODO: Добавить более строгую проверку роли администратора, если пользователей многоdata = load_data()products = data.get('products', [])9 unmodified linescategory_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')8 unmodified linescategory_to_delete = request.form.get('category_name')if category_to_delete and category_to_delete in categories:categories.remove(category_to_delete)# Обновляем товарыupdated_count = 0for product in products:if product.get('category') == category_to_delete:17 unmodified linesif not name or not price_str:flash("Название и цена товара обязательны.", 'error')return redirect(url_for('admin')) # Прерываем выполнениеtry:price = round(float(price_str), 2)16 unmodified linesbreakif 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)1 unmodified linelogging.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,8 unmodified linesflash(f"Ошибка при загрузке фото {photo.filename}.", 'error')elif photo and not photo.filename:logging.warning("Получен пустой объект файла фото при добавлении товара.")# Удаляем временную папку, если она пустаtry:if not os.listdir(uploads_dir):os.rmdir(uploads_dir)7 unmodified lines'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}' добавлен.")14 unmodified linesflash(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()9 unmodified lineslogging.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'25 unmodified linesexcept Exception as e:logging.error(f"Ошибка загрузки нового фото {photo.filename}: {e}", exc_info=True)flash(f"Ошибка при загрузке нового фото {photo.filename}.", 'error')# Удаляем временную папку, если она пустаtry:if not os.listdir(uploads_dir):os.rmdir(uploads_dir)except OSError as e:logging.warning(f"Не удалось удалить временную папку {uploads_dir}: {e}")# Если были успешно загружены новые фото, заменяем старый списокif new_photos_list:logging.info(f"Список фото для товара {product_to_edit['name']} обновлен.")# TODO: Удалить старые фото с HF? Это сложнее, требует хранения списка старых фото.# ----- Начало: Опциональное удаление старых фото ----old_photos = product_to_edit.get('photos', [])if old_photos:logging.info(f"Попытка удаления старых фото: {old_photos}")9 unmodified linesexcept Exception as e:logging.error(f"Ошибка при удалении старых фото {old_photos} с HF: {e}", exc_info=True)flash("Не удалось удалить старые фотографии с сервера.", "warning")# ----- Конец: Опциональное удаление старых фото -----product_to_edit['photos'] = new_photos_listflash("Фотографии товара успешно обновлены.", "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']}'.")11 unmodified linesdeleted_product = products.pop(index)product_name = deleted_product.get('name', 'N/A')# ----- Начало: Удаление фото с HF при удалении товара ----photos_to_delete = deleted_product.get('photos', [])if photos_to_delete and HF_TOKEN_WRITE:logging.info(f"Попытка удаления фото товара '{product_name}' с HF: {photos_to_delete}")10 unmodified linesexcept Exception as e:logging.error(f"Ошибка при удалении фото {photos_to_delete} для товара '{product_name}' с HF: {e}", exc_info=True)flash(f"Не удалось удалить фото для товара '{product_name}' с сервера.", "warning")# ----- Конец: Удаление фото с HF при удалении товара ----save_data(data)logging.info(f"Товар '{product_name}' (индекс {index}) удален.")17 unmodified linesflash(f"Пользователь с логином '{login}' уже существует.", 'error')return redirect(url_for('admin'))# Важно: Хранить пароли в открытом виде НЕБЕЗОПАСНО!# Используйте хеширование для реальных приложений.# from passlib.hash import pbkdf2_sha256# password_hash = pbkdf2_sha256.hash(password)users[login] = {'password': password, # Замените на 'password_hash': password_hash'first_name': first_name, 'last_name': last_name,'country': country, 'city': city}16 unmodified lineslogging.warning(f"Получено неизвестное действие в админ-панели: {action}")flash(f"Неизвестное действие: {action}", 'warning')# После обработки POST-запроса делаем редирект, чтобы избежать повторной отправки формы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')) # Редирект даже при ошибке# GET запрос для отображения админ-панели# Сортируем продукты для отображения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)# --- Маршруты для принудительной синхронизации ---@app.route('/force_upload', methods=['POST'])def force_upload():# TODO: Добавить проверку прав администратораif not session.get('user'):flash("Требуется вход для выполнения этого действия.", 'warning')return redirect(url_for('login'))9 unmodified lines@app.route('/force_download', methods=['POST'])def force_download():# TODO: Добавить проверку прав администратораif not session.get('user'):flash("Требуется вход для выполнения этого действия.", 'warning')return redirect(url_for('login'))8 unmodified linesreturn 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()1 unmodified lineelse:logging.warning("Периодическое резервное копирование НЕ будет запущено (HF_TOKEN или HF_TOKEN_WRITE не установлена).")# Запуск Flask приложенияport = int(os.environ.get('PORT', 7860)) # Порт по умолчанию 7860, можно изменить через переменную окружения PORTlogging.info(f"Запуск Flask приложения на хосте 0.0.0.0 и порту {port}")# debug=False для продакшена! Установите в True только для локальной разработки.# Использование app.run() подходит только для разработки.# Для продакшена используйте WSGI сервер, например, Gunicorn или Waitress.# Пример с Gunicorn: gunicorn --bind 0.0.0.0:7860 app:app# Пример с Waitress: waitress-serve --host 0.0.0.0 --port 7860 app:appapp.run(debug=False, host='0.0.0.0', port=port)12344 unmodified lines91011121314151617181920212223242526272829303132333435363738394041425 unmodified lines48495051525354555657581 unmodified line606162636465666 unmodified lines7374757677781 unmodified line808182838485868788899091929394951 unmodified line97989910010110210310410510610710810910 unmodified lines12012112212312412512612712812913013113213313413516 unmodified lines1521531541551561571 unmodified line1591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152165 unmodified lines2222232242252262272282292302312322332342352362372383 unmodified lines2422432442452462472482492502512522532542552562572586 unmodified lines2652662672682692702712722732742752762772782792802812822832842852 unmodified lines2882892902912922932942953 unmodified lines2993003013023033043051 unmodified line30730830931031131231331431531631731831963 unmodified lines3833843853863873883893903913923933941 unmodified line3963973983994004016 unmodified lines40840941041141241313 unmodified lines4274284294304314324334344354364374384394404411 unmodified line44344444544644744812 unmodified lines46146246346446546619 unmodified lines48648748848949049144 unmodified lines53653753853954054154254354454554610 unmodified lines557558559560561562563121 unmodified lines6856866876886896906916926936946956966976986997003 unmodified lines7047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397401 unmodified line74274374474574674713 unmodified lines76176276376476576617 unmodified lines7847857867877887893 unmodified lines79379479579679779879980080180280380480580680780880981081181281381481581681781814 unmodified lines8338348358368378388398408418428438448453 unmodified lines8498508518528538548558568578588598608618628636 unmodified lines8708718728738748758768778788798808818828838848858868878888898908918927 unmodified lines9009019029039049053 unmodified lines90991091191291391491591691791891992092192292392418 unmodified lines9439449459469479482 unmodified lines95195295395495595620 unmodified lines9779789799809819829839849859869876 unmodified lines9949959969979989997 unmodified lines1007100810091010101110121013101410151016101710181019102010215 unmodified lines1027102810291030103110324 unmodified lines10371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641 unmodified line10661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411056 unmodified lines11121113111411151116111711181119112011211 unmodified line11231124112511261127112811293 unmodified lines11331134113511361137113811397 unmodified lines11471148114911501151115211534 unmodified lines115811591160116111621163116414 unmodified lines117911801181118211831184118510 unmodified lines119611971198119912001201120212036 unmodified lines121012111212121312141215121619 unmodified lines1236123712381239124012411242124312441245124612474 unmodified lines1252125312541255125612573 unmodified lines126112621263126412651266126712686 unmodified lines1275127612771278127912801281128212831284128512861287128827 unmodified lines1316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133824 unmodified lines1363136413651366136713682 unmodified lines13711372137313741375137613771378137913805 unmodified lines1386138713881389139013911392139313949 unmodified lines14041405140614071408140914108 unmodified lines14191420142114221423142417 unmodified lines144214431444144514461447144816 unmodified lines1465146614671468146914701 unmodified line14721473147414751476147714788 unmodified lines1487148814891490149114927 unmodified lines15001501150215031504150514 unmodified lines1520152115221523152415259 unmodified lines15351536153715381539154025 unmodified lines156615671568156915701571157215731574157515761577157815799 unmodified lines1589159015911592159315941595159615971598159911 unmodified lines16111612161316141615161610 unmodified lines16271628162916301631163217 unmodified lines1650165116521653165416551656165716 unmodified lines16741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017019 unmodified lines1711171217131714171517168 unmodified lines17251726172717281729173017311732173317341 unmodified line173617371738173917401741from flask import Flask, render_template_string, request, redirect, url_for, session, send_file, flashimport jsonimport os4 unmodified linesfrom huggingface_hub import HfApi, hf_hub_downloadfrom huggingface_hub.utils import RepositoryNotFoundErrorfrom werkzeug.utils import secure_filenamefrom dotenv import load_dotenvload_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': []}5 unmodified linesexcept 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} после попытки скачивания.")1 unmodified lineif 'products' not in data: data['products'] = []if 'categories' not in data: data['categories'] = []return dataexcept (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)6 unmodified linesreturn {'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)1 unmodified linedef 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}")1 unmodified lineexcept 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:10 unmodified linesreturn {}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):if not HF_TOKEN_WRITE:logging.warning("Переменная окружения HF_TOKEN (для записи) не установлена. Загрузка на Hugging Face пропущена.")return16 unmodified lineslogging.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 завершена.")1 unmodified linelogging.error(f"Общая ошибка при инициализации или загрузке на Hugging Face: {e}", exc_info=True)def download_db_from_hf(specific_file=None):if not HF_TOKEN_READ:logging.warning("Переменная окружения HF_TOKEN_READ не установлена. Попытка скачивания с Hugging Face без токена (может не сработать для приватных репо).")files_to_download = [specific_file] if specific_file else SYNC_FILESlogging.info(f"Начало скачивания файлов {files_to_download} с HF репозитория {REPO_ID}...")downloaded_files_count = 0try: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 += 1except RepositoryNotFoundError:logging.error(f"Репозиторий {REPO_ID} не найден на Hugging Face. Скачивание прервано.")breakexcept 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():backup_interval = 1800logging.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 sessioncatalog_html = '''<!DOCTYPE html><html lang="ru">5 unmodified lines<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: #f0f9f4; color: #2d332f; line-height: 1.6; transition: background 0.3s, color 0.3s; }body.dark-mode { background: #1a2b26; color: #c8d8d3; }.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 #d1e7dd; }body.dark-mode .header { border-bottom-color: #2c4a41; }.header h1 { font-size: 1.8rem; font-weight: 600; color: #1C6758; }.auth-links { display: flex; gap: 15px; align-items: center; }.auth-links a { color: #3D8361; text-decoration: none; font-weight: 500; }.auth-links a:hover { text-decoration: underline; }body.dark-mode .auth-links a { color: #55a683; }.auth-links span { font-weight: 500; }body.dark-mode .auth-links span { color: #b0c8c1;}.theme-toggle { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #7a8d85; transition: color 0.3s ease; }3 unmodified lines.store-address { padding: 15px; text-align: center; background-color: #ffffff; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); font-size: 1rem; color: #44524c; }body.dark-mode .store-address { background-color: #253f37; color: #b0c8c1; }.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 #d1e7dd; 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: #253f37; border-color: #2c4a41; color: #c8d8d3; }#search-input:focus { border-color: #1C6758; box-shadow: 0 0 0 3px rgba(28, 103, 88, 0.2); }body.dark-mode #search-input:focus { border-color: #3D8361; box-shadow: 0 0 0 3px rgba(61, 131, 97, 0.3); }.category-filter { padding: 8px 16px; border: 1px solid #d1e7dd; 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; color: #1C6758; }body.dark-mode .category-filter { background-color: #253f37; border-color: #2c4a41; color: #97b7ae; }.category-filter.active, .category-filter:hover { background-color: #1C6758; color: white; border-color: #1C6758; box-shadow: 0 2px 10px rgba(28, 103, 88, 0.3); }body.dark-mode .category-filter.active, body.dark-mode .category-filter:hover { background-color: #3D8361; border-color: #3D8361; color: #1a2b26; box-shadow: 0 2px 10px rgba(61, 131, 97, 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; 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%; border: 1px solid #e1f0e9;}6 unmodified lines.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: #2d332f; }body.dark-mode .product h2 { color: #c8d8d3; }.product-price { font-size: 1.2rem; color: #1C6758; font-weight: 700; text-align: center; margin: 5px 0; }body.dark-mode .product-price { color: #55a683; }.product-description { font-size: 0.85rem; color: #7a8d85; text-align: center; margin-bottom: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }body.dark-mode .product-description { color: #8aa39a; }.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: #1C6758; 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: #164B41; box-shadow: 0 4px 15px rgba(22, 75, 65, 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: #1C6758; 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(28, 103, 88, 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: #f8fcfb; 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: #253f37; color: #c8d8d3; }2 unmodified lines.close:hover { color: #333; }body.dark-mode .close { color: #7a8d85; }body.dark-mode .close:hover { color: #b0c8c1; }.modal-content h2 { margin-top: 0; margin-bottom: 20px; color: #1C6758; display: flex; align-items: center; gap: 10px;}body.dark-mode .modal-content h2 { color: #55a683; }.cart-item { display: grid; grid-template-columns: auto 1fr auto auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #d1e7dd; }body.dark-mode .cart-item { border-bottom-color: #2c4a41; }.cart-item:last-child { border-bottom: none; }3 unmodified lines.cart-item-price { font-size: 0.9rem; color: #44524c; }body.dark-mode .cart-item-price { color: #8aa39a; }.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 #d1e7dd; 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: #1a2b26; border-color: #2c4a41; color: #c8d8d3; }1 unmodified linebody.dark-mode .cart-summary { border-top-color: #2c4a41; }.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: #7a8d85; }.clear-cart:hover { background-color: #5e6e68; box-shadow: 0 4px 15px rgba(94, 110, 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: #5e6e68; }body.dark-mode .no-results-message { color: #8aa39a; }63 unmodified lines</div></div>{% endfor %}{% if not products %}<p class="no-results-message">Товары пока не добавл��ны.</p>{% endif %}</div></div><div id="productModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span>1 unmodified line</div></div><div id="quantityModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">×</span>6 unmodified lines</div></div><div id="cartModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span>13 unmodified lines</div></div><button id="cart-button" onclick="openCartModal()" aria-label="Открыть корзину"><i class="fas fa-shopping-cart"></i><span id="cart-count">0</span></button><div id="notification-placeholder"></div><script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script><script>const products = {{ products|tojson }};const repoId = '{{ repo_id }}';const currencyCode = '{{ currency_code }}';1 unmodified linelet selectedProductIndex = null;let cart = JSON.parse(localStorage.getItem('soolaCart') || '[]');function toggleTheme() {document.body.classList.toggle('dark-mode');const icon = document.querySelector('.theme-toggle i');12 unmodified lines}}function attemptAutoLogin() {const storedUser = localStorage.getItem('soolaUser');if (storedUser && !isAuthenticated) {19 unmodified lines}}function openModal(index) {loadProductDetails(index);const modal = document.getElementById('productModal');44 unmodified linespagination: { 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, },});}}function openQuantityModal(index) {if (!isAuthenticated) {alert('Пожалуйста, войдите в систему, чтобы добавить товар в корзину.');10 unmodified linesconst colorSelect = document.getElementById('colorSelect');const colorLabel = document.querySelector('label[for="colorSelect"]');colorSelect.innerHTML = '';const validColors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : [];121 unmodified linesfunction removeFromCart(itemId) {cart = cart.filter(item => item.id !== itemId);localStorage.setItem('soolaCart', JSON.stringify(cart));openCartModal();updateCartButton();}function clearCart() {if (confirm("Вы уверены, что хотите очистить корзину?")) {cart = [];localStorage.removeItem('soolaCart');openCartModal();updateCartButton();}}3 unmodified linesreturn;}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`;// --- FIX STARTS HERE ---const userInfo = {{ session.get('user_info', {})|tojson }};if (userInfo && userInfo.login) {// Use direct property access or || for defaultsorderText += `Заказчик: ${userInfo.first_name || ''} ${userInfo.last_name || ''}%0A`;orderText += `Логин: ${userInfo.login}%0A`;orderText += `Страна: ${userInfo.country || 'Не указана'}%0A`;orderText += `Город: ${userInfo.city || 'Не указан'}%0A`;} else {orderText += `Заказчик: (Не авторизован)%0A`;}// --- FIX ENDS HERE ---const now = new Date();const dateTimeString = now.toLocaleString('ru-RU');orderText += `%0AДата заказа: ${dateTimeString}`;const whatsappNumber = "996997703090";const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${encodeURIComponent(orderText)}`;window.open(whatsappUrl, '_blank');}function filterProducts() {const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();const activeCategoryButton = document.querySelector('.category-filter.active');1 unmodified lineconst grid = document.getElementById('products-grid');let visibleProducts = 0;const existingNoResults = grid.querySelector('.no-results-message');if (existingNoResults) existingNoResults.remove();13 unmodified lines}});if (visibleProducts === 0 && (searchTerm || activeCategory !== 'all')) {const p = document.createElement('p');p.className = 'no-results-message';17 unmodified lines});}function showNotification(message, duration = 3000) {const placeholder = document.getElementById('notification-placeholder');if (!placeholder) return;3 unmodified linesnotification.textContent = message;placeholder.appendChild(notification);setTimeout(() => { notification.classList.add('show'); }, 10);setTimeout(() => {notification.classList.remove('show');setTimeout(() => { notification.remove(); }, 500);}, duration);}document.addEventListener('DOMContentLoaded', () => {applyInitialTheme();attemptAutoLogin();updateCartButton();setupFilters();window.addEventListener('click', function(event) {if (event.target.classList.contains('modal')) {closeModal(event.target.id);}});window.addEventListener('keydown', function(event) {if (event.key === 'Escape') {document.querySelectorAll('.modal[style*="display: block"]').forEach(modal => {14 unmodified linesrepo_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', [])is_authenticated = 'user' in session3 unmodified lineslogging.warning(f"Попытка доступа к несуществующему продукту с индексом {index}")return "Товар не найден", 404detail_html = '''<div style="padding: 10px;"><h2 style="font-size: 1.6rem; font-weight: 600; margin-bottom: 15px; text-align: center; color: #1C6758;">{{ product['name'] }}</h2><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;">6 unmodified lines</div>{% endif %}</div>{% 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: #1C6758;"></div><div class="swiper-button-prev" style="color: #1C6758;"></div>{% endif %}</div><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: #1C6758;"><strong>Цена:</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p>{% else %}<p><strong>Цена:</strong> <a href="{{ url_for('login') }}" style="color: #3D8361; text-decoration: underline;">Доступна после входа</a></p>{% endif %}<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>7 unmodified linescurrency_code=CURRENCY_CODE)LOGIN_TEMPLATE = '''<!DOCTYPE html><html lang="ru">3 unmodified lines<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, #d1e7dd, #e9f5f0); 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: #1C6758; margin-bottom: 25px; font-weight: 600; }label { display: block; text-align: left; margin: 15px 0 5px; font-weight: 500; color: #44524c; }input[type="text"], input[type="password"] { width: 100%; padding: 12px; margin-bottom: 15px; border: 1px solid #c4d9d1; border-radius: 8px; box-sizing: border-box; font-size: 1rem; }input:focus { border-color: #1C6758; outline: none; box-shadow: 0 0 0 2px rgba(28, 103, 88, 0.2); }button { width: 100%; padding: 12px; background-color: #1C6758; 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: #164B41; }.error { color: #721c24; background-color: #f8d7da; 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: #3D8361; text-decoration: none; font-size: 0.9rem; }.back-link:hover { text-decoration: underline; }</style></head>18 unmodified lines@app.route('/login', methods=['GET', 'POST'])def login():if request.method == 'POST':login = request.form.get('login')password = request.form.get('password')2 unmodified linesusers = load_users()if login in users and users[login].get('password') == password:user_info = users[login]session['user'] = login20 unmodified lineserror_message = "Неверный логин или пароль."return render_template_string(LOGIN_TEMPLATE, error=error_message), 401return render_template_string(LOGIN_TEMPLATE, error=None)@app.route('/auto_login', methods=['POST'])def auto_login():data = request.get_json()if not data or 'login' not in data:logging.warning("Запрос auto_login без данных или логина.")6 unmodified linesusers = load_users()if login in users:user_info = users[login]session['user'] = loginsession['user_info'] = {7 unmodified linesreturn "OK", 200else: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>5 unmodified lines'''return logout_response_htmlADMIN_TEMPLATE = '''<!DOCTYPE html><html lang="ru">4 unmodified lines<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: #e9f5f0; color: #2d332f; 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 #d1e7dd; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;}h1, h2, h3 { font-weight: 600; color: #1C6758; 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: #164B41; margin-top: 20px; }.section { margin-bottom: 30px; padding: 20px; background-color: #f8fcfb; border: 1px solid #d1e7dd; border-radius: 8px; }form { margin-bottom: 20px; }label { font-weight: 500; margin-top: 10px; display: block; color: #44524c; 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 #c4d9d1; 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: #1C6758; outline: none; box-shadow: 0 0 0 2px rgba(28, 103, 88, 0.1); }textarea { min-height: 80px; resize: vertical; }input[type="file"] { padding: 8px; background-color: #f0f9f4; cursor: pointer; border: 1px solid #c4d9d1;}input[type="file"]::file-selector-button { padding: 5px 10px; border-radius: 4px; background-color: #e0f0e9; border: 1px solid #c4d9d1; cursor: pointer; margin-right: 10px;}button, .button { padding: 10px 18px; border: none; border-radius: 6px; background-color: #1C6758; 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: #164B41; }button:active, .button:active { transform: scale(0.98); }button[type="submit"] { min-width: 120px; justify-content: center; }.delete-button { background-color: #f56565; }.delete-button:hover { background-color: #e53e3e; }.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 #e1f0e9; }1 unmodified line.item strong { color: #2d332f; }.item .description { font-size: 0.85rem; color: #5e6e68; max-height: 60px; overflow: hidden; text-overflow: ellipsis; }.item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; }.item-actions button:not(.delete-button) { background-color: #1C6758; }.item-actions button:not(.delete-button):hover { background-color: #164B41; }.edit-form-container { margin-top: 15px; padding: 20px; background: #f0f9f4; border: 1px dashed #c4d9d1; border-radius: 6px; display: none; }details { background-color: #f8fcfb; border: 1px solid #d1e7dd; border-radius: 8px; margin-bottom: 20px; }details > summary { cursor: pointer; font-weight: 600; color: #164B41; display: block; padding: 15px; border-bottom: 1px solid #d1e7dd; list-style: none; position: relative; }details > summary::after { content: '\\f078'; font-family: 'Font Awesome 6 Free'; font-weight: 900; position: absolute; right: 20px; top: 50%; transform: translateY(-50%); transition: transform 0.2s ease; color: #1C6758; }details[open] > summary::after { transform: translateY(-50%) rotate(180deg); }details[open] > summary { border-bottom: 1px solid #d1e7dd; }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; }.add-color-btn { background-color: #63b3ed; }.add-color-btn:hover { background-color: #4299e1; }.photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #d1e7dd; object-fit: cover;}.sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }.download-hf-button { background-color: #7a8d85; }.download-hf-button:hover { background-color: #5e6e68; }.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;}.message.warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; }</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: #3D8361;"><i class="fas fa-store"></i> Перейти в каталог</a></div>{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}6 unmodified lines<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 download-hf-button" title="Скачать файлы с Hugging Face (перезапишет локальные)"><i class="fas fa-download"></i> Скачать с HF</button></form></div><p style="font-size: 0.85rem; color: #5e6e68;">Резервное копирование на Hugging Face происходит автоматически каждые 30 м��нут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.</p>1 unmodified line<div class="flex-container"><div class="flex-item"><div class="section"><h2><i class="fas fa-tags"></i> Управление категориями</h2><details>3 unmodified lines<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>7 unmodified lines<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 %}4 unmodified lines</div></div><div class="flex-item"><div class="section"><h2><i class="fas fa-users"></i> Управление пользователями</h2><details>14 unmodified lines<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>10 unmodified lines<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 %}6 unmodified lines</div><div class="section"><h2><i class="fas fa-box-open"></i> Управление товарами</h2><details><summary><i class="fas fa-plus-circle"></i> Добавить но��ый товар</summary>19 unmodified lines<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-color-btn" style="margin-top: 5px;" 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>4 unmodified lines{% 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="Посмотреть первое фото">3 unmodified lines<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: #2d332f;">{{ 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>6 unmodified lines</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">27 unmodified lines{% 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-color-btn" style="margin-top: 5px;" 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>24 unmodified lines<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();2 unmodified lines}function removeColorInput(button) {const group = button.closest('.color-input-group');if (group) {const container = group.parentNode;group.remove();} else {console.warn("Не удалось найти родительский .color-input-group для кнопки удаления");}5 unmodified lines@app.route('/admin', methods=['GET', 'POST'])def admin():if not session.get('user'):flash("Требуется вход для доступа к админ-панели.", 'warning')return redirect(url_for('login'))data = load_data()products = data.get('products', [])9 unmodified linescategory_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')8 unmodified linescategory_to_delete = request.form.get('category_name')if category_to_delete and category_to_delete in categories:categories.remove(category_to_delete)updated_count = 0for product in products:if product.get('category') == category_to_delete:17 unmodified linesif not name or not price_str:flash("Название и цена товара обязательны.", 'error')return redirect(url_for('admin'))try:price = round(float(price_str), 2)16 unmodified linesbreakif 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)1 unmodified linelogging.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,8 unmodified linesflash(f"Ошибка при загрузке фото {photo.filename}.", 'error')elif photo and not photo.filename:logging.warning("Получен пустой объект файла фото при добавлении товара.")try:if not os.listdir(uploads_dir):os.rmdir(uploads_dir)7 unmodified lines'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}' добавлен.")14 unmodified linesflash(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()9 unmodified lineslogging.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'25 unmodified linesexcept Exception as e:logging.error(f"Ошибка загрузки нового фото {photo.filename}: {e}", exc_info=True)flash(f"Ошибка при загрузке нового фото {photo.filename}.", 'error')try:if not os.listdir(uploads_dir):os.rmdir(uploads_dir)except OSError as e:logging.warning(f"Не удалось удалить временную папку {uploads_dir}: {e}")if new_photos_list:logging.info(f"Список фото для товара {product_to_edit['name']} обновлен.")old_photos = product_to_edit.get('photos', [])if old_photos:logging.info(f"Попытка удаления старых фото: {old_photos}")9 unmodified linesexcept Exception as e:logging.error(f"Ошибка при удалении старых фото {old_photos} с HF: {e}", exc_info=True)flash("Не удалось удалить старые фотографии с сервера.", "warning")product_to_edit['photos'] = new_photos_listflash("Фотографии товара успешно обновлены.", "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']}'.")11 unmodified linesdeleted_product = products.pop(index)product_name = deleted_product.get('name', 'N/A')photos_to_delete = deleted_product.get('photos', [])if photos_to_delete and HF_TOKEN_WRITE:logging.info(f"Попытка удаления фото товара '{product_name}' с HF: {photos_to_delete}")10 unmodified linesexcept Exception as e:logging.error(f"Ошибка при удалении фото {photos_to_delete} для товара '{product_name}' с HF: {e}", exc_info=True)flash(f"Не удалось удалить фото для товара '{product_name}' с сервера.", "warning")save_data(data)logging.info(f"Товар '{product_name}' (индекс {index}) удален.")17 unmodified linesflash(f"Пользователь с логином '{login}' уже существует.", 'error')return redirect(url_for('admin'))users[login] = {'password': password,'first_name': first_name, 'last_name': last_name,'country': country, 'city': city}16 unmodified lineslogging.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)@app.route('/force_upload', methods=['POST'])def force_upload():if not session.get('user'):flash("Требуется вход для выполнения этого действия.", 'warning')return redirect(url_for('login'))9 unmodified lines@app.route('/force_download', methods=['POST'])def force_download():if not session.get('user'):flash("Требуется вход для выполнения этого действия.", 'warning')return redirect(url_for('login'))8 unmodified linesreturn 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()1 unmodified lineelse: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)
app.py+117-285