Spaces:
Sleeping
Sleeping
| from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify, g | |
| 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 = 'your_unique_secret_key_soola_cosmetics_67890_no_login' | |
| DATA_FILE = 'data.json' | |
| SYNC_FILES = [DATA_FILE] | |
| REPO_ID = "Kgshop/esmiratkani" | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN") | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") | |
| STORE_ADDRESSES = [ | |
| "Город Алматы , Алатау 1 , блок 4 , бутик 112", | |
| ] | |
| CURRENCY_CODE = 'KZT' | |
| CURRENCY_NAME = 'Казахстанский тенге' | |
| DOWNLOAD_RETRIES = 3 | |
| DOWNLOAD_DELAY = 5 | |
| STATUS_MAPS = { | |
| 'ru': { | |
| "new": "Новый", | |
| "accepted": "Принят", | |
| "prepared": "Собран", | |
| "shipped": "Отправлен" | |
| }, | |
| 'kz': { | |
| "new": "Жаңа", | |
| "accepted": "Қабылданды", | |
| "prepared": "Жиналды", | |
| "shipped": "Жөнелтілді" | |
| } | |
| } | |
| translations = { | |
| 'ru': { | |
| 'page_title': "Esmira - ткани и одежда оптом и в розницу", | |
| 'header_title': "Esmira", | |
| 'our_addresses': "Наши адреса в г. Алматы", | |
| 'search_placeholder': "Поиск по названию или описанию...", | |
| 'all_filter': "Все", | |
| 'add_to_cart_button': "В корзину", | |
| 'from_price': "от", | |
| 'no_products_yet': "Товары пока не добавлены.", | |
| 'loading': "Загрузка...", | |
| 'product_load_error': "Не удалось загрузить информацию о товаре.", | |
| 'specify_details': "Укажите детали", | |
| 'variant_label': "Вариант:", | |
| 'size_label': "Размер:", | |
| 'quantity_label': "Количество:", | |
| 'quantity_label_meter': "Количество (метры):", | |
| 'confirm_add_to_cart': "Добавить в корзину", | |
| 'your_cart': "Ваша корзина", | |
| 'cart_is_empty': "Ваша корзина пуста.", | |
| 'total': "Итого:", | |
| 'clear_cart_button': "Очистить", | |
| 'formulate_order_button': "Оформить заказ", | |
| 'cart_item_variant': "Вариант", | |
| 'cart_item_size': "Размер", | |
| 'remove_item_title': "Удалить товар", | |
| 'clear_cart_confirm': "Вы уверены, что хотите очистить корзину?", | |
| 'cart_is_empty_alert': "Корзина пуста!", | |
| 'formulating_order': "Формируем заказ...", | |
| 'add_to_cart_notification': "добавлен в корзину!", | |
| 'no_products_found': "По вашему запросу товары не найдены.", | |
| 'category': "Категория", | |
| 'no_category': "Без категории", | |
| 'available_variants': "Доступные варианты:", | |
| 'available_sizes': "Доступные размеры:", | |
| 'description': "Описание:", | |
| 'no_description': "Описание отсутствует.", | |
| 'order_page_title': "Заказ №", | |
| 'order_created_at': "Дата создания:", | |
| 'order_items': "Товары в заказе", | |
| 'order_total_price': "Общая сумма товаров:", | |
| 'order_status_and_confirmation': "Статус и подтверждение", | |
| 'order_current_status': "Текущий статус:", | |
| 'order_whatsapp_prompt': "Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения заказа и уточнения деталей доставки и оплаты.", | |
| 'order_contact_us_button': "Связаться с нами", | |
| 'return_to_catalog': "Вернуться в каталог", | |
| 'order_not_found_error': "Ошибка", | |
| 'order_not_found_message': "Заказ с таким ID не найден.", | |
| 'whatsapp_confirm_message_1': "Здравствуйте! Хочу подтвердить свой заказ в Esmira:", | |
| 'whatsapp_confirm_message_2': "Номер заказа:", | |
| 'whatsapp_confirm_message_3': "Ссылка на заказ:", | |
| 'whatsapp_confirm_message_4': "Пожалуйста, свяжитесь со мной для уточнения деталей.", | |
| 'product_type': "Тип товара", | |
| 'tkaniny': "Ткани", | |
| 'odezhda': "Одежда", | |
| 'price_per_meter': "Цена за метр", | |
| }, | |
| 'kz': { | |
| 'page_title': "Esmira - маталар мен киімдер көтерме және бөлшек саудада", | |
| 'header_title': "Esmira", | |
| 'our_addresses': "Алматы қаласындағы мекенжайларымыз", | |
| 'search_placeholder': "Аты немесе сипаттамасы бойынша іздеу...", | |
| 'all_filter': "Барлығы", | |
| 'add_to_cart_button': "Себетке салу", | |
| 'from_price': "-ден бастап", | |
| 'no_products_yet': "Тауарлар әлі қосылмаған.", | |
| 'loading': "Жүктелуде...", | |
| 'product_load_error': "Тауар туралы ақпаратты жүктеу мүмкін болмады.", | |
| 'specify_details': "Мәліметтерді көрсетіңіз", | |
| 'variant_label': "Нұсқа:", | |
| 'size_label': "Өлшем:", | |
| 'quantity_label': "Саны:", | |
| 'quantity_label_meter': "Саны (метр):", | |
| 'confirm_add_to_cart': "Себетке қосу", | |
| 'your_cart': "Сіздің себетіңіз", | |
| 'cart_is_empty': "Сіздің себетіңіз бос.", | |
| 'total': "Жиыны:", | |
| 'clear_cart_button': "Тазарту", | |
| 'formulate_order_button': "Тапсырыс беру", | |
| 'cart_item_variant': "Нұсқа", | |
| 'cart_item_size': "Өлшем", | |
| 'remove_item_title': "Тауарды жою", | |
| 'clear_cart_confirm': "Себетті тазалағыңыз келетініне сенімдісіз бе?", | |
| 'cart_is_empty_alert': "Себет бос!", | |
| 'formulating_order': "Тапсырыс қалыптастырылуда...", | |
| 'add_to_cart_notification': "себетке қосылды!", | |
| 'no_products_found': "Сіздің сұранысыңыз бойынша тауарлар табылмады.", | |
| 'category': "Санат", | |
| 'no_category': "Санатсыз", | |
| 'available_variants': "Қолжетімді нұсқалар:", | |
| 'available_sizes': "Қолжетімді өлшемдер:", | |
| 'description': "Сипаттама:", | |
| 'no_description': "Сипаттама жоқ.", | |
| 'order_page_title': "Тапсырыс №", | |
| 'order_created_at': "Құрылған күні:", | |
| 'order_items': "Тапсырыстағы тауарлар", | |
| 'order_total_price': "Тауарлардың жалпы сомасы:", | |
| 'order_status_and_confirmation': "Мәртебесі және растау", | |
| 'order_current_status': "Ағымдағы мәртебе:", | |
| 'order_whatsapp_prompt': "Тапсырысты растау және жеткізу мен төлем туралы мәліметтерді нақтылау үшін WhatsApp арқылы бізбен хабарласыңыз.", | |
| 'order_contact_us_button': "Бізбен байланысу", | |
| 'return_to_catalog': "Каталогқа оралу", | |
| 'order_not_found_error': "Қате", | |
| 'order_not_found_message': "Мұндай ID-мен тапсырыс табылмады.", | |
| 'whatsapp_confirm_message_1': "Сәлеметсіз бе! Esmira-дағы тапсырысымды растағым келеді:", | |
| 'whatsapp_confirm_message_2': "Тапсырыс нөмірі:", | |
| 'whatsapp_confirm_message_3': "Тапсырысқа сілтеме:", | |
| 'whatsapp_confirm_message_4': "Мәліметтерді нақтылау үшін менімен хабарласуыңызды сұраймын.", | |
| 'product_type': "Тауар түрі", | |
| 'tkaniny': "Маталар", | |
| 'odezhda': "Киімдер", | |
| 'price_per_meter': "Метр бағасы", | |
| } | |
| } | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| 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': {}, 'settings': {'whatsapp_number': '+77073363943'}}, 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': {}, 'settings': {'whatsapp_number': '+77073363943'}} | |
| 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 'settings' not in data: data['settings'] = {'whatsapp_number': '+77073363943'} | |
| return data | |
| except FileNotFoundError: | |
| logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.") | |
| except json.JSONDecodeError: | |
| logging.error(f"Error decoding JSON in local {DATA_FILE}. File might be corrupt. Attempting download.") | |
| 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 'settings' not in data: data['settings'] = {'whatsapp_number': '+77073363943'} | |
| 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}. Using default.", 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 'settings' not in data: data['settings'] = {'whatsapp_number': '+77073363943'} | |
| 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_code }}"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>{{ _['page_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=Cormorant+Garamond:wght@400;600;700&family=Georgia&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css"> | |
| <style> | |
| :root { | |
| --primary-color: #9A2A47; | |
| --primary-dark: #7a2138; | |
| --surface-color: #313131; | |
| --background-color: #212121; | |
| --text-color: #F5F5F5; | |
| --text-color-muted: #BDBDBD; | |
| --border-color: #424242; | |
| --accent-color: #E0E0E0; | |
| } | |
| * { margin: 0; padding: 0; box-sizing: border-box; } | |
| body { | |
| font-family: 'Georgia', serif; | |
| background: var(--background-color); | |
| color: var(--text-color); | |
| line-height: 1.6; | |
| transition: background-color 0.3s; | |
| } | |
| .container { max-width: 100%; margin: 0 auto; padding: 0; } | |
| .content-area { padding: 20px; } | |
| .header { display: flex; justify-content: space-between; align-items: center; padding: 15px 20px; background: rgba(33, 33, 33, 0.8); backdrop-filter: blur(10px); border-bottom: 1px solid var(--border-color); position: sticky; top: 0; z-index: 1000; } | |
| .logo-title-container { display: flex; align-items: center; gap: 15px; } | |
| .logo-title-container img { height: 45px; width: auto; object-fit: contain; } | |
| .header h1 { font-family: 'Cormorant Garamond', serif; font-size: 1.8rem; font-weight: 700; color: var(--accent-color); } | |
| .lang-switcher { display: flex; gap: 5px; background-color: var(--surface-color); padding: 5px; border-radius: 50px; } | |
| .lang-switcher a { color: var(--text-color-muted); text-decoration: none; font-size: 0.9rem; padding: 5px 10px; border-radius: 50px; transition: all 0.3s; } | |
| .lang-switcher a.active { background-color: var(--primary-color); color: white; font-weight: bold; } | |
| .store-addresses { padding: 20px; text-align: center; background-color: var(--surface-color); border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.5); font-size: 0.95rem; color: var(--text-color-muted); margin: 20px; } | |
| .store-addresses h3 { font-family: 'Cormorant Garamond', serif; color: var(--primary-color); font-size: 1.3rem; margin-bottom: 10px; font-weight: 600; display: flex; align-items: center; justify-content: center; gap: 8px; } | |
| .store-addresses p { margin: 5px 0; } | |
| .search-container { padding: 0 20px 20px; } | |
| #search-input { width: 100%; padding: 12px 20px; font-size: 1rem; border: 1px solid var(--border-color); border-radius: 50px; outline: none; transition: all 0.3s; background-color: var(--surface-color); color: var(--text-color); } | |
| #search-input:focus { border-color: var(--primary-color); box-shadow: 0 0 0 4px rgba(154, 42, 71, 0.2); } | |
| .filters-wrapper { margin: 0 20px 20px; display: flex; flex-direction: column; gap: 15px; } | |
| .filters-container { display: flex; overflow-x: auto; gap: 10px; padding-bottom: 10px; scrollbar-width: none; -ms-overflow-style: none; } | |
| .filters-container::-webkit-scrollbar { display: none; } | |
| .filter-label { font-size: 0.9rem; color: var(--text-color-muted); margin-left: 5px; } | |
| .filter-btn { padding: 8px 18px; border: 1px solid var(--border-color); border-radius: 50px; background-color: transparent; cursor: pointer; transition: all 0.3s ease; font-size: 0.9rem; font-weight: 400; color: var(--text-color-muted); white-space: nowrap; } | |
| .filter-btn.active, .filter-btn:hover { background-color: var(--primary-color); color: #fff; border-color: var(--primary-color); font-weight: 500; box-shadow: 0 2px 8px rgba(154, 42, 71, 0.3); transform: translateY(-2px); } | |
| .products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; padding: 0 20px 120px; } | |
| @media (min-width: 600px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 20px; } } | |
| .product { background: var(--surface-color); border-radius: 16px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.4); transition: all 0.3s ease; overflow: hidden; display: flex; flex-direction: column; height: 100%; position: relative; border: 1px solid var(--border-color); } | |
| .product:hover { transform: translateY(-5px); box-shadow: 0 8px 25px rgba(154, 42, 71, 0.15); border-color: var(--primary-color); } | |
| .product-image { width: 100%; aspect-ratio: 1 / 1; background-color: #fff; display: flex; justify-content: center; align-items: center; padding: 10px; } | |
| .product-image img { max-width: 100%; max-height: 100%; object-fit: contain; transition: transform 0.3s ease; } | |
| .product:hover .product-image img { transform: scale(1.05); } | |
| .product-info { padding: 15px; flex-grow: 1; display: flex; flex-direction: column; text-align: center; } | |
| .product h2 { font-family: 'Cormorant Garamond', serif; font-size: 1.2rem; font-weight: 600; margin: 0 0 8px 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--accent-color); } | |
| .product-price { font-size: 1.2rem; color: var(--primary-color); font-weight: 700; margin: 5px 0; } | |
| .product-price .from-text { font-size: 0.8rem; color: var(--text-color-muted); font-weight: 400; } | |
| .product-description { display: none; } | |
| .product-actions { padding: 0 15px 15px; } | |
| .product-button { display: inline-flex; align-items: center; justify-content: center; width: 100%; padding: 10px; border: none; border-radius: 50px; background-color: var(--primary-color); color: #fff; font-size: 0.9rem; font-weight: 500; cursor: pointer; transition: all 0.3s ease; text-decoration: none; text-transform: uppercase; letter-spacing: 0.5px; } | |
| .product-button:hover { background-color: var(--primary-dark); box-shadow: 0 4px 10px rgba(154, 42, 71, 0.4); } | |
| .product-button i { margin-right: 8px; } | |
| .fab { position: fixed; background-color: var(--primary-color); color: #fff; border: none; border-radius: 50%; width: 55px; height: 55px; font-size: 1.5rem; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(154, 42, 71, 0.4); z-index: 1000; transition: transform 0.2s ease; } | |
| .fab:hover { transform: scale(1.1); } | |
| #cart-button { bottom: 20px; right: 20px; display: none; } | |
| #cart-button span { position: absolute; top: -2px; right: -2px; background-color: #dc3545; color: white; border-radius: 50%; padding: 3px 7px; font-size: 0.75rem; font-weight: bold; min-width: 22px; text-align: center; } | |
| .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.85); backdrop-filter: blur(8px); overflow-y: auto; } | |
| .modal-content { background: var(--surface-color); margin: 5% auto; padding: 25px; border-radius: 16px; width: 95%; max-width: 600px; box-shadow: 0 10px 40px rgba(0,0,0,0.7); animation: slideIn 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94); position: relative; border: 1px solid var(--border-color); } | |
| @keyframes slideIn { from { transform: translateY(-40px); opacity: 0; } to { transform: translateY(0); opacity: 1; } } | |
| .close { position: absolute; top: 15px; right: 20px; font-size: 2rem; color: var(--text-color-muted); cursor: pointer; transition: color 0.3s, transform 0.3s; line-height: 1; } | |
| .close:hover { color: var(--primary-color); transform: rotate(90deg); } | |
| .modal-content h2 { font-family: 'Cormorant Garamond', serif; margin-top: 0; margin-bottom: 25px; color: var(--primary-color); font-size: 1.8rem; display: flex; align-items: center; gap: 12px;} | |
| .cart-item { display: grid; grid-template-columns: 65px 1fr auto 25px; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid var(--border-color); } | |
| .cart-item:last-child { border-bottom: none; } | |
| .cart-item img { width: 65px; height: 65px; object-fit: contain; border-radius: 8px; background-color: #fff; padding: 5px; } | |
| .cart-item-details strong { display: block; margin-bottom: 4px; font-size: 1.05rem; } | |
| .cart-item-price { font-size: 0.9rem; color: var(--text-color-muted); } | |
| .cart-item-total { font-weight: bold; text-align: right; font-size: 1rem; color: var(--primary-color); } | |
| .cart-item-remove { background:none; border:none; color:#FF453A; cursor:pointer; font-size: 1.5rem; line-height: 1; transition: color 0.2s; } | |
| .cart-item-remove:hover { color: #ff0000; } | |
| .quantity-input, .variant-select, .size-select { width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 1rem; margin-top: 8px; margin-bottom: 20px; box-sizing: border-box; background-color: var(--background-color); color: var(--text-color); } | |
| .cart-summary { margin-top: 25px; text-align: right; border-top: 1px solid var(--border-color); padding-top: 20px; } | |
| .cart-summary strong { font-size: 1.4rem; color: var(--primary-color); } | |
| .cart-actions { margin-top: 25px; display: flex; justify-content: space-between; gap: 12px; } | |
| .cart-actions .product-button { flex-grow: 1; } | |
| .clear-cart { background: #444; color: var(--text-color); } | |
| .clear-cart:hover { background: #555; } | |
| .notification { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background-color: var(--primary-color); color: #fff; padding: 12px 25px; border-radius: 50px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); z-index: 1002; opacity: 0; transition: all 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94); font-size: 0.95rem; font-weight: 500; } | |
| .notification.show { opacity: 1; bottom: 90px; } | |
| .no-results-message { grid-column: 1 / -1; text-align: center; padding: 50px; font-size: 1.2rem; color: var(--text-color-muted); } | |
| #whatsapp-fab { bottom: 20px; left: 20px; background-color: #25D366; color: white; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <header class="header"> | |
| <div class="logo-title-container"> | |
| <img src="https://huggingface.co/spaces/esmira-tkani/admin/resolve/main/Screenshot_20251225-134859.png" alt="Esmira Logo"> | |
| <h1>{{ _['header_title'] }}</h1> | |
| </div> | |
| <div class="lang-switcher"> | |
| <a href="/ru{{ request.path.replace('/kz', '') }}" class="{{ 'active' if lang_code == 'ru' else '' }}">RU</a> | |
| <a href="/kz{{ request.path.replace('/ru', '') }}" class="{{ 'active' if lang_code == 'kz' else '' }}">KZ</a> | |
| </div> | |
| </header> | |
| <div class="store-addresses"> | |
| <h3><i class="fas fa-map-marker-alt"></i> {{ _['our_addresses'] }}</h3> | |
| {% for address in store_addresses %} | |
| <p>{{ address }}</p> | |
| {% endfor %} | |
| </div> | |
| <div class="search-container"> | |
| <input type="text" id="search-input" placeholder="{{ _['search_placeholder'] }}"> | |
| </div> | |
| <div class="filters-wrapper"> | |
| <div> | |
| <span class="filter-label">{{ _['product_type'] }}:</span> | |
| <div class="filters-container"> | |
| <button class="filter-btn type-filter active" data-type="all">{{ _['all_filter'] }}</button> | |
| <button class="filter-btn type-filter" data-type="tkaniny">{{ _['tkaniny'] }}</button> | |
| <button class="filter-btn type-filter" data-type="odezhda">{{ _['odezhda'] }}</button> | |
| </div> | |
| </div> | |
| <div> | |
| <span class="filter-label">{{ _['category'] }}:</span> | |
| <div class="filters-container"> | |
| <button class="filter-btn category-filter active" data-category="all">{{ _['all_filter'] }}</button> | |
| {% for category in categories %} | |
| <button class="filter-btn category-filter" data-category="{{ category }}">{{ category }}</button> | |
| {% endfor %} | |
| </div> | |
| </div> | |
| </div> | |
| <main class="products-grid" id="products-grid"> | |
| {% for product in products %} | |
| <div class="product" | |
| data-name="{{ product['name']|lower }}" | |
| data-description="{{ product.get('description', '')|lower }}" | |
| data-category="{{ product.get('category', _['no_category']) }}" | |
| data-type="{{ product.get('product_type', 'tkaniny') }}"> | |
| <div class="product-image" onclick="openModal({{ loop.index0 }})" style="cursor: pointer;"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" | |
| alt="{{ product['name'] }}" | |
| loading="lazy"> | |
| {% else %} | |
| <img src="https://via.placeholder.com/250x250.png?text=No+Image" alt="No Image" loading="lazy"> | |
| {% endif %} | |
| </div> | |
| <div class="product-info"> | |
| <h2>{{ product['name'] }}</h2> | |
| <div class="product-price"> | |
| {% if product.get('variants') and product.variants|length > 0 %} | |
| <span class="from-text">{{ _['from_price'] }}</span> {{ "%.2f"|format(product.variants|map(attribute='price')|min) }} {{ currency_code }} | |
| {% else %} | |
| - | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div class="product-actions"> | |
| <button class="product-button" onclick="openQuantityModal({{ loop.index0 }})"> | |
| <i class="fas fa-shopping-bag"></i> {{ _['add_to_cart_button'] }} | |
| </button> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% if not products %} | |
| <p class="no-results-message">{{ _['no_products_yet'] }}</p> | |
| {% endif %} | |
| </main> | |
| </div> | |
| <div id="productModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span> | |
| <div id="modalContent">{{ _['loading'] }}</div> | |
| </div> | |
| </div> | |
| <div id="quantityModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">×</span> | |
| <h2>{{ _['specify_details'] }}</h2> | |
| <div id="variant-section"> | |
| <label for="variantSelect">{{ _['variant_label'] }}</label> | |
| <select id="variantSelect" class="variant-select"></select> | |
| </div> | |
| <div id="size-section" style="display: none;"> | |
| <label for="sizeSelect">{{ _['size_label'] }}</label> | |
| <select id="sizeSelect" class="size-select"></select> | |
| </div> | |
| <label for="quantityInput" id="quantity-label">{{ _['quantity_label'] }}</label> | |
| <input type="number" id="quantityInput" class="quantity-input" min="1" value="1" step="1"> | |
| <button class="product-button" onclick="confirmAddToCart()"><i class="fas fa-check"></i> {{ _['confirm_add_to_cart'] }}</button> | |
| </div> | |
| </div> | |
| <div id="cartModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span> | |
| <h2><i class="fas fa-shopping-cart"></i> {{ _['your_cart'] }}</h2> | |
| <div id="cartContent"><p style="text-align: center; padding: 20px 0;">{{ _['cart_is_empty'] }}</p></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> | |
| <button class="product-button formulate-order-button" onclick="formulateOrder()"> | |
| <i class="fas fa-file-alt"></i> {{ _['formulate_order_button'] }} | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| <button id="cart-button" class="fab" onclick="openCartModal()" aria-label="Открыть корзину"> | |
| <i class="fas fa-shopping-cart"></i> | |
| <span id="cart-count">0</span> | |
| </button> | |
| <a href="https://api.whatsapp.com/send?phone={{ whatsapp_number }}" target="_blank" rel="noopener noreferrer" id="whatsapp-fab" class="fab"> | |
| <i class="fab fa-whatsapp"></i> | |
| </a> | |
| <div id="notification-placeholder"></div> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script> | |
| <script> | |
| const products = {{ products|tojson }}; | |
| const repoId = '{{ repo_id }}'; | |
| const currencyCode = '{{ currency_code }}'; | |
| let selectedProductIndex = null; | |
| let cart = JSON.parse(localStorage.getItem('esmiracart') || '[]'); | |
| const langCode = '{{ lang_code }}'; | |
| const translations = {{ _|tojson }}; | |
| function openModal(index) { | |
| loadProductDetails(index); | |
| document.getElementById('productModal').style.display = "block"; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| function closeModal(modalId) { | |
| document.getElementById(modalId).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'); | |
| modalContent.innerHTML = `<p style="text-align:center; padding: 40px;">${translations['loading']}</p>`; | |
| fetch(`/${langCode}/product/${index}`) | |
| .then(response => response.text()) | |
| .then(data => { | |
| modalContent.innerHTML = data; | |
| initializeSwiper(); | |
| }) | |
| .catch(error => { | |
| console.error('Ошибка загрузки деталей продукта:', error); | |
| modalContent.innerHTML = `<p style="color: red; text-align:center; padding: 40px;">${translations['product_load_error']}</p>`; | |
| }); | |
| } | |
| function initializeSwiper() { | |
| new Swiper('#productModal .swiper-container', { | |
| slidesPerView: 1, spaceBetween: 20, loop: true, grabCursor: true, | |
| pagination: { el: '.swiper-pagination', clickable: true, dynamicBullets: true }, | |
| navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, | |
| zoom: { maxRatio: 3, containerClass: 'swiper-zoom-container' }, | |
| autoplay: { delay: 4000, disableOnInteraction: true }, | |
| }); | |
| } | |
| function setupSelect(selectId, items, displayFunc) { | |
| const select = document.getElementById(selectId); | |
| select.innerHTML = ''; | |
| if (items && items.length > 0) { | |
| items.forEach((item, index) => { | |
| const option = document.createElement('option'); | |
| option.value = index; | |
| option.text = displayFunc(item); | |
| select.appendChild(option); | |
| }); | |
| select.parentElement.style.display = 'block'; | |
| } else { | |
| select.parentElement.style.display = 'none'; | |
| } | |
| } | |
| function openQuantityModal(index) { | |
| selectedProductIndex = index; | |
| const product = products[index]; | |
| if (!product) return; | |
| const quantityInput = document.getElementById('quantityInput'); | |
| const quantityLabel = document.getElementById('quantity-label'); | |
| setupSelect('variantSelect', product.variants, v => `${v.name} - ${v.price.toFixed(2)} ${currencyCode}`); | |
| if(product.product_type === 'odezhda') { | |
| setupSelect('sizeSelect', product.sizes, s => s.name); | |
| quantityInput.type = "number"; | |
| quantityInput.step = "1"; | |
| quantityInput.min = "1"; | |
| quantityInput.value = "1"; | |
| quantityLabel.textContent = translations['quantity_label']; | |
| } else { | |
| document.getElementById('size-section').style.display = 'none'; | |
| quantityInput.type = "number"; | |
| quantityInput.step = "0.1"; | |
| quantityInput.min = "0.1"; | |
| quantityInput.value = "1.0"; | |
| quantityLabel.textContent = translations['quantity_label_meter']; | |
| } | |
| document.getElementById('quantityModal').style.display = 'block'; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| function confirmAddToCart() { | |
| if (selectedProductIndex === null) return; | |
| const product = products[selectedProductIndex]; | |
| const quantity = parseFloat(document.getElementById('quantityInput').value); | |
| const variantIndex = document.getElementById('variantSelect').value; | |
| const sizeIndex = document.getElementById('sizeSelect').value; | |
| if (!product || !product.variants || product.variants.length === 0) { | |
| alert("Ошибка: Варианты для этого товара не найдены."); | |
| return; | |
| } | |
| const selectedVariant = product.variants[variantIndex]; | |
| let selectedSize = null; | |
| let cartItemId = `${product.id}-${selectedVariant.name}`; | |
| if (product.product_type === 'odezhda') { | |
| if (!product.sizes || product.sizes.length === 0) { | |
| alert("Ошибка: Размеры для этой одежды не найдены."); | |
| return; | |
| } | |
| selectedSize = product.sizes[sizeIndex]; | |
| cartItemId += `-${selectedSize.name}`; | |
| } | |
| if (isNaN(quantity) || quantity <= 0) { | |
| alert("Пожалуйста, укажите корректное количество."); | |
| return; | |
| } | |
| const existingItem = cart.find(item => item.id === cartItemId); | |
| if (existingItem) { | |
| existingItem.quantity += quantity; | |
| } else { | |
| cart.push({ | |
| id: cartItemId, | |
| productId: product.id, | |
| name: product.name, | |
| price: selectedVariant.price, | |
| variantName: selectedVariant.name, | |
| sizeName: selectedSize ? selectedSize.name : null, | |
| productType: product.product_type, | |
| photo: product.photos && product.photos.length > 0 ? product.photos[0] : null, | |
| quantity: quantity | |
| }); | |
| } | |
| localStorage.setItem('esmiracart', JSON.stringify(cart)); | |
| closeModal('quantityModal'); | |
| updateCartButton(); | |
| showNotification(`${product.name} ${translations['add_to_cart_notification']}`); | |
| } | |
| function updateCartButton() { | |
| const cartCountElement = document.getElementById('cart-count'); | |
| const cartButton = document.getElementById('cart-button'); | |
| const totalItems = cart.length; | |
| if (totalItems > 0) { | |
| cartCountElement.textContent = totalItems; | |
| cartButton.style.display = 'flex'; | |
| } else { | |
| cartButton.style.display = 'none'; | |
| } | |
| } | |
| function openCartModal() { | |
| const cartContent = document.getElementById('cartContent'); | |
| const cartTotalElement = document.getElementById('cartTotal'); | |
| let total = 0; | |
| if (cart.length === 0) { | |
| cartContent.innerHTML = `<p style="text-align: center; padding: 20px 0;">${translations['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/65x65.png?text=N/A'; | |
| let detailsHtml = `<p class="cart-item-price">${translations['cart_item_variant']}: ${item.variantName}</p>`; | |
| if (item.sizeName) { | |
| detailsHtml += `<p class="cart-item-price">${translations['cart_item_size']}: ${item.sizeName}</p>`; | |
| } | |
| return ` | |
| <div class="cart-item"> | |
| <img src="${photoUrl}" alt="${item.name}"> | |
| <div class="cart-item-details"> | |
| <strong>${item.name}</strong> | |
| ${detailsHtml} | |
| <p class="cart-item-price">${item.price.toFixed(2)} ${currencyCode} × ${item.quantity}</p> | |
| </div> | |
| <span class="cart-item-total">${itemTotal.toFixed(2)}</span> | |
| <button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="${translations['remove_item_title']}">×</button> | |
| </div>`; | |
| }).join(''); | |
| cartTotalElement.textContent = total.toFixed(2); | |
| } | |
| document.getElementById('cartModal').style.display = 'block'; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| function removeFromCart(itemId) { | |
| cart = cart.filter(item => item.id !== itemId); | |
| localStorage.setItem('esmiracart', JSON.stringify(cart)); | |
| openCartModal(); | |
| updateCartButton(); | |
| } | |
| function clearCart() { | |
| if (confirm(translations['clear_cart_confirm'])) { | |
| cart = []; | |
| localStorage.removeItem('esmiracart'); | |
| openCartModal(); | |
| updateCartButton(); | |
| } | |
| } | |
| function formulateOrder() { | |
| if (cart.length === 0) { | |
| alert(translations['cart_is_empty_alert']); | |
| return; | |
| } | |
| document.querySelector('.formulate-order-button').disabled = true; | |
| showNotification(translations['formulating_order'], 5000); | |
| fetch('/create_order', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ cart: cart }) | |
| }) | |
| .then(response => response.json()) | |
| .then(data => { | |
| if (data.order_id) { | |
| localStorage.removeItem('esmiracart'); | |
| cart = []; | |
| updateCartButton(); | |
| closeModal('cartModal'); | |
| window.location.href = `/${langCode}/order/${data.order_id}`; | |
| } else { | |
| throw new Error(data.error || 'Не получен ID заказа от сервера.'); | |
| } | |
| }) | |
| .catch(error => { | |
| console.error('Ошибка при формировании заказа:', error); | |
| alert(`Ошибка: ${error.message}`); | |
| document.querySelector('.formulate-order-button').disabled = false; | |
| }); | |
| } | |
| function filterProducts() { | |
| const searchTerm = document.getElementById('search-input').value.toLowerCase().trim(); | |
| const activeCategory = document.querySelector('.category-filter.active').dataset.category; | |
| const activeType = document.querySelector('.type-filter.active').dataset.type; | |
| 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.dataset.name; | |
| const description = productElement.dataset.description; | |
| const category = productElement.dataset.category; | |
| const type = productElement.dataset.type; | |
| const matchesSearch = !searchTerm || name.includes(searchTerm) || description.includes(searchTerm); | |
| const matchesCategory = activeCategory === 'all' || category === activeCategory; | |
| const matchesType = activeType === 'all' || type === activeType; | |
| if (matchesSearch && matchesCategory && matchesType) { | |
| productElement.style.display = 'flex'; | |
| visibleProducts++; | |
| } else { | |
| productElement.style.display = 'none'; | |
| } | |
| }); | |
| if (visibleProducts === 0) { | |
| const msg = document.createElement('p'); | |
| msg.className = 'no-results-message'; | |
| msg.textContent = products.length > 0 ? translations['no_products_found'] : translations['no_products_yet']; | |
| grid.appendChild(msg); | |
| } | |
| } | |
| function setupFilters() { | |
| document.getElementById('search-input').addEventListener('input', filterProducts); | |
| document.querySelectorAll('.filter-btn').forEach(filter => { | |
| filter.addEventListener('click', function() { | |
| const filterGroupClass = this.classList.contains('category-filter') ? '.category-filter.active' : '.type-filter.active'; | |
| document.querySelector(filterGroupClass).classList.remove('active'); | |
| this.classList.add('active'); | |
| filterProducts(); | |
| }); | |
| }); | |
| } | |
| function showNotification(message, duration = 3000) { | |
| const placeholder = document.getElementById('notification-placeholder'); | |
| 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(); | |
| filterProducts(); | |
| 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').forEach(modal => modal.style.display = 'none'); | |
| document.body.style.overflow = 'auto'; | |
| } | |
| }); | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| PRODUCT_DETAIL_TEMPLATE = ''' | |
| <div style="padding: 10px;"> | |
| <h2 style="font-family: 'Cormorant Garamond', serif; font-size: 2rem; font-weight: 700; margin-bottom: 20px; text-align: center; color: var(--primary-color);">{{ product['name'] }}</h2> | |
| <div class="swiper-container" style="max-width: 450px; margin: 0 auto 25px; border-radius: 12px; overflow: hidden; border: 1px solid var(--border-color);"> | |
| <div class="swiper-wrapper"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| {% for photo in product['photos'] %} | |
| <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center; padding: 10px; background-color: #fff;"> | |
| <div class="swiper-zoom-container"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" | |
| alt="{{ product['name'] }} - фото {{ loop.index }}" | |
| style="max-width: 100%; max-height: 400px; object-fit: contain; display: block; margin: auto; cursor: grab;"> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center;"> | |
| <img src="https://via.placeholder.com/400x400.png?text=No+Image" alt="Изображение отсутствует" style="max-width: 100%; max-height: 400px; object-fit: contain;"> | |
| </div> | |
| {% endif %} | |
| </div> | |
| {% if product.get('photos') and product['photos']|length > 1 %} | |
| <div class="swiper-pagination" style="position: relative; bottom: 5px; margin-top: 10px;"></div> | |
| <div class="swiper-button-next" style="color: var(--primary-color);"></div> | |
| <div class="swiper-button-prev" style="color: var(--primary-color);"></div> | |
| {% endif %} | |
| </div> | |
| <div style="font-size: 1rem; line-height: 1.7; padding: 0 10px;"> | |
| <p><strong>{{ _['product_type'] }}:</strong> {{ _[product.get('product_type', 'tkaniny')] }}</p> | |
| <p><strong>{{ _['category'] }}:</strong> {{ product.get('category', _['no_category']) }}</p> | |
| {% if product.get('variants') and product.variants|length > 0 %} | |
| <p style="font-size: 1.4rem; font-weight: bold; color: var(--primary-color); margin: 15px 0;"> | |
| {{ _['from_price'] }} {{ "%.2f"|format(product.variants|map(attribute='price')|min) }} {{ currency_code }} | |
| {% if product.product_type == 'tkaniny' %} / {{ _['price_per_meter']|lower }} {% endif %} | |
| </p> | |
| <p><strong>{{ _['available_variants'] }}</strong></p> | |
| <ul style="list-style: none; padding-left: 0;"> | |
| {% for variant in product.variants %} | |
| <li style="padding: 5px 0; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between;"> | |
| <span>- {{ variant.name }}</span> | |
| <strong>{{ "%.2f"|format(variant.price) }} {{ currency_code }}</strong> | |
| </li> | |
| {% endfor %} | |
| </ul> | |
| {% endif %} | |
| {% if product.product_type == 'odezhda' and product.get('sizes') and product.sizes|length > 0 %} | |
| <p style="margin-top: 15px;"><strong>{{ _['available_sizes'] }}</strong></p> | |
| <ul style="list-style: none; padding-left: 0;"> | |
| {% for size in product.sizes %} | |
| <li style="padding: 5px 0; border-bottom: 1px solid var(--border-color);"> | |
| - {{ size.name }} | |
| </li> | |
| {% endfor %} | |
| </ul> | |
| {% endif %} | |
| <p style="margin-top: 20px;"><strong>{{ _['description'] }}:</strong><br> {{ product.get('description', _['no_description'])|replace('\\n', '<br>')|safe }}</p> | |
| </div> | |
| <div style="padding: 20px 10px 10px; text-align: center;"> | |
| <button class="product-button" onclick="closeModal('productModal'); openQuantityModal({{ products_index }})" style="margin-top: 15px; padding: 12px 25px; font-size: 1rem;"> | |
| <i class="fas fa-shopping-bag"></i> {{ _['add_to_cart_button'] }} | |
| </button> | |
| </div> | |
| </div> | |
| ''' | |
| ORDER_TEMPLATE = ''' | |
| <!DOCTYPE html> | |
| <html lang="{{ lang_code }}"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>{{ _['order_page_title'] }}{{ order.id }} - Esmira</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=Cormorant+Garamond:wght@400;600;700&family=Georgia&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 { | |
| --primary-color: #9A2A47; | |
| --primary-dark: #7a2138; | |
| --surface-color: #313131; | |
| --background-color: #212121; | |
| --text-color: #F5F5F5; | |
| --text-color-muted: #BDBDBD; | |
| --border-color: #424242; | |
| } | |
| body { font-family: 'Georgia', serif; background: var(--background-color); color: var(--text-color); line-height: 1.6; padding: 15px; } | |
| .container { max-width: 800px; margin: 20px auto; padding: 30px; background: var(--surface-color); border-radius: 16px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.6); border: 1px solid var(--border-color); } | |
| h1, h2 { font-family: 'Cormorant Garamond', serif; color: var(--primary-color); } | |
| h1 { text-align: center; margin-bottom: 25px; font-size: 2.2rem; font-weight: 700; } | |
| h2 { margin-top: 30px; margin-bottom: 15px; font-size: 1.6rem; border-bottom: 1px solid var(--border-color); padding-bottom: 8px; display: flex; align-items: center; gap: 10px; } | |
| .order-meta { font-size: 0.9rem; color: var(--text-color-muted); margin-bottom: 20px; text-align: center; } | |
| .order-item { display: grid; grid-template-columns: 60px 1fr auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid var(--border-color); } | |
| .order-item:last-child { border-bottom: none; } | |
| .order-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #fff; padding: 5px; border: 1px solid #444;} | |
| .item-details strong { display: block; margin-bottom: 4px; font-size: 1.05rem; color: var(--text-color);} | |
| .item-details span { font-size: 0.9rem; color: var(--text-color-muted); display: block;} | |
| .item-total { font-weight: bold; text-align: right; font-size: 1.1rem; color: var(--primary-color);} | |
| .order-summary { margin-top: 30px; padding-top: 20px; border-top: 2px solid var(--primary-color); text-align: right; } | |
| .order-summary p { margin-bottom: 10px; font-size: 1.1rem; } | |
| .order-summary strong { font-size: 1.5rem; color: var(--primary-color); } | |
| .customer-info { margin-top: 30px; background-color: rgba(154, 42, 71, 0.05); padding: 20px; border-radius: 12px; border: 1px solid var(--primary-color);} | |
| .customer-info p { margin-bottom: 8px; font-size: 1rem; } | |
| .customer-info strong { color: var(--text-color); } | |
| .actions { margin-top: 30px; text-align: center; } | |
| .button { padding: 12px 25px; border: none; border-radius: 50px; background-color: #25D366; color: white; font-weight: 500; cursor: pointer; transition: all 0.3s ease; font-size: 1.1rem; display: inline-flex; align-items: center; gap: 10px; text-decoration: none; box-shadow: 0 4px 10px rgba(37, 211, 102, 0.3); } | |
| .button:hover { background-color: #1DA851; transform: translateY(-2px); } | |
| .catalog-link { display: block; text-align: center; margin-top: 25px; color: var(--primary-color); text-decoration: none; transition: color 0.2s; } | |
| .catalog-link:hover { color: var(--primary-dark); } | |
| .not-found { text-align: center; color: #ff453a; font-size: 1.2rem; padding: 40px 0;} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| {% if order %} | |
| <h1><i class="fas fa-receipt"></i> {{ _['order_page_title'] }}{{ order.id }}</h1> | |
| <p class="order-meta">{{ _['order_created_at'] }} {{ order.created_at }}</p> | |
| <h2><i class="fas fa-shopping-bag"></i> {{ _['order_items'] }}</h2> | |
| <div id="orderItems"> | |
| {% for item in order.cart %} | |
| <div class="order-item"> | |
| <img src="{{ item.photo_url }}" alt="{{ item.name }}"> | |
| <div class="item-details"> | |
| <strong>{{ item.name }}</strong> | |
| <span>{{ _['cart_item_variant'] }}: {{ item.variantName }}</span> | |
| {% if item.sizeName %} | |
| <span>{{ _['cart_item_size'] }}: {{ item.sizeName }}</span> | |
| {% endif %} | |
| <span>{{ "%.2f"|format(item.price) }} {{ currency_code }} × {{ item.quantity }}</span> | |
| </div> | |
| <div class="item-total"> | |
| {{ "%.2f"|format(item.price * item.quantity) }} {{ currency_code }} | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| <div class="order-summary"> | |
| <p>{{ _['order_total_price'] }}: <strong>{{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p> | |
| </div> | |
| <div class="customer-info"> | |
| <h2><i class="fas fa-info-circle"></i> {{ _['order_status_and_confirmation'] }}</h2> | |
| <p>{{ _['order_current_status'] }}: <strong>{{ status_map.get(order.status, order.status) }}</strong></p> | |
| <p>{{ _['order_whatsapp_prompt'] }}</p> | |
| </div> | |
| <div class="actions"> | |
| <button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> {{ _['order_contact_us_button'] }}</button> | |
| </div> | |
| <a href="{{ url_for('catalog', lang_code=lang_code) }}" class="catalog-link">← {{ _['return_to_catalog'] }}</a> | |
| <script> | |
| function sendOrderViaWhatsApp() { | |
| const orderId = '{{ order.id }}'; | |
| const orderUrl = `{{ request.url }}`; | |
| const whatsappNumber = "{{ whatsapp_number }}".replace(/\D/g, ''); | |
| let message = `{{ _['whatsapp_confirm_message_1'] }}%0A%0A`; | |
| message += `*{{ _['whatsapp_confirm_message_2'] }}* ${orderId}%0A`; | |
| message += `*{{ _['whatsapp_confirm_message_3'] }}* ${encodeURIComponent(orderUrl)}%0A%0A`; | |
| message += `{{ _['whatsapp_confirm_message_4'] }}`; | |
| const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${message}`; | |
| window.open(whatsappUrl, '_blank'); | |
| } | |
| </script> | |
| {% else %} | |
| <h1 style="color: #ff453a;"><i class="fas fa-exclamation-triangle"></i> {{ _['order_not_found_error'] }}</h1> | |
| <p class="not-found">{{ _['order_not_found_message'] }}</p> | |
| <a href="{{ url_for('catalog', lang_code=lang_code) }}" class="catalog-link">← {{ _['return_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>Админ-панель - Esmira</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=Cormorant+Garamond:wght@600&family=Georgia&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 { | |
| --primary-color: #9A2A47; | |
| --primary-dark: #7a2138; | |
| --surface-color: #313131; | |
| --background-color: #212121; | |
| --text-color: #F5F5F5; | |
| --text-color-muted: #BDBDBD; | |
| --border-color: #424242; | |
| --success-bg: #113d21; | |
| --success-text: #6ee791; | |
| --error-bg: #4d0a0a; | |
| --error-text: #ff8f8f; | |
| --warning-bg: #4a3a09; | |
| --warning-text: #ffd56b; | |
| } | |
| body { font-family: 'Georgia', serif; background-color: var(--background-color); color: var(--text-color); padding: 15px; line-height: 1.5; } | |
| .container { max-width: 1200px; margin: 0 auto; background-color: var(--surface-color); padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); border: 1px solid var(--border-color); } | |
| .header { padding-bottom: 20px; margin-bottom: 25px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;} | |
| h1, h2, h3, h4 { font-family: 'Cormorant Garamond', serif; font-weight: 600; color: var(--primary-color); margin:0 0 15px 0;} | |
| h1 { font-size: 2rem; } | |
| h2 { font-size: 1.6rem; margin-top: 30px; display: flex; align-items: center; gap: 10px; padding-bottom: 8px; border-bottom: 1px solid var(--border-color);} | |
| h3 { font-size: 1.2rem; color: var(--text-color); margin-top: 20px;} | |
| .section { margin-bottom: 30px; padding: 20px; background-color: #292929; border: 1px solid var(--border-color); border-radius: 8px; } | |
| label { font-weight: 500; margin-top: 12px; display: block; color: var(--text-color); 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: 6px; border: 1px solid var(--border-color); border-radius: 6px; font-size: 0.95rem; box-sizing: border-box; transition: border-color 0.3s ease; background-color: var(--background-color); color: var(--text-color); } | |
| input:focus, textarea:focus, select:focus { border-color: var(--primary-color); outline: none; box-shadow: 0 0 0 3px rgba(154, 42, 71, 0.2); } | |
| textarea { min-height: 90px; resize: vertical; } | |
| input[type="file"] { padding: 8px; background-color: #222; cursor: pointer; border: 1px solid var(--border-color); border-radius: 6px; } | |
| input[type="checkbox"] { transform: scale(1.2); margin-right: 8px; vertical-align: middle; accent-color: var(--primary-color); } | |
| button, .button { padding: 9px 18px; border: none; border-radius: 50px; background-color: var(--primary-color); color: #fff; font-weight: 500; cursor: pointer; transition: all 0.2s ease; margin-top: 15px; font-size: 0.9rem; display: inline-flex; align-items: center; gap: 6px; text-decoration: none; line-height: 1.2; text-transform: uppercase; letter-spacing: 0.5px; } | |
| button:hover, .button:hover { background-color: var(--primary-dark); transform: translateY(-1px); } | |
| .delete-button { background-color: #8B0000; color: white; } | |
| .delete-button:hover { background-color: #6e0000; } | |
| .item-list { display: grid; gap: 15px; } | |
| .item { background: var(--surface-color); padding: 15px; border-radius: 8px; border: 1px solid var(--border-color); } | |
| .item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; } | |
| .photo-preview img, .photo-edit-item img { width: 60px; height: 60px; border-radius: 6px; margin: 5px 5px 0 0; border: 1px solid var(--border-color); object-fit: cover; background-color: #fff;} | |
| .photo-preview-edit { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 5px; } | |
| .photo-edit-item { position: relative; } | |
| .photo-edit-item input[type="checkbox"] { position: absolute; top: 0px; right: 0px; transform: scale(1.3); accent-color: #ff453a; cursor: pointer; } | |
| .input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; } | |
| .input-group input { flex-grow: 1; margin: 0; } | |
| .remove-btn { background-color: #8B0000; color: white; padding: 6px 10px; font-size: 0.8rem; margin: 0; border-radius: 6px; } | |
| .add-btn { background-color: #1c4532; color: var(--text-color); margin-top: 8px;} | |
| .add-btn:hover { background-color: #22543d; } | |
| .message { padding: 12px 18px; border-radius: 8px; margin-bottom: 20px; font-size: 0.95rem; border: 1px solid;} | |
| .message.success { background-color: var(--success-bg); color: var(--success-text); border-color: var(--success-text);} | |
| .message.error { background-color: var(--error-bg); color: var(--error-text); border-color: var(--error-text);} | |
| .message.warning { background-color: var(--warning-bg); color: var(--warning-text); border-color: var(--warning-text); } | |
| .status-indicator { display: inline-block; padding: 3px 9px; border-radius: 50px; font-size: 0.75rem; font-weight: 500; margin-left: 5px; vertical-align: middle; } | |
| .status-indicator.new { background-color: #e65100; color: #ffe0b2; } | |
| .status-indicator.accepted { background-color: #0277bd; color: #b3e5fc; } | |
| .status-indicator.prepared { background-color: #2f855a; color: #c6f6d5; } | |
| .status-indicator.shipped { background-color: #065f46; color: #a7f3d0; } | |
| details { background-color: #292929; border: 1px solid var(--border-color); border-radius: 8px; margin-bottom: 10px; } | |
| details > summary { cursor: pointer; font-weight: 500; color: var(--text-color); display: flex; justify-content: space-between; align-items: center; padding: 15px 20px; list-style: none; position: relative; } | |
| details[open] > summary { border-bottom: 1px solid var(--border-color); } | |
| .order-details-content { padding: 15px 20px; } | |
| .order-status-form { display: flex; gap: 10px; align-items: center; margin-top: 15px; padding-top: 15px; border-top: 1px dashed var(--border-color); flex-wrap: wrap; } | |
| .order-status-form select { max-width: 180px; margin-top: 0; flex-grow: 1; } | |
| .flex-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; } | |
| .flex-item { min-width: 0; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <div class="logo-title-container" style="display: flex; align-items: center; gap: 15px;"> | |
| <img src="https://huggingface.co/spaces/esmira-tkani/admin/resolve/main/Screenshot_20251225-134859.png" alt="Esmira Logo" style="height: 45px; width: auto;"> | |
| <h1><i class="fas fa-tools"></i> Админ-панель</h1> | |
| </div> | |
| <a href="{{ url_for('catalog', lang_code='ru') }}" class="button"><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-history"></i> История заказов</h2> | |
| {% if orders %} | |
| {% for order in orders | sort(attribute='created_at', reverse=true) %} | |
| {% set current_status = order.get('status', 'new') %} | |
| <details> | |
| <summary> | |
| <span> | |
| Заказ №{{ order.id }} | |
| <span class="status-indicator {{ current_status }}">{{ status_map_ru.get(current_status, current_status) }}</span> | |
| </span> | |
| <span style="font-size: 0.85rem; color: var(--text-color-muted); flex-shrink: 0; margin-left: 10px;"> | |
| Дата: {{ order.created_at }} | Итого: {{ "%.2f"|format(order.total_price) }} {{ currency_code }} | |
| </span> | |
| </summary> | |
| <div class="order-details-content"> | |
| <h3>Состав заказа:</h3> | |
| <div class="order-status-form"> | |
| <form method="POST" style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;"> | |
| <input type="hidden" name="action" value="update_order_status"> | |
| <input type="hidden" name="order_id" value="{{ order.id }}"> | |
| <label for="status_{{ order.id }}" style="margin: 0; display: inline;">Статус:</label> | |
| <select name="new_status" id="status_{{ order.id }}"> | |
| {% for status_key, status_value in status_map_ru.items() %} | |
| <option value="{{ status_key }}" {% if current_status == status_key %}selected{% endif %}>{{ status_value }}</option> | |
| {% endfor %} | |
| </select> | |
| <button type="submit" class="button" style="margin-top:0;"><i class="fas fa-check"></i> Сохранить</button> | |
| <a href="{{ url_for('view_order', lang_code='ru', order_id=order.id) }}" target="_blank" class="button" style="background-color: #444; color: white; margin-top:0;"><i class="fas fa-eye"></i> Просмотр</a> | |
| </form> | |
| </div> | |
| </div> | |
| </details> | |
| {% endfor %} | |
| {% else %} | |
| <p>Активных заказов нет.</p> | |
| {% endif %} | |
| </div> | |
| <div class="section"> | |
| <h2><i class="fas fa-cog"></i> Настройки магазина</h2> | |
| <form method="POST"> | |
| <input type="hidden" name="action" value="update_settings"> | |
| <label for="whatsapp_number">Номер WhatsApp для заказов:</label> | |
| <input type="tel" id="whatsapp_number" name="whatsapp_number" value="{{ settings.get('whatsapp_number', '') }}" required> | |
| <button type="submit"><i class="fas fa-save"></i> Сохранить настройки</button> | |
| </form> | |
| <p style="margin-top: 20px;"><strong>Текущие адреса в г. Алматы:</strong></p> | |
| <ul style="padding-left: 20px;"> | |
| {% for address in store_addresses %} | |
| <li>{{ address }}</li> | |
| {% endfor %} | |
| </ul> | |
| <p style="margin-top: 10px;"><strong>Валюта:</strong> {{ currency_name }} ({{ currency_code }})</p> | |
| </div> | |
| <div class="section"> | |
| <h2><i class="fas fa-tags"></i> Категории</h2> | |
| <details> | |
| <summary><i class="fas fa-plus-circle"></i> Добавить новую категорию</summary> | |
| <div style="padding: 15px;"> | |
| <form method="POST"> | |
| <input type="hidden" name="action" value="add_category"> | |
| <label for="add_category_name">Название новой категории:</label> | |
| <input type="text" id="add_category_name" name="category_name" required> | |
| <button type="submit"><i class="fas fa-plus"></i> Добавить</button> | |
| </form> | |
| </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; padding: 10px;"> | |
| <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: 6px 12px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>Категорий пока нет.</p> | |
| {% endif %} | |
| </div> | |
| <div class="section"> | |
| <h2><i class="fas fa-box-open"></i> Товары</h2> | |
| <details> | |
| <summary><i class="fas fa-plus-circle"></i> Добавить новый товар</summary> | |
| <div style="padding: 15px;"> | |
| <form method="POST" enctype="multipart/form-data" id="add-product-form"> | |
| <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_description">Описание:</label> | |
| <textarea id="add_description" name="description" rows="4"></textarea> | |
| <label for="add_product_type">Тип товара *:</label> | |
| <select id="add_product_type" name="product_type" onchange="toggleProductFields('add')" required> | |
| <option value="tkaniny">Ткани</option> | |
| <option value="odezhda">Одежда</option> | |
| </select> | |
| <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> | |
| <h4>Варианты и цены *:</h4> | |
| <div id="add-variants-container"> | |
| <div class="input-group"> | |
| <input type="text" name="variant_names" placeholder="Название варианта (напр. Красный)" required> | |
| <input type="number" name="variant_prices" step="0.01" min="0" placeholder="Цена" required> | |
| <button type="button" class="remove-btn" onclick="removeInputGroup(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| </div> | |
| <button type="button" class="button add-btn" onclick="addInputGroup('add-variants-container', 'variant')"><i class="fas fa-plus"></i> Добавить вариант</button> | |
| <div id="add-sizes-section" style="display:none; margin-top:20px;"> | |
| <h4>Размеры *:</h4> | |
| <div id="add-sizes-container"> | |
| <div class="input-group"> | |
| <input type="text" name="size_names" placeholder="Название размера (напр. S, 42-44)"> | |
| <button type="button" class="remove-btn" onclick="removeInputGroup(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| </div> | |
| <button type="button" class="button add-btn" onclick="addInputGroup('add-sizes-container', 'size')"><i class="fas fa-plus"></i> Добавить размер</button> | |
| </div> | |
| <br><br> | |
| <button type="submit"><i class="fas fa-save"></i> Добавить товар</button> | |
| </form> | |
| </div> | |
| </details> | |
| <h3>Список товаров:</h3> | |
| {% if products %} | |
| <div class="item-list"> | |
| {% for product in products %} | |
| <div class="item"> | |
| <div style="display: flex; gap: 15px; align-items: flex-start;"> | |
| <div class="photo-preview"> | |
| {% if product.get('photos') and product.photos|length > 0 %} | |
| <a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" target="_blank"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" alt="Фото"> | |
| </a> | |
| {% else %} | |
| <img src="https://via.placeholder.com/60x60.png?text=N/A" alt="Нет фото"> | |
| {% endif %} | |
| </div> | |
| <div style="flex-grow: 1;"> | |
| <h3 style="margin-top: 0; margin-bottom: 5px;">{{ product['name'] }}</h3> | |
| <p style="font-size: 0.9rem; color: var(--text-color-muted);"><strong>Тип:</strong> {{ 'Ткани' if product.get('product_type') == 'tkaniny' else 'Одежда' }}</p> | |
| <p style="font-size: 0.9rem; color: var(--text-color-muted);"><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> | |
| </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 }}" style="display: none; margin-top: 15px; border-top: 1px solid var(--border-color); padding-top: 15px;"> | |
| <h4><i class="fas fa-edit"></i> Редактирование</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>Описание:</label> | |
| <textarea name="description" rows="4">{{ product.get('description', '') }}</textarea> | |
| <label>Тип товара *:</label> | |
| <select name="product_type" onchange="toggleProductFields('edit-{{ product.id }}')" required> | |
| <option value="tkaniny" {% if product.get('product_type') == 'tkaniny' %}selected{% endif %}>Ткани</option> | |
| <option value="odezhda" {% if product.get('product_type') == 'odezhda' %}selected{% endif %}>Одежда</option> | |
| </select> | |
| <label>Категория:</label> | |
| <select name="category"> | |
| <option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option> | |
| {% endfor %} | |
| </select> | |
| <label>Текущие фотографии (отметьте для удаления):</label> | |
| <div class="photo-preview-edit"> | |
| {% if product.get('photos') %} | |
| {% for photo in product['photos'] %} | |
| <div class="photo-edit-item"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="Фото {{ loop.index }}"> | |
| <input type="checkbox" name="delete_photos" value="{{ photo }}" title="Отметить для удаления"> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <p style="font-size: 0.9rem; color: var(--text-color-muted);">Фотографий нет.</p> | |
| {% endif %} | |
| </div> | |
| <label>Добавить новые фотографии:</label> | |
| <input type="file" name="photos" accept="image/*" multiple> | |
| <h4>Варианты и цены *:</h4> | |
| <div id="edit-variants-container-{{ product.id }}"> | |
| {% for variant in product.get('variants', []) %} | |
| <div class="input-group"> | |
| <input type="text" name="variant_names" value="{{ variant.name }}" required> | |
| <input type="number" name="variant_prices" step="0.01" min="0" value="{{ variant.price }}" required> | |
| <button type="button" class="remove-btn" onclick="removeInputGroup(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| <button type="button" class="button add-btn" onclick="addInputGroup('edit-variants-container-{{ product.id }}', 'variant')"><i class="fas fa-plus"></i> Добавить вариант</button> | |
| <div id="edit-{{ product.id }}-sizes-section" style="margin-top:20px; display: {% if product.get('product_type') == 'odezhda' %}block{% else %}none{% endif %};"> | |
| <h4>Размеры *:</h4> | |
| <div id="edit-sizes-container-{{ product.id }}"> | |
| {% for size in product.get('sizes', []) %} | |
| <div class="input-group"> | |
| <input type="text" name="size_names" value="{{ size.name }}" > | |
| <button type="button" class="remove-btn" onclick="removeInputGroup(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| <button type="button" class="button add-btn" onclick="addInputGroup('edit-sizes-container-{{ product.id }}', 'size')"><i class="fas fa-plus"></i> Добавить размер</button> | |
| </div> | |
| <br><br> | |
| <button type="submit"><i class="fas fa-save"></i> Сохранить изменения</button> | |
| </form> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>Товаров пока нет.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <script> | |
| function toggleEditForm(formId) { | |
| const form = document.getElementById(formId); | |
| form.style.display = form.style.display === 'none' ? 'block' : 'none'; | |
| } | |
| function addInputGroup(containerId, type) { | |
| const container = document.getElementById(containerId); | |
| const newInputGroup = document.createElement('div'); | |
| newInputGroup.className = 'input-group'; | |
| if (type === 'variant') { | |
| newInputGroup.innerHTML = ` | |
| <input type="text" name="variant_names" placeholder="Название варианта" required> | |
| <input type="number" name="variant_prices" step="0.01" min="0" placeholder="Цена" required> | |
| <button type="button" class="remove-btn" onclick="removeInputGroup(this)"><i class="fas fa-times"></i></button> | |
| `; | |
| } else { // size | |
| newInputGroup.innerHTML = ` | |
| <input type="text" name="size_names" placeholder="Название размера"> | |
| <button type="button" class="remove-btn" onclick="removeInputGroup(this)"><i class="fas fa-times"></i></button> | |
| `; | |
| } | |
| container.appendChild(newInputGroup); | |
| } | |
| function removeInputGroup(button) { | |
| const group = button.closest('.input-group'); | |
| const container = group.parentNode; | |
| if (container.children.length > 1) { | |
| group.remove(); | |
| } else { | |
| alert("Должен быть хотя бы один элемент."); | |
| } | |
| } | |
| function toggleProductFields(prefix) { | |
| const productType = document.querySelector(`[name="product_type"]`).value; | |
| const sizesSection = document.getElementById(`${prefix}-sizes-section`); | |
| const sizeInputs = sizesSection.querySelectorAll('input[name="size_names"]'); | |
| if (productType === 'odezhda') { | |
| sizesSection.style.display = 'block'; | |
| if (sizesSection.querySelector('.input-group') === null) { | |
| addInputGroup(`${prefix}-sizes-container`, 'size') | |
| } | |
| sizeInputs.forEach(input => input.required = true); | |
| } else { | |
| sizesSection.style.display = 'none'; | |
| sizeInputs.forEach(input => input.required = false); | |
| } | |
| } | |
| document.addEventListener('DOMContentLoaded', function() { | |
| document.querySelectorAll('form[id^="edit-form-"]').forEach(form => { | |
| const id = form.id.replace('edit-form-', ''); | |
| const select = form.querySelector('select[name="product_type"]'); | |
| if(select) { | |
| const productType = select.value; | |
| const sizesSection = document.getElementById(`edit-${id}-sizes-section`); | |
| const sizeInputs = sizesSection.querySelectorAll('input[name="size_names"]'); | |
| if (productType === 'odezhda') { | |
| sizesSection.style.display = 'block'; | |
| sizeInputs.forEach(input => input.required = true); | |
| } else { | |
| sizesSection.style.display = 'none'; | |
| sizeInputs.forEach(input => input.required = false); | |
| } | |
| } | |
| }); | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| def before_request(): | |
| path_parts = request.path.split('/') | |
| if len(path_parts) > 1 and path_parts[1] in translations: | |
| g.lang_code = path_parts[1] | |
| else: | |
| g.lang_code = 'ru' | |
| g.translations = translations.get(g.lang_code, translations['ru']) | |
| def index(): | |
| return redirect(url_for('catalog', lang_code='ru')) | |
| def catalog(lang_code): | |
| data = load_data() | |
| all_products = data.get('products', []) | |
| categories = sorted(data.get('categories', [])) | |
| settings = data.get('settings', {}) | |
| whatsapp_number = settings.get('whatsapp_number', '+77073363943').replace(' ', '').replace('+', '') | |
| products_in_stock = [p for p in all_products if p.get('variants')] | |
| for p in products_in_stock: | |
| p['variants'] = sorted(p.get('variants', []), key=lambda v: v.get('price', 0)) | |
| products_sorted = sorted(products_in_stock, key=lambda p: p.get('name', '').lower()) | |
| return render_template_string( | |
| CATALOG_TEMPLATE, | |
| products=products_sorted, | |
| categories=categories, | |
| repo_id=REPO_ID, | |
| store_addresses=STORE_ADDRESSES, | |
| currency_code=CURRENCY_CODE, | |
| lang_code=g.lang_code, | |
| _=g.translations, | |
| whatsapp_number=whatsapp_number | |
| ) | |
| def product_detail(lang_code, index): | |
| data = load_data() | |
| all_products = data.get('products', []) | |
| products_in_stock = [p for p in all_products if p.get('variants')] | |
| for p in products_in_stock: | |
| p['variants'] = sorted(p.get('variants', []), key=lambda v: v.get('price', 0)) | |
| products_sorted = sorted(products_in_stock, key=lambda p: p.get('name', '').lower()) | |
| try: | |
| product = products_sorted[index] | |
| except IndexError: | |
| return "Товар не найден.", 404 | |
| return render_template_string( | |
| PRODUCT_DETAIL_TEMPLATE, | |
| product=product, | |
| products_index=index, | |
| repo_id=REPO_ID, | |
| currency_code=CURRENCY_CODE, | |
| lang_code=g.lang_code, | |
| _=g.translations | |
| ) | |
| def create_order(): | |
| order_data = request.get_json() | |
| if not order_data or 'cart' not in order_data or not order_data['cart']: | |
| return jsonify({"error": "Корзина пуста."}), 400 | |
| cart_items = order_data['cart'] | |
| total_price = 0 | |
| processed_cart = [] | |
| data = load_data() | |
| products_map = {p['id']: p for p in data.get('products', [])} | |
| for item in cart_items: | |
| product = products_map.get(item.get('productId')) | |
| if not product: continue | |
| variant_exists = any(v['name'] == item.get('variantName') and v['price'] == item.get('price') for v in product.get('variants', [])) | |
| if not variant_exists: continue | |
| try: | |
| price = float(item['price']) | |
| quantity = float(item['quantity']) | |
| if price < 0 or quantity <= 0: raise ValueError("Invalid price/qty") | |
| total_price += price * quantity | |
| photo_name = item.get('photo') | |
| photo_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{photo_name}" if photo_name else "https://via.placeholder.com/60x60.png?text=N/A" | |
| processed_cart.append({ | |
| "name": item['name'], | |
| "price": price, | |
| "quantity": quantity, | |
| "variantName": item.get('variantName', 'N/A'), | |
| "sizeName": item.get('sizeName'), | |
| "photo": photo_name, | |
| "photo_url": photo_url | |
| }) | |
| except (ValueError, TypeError): | |
| return jsonify({"error": "Неверная цена или количество."}), 400 | |
| if not processed_cart: | |
| return jsonify({"error": "Не удалось обработать товары в корзине."}), 400 | |
| order_id = f"{datetime.now().strftime('%y%m%d%H%M')}-{uuid.uuid4().hex[:4]}" | |
| new_order = { | |
| "id": order_id, | |
| "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
| "cart": processed_cart, | |
| "total_price": round(total_price, 2), | |
| "status": "new" | |
| } | |
| try: | |
| data['orders'][order_id] = new_order | |
| save_data(data) | |
| return jsonify({"order_id": order_id}), 201 | |
| except Exception as e: | |
| logging.error(f"Failed to save order {order_id}: {e}") | |
| return jsonify({"error": "Ошибка сервера."}), 500 | |
| def view_order(lang_code, order_id): | |
| data = load_data() | |
| order = data.get('orders', {}).get(order_id) | |
| settings = data.get('settings', {}) | |
| whatsapp_number = settings.get('whatsapp_number', '+77073363943') | |
| status_map = STATUS_MAPS.get(lang_code, STATUS_MAPS['ru']) | |
| return render_template_string(ORDER_TEMPLATE, order=order, status_map=status_map, currency_code=CURRENCY_CODE, lang_code=g.lang_code, _=g.translations, whatsapp_number=whatsapp_number) | |
| def admin(): | |
| data = load_data() | |
| if 'orders' not in data: data['orders'] = {} | |
| if 'settings' not in data: data['settings'] = {'whatsapp_number': '+77073363943'} | |
| needs_save = False | |
| for p in data.get('products', []): | |
| if 'id' not in p: | |
| p['id'] = str(uuid.uuid4()) | |
| needs_save = True | |
| if needs_save: | |
| save_data(data) | |
| if request.method == 'POST': | |
| action = request.form.get('action') | |
| try: | |
| if action == 'update_settings': | |
| new_whatsapp = request.form.get('whatsapp_number', '').strip() | |
| if new_whatsapp: | |
| data['settings']['whatsapp_number'] = new_whatsapp | |
| save_data(data) | |
| flash('Настройки успешно обновлены.', 'success') | |
| else: | |
| flash('Номер WhatsApp не может быть пустым.', 'error') | |
| elif action == 'update_order_status': | |
| order_id = request.form.get('order_id') | |
| new_status = request.form.get('new_status') | |
| if order_id in data['orders'] and new_status in STATUS_MAPS['ru']: | |
| data['orders'][order_id]['status'] = new_status | |
| save_data(data) | |
| flash(f"Статус заказа №{order_id} изменен.", 'success') | |
| else: | |
| flash("Ошибка обновления статуса заказа.", 'error') | |
| elif action == 'add_category': | |
| category_name = request.form.get('category_name', '').strip() | |
| if category_name and category_name not in data['categories']: | |
| data['categories'].append(category_name) | |
| save_data(data) | |
| flash(f"Категория '{category_name}' добавлена.", 'success') | |
| else: | |
| flash("Ошибка: Категория пуста или уже существует.", 'error') | |
| elif action == 'delete_category': | |
| category_to_delete = request.form.get('category_name') | |
| if category_to_delete in data['categories']: | |
| data['categories'].remove(category_to_delete) | |
| for product in data['products']: | |
| if product.get('category') == category_to_delete: | |
| product['category'] = 'Без категории' | |
| save_data(data) | |
| flash(f"Категория '{category_to_delete}' удалена.", 'success') | |
| else: | |
| flash("Категория не найдена.", 'error') | |
| elif action == 'add_product' or action == 'edit_product': | |
| name = request.form.get('name', '').strip() | |
| if not name: | |
| flash("Название товара обязательно.", 'error') | |
| return redirect(url_for('admin')) | |
| variant_names = [v.strip() for v in request.form.getlist('variant_names') if v.strip()] | |
| variant_prices_str = request.form.getlist('variant_prices') | |
| if not variant_names or not variant_prices_str or len(variant_names) != len(variant_prices_str): | |
| flash("Ошибка в вариантах. У каждого варианта должно быть название и цена.", 'error') | |
| return redirect(url_for('admin')) | |
| variants = [] | |
| try: | |
| for i, v_name in enumerate(variant_names): | |
| price = round(float(variant_prices_str[i].replace(',', '.')), 2) | |
| if price < 0: price = 0 | |
| variants.append({'name': v_name, 'price': price}) | |
| except ValueError: | |
| flash("Неверный формат цены в вариантах.", 'error') | |
| return redirect(url_for('admin')) | |
| product_type = request.form.get('product_type') | |
| sizes = [] | |
| if product_type == 'odezhda': | |
| size_names = [s.strip() for s in request.form.getlist('size_names') if s.strip()] | |
| if not size_names: | |
| flash("Для одежды необходимо указать хотя бы один размер.", 'error') | |
| return redirect(url_for('admin')) | |
| sizes = [{'name': s_name} for s_name in size_names] | |
| product_data = { | |
| 'name': name, | |
| 'description': request.form.get('description', '').strip(), | |
| 'category': request.form.get('category'), | |
| 'product_type': product_type, | |
| 'variants': variants, | |
| 'sizes': sizes | |
| } | |
| newly_uploaded_photos = [] | |
| photos_files = request.files.getlist('photos') | |
| if photos_files and any(f.filename for f in photos_files): | |
| if not HF_TOKEN_WRITE: | |
| flash("Токен HF_TOKEN не настроен, фото не загружены.", "warning") | |
| else: | |
| api = HfApi() | |
| uploads_dir = 'uploads_temp' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| for photo in photos_files[:10]: | |
| 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(name.replace(' ', '_'))[:50] | |
| photo_filename = f"{safe_name}_{datetime.now().strftime('%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"Photo for {name}" | |
| ) | |
| newly_uploaded_photos.append(photo_filename) | |
| os.remove(temp_path) | |
| except Exception as e: | |
| logging.error(f"Error uploading photo {photo.filename}: {e}") | |
| flash(f"Ошибка загрузки фото {photo.filename}.", 'error') | |
| if action == 'add_product': | |
| product_data['id'] = str(uuid.uuid4()) | |
| product_data['photos'] = newly_uploaded_photos | |
| data['products'].append(product_data) | |
| flash(f"Товар '{name}' добавлен.", 'success') | |
| else: | |
| product_id = request.form.get('product_id') | |
| product_index = next((i for i, p in enumerate(data['products']) if p.get('id') == product_id), -1) | |
| if product_index != -1: | |
| product_to_edit = data['products'][product_index] | |
| current_photos = product_to_edit.get('photos', []) | |
| photos_to_delete = request.form.getlist('delete_photos') | |
| if photos_to_delete and HF_TOKEN_WRITE: | |
| try: | |
| HfApi().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 | |
| ) | |
| flash(f"Удалено {len(photos_to_delete)} фото.", 'success') | |
| except Exception as e: | |
| logging.error(f"Error deleting photos from HF: {e}") | |
| flash("Не удалось удалить фото с сервера.", "warning") | |
| updated_photos = [p for p in current_photos if p not in photos_to_delete] | |
| product_data['photos'] = updated_photos + newly_uploaded_photos | |
| product_data['id'] = product_id | |
| data['products'][product_index] = product_data | |
| flash(f"Товар '{name}' обновлен.", 'success') | |
| else: | |
| flash("Товар для редактирования не найден.", 'error') | |
| save_data(data) | |
| elif action == 'delete_product': | |
| product_id = request.form.get('product_id') | |
| product_to_delete = next((p for p in data['products'] if p.get('id') == product_id), None) | |
| if product_to_delete: | |
| data['products'].remove(product_to_delete) | |
| photos_to_delete = product_to_delete.get('photos', []) | |
| if photos_to_delete and HF_TOKEN_WRITE: | |
| try: | |
| HfApi().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 | |
| ) | |
| except Exception as e: | |
| logging.error(f"Error deleting photos from HF: {e}") | |
| flash("Не удалось удалить фото с сервера.", "warning") | |
| save_data(data) | |
| flash(f"Товар '{product_to_delete.get('name')}' удален.", 'success') | |
| else: | |
| flash("Товар для удаления не найден.", 'error') | |
| return redirect(url_for('admin')) | |
| except Exception as e: | |
| logging.error(f"Error processing admin action '{action}': {e}", exc_info=True) | |
| flash(f"Произошла внутренняя ошибка: {e}", 'error') | |
| return redirect(url_for('admin')) | |
| current_data = load_data() | |
| return render_template_string( | |
| ADMIN_TEMPLATE, | |
| products=sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower()), | |
| categories=sorted(current_data.get('categories', [])), | |
| orders=list(current_data.get('orders', {}).values()), | |
| settings=current_data.get('settings', {}), | |
| status_map_ru=STATUS_MAPS['ru'], | |
| repo_id=REPO_ID, | |
| store_addresses=STORE_ADDRESSES, | |
| currency_code=CURRENCY_CODE, | |
| currency_name=CURRENCY_NAME | |
| ) | |
| if __name__ == '__main__': | |
| logging.info("Application starting up...") | |
| download_db_from_hf() | |
| load_data() | |
| if HF_TOKEN_WRITE: | |
| threading.Thread(target=periodic_backup, daemon=True).start() | |
| port = int(os.environ.get('PORT', 7860)) | |
| app.run(debug=False, host='0.0.0.0', port=port) | |