Spaces:
Paused
Paused
| from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify, session | |
| 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, HfHubHTTPError | |
| from werkzeug.utils import secure_filename | |
| from dotenv import load_dotenv | |
| import requests | |
| import uuid | |
| load_dotenv() | |
| app = Flask(__name__) | |
| app.secret_key = 'zhan_postel_secret_key' | |
| DATA_FILE = 'data.json' | |
| SYNC_FILES = [DATA_FILE] | |
| REPO_ID = "Kgshop/zhan" | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN") | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") | |
| STORE_ADDRESS = "ТЦ мизам, северное кольцо 78/1А, сектор А, ряд 2, бутик 34-35-36" | |
| CURRENCY_CODE = 'KZT' | |
| CURRENCY_NAME = 'Тенге' | |
| DOWNLOAD_RETRIES = 3 | |
| DOWNLOAD_DELAY = 5 | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| translations = { | |
| 'ru': { | |
| 'site_title': "Zhan Postel - Каталог", | |
| 'brand_name': "Zhan Postel", | |
| 'our_address': "Наш адрес:", | |
| 'all_categories': "Все категории", | |
| 'search_placeholder': "Поиск по названию...", | |
| 'no_products_added': "Товары пока не добавлены.", | |
| 'no_products_found': "По вашему запросу товары не найдены.", | |
| 'top_product': "Топ", | |
| 'price_per_piece': "Цена за шт.", | |
| 'details': "Подробнее", | |
| 'add_to_cart': "В корзину", | |
| 'loading': "Загрузка...", | |
| 'specify_quantity_size': "Укажите количество и размер", | |
| 'quantity': "Количество:", | |
| 'size_variant': "Размер:", | |
| 'confirm_add_to_cart': "Добавить в корзину", | |
| 'your_cart': "Ваша корзина", | |
| 'cart_is_empty': "Ваша корзина пуста.", | |
| 'total': "Итого:", | |
| 'clear_cart': "Очистить корзину", | |
| 'formulate_order': "Оформить заказ", | |
| 'open_cart': "Открыть корзину", | |
| 'close': "Закрыть", | |
| 'product_added_notification': "добавлен в корзину!", | |
| 'product_load_error': "Не удалось загрузить информацию о товаре.", | |
| 'enter_correct_quantity': "Пожалуйста, укажите корректное количество (больше 0).", | |
| 'product_add_error': "Ошибка добавления: товар не найден.", | |
| 'confirm_clear_cart': "Вы уверены, что хотите очистить корзину?", | |
| 'cart_empty_error': "Корзина пуста! Добавьте товары перед оформлением заказа.", | |
| 'formulating_order': "Оформляем заказ...", | |
| 'order_creation_error': "Ошибка при оформлении заказа:", | |
| 'category': "Категория:", | |
| 'no_category': "Без категории", | |
| 'price': "Цена:", | |
| 'description': "Описание:", | |
| 'no_description': "Описание отсутствует.", | |
| 'available_sizes': "Доступные размеры:", | |
| 'order_title': "Заказ №", | |
| 'your_order': "Ваш Заказ №", | |
| 'creation_date': "Дата создания:", | |
| 'products_in_order': "Товары в заказе", | |
| 'total_to_pay': "ИТОГО К ОПЛАТЕ:", | |
| 'order_status': "Статус заказа", | |
| 'order_status_desc': "Этот заказ был оформлен без входа в систему. Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.", | |
| 'send_order': "Отправить заказ", | |
| 'back_to_catalog': "← Вернуться в каталог", | |
| 'whatsapp_greeting': "Здравствуйте! Хочу подтвердить свой заказ на Zhan Postel:", | |
| 'whatsapp_order_number': "Номер заказа:", | |
| 'whatsapp_order_link': "Ссылка на заказ:", | |
| 'whatsapp_contact_me': "Пожалуйста, свяжитесь со мной для уточнения деталей оплаты и доставки.", | |
| 'error': "Ошибка", | |
| 'order_not_found': "Заказ с таким ID не найден.", | |
| 'your_favorites': 'Избранное', | |
| 'favorites_is_empty': 'В избранном пока ничего нет.', | |
| 'addresses': 'Адрес', | |
| 'whatsapp': 'WhatsApp', | |
| 'favorites': 'Избранное', | |
| 'employee': 'Сотрудник:', | |
| 'online_order': 'Онлайн', | |
| 'address_title': 'Адрес:', | |
| 'address_detail': 'ТЦ мизам, северное кольцо 78/1А, сектор А, ряд 2, бутик 34-35-36', | |
| }, | |
| 'kk': { | |
| 'site_title': "Zhan Postel - Каталог", | |
| 'brand_name': "Zhan Postel", | |
| 'our_address': "Біздің мекенжайымыз:", | |
| 'all_categories': "Барлық санаттар", | |
| 'search_placeholder': "Аты бойынша іздеу...", | |
| 'no_products_added': "Тауарлар әлі қосылмаған.", | |
| 'no_products_found': "Сіздің сұранысыңыз бойынша тауарлар табылмады.", | |
| 'top_product': "Топ", | |
| 'price_per_piece': "Дана бағасы", | |
| 'details': "Толығырақ", | |
| 'add_to_cart': "Себетке қосу", | |
| 'loading': "Жүктелуде...", | |
| 'specify_quantity_size': "Саны мен өлшемін көрсетіңіз", | |
| 'quantity': "Саны:", | |
| 'size_variant': "Өлшемі:", | |
| 'confirm_add_to_cart': "Себетке қосу", | |
| 'your_cart': "Сіздің себетіңіз", | |
| 'cart_is_empty': "Сіздің себетіңіз бос.", | |
| 'total': "Жиыны:", | |
| 'clear_cart': "Себетті тазалау", | |
| 'formulate_order': "Тапсырысты рәсімдеу", | |
| 'open_cart': "Себетті ашу", | |
| 'close': "Жабу", | |
| 'product_added_notification': "себетке қосылды!", | |
| 'product_load_error': "Тауар туралы ақпаратты жүктеу мүмкін болмады.", | |
| 'enter_correct_quantity': "Дұрыс санды көрсетіңіз (0-ден көп).", | |
| 'product_add_error': "Қосу қатесі: тауар табылмады.", | |
| 'confirm_clear_cart': "Себетті тазалағыңыз келетініне сенімдісіз бе?", | |
| 'cart_empty_error': "Себет бос! Тапсырысты рәсімдеу алдында тауарларды қосыңыз.", | |
| 'formulating_order': "Тапсырысты рәсімдеудеміз...", | |
| 'order_creation_error': "Тапсырысты рәсімдеу кезінде қате:", | |
| 'category': "Санат:", | |
| 'no_category': "Санатсыз", | |
| 'price': "Бағасы:", | |
| 'description': "Сипаттамасы:", | |
| 'no_description': "Сипаттамасы жоқ.", | |
| 'available_sizes': "Қолжетімді өлшемдер:", | |
| 'order_title': "Тапсырыс №", | |
| 'your_order': "Сіздің Тапсырысыңыз №", | |
| 'creation_date': "Құрылған күні:", | |
| 'products_in_order': "Тапсырыстағы тауарлар", | |
| 'total_to_pay': "ТӨЛЕУГЕ ЖИЫНЫ:", | |
| 'order_status': "Тапсырыс мәртебесі", | |
| 'order_status_desc': "Бұл тапсырыс жүйеге кірмей рәсімделді. Растау және мәліметтерді нақтылау үшін WhatsApp арқылы бізбен хабарласыңыз.", | |
| 'send_order': "Тапсырысты жіберу", | |
| 'back_to_catalog': "← Каталогқа оралу", | |
| 'whatsapp_greeting': "Сәлеметсіз бе! Мен Zhan Postel-дегі тапсырысымды растағым келеді:", | |
| 'whatsapp_order_number': "Тапсырыс нөмірі:", | |
| 'whatsapp_order_link': "Тапсырысқа сілтеме:", | |
| 'whatsapp_contact_me': "Төлем және жеткізу мәліметтерін нақтылау үшін менімен хабарласыңыз.", | |
| 'error': "Қате", | |
| 'order_not_found': "Бұл ID-мен тапсырыс табылмады.", | |
| 'your_favorites': 'Таңдаулылар', | |
| 'favorites_is_empty': 'Таңдаулыларда әзірше ештеңе жоқ.', | |
| 'addresses': 'Мекенжай', | |
| 'whatsapp': 'WhatsApp', | |
| 'favorites': 'Таңдаулылар', | |
| 'employee': 'Қызметкер:', | |
| 'online_order': 'Онлайн', | |
| 'address_title': 'Мекенжай:', | |
| 'address_detail': 'Мизам СО, солтүстік айналма 78/1А, А секторы, 2 қатар, 34-35-36 бутик', | |
| } | |
| } | |
| def get_locale(): | |
| return session.get('lang', 'ru') | |
| def _(key): | |
| lang = get_locale() | |
| return translations.get(lang, {}).get(key, key) | |
| def inject_helpers(): | |
| return dict(_=_, lang=get_locale(), translations=translations) | |
| def set_language(language): | |
| session['lang'] = language if language in translations else 'ru' | |
| return redirect(request.referrer or url_for('catalog')) | |
| def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY): | |
| if not HF_TOKEN_READ and not HF_TOKEN_WRITE: | |
| logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.") | |
| token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE | |
| files_to_download = [specific_file] if specific_file else SYNC_FILES | |
| logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...") | |
| all_successful = True | |
| for file_name in files_to_download: | |
| success = False | |
| for attempt in range(retries + 1): | |
| try: | |
| logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...") | |
| local_path = hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=file_name, | |
| repo_type="dataset", | |
| token=token_to_use, | |
| local_dir=".", | |
| local_dir_use_symlinks=False, | |
| force_download=True, | |
| resume_download=False | |
| ) | |
| logging.info(f"Successfully downloaded {file_name} to {local_path}.") | |
| success = True | |
| break | |
| except RepositoryNotFoundError: | |
| logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.") | |
| return False | |
| except HfHubHTTPError as e: | |
| if e.response.status_code == 404: | |
| logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.") | |
| if attempt == 0 and not os.path.exists(file_name): | |
| try: | |
| if file_name == DATA_FILE: | |
| with open(file_name, 'w', encoding='utf-8') as f: | |
| json.dump({'products': [], 'categories': [], 'orders': {}, 'employees': []}, f) | |
| logging.info(f"Created empty local file {file_name} because it was not found on HF.") | |
| except Exception as create_e: | |
| logging.error(f"Failed to create empty local file {file_name}: {create_e}") | |
| success = False | |
| break | |
| else: | |
| logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") | |
| except requests.exceptions.RequestException as e: | |
| logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") | |
| except Exception as e: | |
| logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True) | |
| if attempt < retries: | |
| time.sleep(delay) | |
| if not success: | |
| logging.error(f"Failed to download {file_name} after {retries + 1} attempts.") | |
| all_successful = False | |
| logging.info(f"Download process finished. Overall success: {all_successful}") | |
| return all_successful | |
| def upload_db_to_hf(specific_file=None): | |
| if not HF_TOKEN_WRITE: | |
| logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.") | |
| return | |
| try: | |
| api = HfApi() | |
| files_to_upload = [specific_file] if specific_file else SYNC_FILES | |
| logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...") | |
| for file_name in files_to_upload: | |
| if os.path.exists(file_name): | |
| try: | |
| api.upload_file( | |
| path_or_fileobj=file_name, | |
| path_in_repo=file_name, | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" | |
| ) | |
| logging.info(f"File {file_name} successfully uploaded to Hugging Face.") | |
| except Exception as e: | |
| logging.error(f"Error uploading file {file_name} to Hugging Face: {e}") | |
| else: | |
| logging.warning(f"File {file_name} not found locally, skipping upload.") | |
| logging.info("Finished uploading files to HF.") | |
| except Exception as e: | |
| logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True) | |
| def periodic_backup(): | |
| backup_interval = 1800 | |
| logging.info(f"Setting up periodic backup every {backup_interval} seconds.") | |
| while True: | |
| time.sleep(backup_interval) | |
| logging.info("Starting periodic backup...") | |
| upload_db_to_hf() | |
| logging.info("Periodic backup finished.") | |
| def load_data(): | |
| default_data = {'products': [], 'categories': [], 'orders': {}, 'employees': []} | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info(f"Local data loaded successfully from {DATA_FILE}") | |
| if not isinstance(data, dict): | |
| logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.") | |
| raise FileNotFoundError | |
| if 'products' not in data: data['products'] = [] | |
| if 'categories' not in data: data['categories'] = [] | |
| if 'orders' not in data: data['orders'] = {} | |
| if 'employees' not in data: data['employees'] = [] | |
| return data | |
| except FileNotFoundError: | |
| logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.") | |
| if download_db_from_hf(specific_file=DATA_FILE): | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info(f"Data loaded successfully from {DATA_FILE} after download.") | |
| if not isinstance(data, dict): | |
| logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.") | |
| return default_data | |
| if 'products' not in data: data['products'] = [] | |
| if 'categories' not in data: data['categories'] = [] | |
| if 'orders' not in data: data['orders'] = {} | |
| if 'employees' not in data: data['employees'] = [] | |
| return data | |
| except FileNotFoundError: | |
| logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.") | |
| return default_data | |
| except json.JSONDecodeError: | |
| logging.error(f"Error decoding JSON in downloaded {DATA_FILE}. Using default.") | |
| return default_data | |
| except Exception as e: | |
| logging.error(f"Unknown error loading downloaded {DATA_FILE}: {e}.", exc_info=True) | |
| return default_data | |
| else: | |
| logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.") | |
| if not os.path.exists(DATA_FILE): | |
| try: | |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: | |
| json.dump(default_data, f) | |
| logging.info(f"Created empty local file {DATA_FILE} after failed download.") | |
| except Exception as create_e: | |
| logging.error(f"Failed to create empty local file {DATA_FILE}: {create_e}") | |
| return default_data | |
| def save_data(data): | |
| try: | |
| if not isinstance(data, dict): | |
| logging.error("Attempted to save invalid data structure (not a dict). Aborting save.") | |
| return | |
| if 'products' not in data: data['products'] = [] | |
| if 'categories' not in data: data['categories'] = [] | |
| if 'orders' not in data: data['orders'] = {} | |
| if 'employees' not in data: data['employees'] = [] | |
| with open(DATA_FILE, 'w', encoding='utf-8') as file: | |
| json.dump(data, file, ensure_ascii=False, indent=4) | |
| logging.info(f"Data successfully saved to {DATA_FILE}") | |
| upload_db_to_hf(specific_file=DATA_FILE) | |
| except Exception as e: | |
| logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True) | |
| CATALOG_TEMPLATE = ''' | |
| <!DOCTYPE html> | |
| <html lang="{{ lang }}"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>{{ _('site_title') }}</title> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;700&display=swap" rel="stylesheet"> | |
| <style> | |
| :root { | |
| --bg-color: #0d0d0d; | |
| --surface-color: #1a1a1a; | |
| --primary-accent: #ffffff; | |
| --primary-accent-hover: #cccccc; | |
| --text-color: #f5f5f5; | |
| --text-muted: #888888; | |
| --border-color: #333333; | |
| } | |
| * { margin: 0; padding: 0; box-sizing: border-box; } | |
| body { font-family: 'Manrope', sans-serif; background: var(--bg-color); color: var(--text-color); line-height: 1.6; padding-bottom: 80px; -webkit-font-smoothing: antialiased; } | |
| .container { max-width: 1600px; margin: 0 auto; padding: 20px; } | |
| .header { display: flex; justify-content: space-between; align-items: center; padding: 20px 0; border-bottom: 1px solid var(--border-color); } | |
| .header h1 { font-size: 2rem; font-weight: 500; color: var(--text-color); letter-spacing: 2px; text-transform: uppercase; } | |
| .lang-switcher { display: flex; gap: 10px; } | |
| .lang-switcher a { color: var(--text-muted); text-decoration: none; font-weight: 500; padding: 5px 10px; border: 1px solid transparent; border-radius: 4px; transition: all 0.3s ease; } | |
| .lang-switcher a.active, .lang-switcher a:hover { color: var(--primary-accent); border-color: var(--primary-accent); } | |
| .store-address { padding: 15px; text-align: center; margin: 30px 0; border-top: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color); font-size: 1rem; color: var(--text-muted); } | |
| .filters-container { margin: 30px 0; display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; } | |
| .search-container { margin: 30px 0; text-align: center; } | |
| #search-input { width: 90%; max-width: 600px; padding: 14px 22px; font-size: 1rem; border: 1px solid var(--border-color); border-radius: 50px; outline: none; transition: all 0.3s ease; background-color: transparent; color: var(--text-color); } | |
| #search-input:focus { border-color: var(--primary-accent); } | |
| .category-filter { padding: 10px 25px; border: 1px solid var(--border-color); border-radius: 30px; background-color: transparent; cursor: pointer; transition: all 0.3s ease; font-size: 0.9rem; font-weight: 500; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; } | |
| .category-filter.active, .category-filter:hover { background-color: var(--primary-accent); color: var(--bg-color); border-color: var(--primary-accent); } | |
| .products-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 25px; } | |
| @media (min-width: 768px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); } } | |
| .product { background: var(--surface-color); border-radius: 8px; transition: transform 0.3s ease; overflow: hidden; display: flex; flex-direction: column; height: 100%; border: 1px solid var(--border-color); position: relative; } | |
| .product:hover { transform: translateY(-5px); } | |
| .product-clickable-area { cursor: pointer; flex-grow: 1; display: flex; flex-direction: column; } | |
| .product-image { width: 100%; aspect-ratio: 1 / 1.1; background-color: var(--bg-color); overflow: hidden; display: flex; justify-content: center; align-items: center; } | |
| .product-image img { width: 100%; height: 100%; object-fit: cover; transition: transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94); } | |
| .product:hover .product-image img { transform: scale(1.03); } | |
| .product-info { padding: 20px; flex-grow: 1; display: flex; flex-direction: column; text-align: left; } | |
| .product h2 { font-size: 1.2rem; font-weight: 500; margin: 0 0 8px 0; color: var(--text-color); } | |
| .product-price { font-size: 1.3rem; color: var(--text-color); font-weight: 500; margin-bottom: 10px; } | |
| .product-sizes { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; min-height: 24px; } | |
| .size-tag { font-size: 0.75rem; background-color: transparent; color: var(--text-muted); padding: 3px 10px; border-radius: 4px; border: 1px solid var(--border-color); } | |
| #cart-button { position: fixed; bottom: 90px; right: 30px; background-color: var(--primary-accent); color: var(--bg-color); border: none; border-radius: 50%; width: 60px; height: 60px; font-size: 1.6rem; cursor: pointer; display: none; align-items: center; justify-content: center; box-shadow: 0 5px 20px rgba(255, 255, 255, 0.1); transition: all 0.3s ease; z-index: 1000; } | |
| #cart-button:hover { transform: scale(1.1); } | |
| #cart-button span { position: absolute; top: -5px; right: -5px; background-color: var(--bg-color); color: var(--text-color); border: 1px solid var(--text-color); border-radius: 50%; padding: 3px 8px; font-size: 0.8rem; 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.8); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); overflow-y: auto; } | |
| .modal-content { background: var(--surface-color); margin: 3% auto; padding: 0; border-radius: 8px; width: 95%; max-width: 900px; box-shadow: 0 10px 40px rgba(0,0,0,0.5); animation: fadeIn 0.4s ease-out; position: relative; border: 1px solid var(--border-color); } | |
| @keyframes fadeIn { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } } | |
| .close { position: absolute; top: 15px; right: 20px; font-size: 2rem; color: var(--text-muted); cursor: pointer; transition: color 0.3s; line-height: 1; z-index: 10; } | |
| .close:hover { color: var(--text-color); } | |
| .modal-header { padding: 30px; border-bottom: 1px solid var(--border-color); } | |
| .modal-header h2 { margin: 0; color: var(--text-color); display: flex; align-items: center; gap: 12px; font-weight: 500; font-size: 1.5rem; } | |
| .modal-body { padding: 30px; } | |
| .cart-item { display: grid; grid-template-columns: 80px 1fr auto auto; gap: 20px; align-items: center; padding: 20px 0; border-bottom: 1px solid var(--border-color); } | |
| .cart-item:last-child { border-bottom: none; } | |
| .cart-item img { width: 80px; height: 80px; object-fit: cover; border-radius: 4px; background-color: var(--bg-color); } | |
| .cart-item-details strong { display: block; margin-bottom: 5px; font-size: 1.1rem; font-weight: 500; } | |
| .cart-item-price { font-size: 0.9rem; color: var(--text-muted); } | |
| .cart-item-total { font-weight: 500; text-align: right; font-size: 1.1rem; color: var(--text-color); } | |
| .cart-item-remove { background:none; border:none; color: var(--text-muted); cursor:pointer; font-size: 1.5rem; transition: color 0.3s; } | |
| .cart-item-remove:hover { color: var(--text-color); } | |
| .modal-footer { padding: 30px; border-top: 1px solid var(--border-color); } | |
| .form-group { margin-bottom: 15px; } | |
| .form-group label { display: block; font-size: 0.9rem; color: var(--text-muted); margin-bottom: 5px; } | |
| .form-control, .employee-select { width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 4px; font-size: 1rem; background-color: var(--bg-color); color: var(--text-color); } | |
| .cart-summary { margin-top: 25px; text-align: right; } | |
| .cart-summary strong { font-size: 1.4rem; color: var(--text-color); font-weight: 500; } | |
| .cart-actions { margin-top: 30px; display: flex; justify-content: space-between; gap: 15px; flex-wrap: wrap; } | |
| .product-button { display: block; width: 100%; padding: 14px; border: 1px solid var(--primary-accent); border-radius: 4px; background-color: var(--primary-accent); color: var(--bg-color); font-size: 1rem; font-weight: 700; cursor: pointer; transition: all 0.3s ease; text-align: center; text-decoration: none; } | |
| .product-button:hover { background-color: transparent; color: var(--primary-accent); } | |
| .cart-actions .product-button { width: auto; flex-grow: 1; } | |
| .clear-cart { background-color: transparent; color: var(--text-muted); border-color: var(--text-muted); } | |
| .clear-cart:hover { background-color: var(--text-muted); color: var(--bg-color); } | |
| .notification { position: fixed; bottom: 90px; left: 50%; transform: translateX(-50%); background-color: var(--primary-accent); color: var(--bg-color); padding: 12px 25px; border-radius: 4px; box-shadow: 0 5px 15px rgba(0,0,0,0.3); z-index: 1002; opacity: 0; transition: opacity 0.5s ease; font-size: 1rem; font-weight: 500;} | |
| .notification.show { opacity: 1;} | |
| .no-results-message { grid-column: 1 / -1; text-align: center; padding: 50px; font-size: 1.2rem; color: var(--text-muted); } | |
| .top-product-indicator { position: absolute; top: 15px; right: 15px; background-color: rgba(255, 255, 255, 0.9); color: var(--bg-color); padding: 4px 12px; font-size: 0.8rem; border-radius: 20px; font-weight: 700; z-index: 10; text-transform: uppercase; letter-spacing: 1px; } | |
| .favorite-button { position: absolute; top: 15px; left: 15px; background: none; border: none; color: var(--text-color); font-size: 1.5rem; cursor: pointer; z-index: 10; padding: 5px; line-height: 1; transition: color 0.3s, transform 0.3s; text-shadow: 0 0 5px rgba(0,0,0,0.8); } | |
| .favorite-button.favorited { color: #ffffff; transform: scale(1.1); } | |
| .favorite-button .fa-solid { display: none; } | |
| .favorite-button.favorited .fa-solid { display: inline; } | |
| .favorite-button.favorited .fa-regular { display: none; } | |
| .favorite-button:hover { transform: scale(1.2); } | |
| .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background-color: var(--surface-color); display: flex; justify-content: space-around; align-items: center; padding: 10px 0; z-index: 999; border-top: 1px solid var(--border-color); } | |
| .nav-button { background: none; border: none; color: var(--text-muted); cursor: pointer; text-align: center; font-size: 0.8rem; transition: color 0.3s; display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 5px 10px; text-decoration: none; text-transform: uppercase; letter-spacing: 0.5px; } | |
| .nav-button:hover, .nav-button.active { color: var(--primary-accent); } | |
| .nav-button i { font-size: 1.5rem; } | |
| .address-list p { margin-bottom: 10px; } | |
| .lightbox { display: none; position: fixed; z-index: 1003; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.9); justify-content: center; align-items: center; animation: fadeIn 0.3s; } | |
| .lightbox-content { max-width: 90%; max-height: 90%; object-fit: contain; } | |
| .lightbox-close { position: absolute; top: 20px; right: 35px; color: #fff; font-size: 40px; font-weight: bold; cursor: pointer; transition: color 0.3s; } | |
| .lightbox-close:hover { color: #ccc; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <h1>{{ _('brand_name') }}</h1> | |
| <div class="lang-switcher"> | |
| <a href="{{ url_for('set_language', language='ru') }}" class="{{ 'active' if lang == 'ru' }}">RU</a> | |
| <a href="{{ url_for('set_language', language='kk') }}" class="{{ 'active' if lang == 'kk' }}">KZ</a> | |
| </div> | |
| </div> | |
| <div class="store-address">{{ _('our_address') }} {{ store_address }}</div> | |
| <div class="filters-container"> | |
| <button class="category-filter active" data-category="all">{{ _('all_categories') }}</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="{{ _('search_placeholder') }}"> | |
| </div> | |
| <div class="products-grid" id="products-grid"> | |
| {% for product in products %} | |
| <div class="product" | |
| data-id="{{ product.id }}" | |
| data-name="{{ product['name']|lower }}" | |
| data-description="{{ product.get('description', '')|lower }}" | |
| data-category="{{ product.get('category', 'Без категории') }}"> | |
| <button class="favorite-button" onclick="toggleFavorite('{{ product.id }}', this)"> | |
| <i class="fa-regular fa-heart"></i><i class="fa-solid fa-heart"></i> | |
| </button> | |
| {% if product.get('is_top', False) %} | |
| <span class="top-product-indicator">{{ _('top_product') }}</span> | |
| {% endif %} | |
| <div class="product-clickable-area" onclick="openModalByIndex({{ loop.index0 }})"> | |
| <div class="product-image"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" | |
| alt="{{ product['name'] }}" | |
| loading="lazy"> | |
| {% else %} | |
| <img src="https://via.placeholder.com/400x400.png?text=No+Image" alt="No Image" loading="lazy"> | |
| {% endif %} | |
| </div> | |
| <div class="product-info"> | |
| <h2>{{ product['name'] }}</h2> | |
| <p class="product-price">{{ "%.0f"|format(product['price']) }} {{ currency_code }}</p> | |
| <div class="product-sizes"> | |
| {% set sizes = product.get('sizes', [])|select('ne', '')|list %} | |
| {% if sizes %} | |
| {% for size in sizes %} | |
| <span class="size-tag">{{ size }}</span> | |
| {% endfor %} | |
| {% endif %} | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% if not products %} | |
| <p class="no-results-message">{{ _('no_products_added') }}</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div id="productModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('productModal')" aria-label="{{ _('close') }}">×</span> | |
| <div id="modalContent">{{ _('loading') }}...</div> | |
| </div> | |
| </div> | |
| <div id="cartModal" class="modal"> | |
| <div class="modal-content"> | |
| <div class="modal-header"> | |
| <h2><i class="fas fa-shopping-cart"></i> {{ _('your_cart') }}</h2> | |
| </div> | |
| <div class="modal-body" id="cartContent"><p style="text-align: center; padding: 20px;">{{ _('cart_is_empty') }}</p></div> | |
| <div class="modal-footer"> | |
| <div class="form-group"> | |
| <label for="employeeSelect">{{ _('employee') }}</label> | |
| <select id="employeeSelect" class="employee-select"></select> | |
| </div> | |
| <div class="cart-summary"> | |
| <strong>{{ _('total') }} <span id="cartTotal">0.00</span> {{ currency_code }}</strong> | |
| </div> | |
| <div class="cart-actions"> | |
| <button class="product-button clear-cart" onclick="clearCart()"> | |
| <i class="fas fa-trash"></i> {{ _('clear_cart') }} | |
| </button> | |
| <button class="product-button formulate-order-button" onclick="formulateOrder()"> | |
| <i class="fas fa-file-alt"></i> {{ _('formulate_order') }} | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <div id="favoritesModal" class="modal"> | |
| <div class="modal-content"> | |
| <div class="modal-header"> | |
| <h2><i class="fas fa-heart"></i> {{ _('your_favorites') }}</h2> | |
| </div> | |
| <div class="modal-body" id="favoritesContent"><p style="text-align: center; padding: 20px;">{{ _('favorites_is_empty') }}</p></div> | |
| </div> | |
| </div> | |
| <div id="addressModal" class="modal"> | |
| <div class="modal-content"> | |
| <div class="modal-header"> | |
| <h2><i class="fas fa-map-marker-alt"></i> {{ _('addresses') }}</h2> | |
| </div> | |
| <div class="modal-body"> | |
| <div class="address-list"> | |
| <p><strong>{{ _('address_title') }}</strong> {{ _('address_detail') }}</p> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <button id="cart-button" onclick="openCartModal()" aria-label="{{ _('open_cart') }}"> | |
| <i class="fas fa-shopping-cart"></i> | |
| <span id="cart-count">0</span> | |
| </button> | |
| <div class="bottom-nav"> | |
| <a href="https://api.whatsapp.com/send?phone=+77477174564" target="_blank" class="nav-button"> | |
| <i class="fab fa-whatsapp"></i> | |
| <span>{{ _('whatsapp') }}</span> | |
| </a> | |
| <button class="nav-button" onclick="openModal('addressModal')"> | |
| <i class="fas fa-map-marker-alt"></i> | |
| <span>{{ _('addresses') }}</span> | |
| </button> | |
| <button class="nav-button" onclick="openFavoritesModal()"> | |
| <i class="fas fa-heart"></i> | |
| <span>{{ _('favorites') }}</span> | |
| </button> | |
| </div> | |
| <div id="notification-placeholder"></div> | |
| <div id="lightbox" class="lightbox" onclick="closeLightbox(event)"> | |
| <span class="lightbox-close" onclick="closeLightbox()">×</span> | |
| <img class="lightbox-content" id="lightbox-img"> | |
| </div> | |
| <script> | |
| const products = {{ products|tojson }}; | |
| const employees = {{ employees|tojson }}; | |
| const repoId = '{{ repo_id }}'; | |
| const currencyCode = '{{ currency_code }}'; | |
| const t = {{ translations[lang]|tojson|safe }}; | |
| let cart = JSON.parse(localStorage.getItem('zhanPostelCart') || '[]'); | |
| let favorites = JSON.parse(localStorage.getItem('zhanPostelFavorites') || '[]'); | |
| function openModal(modalId) { | |
| const modal = document.getElementById(modalId); | |
| if (modal) { | |
| modal.style.display = "block"; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| } | |
| function openModalByIndex(index) { | |
| loadProductDetails(index); | |
| openModal('productModal'); | |
| } | |
| function closeModal(modalId) { | |
| const modal = document.getElementById(modalId); | |
| if (modal) { | |
| modal.style.display = "none"; | |
| } | |
| const anyModalOpen = document.querySelector('.modal[style*="display: block"]'); | |
| if (!anyModalOpen) { | |
| document.body.style.overflow = 'auto'; | |
| } | |
| } | |
| function loadProductDetails(index) { | |
| const modalContent = document.getElementById('modalContent'); | |
| if (!modalContent) return; | |
| modalContent.innerHTML = `<p style="text-align:center; padding: 40px;">${t.loading}...</p>`; | |
| fetch(`/product/${index}?lang=${'{{lang}}'}`) | |
| .then(response => { | |
| if (!response.ok) throw new Error(`Error ${response.status}: ${response.statusText}`); | |
| return response.text(); | |
| }) | |
| .then(data => { | |
| modalContent.innerHTML = data; | |
| }) | |
| .catch(error => { | |
| console.error('Error loading product details:', error); | |
| modalContent.innerHTML = `<p style="color: red; text-align:center; padding: 40px;">${t.product_load_error} ${error.message}</p>`; | |
| }); | |
| } | |
| function updateMainPhoto(newSrc, thumbElement) { | |
| const mainPhoto = document.getElementById('main-product-photo'); | |
| if (mainPhoto) { | |
| mainPhoto.style.opacity = 0; | |
| setTimeout(() => { | |
| mainPhoto.src = newSrc; | |
| mainPhoto.style.opacity = 1; | |
| }, 200); | |
| } | |
| document.querySelectorAll('#thumbnail-grid .thumbnail').forEach(t => t.classList.remove('active')); | |
| thumbElement.classList.add('active'); | |
| } | |
| function openLightbox(src) { | |
| const lightbox = document.getElementById('lightbox'); | |
| if (lightbox) { | |
| document.getElementById('lightbox-img').src = src; | |
| lightbox.style.display = 'flex'; | |
| } | |
| } | |
| function closeLightbox(event) { | |
| const lightbox = document.getElementById('lightbox'); | |
| if (lightbox && (!event || event.target === lightbox || event.target.classList.contains('lightbox-close'))) { | |
| lightbox.style.display = 'none'; | |
| } | |
| } | |
| function addToCartFromDetail(productId) { | |
| const product = products.find(p => p.id === productId); | |
| if (!product) { | |
| alert(t.product_add_error); | |
| return; | |
| } | |
| const controlsContainer = document.getElementById('modalContent'); | |
| const quantityInput = controlsContainer.querySelector('.quantity-input'); | |
| const sizeSelect = controlsContainer.querySelector('.size-select'); | |
| const quantity = parseInt(quantityInput.value); | |
| const size = (sizeSelect && sizeSelect.value) ? sizeSelect.value : 'N/A'; | |
| if (isNaN(quantity) || quantity <= 0) { | |
| alert(t.enter_correct_quantity); | |
| quantityInput.focus(); | |
| return; | |
| } | |
| const cartItemId = `${product.id}-${size}`; | |
| const existingItemIndex = cart.findIndex(item => item.id === cartItemId); | |
| const photoForCart = (product.photos && product.photos.length > 0) ? product.photos[0] : null; | |
| if (existingItemIndex > -1) { | |
| cart[existingItemIndex].quantity += quantity; | |
| } else { | |
| cart.push({ | |
| id: cartItemId, productId: product.id, name: product.name, price: product.price, | |
| photo: photoForCart, quantity: quantity, size: size | |
| }); | |
| } | |
| localStorage.setItem('zhanPostelCart', JSON.stringify(cart)); | |
| updateCartButton(); | |
| showNotification(`${product.name} ${t.product_added_notification}`); | |
| } | |
| function updateCartButton() { | |
| const cartCountElement = document.getElementById('cart-count'); | |
| const cartButton = document.getElementById('cart-button'); | |
| if (!cartCountElement || !cartButton) return; | |
| const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0); | |
| if (totalItems > 0) { | |
| cartCountElement.textContent = totalItems; | |
| cartButton.style.display = 'flex'; | |
| } else { | |
| cartCountElement.textContent = '0'; | |
| cartButton.style.display = 'none'; | |
| } | |
| } | |
| function openCartModal() { | |
| const cartContent = document.getElementById('cartContent'); | |
| const cartTotalElement = document.getElementById('cartTotal'); | |
| if (!cartContent || !cartTotalElement) return; | |
| let total = 0; | |
| if (cart.length === 0) { | |
| cartContent.innerHTML = `<p style="text-align: center; padding: 20px;">${t.cart_is_empty}</p>`; | |
| cartTotalElement.textContent = '0.00'; | |
| } else { | |
| cartContent.innerHTML = cart.map(item => { | |
| const itemTotal = item.price * item.quantity; | |
| total += itemTotal; | |
| const photoUrl = item.photo | |
| ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` | |
| : 'https://via.placeholder.com/80x80.png?text=N/A'; | |
| const sizeText = item.size !== 'N/A' ? ` (${item.size})` : ''; | |
| return ` | |
| <div class="cart-item"> | |
| <img src="${photoUrl}" alt="${item.name}"> | |
| <div class="cart-item-details"> | |
| <strong>${item.name}${sizeText}</strong> | |
| <p class="cart-item-price">${item.quantity} × ${item.price.toFixed(0)} ${currencyCode}</p> | |
| </div> | |
| <span class="cart-item-total">${itemTotal.toFixed(0)} ${currencyCode}</span> | |
| <button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="Удалить товар">×</button> | |
| </div>`; | |
| }).join(''); | |
| cartTotalElement.textContent = total.toFixed(0); | |
| } | |
| const employeeSelect = document.getElementById('employeeSelect'); | |
| if (employeeSelect) { | |
| employeeSelect.innerHTML = `<option value="${t.online_order}">${t.online_order}</option>`; | |
| employees.forEach(emp => { | |
| const option = document.createElement('option'); | |
| option.value = emp; | |
| option.text = emp; | |
| employeeSelect.appendChild(option); | |
| }); | |
| } | |
| openModal('cartModal'); | |
| } | |
| function removeFromCart(itemId) { | |
| cart = cart.filter(item => item.id !== itemId); | |
| localStorage.setItem('zhanPostelCart', JSON.stringify(cart)); | |
| openCartModal(); | |
| updateCartButton(); | |
| } | |
| function clearCart() { | |
| if (confirm(t.confirm_clear_cart)) { | |
| cart = []; | |
| localStorage.removeItem('zhanPostelCart'); | |
| openCartModal(); | |
| updateCartButton(); | |
| } | |
| } | |
| function formulateOrder() { | |
| if (cart.length === 0) { | |
| alert(t.cart_empty_error); | |
| return; | |
| } | |
| const employee = document.getElementById('employeeSelect').value; | |
| const orderData = { cart: cart, employee: employee }; | |
| const formulateButton = document.querySelector('.formulate-order-button'); | |
| if (formulateButton) formulateButton.disabled = true; | |
| showNotification(t.formulating_order, 5000); | |
| fetch('/create_order', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify(orderData) | |
| }) | |
| .then(response => { | |
| if (!response.ok) { | |
| return response.json().then(err => { throw new Error(err.error || 'Failed to create order'); }); | |
| } | |
| return response.json(); | |
| }) | |
| .then(data => { | |
| if (data.order_id) { | |
| localStorage.removeItem('zhanPostelCart'); | |
| cart = []; | |
| updateCartButton(); | |
| closeModal('cartModal'); | |
| window.location.href = `/order/${data.order_id}`; | |
| } else { | |
| throw new Error('Order ID not received from server.'); | |
| } | |
| }) | |
| .catch(error => { | |
| console.error('Order formulation error:', error); | |
| alert(`${t.order_creation_error} ${error.message}`); | |
| if (formulateButton) formulateButton.disabled = false; | |
| }); | |
| } | |
| function filterProducts() { | |
| const searchTerm = document.getElementById('search-input').value.toLowerCase().trim(); | |
| const activeCategoryButton = document.querySelector('.category-filter.active'); | |
| const activeCategory = activeCategoryButton ? activeCategoryButton.dataset.category : 'all'; | |
| const grid = document.getElementById('products-grid'); | |
| let visibleProducts = 0; | |
| const existingNoResults = grid.querySelector('.no-results-message'); | |
| if (existingNoResults) existingNoResults.remove(); | |
| document.querySelectorAll('.products-grid .product').forEach(productElement => { | |
| const name = productElement.getAttribute('data-name'); | |
| const description = productElement.getAttribute('data-description'); | |
| const category = productElement.getAttribute('data-category'); | |
| const matchesSearch = !searchTerm || name.includes(searchTerm) || description.includes(searchTerm); | |
| const matchesCategory = activeCategory === 'all' || category === activeCategory; | |
| if (matchesSearch && matchesCategory) { | |
| productElement.style.display = 'flex'; | |
| visibleProducts++; | |
| } else { | |
| productElement.style.display = 'none'; | |
| } | |
| }); | |
| if (visibleProducts === 0 && products.length > 0) { | |
| const p = document.createElement('p'); | |
| p.className = 'no-results-message'; | |
| p.textContent = t.no_products_found; | |
| grid.appendChild(p); | |
| } else if (products.length === 0 && !grid.querySelector('.no-results-message')) { | |
| const p = document.createElement('p'); | |
| p.className = 'no-results-message'; | |
| p.textContent = t.no_products_added; | |
| grid.appendChild(p); | |
| } | |
| } | |
| function setupFilters() { | |
| const searchInput = document.getElementById('search-input'); | |
| const categoryFilters = document.querySelectorAll('.category-filter'); | |
| if(searchInput) searchInput.addEventListener('input', filterProducts); | |
| categoryFilters.forEach(filter => { | |
| filter.addEventListener('click', function() { | |
| categoryFilters.forEach(f => f.classList.remove('active')); | |
| this.classList.add('active'); | |
| filterProducts(); | |
| }); | |
| }); | |
| filterProducts(); | |
| } | |
| function toggleFavorite(productId, buttonElement) { | |
| event.stopPropagation(); | |
| const index = favorites.indexOf(productId); | |
| if (index > -1) { | |
| favorites.splice(index, 1); | |
| buttonElement.classList.remove('favorited'); | |
| } else { | |
| favorites.push(productId); | |
| buttonElement.classList.add('favorited'); | |
| } | |
| localStorage.setItem('zhanPostelFavorites', JSON.stringify(favorites)); | |
| } | |
| function updateFavoriteIcons() { | |
| document.querySelectorAll('.favorite-button').forEach(button => { | |
| const productId = button.closest('.product').dataset.id; | |
| if (favorites.includes(productId)) { | |
| button.classList.add('favorited'); | |
| } else { | |
| button.classList.remove('favorited'); | |
| } | |
| }); | |
| } | |
| function openFavoriteProductDetail(productId) { | |
| const productIndex = products.findIndex(p => p.id === productId); | |
| if (productIndex > -1) { | |
| closeModal('favoritesModal'); | |
| setTimeout(() => { | |
| openModalByIndex(productIndex); | |
| }, 250); | |
| } | |
| } | |
| function openFavoritesModal() { | |
| const favoritesContent = document.getElementById('favoritesContent'); | |
| favoritesContent.innerHTML = ''; | |
| if (favorites.length === 0) { | |
| favoritesContent.innerHTML = `<p style="text-align: center; padding: 20px;">${t.favorites_is_empty}</p>`; | |
| } else { | |
| const favoriteProducts = products.filter(p => favorites.includes(p.id)); | |
| favoriteProducts.forEach(item => { | |
| const photoUrl = item.photos && item.photos.length > 0 | |
| ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photos[0]}` | |
| : 'https://via.placeholder.com/80x80.png?text=N/A'; | |
| const itemHtml = ` | |
| <div class="cart-item" onclick="openFavoriteProductDetail('${item.id}')" style="cursor: pointer;"> | |
| <img src="${photoUrl}" alt="${item.name}"> | |
| <div class="cart-item-details"> | |
| <strong>${item.name}</strong> | |
| <p class="cart-item-price">${item.price.toFixed(0)} ${currencyCode}</p> | |
| </div> | |
| <span class="cart-item-total"></span> | |
| <button class="cart-item-remove" onclick="removeFromFavorites('${item.id}', event)" title="Удалить из избранного">×</button> | |
| </div>`; | |
| favoritesContent.innerHTML += itemHtml; | |
| }); | |
| } | |
| openModal('favoritesModal'); | |
| } | |
| function removeFromFavorites(productId, event) { | |
| event.stopPropagation(); | |
| const index = favorites.indexOf(productId); | |
| if (index > -1) { | |
| favorites.splice(index, 1); | |
| localStorage.setItem('zhanPostelFavorites', JSON.stringify(favorites)); | |
| openFavoritesModal(); | |
| updateFavoriteIcons(); | |
| } | |
| } | |
| function showNotification(message, duration = 3000) { | |
| const placeholder = document.getElementById('notification-placeholder'); | |
| if (!placeholder) return; | |
| const notification = document.createElement('div'); | |
| notification.className = 'notification'; | |
| notification.textContent = message; | |
| placeholder.appendChild(notification); | |
| void notification.offsetWidth; | |
| notification.classList.add('show'); | |
| setTimeout(() => { | |
| notification.classList.remove('show'); | |
| notification.addEventListener('transitionend', () => notification.remove()); | |
| }, duration); | |
| } | |
| document.addEventListener('DOMContentLoaded', () => { | |
| updateCartButton(); | |
| setupFilters(); | |
| updateFavoriteIcons(); | |
| 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 => { | |
| closeModal(modal.id); | |
| }); | |
| const lightbox = document.getElementById('lightbox'); | |
| if (lightbox && lightbox.style.display !== 'none') { | |
| closeLightbox(); | |
| } | |
| } | |
| }); | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| PRODUCT_DETAIL_TEMPLATE = ''' | |
| <style> | |
| .product-detail-layout { display: grid; grid-template-columns: 1fr; gap: 20px; padding: 15px; } | |
| @media (min-width: 768px) { .product-detail-layout { grid-template-columns: 1fr 1fr; gap: 40px; padding: 30px; } } | |
| .photo-gallery { display: flex; flex-direction: column; gap: 10px; } | |
| .main-photo-container { width: 100%; aspect-ratio: 1 / 1; background-color: var(--bg-color); border-radius: 8px; overflow: hidden; cursor: zoom-in; position: relative; } | |
| .main-photo { width: 100%; height: 100%; object-fit: cover; transition: opacity 0.2s ease-in-out; } | |
| .thumbnail-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(60px, 1fr)); gap: 10px; } | |
| .thumbnail { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; border-radius: 4px; cursor: pointer; border: 2px solid transparent; transition: border-color 0.3s ease; } | |
| .thumbnail.active, .thumbnail:hover { border-color: var(--primary-accent); } | |
| .product-detail-info { display: flex; flex-direction: column; } | |
| .product-detail-info h2 { font-size: 2rem; font-weight: 500; margin-bottom: 10px; line-height: 1.2; } | |
| .product-detail-info .price { font-size: 1.8rem; font-weight: 500; margin-bottom: 20px; } | |
| .product-detail-info .description-block { margin-top: 15px; margin-bottom: 20px; } | |
| .product-detail-info p { margin-bottom: 10px; color: var(--text-muted); line-height: 1.7; } | |
| .product-detail-info strong { color: var(--text-color); font-weight: 500; } | |
| .controls-section { margin-top: auto; padding-top: 20px; border-top: 1px solid var(--border-color); } | |
| .control-group { margin-bottom: 15px; } | |
| .control-group label { display: block; font-size: 1rem; color: var(--text-muted); margin-bottom: 8px; font-weight: 400; } | |
| .control-group .form-control { width: 100%; padding: 14px; border: 1px solid var(--border-color); border-radius: 4px; font-size: 1rem; background-color: var(--bg-color); color: var(--text-color); -moz-appearance: textfield; } | |
| .control-group input[type=number]::-webkit-inner-spin-button, | |
| .control-group input[type=number]::-webkit-outer-spin-button { | |
| -webkit-appearance: none; | |
| margin: 0; | |
| } | |
| .detail-add-to-cart-btn { width: 100%; padding: 16px; font-size: 1.1rem; } | |
| </style> | |
| <div class="product-detail-layout"> | |
| {% set photos = product.get('photos', []) %} | |
| <div class="photo-gallery"> | |
| <div class="main-photo-container" onclick="openLightbox(this.querySelector('img').src)"> | |
| {% if photos %} | |
| <img id="main-product-photo" class="main-photo" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photos[0] }}" alt="{{ product.name }}"> | |
| {% else %} | |
| <img id="main-product-photo" class="main-photo" src="https://via.placeholder.com/600x600.png?text=No+Image" alt="No image available"> | |
| {% endif %} | |
| </div> | |
| {% if photos|length > 1 %} | |
| <div class="thumbnail-grid" id="thumbnail-grid"> | |
| {% for photo in photos %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" | |
| alt="Thumbnail {{ loop.index }}" | |
| class="thumbnail {{ 'active' if loop.first }}" | |
| onclick="updateMainPhoto('https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}', this)"> | |
| {% endfor %} | |
| </div> | |
| {% endif %} | |
| </div> | |
| <div class="product-detail-info"> | |
| <div> | |
| <h2>{{ product['name'] }}</h2> | |
| <p class="price">{{ "%.0f"|format(product['price']) }} {{ currency_code }}</p> | |
| <p><strong>{{ _('category') }}:</strong> {{ product.get('category', _('no_category')) }}</p> | |
| {% set sizes = product.get('sizes', [])|select('ne', '')|list %} | |
| {% if sizes %} | |
| <p><strong>{{ _('available_sizes') }}:</strong> {{ sizes|join(', ') }}</p> | |
| {% endif %} | |
| <div class="description-block"> | |
| <p><strong>{{ _('description') }}:</strong><br> | |
| {{ product.get('description', _('no_description'))|replace('\\n', '<br>')|safe }}</p> | |
| </div> | |
| </div> | |
| <div class="controls-section"> | |
| {% if sizes %} | |
| <div class="control-group"> | |
| <label for="size-select">{{ _('size_variant') }}</label> | |
| <select id="size-select" class="form-control size-select"> | |
| {% for size in sizes %} | |
| <option value="{{ size }}">{{ size }}</option> | |
| {% endfor %} | |
| </select> | |
| </div> | |
| {% endif %} | |
| <div class="control-group"> | |
| <label for="quantity-input">{{ _('quantity') }}</label> | |
| <input type="number" id="quantity-input" class="form-control quantity-input" value="1" min="1"> | |
| </div> | |
| <button class="product-button detail-add-to-cart-btn" onclick="addToCartFromDetail('{{ product.id }}')"> | |
| <i class="fas fa-cart-plus"></i> {{ _('add_to_cart') }} | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| ''' | |
| ORDER_TEMPLATE = ''' | |
| <!DOCTYPE html> | |
| <html lang="{{ lang }}"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>{{ _('order_title') }}{{ order.id }} - Zhan Postel</title> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;700&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <style> | |
| :root { | |
| --bg-color: #0d0d0d; | |
| --surface-color: #1a1a1a; | |
| --primary-accent: #ffffff; | |
| --primary-accent-hover: #cccccc; | |
| --text-color: #f5f5f5; | |
| --text-muted: #888888; | |
| --border-color: #333333; | |
| } | |
| body { font-family: 'Manrope', sans-serif; background: var(--bg-color); color: var(--text-color); padding: 20px; } | |
| .container { max-width: 800px; margin: 20px auto; padding: 40px; background: var(--surface-color); border-radius: 8px; border: 1px solid var(--border-color); } | |
| h1 { text-align: center; color: var(--text-color); margin-bottom: 25px; font-size: 2rem; font-weight: 500; } | |
| h2 { color: var(--text-color); margin-top: 30px; margin-bottom: 15px; font-size: 1.5rem; font-weight: 500; border-bottom: 1px solid var(--border-color); padding-bottom: 10px;} | |
| .order-meta { font-size: 0.9rem; color: var(--text-muted); margin-bottom: 25px; text-align: center; } | |
| .order-item { display: grid; grid-template-columns: 80px 1fr auto; gap: 20px; align-items: center; padding: 15px 0; border-bottom: 1px solid var(--border-color); } | |
| .order-item:last-child { border-bottom: none; } | |
| .order-item img { width: 80px; height: 80px; object-fit: cover; border-radius: 4px; background-color: var(--bg-color); } | |
| .item-details strong { display: block; margin-bottom: 5px; font-size: 1.1rem; color: var(--text-color); font-weight: 500;} | |
| .item-details span { font-size: 0.9rem; color: var(--text-muted); display: block;} | |
| .item-total { font-weight: 500; text-align: right; font-size: 1.1rem; color: var(--text-color);} | |
| .order-summary { margin-top: 30px; padding-top: 20px; border-top: 2px solid var(--border-color); text-align: right; } | |
| .order-summary p { margin-bottom: 10px; font-size: 1.2rem; } | |
| .order-summary strong { font-size: 1.5rem; color: var(--text-color); font-weight: 500;} | |
| .customer-info { margin-top: 30px; background-color: var(--bg-color); padding: 25px; border-radius: 8px; border: 1px solid var(--border-color);} | |
| .customer-info p { margin-bottom: 8px; font-size: 1rem; } | |
| .actions { margin-top: 35px; text-align: center; } | |
| .button { padding: 14px 30px; border: 1px solid var(--primary-accent); border-radius: 4px; background-color: var(--primary-accent); color: var(--bg-color); font-weight: 700; cursor: pointer; transition: all 0.3s ease; font-size: 1.1rem; display: inline-flex; align-items: center; gap: 10px; text-decoration: none; } | |
| .button:hover { background-color: transparent; color: var(--primary-accent); } | |
| .catalog-link { display: block; text-align: center; margin-top: 30px; color: var(--primary-accent); text-decoration: none; font-size: 1rem; } | |
| .catalog-link:hover { text-decoration: underline; } | |
| .not-found { text-align: center; color: #e57373; font-size: 1.2rem; padding: 40px 0;} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| {% if order %} | |
| <h1><i class="fas fa-receipt"></i> {{ _('your_order') }}{{ order.id }}</h1> | |
| <p class="order-meta">{{ _('creation_date') }}: {{ order.created_at }}</p> | |
| {% if order.employee %} | |
| <p class="order-meta">{{ _('employee') }} {{ order.employee }}</p> | |
| {% endif %} | |
| <h2><i class="fas fa-shopping-bag"></i> {{ _('products_in_order') }}</h2> | |
| <div id="orderItems"> | |
| {% for item in order.cart %} | |
| <div class="order-item"> | |
| <a href="{{ item.photo_url }}" target="_blank"><img src="{{ item.photo_url }}" alt="{{ item.name }}"></a> | |
| <div class="item-details"> | |
| <strong>{{ item.name }} {% if item.size != 'N/A' %}({{ item.size }}){% endif %}</strong> | |
| <span>{{ item.quantity }} × {{ "%.0f"|format(item.price) }} {{ currency_code }}</span> | |
| </div> | |
| <div class="item-total"> | |
| {{ "%.0f"|format(item.price * item.quantity) }} {{ currency_code }} | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| <div class="order-summary"> | |
| <p><strong>{{ _('total_to_pay') }}: {{ "%.0f"|format(order.total_price) }} {{ currency_code }}</strong></p> | |
| </div> | |
| <div class="customer-info"> | |
| <h2><i class="fas fa-info-circle"></i> {{ _('order_status') }}</h2> | |
| <p>{{ _('order_status_desc') }}</p> | |
| </div> | |
| <div class="actions"> | |
| <button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> {{ _('send_order') }}</button> | |
| </div> | |
| <a href="{{ url_for('catalog') }}" class="catalog-link">{{ _('back_to_catalog') }}</a> | |
| <script> | |
| function sendOrderViaWhatsApp() { | |
| const orderId = '{{ order.id }}'; | |
| const orderUrl = `{{ request.url }}`; | |
| const whatsappNumber = "+77477174564"; | |
| let message = `{{ _('whatsapp_greeting') }}%0A%0A`; | |
| message += `*{{ _('whatsapp_order_number') }}* ${orderId}%0A`; | |
| message += `*{{ _('whatsapp_order_link') }}* ${encodeURIComponent(orderUrl)}%0A%0A`; | |
| message += `{{ _('whatsapp_contact_me') }}`; | |
| const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${message}`; | |
| window.open(whatsappUrl, '_blank'); | |
| } | |
| </script> | |
| {% else %} | |
| <h1 style="color: #e57373;"><i class="fas fa-exclamation-triangle"></i> {{ _('error') }}</h1> | |
| <p class="not-found">{{ _('order_not_found') }}</p> | |
| <a href="{{ url_for('catalog') }}" class="catalog-link">{{ _('back_to_catalog') }}</a> | |
| {% endif %} | |
| </div> | |
| </body> | |
| </html> | |
| ''' | |
| ADMIN_TEMPLATE = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Админ-панель - Zhan Postel</title> | |
| <link href="https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;700&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: 'Manrope', sans-serif; background-color: #f0f2f5; color: #333; padding: 20px; line-height: 1.6; } | |
| .container { max-width: 1200px; margin: 0 auto; background-color: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.05); } | |
| .header { padding-bottom: 15px; margin-bottom: 25px; border-bottom: 1px solid #e5e7eb; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;} | |
| h1, h2, h3 { font-weight: 500; color: #111827; 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: #374151; margin-top: 20px; } | |
| .section { margin-bottom: 30px; padding: 20px; background-color: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; } | |
| form { margin-bottom: 20px; } | |
| label { font-weight: 500; margin-top: 10px; display: block; color: #4b5563; font-size: 0.9rem;} | |
| input[type="text"], input[type="number"], input[type="password"], input[type="tel"], textarea, select { width: 100%; padding: 10px 12px; margin-top: 5px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.95rem; box-sizing: border-box; transition: border-color 0.3s ease; background-color: #fff; } | |
| input:focus, textarea:focus, select:focus { border-color: #4f46e5; outline: none; box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.1); } | |
| textarea { min-height: 80px; resize: vertical; } | |
| input[type="file"] { padding: 8px; background-color: #f9fafb; cursor: pointer; border: 1px solid #d1d5db;} | |
| input[type="file"]::file-selector-button { padding: 5px 10px; border-radius: 4px; background-color: #e5e7eb; border: 1px solid #d1d5db; cursor: pointer; margin-right: 10px;} | |
| input[type="checkbox"] { margin-right: 5px; vertical-align: middle; } | |
| label.inline-label { display: inline-block; margin-top: 10px; font-weight: normal; } | |
| button, .button { padding: 10px 18px; border: none; border-radius: 6px; background-color: #4f46e5; 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: #4338ca; } | |
| button:active, .button:active { transform: scale(0.98); } | |
| button[type="submit"] { min-width: 120px; justify-content: center; } | |
| .delete-button { background-color: #ef4444; } | |
| .delete-button:hover { background-color: #dc2626; } | |
| .add-button { background-color: #4f46e5; } | |
| .add-button:hover { background-color: #4338ca; } | |
| .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 #e5e7eb; } | |
| .item p { margin: 5px 0; font-size: 0.9rem; color: #4b5563; } | |
| .item strong { color: #1f2937; } | |
| .item .description { font-size: 0.85rem; color: #6b7280; max-height: 60px; overflow: hidden; text-overflow: ellipsis; } | |
| .item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; } | |
| .edit-form-container { margin-top: 15px; padding: 20px; background: #f0f2f5; border: 1px dashed #d1d5db; border-radius: 6px; display: none; } | |
| details { background-color: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; margin-bottom: 20px; } | |
| details > summary { cursor: pointer; font-weight: 500; color: #111827; display: block; padding: 15px; 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: #4f46e5; } | |
| details[open] > summary::after { transform: translateY(-50%) rotate(180deg); } | |
| details[open] > summary { border-bottom: 1px solid #e5e7eb; } | |
| details .form-content { padding: 20px; } | |
| .size-input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; } | |
| .size-input-group input { flex-grow: 1; margin: 0; } | |
| .remove-size-btn { background-color: #ef4444; padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; } | |
| .remove-size-btn:hover { background-color: #dc2626; } | |
| .add-size-btn { background-color: #a5b4fc; color: #1e1b4b; } | |
| .add-size-btn:hover { background-color: #818cf8; } | |
| .photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #e5e7eb; object-fit: cover;} | |
| .sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; } | |
| .download-hf-button { background-color: #6b7280; } | |
| .download-hf-button:hover { background-color: #4b5563; } | |
| .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: #d1fae5; color: #065f46; border: 1px solid #a7f3d0;} | |
| .message.error { background-color: #fee2e2; color: #991b1b; border: 1px solid #fecaca;} | |
| .message.warning { background-color: #fef3c7; color: #92400e; border: 1px solid #fde68a; } | |
| .status-indicator { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; font-weight: 500; margin-left: 10px; vertical-align: middle; } | |
| .status-indicator.in-stock { background-color: #d1fae5; color: #047857; } | |
| .status-indicator.out-of-stock { background-color: #fee2e2; color: #b91c1c; } | |
| .status-indicator.top-product { background-color: #feefc7; color: #92400e; margin-left: 5px;} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <h1><i class="fas fa-tools"></i> Админ-панель Zhan Postel</h1> | |
| <a href="{{ url_for('catalog') }}" class="button" style="background-color: #16a34a;"><i class="fas fa-store"></i> Перейти в каталог</a> | |
| </div> | |
| {% with messages = get_flashed_messages(with_categories=true) %} | |
| {% if messages %} | |
| {% for category, message in messages %} | |
| <div class="message {{ category }}">{{ message }}</div> | |
| {% endfor %} | |
| {% endif %} | |
| {% endwith %} | |
| <div class="section"> | |
| <h2><i class="fas fa-sync-alt"></i> Синхронизация с Датацентром</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> Загрузить БД</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="Скачать файлы (перезапишет локальные)"><i class="fas fa-download"></i> Скачать БД</button> | |
| </form> | |
| </div> | |
| <p style="font-size: 0.85rem; color: #6b7280;">Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.</p> | |
| </div> | |
| <div class="flex-container"> | |
| <div class="flex-item"> | |
| <div class="section"> | |
| <h2><i class="fas fa-tags"></i> Управление категориями</h2> | |
| <details> | |
| <summary><i class="fas fa-plus-circle"></i> Добавить новую категорию</summary> | |
| <div class="form-content"> | |
| <form method="POST"> | |
| <input type="hidden" name="action" value="add_category"> | |
| <label for="add_category_name">Название новой категории:</label> | |
| <input type="text" id="add_category_name" name="category_name" required> | |
| <button type="submit" class="add-button"><i class="fas fa-plus"></i> Добавить</button> | |
| </form> | |
| </div> | |
| </details> | |
| <h3>Существующие категории:</h3> | |
| {% if categories %} | |
| <div class="item-list"> | |
| {% for category in categories %} | |
| <div class="item" style="display: flex; justify-content: space-between; align-items: center;"> | |
| <span>{{ category }}</span> | |
| <form method="POST" style="margin: 0;" onsubmit="return confirm('Вы уверены, что хотите удалить категорию \'{{ category }}\'? Товары этой категории будут помечены как \'Без категории\'.');"> | |
| <input type="hidden" name="action" value="delete_category"> | |
| <input type="hidden" name="category_name" value="{{ category }}"> | |
| <button type="submit" class="delete-button" style="padding: 5px 10px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>Категорий пока нет.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div class="flex-item"> | |
| <div class="section"> | |
| <h2><i class="fas fa-users"></i> Управление сотрудниками</h2> | |
| <details> | |
| <summary><i class="fas fa-user-plus"></i> Добавить нового сотрудника</summary> | |
| <div class="form-content"> | |
| <form method="POST"> | |
| <input type="hidden" name="action" value="add_employee"> | |
| <label for="add_employee_name">Имя сотрудника:</label> | |
| <input type="text" id="add_employee_name" name="employee_name" required> | |
| <button type="submit" class="add-button"><i class="fas fa-plus"></i> Добавить</button> | |
| </form> | |
| </div> | |
| </details> | |
| <h3>Список сотрудников:</h3> | |
| {% if employees %} | |
| <div class="item-list"> | |
| {% for employee in employees %} | |
| <div class="item" style="display: flex; justify-content: space-between; align-items: center;"> | |
| <span>{{ employee }}</span> | |
| <form method="POST" style="margin: 0;" onsubmit="return confirm('Вы уверены, что хотите удалить сотрудника \'{{ employee }}\'?');"> | |
| <input type="hidden" name="action" value="delete_employee"> | |
| <input type="hidden" name="employee_name" value="{{ employee }}"> | |
| <button type="submit" class="delete-button" style="padding: 5px 10px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>Сотрудников пока нет.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| </div> | |
| <div class="section"> | |
| <h2><i class="fas fa-box-open"></i> Управление товарами</h2> | |
| <div style="margin-bottom: 20px;"> | |
| <label for="admin-product-search" style="font-weight: 500;">Поиск по товарам:</label> | |
| <input type="text" id="admin-product-search" placeholder="Введите название товара для поиска..." onkeyup="filterAdminProducts()"> | |
| </div> | |
| <details> | |
| <summary><i class="fas fa-plus-circle"></i> Добавить новый товар</summary> | |
| <div class="form-content"> | |
| <form method="POST" enctype="multipart/form-data"> | |
| <input type="hidden" name="action" value="add_product"> | |
| <label for="add_name">Название товара *:</label> | |
| <input type="text" id="add_name" name="name" required> | |
| <label for="add_price">Цена за шт. ({{ currency_code }}) *:</label> | |
| <input type="number" id="add_price" name="price" step="1" min="0" required> | |
| <label for="add_description">Описание:</label> | |
| <textarea id="add_description" name="description" rows="4"></textarea> | |
| <label for="add_category">Категория:</label> | |
| <select id="add_category" name="category"> | |
| <option value="Без категории">Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category }}">{{ category }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="add_photos">Фотографии (до 10 шт.):</label> | |
| <input type="file" id="add_photos" name="photos" accept="image/*" multiple> | |
| <label>Размеры (оставьте пустым, если нет):</label> | |
| <div id="add-size-inputs"> | |
| <div class="size-input-group"> | |
| <input type="text" name="sizes" placeholder="Например: 1.5-спальный"> | |
| <button type="button" class="remove-size-btn" onclick="removeSizeInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| </div> | |
| <button type="button" class="button add-size-btn" style="margin-top: 5px;" onclick="addSizeInput('add-size-inputs')"><i class="fas fa-ruler-combined"></i> Добавить поле для размера</button> | |
| <br> | |
| <div style="margin-top: 15px;"> | |
| <input type="checkbox" id="add_in_stock" name="in_stock" checked> | |
| <label for="add_in_stock" class="inline-label">В наличии</label> | |
| </div> | |
| <div style="margin-top: 5px;"> | |
| <input type="checkbox" id="add_is_top" name="is_top"> | |
| <label for="add_is_top" class="inline-label">Топ товар (показывать наверху)</label> | |
| </div> | |
| <br> | |
| <button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Добавить товар</button> | |
| </form> | |
| </div> | |
| </details> | |
| <h3>Список товаров:</h3> | |
| {% if products %} | |
| <div class="item-list" id="admin-product-list"> | |
| {% for product in products %} | |
| <div class="item" data-product-name="{{ product.name|lower }}"> | |
| <div style="display: flex; gap: 15px; align-items: flex-start;"> | |
| <div class="photo-preview" style="flex-shrink: 0;"> | |
| {% if product.get('photos') %} | |
| <a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" target="_blank" title="Посмотреть первое фото"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" alt="Фото"> | |
| </a> | |
| {% else %} | |
| <img src="https://via.placeholder.com/70x70.png?text=N/A" alt="Нет фото"> | |
| {% endif %} | |
| </div> | |
| <div style="flex-grow: 1;"> | |
| <h3 style="margin-top: 0; margin-bottom: 5px; color: #1f2937;"> | |
| {{ product['name'] }} | |
| {% if product.get('in_stock', True) %} | |
| <span class="status-indicator in-stock">В наличии</span> | |
| {% else %} | |
| <span class="status-indicator out-of-stock">Нет в наличии</span> | |
| {% endif %} | |
| {% if product.get('is_top', False) %} | |
| <span class="status-indicator top-product"><i class="fas fa-star"></i> Топ</span> | |
| {% endif %} | |
| </h3> | |
| <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> | |
| <p><strong>Цена за шт.:</strong> {{ "%.0f"|format(product['price']) }} {{ currency_code }}</p> | |
| <p class="description" title="{{ product.get('description', '') }}"><strong>Описание:</strong> {{ product.get('description', 'N/A')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}</p> | |
| {% set sizes = product.get('sizes', []) %} | |
| <p><strong>Размеры:</strong> {{ sizes|select('ne', '')|join(', ') if sizes|select('ne', '')|list|length > 0 else 'Нет' }}</p> | |
| {% if product.get('photos') and product['photos']|length > 1 %} | |
| <p style="font-size: 0.8rem; color: #6b7280;">(Всего фото: {{ product['photos']|length }})</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div class="item-actions"> | |
| <button type="button" class="button" onclick="toggleEditForm('edit-form-{{ product.id }}')"><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="product_id" value="{{ product.id }}"> | |
| <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button> | |
| </form> | |
| </div> | |
| <div id="edit-form-{{ product.id }}" class="edit-form-container"> | |
| <h4><i class="fas fa-edit"></i> Редактирование: {{ product['name'] }}</h4> | |
| <form method="POST" enctype="multipart/form-data"> | |
| <input type="hidden" name="action" value="edit_product"> | |
| <input type="hidden" name="product_id" value="{{ product.id }}"> | |
| <label>Название *:</label> | |
| <input type="text" name="name" value="{{ product['name'] }}" required> | |
| <label>Цена за шт. ({{ currency_code }}) *:</label> | |
| <input type="number" name="price" step="1" min="0" value="{{ product['price'] }}" required> | |
| <label>Описание:</label> | |
| <textarea name="description" rows="4">{{ product.get('description', '') }}</textarea> | |
| <label>Категория:</label> | |
| <select name="category"> | |
| <option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option> | |
| {% endfor %} | |
| </select> | |
| <label>Заменить фотографии (выберите новые файлы, до 10 шт.):</label> | |
| <input type="file" name="photos" accept="image/*" multiple> | |
| {% if product.get('photos') %} | |
| <p style="font-size: 0.85rem; margin-top: 5px;">Текущие фото:</p> | |
| <div class="photo-preview"> | |
| {% for photo in product['photos'] %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="Фото {{ loop.index }}"> | |
| {% endfor %} | |
| </div> | |
| {% endif %} | |
| <label>Размеры:</label> | |
| <div id="edit-size-inputs-{{ product.id }}"> | |
| {% set current_sizes = product.get('sizes', []) %} | |
| {% if current_sizes and current_sizes|select('ne', '')|list|length > 0 %} | |
| {% for size in current_sizes %} | |
| {% if size.strip() %} | |
| <div class="size-input-group"> | |
| <input type="text" name="sizes" value="{{ size }}"> | |
| <button type="button" class="remove-size-btn" onclick="removeSizeInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| {% endfor %} | |
| {% else %} | |
| <div class="size-input-group"> | |
| <input type="text" name="sizes" placeholder="Например: Евро"> | |
| <button type="button" class="remove-size-btn" onclick="removeSizeInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| </div> | |
| <button type="button" class="button add-size-btn" style="margin-top: 5px;" onclick="addSizeInput('edit-size-inputs-{{ product.id }}')"><i class="fas fa-ruler-combined"></i> Добавить поле для размера</button> | |
| <br> | |
| <div style="margin-top: 15px;"> | |
| <input type="checkbox" id="edit_in_stock_{{ product.id }}" name="in_stock" {% if product.get('in_stock', True) %}checked{% endif %}> | |
| <label for="edit_in_stock_{{ product.id }}" class="inline-label">В наличии</label> | |
| </div> | |
| <div style="margin-top: 5px;"> | |
| <input type="checkbox" id="edit_is_top_{{ product.id }}" name="is_top" {% if product.get('is_top', False) %}checked{% endif %}> | |
| <label for="edit_is_top_{{ product.id }}" class="inline-label">Топ товар</label> | |
| </div> | |
| <br> | |
| <button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Сохранить изменения</button> | |
| </form> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>Товаров пока нет.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <script> | |
| function toggleEditForm(formId) { | |
| const formContainer = document.getElementById(formId); | |
| if (formContainer) { | |
| formContainer.style.display = formContainer.style.display === 'none' || formContainer.style.display === '' ? 'block' : 'none'; | |
| } | |
| } | |
| function addSizeInput(containerId) { | |
| const container = document.getElementById(containerId); | |
| if (container) { | |
| const newInputGroup = document.createElement('div'); | |
| newInputGroup.className = 'size-input-group'; | |
| newInputGroup.innerHTML = ` | |
| <input type="text" name="sizes" placeholder="Новый размер"> | |
| <button type="button" class="remove-size-btn" onclick="removeSizeInput(this)"><i class="fas fa-times"></i></button> | |
| `; | |
| container.appendChild(newInputGroup); | |
| const newInput = newInputGroup.querySelector('input[name="sizes"]'); | |
| if (newInput) { newInput.focus(); } | |
| } | |
| } | |
| function removeSizeInput(button) { | |
| const group = button.closest('.size-input-group'); | |
| if (group) { | |
| const container = group.parentNode; | |
| group.remove(); | |
| if (container && container.children.length === 0) { | |
| const placeholderGroup = document.createElement('div'); | |
| placeholderGroup.className = 'size-input-group'; | |
| placeholderGroup.innerHTML = ` | |
| <input type="text" name="sizes" placeholder="Например: Семейный"> | |
| <button type="button" class="remove-size-btn" onclick="removeSizeInput(this)"><i class="fas fa-times"></i></button> | |
| `; | |
| container.appendChild(placeholderGroup); | |
| } | |
| } else { | |
| console.warn("Could not find parent .size-input-group for remove button"); | |
| } | |
| } | |
| function filterAdminProducts() { | |
| const searchTerm = document.getElementById('admin-product-search').value.toLowerCase().trim(); | |
| const productItems = document.querySelectorAll('#admin-product-list .item'); | |
| productItems.forEach(item => { | |
| const productName = item.getAttribute('data-product-name'); | |
| if (productName.includes(searchTerm)) { | |
| item.style.display = 'block'; | |
| } else { | |
| item.style.display = 'none'; | |
| } | |
| }); | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| def catalog(): | |
| data = load_data() | |
| all_products = data.get('products', []) | |
| categories = sorted(data.get('categories', [])) | |
| employees = sorted(data.get('employees', [])) | |
| needs_save = False | |
| for product in all_products: | |
| if 'id' not in product or not product['id']: | |
| product['id'] = str(uuid.uuid4()) | |
| needs_save = True | |
| if needs_save: | |
| data['products'] = all_products | |
| save_data(data) | |
| products_in_stock = [p for p in all_products if p.get('in_stock', True)] | |
| products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower())) | |
| return render_template_string( | |
| CATALOG_TEMPLATE, | |
| products=products_sorted, | |
| categories=categories, | |
| employees=employees, | |
| repo_id=REPO_ID, | |
| store_address=STORE_ADDRESS, | |
| currency_code=CURRENCY_CODE | |
| ) | |
| def product_detail(index): | |
| lang = request.args.get('lang', 'ru') | |
| session['lang'] = lang if lang in translations else 'ru' | |
| data = load_data() | |
| all_products = data.get('products', []) | |
| products_in_stock = [p for p in all_products if p.get('in_stock', True)] | |
| products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower())) | |
| try: | |
| product = products_sorted[index] | |
| except IndexError: | |
| logging.warning(f"Attempted access to non-existent or out-of-stock product with index {index}") | |
| return _("product_not_found"), 404 | |
| return render_template_string( | |
| PRODUCT_DETAIL_TEMPLATE, | |
| product=product, | |
| repo_id=REPO_ID, | |
| currency_code=CURRENCY_CODE | |
| ) | |
| def create_order(): | |
| order_data = request.get_json() | |
| if not order_data or 'cart' not in order_data or not order_data['cart']: | |
| logging.warning("Create order request missing cart data or cart is empty.") | |
| return jsonify({"error": "Корзина пуста или не передана."}), 400 | |
| cart_items = order_data['cart'] | |
| employee_name = order_data.get('employee', 'Онлайн') | |
| total_price = 0 | |
| processed_cart = [] | |
| for item in cart_items: | |
| if not all(k in item for k in ('name', 'price', 'quantity')): | |
| logging.error(f"Invalid cart item structure received: {item}") | |
| return jsonify({"error": "Неверный формат товара в корзине."}), 400 | |
| try: | |
| price = float(item['price']) | |
| quantity = int(item['quantity']) | |
| if price < 0 or quantity <= 0: | |
| raise ValueError("Invalid price or quantity") | |
| total_price += price * quantity | |
| processed_cart.append({ | |
| "name": item['name'], | |
| "price": price, | |
| "quantity": quantity, | |
| "size": item.get('size', 'N/A'), | |
| "photo": item.get('photo'), | |
| "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item['photo']}" if item.get('photo') else "https://via.placeholder.com/80x80.png?text=N/A" | |
| }) | |
| except (ValueError, TypeError) as e: | |
| logging.error(f"Invalid price/quantity in cart item: {item}. Error: {e}") | |
| return jsonify({"error": "Неверная цена или количество в товаре."}), 400 | |
| order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}" | |
| order_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
| new_order = { | |
| "id": order_id, | |
| "created_at": order_timestamp, | |
| "cart": processed_cart, | |
| "total_price": round(total_price, 2), | |
| "employee": employee_name, | |
| "status": "new" | |
| } | |
| try: | |
| data = load_data() | |
| if 'orders' not in data or not isinstance(data.get('orders'), dict): | |
| data['orders'] = {} | |
| data['orders'][order_id] = new_order | |
| save_data(data) | |
| logging.info(f"Order {order_id} created successfully by {employee_name}.") | |
| return jsonify({"order_id": order_id}), 201 | |
| except Exception as e: | |
| logging.error(f"Failed to save order {order_id}: {e}", exc_info=True) | |
| return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500 | |
| def view_order(order_id): | |
| data = load_data() | |
| order = data.get('orders', {}).get(order_id) | |
| if order: | |
| logging.info(f"Displaying order {order_id}") | |
| else: | |
| logging.warning(f"Order {order_id} not found.") | |
| return render_template_string(ORDER_TEMPLATE, | |
| order=order, | |
| repo_id=REPO_ID, | |
| currency_code=CURRENCY_CODE) | |
| def admin(): | |
| data = load_data() | |
| products = data.get('products', []) | |
| categories = data.get('categories', []) | |
| employees = data.get('employees', []) | |
| needs_save = False | |
| for product in products: | |
| if 'id' not in product: | |
| product['id'] = str(uuid.uuid4()) | |
| needs_save = True | |
| if needs_save: | |
| logging.info("Assigning unique IDs to products that were missing them.") | |
| data['products'] = products | |
| save_data(data) | |
| if request.method == 'POST': | |
| action = request.form.get('action') | |
| logging.info(f"Admin action received: {action}") | |
| try: | |
| if action == 'add_category': | |
| category_name = request.form.get('category_name', '').strip() | |
| if category_name and category_name not in categories: | |
| categories.append(category_name) | |
| data['categories'] = categories | |
| save_data(data) | |
| logging.info(f"Category '{category_name}' added.") | |
| flash(f"Категория '{category_name}' успешно добавлена.", 'success') | |
| elif not category_name: | |
| logging.warning("Attempted to add empty category.") | |
| flash("Название категории не может быть пустым.", 'error') | |
| else: | |
| logging.warning(f"Category '{category_name}' already exists.") | |
| flash(f"Категория '{category_name}' уже существует.", 'error') | |
| elif action == 'delete_category': | |
| category_to_delete = request.form.get('category_name') | |
| if category_to_delete and category_to_delete in categories: | |
| categories.remove(category_to_delete) | |
| updated_count = 0 | |
| for product in products: | |
| if product.get('category') == category_to_delete: | |
| product['category'] = 'Без категории' | |
| updated_count += 1 | |
| data['categories'] = categories | |
| data['products'] = products | |
| save_data(data) | |
| logging.info(f"Category '{category_to_delete}' deleted. Updated products: {updated_count}.") | |
| flash(f"Категория '{category_to_delete}' удалена. {updated_count} товаров обновлено.", 'success') | |
| else: | |
| logging.warning(f"Attempted to delete non-existent or empty category: {category_to_delete}") | |
| flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error') | |
| elif action == 'add_employee': | |
| employee_name = request.form.get('employee_name', '').strip() | |
| if employee_name and employee_name not in employees: | |
| employees.append(employee_name) | |
| data['employees'] = employees | |
| save_data(data) | |
| flash(f"Сотрудник '{employee_name}' успешно добавлен.", 'success') | |
| elif not employee_name: | |
| flash("Имя сотрудника не может быть пустым.", 'error') | |
| else: | |
| flash(f"Сотрудник '{employee_name}' уже существует.", 'error') | |
| elif action == 'delete_employee': | |
| employee_to_delete = request.form.get('employee_name') | |
| if employee_to_delete and employee_to_delete in employees: | |
| employees.remove(employee_to_delete) | |
| data['employees'] = employees | |
| save_data(data) | |
| flash(f"Сотрудник '{employee_to_delete}' удален.", 'success') | |
| else: | |
| flash(f"Не удалось удалить сотрудника '{employee_to_delete}'.", 'error') | |
| elif action == 'add_product': | |
| name = request.form.get('name', '').strip() | |
| price_str = request.form.get('price', '').replace(',', '.') | |
| description = request.form.get('description', '').strip() | |
| category = request.form.get('category') | |
| photos_files = request.files.getlist('photos') | |
| sizes = [s.strip() for s in request.form.getlist('sizes') if s.strip()] | |
| in_stock = 'in_stock' in request.form | |
| is_top = 'is_top' in request.form | |
| if not name or not price_str: | |
| flash("Название и цена обязательны.", 'error') | |
| return redirect(url_for('admin')) | |
| try: | |
| price = round(float(price_str)) | |
| if price < 0: | |
| raise ValueError | |
| except ValueError: | |
| flash("Неверный формат цены.", 'error') | |
| return redirect(url_for('admin')) | |
| photos_list = [] | |
| if photos_files and HF_TOKEN_WRITE: | |
| uploads_dir = 'uploads_temp' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| api = HfApi() | |
| photo_limit = 10 | |
| uploaded_count = 0 | |
| for photo in photos_files: | |
| if uploaded_count >= photo_limit: | |
| logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.") | |
| flash(f"Загружено только первые {photo_limit} фото.", "warning") | |
| break | |
| if photo and photo.filename: | |
| try: | |
| ext = os.path.splitext(photo.filename)[1].lower() | |
| if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']: | |
| logging.warning(f"Skipping non-image file upload: {photo.filename}") | |
| flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning") | |
| continue | |
| safe_name = secure_filename(name.replace(' ', '_'))[:50] | |
| photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}" | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| photo.save(temp_path) | |
| logging.info(f"Uploading photo {photo_filename} to HF for product {name}...") | |
| api.upload_file( | |
| path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}", | |
| repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, | |
| commit_message=f"Add photo for product {name}" | |
| ) | |
| photos_list.append(photo_filename) | |
| logging.info(f"Photo {photo_filename} uploaded successfully.") | |
| os.remove(temp_path) | |
| uploaded_count += 1 | |
| except Exception as e: | |
| logging.error(f"Error uploading photo {photo.filename} to HF: {e}", exc_info=True) | |
| flash(f"Ошибка при загрузке фото {photo.filename}.", 'error') | |
| if os.path.exists(temp_path): | |
| try: os.remove(temp_path) | |
| except OSError: pass | |
| elif photo and not photo.filename: | |
| logging.warning("Received an empty photo file object when adding product.") | |
| try: | |
| if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): | |
| os.rmdir(uploads_dir) | |
| except OSError as e: | |
| logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}") | |
| elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files): | |
| flash("HF_TOKEN (write) не настроен. Фотографии не были загружены.", "warning") | |
| new_product = { | |
| 'id': str(uuid.uuid4()), | |
| 'name': name, 'price': price, 'description': description, | |
| 'category': category if category in categories else 'Без категории', | |
| 'photos': photos_list, 'sizes': sizes, | |
| 'in_stock': in_stock, 'is_top': is_top | |
| } | |
| products.append(new_product) | |
| data['products'] = products | |
| save_data(data) | |
| logging.info(f"Product '{name}' added.") | |
| flash(f"Товар '{name}' успешно добавлен.", 'success') | |
| elif action == 'edit_product': | |
| product_id = request.form.get('product_id') | |
| if not product_id: | |
| flash("Ошибка редактирования: ID товара не передан.", 'error') | |
| return redirect(url_for('admin')) | |
| product_index = next((i for i, p in enumerate(products) if p.get('id') == product_id), -1) | |
| if product_index == -1: | |
| flash(f"Ошибка редактирования: товар с ID '{product_id}' не найден.", 'error') | |
| logging.error(f"Invalid product ID '{product_id}' for editing.") | |
| return redirect(url_for('admin')) | |
| product_to_edit = products[product_index] | |
| original_name = product_to_edit.get('name', 'N/A') | |
| 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.get('description', '')).strip() | |
| category = request.form.get('category') | |
| product_to_edit['category'] = category if category in categories else 'Без категории' | |
| product_to_edit['sizes'] = [s.strip() for s in request.form.getlist('sizes') if s.strip()] | |
| product_to_edit['in_stock'] = 'in_stock' in request.form | |
| product_to_edit['is_top'] = 'is_top' in request.form | |
| try: | |
| price = round(float(price_str)) | |
| if price < 0: raise ValueError | |
| product_to_edit['price'] = price | |
| except ValueError: | |
| logging.warning(f"Invalid price format during edit of product {original_name}. Not changed.") | |
| flash(f"Неверный формат цены для товара '{original_name}'. Не изменено.", 'warning') | |
| photos_files = request.files.getlist('photos') | |
| if photos_files and any(f.filename for f in photos_files) and HF_TOKEN_WRITE: | |
| uploads_dir = 'uploads_temp' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| api = HfApi() | |
| new_photos_list = [] | |
| photo_limit = 10 | |
| uploaded_count = 0 | |
| logging.info(f"Uploading new photos for product {product_to_edit['name']}...") | |
| for photo in photos_files: | |
| if uploaded_count >= photo_limit: | |
| break | |
| if photo and photo.filename: | |
| try: | |
| ext = os.path.splitext(photo.filename)[1].lower() | |
| if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']: continue | |
| safe_name = secure_filename(product_to_edit['name'].replace(' ', '_'))[:50] | |
| photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}" | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| photo.save(temp_path) | |
| api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}", | |
| repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, | |
| commit_message=f"Update photo for product {product_to_edit['name']}") | |
| new_photos_list.append(photo_filename) | |
| os.remove(temp_path) | |
| uploaded_count += 1 | |
| except Exception as e: | |
| logging.error(f"Error uploading new photo {photo.filename}: {e}", exc_info=True) | |
| if os.path.exists(temp_path): | |
| try: os.remove(temp_path) | |
| except OSError: pass | |
| try: | |
| if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): | |
| os.rmdir(uploads_dir) | |
| except OSError as e: | |
| logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}") | |
| if new_photos_list: | |
| old_photos = product_to_edit.get('photos', []) | |
| if old_photos: | |
| try: | |
| api.delete_files( | |
| repo_id=REPO_ID, paths_in_repo=[f"photos/{p}" for p in old_photos], | |
| repo_type="dataset", token=HF_TOKEN_WRITE, | |
| commit_message=f"Delete old photos for product {product_to_edit['name']}" | |
| ) | |
| except Exception as e: | |
| logging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True) | |
| product_to_edit['photos'] = new_photos_list | |
| flash("Фотографии товара успешно обновлены.", "success") | |
| products[product_index] = product_to_edit | |
| data['products'] = products | |
| save_data(data) | |
| logging.info(f"Product '{original_name}' (ID {product_id}) updated to '{product_to_edit['name']}'.") | |
| flash(f"Товар '{product_to_edit['name']}' успешно обновлен.", 'success') | |
| elif action == 'delete_product': | |
| product_id = request.form.get('product_id') | |
| product_to_delete = next((p for p in products if p.get('id') == product_id), None) | |
| if product_to_delete: | |
| product_name = product_to_delete.get('name', 'N/A') | |
| products.remove(product_to_delete) | |
| photos_to_delete = product_to_delete.get('photos', []) | |
| if photos_to_delete and HF_TOKEN_WRITE: | |
| try: | |
| api = HfApi() | |
| api.delete_files( | |
| repo_id=REPO_ID, paths_in_repo=[f"photos/{p}" for p in photos_to_delete], | |
| repo_type="dataset", token=HF_TOKEN_WRITE, | |
| commit_message=f"Delete photos for deleted product {product_name}" | |
| ) | |
| except Exception as e: | |
| logging.error(f"Error deleting photos {photos_to_delete} from HF: {e}", exc_info=True) | |
| data['products'] = products | |
| save_data(data) | |
| logging.info(f"Product '{product_name}' (ID {product_id}) deleted.") | |
| flash(f"Товар '{product_name}' удален.", 'success') | |
| else: | |
| flash(f"Ошибка удаления: неверный ID товара '{product_id}'.", 'error') | |
| else: | |
| flash(f"Неизвестное действие: {action}", 'warning') | |
| return redirect(url_for('admin')) | |
| except Exception as e: | |
| logging.error(f"Error processing admin action '{action}': {e}", exc_info=True) | |
| flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'.", 'error') | |
| return redirect(url_for('admin')) | |
| current_data = load_data() | |
| display_products = sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower()) | |
| display_categories = sorted(current_data.get('categories', [])) | |
| display_employees = sorted(current_data.get('employees', [])) | |
| return render_template_string( | |
| ADMIN_TEMPLATE, | |
| products=display_products, | |
| categories=display_categories, | |
| employees=display_employees, | |
| repo_id=REPO_ID, | |
| currency_code=CURRENCY_CODE | |
| ) | |
| def force_upload(): | |
| logging.info("Forcing upload to Hugging Face...") | |
| try: | |
| upload_db_to_hf() | |
| flash("Данные успешно загружены на Hugging Face.", 'success') | |
| except Exception as e: | |
| logging.error(f"Error during forced upload: {e}", exc_info=True) | |
| flash(f"Ошибка при загрузке на Hugging Face: {e}", 'error') | |
| return redirect(url_for('admin')) | |
| def force_download(): | |
| logging.info("Forcing download from Hugging Face...") | |
| try: | |
| if download_db_from_hf(): | |
| flash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success') | |
| load_data() | |
| else: | |
| flash("Не удалось скачать данные с Hugging Face после нескольких попыток.", 'error') | |
| except Exception as e: | |
| logging.error(f"Error during forced download: {e}", exc_info=True) | |
| flash(f"Ошибка при скачивании с Hugging Face: {e}", 'error') | |
| return redirect(url_for('admin')) | |
| if __name__ == '__main__': | |
| logging.info("Application starting up. Performing initial data load/download...") | |
| download_db_from_hf() | |
| load_data() | |
| logging.info("Initial data load complete.") | |
| if HF_TOKEN_WRITE: | |
| backup_thread = threading.Thread(target=periodic_backup, daemon=True) | |
| backup_thread.start() | |
| logging.info("Periodic backup thread started.") | |
| else: | |
| logging.warning("Periodic backup will NOT run (HF_TOKEN for writing not set).") | |
| port = int(os.environ.get('PORT', 7860)) | |
| logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}") | |
| app.run(debug=False, host='0.0.0.0', port=port) | |