Spaces:
Running
Running
| from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify | |
| 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_meka_shop_12345_no_login' | |
| DATA_FILE = 'data.json' | |
| SYNC_FILES = [DATA_FILE] | |
| REPO_ID = "Kgshop/prazdnik" | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN") | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") | |
| STORE_ADDRESS = "Рынок Джунхай , 6 проход , 49А контейнер " | |
| CURRENCY_CODE = 'KGS' | |
| CURRENCY_NAME = 'Кыргызский сом' | |
| WHATSAPP_NUMBER = "996702888188" | |
| DOWNLOAD_RETRIES = 3 | |
| DOWNLOAD_DELAY = 5 | |
| 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': {}}, 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': {}} | |
| def process_data(data): | |
| if not isinstance(data, dict): | |
| 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 'categories' in data: | |
| new_categories = [] | |
| for cat in data['categories']: | |
| if isinstance(cat, str): | |
| new_categories.append({'name': cat, 'subcategories': []}) | |
| elif isinstance(cat, dict) and 'name' in cat: | |
| if 'subcategories' not in cat or not isinstance(cat['subcategories'], list): | |
| cat['subcategories'] = [] | |
| new_categories.append(cat) | |
| else: | |
| logging.warning(f"Skipping invalid category entry: {cat}") | |
| data['categories'] = new_categories | |
| else: | |
| data['categories'] = [] | |
| for product in data['products']: | |
| if 'id' not in product: | |
| product['id'] = uuid.uuid4().hex # Assign stable ID if missing | |
| if 'subcategory' not in product: | |
| product['subcategory'] = 'Без подкатегории' | |
| if 'prices' not in product or not isinstance(product['prices'], list): | |
| if 'price' in product: | |
| product['prices'] = [{'type': 'шт', 'value': product.pop('price')}] | |
| else: | |
| product['prices'] = [] | |
| product['prices'] = [p for p in product['prices'] if isinstance(p, dict) and 'type' in p and 'value' in p] | |
| for p in product['prices']: | |
| try: | |
| p['value'] = round(float(p['value']), 2) | |
| except (ValueError, TypeError): | |
| p['value'] = 0.0 | |
| if not product['prices']: | |
| product['prices'] = [{'type': 'шт', 'value': 0.0}] | |
| return data | |
| 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}") | |
| return process_data(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.") | |
| return process_data(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'] = {} | |
| 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="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Мир праздника - Каталог</title> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css"> | |
| <style> | |
| * { margin: 0; padding: 0; box-sizing: border-box; } | |
| body { font-family: 'Poppins', sans-serif; background: #ffffff; color: #333333; line-height: 1.6; } | |
| .container { max-width: 1300px; margin: 0 auto; padding: 20px; } | |
| .header { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; border-bottom: 1px solid #e0e0e0; } | |
| .header h1 { font-size: 1.8rem; font-weight: 600; color: #e3a84f; } | |
| .store-address { padding: 15px; text-align: center; background-color: #f9f9f9; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.03); font-size: 1rem; color: #666; } | |
| .filters-container { margin: 20px 0; display: flex; flex-direction: column; gap: 10px; justify-content: center; align-items: center; } | |
| #main-category-filters, #subcategory-filters { | |
| width: 100%; | |
| max-width: 1000px; | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| justify-content: center; | |
| } | |
| #main-category-filters { | |
| padding-bottom: 10px; | |
| border-bottom: 1px solid #e0e0e0; | |
| } | |
| #subcategory-filters { | |
| padding-top: 10px; | |
| } | |
| .subcategory-group { | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| justify-content: center; | |
| } | |
| .search-container { margin: 20px 0; text-align: center; } | |
| #search-input { width: 90%; max-width: 600px; padding: 12px 18px; font-size: 1rem; border: 1px solid #e0e0e0; border-radius: 25px; outline: none; box-shadow: 0 2px 5px rgba(0,0,0,0.03); transition: all 0.3s ease; } | |
| #search-input:focus { border-color: #e3a84f; box-shadow: 0 0 0 3px rgba(227, 168, 79, 0.15); } | |
| .category-filter { padding: 8px 16px; border: 1px solid #e0e0e0; border-radius: 20px; background-color: #fff; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.9rem; font-weight: 400; color: #c89345; white-space: nowrap;} | |
| .category-filter.main-cat-btn { font-weight: 600; } | |
| .category-filter.subcategory-filter { font-size: 0.8rem; padding: 6px 12px; background-color: #f5f5f5; color: #666; border-color: #f5f5f5; } | |
| .category-filter.active, .category-filter:hover { background-color: #e3a84f; color: white; border-color: #e3a84f; box-shadow: 0 2px 10px rgba(227, 168, 79, 0.2); } | |
| .category-filter.subcategory-filter.active, .category-filter.subcategory-filter:hover { background-color: #e3a84f; color: white; border-color: #e3a84f; } | |
| .products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 20px; padding: 10px; } | |
| @media (min-width: 600px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); } } | |
| @media (min-width: 900px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); } } | |
| .product { background: #fff; border-radius: 15px; padding: 0; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; height: 100%; border: 1px solid #f0f0f0;} | |
| .product:hover { transform: translateY(-5px) scale(1.02); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1); } | |
| .product-image { width: 100%; aspect-ratio: 1 / 1; background-color: #fff; border-radius: 10px 10px 0 0; overflow: hidden; display: flex; justify-content: center; align-items: center; margin-bottom: 0; } | |
| .product-image img { max-width: 100%; max-height: 100%; object-fit: contain; transition: transform 0.3s ease; } | |
| .product-info { padding: 15px; flex-grow: 1; display: flex; flex-direction: column; justify-content: center; } | |
| .product h2 { font-size: 1.1rem; font-weight: 600; margin: 0 0 8px 0; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #333; } | |
| .product-price { font-size: 1rem; color: #c89345; font-weight: 700; text-align: center; margin: 5px 0; display: block; line-height: 1.4;} | |
| .product-description { font-size: 0.85rem; color: #666; text-align: center; margin-bottom: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } | |
| .product-actions { padding: 0 15px 15px 15px; display: flex; flex-direction: column; gap: 8px; } | |
| .product-button { display: block; width: 100%; padding: 10px; border: none; border-radius: 8px; background-color: #e3a84f; color: white; font-size: 0.9rem; font-weight: 500; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); text-align: center; text-decoration: none; } | |
| .product-button:hover { background-color: #c89345; box-shadow: 0 4px 15px rgba(200, 147, 69, 0.3); transform: translateY(-2px); } | |
| .product-button i { margin-right: 5px; } | |
| .add-to-cart { background-color: #e3a84f; } | |
| .add-to-cart:hover { background-color: #c89345; box-shadow: 0 4px 15px rgba(200, 147, 69, 0.4); } | |
| #cart-button { position: fixed; bottom: 25px; right: 25px; background-color: #e3a84f; color: white; border: none; border-radius: 50%; width: 55px; height: 55px; font-size: 1.5rem; cursor: pointer; display: none; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(227, 168, 79, 0.4); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1000; } | |
| #cart-button:hover { background-color: #c89345; box-shadow: 0 6px 20px rgba(200, 147, 69, 0.5); } | |
| #cart-button .fa-shopping-cart { margin-right: 0; } | |
| #cart-button span { position: absolute; top: -5px; right: -5px; background-color: #c89345; color: white; border-radius: 50%; padding: 2px 6px; font-size: 0.7rem; font-weight: bold; } | |
| .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); backdrop-filter: blur(3px); overflow-y: auto; } | |
| .modal-content { background: #ffffff; margin: 5% auto; padding: 25px; border-radius: 15px; width: 90%; max-width: 700px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); animation: slideIn 0.3s ease-out; position: relative; } | |
| @keyframes slideIn { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } } | |
| .close { position: absolute; top: 15px; right: 15px; font-size: 1.8rem; color: #aaa; cursor: pointer; transition: color 0.3s; line-height: 1; } | |
| .close:hover { color: #666; } | |
| .modal-content h2 { margin-top: 0; margin-bottom: 20px; color: #e3a84f; display: flex; align-items: center; gap: 10px;} | |
| .cart-item { display: grid; grid-template-columns: auto 1fr auto auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #e0e0e0; } | |
| .cart-item:last-child { border-bottom: none; } | |
| .cart-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #fff; padding: 5px; grid-column: 1; border: 1px solid #e0e0e0;} | |
| .cart-item-details { grid-column: 2; } | |
| .cart-item-details strong { display: block; margin-bottom: 5px; font-size: 1rem; color: #333;} | |
| .cart-item-price { font-size: 0.9rem; color: #666; } | |
| .cart-item-total { font-weight: bold; text-align: right; grid-column: 3; font-size: 1rem; color: #c89345;} | |
| .cart-item-remove { grid-column: 4; background:none; border:none; color:#dc3545; cursor:pointer; font-size: 1.3em; padding: 5px; line-height: 1; } | |
| .cart-item-remove:hover { color: #c82333; } | |
| .quantity-input, .color-select, .price-type-select { width: 100%; max-width: 180px; padding: 10px; border: 1px solid #e0e0e0; border-radius: 8px; font-size: 1rem; margin: 10px 0; box-sizing: border-box; display: block;} | |
| .quantity-input:focus, .color-select:focus, .price-type-select:focus { border-color: #e3a84f; outline: none; box-shadow: 0 0 0 2px rgba(227, 168, 79, 0.1); } | |
| .cart-summary { margin-top: 20px; text-align: right; border-top: 1px solid #e0e0e0; padding-top: 15px; } | |
| .cart-summary strong { font-size: 1.2rem; color: #e3a84f;} | |
| .cart-actions { margin-top: 25px; display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; } | |
| .cart-actions .product-button { width: auto; flex-grow: 1; } | |
| .clear-cart { background-color: #6c757d; } | |
| .clear-cart:hover { background-color: #5a6268; box-shadow: 0 4px 15px rgba(90, 98, 104, 0.4); } | |
| .formulate-order-button { background-color: #e3a84f; } | |
| .formulate-order-button:hover { background-color: #c89345; box-shadow: 0 4px 15px rgba(200, 147, 69, 0.4); } | |
| .notification { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background-color: #e3a84f; color: white; padding: 10px 20px; border-radius: 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); z-index: 1002; opacity: 0; transition: opacity 0.5s ease; font-size: 0.9rem;} | |
| .notification.show { opacity: 1;} | |
| .no-results-message { grid-column: 1 / -1; text-align: center; padding: 40px; font-size: 1.1rem; color: #999; } | |
| .top-product-indicator { position: absolute; top: 8px; right: 8px; background-color: rgba(255, 215, 0, 0.8); color: #333; padding: 2px 6px; font-size: 0.7rem; border-radius: 4px; font-weight: bold; z-index: 10; backdrop-filter: blur(2px); } | |
| .product { position: relative; } | |
| .price-list { font-size: 1rem; color: #c89345; font-weight: 700; text-align: center; margin: 5px 0; display: block; line-height: 1.4;} | |
| .price-item { font-size: 0.9rem; font-weight: normal; display: block;} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <div class="logo-title-container" style="display: flex; align-items: center; gap: 15px;"> | |
| <h1>Мир праздника</h1> | |
| </div> | |
| </div> | |
| <div class="store-address">Наш адрес: {{ store_address }}</div> | |
| <div class="filters-container"> | |
| <div id="main-category-filters"> | |
| <button class="category-filter active" data-category="all" data-subcategory="all">Все категории</button> | |
| {% for category_obj in categories_data %} | |
| <button class="category-filter main-cat-btn" data-category="{{ category_obj.name }}" data-subcategory="all">{{ category_obj.name }}</button> | |
| {% endfor %} | |
| </div> | |
| <div id="subcategory-filters" style="display: none;"> | |
| {% for category_obj in categories_data %} | |
| {% if category_obj.subcategories %} | |
| <div class="subcategory-group" data-parent-category="{{ category_obj.name }}" style="display: none;"> | |
| <span style="font-size: 0.9rem; color: #999; margin-right: 10px; padding: 6px 0;">Подкатегории {{ category_obj.name }}:</span> | |
| {% for subcategory in category_obj.subcategories %} | |
| <button class="category-filter subcategory-filter" data-category="{{ category_obj.name }}" data-subcategory="{{ subcategory }}">{{ subcategory }}</button> | |
| {% endfor %} | |
| </div> | |
| {% endif %} | |
| {% endfor %} | |
| </div> | |
| </div> | |
| <div class="search-container"> | |
| <input type="text" id="search-input" placeholder="Поиск по названию или описанию..."> | |
| </div> | |
| <div class="products-grid" id="products-grid"> | |
| {% for product in products %} | |
| <div class="product" | |
| data-product-id="{{ product['id'] }}" | |
| data-name="{{ product['name']|lower }}" | |
| data-description="{{ product.get('description', '')|lower }}" | |
| data-category="{{ product.get('category', 'Без категории') }}" | |
| data-subcategory="{{ product.get('subcategory', 'Без подкатегории') }}"> | |
| {% if product.get('is_top', False) %} | |
| <span class="top-product-indicator"><i class="fas fa-star"></i> Топ</span> | |
| {% endif %} | |
| <div class="product-image"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" | |
| alt="{{ product['name'] }}" | |
| loading="lazy"> | |
| {% else %} | |
| <img src="https://via.placeholder.com/250x250.png?text=No+Image" alt="No Image" loading="lazy"> | |
| {% endif %} | |
| </div> | |
| <div class="product-info"> | |
| <h2>{{ product['name'] }}</h2> | |
| <div class="price-list"> | |
| {% if product.get('prices') %} | |
| {% for price_item in product['prices'] %} | |
| <span class="price-item">{{ "%.2f"|format(price_item['value']) }} {{ currency_code }} / {{ price_item['type'] }}</span> | |
| {% endfor %} | |
| {% else %} | |
| <span class="price-item">Нет цены</span> | |
| {% endif %} | |
| </div> | |
| <p class="product-description">{{ product.get('category', 'Без категории') }}{% if product.get('subcategory', 'Без подкатегории') != 'Без подкатегории' %} / {{ product.get('subcategory') }}{% endif %}</p> | |
| </div> | |
| <div class="product-actions"> | |
| <button class="product-button" onclick="openModal('{{ product.id }}')">Подробнее</button> | |
| <button class="product-button add-to-cart" onclick="openQuantityModal('{{ product.id }}')"> | |
| <i class="fas fa-cart-plus"></i> В корзину | |
| </button> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% if not products %} | |
| <p class="no-results-message">Товары пока не добавлены.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div id="productModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span> | |
| <div id="modalContent">Загрузка...</div> | |
| </div> | |
| </div> | |
| <div id="quantityModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">×</span> | |
| <h2>Укажите количество, вариант и цвет</h2> | |
| <label for="priceTypeSelect">Вариант цены:</label> | |
| <select id="priceTypeSelect" class="price-type-select"></select> | |
| <label for="quantityInput">Количество:</label> | |
| <input type="number" id="quantityInput" class="quantity-input" min="1" value="1"> | |
| <label for="colorSelect">Цвет/Вариант:</label> | |
| <select id="colorSelect" class="color-select"></select> | |
| <button class="product-button add-to-cart" onclick="confirmAddToCart()"><i class="fas fa-check"></i> Добавить в корзину</button> | |
| </div> | |
| </div> | |
| <div id="cartModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span> | |
| <h2><i class="fas fa-shopping-cart"></i> Ваша корзина</h2> | |
| <div id="cartContent"><p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p></div> | |
| <div class="cart-summary"> | |
| <strong>Итого: <span id="cartTotal">0.00</span> {{ currency_code }}</strong> | |
| </div> | |
| <div class="cart-actions"> | |
| <button class="product-button clear-cart" onclick="clearCart()"> | |
| <i class="fas fa-trash"></i> Очистить корзину | |
| </button> | |
| <button class="product-button formulate-order-button" onclick="formulateOrder()"> | |
| <i class="fas fa-file-alt"></i> Сформировать заказ | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| <button id="cart-button" onclick="openCartModal()" aria-label="Открыть корзину"> | |
| <i class="fas fa-shopping-cart"></i> | |
| <span id="cart-count">0</span> | |
| </button> | |
| <div id="notification-placeholder"></div> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script> | |
| <script> | |
| const products = {{ products|tojson }}; | |
| const repoId = '{{ repo_id }}'; | |
| const currencyCode = '{{ currency_code }}'; | |
| const productMap = {}; | |
| products.forEach(p => { productMap[p.id] = p; }); | |
| let selectedProductId = null; | |
| let cart = JSON.parse(localStorage.getItem('mekaCart') || '[]'); | |
| function openModal(productId) { | |
| loadProductDetails(productId); | |
| const modal = document.getElementById('productModal'); | |
| if (modal) { | |
| modal.style.display = "block"; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| } | |
| function closeModal(modalId) { | |
| const modal = document.getElementById(modalId); | |
| if (modal) { | |
| modal.style.display = "none"; | |
| } | |
| const anyModalOpen = document.querySelector('.modal[style*="display: block"]'); | |
| if (!anyModalOpen) { | |
| document.body.style.overflow = 'auto'; | |
| } | |
| } | |
| function loadProductDetails(productId) { | |
| const modalContent = document.getElementById('modalContent'); | |
| if (!modalContent) return; | |
| modalContent.innerHTML = '<p style="text-align:center; padding: 40px;">Загрузка...</p>'; | |
| fetch('/product/' + productId) | |
| .then(response => { | |
| if (!response.ok) throw new Error(`Ошибка ${response.status}: ${response.statusText}`); | |
| return response.text(); | |
| }) | |
| .then(data => { | |
| modalContent.innerHTML = data; | |
| initializeSwiper(); | |
| }) | |
| .catch(error => { | |
| console.error('Ошибка загрузки деталей продукта:', error); | |
| modalContent.innerHTML = `<p style="color: #dc3545; text-align:center; padding: 40px;">Не удалось загрузить информацию о товаре. ${error.message}</p>`; | |
| }); | |
| } | |
| function initializeSwiper() { | |
| const swiperContainer = document.querySelector('#productModal .swiper-container'); | |
| if (swiperContainer) { | |
| new Swiper(swiperContainer, { | |
| slidesPerView: 1, | |
| spaceBetween: 20, | |
| loop: true, | |
| grabCursor: true, | |
| pagination: { el: '.swiper-pagination', clickable: true }, | |
| navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, | |
| zoom: { maxRatio: 3, containerClass: 'swiper-zoom-container' }, | |
| autoplay: { delay: 5000, disableOnInteraction: true, }, | |
| }); | |
| } | |
| } | |
| function openQuantityModal(productId) { | |
| selectedProductId = productId; | |
| const product = productMap[productId]; | |
| if (!product) { | |
| console.error("Product not found for ID:", productId); | |
| alert("Ошибка: товар не найден."); | |
| return; | |
| } | |
| const colorSelect = document.getElementById('colorSelect'); | |
| const colorLabel = document.querySelector('label[for="colorSelect"]'); | |
| colorSelect.innerHTML = ''; | |
| const validColors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : []; | |
| if (validColors.length > 0) { | |
| validColors.forEach(color => { | |
| const option = document.createElement('option'); | |
| option.value = color.trim(); | |
| option.text = color.trim(); | |
| colorSelect.appendChild(option); | |
| }); | |
| colorSelect.style.display = 'block'; | |
| if(colorLabel) colorLabel.style.display = 'block'; | |
| } else { | |
| colorSelect.style.display = 'none'; | |
| if(colorLabel) colorLabel.style.display = 'none'; | |
| } | |
| const priceTypeSelect = document.getElementById('priceTypeSelect'); | |
| const priceTypeLabel = document.querySelector('label[for="priceTypeSelect"]'); | |
| priceTypeSelect.innerHTML = ''; | |
| const validPrices = product.prices ? product.prices.filter(p => p.type && p.value >= 0) : []; | |
| if (validPrices.length > 0) { | |
| validPrices.forEach(price_item => { | |
| const option = document.createElement('option'); | |
| option.value = price_item.type.trim(); | |
| option.text = `${price_item.value.toFixed(2)} ${currencyCode} / ${price_item.type.trim()}`; | |
| option.dataset.priceValue = price_item.value; | |
| priceTypeSelect.appendChild(option); | |
| }); | |
| priceTypeSelect.style.display = 'block'; | |
| if(priceTypeLabel) priceTypeLabel.style.display = 'block'; | |
| } else { | |
| priceTypeSelect.style.display = 'none'; | |
| if(priceTypeLabel) priceTypeLabel.style.display = 'none'; | |
| alert("Для этого товара нет доступных цен."); | |
| return; | |
| } | |
| document.getElementById('quantityInput').value = 1; | |
| const modal = document.getElementById('quantityModal'); | |
| if(modal) { | |
| modal.style.display = 'block'; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| } | |
| function confirmAddToCart() { | |
| if (selectedProductId === null) return; | |
| const quantityInput = document.getElementById('quantityInput'); | |
| const quantity = parseInt(quantityInput.value); | |
| const colorSelect = document.getElementById('colorSelect'); | |
| const color = colorSelect.style.display !== 'none' && colorSelect.value ? colorSelect.value : 'N/A'; | |
| const priceTypeSelect = document.getElementById('priceTypeSelect'); | |
| const selectedPriceOption = priceTypeSelect.options[priceTypeSelect.selectedIndex]; | |
| const priceType = selectedPriceOption ? selectedPriceOption.value : 'шт'; | |
| const priceValue = selectedPriceOption ? parseFloat(selectedPriceOption.dataset.priceValue) : null; | |
| if (isNaN(quantity) || quantity <= 0) { | |
| alert("Пожалуйста, укажите корректное количество (больше 0)."); | |
| quantityInput.focus(); | |
| return; | |
| } | |
| if (priceValue === null || isNaN(priceValue)) { | |
| alert("Ошибка: Не удалось получить цену товара."); | |
| return; | |
| } | |
| const product = productMap[selectedProductId]; | |
| if (!product) { | |
| alert("Ошибка добавления: товар не найден."); | |
| return; | |
| } | |
| const cartItemId = `${product.id}-${priceType}-${color}`; | |
| const existingItemIndex = cart.findIndex(item => item.id === cartItemId); | |
| if (existingItemIndex > -1) { | |
| cart[existingItemIndex].quantity += quantity; | |
| } else { | |
| cart.push({ | |
| id: cartItemId, | |
| product_id: product.id, | |
| name: product.name, | |
| price_type: priceType, | |
| price_value: priceValue, | |
| photo: product.photos && product.photos.length > 0 ? product.photos[0] : null, | |
| quantity: quantity, | |
| color: color | |
| }); | |
| } | |
| localStorage.setItem('mekaCart', JSON.stringify(cart)); | |
| closeModal('quantityModal'); | |
| updateCartButton(); | |
| showNotification(`${product.name} (${priceType}) добавлен в корзину!`); | |
| } | |
| function updateCartButton() { | |
| const cartCountElement = document.getElementById('cart-count'); | |
| const cartButton = document.getElementById('cart-button'); | |
| if (!cartCountElement || !cartButton) return; | |
| let totalItems = 0; | |
| cart.forEach(item => { totalItems += item.quantity; }); | |
| if (totalItems > 0) { | |
| cartCountElement.textContent = totalItems; | |
| cartButton.style.display = 'flex'; | |
| } else { | |
| cartCountElement.textContent = '0'; | |
| cartButton.style.display = 'none'; | |
| } | |
| } | |
| function openCartModal() { | |
| const cartContent = document.getElementById('cartContent'); | |
| const cartTotalElement = document.getElementById('cartTotal'); | |
| if (!cartContent || !cartTotalElement) return; | |
| let total = 0; | |
| if (cart.length === 0) { | |
| cartContent.innerHTML = '<p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p>'; | |
| cartTotalElement.textContent = '0.00'; | |
| } else { | |
| cartContent.innerHTML = cart.map(item => { | |
| const itemTotal = item.price_value * item.quantity; | |
| total += itemTotal; | |
| const photoUrl = item.photo | |
| ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` | |
| : 'https://via.placeholder.com/60x60.png?text=N/A'; | |
| const colorText = item.color && item.color !== 'N/A' ? ` (Цвет: ${item.color})` : ''; | |
| const priceTypeText = item.price_type ? `/${item.price_type}` : ''; | |
| return ` | |
| <div class="cart-item"> | |
| <img src="${photoUrl}" alt="${item.name}"> | |
| <div class="cart-item-details"> | |
| <strong>${item.name}${colorText}</strong> | |
| <p class="cart-item-price">${item.price_value.toFixed(2)} ${currencyCode} ${priceTypeText} × ${item.quantity}</p> | |
| </div> | |
| <span class="cart-item-total">${itemTotal.toFixed(2)} ${currencyCode}</span> | |
| <button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="Удалить товар">×</button> | |
| </div> | |
| `; | |
| }).join(''); | |
| cartTotalElement.textContent = total.toFixed(2); | |
| } | |
| const modal = document.getElementById('cartModal'); | |
| if (modal) { | |
| modal.style.display = 'block'; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| } | |
| function removeFromCart(itemId) { | |
| cart = cart.filter(item => item.id !== itemId); | |
| localStorage.setItem('mekaCart', JSON.stringify(cart)); | |
| openCartModal(); | |
| updateCartButton(); | |
| } | |
| function clearCart() { | |
| if (confirm("Вы уверены, что хотите очистить корзину?")) { | |
| cart = []; | |
| localStorage.removeItem('mekaCart'); | |
| openCartModal(); | |
| updateCartButton(); | |
| } | |
| } | |
| function formulateOrder() { | |
| if (cart.length === 0) { | |
| alert("Корзина пуста! Добавьте товары перед формированием заказа."); | |
| return; | |
| } | |
| const orderData = { | |
| cart: cart | |
| }; | |
| const formulateButton = document.querySelector('.formulate-order-button'); | |
| if (formulateButton) formulateButton.disabled = true; | |
| showNotification("Формируем заказ...", 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 || 'Не удалось создать заказ'); }); | |
| } | |
| return response.json(); | |
| }) | |
| .then(data => { | |
| if (data.order_id) { | |
| localStorage.removeItem('mekaCart'); | |
| cart = []; | |
| updateCartButton(); | |
| closeModal('cartModal'); | |
| window.location.href = `/order/${data.order_id}`; | |
| } else { | |
| throw new Error('Не получен ID заказа от сервера.'); | |
| } | |
| }) | |
| .catch(error => { | |
| console.error('Ошибка при формировании заказа:', error); | |
| alert(`Ошибка: ${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 activeSubcategory = activeCategoryButton ? activeCategoryButton.dataset.subcategory : '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 productCategory = productElement.getAttribute('data-category'); | |
| const productSubcategory = productElement.getAttribute('data-subcategory'); | |
| const matchesSearch = !searchTerm || name.includes(searchTerm) || description.includes(searchTerm); | |
| let matchesFilter = false; | |
| if (activeCategory === 'all') { | |
| matchesFilter = true; | |
| } else if (productCategory === activeCategory) { | |
| if (activeSubcategory === 'all') { | |
| matchesFilter = true; | |
| } else if (productSubcategory === activeSubcategory) { | |
| matchesFilter = true; | |
| } | |
| } | |
| if (matchesSearch && matchesFilter) { | |
| 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 = 'По вашему запросу товары не найдены.'; | |
| 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 = 'Товары пока не добавлены.'; | |
| grid.appendChild(p); | |
| } | |
| } | |
| function updateSubcategoryVisibility(activeCategory) { | |
| const subcategoryContainer = document.getElementById('subcategory-filters'); | |
| if (activeCategory === 'all') { | |
| subcategoryContainer.style.display = 'none'; | |
| document.querySelectorAll('.subcategory-group').forEach(group => group.style.display = 'none'); | |
| return; | |
| } | |
| let found = false; | |
| document.querySelectorAll('.subcategory-group').forEach(group => { | |
| if (group.dataset.parentCategory === activeCategory) { | |
| group.style.display = 'flex'; | |
| found = true; | |
| } else { | |
| group.style.display = 'none'; | |
| } | |
| }); | |
| if (found) { | |
| subcategoryContainer.style.display = 'flex'; | |
| } else { | |
| subcategoryContainer.style.display = 'none'; | |
| } | |
| } | |
| 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'); | |
| const activeCategory = this.dataset.category; | |
| updateSubcategoryVisibility(activeCategory); | |
| filterProducts(); | |
| }); | |
| }); | |
| updateSubcategoryVisibility('all'); | |
| filterProducts(); | |
| } | |
| function showNotification(message, duration = 3000) { | |
| let placeholder = document.getElementById('notification-placeholder'); | |
| if (!placeholder) { | |
| const newPlaceholder = document.createElement('div'); | |
| newPlaceholder.id = 'notification-placeholder'; | |
| newPlaceholder.style.position = 'fixed'; | |
| newPlaceholder.style.bottom = '80px'; | |
| newPlaceholder.style.left = '50%'; | |
| newPlaceholder.style.transform = 'translateX(-50%)'; | |
| newPlaceholder.style.zIndex = '1002'; | |
| document.body.appendChild(newPlaceholder); | |
| placeholder = newPlaceholder; | |
| } | |
| 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(); | |
| 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); | |
| }); | |
| } | |
| }); | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| PRODUCT_DETAIL_TEMPLATE = ''' | |
| <div style="padding: 10px;"> | |
| <h2 style="font-size: 1.6rem; font-weight: 600; margin-bottom: 15px; text-align: center; color: #e3a84f;">{{ product['name'] }}</h2> | |
| <div class="swiper-container" style="max-width: 450px; margin: 0 auto 20px; border-radius: 10px; overflow: hidden; background-color: #fff; border: 1px solid #e0e0e0;"> | |
| <div class="swiper-wrapper"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| {% for photo in product['photos'] %} | |
| <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center; padding: 10px;"> | |
| <div class="swiper-zoom-container"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" | |
| alt="{{ product['name'] }} - фото {{ loop.index }}" | |
| style="max-width: 100%; max-height: 400px; object-fit: contain; display: block; margin: auto; cursor: grab;"> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center;"> | |
| <img src="https://via.placeholder.com/400x400.png?text=No+Image" alt="Изображение отсутствует" style="max-width: 100%; max-height: 400px; object-fit: contain;"> | |
| </div> | |
| {% endif %} | |
| </div> | |
| {% if product.get('photos') and product['photos']|length > 1 %} | |
| <div class="swiper-pagination" style="position: relative; bottom: 5px;"></div> | |
| <div class="swiper-button-next" style="color: #e3a84f;"></div> | |
| <div class="swiper-button-prev" style="color: #e3a84f;"></div> | |
| {% endif %} | |
| </div> | |
| <div style="margin-top: 20px; font-size: 1rem; line-height: 1.7; color: #333;"> | |
| <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> | |
| {% if product.get('subcategory', 'Без подкатегории') != 'Без подкатегории' %} | |
| <p><strong>Подкатегория:</strong> {{ product.get('subcategory') }}</p> | |
| {% endif %} | |
| <p style="font-size: 1.2rem; font-weight: bold; color: #c89345; margin-bottom: 10px;"><strong>Цена:</strong></p> | |
| <div class="price-list" style="text-align: left;"> | |
| {% if product.get('prices') %} | |
| {% for price_item in product['prices'] %} | |
| <span class="price-item" style="font-size: 1rem; font-weight: normal; color: #333;">{{ "%.2f"|format(price_item['value']) }} {{ currency_code }} / {{ price_item['type'] }}</span> | |
| {% endfor %} | |
| {% else %} | |
| <span class="price-item" style="font-size: 1rem; font-weight: normal; color: #333;">Нет доступных цен</span> | |
| {% endif %} | |
| </div> | |
| <p style="margin-top: 15px;"><strong>Описание:</strong><br> {{ product.get('description', 'Описание отсутствует.')|replace('\\n', '<br>')|safe }}</p> | |
| {% set colors = product.get('colors', []) %} | |
| {% if colors and colors|select('ne', '')|list|length > 0 %} | |
| <p><strong>Доступные цвета/варианты:</strong> {{ colors|select('ne', '')|join(', ') }}</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <style> | |
| #productModal .swiper-button-next, #productModal .swiper-button-prev { | |
| color: #e3a84f; | |
| } | |
| </style> | |
| ''' | |
| ORDER_TEMPLATE = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Заказ №{{ order.id }} - Мир праздника</title> | |
| <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <style> | |
| body { font-family: 'Poppins', sans-serif; background: #ffffff; color: #333; line-height: 1.6; padding: 20px; } | |
| .container { max-width: 800px; margin: 20px auto; padding: 30px; background: #fff; border-radius: 15px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); border: 1px solid #e0e0e0; } | |
| h1 { text-align: center; color: #e3a84f; margin-bottom: 25px; font-size: 1.8rem; font-weight: 600; } | |
| h2 { color: #c89345; margin-top: 30px; margin-bottom: 15px; font-size: 1.4rem; border-bottom: 1px solid #e0e0e0; padding-bottom: 8px;} | |
| .order-meta { font-size: 0.9rem; color: #999; 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 #f0f0f0; } | |
| .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 #e0e0e0;} | |
| .item-details strong { display: block; margin-bottom: 5px; font-size: 1.05rem; color: #333;} | |
| .item-details span { font-size: 0.9rem; color: #666; display: block;} | |
| .item-total { font-weight: bold; text-align: right; font-size: 1rem; color: #c89345;} | |
| .order-summary { margin-top: 30px; padding-top: 20px; border-top: 2px solid #e3a84f; text-align: right; } | |
| .order-summary p { margin-bottom: 10px; font-size: 1.1rem; } | |
| .order-summary strong { font-size: 1.3rem; color: #e3a84f; } | |
| .customer-info { margin-top: 30px; background-color: #f9f9f9; padding: 20px; border-radius: 8px; border: 1px solid #e0e0e0;} | |
| .customer-info p { margin-bottom: 8px; font-size: 0.95rem; } | |
| .customer-info strong { color: #c89345; } | |
| .actions { margin-top: 30px; text-align: center; } | |
| .button { padding: 12px 25px; border: none; border-radius: 8px; background-color: #e3a84f; color: white; font-weight: 600; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease; font-size: 1rem; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; } | |
| .button:hover { background-color: #c89345; } | |
| .button:active { transform: scale(0.98); } | |
| .button i { font-size: 1.2rem; } | |
| .catalog-link { display: block; text-align: center; margin-top: 25px; color: #e3a84f; text-decoration: none; font-size: 0.9rem; } | |
| .catalog-link:hover { text-decoration: underline; } | |
| .not-found { text-align: center; color: #dc3545; font-size: 1.2rem; padding: 40px 0;} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| {% if order %} | |
| <h1><i class="fas fa-receipt"></i> Ваш Заказ №{{ order.id }}</h1> | |
| <p class="order-meta">Дата создания: {{ order.created_at }}</p> | |
| <h2><i class="fas fa-shopping-bag"></i> Товары в заказе</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 }} {% if item.color and item.color != 'N/A' %}({{ item.color }}){% endif %}</strong> | |
| <span>{{ "%.2f"|format(item.price_value) }} {{ currency_code }} {% if item.price_type %}/ {{ item.price_type }}{% endif %} × {{ item.quantity }}</span> | |
| </div> | |
| <div class="item-total"> | |
| {{ "%.2f"|format(item.price_value * item.quantity) }} {{ currency_code }} | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| <div class="order-summary"> | |
| <p>Общая сумма товаров: <strong>{{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p> | |
| <p><strong>ИТОГО К ОПЛАТЕ: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p> | |
| </div> | |
| <div class="customer-info"> | |
| <h2><i class="fas fa-info-circle"></i> Статус заказа</h2> | |
| <p>Этот заказ был оформлен без входа в систему.</p> | |
| <p>Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.</p> | |
| </div> | |
| <div class="actions"> | |
| <button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> Отправить заказ</button> | |
| </div> | |
| <a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в каталог</a> | |
| <script> | |
| function sendOrderViaWhatsApp() { | |
| const orderId = '{{ order.id }}'; | |
| const orderUrl = `{{ request.url }}`; | |
| const whatsappNumber = "{{ whatsapp_number }}"; | |
| let message = `Здравствуйте! Хочу подтвердить свой заказ на сайте "Мир праздника":%0A%0A`; | |
| message += `*Номер заказа:* ${orderId}%0A`; | |
| message += `*Ссылка на заказ:* ${encodeURIComponent(orderUrl)}%0A%0A`; | |
| message += `Пожалуйста, свяжитесь со мной для уточнения деталей оплаты и доставки.`; | |
| const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${message}`; | |
| window.open(whatsappUrl, '_blank'); | |
| } | |
| </script> | |
| {% else %} | |
| <h1 style="color: #dc3545;"><i class="fas fa-exclamation-triangle"></i> Ошибка</h1> | |
| <p class="not-found">Заказ с таким ID не найден.</p> | |
| <a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в каталог</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>Админ-панель - Мир праздника</title> | |
| <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <style> | |
| body { font-family: 'Poppins', sans-serif; background-color: #ffffff; 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 #e0e0e0; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;} | |
| h1, h2, h3 { font-weight: 600; color: #e3a84f; 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: #c89345; margin-top: 20px; } | |
| .section { margin-bottom: 30px; padding: 20px; background-color: #f9f9f9; border: 1px solid #e0e0e0; border-radius: 8px; } | |
| form { margin-bottom: 20px; } | |
| label { font-weight: 500; margin-top: 10px; display: block; color: #666; 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 #e0e0e0; 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: #e3a84f; outline: none; box-shadow: 0 0 0 2px rgba(227, 168, 79, 0.1); } | |
| textarea { min-height: 80px; resize: vertical; } | |
| input[type="file"] { padding: 8px; background-color: #ffffff; cursor: pointer; border: 1px solid #e0e0e0;} | |
| input[type="file"]::file-selector-button { padding: 5px 10px; border-radius: 4px; background-color: #f0f0f0; border: 1px solid #e0e0e0; 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: #e3a84f; 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: #c89345; } | |
| button:active, .button:active { transform: scale(0.98); } | |
| button[type="submit"] { min-width: 120px; justify-content: center; } | |
| .delete-button { background-color: #dc3545; } | |
| .delete-button:hover { background-color: #c82333; } | |
| .add-button { background-color: #e3a84f; } | |
| .add-button:hover { background-color: #c89345; } | |
| .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.03); border: 1px solid #f0f0f0; } | |
| .item p { margin: 5px 0; font-size: 0.9rem; color: #666; } | |
| .item strong { color: #333; } | |
| .item .description { font-size: 0.85rem; color: #999; max-height: 60px; overflow: hidden; text-overflow: ellipsis; } | |
| .item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; } | |
| .item-actions button:not(.delete-button) { background-color: #e3a84f; } | |
| .item-actions button:not(.delete-button):hover { background-color: #c89345; } | |
| .edit-form-container { margin-top: 15px; padding: 20px; background: #fffcf5; border: 1px dashed #e0e0e0; border-radius: 6px; display: none; } | |
| details { background-color: #f9f9f9; border: 1px solid #e0e0e0; border-radius: 8px; margin-bottom: 20px; } | |
| details > summary { cursor: pointer; font-weight: 600; color: #c89345; display: block; padding: 15px; border-bottom: 1px solid #e0e0e0; 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: #e3a84f; } | |
| details[open] > summary::after { transform: translateY(-50%) rotate(180deg); } | |
| details[open] > summary { border-bottom: 1px solid #e0e0e0; } | |
| details .form-content { padding: 20px; } | |
| .color-input-group, .price-input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; } | |
| .color-input-group input, .price-input-group input { flex-grow: 1; margin: 0; } | |
| .price-input-group input[type="text"] { width: 100px; flex-grow: 0; } | |
| .price-input-group input[type="number"] { flex-grow: 1; } | |
| .price-input-group label { margin-top: 0; width: auto; display: inline-block; font-weight: normal; color: #333;} | |
| .remove-color-btn, .remove-price-btn { background-color: #dc3545; padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; } | |
| .remove-color-btn:hover, .remove-price-btn:hover { background-color: #c82333; } | |
| .add-color-btn, .add-price-btn { background-color: #f0c38b; color: #c89345; border: 1px solid #e0e0e0; } | |
| .add-color-btn:hover, .add-price-btn:hover { background-color: #e3a84f; color: white; border-color: #e3a84f; } | |
| .photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #e0e0e0; object-fit: cover;} | |
| .sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; } | |
| .download-hf-button { background-color: #6c757d; } | |
| .download-hf-button:hover { background-color: #5a6268; } | |
| .flex-container { display: flex; flex-wrap: wrap; gap: 20px; } | |
| .flex-item { flex: 1; min-width: 350px; } | |
| .message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; font-size: 0.9rem;} | |
| .message.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;} | |
| .message.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;} | |
| .message.warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; } | |
| .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: #d4edda; color: #155724; } | |
| .status-indicator.out-of-stock { background-color: #f8d7da; color: #721c24; } | |
| .status-indicator.top-product { background-color: #fff3cd; color: #856404; margin-left: 5px;} | |
| .admin-price-list { margin-top: 5px; } | |
| .admin-price-item { font-size: 0.85rem; color: #333; display: block; margin-bottom: 3px;} | |
| .category-item { background: #fff; padding: 15px 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.03); border: 1px solid #f0f0f0; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <div class="logo-title-container" style="display: flex; align-items: center; gap: 15px;"> | |
| <h1><i class="fas fa-tools"></i> Админ-панель Мир праздника</h1> | |
| </div> | |
| <a href="{{ url_for('catalog') }}" class="button" style="background-color: #e3a84f;"><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: #999;">Резервное копирование происходит автоматически каждые 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> | |
| <details style="margin-top: 10px;"> | |
| <summary><i class="fas fa-sitemap"></i> Добавить подкатегорию</summary> | |
| <div class="form-content"> | |
| <form method="POST"> | |
| <input type="hidden" name="action" value="add_subcategory"> | |
| <label for="parent_category_name">Выберите главную категорию:</label> | |
| <select id="parent_category_name" name="parent_category_name" required> | |
| {% for category in categories_data %} | |
| <option value="{{ category.name }}">{{ category.name }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="add_subcategory_name">Название новой подкатегории:</label> | |
| <input type="text" id="add_subcategory_name" name="subcategory_name" required> | |
| <button type="submit" class="add-button"><i class="fas fa-plus"></i> Добавить подкатегорию</button> | |
| </form> | |
| </div> | |
| </details> | |
| <h3>Существующие категории:</h3> | |
| {% if categories_data %} | |
| <div class="item-list"> | |
| {% for category in categories_data %} | |
| <div class="category-item"> | |
| <div style="display: flex; justify-content: space-between; align-items: center; background: #f0f0f0; padding: 5px 10px; border-radius: 4px; margin-bottom: 5px;"> | |
| <span><strong>{{ category.name }}</strong> (Главная)</span> | |
| <form method="POST" style="margin: 0;" onsubmit="return confirm('Удалить главную категорию \'{{ category.name }}\'? Это также удалит все подкатегории и обновит товары.');"> | |
| <input type="hidden" name="action" value="delete_category"> | |
| <input type="hidden" name="category_name" value="{{ category.name }}"> | |
| <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> | |
| {% for subcategory in category.subcategories %} | |
| <div style="display: flex; justify-content: space-between; align-items: center; padding: 5px 10px; margin-left: 15px; border-left: 2px solid #e3a84f;"> | |
| <span style="font-size: 0.9em;">— {{ subcategory }} (Подкатегория)</span> | |
| <form method="POST" style="margin: 0;" onsubmit="return confirm('Удалить подкатегорию \'{{ subcategory }}\' из \'{{ category.name }}\'?');"> | |
| <input type="hidden" name="action" value="delete_category"> | |
| <input type="hidden" name="category_name" value="{{ category.name }}"> | |
| <input type="hidden" name="subcategory_name" value="{{ subcategory }}"> | |
| <button type="submit" class="delete-button" style="padding: 3px 8px; font-size: 0.7rem; margin: 0;"><i class="fas fa-times"></i></button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>Категорий пока нет.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div class="flex-item"> | |
| <div class="section"> | |
| <h2><i class="fas fa-info-circle"></i> Информация</h2> | |
| <p>Управление пользователями отключено, так как сайт не требует входа.</p> | |
| <p>Заказы создаются анонимно и должны быть подтверждены через WhatsApp.</p> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="section"> | |
| <h2><i class="fas fa-box-open"></i> Управление товарами</h2> | |
| <details> | |
| <summary><i class="fas fa-plus-circle"></i> Добавить новый товар</summary> | |
| <div class="form-content"> | |
| <form method="POST" enctype="multipart/form-data"> | |
| <input type="hidden" name="action" value="add_product"> | |
| <label for="add_name">Название товара *:</label> | |
| <input type="text" id="add_name" name="name" required> | |
| <label>Цены (минимум одна) *:</label> | |
| <div id="add-price-inputs"> | |
| <div class="price-input-group"> | |
| <label>Тип:</label> | |
| <input type="text" name="price_types" placeholder="шт, упаковка, блок..."> | |
| <label>Цена:</label> | |
| <input type="number" name="price_values" step="0.01" min="0"> | |
| <button type="button" class="remove-price-btn" onclick="removePriceInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| </div> | |
| <button type="button" class="button add-price-btn" style="margin-top: 5px;" onclick="addPriceInput('add-price-inputs')"><i class="fas fa-dollar-sign"></i> Добавить поле для цены</button> | |
| <br> | |
| <label for="add_description" style="margin-top: 15px;">Описание:</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_data %} | |
| <option value="{{ category.name }}">{{ category.name }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="add_subcategory">Подкатегория:</label> | |
| <select id="add_subcategory" name="subcategory"> | |
| <option value="Без подкатегории">Без подкатегории</option> | |
| </select> | |
| <label for="add_photos">Фотографии (до 10 шт.):</label> | |
| <input type="file" id="add_photos" name="photos" accept="image/*" multiple> | |
| <label>Цвета/Варианты (оставьте пустым, если нет):</label> | |
| <div id="add-color-inputs"> | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" placeholder="Например: Розовый"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| </div> | |
| <button type="button" class="button add-color-btn" style="margin-top: 5px;" onclick="addColorInput('add-color-inputs')"><i class="fas fa-palette"></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"> | |
| {% for product in products %} | |
| <div class="item"> | |
| <div style="display: flex; gap: 15px; align-items: flex-start;"> | |
| <div class="photo-preview" style="flex-shrink: 0;"> | |
| {% if product.get('photos') %} | |
| <a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" target="_blank" title="Посмотреть первое фото"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" alt="Фото"> | |
| </a> | |
| {% else %} | |
| <img src="https://via.placeholder.com/70x70.png?text=N/A" alt="Нет фото"> | |
| {% endif %} | |
| </div> | |
| <div style="flex-grow: 1;"> | |
| <h3 style="margin-top: 0; margin-bottom: 5px; color: #333;"> | |
| {{ product['name'] }} | |
| {% 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> {{ product.get('subcategory', 'Без подкатегории') }}</p> | |
| <p><strong>Цены:</strong></p> | |
| <div class="admin-price-list"> | |
| {% if product.get('prices') %} | |
| {% for price_item in product['prices'] %} | |
| <span class="admin-price-item">{{ "%.2f"|format(price_item['value']) }} {{ currency_code }} / {{ price_item['type'] }}</span> | |
| {% endfor %} | |
| {% else %} | |
| <span class="admin-price-item">Нет цен</span> | |
| {% endif %} | |
| </div> | |
| <p class="description" title="{{ product.get('description', '') }}"><strong>Описание:</strong> {{ product.get('description', 'N/A')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}</p> | |
| {% set colors = product.get('colors', []) %} | |
| <p><strong>Цвета/Вар-ты:</strong> {{ colors|select('ne', '')|join(', ') if colors|select('ne', '')|list|length > 0 else 'Нет' }}</p> | |
| {% if product.get('photos') and product['photos']|length > 1 %} | |
| <p style="font-size: 0.8rem; color: #999;">(Всего фото: {{ 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>Цены (минимум одна) *:</label> | |
| <div id="edit-price-inputs-{{ product.id }}"> | |
| {% set current_prices = product.get('prices', []) %} | |
| {% if current_prices %} | |
| {% for price_item in current_prices %} | |
| <div class="price-input-group"> | |
| <label>Тип:</label> | |
| <input type="text" name="price_types" value="{{ price_item.get('type', '') }}" placeholder="шт, упаковка, блок..."> | |
| <label>Цена:</label> | |
| <input type="number" name="price_values" step="0.01" min="0" value="{{ "%.2f"|format(price_item.get('value', 0.0)) }}"> | |
| <button type="button" class="remove-price-btn" onclick="removePriceInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <div class="price-input-group"> | |
| <label>Тип:</label> | |
| <input type="text" name="price_types" placeholder="шт, упаковка, блок..."> | |
| <label>Цена:</label> | |
| <input type="number" name="price_values" step="0.01" min="0"> | |
| <button type="button" class="remove-price-btn" onclick="removePriceInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| </div> | |
| <button type="button" class="button add-price-btn" style="margin-top: 5px;" onclick="addPriceInput('edit-price-inputs-{{ product.id }}')"><i class="fas fa-dollar-sign"></i> Добавить поле для цены</button> | |
| <br> | |
| <label style="margin-top: 15px;">Описание:</label> | |
| <textarea name="description" rows="4">{{ product.get('description', '') }}</textarea> | |
| <label>Категория:</label> | |
| <select id="edit_category_{{ product.id }}" | |
| name="category" | |
| data-initial-subcategory="{{ product.get('subcategory', 'Без подкатегории') }}" | |
| onchange="updateSubcategorySelect('edit_category_{{ product.id }}', 'edit_subcategory_{{ product.id }}')"> | |
| <option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option> | |
| {% for category in categories_data %} | |
| <option value="{{ category.name }}" {% if product.get('category') == category.name %}selected{% endif %}>{{ category.name }}</option> | |
| {% endfor %} | |
| </select> | |
| <label>Подкатегория:</label> | |
| <select id="edit_subcategory_{{ product.id }}" name="subcategory"> | |
| <!-- Options populated by JS --> | |
| </select> | |
| <label>Заменить фотографии (выберите новые файлы, до 10 шт.):</label> | |
| <input type="file" name="photos" accept="image/*" multiple> | |
| {% if product.get('photos') %} | |
| <p style="font-size: 0.85rem; margin-top: 5px;">Текущие фото:</p> | |
| <div class="photo-preview"> | |
| {% for photo in product['photos'] %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="Фото {{ loop.index }}"> | |
| {% endfor %} | |
| </div> | |
| {% endif %} | |
| <label>Цвета/Варианты:</label> | |
| <div id="edit-color-inputs-{{ product.id }}"> | |
| {% set current_colors = product.get('colors', []) %} | |
| {% if current_colors and current_colors|select('ne', '')|list|length > 0 %} | |
| {% for color in current_colors %} | |
| {% if color.strip() %} | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" value="{{ color }}"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| {% endfor %} | |
| {% else %} | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" placeholder="Например: Цвет"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| </div> | |
| <button type="button" class="button add-color-btn" style="margin-top: 5px;" onclick="addColorInput('edit-color-inputs-{{ product.id }}')"><i class="fas fa-palette"></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> | |
| const categoriesData = {{ categories_data|tojson }}; | |
| const categorySubcategoryMap = {}; | |
| categoriesData.forEach(c => { | |
| categorySubcategoryMap[c.name] = c.subcategories; | |
| }); | |
| function updateSubcategorySelect(categorySelectId, subcategorySelectId, initialSubcategoryOverride = null) { | |
| const categorySelect = document.getElementById(categorySelectId); | |
| const subcategorySelect = document.getElementById(subcategorySelectId); | |
| if (!categorySelect || !subcategorySelect) return; | |
| const selectedCategory = categorySelect.value; | |
| const subcategories = categorySubcategoryMap[selectedCategory] || []; | |
| let currentSubcategory; | |
| if (initialSubcategoryOverride) { | |
| currentSubcategory = initialSubcategoryOverride; | |
| } else if (categorySelect.dataset.initialSubcategory) { | |
| currentSubcategory = categorySelect.dataset.initialSubcategory; | |
| delete categorySelect.dataset.initialSubcategory; | |
| } else { | |
| currentSubcategory = 'Без подкатегории'; | |
| } | |
| // If the main category changed, reset subcategory selection preference | |
| if (categorySelect.value !== selectedCategory) { | |
| currentSubcategory = 'Без подкатегории'; | |
| } | |
| subcategorySelect.innerHTML = '<option value="Без подкатегории">Без подкатегории</option>'; | |
| subcategories.forEach(sub => { | |
| const option = document.createElement('option'); | |
| option.value = sub; | |
| option.textContent = sub; | |
| if (sub === currentSubcategory) { | |
| option.selected = true; | |
| } | |
| subcategorySelect.appendChild(option); | |
| }); | |
| } | |
| function toggleEditForm(formId) { | |
| const formContainer = document.getElementById(formId); | |
| if (formContainer) { | |
| formContainer.style.display = formContainer.style.display === 'none' || formContainer.style.display === '' ? 'block' : 'none'; | |
| if (formContainer.style.display === 'block') { | |
| const productId = formId.split('-').pop(); | |
| const catSelect = document.getElementById(`edit_category_${productId}`); | |
| if (catSelect) { | |
| const initialSubcategory = catSelect.getAttribute('data-initial-subcategory'); | |
| updateSubcategorySelect(`edit_category_${productId}`, `edit_subcategory_${productId}`, initialSubcategory); | |
| } | |
| } | |
| } | |
| } | |
| function addColorInput(containerId) { | |
| const container = document.getElementById(containerId); | |
| if (container) { | |
| const newInputGroup = document.createElement('div'); | |
| newInputGroup.className = 'color-input-group'; | |
| newInputGroup.innerHTML = ` | |
| <input type="text" name="colors" placeholder="Новый цвет/вариант"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> | |
| `; | |
| container.appendChild(newInputGroup); | |
| const newInput = newInputGroup.querySelector('input[name="colors"]'); | |
| if (newInput) { | |
| newInput.focus(); | |
| } | |
| } | |
| } | |
| function removeColorInput(button) { | |
| const group = button.closest('.color-input-group'); | |
| if (group) { | |
| const container = group.parentNode; | |
| group.remove(); | |
| } else { | |
| console.warn("Could not find parent .color-input-group for remove button"); | |
| } | |
| } | |
| function addPriceInput(containerId) { | |
| const container = document.getElementById(containerId); | |
| if (container) { | |
| const newInputGroup = document.createElement('div'); | |
| newInputGroup.className = 'price-input-group'; | |
| newInputGroup.innerHTML = ` | |
| <label>Тип:</label> | |
| <input type="text" name="price_types" placeholder="шт, упаковка, блок..."> | |
| <label>Цена:</label> | |
| <input type="number" name="price_values" step="0.01" min="0"> | |
| <button type="button" class="remove-price-btn" onclick="removePriceInput(this)"><i class="fas fa-times"></i></button> | |
| `; | |
| container.appendChild(newInputGroup); | |
| const typeInput = newInputGroup.querySelector('input[name="price_types"]'); | |
| if (typeInput) { | |
| typeInput.focus(); | |
| } | |
| } | |
| } | |
| function removePriceInput(button) { | |
| const group = button.closest('.price-input-group'); | |
| if (group) { | |
| const container = group.parentNode; | |
| if (container.children.length <= 1) { | |
| alert("Должен быть указан хотя бы один вариант цены."); | |
| return; | |
| } | |
| group.remove(); | |
| } else { | |
| console.warn("Could not find parent .price-input-group for remove button"); | |
| } | |
| } | |
| document.addEventListener('DOMContentLoaded', () => { | |
| const addPriceInputsDiv = document.getElementById('add-price-inputs'); | |
| if(addPriceInputsDiv && addPriceInputsDiv.children.length === 0) { | |
| addPriceInput('add-price-inputs'); | |
| } | |
| const addCatSelect = document.getElementById('add_category'); | |
| if (addCatSelect) { | |
| updateSubcategorySelect('add_category', 'add_subcategory'); | |
| addCatSelect.addEventListener('change', () => updateSubcategorySelect('add_category', 'add_subcategory')); | |
| } | |
| document.querySelectorAll('select[id^="edit_category_"]').forEach(catSelect => { | |
| const productId = catSelect.id.split('_').pop(); | |
| const formContainer = document.getElementById(`edit-form-${productId}`); | |
| if (formContainer && formContainer.style.display === 'block') { | |
| const initialSubcategory = catSelect.getAttribute('data-initial-subcategory'); | |
| updateSubcategorySelect(catSelect.id, `edit_subcategory_${productId}`, initialSubcategory); | |
| } | |
| catSelect.addEventListener('change', () => updateSubcategorySelect(catSelect.id, `edit_subcategory_${productId}`)); | |
| }); | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| def catalog(): | |
| data = load_data() | |
| all_products = data.get('products', []) | |
| categories_data = data.get('categories', []) | |
| 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_data=categories_data, | |
| repo_id=REPO_ID, | |
| store_address=STORE_ADDRESS, | |
| currency_code=CURRENCY_CODE | |
| ) | |
| def product_detail(product_id): | |
| data = load_data() | |
| all_products = data.get('products', []) | |
| product = next((p for p in all_products if p.get('id') == product_id), None) | |
| if not product or not product.get('in_stock', True): | |
| logging.warning(f"Attempted access to non-existent or out-of-stock product with ID {product_id}") | |
| return "Товар не найден или отсутствует в наличии.", 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'] | |
| total_price = 0 | |
| processed_cart = [] | |
| for item in cart_items: | |
| # Check required fields including product_id | |
| if not all(k in item for k in ('name', 'price_value', 'quantity', 'price_type', 'product_id')): | |
| logging.error(f"Invalid cart item structure received (missing required keys): {item}") | |
| return jsonify({"error": "Неверный формат товара в корзине."}), 400 | |
| try: | |
| price_value = float(item['price_value']) | |
| quantity = int(item['quantity']) | |
| price_type = item.get('price_type', 'шт') | |
| name = item['name'] | |
| color = item.get('color', 'N/A') | |
| photo = item.get('photo') | |
| product_id = item.get('product_id') | |
| if price_value < 0 or quantity <= 0: | |
| raise ValueError("Invalid price or quantity") | |
| total_price += price_value * quantity | |
| processed_cart.append({ | |
| "product_id": product_id, | |
| "name": name, | |
| "price_type": price_type, | |
| "price_value": round(price_value, 2), | |
| "quantity": quantity, | |
| "color": color, | |
| "photo": photo, | |
| "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{photo}" if photo else "https://via.placeholder.com/60x60.png?text=N/A" | |
| }) | |
| except (ValueError, TypeError) as e: | |
| logging.error(f"Invalid price_value/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), | |
| "user_info": None, | |
| "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 (anonymously).") | |
| 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, | |
| whatsapp_number=WHATSAPP_NUMBER) | |
| def admin(): | |
| data = load_data() | |
| products = data.get('products', []) | |
| categories = data.get('categories', []) | |
| if 'orders' not in data or not isinstance(data.get('orders'), dict): | |
| data['orders'] = {} | |
| 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 not any(c['name'] == category_name for c in categories): | |
| categories.append({'name': category_name, 'subcategories': []}) | |
| 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 == 'add_subcategory': | |
| parent_category_name = request.form.get('parent_category_name') | |
| subcategory_name = request.form.get('subcategory_name', '').strip() | |
| parent_cat = next((c for c in categories if c['name'] == parent_category_name), None) | |
| if parent_cat and subcategory_name: | |
| if subcategory_name not in parent_cat['subcategories']: | |
| parent_cat['subcategories'].append(subcategory_name) | |
| save_data(data) | |
| flash(f"Подкатегория '{subcategory_name}' добавлена в '{parent_category_name}'.", 'success') | |
| else: | |
| flash(f"Подкатегория '{subcategory_name}' уже существует в этой категории.", 'error') | |
| else: | |
| flash("Неверное название категории или подкатегории.", 'error') | |
| elif action == 'delete_category': | |
| category_to_delete = request.form.get('category_name') | |
| subcategory_to_delete = request.form.get('subcategory_name') | |
| if subcategory_to_delete and category_to_delete: | |
| parent_cat = next((c for c in categories if c['name'] == category_to_delete), None) | |
| if parent_cat and subcategory_to_delete in parent_cat['subcategories']: | |
| parent_cat['subcategories'].remove(subcategory_to_delete) | |
| updated_count = 0 | |
| for product in products: | |
| if product.get('category') == category_to_delete and product.get('subcategory') == subcategory_to_delete: | |
| product['subcategory'] = 'Без подкатегории' | |
| updated_count += 1 | |
| save_data(data) | |
| flash(f"Подкатегория '{subcategory_to_delete}' из '{category_to_delete}' удалена. {updated_count} товаров обновлено.", 'success') | |
| else: | |
| flash(f"Не удалось найти подкатегорию '{subcategory_to_delete}' в '{category_to_delete}'.", 'error') | |
| elif category_to_delete and not subcategory_to_delete: | |
| if any(c['name'] == category_to_delete for c in categories): | |
| data['categories'] = [c for c in categories if c['name'] != category_to_delete] | |
| categories = data['categories'] | |
| updated_count = 0 | |
| for product in products: | |
| if product.get('category') == category_to_delete: | |
| product['category'] = 'Без категории' | |
| product['subcategory'] = 'Без подкатегории' | |
| updated_count += 1 | |
| data['products'] = products | |
| save_data(data) | |
| flash(f"Главная категория '{category_to_delete}' удалена. {updated_count} товаров обновлено.", 'success') | |
| else: | |
| flash(f"Не удалось найти главную категорию '{category_to_delete}'.", 'error') | |
| else: | |
| flash("Неверное действие удаления категории/подкатегории.", 'error') | |
| elif action == 'add_product': | |
| name = request.form.get('name', '').strip() | |
| description = request.form.get('description', '').strip() | |
| category = request.form.get('category') | |
| subcategory = request.form.get('subcategory', 'Без подкатегории').strip() | |
| photos_files = request.files.getlist('photos') | |
| colors = [c.strip() for c in request.form.getlist('colors') if c.strip()] | |
| in_stock = 'in_stock' in request.form | |
| is_top = 'is_top' in request.form | |
| price_types = request.form.getlist('price_types') | |
| price_values_str = request.form.getlist('price_values') | |
| prices = [] | |
| valid_prices_exist = False | |
| for type_str, value_str in zip(price_types, price_values_str): | |
| type_str = type_str.strip() | |
| value_str = value_str.strip().replace(',', '.') | |
| if not type_str or not value_str: | |
| continue | |
| try: | |
| price_value = round(float(value_str), 2) | |
| if price_value >= 0: | |
| prices.append({'type': type_str, 'value': price_value}) | |
| valid_prices_exist = True | |
| except ValueError: | |
| logging.warning(f"Skipping invalid price value '{value_str}' for type '{type_str}' during add product.") | |
| if not name: | |
| flash("Название товара обязательно.", 'error') | |
| return redirect(url_for('admin')) | |
| if not valid_prices_exist: | |
| flash("Должен быть указан хотя бы один действительный вариант цены (Тип и Цена > 0).", 'error') | |
| return redirect(url_for('admin')) | |
| if category != 'Без категории' and not any(c['name'] == category for c in categories): | |
| category = 'Без категории' | |
| subcategory = 'Без подкатегории' | |
| flash("Выбранная категория не найдена. Установлено 'Без категории'.", 'warning') | |
| 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': uuid.uuid4().hex, # Assigning stable ID here | |
| 'name': name, 'prices': prices, 'description': description, | |
| 'category': category, 'subcategory': subcategory, | |
| 'photos': photos_list, 'colors': colors, | |
| 'in_stock': in_stock, 'is_top': is_top | |
| } | |
| products.append(new_product) | |
| data['products'] = products | |
| save_data(data) | |
| logging.info(f"Product '{name}' added with ID {new_product['id']}.") | |
| flash(f"Товар '{name}' успешно добавлен.", 'success') | |
| elif action == 'edit_product': | |
| product_id = request.form.get('product_id') | |
| 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"Product with ID '{product_id}' not found 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() | |
| product_to_edit['description'] = request.form.get('description', product_to_edit.get('description', '')).strip() | |
| new_category = request.form.get('category') | |
| new_subcategory = request.form.get('subcategory', 'Без подкатегории').strip() | |
| if new_category != 'Без категории' and not any(c['name'] == new_category for c in categories): | |
| new_category = 'Без категории' | |
| new_subcategory = 'Без подкатегории' | |
| flash("Выбранная категория не найдена. Установлено 'Без категории' и 'Без подкатегории'.", 'warning') | |
| product_to_edit['category'] = new_category | |
| product_to_edit['subcategory'] = new_subcategory | |
| product_to_edit['colors'] = [c.strip() for c in request.form.getlist('colors') if c.strip()] | |
| product_to_edit['in_stock'] = 'in_stock' in request.form | |
| product_to_edit['is_top'] = 'is_top' in request.form | |
| price_types = request.form.getlist('price_types') | |
| price_values_str = request.form.getlist('price_values') | |
| edited_prices = [] | |
| valid_prices_exist = False | |
| for type_str, value_str in zip(price_types, price_values_str): | |
| type_str = type_str.strip() | |
| value_str = value_str.strip().replace(',', '.') | |
| if not type_str or not value_str: | |
| continue | |
| try: | |
| price_value = round(float(value_str), 2) | |
| if price_value >= 0: | |
| edited_prices.append({'type': type_str, 'value': price_value}) | |
| valid_prices_exist = True | |
| except ValueError: | |
| logging.warning(f"Skipping invalid price value '{value_str}' for type '{type_str}' during edit of product {original_name}.") | |
| if not valid_prices_exist: | |
| logging.warning(f"No valid prices provided during edit for product {original_name}. Prices not updated.") | |
| flash(f"Не указан ни один действительный вариант цены (Тип и Цена > 0) для товара '{product_to_edit['name']}'. Цены не изменены.", 'warning') | |
| else: | |
| product_to_edit['prices'] = edited_prices | |
| 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: | |
| 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 during edit: {photo.filename}") | |
| flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning") | |
| 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) | |
| logging.info(f"Uploading new photo {photo_filename} to HF...") | |
| api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}", | |
| repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, | |
| commit_message=f"Update photo for product {product_to_edit['name']}") | |
| new_photos_list.append(photo_filename) | |
| logging.info(f"New photo {photo_filename} uploaded successfully.") | |
| os.remove(temp_path) | |
| uploaded_count += 1 | |
| except Exception as e: | |
| logging.error(f"Error uploading new photo {photo.filename}: {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 editing 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}") | |
| if new_photos_list: | |
| logging.info(f"New photo list for product {product_to_edit['name']} generated.") | |
| old_photos = product_to_edit.get('photos', []) | |
| if old_photos: | |
| logging.info(f"Attempting to delete old photos: {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']}" | |
| ) | |
| logging.info(f"Old photos for product {product_to_edit['name']} deleted from HF.") | |
| except Exception as e: | |
| logging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True) | |
| flash("Не удалось удалить старые фотографии с сервера. Новые фото загружены.", "warning") | |
| product_to_edit['photos'] = new_photos_list | |
| flash("Фотографии товара успешно обновлены.", "success") | |
| elif uploaded_count == 0 and any(f.filename for f in photos_files): | |
| flash("Не удалось загрузить новые фотографии (возможно, неверный формат).", "error") | |
| elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files): | |
| flash("HF_TOKEN (write) не настроен. Фотографии не были обновлены.", "warning") | |
| 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_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"Product with ID '{product_id}' not found for deletion.") | |
| return redirect(url_for('admin')) | |
| deleted_product = products.pop(product_index) | |
| product_name = deleted_product.get('name', 'N/A') | |
| photos_to_delete = deleted_product.get('photos', []) | |
| if photos_to_delete and HF_TOKEN_WRITE: | |
| logging.info(f"Attempting to delete photos for product '{product_name}' from HF: {photos_to_delete}") | |
| 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}" | |
| ) | |
| logging.info(f"Photos for product '{product_name}' deleted from HF.") | |
| except Exception as e: | |
| logging.error(f"Error deleting photos {photos_to_delete} for product '{product_name}' from HF: {e}", exc_info=True) | |
| flash(f"Не удалось удалить фото для товара '{product_name}' с сервера. Товар удален локально.", "warning") | |
| elif photos_to_delete and not HF_TOKEN_WRITE: | |
| logging.warning(f"HF_TOKEN (write) not set. Cannot delete photos {photos_to_delete} for deleted product '{product_name}'.") | |
| flash(f"Товар '{product_name}' удален локально, но фото не удалены с сервера (токен не задан).", "warning") | |
| data['products'] = products | |
| save_data(data) | |
| logging.info(f"Product '{product_name}' (ID {product_id}) deleted.") | |
| flash(f"Товар '{product_name}' удален.", 'success') | |
| else: | |
| logging.warning(f"Received unknown admin action: {action}") | |
| flash(f"Неизвестное действие: {action}", 'warning') | |
| return redirect(url_for('admin')) | |
| except Exception as e: | |
| logging.error(f"Произошла внутренняя ошибка при выполнении действия '{action}': {e}", exc_info=True) | |
| flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'. Подробности в логе сервера.", 'error') | |
| return redirect(url_for('admin')) | |
| current_data = load_data() | |
| display_products = sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower()) | |
| display_categories_data = current_data.get('categories', []) | |
| return render_template_string( | |
| ADMIN_TEMPLATE, | |
| products=display_products, | |
| categories_data=display_categories_data, | |
| 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) | |