Spaces:
Paused
Paused
| # -*- coding: utf-8 -*- | |
| from flask import Flask, render_template_string, request, redirect, url_for, send_file | |
| import json | |
| import os | |
| import logging | |
| import threading | |
| import time | |
| from datetime import datetime | |
| from huggingface_hub import HfApi, hf_hub_download | |
| from huggingface_hub.utils import RepositoryNotFoundError | |
| from werkzeug.utils import secure_filename | |
| from urllib.parse import quote | |
| app = Flask(__name__) | |
| DATA_FILE = 'data.json' | |
| REPO_ID = "Kgshop/Mebelhause" | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN") | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") | |
| LOGO_URL = "https://huggingface.co/spaces/Mebelhause/Kg/resolve/main/Screenshot_20250411-112027.png" | |
| WHATSAPP_NUMBER = "+996700253966" | |
| logging.basicConfig(level=logging.INFO) | |
| def load_data(): | |
| try: | |
| download_db_from_hf() | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info("Данные успешно загружены из JSON") | |
| if not isinstance(data, dict) or 'products' not in data or 'categories' not in data: | |
| logging.warning("Структура данных некорректна, используется структура по умолчанию.") | |
| return {'products': [], 'categories': []} | |
| # Ensure products and categories are lists | |
| if not isinstance(data.get('products'), list): | |
| data['products'] = [] | |
| if not isinstance(data.get('categories'), list): | |
| data['categories'] = [] | |
| return data | |
| except FileNotFoundError: | |
| logging.warning("Локальный файл базы данных не найден. Создание пустой базы.") | |
| return {'products': [], 'categories': []} | |
| except json.JSONDecodeError: | |
| logging.error("Ошибка: Невозможно декодировать JSON файл. Возврат пустой базы.") | |
| return {'products': [], 'categories': []} | |
| except RepositoryNotFoundError: | |
| logging.error("Репозиторий Hugging Face не найден. Создание локальной базы данных.") | |
| # Create an empty file if it doesn't exist locally after repo not found | |
| if not os.path.exists(DATA_FILE): | |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: | |
| json.dump({'products': [], 'categories': []}, f) | |
| return {'products': [], 'categories': []} | |
| except Exception as e: | |
| logging.error(f"Произошла ошибка при загрузке данных: {e}. Возврат пустой базы.") | |
| return {'products': [], 'categories': []} | |
| def save_data(data): | |
| try: | |
| # Ensure structure is correct before saving | |
| if 'products' not in data or not isinstance(data['products'], list): | |
| data['products'] = [] | |
| if 'categories' not in data or not isinstance(data['categories'], list): | |
| data['categories'] = [] | |
| with open(DATA_FILE, 'w', encoding='utf-8') as file: | |
| json.dump(data, file, ensure_ascii=False, indent=4) | |
| logging.info("Данные успешно сохранены в JSON") | |
| upload_db_to_hf() | |
| except Exception as e: | |
| logging.error(f"Ошибка при сохранении данных: {e}") | |
| # Optionally re-raise or handle differently | |
| # raise | |
| def upload_db_to_hf(): | |
| if not HF_TOKEN_WRITE: | |
| logging.warning("HF_TOKEN (write) не установлен. Загрузка на Hugging Face пропущена.") | |
| return | |
| if not os.path.exists(DATA_FILE): | |
| logging.warning(f"Файл {DATA_FILE} не найден для загрузки.") | |
| return | |
| try: | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=DATA_FILE, | |
| path_in_repo=DATA_FILE, | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Автоматическое резервное копирование базы данных {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" | |
| ) | |
| logging.info("Резервная копия JSON базы успешно загружена на Hugging Face.") | |
| except RepositoryNotFoundError: | |
| logging.error(f"Репозиторий {REPO_ID} не найден на Hugging Face. Не удалось загрузить.") | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке резервной копии на Hugging Face: {e}") | |
| def download_db_from_hf(): | |
| if not HF_TOKEN_READ: | |
| logging.warning("HF_TOKEN_READ не установлен. Скачивание с Hugging Face пропущено.") | |
| # Attempt to create an empty file if none exists | |
| if not os.path.exists(DATA_FILE): | |
| save_data({'products': [], 'categories': []}) # Save an empty structure | |
| return | |
| try: | |
| hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=DATA_FILE, | |
| repo_type="dataset", | |
| token=HF_TOKEN_READ, | |
| local_dir=".", | |
| local_dir_use_symlinks=False, | |
| force_download=True, # Ensure we get the latest version | |
| resume_download=False # Avoid issues with partial downloads | |
| ) | |
| logging.info("JSON база успешно скачана из Hugging Face.") | |
| # Verify file integrity after download | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as f: | |
| json.load(f) | |
| logging.info("Проверка целостности JSON после скачивания: OK") | |
| except (json.JSONDecodeError, FileNotFoundError) as e: | |
| logging.error(f"Ошибка проверки JSON после скачивания: {e}. Файл может быть поврежден или пуст.") | |
| # Attempt to create a default empty file if it's broken | |
| save_data({'products': [], 'categories': []}) | |
| except RepositoryNotFoundError as e: | |
| logging.error(f"Репозиторий {REPO_ID} не найден на Hugging Face: {e}") | |
| if not os.path.exists(DATA_FILE): | |
| save_data({'products': [], 'categories': []}) # Save an empty structure | |
| # Do not raise here, allow fallback to local/empty data | |
| except Exception as e: | |
| # Catch specific hf_hub exceptions if needed, e.g., HTTPError | |
| logging.error(f"Ошибка при скачивании JSON базы из Hugging Face: {e}") | |
| if not os.path.exists(DATA_FILE): | |
| save_data({'products': [], 'categories': []}) # Save an empty structure | |
| # Do not raise here, allow fallback to local/empty data | |
| def periodic_backup(): | |
| while True: | |
| time.sleep(800) # Sleep first to avoid immediate backup on start | |
| logging.info("Запуск периодического резервного копирования...") | |
| # Ensure data is loaded before backup attempt | |
| try: | |
| load_data() # Reload potentially updated data | |
| except Exception as e: | |
| logging.error(f"Ошибка загрузки данных перед бэкапом: {e}") | |
| # Now attempt upload | |
| upload_db_to_hf() | |
| # --- Global Styles --- | |
| GLOBAL_STYLES = """ | |
| <style> | |
| :root { | |
| --bg-beige: #f5f5dc; | |
| --text-dark-brown: #4d2c1a; /* Darker brown for text */ | |
| --accent-wood: #8b4513; /* SaddleBrown */ | |
| --accent-light-wood: #deb887; /* BurlyWood */ | |
| --button-bg: var(--accent-wood); | |
| --button-hover-bg: #a0522d; /* Sienna - slightly lighter */ | |
| --card-bg: #ffffff; | |
| --border-color: #e0d8c7; /* Lighter border */ | |
| --header-bg: #ffffff; /* White header */ | |
| --footer-bg: var(--text-dark-brown); | |
| --footer-text: var(--bg-beige); | |
| --link-color: var(--accent-wood); | |
| --link-hover-color: var(--button-hover-bg); | |
| --font-primary: 'Poppins', sans-serif; | |
| } | |
| * { | |
| margin: 0; | |
| padding: 0; | |
| box-sizing: border-box; | |
| } | |
| body { | |
| font-family: var(--font-primary); | |
| background-color: var(--bg-beige); | |
| color: var(--text-dark-brown); | |
| line-height: 1.6; | |
| font-size: 16px; | |
| } | |
| .container { | |
| max-width: 1300px; | |
| margin: 0 auto; | |
| padding: 20px; | |
| } | |
| .header { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| padding: 15px 20px; | |
| background-color: var(--header-bg); | |
| box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); | |
| position: sticky; | |
| top: 0; | |
| z-index: 1000; | |
| } | |
| .header-logo { | |
| height: 60px; /* Adjust height as needed */ | |
| width: auto; /* Maintain aspect ratio */ | |
| object-fit: contain; /* Ensure logo fits well */ | |
| } | |
| .header nav a { | |
| color: var(--text-dark-brown); | |
| text-decoration: none; | |
| margin-left: 25px; | |
| font-weight: 500; | |
| transition: color 0.3s ease; | |
| font-size: 1.1rem; | |
| } | |
| .header nav a:hover, .header nav a.active { | |
| color: var(--accent-wood); | |
| font-weight: 600; | |
| } | |
| .main-content { | |
| padding: 40px 0; | |
| } | |
| h1, h2, h3 { | |
| color: var(--text-dark-brown); | |
| margin-bottom: 1rem; | |
| font-weight: 600; | |
| } | |
| h1 { font-size: 2.5rem; text-align: center; margin-bottom: 2rem; } | |
| h2 { font-size: 2rem; margin-bottom: 1.5rem; border-bottom: 2px solid var(--accent-light-wood); padding-bottom: 0.5rem;} | |
| h3 { font-size: 1.5rem; } | |
| button, .button-link { | |
| padding: 12px 25px; | |
| border: none; | |
| border-radius: 8px; | |
| background-color: var(--button-bg); | |
| color: white; | |
| font-weight: 500; | |
| cursor: pointer; | |
| transition: background-color 0.3s ease, transform 0.2s ease; | |
| text-decoration: none; /* For button-link */ | |
| display: inline-block; /* For button-link */ | |
| font-size: 1rem; | |
| text-align: center; | |
| } | |
| button:hover, .button-link:hover { | |
| background-color: var(--button-hover-bg); | |
| transform: translateY(-2px); | |
| } | |
| .whatsapp-float { | |
| position: fixed; | |
| width: 60px; | |
| height: 60px; | |
| bottom: 30px; | |
| right: 30px; | |
| background-color: #25D366; | |
| color: #FFF; | |
| border-radius: 50px; | |
| text-align: center; | |
| font-size: 30px; | |
| box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); | |
| z-index: 100; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| text-decoration: none; | |
| transition: transform 0.3s ease; | |
| } | |
| .whatsapp-float:hover { | |
| transform: scale(1.1); | |
| } | |
| .whatsapp-float i { | |
| margin-top: 0; /* Adjust if needed */ | |
| } | |
| .footer { | |
| background-color: var(--footer-bg); | |
| color: var(--footer-text); | |
| text-align: center; | |
| padding: 20px; | |
| margin-top: 40px; | |
| } | |
| .footer p { | |
| margin: 0; | |
| font-size: 0.9rem; | |
| } | |
| /* Form Styles */ | |
| .form-section { | |
| background: var(--card-bg); | |
| padding: 30px; | |
| border-radius: 15px; | |
| box-shadow: 0 4px 15px rgba(0,0,0,0.1); | |
| margin-bottom: 30px; | |
| } | |
| label { | |
| font-weight: 500; | |
| margin-top: 15px; | |
| display: block; | |
| color: var(--text-dark-brown); | |
| } | |
| input[type="text"], | |
| input[type="number"], | |
| input[type="file"], | |
| textarea, | |
| select { | |
| width: 100%; | |
| padding: 12px; | |
| margin-top: 8px; | |
| border: 1px solid var(--border-color); | |
| border-radius: 8px; | |
| font-size: 1rem; | |
| background-color: #fff; | |
| color: var(--text-dark-brown); | |
| transition: border-color 0.3s ease, box-shadow 0.3s ease; | |
| } | |
| input:focus, textarea:focus, select:focus { | |
| border-color: var(--accent-wood); | |
| box-shadow: 0 0 0 3px rgba(139, 69, 19, 0.2); /* SaddleBrown with opacity */ | |
| outline: none; | |
| } | |
| textarea { | |
| min-height: 100px; | |
| resize: vertical; | |
| } | |
| .form-button { | |
| margin-top: 20px; | |
| } | |
| .delete-button { | |
| background-color: #ef4444; | |
| } | |
| .delete-button:hover { | |
| background-color: #dc2626; | |
| } | |
| .add-color-btn { | |
| background-color: #10b981; | |
| margin-left: 10px; | |
| padding: 8px 15px; | |
| } | |
| .add-color-btn:hover { | |
| background-color: #059669; | |
| } | |
| .color-input-group { | |
| display: flex; | |
| align-items: center; | |
| gap: 10px; | |
| margin-top: 5px; | |
| } | |
| .color-input-group input { | |
| flex-grow: 1; | |
| } | |
| .color-input-group button { | |
| flex-shrink: 0; | |
| margin-top: 8px; /* Align with input's margin */ | |
| padding: 10px 10px; /* Smaller padding */ | |
| font-size: 0.9rem; | |
| } | |
| .remove-color-btn { | |
| background-color: #ef4444; | |
| color: white; | |
| border: none; | |
| border-radius: 50%; | |
| width: 25px; | |
| height: 25px; | |
| font-size: 14px; | |
| line-height: 25px; /* Center the 'X' */ | |
| text-align: center; | |
| cursor: pointer; | |
| padding: 0; | |
| margin-left: 5px; | |
| } | |
| /* Modal Styles */ | |
| .modal { | |
| display: none; | |
| position: fixed; | |
| z-index: 1001; | |
| left: 0; | |
| top: 0; | |
| width: 100%; | |
| height: 100%; | |
| overflow: auto; | |
| background-color: rgba(0,0,0,0.6); | |
| backdrop-filter: blur(5px); | |
| } | |
| .modal-content { | |
| background-color: var(--card-bg); | |
| margin: 5% auto; | |
| padding: 30px; | |
| border-radius: 15px; | |
| width: 90%; | |
| max-width: 700px; | |
| box-shadow: 0 10px 30px rgba(0,0,0,0.2); | |
| animation: slideIn 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94); | |
| position: relative; | |
| } | |
| @keyframes slideIn { | |
| from { transform: translateY(-50px); opacity: 0; } | |
| to { transform: translateY(0); opacity: 1; } | |
| } | |
| .close { | |
| position: absolute; | |
| top: 15px; | |
| right: 20px; | |
| color: var(--text-dark-brown); | |
| font-size: 2rem; | |
| font-weight: bold; | |
| cursor: pointer; | |
| transition: color 0.3s; | |
| } | |
| .close:hover, .close:focus { | |
| color: var(--accent-wood); | |
| text-decoration: none; | |
| } | |
| .modal-content h2 { | |
| margin-top: 0; | |
| margin-bottom: 1.5rem; | |
| border-bottom: 1px solid var(--border-color); | |
| padding-bottom: 0.8rem; | |
| } | |
| .modal-content p { | |
| margin-bottom: 1rem; | |
| } | |
| .modal-content strong { | |
| color: var(--accent-wood); | |
| } | |
| /* Swiper Styles for Modal */ | |
| .swiper-container { | |
| width: 100%; | |
| max-width: 450px; /* Adjust as needed */ | |
| margin: 0 auto 25px; | |
| border-radius: 10px; | |
| overflow: hidden; | |
| background-color: #eee; /* Placeholder background */ | |
| } | |
| .swiper-slide { | |
| text-align: center; | |
| background: #fff; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| height: 350px; /* Fixed height for slides */ | |
| } | |
| .swiper-slide img { | |
| display: block; | |
| max-width: 100%; | |
| max-height: 100%; | |
| object-fit: contain; | |
| border-radius: 10px; | |
| } | |
| .swiper-pagination-bullet-active { | |
| background: var(--accent-wood) !important; | |
| } | |
| .swiper-button-next, .swiper-button-prev { | |
| color: var(--accent-wood) !important; | |
| background-color: rgba(255, 255, 255, 0.7); | |
| border-radius: 50%; | |
| width: 40px !important; | |
| height: 40px !important; | |
| transition: background-color 0.3s ease; | |
| } | |
| .swiper-button-next:hover, .swiper-button-prev:hover { | |
| background-color: rgba(255, 255, 255, 0.9); | |
| } | |
| .swiper-button-next::after, .swiper-button-prev::after { | |
| font-size: 20px !important; | |
| font-weight: bold; | |
| } | |
| </style> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css"> | |
| """ | |
| # --- Landing Page --- | |
| def landing(): | |
| landing_html = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Mebel Hause KG - Изготовление мебели на заказ</title> | |
| ''' + GLOBAL_STYLES + ''' | |
| <style> | |
| .hero { | |
| background: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)), url('https://images.unsplash.com/photo-1555041469-a586c61ea9bc?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1770&q=80') no-repeat center center/cover; /* Example background */ | |
| color: white; | |
| padding: 100px 20px; | |
| text-align: center; | |
| border-radius: 0 0 20px 20px; /* Rounded bottom corners */ | |
| } | |
| .hero h1 { | |
| font-size: 3rem; | |
| margin-bottom: 1rem; | |
| color: white; | |
| text-shadow: 2px 2px 8px rgba(0,0,0,0.6); | |
| border-bottom: none; /* Override global h1 style */ | |
| } | |
| .hero p { | |
| font-size: 1.3rem; | |
| margin-bottom: 2rem; | |
| text-shadow: 1px 1px 6px rgba(0,0,0,0.7); | |
| } | |
| .features { | |
| display: grid; | |
| grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); | |
| gap: 30px; | |
| margin-top: 40px; | |
| } | |
| .feature-item { | |
| background: var(--card-bg); | |
| padding: 25px; | |
| border-radius: 15px; | |
| text-align: center; | |
| box-shadow: 0 4px 15px rgba(0,0,0,0.08); | |
| transition: transform 0.3s ease, box-shadow 0.3s ease; | |
| } | |
| .feature-item:hover { | |
| transform: translateY(-5px); | |
| box-shadow: 0 6px 20px rgba(0,0,0,0.12); | |
| } | |
| .feature-item i { | |
| font-size: 3rem; | |
| color: var(--accent-wood); | |
| margin-bottom: 1rem; | |
| } | |
| .feature-item h3 { | |
| margin-bottom: 0.5rem; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <header class="header"> | |
| <img src="{{ logo_url }}" alt="Mebel Hause KG Logo" class="header-logo"> | |
| <nav> | |
| <a href="#calculator">Калькулятор</a> | |
| <a href="{{ url_for('catalog') }}">Каталог</a> | |
| <a href="#about">О нас</a> | |
| <a href="#contact">Контакты</a> | |
| </nav> | |
| </header> | |
| <section class="hero"> | |
| <h1>Mebel Hause KG</h1> | |
| <p>Создаем мебель вашей мечты с любовью и мастерством</p> | |
| <a href="{{ url_for('catalog') }}" class="button-link">Смотреть готовые изделия</a> | |
| </section> | |
| <main class="main-content container"> | |
| <section id="about"> | |
| <h2>Почему выбирают нас?</h2> | |
| <div class="features"> | |
| <div class="feature-item"> | |
| <i class="fas fa-couch"></i> | |
| <h3>Индивидуальный дизайн</h3> | |
| <p>Разработаем уникальный проект под ваш интерьер и пожелания.</p> | |
| </div> | |
| <div class="feature-item"> | |
| <i class="fas fa-ruler-combined"></i> | |
| <h3>Точные замеры</h3> | |
| <p>Гарантируем идеальное соответствие мебели вашему пространству.</p> | |
| </div> | |
| <div class="feature-item"> | |
| <i class="fas fa-check-circle"></i> | |
| <h3>Качественные материалы</h3> | |
| <p>Используем только проверенные и долговечные материалы.</p> | |
| </div> | |
| <div class="feature-item"> | |
| <i class="fas fa-shipping-fast"></i> | |
| <h3>Своевременная доставка</h3> | |
| <p>Доставим и соберем вашу новую мебель точно в срок.</p> | |
| </div> | |
| </div> | |
| </section> | |
| <section id="calculator" class="form-section"> | |
| <h2>Рассчитать стоимость мебели</h2> | |
| <p>Заполните форму ниже, и мы свяжемся с вами для уточнения деталей и расчета.</p> | |
| <form id="calculator-form"> | |
| <label for="furniture-type">Вид мебели:</label> | |
| <select id="furniture-type" name="furniture-type"> | |
| <option value="Кухня">Кухня</option> | |
| <option value="Шкаф">Шкаф (купе, распашной)</option> | |
| <option value="ТВ Зона">ТВ Зона</option> | |
| <option value="Кровать">Кровать</option> | |
| <option value="Стол">Стол (обеденный, письменный, журнальный)</option> | |
| <option value="Диван">Диван</option> | |
| <option value="Прихожая">Прихожая</option> | |
| <option value="Детская">Детская мебель</option> | |
| <option value="Другое">Другое (укажите в пожеланиях)</option> | |
| </select> | |
| <label for="material">Предпочитаемый материал:</label> | |
| <select id="material" name="material"> | |
| <option value="ЛДСП">ЛДСП (Ламинированная ДСП)</option> | |
| <option value="МДФ">МДФ (крашеный, пленочный, шпонированный)</option> | |
| <option value="Массив дерева">Массив дерева</option> | |
| <option value="Шпон">Шпон</option> | |
| <option value="Пластик/Акрил">Пластик / Акриловые панели</option> | |
| <option value="Не уверен">Не уверен / Нужна консультация</option> | |
| </select> | |
| <label for="dimensions">Примерные размеры (ШхВхГ в см) или площадь:</label> | |
| <input type="text" id="dimensions" name="dimensions" placeholder="Например: 200x240x60 см или 'стена 3 метра'"> | |
| <label for="wishes">Дополнительные пожелания:</label> | |
| <textarea id="wishes" name="wishes" placeholder="Например: цвет, фурнитура, особенности конструкции, стиль..."></textarea> | |
| <button type="button" class="form-button" onclick="generateWhatsAppMessage()">Отправить запрос на расчет</button> | |
| </form> | |
| </section> | |
| <section id="contact"> | |
| <h2>Свяжитесь с нами</h2> | |
| <p>Готовы обсудить ваш проект? Напишите нам в WhatsApp или позвоните!</p> | |
| <p style="font-size: 1.2rem; font-weight: 600;">Телефон / WhatsApp: <a href="https://wa.me/{{ whatsapp_number }}" target="_blank" style="color: var(--link-color);">{{ whatsapp_number_display }}</a></p> | |
| <p>Мы находимся в Бишкеке.</p> | |
| </section> | |
| </main> | |
| <footer class="footer"> | |
| <p>© {{ current_year }} Mebel Hause KG. Все права защищены.</p> | |
| </footer> | |
| <a href="https://wa.me/{{ whatsapp_number }}" class="whatsapp-float" target="_blank"> | |
| <i class="fab fa-whatsapp"></i> | |
| </a> | |
| <script> | |
| function generateWhatsAppMessage() { | |
| const furnitureType = document.getElementById('furniture-type').value; | |
| const material = document.getElementById('material').value; | |
| const dimensions = document.getElementById('dimensions').value; | |
| const wishes = document.getElementById('wishes').value; | |
| const whatsappNumber = "{{ whatsapp_number }}"; | |
| let message = `Здравствуйте, Mebel Hause KG!\\n\\nХочу рассчитать стоимость мебели:\\n`; | |
| message += `*Тип:* ${furnitureType}\\n`; | |
| message += `*Материал:* ${material}\\n`; | |
| if (dimensions) { | |
| message += `*Размеры/Площадь:* ${dimensions}\\n`; | |
| } | |
| if (wishes) { | |
| message += `*Пожелания:* ${wishes}\\n`; | |
| } | |
| message += `\\nЖду вашего ответа.`; | |
| const encodedMessage = encodeURIComponent(message); | |
| const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${encodedMessage}`; | |
| // const whatsappUrl = `https://wa.me/${whatsappNumber}?text=${encodedMessage}`; // Alternative format | |
| window.open(whatsappUrl, '_blank'); | |
| } | |
| // Active link highlighting | |
| document.addEventListener("DOMContentLoaded", function() { | |
| const navLinks = document.querySelectorAll('.header nav a'); | |
| const currentPath = window.location.pathname; | |
| navLinks.forEach(link => { | |
| // Simple check for landing page links (using hash) | |
| if (link.getAttribute('href').startsWith('#') && currentPath === '/') { | |
| // Could add logic for scrollspy here if needed | |
| } else if (link.getAttribute('href') === currentPath) { | |
| link.classList.add('active'); | |
| } | |
| }); | |
| }); | |
| </script> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/js/all.min.js"></script> | |
| </body> | |
| </html> | |
| ''' | |
| # Format number for display | |
| whatsapp_display = f"+{WHATSAPP_NUMBER[0]} ({WHATSAPP_NUMBER[1:4]}) {WHATSAPP_NUMBER[4:7]}-{WHATSAPP_NUMBER[7:10]}-{WHATSAPP_NUMBER[10:]}" | |
| return render_template_string( | |
| landing_html, | |
| logo_url=LOGO_URL, | |
| whatsapp_number=WHATSAPP_NUMBER, | |
| whatsapp_number_display=whatsapp_display, | |
| current_year=datetime.now().year | |
| ) | |
| # --- Catalog Page --- | |
| def catalog(): | |
| data = load_data() | |
| products = data.get('products', []) | |
| categories = data.get('categories', []) | |
| catalog_html = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Каталог готовой мебели - Mebel Hause KG</title> | |
| ''' + GLOBAL_STYLES + ''' | |
| <style> | |
| .filters-container { | |
| margin: 30px 0; | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| justify-content: center; | |
| padding-bottom: 20px; | |
| border-bottom: 1px solid var(--border-color); | |
| } | |
| .search-container { | |
| margin: 20px 0; | |
| text-align: center; | |
| } | |
| #search-input { | |
| width: 90%; | |
| max-width: 600px; | |
| padding: 12px 18px; | |
| font-size: 1rem; | |
| border: 1px solid var(--border-color); | |
| border-radius: 8px; | |
| outline: none; | |
| box-shadow: 0 2px 5px rgba(0,0,0,0.05); | |
| transition: all 0.3s ease; | |
| } | |
| #search-input:focus { | |
| border-color: var(--accent-wood); | |
| box-shadow: 0 0 0 3px rgba(139, 69, 19, 0.2); | |
| } | |
| .category-filter { | |
| padding: 8px 16px; | |
| border: 1px solid var(--border-color); | |
| border-radius: 20px; /* Pill shape */ | |
| background-color: var(--card-bg); | |
| color: var(--text-dark-brown); | |
| cursor: pointer; | |
| transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); | |
| font-size: 0.9rem; | |
| font-weight: 500; | |
| } | |
| .category-filter.active, .category-filter:hover { | |
| background-color: var(--accent-wood); | |
| color: white; | |
| border-color: var(--accent-wood); | |
| box-shadow: 0 2px 10px rgba(139, 69, 19, 0.3); | |
| } | |
| .products-grid { | |
| display: grid; | |
| /* Responsive columns: 1 on small, 2 on medium, 3-4 on large */ | |
| grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); | |
| gap: 25px; | |
| padding: 10px 0; /* Remove side padding */ | |
| } | |
| .product { | |
| background: var(--card-bg); | |
| border-radius: 15px; | |
| padding: 0; /* Remove padding, handle inside */ | |
| 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; /* Ensure content respects border radius */ | |
| display: flex; | |
| flex-direction: column; | |
| } | |
| .product:hover { | |
| transform: translateY(-5px) scale(1.02); | |
| box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12); | |
| } | |
| .product-image { | |
| width: 100%; | |
| aspect-ratio: 4 / 3; /* Adjust aspect ratio */ | |
| background-color: #f0f0f0; /* Light placeholder bg */ | |
| overflow: hidden; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| } | |
| .product-image img { | |
| width: 100%; | |
| height: 100%; | |
| object-fit: cover; /* Cover the area */ | |
| transition: transform 0.4s ease; | |
| } | |
| .product:hover .product-image img { | |
| transform: scale(1.05); /* Slight zoom on hover */ | |
| } | |
| .product-info { | |
| padding: 15px; | |
| text-align: center; | |
| flex-grow: 1; /* Allow info to take remaining space */ | |
| display: flex; | |
| flex-direction: column; | |
| justify-content: space-between; /* Push buttons down */ | |
| } | |
| .product-info-top { | |
| margin-bottom: 15px; /* Space before buttons */ | |
| } | |
| .product h2 { | |
| font-size: 1.1rem; /* Slightly smaller */ | |
| font-weight: 600; | |
| margin: 0 0 8px 0; /* Adjust margin */ | |
| white-space: nowrap; | |
| overflow: hidden; | |
| text-overflow: ellipsis; | |
| border-bottom: none; /* Override global */ | |
| padding-bottom: 0; | |
| } | |
| .product-price { | |
| font-size: 1.2rem; | |
| color: var(--accent-wood); /* Accent color for price */ | |
| font-weight: 700; | |
| margin: 5px 0; | |
| } | |
| .product-description { | |
| font-size: 0.9rem; | |
| color: #555; /* Slightly lighter text */ | |
| margin-bottom: 15px; | |
| overflow: hidden; | |
| text-overflow: ellipsis; | |
| /* Limit description lines */ | |
| display: -webkit-box; | |
| -webkit-line-clamp: 2; /* Show max 2 lines */ | |
| -webkit-box-orient: vertical; | |
| } | |
| .product-buttons { | |
| display: flex; | |
| gap: 10px; /* Space between buttons */ | |
| margin-top: auto; /* Push to bottom */ | |
| } | |
| .product-button { | |
| flex: 1; /* Make buttons equal width */ | |
| padding: 10px; | |
| border: none; | |
| border-radius: 8px; | |
| background-color: var(--button-bg); | |
| 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: var(--button-hover-bg); | |
| transform: translateY(-2px); | |
| } | |
| .add-to-cart { | |
| background-color: #10b981; /* Green for cart */ | |
| } | |
| .add-to-cart:hover { | |
| background-color: #059669; | |
| box-shadow: 0 4px 15px rgba(5, 150, 105, 0.4); | |
| } | |
| #cart-button { | |
| position: fixed; | |
| bottom: 30px; /* Match whatsapp button height */ | |
| right: 100px; /* Position next to whatsapp */ | |
| background-color: var(--accent-light-wood); /* Light wood color */ | |
| color: var(--text-dark-brown); | |
| border: none; | |
| border-radius: 50%; | |
| width: 60px; | |
| height: 60px; | |
| font-size: 1.5rem; /* Larger icon */ | |
| cursor: pointer; | |
| display: none; /* Hidden by default */ | |
| justify-content: center; | |
| align-items: center; | |
| box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); | |
| transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); | |
| z-index: 1000; | |
| } | |
| #cart-button:hover { | |
| transform: scale(1.1); | |
| background-color: var(--accent-wood); | |
| color: white; | |
| } | |
| #cart-count { | |
| position: absolute; | |
| top: -5px; | |
| right: -5px; | |
| background-color: #ef4444; /* Red badge */ | |
| color: white; | |
| border-radius: 50%; | |
| padding: 2px 6px; | |
| font-size: 0.7rem; | |
| font-weight: bold; | |
| } | |
| /* Cart Modal Specific Styles */ | |
| .cart-item { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| padding: 15px 0; | |
| border-bottom: 1px solid var(--border-color); | |
| } | |
| .cart-item:last-child { | |
| border-bottom: none; | |
| } | |
| .cart-item img { | |
| width: 60px; | |
| height: 60px; | |
| object-fit: cover; | |
| border-radius: 8px; | |
| margin-right: 15px; | |
| border: 1px solid var(--border-color); | |
| } | |
| .cart-item-details { | |
| flex-grow: 1; | |
| margin-right: 15px; | |
| } | |
| .cart-item-details strong { | |
| display: block; | |
| margin-bottom: 3px; | |
| } | |
| .cart-item-details p { | |
| font-size: 0.9rem; | |
| color: #555; | |
| margin-bottom: 0; | |
| } | |
| .cart-item-price { | |
| font-weight: 600; | |
| min-width: 80px; /* Ensure price alignment */ | |
| text-align: right; | |
| } | |
| .cart-actions { | |
| display: flex; | |
| justify-content: flex-end; | |
| gap: 15px; | |
| margin-top: 25px; | |
| padding-top: 20px; | |
| border-top: 1px solid var(--border-color); | |
| } | |
| #cartTotal { | |
| font-size: 1.3rem; | |
| } | |
| .quantity-input, .color-select { /* Style for quantity/color modal */ | |
| width: 100%; | |
| max-width: 200px; /* Adjust width */ | |
| padding: 10px; | |
| border: 1px solid var(--border-color); | |
| border-radius: 8px; | |
| font-size: 1rem; | |
| margin: 10px 0; | |
| display: block; /* Ensure they take block space */ | |
| } | |
| .modal-content .product-button { /* Reuse product button style */ | |
| margin-top: 15px; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <header class="header"> | |
| <a href="{{ url_for('landing') }}"> | |
| <img src="{{ logo_url }}" alt="Mebel Hause KG Logo" class="header-logo"> | |
| </a> | |
| <nav> | |
| <a href="{{ url_for('landing') }}#calculator">Калькулятор</a> | |
| <a href="{{ url_for('catalog') }}" class="active">Каталог</a> | |
| <a href="{{ url_for('landing') }}#about">О нас</a> | |
| <a href="{{ url_for('landing') }}#contact">Контакты</a> | |
| </nav> | |
| </header> | |
| <div class="container main-content"> | |
| <h1>Каталог готовых изделий</h1> | |
| <p style="text-align: center; margin-bottom: 2rem;">Ознакомьтесь с нашими работами. Возможно, что-то из этого подойдет именно вам!</p> | |
| <div class="filters-container"> | |
| <button class="category-filter active" data-category="all">Все категории</button> | |
| {% for category in categories %} | |
| <button class="category-filter" data-category="{{ category }}">{{ category }}</button> | |
| {% endfor %} | |
| </div> | |
| <div class="search-container"> | |
| <input type="text" id="search-input" placeholder="Поиск по названию или описанию..."> | |
| </div> | |
| <div class="products-grid" id="products-grid"> | |
| {% for product in products %} | |
| <div class="product" | |
| data-name="{{ product['name']|lower }}" | |
| data-description="{{ product['description']|lower }}" | |
| data-category="{{ product.get('category', 'Без категории') }}"> | |
| <div class="product-image"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}?download=true" | |
| alt="{{ product['name'] }}" | |
| loading="lazy"> | |
| {% else %} | |
| <img src="https://via.placeholder.com/400x300?text=Нет+фото" alt="Нет фото"> | |
| {% endif %} | |
| </div> | |
| <div class="product-info"> | |
| <div class="product-info-top"> | |
| <h2>{{ product['name'] }}</h2> | |
| <div class="product-price">{{ product['price'] }} сом</div> | |
| <p class="product-description">{{ product['description'] }}</p> | |
| </div> | |
| <div class="product-buttons"> | |
| <button class="product-button" onclick="openModal({{ loop.index0 }})">Подробнее</button> | |
| <button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})"> | |
| <i class="fas fa-cart-plus"></i> В корзину | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| {% else %} | |
| <p>В каталоге пока нет товаров.</p> | |
| {% endfor %} | |
| </div> | |
| </div> | |
| <div id="productModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('productModal')">×</span> | |
| <div id="modalContent"></div> | |
| </div> | |
| </div> | |
| <div id="quantityModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('quantityModal')">×</span> | |
| <h2>Добавить в корзину</h2> | |
| <label for="quantityInput">Количество:</label> | |
| <input type="number" id="quantityInput" class="quantity-input" min="1" value="1"> | |
| <div id="colorSelectorContainer"> | |
| <label for="colorSelect">Цвет:</label> | |
| <select id="colorSelect" class="color-select"></select> | |
| </div> | |
| <button class="product-button add-to-cart" onclick="confirmAddToCart()"> | |
| <i class="fas fa-check"></i> Добавить | |
| </button> | |
| </div> | |
| </div> | |
| <div id="cartModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('cartModal')">×</span> | |
| <h2><i class="fas fa-shopping-cart"></i> Ваша корзина</h2> | |
| <div id="cartContent"><p>Корзина пуста.</p></div> | |
| <div style="margin-top: 20px; text-align: right; font-size: 1.2rem; font-weight: 600;"> | |
| <strong>Итого: <span id="cartTotal">0</span> сом</strong> | |
| </div> | |
| <div class="cart-actions"> | |
| <button class="product-button delete-button" onclick="clearCart()"> | |
| <i class="fas fa-trash"></i> Очистить | |
| </button> | |
| <button class="product-button add-to-cart" onclick="orderViaWhatsApp()"> | |
| <i class="fab fa-whatsapp"></i> Заказать по WhatsApp | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| <button id="cart-button" onclick="openCartModal()"> | |
| <i class="fas fa-shopping-cart"></i> | |
| <span id="cart-count">0</span> | |
| </button> | |
| <a href="https://wa.me/{{ whatsapp_number }}" class="whatsapp-float" target="_blank"> | |
| <i class="fab fa-whatsapp"></i> | |
| </a> | |
| <footer class="footer"> | |
| <p>© {{ current_year }} Mebel Hause KG. Все права защищены.</p> | |
| </footer> | |
| <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 whatsappNumber = "{{ whatsapp_number }}"; | |
| let selectedProductIndex = null; | |
| let productModalSwiper = null; | |
| function openModal(index) { | |
| loadProductDetails(index); | |
| document.getElementById('productModal').style.display = "block"; | |
| } | |
| function closeModal(modalId) { | |
| document.getElementById(modalId).style.display = "none"; | |
| if (modalId === 'productModal' && productModalSwiper) { | |
| productModalSwiper.destroy(true, true); | |
| productModalSwiper = null; | |
| } | |
| } | |
| function loadProductDetails(index) { | |
| fetch('/product/' + index) | |
| .then(response => { | |
| if (!response.ok) { | |
| throw new Error('Товар не найден'); | |
| } | |
| return response.text(); | |
| }) | |
| .then(data => { | |
| document.getElementById('modalContent').innerHTML = data; | |
| initializeSwiper(); // Initialize Swiper after content is loaded | |
| }) | |
| .catch(error => { | |
| console.error('Ошибка загрузки деталей товара:', error); | |
| document.getElementById('modalContent').innerHTML = '<p>Не удалось загрузить информацию о товаре.</p>'; | |
| }); | |
| } | |
| function initializeSwiper() { | |
| const swiperElement = document.querySelector('#productModal .swiper-container'); | |
| if (swiperElement) { | |
| if (productModalSwiper) { // Destroy previous instance if exists | |
| productModalSwiper.destroy(true, true); | |
| } | |
| productModalSwiper = new Swiper(swiperElement, { | |
| slidesPerView: 1, | |
| spaceBetween: 20, | |
| loop: true, // Loop if more than one slide | |
| grabCursor: true, | |
| pagination: { el: '.swiper-pagination', clickable: true }, | |
| navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, | |
| zoom: { maxRatio: 3, containerClass: 'swiper-zoom-container' }, | |
| lazy: { loadPrevNext: true }, // Enable lazy loading | |
| }); | |
| // Ensure loop works correctly only if there are multiple images | |
| if (productModalSwiper.slides.length <= 3) { // Swiper adds duplicates for loop | |
| productModalSwiper.params.loop = false; | |
| productModalSwiper.update(); | |
| } | |
| } else { | |
| console.log("Swiper container not found in modal content."); | |
| } | |
| } | |
| function openQuantityModal(index) { | |
| selectedProductIndex = index; | |
| const product = products[index]; | |
| if (!product) { | |
| console.error("Товар не найден по индексу:", index); | |
| alert("Ошибка: Товар не найден."); | |
| return; | |
| } | |
| const colorSelect = document.getElementById('colorSelect'); | |
| const colorContainer = document.getElementById('colorSelectorContainer'); | |
| colorSelect.innerHTML = ''; // Clear previous options | |
| if (product.colors && product.colors.length > 0) { | |
| product.colors.forEach(color => { | |
| const option = document.createElement('option'); | |
| option.value = color; | |
| option.textContent = color; | |
| colorSelect.appendChild(option); | |
| }); | |
| colorContainer.style.display = 'block'; // Show color selector | |
| } else { | |
| // If no colors, add a default placeholder and hide selector? Or just proceed? | |
| // Let's hide it if no colors are defined for this product | |
| colorContainer.style.display = 'none'; | |
| } | |
| document.getElementById('quantityInput').value = 1; // Reset quantity | |
| document.getElementById('quantityModal').style.display = 'block'; | |
| } | |
| function confirmAddToCart() { | |
| if (selectedProductIndex === null || !products[selectedProductIndex]) { | |
| console.error("Не выбран товар для добавления."); | |
| alert("Ошибка: Пожалуйста, выберите товар."); | |
| return; | |
| } | |
| const quantity = parseInt(document.getElementById('quantityInput').value) || 1; | |
| const product = products[selectedProductIndex]; | |
| const colorSelect = document.getElementById('colorSelect'); | |
| // Use selected color if available, otherwise use a placeholder or null | |
| let color = 'N/A'; // Default if no colors | |
| if (product.colors && product.colors.length > 0) { | |
| color = colorSelect.value || product.colors[0]; // Get selected or first color | |
| } | |
| if (quantity <= 0) { | |
| alert("Укажите количество больше 0"); | |
| return; | |
| } | |
| let cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| // Unique ID considering product name and color (if applicable) | |
| const cartItemId = product.colors && product.colors.length > 0 ? `${product.name}-${color}` : product.name; | |
| const existingItemIndex = cart.findIndex(item => item.id === cartItemId); | |
| if (existingItemIndex > -1) { | |
| cart[existingItemIndex].quantity += quantity; | |
| } else { | |
| cart.push({ | |
| id: cartItemId, | |
| name: product.name, | |
| price: product.price, | |
| photo: product.photos && product.photos.length > 0 ? product.photos[0] : '', | |
| quantity: quantity, | |
| color: color, // Store the selected color | |
| repoId: repoId // Store repoId for image URL generation later | |
| }); | |
| } | |
| localStorage.setItem('cart', JSON.stringify(cart)); | |
| closeModal('quantityModal'); | |
| updateCartButton(); | |
| showNotification(`${product.name} добавлен в корзину!`); | |
| } | |
| function showNotification(message) { | |
| const notification = document.createElement('div'); | |
| notification.style.position = 'fixed'; | |
| notification.style.bottom = '20px'; | |
| notification.style.left = '50%'; | |
| notification.style.transform = 'translateX(-50%)'; | |
| notification.style.backgroundColor = 'var(--accent-wood)'; | |
| notification.style.color = 'white'; | |
| notification.style.padding = '10px 20px'; | |
| notification.style.borderRadius = '8px'; | |
| notification.style.zIndex = '1005'; | |
| notification.style.opacity = '0'; | |
| notification.style.transition = 'opacity 0.5s ease'; | |
| notification.textContent = message; | |
| document.body.appendChild(notification); | |
| // Fade in | |
| setTimeout(() => { notification.style.opacity = '1'; }, 10); | |
| // Fade out and remove | |
| setTimeout(() => { | |
| notification.style.opacity = '0'; | |
| setTimeout(() => { document.body.removeChild(notification); }, 500); | |
| }, 3000); // Show for 3 seconds | |
| } | |
| function updateCartButton() { | |
| const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const cartButton = document.getElementById('cart-button'); | |
| const cartCount = document.getElementById('cart-count'); | |
| const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0); | |
| if (totalItems > 0) { | |
| cartButton.style.display = 'flex'; // Use flex to center icon | |
| cartCount.textContent = totalItems; | |
| cartCount.style.display = 'block'; | |
| } else { | |
| cartButton.style.display = 'none'; | |
| cartCount.style.display = 'none'; | |
| } | |
| } | |
| function openCartModal() { | |
| const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const cartContent = document.getElementById('cartContent'); | |
| let total = 0; | |
| if (cart.length === 0) { | |
| cartContent.innerHTML = '<p style="text-align: center; padding: 20px 0;">Ваша корзина пуста.</p>'; | |
| document.getElementById('cartTotal').textContent = '0'; | |
| } else { | |
| cartContent.innerHTML = cart.map(item => { | |
| const itemTotal = item.price * item.quantity; | |
| total += itemTotal; | |
| const photoUrl = item.photo ? `https://huggingface.co/datasets/${item.repoId}/resolve/main/photos/${item.photo}?download=true` : 'https://via.placeholder.com/60x60?text=N/A'; | |
| return ` | |
| <div class="cart-item"> | |
| <img src="${photoUrl}" alt="${item.name}"> | |
| <div class="cart-item-details"> | |
| <strong>${item.name}</strong> | |
| <p>${item.quantity} шт. × ${item.price} сом ${item.color !== 'N/A' ? `(Цвет: ${item.color})` : ''}</p> | |
| </div> | |
| <span class="cart-item-price">${itemTotal} сом</span> | |
| <button onclick="removeFromCart('${item.id}')" style="background: none; border: none; color: #ef4444; cursor: pointer; font-size: 1.2rem; margin-left: 10px;" title="Удалить товар">×</button> | |
| </div> | |
| `; | |
| }).join(''); | |
| document.getElementById('cartTotal').textContent = total; | |
| } | |
| document.getElementById('cartModal').style.display = 'block'; | |
| } | |
| function removeFromCart(itemId) { | |
| let cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| cart = cart.filter(item => item.id !== itemId); | |
| localStorage.setItem('cart', JSON.stringify(cart)); | |
| openCartModal(); // Refresh cart modal view | |
| updateCartButton(); // Update cart button count | |
| } | |
| function orderViaWhatsApp() { | |
| const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| if (cart.length === 0) { | |
| alert("Ваша корзина пуста!"); | |
| return; | |
| } | |
| let total = 0; | |
| let orderText = "Здравствуйте! Хочу заказать следующие товары из каталога:\\n\\n"; | |
| cart.forEach((item, index) => { | |
| const itemTotal = item.price * item.quantity; | |
| total += itemTotal; | |
| orderText += `${index + 1}. ${item.name}`; | |
| if (item.color !== 'N/A') { | |
| orderText += ` (Цвет: ${item.color})`; | |
| } | |
| orderText += ` - ${item.quantity} шт. x ${item.price} сом = ${itemTotal} сом\\n`; | |
| }); | |
| orderText += `\\n*Итого: ${total} сом*`; | |
| const encodedMessage = encodeURIComponent(orderText); | |
| // const whatsappUrl = `https://wa.me/${whatsappNumber}?text=${encodedMessage}`; | |
| const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${encodedMessage}`; | |
| window.open(whatsappUrl, '_blank'); | |
| // Optionally clear cart after sending? Or ask user? | |
| // clearCart(); | |
| } | |
| function clearCart() { | |
| if (confirm("Вы уверены, что хотите очистить корзину?")) { | |
| localStorage.removeItem('cart'); | |
| closeModal('cartModal'); | |
| updateCartButton(); | |
| openCartModal(); // Refresh modal to show empty state | |
| } | |
| } | |
| window.onclick = function(event) { | |
| const modals = document.querySelectorAll('.modal'); | |
| modals.forEach(modal => { | |
| if (event.target == modal) { | |
| closeModal(modal.id); | |
| } | |
| }); | |
| } | |
| document.addEventListener('keydown', function(event) { | |
| if (event.key === "Escape") { | |
| const modals = document.querySelectorAll('.modal'); | |
| modals.forEach(modal => { | |
| if (modal.style.display === "block") { | |
| closeModal(modal.id); | |
| } | |
| }); | |
| } | |
| }); | |
| document.getElementById('search-input').addEventListener('input', filterProducts); | |
| document.querySelectorAll('.category-filter').forEach(filter => { | |
| filter.addEventListener('click', function() { | |
| document.querySelectorAll('.category-filter').forEach(f => f.classList.remove('active')); | |
| this.classList.add('active'); | |
| filterProducts(); | |
| }); | |
| }); | |
| function filterProducts() { | |
| const searchTerm = document.getElementById('search-input').value.toLowerCase().trim(); | |
| const activeCategory = document.querySelector('.category-filter.active').dataset.category; | |
| let hasVisibleProducts = false; | |
| document.querySelectorAll('.product').forEach(product => { | |
| const name = product.getAttribute('data-name'); | |
| const description = product.getAttribute('data-description'); | |
| const category = product.getAttribute('data-category'); | |
| const matchesSearch = searchTerm === '' || name.includes(searchTerm) || description.includes(searchTerm); | |
| const matchesCategory = activeCategory === 'all' || category === activeCategory; | |
| if (matchesSearch && matchesCategory) { | |
| product.style.display = 'flex'; // Use flex as it's the default for .product | |
| hasVisibleProducts = true; | |
| } else { | |
| product.style.display = 'none'; | |
| } | |
| }); | |
| // Optional: Show a message if no products match | |
| const grid = document.getElementById('products-grid'); | |
| let noMatchMsg = grid.querySelector('.no-match-message'); | |
| if (!hasVisibleProducts) { | |
| if (!noMatchMsg) { | |
| noMatchMsg = document.createElement('p'); | |
| noMatchMsg.className = 'no-match-message'; | |
| noMatchMsg.textContent = 'Товары не найдены по вашему запросу.'; | |
| noMatchMsg.style.textAlign = 'center'; | |
| noMatchMsg.style.gridColumn = '1 / -1'; // Span all columns | |
| grid.appendChild(noMatchMsg); | |
| } | |
| } else { | |
| if (noMatchMsg) { | |
| grid.removeChild(noMatchMsg); | |
| } | |
| } | |
| } | |
| // Initial setup | |
| document.addEventListener('DOMContentLoaded', () => { | |
| updateCartButton(); | |
| filterProducts(); // Initial filter on page load | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| return render_template_string( | |
| catalog_html, | |
| products=products, | |
| categories=categories, | |
| repo_id=REPO_ID, | |
| logo_url=LOGO_URL, | |
| whatsapp_number=WHATSAPP_NUMBER, | |
| current_year=datetime.now().year | |
| ) | |
| # --- Product Detail Partial --- | |
| def product_detail(index): | |
| data = load_data() | |
| products = data.get('products', []) | |
| try: | |
| product = products[index] | |
| except IndexError: | |
| logging.warning(f"Попытка доступа к несуществующему продукту с индексом {index}") | |
| return "Товар не найден", 404 | |
| detail_html = ''' | |
| <h2 style="font-size: 1.8rem; font-weight: 600; margin-bottom: 20px; text-align: center;">{{ product['name'] }}</h2> | |
| <div class="swiper-container"> | |
| <div class="swiper-wrapper"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| {% for photo in product['photos'] %} | |
| <div class="swiper-slide"> | |
| <div class="swiper-zoom-container"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}?download=true" | |
| alt="{{ product['name'] }} - Фото {{ loop.index }}" | |
| loading="lazy"> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <div class="swiper-slide"> | |
| <img src="https://via.placeholder.com/450x350?text=Нет+фото" alt="Фото отсутствует"> | |
| </div> | |
| {% endif %} | |
| </div> | |
| <!-- Add Pagination --> | |
| <div class="swiper-pagination"></div> | |
| <!-- Add Navigation --> | |
| <div class="swiper-button-next"></div> | |
| <div class="swiper-button-prev"></div> | |
| </div> | |
| <div style="padding: 0 15px;"> <!-- Add padding around text details --> | |
| <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> | |
| <p><strong>Цена:</strong> <span style="font-weight: 700; font-size: 1.2em; color: var(--accent-wood);">{{ product['price'] }} сом</span></p> | |
| <p><strong>Описание:</strong></p> | |
| <p style="white-space: pre-wrap;">{{ product['description'] }}</p> <!-- Preserve line breaks in description --> | |
| {% if product.get('colors') and product['colors']|length > 0 %} | |
| <p><strong>Доступные цвета:</strong> {{ product['colors']|join(', ') }}</p> | |
| {% endif %} | |
| </div> | |
| ''' | |
| return render_template_string(detail_html, product=product, repo_id=REPO_ID) | |
| # --- Admin Panel --- | |
| def admin(): | |
| data = load_data() | |
| products = data.get('products', []) | |
| categories = data.get('categories', []) | |
| message = None # To display success/error messages | |
| if request.method == 'POST': | |
| action = request.form.get('action') | |
| logging.debug(f"Admin action received: {action}") | |
| logging.debug(f"Form data: {request.form}") | |
| logging.debug(f"Files data: {request.files}") | |
| try: | |
| if action == 'add_category': | |
| category_name = request.form.get('category_name', '').strip() | |
| if category_name and category_name not in categories: | |
| categories.append(category_name) | |
| save_data(data) | |
| message = ("Категория добавлена", "success") | |
| elif not category_name: | |
| message = ("Название категории не может быть пустым", "error") | |
| else: | |
| message = ("Категория уже существует", "error") | |
| return redirect(url_for('admin', msg=message[0], type=message[1])) | |
| elif action == 'delete_category': | |
| category_index_str = request.form.get('category_index') | |
| if category_index_str is not None: | |
| category_index = int(category_index_str) | |
| if 0 <= category_index < len(categories): | |
| deleted_category = categories.pop(category_index) | |
| # Update products using this category | |
| for product in products: | |
| if product.get('category') == deleted_category: | |
| product['category'] = 'Без категории' # Assign to default | |
| save_data(data) | |
| message = ("Категория удалена", "success") | |
| else: | |
| message = ("Неверный индекс категории", "error") | |
| else: | |
| message = ("Индекс категории не указан", "error") | |
| return redirect(url_for('admin', msg=message[0], type=message[1])) | |
| elif action == 'add' or action == 'edit': | |
| name = request.form.get('name', '').strip() | |
| price_str = request.form.get('price', '0').replace(',', '.') | |
| description = request.form.get('description', '').strip() | |
| category = request.form.get('category') | |
| photos_files = request.files.getlist('photos') | |
| # Get colors - handle empty strings and potential duplicates | |
| colors = [c.strip() for c in request.form.getlist('colors') if c.strip()] | |
| colors = sorted(list(set(colors))) # Remove duplicates and sort | |
| logging.debug(f"Received colors: {request.form.getlist('colors')}") | |
| logging.debug(f"Processed colors: {colors}") | |
| if not name or not description: | |
| message = ("Название и описание товара обязательны", "error") | |
| # Need to pass current state back if redirecting | |
| return redirect(url_for('admin', msg=message[0], type=message[1])) | |
| try: | |
| price = float(price_str) | |
| if price < 0: raise ValueError("Price cannot be negative") | |
| except ValueError: | |
| message = ("Некорректное значение цены", "error") | |
| return redirect(url_for('admin', msg=message[0], type=message[1])) | |
| photos_list = [] | |
| # Upload new photos if provided | |
| if photos_files and any(f.filename for f in photos_files): | |
| if not HF_TOKEN_WRITE: | |
| message = ("HF_TOKEN (write) не установлен. Невозможно загрузить фото.", "warning") | |
| # Decide if you want to proceed without photos or stop | |
| # return redirect(url_for('admin', msg=message[0], type=message[1])) | |
| else: | |
| api = HfApi() | |
| uploads_dir = 'uploads_temp' # Temporary local storage | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| for photo in photos_files[:10]: # Limit photos | |
| if photo and photo.filename: | |
| try: | |
| photo_filename = secure_filename(f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{photo.filename}") | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| photo.save(temp_path) | |
| logging.info(f"Uploading photo {photo_filename} to HF...") | |
| api.upload_file( | |
| path_or_fileobj=temp_path, | |
| path_in_repo=f"photos/{photo_filename}", | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Фото для товара {name}" | |
| ) | |
| photos_list.append(photo_filename) | |
| logging.info(f"Photo {photo_filename} uploaded successfully.") | |
| # Clean up local temp file | |
| if os.path.exists(temp_path): | |
| os.remove(temp_path) | |
| except Exception as e: | |
| logging.error(f"Ошибка загрузки фото {photo.filename}: {e}") | |
| message = (f"Ошибка загрузки фото {photo.filename}", "error") | |
| # Decide whether to stop or continue | |
| # Clean up temp directory if empty | |
| if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): | |
| os.rmdir(uploads_dir) | |
| if action == 'add': | |
| new_product = { | |
| 'name': name, | |
| 'price': price, | |
| 'description': description, | |
| 'category': category if category in categories else 'Без категории', | |
| 'photos': photos_list, # Only new photos for 'add' | |
| 'colors': colors | |
| } | |
| products.append(new_product) | |
| message = ("Товар успешно добавлен", "success") | |
| elif action == 'edit': | |
| index_str = request.form.get('index') | |
| if index_str is not None: | |
| index = int(index_str) | |
| if 0 <= index < len(products): | |
| # Update fields | |
| products[index]['name'] = name | |
| products[index]['price'] = price | |
| products[index]['description'] = description | |
| products[index]['category'] = category if category in categories else 'Без категории' | |
| products[index]['colors'] = colors | |
| # If new photos were uploaded, replace the old list. Otherwise, keep existing photos. | |
| if photos_list: | |
| # Optionally delete old photos from HF here if needed (more complex) | |
| products[index]['photos'] = photos_list | |
| # If no new photos uploaded, 'photos_list' is empty, | |
| # and we don't touch products[index]['photos'] | |
| message = ("Товар успешно обновлен", "success") | |
| else: | |
| message = ("Неверный индекс товара для редактирования", "error") | |
| else: | |
| message = ("Индекс товара для редактирования не указан", "error") | |
| elif action == 'delete': | |
| index_str = request.form.get('index') | |
| if index_str is not None: | |
| index = int(index_str) | |
| if 0 <= index < len(products): | |
| # Optionally delete photos from HF here (more complex) | |
| del products[index] | |
| message = ("Товар удален", "success") | |
| else: | |
| message = ("Неверный индекс товара для удаления", "error") | |
| else: | |
| message = ("Индекс товара для удаления не указан", "error") | |
| # Save changes if any action potentially modified data (except delete errors) | |
| if message and message[1] != "error": # Save on success or warning | |
| save_data(data) | |
| # Redirect only after processing and potential save | |
| return redirect(url_for('admin', msg=message[0] if message else None, type=message[1] if message else None)) | |
| except Exception as e: | |
| logging.error(f"Ошибка в админ панели ({action}): {e}", exc_info=True) | |
| message = (f"Произошла внутренняя ошибка: {e}", "error") | |
| return redirect(url_for('admin', msg=message[0], type=message[1])) | |
| # --- Admin HTML --- | |
| flash_message = request.args.get('msg') | |
| flash_type = request.args.get('type', 'info') # Default type | |
| admin_html = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Админ-панель - Mebel Hause KG</title> | |
| ''' + GLOBAL_STYLES + ''' | |
| <style> | |
| /* Admin specific styles */ | |
| .admin-container { | |
| padding-top: 20px; | |
| } | |
| .admin-section { | |
| margin-bottom: 40px; | |
| } | |
| .product-list, .category-list { | |
| display: grid; | |
| gap: 20px; | |
| margin-top: 20px; | |
| } | |
| .product-item, .category-item { | |
| background: var(--card-bg); | |
| padding: 20px; | |
| border-radius: 15px; | |
| box-shadow: 0 4px 15px rgba(0,0,0,0.08); | |
| border: 1px solid var(--border-color); | |
| } | |
| .product-item h3, .category-item h3 { | |
| margin-top: 0; | |
| margin-bottom: 10px; | |
| font-size: 1.3rem; | |
| border-bottom: 1px solid var(--border-color); | |
| padding-bottom: 8px; | |
| } | |
| .product-item p { | |
| margin-bottom: 8px; | |
| font-size: 0.95rem; | |
| } | |
| .edit-form { | |
| margin-top: 20px; | |
| padding: 20px; | |
| background: #f9f9f7; /* Slightly off-white */ | |
| border: 1px solid var(--border-color); | |
| border-radius: 10px; | |
| } | |
| details summary { | |
| cursor: pointer; | |
| font-weight: 500; | |
| color: var(--link-color); | |
| margin: 15px 0; | |
| display: inline-block; /* Fit content */ | |
| } | |
| .product-photos-admin { | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| margin-top: 10px; | |
| } | |
| .product-photos-admin img { | |
| max-width: 100px; | |
| max-height: 100px; | |
| object-fit: cover; | |
| border-radius: 8px; | |
| border: 1px solid var(--border-color); | |
| } | |
| .action-buttons form { | |
| display: inline-block; | |
| margin-right: 10px; | |
| } | |
| .action-buttons button { | |
| padding: 8px 15px; | |
| font-size: 0.9rem; | |
| } | |
| /* Flash Messages */ | |
| .flash-message { | |
| padding: 15px; | |
| margin-bottom: 20px; | |
| border-radius: 8px; | |
| font-weight: 500; | |
| } | |
| .flash-message.success { | |
| background-color: #d1e7dd; /* Light green */ | |
| color: #0f5132; /* Dark green */ | |
| border: 1px solid #badbcc; | |
| } | |
| .flash-message.error { | |
| background-color: #f8d7da; /* Light red */ | |
| color: #842029; /* Dark red */ | |
| border: 1px solid #f5c2c7; | |
| } | |
| .flash-message.warning { | |
| background-color: #fff3cd; /* Light yellow */ | |
| color: #664d03; /* Dark yellow */ | |
| border: 1px solid #ffecb5; | |
| } | |
| .flash-message.info { | |
| background-color: #cff4fc; /* Light blue */ | |
| color: #055160; /* Dark blue */ | |
| border: 1px solid #b6effb; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <header class="header"> | |
| <a href="{{ url_for('landing') }}"> | |
| <img src="{{ logo_url }}" alt="Mebel Hause KG Logo" class="header-logo"> | |
| </a> | |
| <nav> | |
| <a href="{{ url_for('landing') }}">Главная</a> | |
| <a href="{{ url_for('catalog') }}">Каталог</a> | |
| <a href="{{ url_for('admin') }}" class="active">Админ</a> | |
| </nav> | |
| </header> | |
| <div class="container admin-container"> | |
| <h1>Админ-панель</h1> | |
| {% if flash_message %} | |
| <div class="flash-message {{ flash_type }}"> | |
| {{ flash_message }} | |
| </div> | |
| {% endif %} | |
| <section class="admin-section form-section"> | |
| <h2>Добавить новый товар</h2> | |
| <form method="POST" enctype="multipart/form-data"> | |
| <input type="hidden" name="action" value="add"> | |
| <label for="add-name">Название товара:</label> | |
| <input type="text" id="add-name" name="name" required> | |
| <label for="add-price">Цена (сом):</label> | |
| <input type="number" id="add-price" name="price" step="0.01" min="0" required> | |
| <label for="add-description">Описание:</label> | |
| <textarea id="add-description" name="description" rows="4" required></textarea> | |
| <label for="add-category">Категория:</label> | |
| <select id="add-category" name="category"> | |
| <option value="Без категории">Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category }}">{{ category }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="add-photos">Фотографии (до 10 шт.):</label> | |
| <input type="file" id="add-photos" name="photos" accept="image/*" multiple> | |
| <label>Цвета:</label> | |
| <div id="add-color-inputs"> | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" placeholder="Например: Красный"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)" style="display: none;">×</button> | |
| </div> | |
| </div> | |
| <button type="button" class="button-link add-color-btn" onclick="addColorInput('add-color-inputs')">Добавить цвет</button> | |
| <button type="submit" class="form-button">Добавить товар</button> | |
| </form> | |
| </section> | |
| <section class="admin-section"> | |
| <h2>Управление категориями</h2> | |
| <div class="form-section"> | |
| <form method="POST"> | |
| <input type="hidden" name="action" value="add_category"> | |
| <label for="category-name">Название новой категории:</label> | |
| <input type="text" id="category-name" name="category_name" required> | |
| <button type="submit" class="form-button">Добавить категорию</button> | |
| </form> | |
| </div> | |
| <h3>Список категорий</h3> | |
| {% if categories %} | |
| <div class="category-list"> | |
| {% for category in categories %} | |
| <div class="category-item"> | |
| <h3>{{ category }}</h3> | |
| {% if category != 'Без категории' %} | |
| <form method="POST" style="display: inline;"> | |
| <input type="hidden" name="action" value="delete_category"> | |
| <input type="hidden" name="category_index" value="{{ loop.index0 }}"> | |
| <button type="submit" class="button-link delete-button" onclick="return confirm('Удалить категорию {{ category }}? Товары будут перемещены в категорию Без категории.');">Удалить</button> | |
| </form> | |
| {% else %} | |
| <p><i>(Системная категория, не удаляется)</i></p> | |
| {% endif %} | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>Категорий пока нет.</p> | |
| {% endif %} | |
| </section> | |
| <section class="admin-section"> | |
| <h2>Управление базой данных</h2> | |
| <div class="action-buttons"> | |
| <form method="POST" action="{{ url_for('backup') }}" style="display: inline;"> | |
| <button type="submit" class="button-link">Создать резервную копию на HF</button> | |
| </form> | |
| <form method="GET" action="{{ url_for('download') }}" style="display: inline;"> | |
| <button type="submit" class="button-link">Скачать базу данных (JSON)</button> | |
| </form> | |
| </div> | |
| </section> | |
| <section class="admin-section"> | |
| <h2>Список товаров</h2> | |
| {% if products %} | |
| <div class="product-list"> | |
| {% for product in products %} | |
| <div class="product-item"> | |
| <h3>{{ product['name'] }}</h3> | |
| <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> | |
| <p><strong>Цена:</strong> {{ product['price'] }} сом</p> | |
| <p><strong>Описание:</strong> {{ product['description'][:100] }}{% if product['description']|length > 100 %}...{% endif %}</p> | |
| <p><strong>Цвета:</strong> {{ product.get('colors', [])|join(', ') if product.get('colors') else 'Не указаны' }}</p> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <p><strong>Фотографии:</strong></p> | |
| <div class="product-photos-admin"> | |
| {% for photo in product['photos'] %} | |
| <a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}?download=true" target="_blank"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}?download=true" | |
| alt="{{ product['name'] }} - Фото {{ loop.index }}" loading="lazy"> | |
| </a> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p><strong>Фотографии:</strong> Нет</p> | |
| {% endif %} | |
| <details> | |
| <summary>Редактировать товар</summary> | |
| <form method="POST" enctype="multipart/form-data" class="edit-form"> | |
| <input type="hidden" name="action" value="edit"> | |
| <input type="hidden" name="index" value="{{ loop.index0 }}"> | |
| <label for="edit-name-{{ loop.index0 }}">Название:</label> | |
| <input type="text" id="edit-name-{{ loop.index0 }}" name="name" value="{{ product['name'] }}" required> | |
| <label for="edit-price-{{ loop.index0 }}">Цена:</label> | |
| <input type="number" id="edit-price-{{ loop.index0 }}" name="price" step="0.01" min="0" value="{{ product['price'] }}" required> | |
| <label for="edit-description-{{ loop.index0 }}">Описание:</label> | |
| <textarea id="edit-description-{{ loop.index0 }}" name="description" rows="4" required>{{ product['description'] }}</textarea> | |
| <label for="edit-category-{{ loop.index0 }}">Категория:</label> | |
| <select id="edit-category-{{ loop.index0 }}" name="category"> | |
| <option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option> | |
| {% for cat in categories %} | |
| <option value="{{ cat }}" {% if product.get('category') == cat %}selected{% endif %}>{{ cat }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="edit-photos-{{ loop.index0 }}">Заменить фотографии (до 10, старые будут удалены при загрузке новых):</label> | |
| <input type="file" id="edit-photos-{{ loop.index0 }}" name="photos" accept="image/*" multiple> | |
| <label>Цвета:</label> | |
| <div id="edit-color-inputs-{{ loop.index0 }}"> | |
| {% if product.get('colors') %} | |
| {% for color in product.get('colors', []) %} | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" value="{{ color }}"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)">×</button> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" placeholder="Например: Синий"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)" style="display:none;">×</button> | |
| </div> | |
| {% endif %} | |
| {% if not product.get('colors') %} {# Ensure at least one input exists even if no colors are set #} | |
| <div class="color-input-group" style="display:none;"> {# Hidden template if no colors initially #} | |
| <input type="text" name="colors" placeholder="Например: Синий"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)">×</button> | |
| </div> | |
| {% endif %} | |
| </div> | |
| <button type="button" class="button-link add-color-btn" onclick="addColorInput('edit-color-inputs-{{ loop.index0 }}')">Добавить цвет</button> | |
| <button type="submit" class="form-button">Сохранить изменения</button> | |
| </form> | |
| </details> | |
| <div class="action-buttons"> | |
| <form method="POST" onsubmit="return confirm('Вы уверены, что хотите удалить товар {{ product['name'] }}?');"> | |
| <input type="hidden" name="action" value="delete"> | |
| <input type="hidden" name="index" value="{{ loop.index0 }}"> | |
| <button type="submit" class="button-link delete-button">Удалить товар</button> | |
| </form> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>В базе данных пока нет товаров.</p> | |
| {% endif %} | |
| </section> | |
| </div> | |
| <footer class="footer"> | |
| <p>© {{ current_year }} Mebel Hause KG. Админ-панель.</p> | |
| </footer> | |
| <script> | |
| function addColorInput(containerId) { | |
| const container = document.getElementById(containerId); | |
| if (!container) return; | |
| // Find a template or the last input group to clone | |
| const templateGroup = container.querySelector('.color-input-group:last-child'); | |
| const newGroup = templateGroup ? templateGroup.cloneNode(true) : document.createElement('div'); | |
| newGroup.className = 'color-input-group'; // Ensure class name | |
| if (!templateGroup) { // If container was empty, create structure | |
| newGroup.innerHTML = '<input type="text" name="colors" placeholder="Например: Цвет"><button type="button" class="remove-color-btn" onclick="removeColorInput(this)">×</button>'; | |
| } else { | |
| const input = newGroup.querySelector('input[name="colors"]'); | |
| if (input) input.value = ''; // Clear the value | |
| const removeBtn = newGroup.querySelector('.remove-color-btn'); | |
| if (removeBtn) removeBtn.style.display = 'inline-block'; // Ensure remove button is visible | |
| } | |
| newGroup.style.display = 'flex'; // Ensure the new group is visible | |
| container.appendChild(newGroup); | |
| // Show remove button on previous last item if it was hidden | |
| const allGroups = container.querySelectorAll('.color-input-group'); | |
| if (allGroups.length > 1) { | |
| const secondLastGroup = allGroups[allGroups.length - 2]; | |
| const prevRemoveBtn = secondLastGroup.querySelector('.remove-color-btn'); | |
| if (prevRemoveBtn) prevRemoveBtn.style.display = 'inline-block'; | |
| } | |
| // Always hide remove button if only one input remains | |
| updateRemoveButtons(containerId); | |
| } | |
| function removeColorInput(button) { | |
| const container = button.closest('[id^="color-inputs"], [id^="edit-color-inputs"]'); | |
| const groupToRemove = button.closest('.color-input-group'); | |
| if (container && groupToRemove) { | |
| // Only remove if there's more than one group | |
| if (container.querySelectorAll('.color-input-group').length > 1) { | |
| groupToRemove.remove(); | |
| } else { | |
| // If it's the last one, just clear the input value | |
| const input = groupToRemove.querySelector('input[name="colors"]'); | |
| if (input) input.value = ''; | |
| alert("Должно быть хотя бы одно поле для цвета. Очищено."); | |
| } | |
| updateRemoveButtons(container.id); // Update visibility after removal | |
| } | |
| } | |
| function updateRemoveButtons(containerId) { | |
| const container = document.getElementById(containerId); | |
| if (!container) return; | |
| const allGroups = container.querySelectorAll('.color-input-group'); | |
| allGroups.forEach((group, index) => { | |
| const removeBtn = group.querySelector('.remove-color-btn'); | |
| if (removeBtn) { | |
| // Show remove button only if there is more than one group | |
| removeBtn.style.display = (allGroups.length > 1) ? 'inline-block' : 'none'; | |
| } | |
| }); | |
| } | |
| // Initial call to set up remove buttons correctly on page load for edit forms | |
| document.addEventListener('DOMContentLoaded', () => { | |
| const editColorContainers = document.querySelectorAll('[id^="edit-color-inputs-"]'); | |
| editColorContainers.forEach(container => { | |
| updateRemoveButtons(container.id); | |
| }); | |
| // Also for the add form | |
| updateRemoveButtons('add-color-inputs'); | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| return render_template_string( | |
| admin_html, | |
| products=products, | |
| categories=categories, | |
| repo_id=REPO_ID, | |
| logo_url=LOGO_URL, | |
| flash_message=flash_message, | |
| flash_type=flash_type, | |
| current_year=datetime.now().year | |
| ) | |
| def backup(): | |
| try: | |
| upload_db_to_hf() | |
| # Redirect back with success message | |
| return redirect(url_for('admin', msg="Резервное копирование на Hugging Face запущено.", type="success")) | |
| except Exception as e: | |
| logging.error(f"Ошибка при ручном резервном копировании: {e}") | |
| return redirect(url_for('admin', msg=f"Ошибка резервного копирования: {e}", type="error")) | |
| def download(): | |
| try: | |
| # Optionally trigger a download from HF first to ensure local is up-to-date | |
| # download_db_from_hf() # Uncomment if you want to force sync before download | |
| if os.path.exists(DATA_FILE): | |
| return send_file(DATA_FILE, as_attachment=True, download_name='mebelhause_database.json') | |
| else: | |
| return redirect(url_for('admin', msg="Локальный файл базы данных не найден.", type="error")) | |
| except Exception as e: | |
| logging.error(f"Ошибка при скачивании файла базы данных: {e}") | |
| return redirect(url_for('admin', msg=f"Ошибка скачивания файла: {e}", type="error")) | |
| if __name__ == '__main__': | |
| # Ensure data file exists on start, try loading/downloading | |
| try: | |
| initial_data = load_data() | |
| # If load_data created an empty structure due to errors, save it. | |
| if not os.path.exists(DATA_FILE) or os.path.getsize(DATA_FILE) == 0: | |
| save_data(initial_data) | |
| except Exception as e: | |
| logging.error(f"Критическая ошибка при инициализации базы данных: {e}") | |
| # Consider exiting if the DB is crucial and cannot be loaded/created | |
| # exit(1) | |
| # Start periodic backup in a separate thread | |
| if HF_TOKEN_WRITE and HF_TOKEN_READ: # Only run backup if tokens are set | |
| backup_thread = threading.Thread(target=periodic_backup, daemon=True) | |
| backup_thread.start() | |
| else: | |
| logging.warning("Токены Hugging Face (WRITE или READ) не установлены. Периодическое резервное копирование отключено.") | |
| # Run Flask App | |
| # Use 'waitress' for production instead of Flask's built-in server | |
| # from waitress import serve | |
| # serve(app, host='0.0.0.0', port=7860) | |
| # For development: | |
| app.run(debug=False, host='0.0.0.0', port=7860) # Set debug=False for production/waitress |