Spaces:
Sleeping
Sleeping
| 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 | |
| import hmac | |
| import hashlib | |
| from urllib.parse import unquote, parse_qs | |
| load_dotenv() | |
| app = Flask(__name__) | |
| app.secret_key = 'your_unique_secret_key_soola_cosmetics_67890_no_login' | |
| DATA_FILE = 'data.json' | |
| USERS_DATA_FILE = 'users.json' | |
| SYNC_FILES = [DATA_FILE, USERS_DATA_FILE] | |
| REPO_ID = "Kgshop/aiocult" | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN") | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") | |
| BOT_TOKEN = "8337420753:AAEEAIp7k-UL49Tli5-Q6DMSN2OunB3H_CA" | |
| STORE_ADDRESS = " Алматы, «Байсат» 1 этаж, синий сектор 117-118 Бутик " | |
| CURRENCY_CODE = 'TON' | |
| CURRENCY_NAME = 'Toncoin' | |
| DOWNLOAD_RETRIES = 3 | |
| DOWNLOAD_DELAY = 5 | |
| STATUS_MAP_RU = { | |
| "new": "Новый", | |
| "paid": "Оплачен", | |
| "accepted": "Принят", | |
| "prepared": "Собран", | |
| "shipped": "Отправлен" | |
| } | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY): | |
| if not HF_TOKEN_READ and not HF_TOKEN_WRITE: | |
| logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.") | |
| token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE | |
| files_to_download = [specific_file] if specific_file else SYNC_FILES | |
| logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...") | |
| all_successful = True | |
| for file_name in files_to_download: | |
| success = False | |
| for attempt in range(retries + 1): | |
| try: | |
| logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...") | |
| local_path = hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=file_name, | |
| repo_type="dataset", | |
| token=token_to_use, | |
| local_dir=".", | |
| local_dir_use_symlinks=False, | |
| force_download=True, | |
| resume_download=False | |
| ) | |
| logging.info(f"Successfully downloaded {file_name} to {local_path}.") | |
| success = True | |
| break | |
| except RepositoryNotFoundError: | |
| logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.") | |
| return False | |
| except HfHubHTTPError as e: | |
| if e.response.status_code == 404: | |
| logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.") | |
| if attempt == 0 and not os.path.exists(file_name): | |
| try: | |
| if file_name == DATA_FILE: | |
| with open(file_name, 'w', encoding='utf-8') as f: | |
| json.dump({'products': [], 'categories': [], 'orders': {}, 'settings': {'ton_wallet_address': ''}}, f) | |
| logging.info(f"Created empty local file {file_name} because it was not found on HF.") | |
| elif file_name == USERS_DATA_FILE: | |
| with open(file_name, 'w', encoding='utf-8') as f: | |
| json.dump([], f) | |
| logging.info(f"Created empty local file {file_name} because it was not found on HF.") | |
| except Exception as create_e: | |
| logging.error(f"Failed to create empty local file {file_name}: {create_e}") | |
| success = False | |
| break | |
| else: | |
| logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") | |
| except requests.exceptions.RequestException as e: | |
| logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") | |
| except Exception as e: | |
| logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True) | |
| if attempt < retries: | |
| time.sleep(delay) | |
| if not success: | |
| logging.error(f"Failed to download {file_name} after {retries + 1} attempts.") | |
| all_successful = False | |
| logging.info(f"Download process finished. Overall success: {all_successful}") | |
| return all_successful | |
| def upload_db_to_hf(specific_file=None): | |
| if not HF_TOKEN_WRITE: | |
| logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.") | |
| return | |
| try: | |
| api = HfApi() | |
| files_to_upload = [specific_file] if specific_file else SYNC_FILES | |
| logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...") | |
| for file_name in files_to_upload: | |
| if os.path.exists(file_name): | |
| try: | |
| api.upload_file( | |
| path_or_fileobj=file_name, | |
| path_in_repo=file_name, | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" | |
| ) | |
| logging.info(f"File {file_name} successfully uploaded to Hugging Face.") | |
| except Exception as e: | |
| logging.error(f"Error uploading file {file_name} to Hugging Face: {e}") | |
| else: | |
| logging.warning(f"File {file_name} not found locally, skipping upload.") | |
| logging.info("Finished uploading files to HF.") | |
| except Exception as e: | |
| logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True) | |
| def periodic_backup(): | |
| backup_interval = 1800 | |
| logging.info(f"Setting up periodic backup every {backup_interval} seconds.") | |
| while True: | |
| time.sleep(backup_interval) | |
| logging.info("Starting periodic backup...") | |
| upload_db_to_hf() | |
| logging.info("Periodic backup finished.") | |
| def load_data(): | |
| default_data = {'products': [], 'categories': [], 'orders': {}, 'settings': {'ton_wallet_address': ''}} | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info(f"Local data loaded successfully from {DATA_FILE}") | |
| if not isinstance(data, dict): | |
| logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.") | |
| raise FileNotFoundError | |
| if 'products' not in data: data['products'] = [] | |
| if 'categories' not in data: data['categories'] = [] | |
| if 'orders' not in data: data['orders'] = {} | |
| if 'settings' not in data: data['settings'] = {'ton_wallet_address': ''} | |
| return data | |
| except FileNotFoundError: | |
| logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.") | |
| except json.JSONDecodeError: | |
| logging.error(f"Error decoding JSON in local {DATA_FILE}. File might be corrupt. Attempting download.") | |
| if download_db_from_hf(specific_file=DATA_FILE): | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info(f"Data loaded successfully from {DATA_FILE} after download.") | |
| if not isinstance(data, dict): | |
| logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.") | |
| return default_data | |
| if 'products' not in data: data['products'] = [] | |
| if 'categories' not in data: data['categories'] = [] | |
| if 'orders' not in data: data['orders'] = {} | |
| if 'settings' not in data: data['settings'] = {'ton_wallet_address': ''} | |
| return data | |
| except FileNotFoundError: | |
| logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.") | |
| return default_data | |
| except json.JSONDecodeError: | |
| logging.error(f"Error decoding JSON in downloaded {DATA_FILE}. Using default.") | |
| return default_data | |
| except Exception as e: | |
| logging.error(f"Unknown error loading downloaded {DATA_FILE}: {e}. Using default.", exc_info=True) | |
| return default_data | |
| else: | |
| logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.") | |
| if not os.path.exists(DATA_FILE): | |
| try: | |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: | |
| json.dump(default_data, f) | |
| logging.info(f"Created empty local file {DATA_FILE} after failed download.") | |
| except Exception as create_e: | |
| logging.error(f"Failed to create empty local file {DATA_FILE}: {create_e}") | |
| return default_data | |
| def save_data(data): | |
| try: | |
| if not isinstance(data, dict): | |
| logging.error("Attempted to save invalid data structure (not a dict). Aborting save.") | |
| return | |
| if 'products' not in data: data['products'] = [] | |
| if 'categories' not in data: data['categories'] = [] | |
| if 'orders' not in data: data['orders'] = {} | |
| if 'settings' not in data: data['settings'] = {'ton_wallet_address': ''} | |
| 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) | |
| def load_users(): | |
| default_users = {} | |
| try: | |
| with open(USERS_DATA_FILE, 'r', encoding='utf-8') as file: | |
| users_list = json.load(file) | |
| if not isinstance(users_list, list): | |
| raise json.JSONDecodeError("Users file is not a list", "", 0) | |
| logging.info(f"Local users loaded successfully from {USERS_DATA_FILE}") | |
| return {str(user['id']): user for user in users_list} | |
| except FileNotFoundError: | |
| logging.warning(f"Local file {USERS_DATA_FILE} not found. Attempting download from HF.") | |
| except json.JSONDecodeError: | |
| logging.error(f"Error decoding JSON in local {USERS_DATA_FILE}. File might be corrupt. Attempting download.") | |
| if download_db_from_hf(specific_file=USERS_DATA_FILE): | |
| try: | |
| with open(USERS_DATA_FILE, 'r', encoding='utf-8') as file: | |
| users_list = json.load(file) | |
| if not isinstance(users_list, list): | |
| logging.error(f"Downloaded {USERS_DATA_FILE} is not a list. Using default.") | |
| return default_users | |
| logging.info(f"Users loaded successfully from {USERS_DATA_FILE} after download.") | |
| return {str(user['id']): user for user in users_list} | |
| except FileNotFoundError: | |
| logging.error(f"File {USERS_DATA_FILE} still not found after download. Using default.") | |
| return default_users | |
| except json.JSONDecodeError: | |
| logging.error(f"Error decoding JSON in downloaded {USERS_DATA_FILE}. Using default.") | |
| return default_users | |
| except Exception as e: | |
| logging.error(f"Unknown error loading downloaded {USERS_DATA_FILE}: {e}. Using default.", exc_info=True) | |
| return default_users | |
| else: | |
| logging.error(f"Failed to download {USERS_DATA_FILE} from HF. Using empty default.") | |
| if not os.path.exists(USERS_DATA_FILE): | |
| try: | |
| with open(USERS_DATA_FILE, 'w', encoding='utf-8') as f: | |
| json.dump([], f) | |
| logging.info(f"Created empty local file {USERS_DATA_FILE} after failed download.") | |
| except Exception as create_e: | |
| logging.error(f"Failed to create empty local file {USERS_DATA_FILE}: {create_e}") | |
| return default_users | |
| def save_users(users_data): | |
| try: | |
| if not isinstance(users_data, dict): | |
| logging.error("Attempted to save invalid users data (not a dict). Aborting save.") | |
| return | |
| users_list = list(users_data.values()) | |
| with open(USERS_DATA_FILE, 'w', encoding='utf-8') as file: | |
| json.dump(users_list, file, ensure_ascii=False, indent=4) | |
| logging.info(f"Users data successfully saved to {USERS_DATA_FILE}") | |
| upload_db_to_hf(specific_file=USERS_DATA_FILE) | |
| except Exception as e: | |
| logging.error(f"Error saving users data to {USERS_DATA_FILE}: {e}", exc_info=True) | |
| def broadcast_new_product_notification(product, base_url): | |
| users = load_users() | |
| if not users: | |
| return | |
| text = ( | |
| f"🎉 <b>Новый товар в каталоге!</b> 👋\n\n" | |
| f"<b>{product['name']}</b>\n" | |
| f"Цена: {product['price']:.4f} {CURRENCY_CODE}\n\n" | |
| f"Посмотрите его в каталоге:\n{base_url}" | |
| ) | |
| url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage" | |
| params_base = { | |
| "text": text, | |
| "parse_mode": "HTML" | |
| } | |
| for user_id in users.keys(): | |
| params = params_base.copy() | |
| params["chat_id"] = user_id | |
| try: | |
| response = requests.get(url, params=params) | |
| result = response.json() | |
| if result.get("ok"): | |
| logging.info(f"Sent notification to {user_id}") | |
| else: | |
| logging.error(f"Error {user_id}: {result.get('description')}") | |
| except Exception as e: | |
| logging.error(f"Ex {user_id}: {e}") | |
| 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> | |
| <script src="https://telegram.org/js/telegram-web-app.js"></script> | |
| <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=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css"> | |
| <style> | |
| :root { | |
| --primary-color: #007AFF; | |
| --primary-dark: #0056b3; | |
| --surface-color: #FFFFFF; | |
| --surface-dark: #21252B; | |
| --background-color: #F0F2F5; | |
| --background-dark: #1E2124; | |
| --text-color: #1A1A1A; | |
| --text-color-dark: #E0E0E0; | |
| --border-color: #E0E0E0; | |
| --border-color-dark: #3A3A3A; | |
| } | |
| * { margin: 0; padding: 0; box-sizing: border-box; } | |
| body { font-family: 'Roboto', sans-serif; background: var(--background-color); color: var(--text-color); line-height: 1.5; transition: all 0.3s; } | |
| body.dark-mode { background: var(--background-dark); color: var(--text-color-dark); } | |
| .container { max-width: 100%; margin: 0 auto; padding: 0; } | |
| .content-area { padding: 15px; } | |
| .header { display: flex; justify-content: space-between; align-items: center; padding: 10px 15px; background: var(--surface-color); border-bottom: 1px solid var(--border-color); box-shadow: 0 1px 3px rgba(0,0,0,0.05); } | |
| body.dark-mode .header { background: var(--surface-dark); border-bottom-color: var(--border-color-dark); } | |
| .header h1 { font-size: 1.4rem; font-weight: 500; color: var(--primary-color); } | |
| .logo-title-container img { height: 35px; width: 35px; border-radius: 50%; object-fit: cover; box-shadow: 0 0 5px rgba(0, 122, 255, 0.5); } | |
| .theme-toggle { background: none; border: none; font-size: 1.3rem; cursor: pointer; color: var(--primary-color); padding: 5px; } | |
| .theme-toggle:hover { opacity: 0.8; } | |
| .store-address { padding: 12px 15px; text-align: center; background-color: var(--surface-color); border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); font-size: 0.9rem; color: #555; margin: 15px; } | |
| body.dark-mode .store-address { background-color: var(--surface-dark); color: var(--text-color-dark); box-shadow: 0 1px 3px rgba(255,255,255,0.1); } | |
| .search-container { padding: 0 15px 15px; } | |
| #search-input { width: 100%; padding: 10px 15px; font-size: 1rem; border: 1px solid var(--border-color); border-radius: 20px; outline: none; transition: all 0.3s; background-color: var(--surface-color); color: var(--text-color); } | |
| body.dark-mode #search-input { background-color: var(--surface-dark); border-color: var(--border-color-dark); color: var(--text-color-dark); } | |
| #search-input:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.2); } | |
| .filters-container { margin: 0 15px 15px; display: flex; overflow-x: auto; gap: 8px; padding-bottom: 5px; scrollbar-width: none; } | |
| .filters-container::-webkit-scrollbar { display: none; } | |
| .category-filter { padding: 8px 14px; border: 1px solid var(--border-color); border-radius: 20px; background-color: var(--surface-color); cursor: pointer; transition: all 0.2s ease; font-size: 0.85rem; font-weight: 400; color: #555; white-space: nowrap; } | |
| body.dark-mode .category-filter { background-color: var(--surface-dark); border-color: var(--border-color-dark); color: var(--text-color-dark); } | |
| .category-filter.active, .category-filter:hover { background-color: var(--primary-color); color: white; border-color: var(--primary-color); box-shadow: 0 2px 5px rgba(0, 122, 255, 0.3); } | |
| .products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; padding: 10px 15px 70px; } | |
| @media (min-width: 600px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 15px; } } | |
| .product { background: var(--surface-color); border-radius: 12px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); transition: transform 0.2s ease, box-shadow 0.2s ease; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; height: 100%; position: relative; } | |
| body.dark-mode .product { background: var(--surface-dark); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); } | |
| .product:active { transform: scale(0.98); } | |
| .product-image { width: 100%; aspect-ratio: 1 / 1; background-color: var(--surface-color); display: flex; justify-content: center; align-items: center; padding: 10px; } | |
| .product-image img { max-width: 100%; max-height: 100%; object-fit: contain; } | |
| .product-info { padding: 10px; flex-grow: 1; display: flex; flex-direction: column; justify-content: center; } | |
| .product h2 { font-size: 0.95rem; font-weight: 500; margin: 0 0 5px 0; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-color); } | |
| body.dark-mode .product h2 { color: var(--text-color-dark); } | |
| .product-price { font-size: 1.1rem; color: var(--primary-color); font-weight: 700; text-align: center; margin: 5px 0; } | |
| .product-description { display: none; } | |
| .product-actions { padding: 0 10px 10px 10px; display: flex; flex-direction: column; gap: 6px; } | |
| .product-button { display: block; width: 100%; padding: 8px; border: none; border-radius: 8px; background-color: var(--primary-color); color: white; font-size: 0.85rem; font-weight: 500; cursor: pointer; transition: all 0.2s ease; text-align: center; text-decoration: none; } | |
| .product-button:hover { background-color: var(--primary-dark); } | |
| .product-button i { margin-right: 5px; } | |
| #cart-button { position: fixed; bottom: 15px; right: 15px; background-color: var(--primary-color); color: white; border: none; border-radius: 50%; width: 50px; height: 50px; font-size: 1.3rem; cursor: pointer; display: none; align-items: center; justify-content: center; box-shadow: 0 4px 10px rgba(0, 122, 255, 0.4); z-index: 1000; } | |
| #cart-button span { position: absolute; top: -5px; right: -5px; background-color: #FF3B30; color: white; border-radius: 50%; padding: 2px 6px; font-size: 0.7rem; font-weight: bold; min-width: 20px; text-align: center; } | |
| #install-button { position: fixed; bottom: 80px; right: 15px; background-color: #34C759; color: white; border: none; border-radius: 50%; width: 50px; height: 50px; font-size: 1.3rem; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 10px rgba(52, 199, 89, 0.4); z-index: 999; } | |
| #install-button:hover { background-color: #2da84e; } | |
| .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); backdrop-filter: blur(5px); overflow-y: auto; } | |
| .modal-content { background: var(--surface-color); margin: 5% auto; padding: 20px; border-radius: 12px; width: 95%; max-width: 600px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); animation: slideIn 0.3s ease-out; position: relative; } | |
| body.dark-mode .modal-content { background: var(--surface-dark); color: var(--text-color-dark); } | |
| @keyframes slideIn { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } } | |
| .close { position: absolute; top: 10px; right: 15px; font-size: 1.8rem; color: #aaa; cursor: pointer; transition: color 0.3s; line-height: 1; } | |
| .close:hover { color: var(--primary-color); } | |
| body.dark-mode .close { color: var(--text-color-dark); } | |
| body.dark-mode .close:hover { color: var(--primary-color); } | |
| .modal-content h2 { margin-top: 0; margin-bottom: 20px; color: var(--primary-color); font-size: 1.5rem; display: flex; align-items: center; gap: 10px;} | |
| .cart-item { display: grid; grid-template-columns: 60px 1fr auto 20px; gap: 10px; align-items: center; padding: 10px 0; border-bottom: 1px solid var(--border-color); } | |
| body.dark-mode .cart-item { border-bottom-color: var(--border-color-dark); } | |
| .cart-item:last-child { border-bottom: none; } | |
| .cart-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 6px; background-color: var(--surface-color); padding: 5px; } | |
| .cart-item-details { grid-column: 2; } | |
| .cart-item-details strong { display: block; margin-bottom: 3px; font-size: 1rem; } | |
| .cart-item-price { font-size: 0.85rem; color: #777; } | |
| body.dark-mode .cart-item-price { color: #aaa; } | |
| .cart-item-total { font-weight: bold; text-align: right; grid-column: 3; font-size: 0.95rem;} | |
| .cart-item-remove { background:none; border:none; color:#FF3B30; cursor:pointer; font-size: 1.2em; padding: 5px; line-height: 1; } | |
| .quantity-input, .color-select, .model-select { width: 100%; padding: 10px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 1rem; margin-top: 5px; margin-bottom: 15px; box-sizing: border-box; background-color: var(--surface-color); color: var(--text-color); } | |
| body.dark-mode .quantity-input, body.dark-mode .color-select, body.dark-mode .model-select { background-color: var(--background-dark); border-color: var(--border-color-dark); color: var(--text-color-dark); } | |
| .cart-summary { margin-top: 20px; text-align: right; border-top: 1px solid var(--border-color); padding-top: 15px; } | |
| body.dark-mode .cart-summary { border-top-color: var(--border-color-dark); } | |
| .cart-summary strong { font-size: 1.2rem; color: var(--primary-color); } | |
| .cart-actions { margin-top: 20px; display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; } | |
| .cart-actions .product-button { flex-grow: 1; padding: 10px; } | |
| .clear-cart { background-color: #aaa; } | |
| .clear-cart:hover { background-color: #888; } | |
| .formulate-order-button { background-color: var(--primary-color); } | |
| .formulate-order-button:hover { background-color: var(--primary-dark); } | |
| .notification { position: fixed; bottom: 70px; left: 50%; transform: translateX(-50%); background-color: var(--primary-color); 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: #aaa; } | |
| .top-product-indicator { position: absolute; top: 5px; right: 5px; background-color: rgba(255, 193, 7, 0.9); color: #333; padding: 2px 6px; font-size: 0.7rem; border-radius: 4px; font-weight: bold; z-index: 10; } | |
| .instruction-step { display: flex; align-items: center; gap: 15px; margin-bottom: 20px; background: rgba(0,0,0,0.03); padding: 15px; border-radius: 10px; } | |
| body.dark-mode .instruction-step { background: rgba(255,255,255,0.05); } | |
| .instruction-icon { font-size: 1.8rem; color: var(--primary-color); width: 40px; text-align: center; display: flex; justify-content: center; align-items: center; } | |
| .instruction-text { font-size: 1rem; flex-grow: 1; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <div class="logo-title-container" style="display: flex; align-items: center; gap: 10px;"> | |
| <img src="https://huggingface.co/spaces/Kgshop/mobilnymir/resolve/main/IMG_20251019_120056_121.jpg" alt="Мобильный мир Logo"> | |
| <h1>Мобильный мир</h1> | |
| </div> | |
| <button class="theme-toggle" onclick="toggleTheme()" aria-label="Переключить тему"> | |
| <i class="fas fa-moon"></i> | |
| </button> | |
| </div> | |
| <div class="store-address">Наш адрес: {{ store_address }}</div> | |
| <div class="search-container"> | |
| <input type="text" id="search-input" placeholder="Поиск по названию..."> | |
| </div> | |
| <div class="filters-container"> | |
| <button class="category-filter active" data-category="all">Все категории</button> | |
| {% for category in categories %} | |
| <button class="category-filter" data-category="{{ category }}">{{ category }}</button> | |
| {% endfor %} | |
| </div> | |
| <div class="products-grid" id="products-grid"> | |
| {% for product in products %} | |
| <div class="product" | |
| data-name="{{ product['name']|lower }}" | |
| data-description="{{ product.get('description', '')|lower }}" | |
| data-category="{{ product.get('category', 'Без категории') }}"> | |
| {% if product.get('is_top', False) %} | |
| <span class="top-product-indicator"><i class="fas fa-star"></i> Топ</span> | |
| {% endif %} | |
| <div class="product-image" onclick="openModal({{ loop.index0 }})" style="cursor: pointer;"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" | |
| alt="{{ product['name'] }}" | |
| loading="lazy"> | |
| {% else %} | |
| <img src="https://via.placeholder.com/250x250.png?text=No+Image" alt="No Image" loading="lazy"> | |
| {% endif %} | |
| </div> | |
| <div class="product-info"> | |
| <h2>{{ product['name'] }}</h2> | |
| <div class="product-price">{{ "%.4f"|format(product['price']) }} {{ currency_code }}</div> | |
| <p class="product-description">{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}</p> | |
| </div> | |
| <div class="product-actions"> | |
| <button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})"> | |
| <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="quantityInput">Количество:</label> | |
| <input type="number" id="quantityInput" class="quantity-input" min="1" value="1"> | |
| <label for="colorSelect" id="colorLabel">Цвет/Вариант:</label> | |
| <select id="colorSelect" class="color-select"></select> | |
| <label for="modelSelect" id="modelLabel">Модель/Объем:</label> | |
| <select id="modelSelect" class="model-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.0000</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> | |
| <div id="installModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('installModal')" aria-label="Закрыть">×</span> | |
| <h2 style="margin-bottom: 25px;"><i class="fas fa-mobile-alt"></i> Установка приложения</h2> | |
| <div id="android-instructions" style="display: none;"> | |
| <p style="margin-bottom: 15px; font-weight: 500;">Для Android:</p> | |
| <div class="instruction-step"> | |
| <div class="instruction-icon"><i class="fas fa-ellipsis-v"></i></div> | |
| <div class="instruction-text">Нажмите на <b>три точки</b> в правом верхнем углу экрана.</div> | |
| </div> | |
| <div class="instruction-step"> | |
| <div class="instruction-icon"><i class="fas fa-plus-square"></i></div> | |
| <div class="instruction-text">Выберите <b>«Создать ярлык»</b> и <b>«Добавить на Главный экран»</b>.</div> | |
| </div> | |
| </div> | |
| <div id="ios-instructions" style="display: none;"> | |
| <p style="margin-bottom: 15px; font-weight: 500;">Для iPhone (iOS):</p> | |
| <div class="instruction-step"> | |
| <div class="instruction-icon"><i class="fas fa-share-square"></i></div> | |
| <div class="instruction-text">Нажмите кнопку <b>«Поделиться»</b> внизу экрана (квадрат со стрелкой).</div> | |
| </div> | |
| <div class="instruction-step"> | |
| <div class="instruction-icon"><i class="fas fa-plus-square"></i></div> | |
| <div class="instruction-text">Прокрутите вниз и выберите <b>«На экран "Домой"»</b>.</div> | |
| </div> | |
| </div> | |
| <div id="pc-instructions" style="display: none;"> | |
| <p style="text-align: center;">Эта функция доступна на мобильных устройствах.</p> | |
| </div> | |
| </div> | |
| </div> | |
| <button id="install-button" onclick="openInstallModal()" aria-label="Установить приложение"> | |
| <i class="fas fa-home"></i> | |
| </button> | |
| <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 }}'; | |
| let selectedProductIndex = null; | |
| let cart = JSON.parse(localStorage.getItem('soolaCart') || '[]'); | |
| function toggleTheme() { | |
| document.body.classList.toggle('dark-mode'); | |
| const icon = document.querySelector('.theme-toggle i'); | |
| const isDarkMode = document.body.classList.contains('dark-mode'); | |
| icon.classList.toggle('fa-moon', !isDarkMode); | |
| icon.classList.toggle('fa-sun', isDarkMode); | |
| localStorage.setItem('soolaTheme', isDarkMode ? 'dark' : 'light'); | |
| } | |
| function applyInitialTheme() { | |
| const savedTheme = localStorage.getItem('soolaTheme'); | |
| const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; | |
| if (savedTheme === 'dark' || (!savedTheme && prefersDark)) { | |
| document.body.classList.add('dark-mode'); | |
| const icon = document.querySelector('.theme-toggle i'); | |
| if (icon) icon.classList.replace('fa-moon', 'fa-sun'); | |
| } else { | |
| const icon = document.querySelector('.theme-toggle i'); | |
| if (icon) icon.classList.replace('fa-sun', 'fa-moon'); | |
| } | |
| } | |
| function authenticateUser() { | |
| const tg = window.Telegram.WebApp; | |
| if (tg && tg.initData) { | |
| if (sessionStorage.getItem('tma_verified')) { | |
| console.log('TMA user already verified in this session.'); | |
| return; | |
| } | |
| fetch('/verify_tma', { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| body: JSON.stringify({ initData: tg.initData }), | |
| }) | |
| .then(response => response.json()) | |
| .then(data => { | |
| if(data.status === 'ok') { | |
| console.log('TMA User Verified:', data.user); | |
| sessionStorage.setItem('tma_verified', 'true'); | |
| } else { | |
| console.error('TMA Verification Failed:', data.message); | |
| } | |
| }) | |
| .catch((error) => { | |
| console.error('Error during TMA verification:', error); | |
| }); | |
| } else { | |
| console.log("Telegram Web App data not available."); | |
| } | |
| } | |
| function getMobileOperatingSystem() { | |
| var userAgent = navigator.userAgent || navigator.vendor || window.opera; | |
| if (/android/i.test(userAgent)) { | |
| return "Android"; | |
| } | |
| if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) { | |
| return "iOS"; | |
| } | |
| return "unknown"; | |
| } | |
| function openInstallModal() { | |
| const os = getMobileOperatingSystem(); | |
| const androidInst = document.getElementById('android-instructions'); | |
| const iosInst = document.getElementById('ios-instructions'); | |
| const pcInst = document.getElementById('pc-instructions'); | |
| androidInst.style.display = 'none'; | |
| iosInst.style.display = 'none'; | |
| pcInst.style.display = 'none'; | |
| if (os === 'Android') { | |
| androidInst.style.display = 'block'; | |
| } else if (os === 'iOS') { | |
| iosInst.style.display = 'block'; | |
| } else { | |
| androidInst.style.display = 'block'; | |
| iosInst.style.display = 'block'; | |
| } | |
| const modal = document.getElementById('installModal'); | |
| if (modal) { | |
| modal.style.display = 'block'; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| } | |
| function openModal(index) { | |
| loadProductDetails(index); | |
| 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(index) { | |
| const modalContent = document.getElementById('modalContent'); | |
| if (!modalContent) return; | |
| modalContent.innerHTML = '<p style="text-align:center; padding: 40px;">Загрузка...</p>'; | |
| fetch('/product/' + index) | |
| .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: red; 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 setupVariantSelect(selectId, labelId, variants) { | |
| const select = document.getElementById(selectId); | |
| const label = document.getElementById(labelId); | |
| const validVariants = variants ? variants.filter(v => v && v.trim() !== "") : []; | |
| select.innerHTML = ''; | |
| if (validVariants.length > 0) { | |
| validVariants.forEach(variant => { | |
| const option = document.createElement('option'); | |
| option.value = variant.trim(); | |
| option.text = variant.trim(); | |
| select.appendChild(option); | |
| }); | |
| select.style.display = 'block'; | |
| if(label) label.style.display = 'block'; | |
| } else { | |
| select.style.display = 'none'; | |
| if(label) label.style.display = 'none'; | |
| } | |
| } | |
| function openQuantityModal(index) { | |
| selectedProductIndex = index; | |
| const product = products[index]; | |
| if (!product) { | |
| console.error("Product not found for index:", index); | |
| alert("Ошибка: товар не найден."); | |
| return; | |
| } | |
| setupVariantSelect('colorSelect', 'colorLabel', product.colors); | |
| setupVariantSelect('modelSelect', 'modelLabel', product.models); | |
| document.getElementById('quantityInput').value = 1; | |
| const modal = document.getElementById('quantityModal'); | |
| if(modal) { | |
| modal.style.display = 'block'; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| } | |
| function confirmAddToCart() { | |
| if (selectedProductIndex === null) return; | |
| const quantityInput = document.getElementById('quantityInput'); | |
| const quantity = parseInt(quantityInput.value); | |
| const colorSelect = document.getElementById('colorSelect'); | |
| const modelSelect = document.getElementById('modelSelect'); | |
| const color = colorSelect.style.display !== 'none' && colorSelect.value ? colorSelect.value : 'N/A'; | |
| const model = modelSelect.style.display !== 'none' && modelSelect.value ? modelSelect.value : 'N/A'; | |
| if (isNaN(quantity) || quantity <= 0) { | |
| alert("Пожалуйста, укажите корректное количество (больше 0)."); | |
| quantityInput.focus(); | |
| return; | |
| } | |
| const product = products[selectedProductIndex]; | |
| if (!product) { | |
| alert("Ошибка добавления: товар не найден."); | |
| return; | |
| } | |
| const cartItemId = `${product.name}-${color}-${model}`; | |
| const existingItemIndex = cart.findIndex(item => item.id === cartItemId); | |
| if (existingItemIndex > -1) { | |
| cart[existingItemIndex].quantity += quantity; | |
| } else { | |
| cart.push({ | |
| id: cartItemId, | |
| name: product.name, | |
| price: product.price, | |
| photo: product.photos && product.photos.length > 0 ? product.photos[0] : null, | |
| quantity: quantity, | |
| color: color, | |
| model: model | |
| }); | |
| } | |
| localStorage.setItem('soolaCart', JSON.stringify(cart)); | |
| closeModal('quantityModal'); | |
| updateCartButton(); | |
| showNotification(`${product.name} добавлен в корзину!`); | |
| } | |
| 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.0000'; | |
| } else { | |
| cartContent.innerHTML = cart.map(item => { | |
| const itemTotal = item.price * item.quantity; | |
| total += itemTotal; | |
| const photoUrl = item.photo | |
| ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` | |
| : 'https://via.placeholder.com/60x60.png?text=N/A'; | |
| let variantText = []; | |
| if (item.color !== 'N/A') variantText.push(`Цвет: ${item.color}`); | |
| if (item.model !== 'N/A') variantText.push(`Модель: ${item.model}`); | |
| const variantDisplay = variantText.length > 0 ? ` (${variantText.join(', ')})` : ''; | |
| return ` | |
| <div class="cart-item"> | |
| <img src="${photoUrl}" alt="${item.name}"> | |
| <div class="cart-item-details"> | |
| <strong>${item.name}${variantDisplay}</strong> | |
| <p class="cart-item-price">${item.price.toFixed(4)} ${currencyCode} × ${item.quantity}</p> | |
| </div> | |
| <span class="cart-item-total">${itemTotal.toFixed(4)} ${currencyCode}</span> | |
| <button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="Удалить товар">×</button> | |
| </div> | |
| `; | |
| }).join(''); | |
| cartTotalElement.textContent = total.toFixed(4); | |
| } | |
| 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('soolaCart', JSON.stringify(cart)); | |
| openCartModal(); | |
| updateCartButton(); | |
| } | |
| function clearCart() { | |
| if (confirm("Вы уверены, что хотите очистить корзину?")) { | |
| cart = []; | |
| localStorage.removeItem('soolaCart'); | |
| 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('soolaCart'); | |
| 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 grid = document.getElementById('products-grid'); | |
| let visibleProducts = 0; | |
| const existingNoResults = grid.querySelector('.no-results-message'); | |
| if (existingNoResults) existingNoResults.remove(); | |
| const allProductElements = document.querySelectorAll('.products-grid .product'); | |
| if (allProductElements.length === 0 && products.length > 0) return; | |
| document.querySelectorAll('.products-grid .product').forEach(productElement => { | |
| const name = productElement.getAttribute('data-name'); | |
| const description = productElement.getAttribute('data-description'); | |
| const category = productElement.getAttribute('data-category'); | |
| const matchesSearch = !searchTerm || name.includes(searchTerm) || description.includes(searchTerm); | |
| const matchesCategory = activeCategory === 'all' || category === activeCategory; | |
| if (matchesSearch && matchesCategory) { | |
| productElement.style.display = 'flex'; | |
| visibleProducts++; | |
| } else { | |
| productElement.style.display = 'none'; | |
| } | |
| }); | |
| if (visibleProducts === 0) { | |
| if (products.length > 0) { | |
| const p = document.createElement('p'); | |
| p.className = 'no-results-message'; | |
| p.textContent = 'По вашему запросу товары не найдены.'; | |
| grid.appendChild(p); | |
| } else if (!grid.querySelector('.no-results-message')) { | |
| const p = document.createElement('p'); | |
| p.className = 'no-results-message'; | |
| p.textContent = 'Товары пока не добавлены.'; | |
| grid.appendChild(p); | |
| } | |
| } | |
| } | |
| function setupFilters() { | |
| const searchInput = document.getElementById('search-input'); | |
| const categoryFilters = document.querySelectorAll('.category-filter'); | |
| if(searchInput) searchInput.addEventListener('input', filterProducts); | |
| categoryFilters.forEach(filter => { | |
| filter.addEventListener('click', function() { | |
| categoryFilters.forEach(f => f.classList.remove('active')); | |
| this.classList.add('active'); | |
| filterProducts(); | |
| }); | |
| }); | |
| filterProducts(); | |
| } | |
| function 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 = '70px'; | |
| 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', () => { | |
| applyInitialTheme(); | |
| updateCartButton(); | |
| setupFilters(); | |
| authenticateUser(); | |
| 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: var(--primary-color);">{{ product['name'] }}</h2> | |
| <div class="swiper-container" style="max-width: 450px; margin: 0 auto 20px; border-radius: 10px; overflow: hidden; background-color: var(--surface-color);"> | |
| <div class="swiper-wrapper"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| {% for photo in product['photos'] %} | |
| <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center; padding: 10px;"> | |
| <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: var(--primary-color);"></div> | |
| <div class="swiper-button-prev" style="color: var(--primary-color);"></div> | |
| {% endif %} | |
| </div> | |
| <div style="margin-top: 20px; font-size: 1rem; line-height: 1.7; padding: 0 10px;"> | |
| <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p> | |
| <p style="font-size: 1.2rem; font-weight: bold; color: var(--primary-color);"><strong>Цена:</strong> {{ "%.4f"|format(product['price']) }} {{ currency_code }}</p> | |
| <p><strong>Описание:</strong><br> {{ product.get('description', 'Описание отсутствует.')|replace('\\n', '<br>')|safe }}</p> | |
| {% set colors = product.get('colors', []) %} | |
| {% if colors and colors|select('ne', '')|list|length > 0 %} | |
| <p><strong>Доступные цвета/варианты:</strong> {{ colors|select('ne', '')|join(', ') }}</p> | |
| {% endif %} | |
| {% set models = product.get('models', []) %} | |
| {% if models and models|select('ne', '')|list|length > 0 %} | |
| <p><strong>Доступные модели/объемы:</strong> {{ models|select('ne', '')|join(', ') }}</p> | |
| {% endif %} | |
| </div> | |
| <div style="padding: 10px; text-align: center;"> | |
| <button class="product-button add-to-cart" onclick="openQuantityModal({{ products_index }})" style="margin-top: 15px;"> | |
| <i class="fas fa-cart-plus"></i> Добавить в корзину | |
| </button> | |
| </div> | |
| </div> | |
| <script> | |
| document.documentElement.style.setProperty('--primary-color', '#007AFF'); | |
| document.documentElement.style.setProperty('--surface-color', document.body.classList.contains('dark-mode') ? '#21252B' : '#FFFFFF'); | |
| </script> | |
| ''' | |
| 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> | |
| <script src="https://unpkg.com/@tonconnect/ui@latest/dist/tonconnect-ui.min.js"></script> | |
| <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <style> | |
| :root { | |
| --primary-color: #007AFF; | |
| --primary-dark: #0056b3; | |
| --surface-color: #FFFFFF; | |
| --background-color: #F0F2F5; | |
| --text-color: #1A1A1A; | |
| --border-color: #E0E0E0; | |
| --success-color: #34C759; | |
| --error-color: #FF3B30; | |
| } | |
| body { font-family: 'Roboto', sans-serif; background: var(--background-color); color: var(--text-color); line-height: 1.5; padding: 15px; } | |
| .container { max-width: 800px; margin: 15px auto; padding: 25px; background: var(--surface-color); border-radius: 12px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1); border: 1px solid var(--border-color); } | |
| h1 { text-align: center; color: var(--primary-color); margin-bottom: 20px; font-size: 1.6rem; font-weight: 500; } | |
| h2 { color: var(--primary-color); margin-top: 25px; margin-bottom: 12px; font-size: 1.3rem; border-bottom: 1px solid var(--border-color); padding-bottom: 5px;} | |
| .order-meta { font-size: 0.85rem; color: #888; margin-bottom: 15px; text-align: center; } | |
| .order-item { display: grid; grid-template-columns: 60px 1fr auto; gap: 15px; align-items: center; padding: 12px 0; border-bottom: 1px solid var(--border-color); } | |
| .order-item:last-child { border-bottom: none; } | |
| .order-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 6px; background-color: #f7f7f7; padding: 5px; border: 1px solid #ddd;} | |
| .item-details strong { display: block; margin-bottom: 3px; font-size: 1rem; color: var(--text-color);} | |
| .item-details span { font-size: 0.85rem; color: #555; display: block;} | |
| .item-total { font-weight: bold; text-align: right; font-size: 1rem; color: var(--primary-color);} | |
| .order-summary { margin-top: 25px; padding-top: 15px; border-top: 2px solid var(--primary-color); text-align: right; } | |
| .order-summary p { margin-bottom: 8px; font-size: 1rem; } | |
| .order-summary strong { font-size: 1.2rem; color: var(--primary-color); } | |
| .payment-section { margin-top: 25px; background-color: #e6f0ff; padding: 20px; border-radius: 8px; border: 1px solid #cce0ff; text-align: center; } | |
| .payment-section p { margin-bottom: 15px; font-size: 1rem; } | |
| .actions { margin-top: 25px; text-align: center; } | |
| .button { padding: 12px 25px; border: none; border-radius: 8px; background-color: var(--primary-color); color: white; font-weight: 500; cursor: pointer; transition: background-color 0.2s ease, opacity 0.2s ease; font-size: 1rem; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; } | |
| .button:hover { background-color: var(--primary-dark); } | |
| .button:disabled { background-color: #a0a0a0; cursor: not-allowed; opacity: 0.7; } | |
| .not-found { text-align: center; color: var(--error-color); font-size: 1.2rem; padding: 40px 0;} | |
| .ton-connect-button-container { display: flex; justify-content: center; margin-bottom: 20px; } | |
| #payment-status { margin-top: 15px; font-weight: 500; } | |
| .status-paid { color: var(--success-color); } | |
| .status-error { color: var(--error-color); } | |
| </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 }} | Статус: <strong class="{{'status-paid' if order.status == 'paid'}}">{{ status_map_ru.get(order.status, order.status) }}</strong></p> | |
| <h2><i class="fas fa-shopping-bag"></i> Товары в заказе</h2> | |
| <div id="orderItems"> | |
| {% for item in order.cart %} | |
| {% set variant_info = [] %} | |
| {% if item.color and item.color != 'N/A' %} | |
| {% set _ = variant_info.append('Цвет: ' + item.color) %} | |
| {% endif %} | |
| {% if item.model and item.model != 'N/A' %} | |
| {% set _ = variant_info.append('Модель: ' + item.model) %} | |
| {% endif %} | |
| {% set variant_display = variant_info | join(', ') %} | |
| <div class="order-item"> | |
| <img src="{{ item.photo_url }}" alt="{{ item.name }}"> | |
| <div class="item-details"> | |
| <strong>{{ item.name }}</strong> | |
| {% if variant_display %} | |
| <span>({{ variant_display }})</span> | |
| {% endif %} | |
| <span>{{ "%.4f"|format(item.price) }} {{ currency_code }} × {{ item.quantity }}</span> | |
| </div> | |
| <div class="item-total"> | |
| {{ "%.4f"|format(item.price * item.quantity) }} {{ currency_code }} | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| <div class="order-summary"> | |
| <p><strong>ИТОГО К ОПЛАТЕ: {{ "%.4f"|format(order.total_price) }} {{ currency_code }}</strong></p> | |
| </div> | |
| {% if ton_wallet_address and order.status == 'new' %} | |
| <div class="payment-section"> | |
| <h2><i class="fas fa-wallet"></i> Оплата заказа</h2> | |
| <p>Для оплаты заказа подключите ваш TON кошелек и подтвердите транзакцию.</p> | |
| <div class="ton-connect-button-container"> | |
| <div id="ton-connect-button"></div> | |
| </div> | |
| <button id="pay-button" class="button" disabled><i class="fas fa-paper-plane"></i> Оплатить {{ "%.4f"|format(order.total_price) }} TON</button> | |
| <div id="payment-status">Статус: Ожидание подключения кошелька</div> | |
| </div> | |
| {% elif order.status != 'new' %} | |
| <div class="payment-section" style="background-color: #e6ffed; border-color: #b3f4c7;"> | |
| <h2><i class="fas fa-check-circle"></i> Заказ обработан</h2> | |
| <p>Текущий статус вашего заказа: <strong>{{ status_map_ru.get(order.status, order.status) }}</strong></p> | |
| <p>Спасибо за покупку!</p> | |
| </div> | |
| {% else %} | |
| <div class="payment-section" style="background-color: #ffe6e6; border-color: #ffb3b3;"> | |
| <h2><i class="fas fa-exclamation-triangle"></i> Оплата не настроена</h2> | |
| <p>В данный момент оплата недоступна. Пожалуйста, свяжитесь с администрацией магазина.</p> | |
| </div> | |
| {% endif %} | |
| <a href="{{ url_for('catalog') }}" class="catalog-link" style="display: block; text-align: center; margin-top: 20px; color: var(--primary-color); text-decoration: none;">← Вернуться в каталог</a> | |
| {% if ton_wallet_address and order.status == 'new' %} | |
| <script> | |
| const tonConnectUI = new TON_CONNECT_UI.TonConnectUI({ | |
| manifestUrl: 'https://huggingface.co/spaces/Aleksmorshen/MorshenGroup/resolve/main/tonconnect-manifest.json', | |
| buttonRootId: 'ton-connect-button' | |
| }); | |
| const payButton = document.getElementById('pay-button'); | |
| const paymentStatus = document.getElementById('payment-status'); | |
| tonConnectUI.onStatusChange(wallet => { | |
| if (wallet) { | |
| payButton.disabled = false; | |
| paymentStatus.textContent = '✅ Кошелек подключен. Готово к оплате.'; | |
| paymentStatus.className = 'status-paid'; | |
| } else { | |
| payButton.disabled = true; | |
| paymentStatus.textContent = '❌ Кошелек не подключен.'; | |
| paymentStatus.className = 'status-error'; | |
| } | |
| }); | |
| payButton.addEventListener('click', async () => { | |
| const transaction = { | |
| validUntil: Math.floor(Date.now() / 1000) + 600, // 10 minutes | |
| messages: [ | |
| { | |
| address: '{{ ton_wallet_address }}', | |
| amount: '{{ (order.total_price * 10**9)|int }}' // nanoTONs | |
| } | |
| ] | |
| }; | |
| try { | |
| paymentStatus.textContent = 'Пожалуйста, подтвердите транзакцию в вашем кошельке...'; | |
| payButton.disabled = true; | |
| const result = await tonConnectUI.sendTransaction(transaction); | |
| paymentStatus.textContent = '✅ Транзакция отправлена! Проверяем...'; | |
| paymentStatus.className = 'status-paid'; | |
| fetch('/update_order_status_after_payment', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ order_id: '{{ order.id }}', boc: result.boc }) | |
| }) | |
| .then(response => response.json()) | |
| .then(data => { | |
| if (data.status === 'ok') { | |
| paymentStatus.innerHTML = `<strong>Оплата прошла успешно!</strong><br>Статус заказа обновлен. Перезагрузка страницы...`; | |
| setTimeout(() => window.location.reload(), 3000); | |
| } else { | |
| paymentStatus.textContent = 'Ошибка при обновлении статуса заказа на сервере.'; | |
| paymentStatus.className = 'status-error'; | |
| } | |
| }); | |
| } catch (error) { | |
| console.error(error); | |
| paymentStatus.textContent = '❌ Ошибка транзакции: ' + (error.message || 'Транзакция была отклонена.'); | |
| paymentStatus.className = 'status-error'; | |
| payButton.disabled = false; | |
| } | |
| }); | |
| </script> | |
| {% endif %} | |
| {% else %} | |
| <h1 style="color: #c53030;"><i class="fas fa-exclamation-triangle"></i> Ошибка</h1> | |
| <p class="not-found">Заказ с таким ID не найден.</p> | |
| <a href="{{ url_for('catalog') }}" class="catalog-link" style="display: block; text-align: center; margin-top: 20px; color: var(--primary-color); text-decoration: none;">← Вернуться в каталог</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=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <style> | |
| :root { | |
| --primary-color: #007AFF; | |
| --primary-dark: #0056b3; | |
| --surface-color: #FFFFFF; | |
| --surface-dark: #21252B; | |
| --background-color: #F0F2F5; | |
| --background-dark: #1E2124; | |
| --text-color: #1A1A1A; | |
| --text-color-dark: #E0E0E0; | |
| --border-color: #E0E0E0; | |
| --border-color-dark: #3A3A3A; | |
| --success-bg: #e6ffed; | |
| --success-text: #176f44; | |
| --error-bg: #ffe6e6; | |
| --error-text: #a00000; | |
| --warning-bg: #fffbe6; | |
| --warning-text: #7f6e1f; | |
| } | |
| body { font-family: 'Roboto', sans-serif; background-color: var(--background-color); color: var(--text-color); padding: 15px; line-height: 1.5; } | |
| .container { max-width: 1200px; margin: 0 auto; background-color: var(--surface-color); padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); } | |
| .header { padding-bottom: 15px; margin-bottom: 20px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;} | |
| h1, h2, h3 { font-weight: 500; color: var(--primary-color); margin-bottom: 15px; } | |
| h1 { font-size: 1.6rem; } | |
| h2 { font-size: 1.4rem; margin-top: 30px; display: flex; align-items: center; gap: 8px; padding-bottom: 5px; border-bottom: 1px solid var(--border-color);} | |
| h3 { font-size: 1.1rem; color: var(--text-color); margin-top: 20px; font-weight: 600; } | |
| .section { margin-bottom: 30px; padding: 20px; background-color: #F8F9FB; border: 1px solid var(--border-color); border-radius: 8px; } | |
| body.dark-mode { background-color: var(--background-dark); color: var(--text-color-dark); } | |
| body.dark-mode .container { background-color: var(--surface-dark); box-shadow: 0 4px 15px rgba(255,255,255,0.1); } | |
| body.dark-mode .header { border-bottom-color: var(--border-color-dark); } | |
| body.dark-mode h1, body.dark-mode h2, body.dark-mode h3 { color: var(--primary-color); } | |
| body.dark-mode .section { background-color: var(--background-dark); border-color: var(--border-color-dark); } | |
| label { font-weight: 500; margin-top: 10px; display: block; color: var(--text-color); font-size: 0.9rem;} | |
| input[type="text"], input[type="number"], input[type="password"], input[type="tel"], textarea, select { width: 100%; padding: 10px 12px; margin-top: 5px; border: 1px solid var(--border-color); border-radius: 6px; font-size: 0.95rem; box-sizing: border-box; transition: border-color 0.3s ease; background-color: var(--surface-color); color: var(--text-color); } | |
| body.dark-mode input[type="text"], body.dark-mode input[type="number"], body.dark-mode textarea, body.dark-mode select { background-color: var(--surface-dark); border-color: var(--border-color-dark); color: var(--text-color-dark); } | |
| input:focus, textarea:focus, select:focus { border-color: var(--primary-color); outline: none; box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2); } | |
| textarea { min-height: 80px; resize: vertical; } | |
| input[type="file"] { padding: 8px; background-color: #F8F9FB; cursor: pointer; border: 1px solid var(--border-color); border-radius: 6px; } | |
| input[type="checkbox"] { transform: scale(1.1); margin-right: 5px; vertical-align: middle; } | |
| button, .button { padding: 8px 15px; border: none; border-radius: 6px; background-color: var(--primary-color); color: white; font-weight: 500; cursor: pointer; transition: background-color 0.2s ease, transform 0.1s ease; margin-top: 10px; font-size: 0.9rem; display: inline-flex; align-items: center; gap: 5px; text-decoration: none; line-height: 1.2;} | |
| button:hover, .button:hover { background-color: var(--primary-dark); } | |
| .delete-button { background-color: #FF3B30; } | |
| .delete-button:hover { background-color: #d11a2a; } | |
| .add-button { background-color: var(--primary-color); } | |
| .add-button:hover { background-color: var(--primary-dark); } | |
| .item-list { display: grid; gap: 15px; } | |
| .item { background: var(--surface-color); padding: 15px; border-radius: 8px; box-shadow: 0 1px 4px rgba(0,0,0,0.05); border: 1px solid var(--border-color); } | |
| body.dark-mode .item { background: var(--surface-dark); border-color: var(--border-color-dark); } | |
| .item p { margin: 3px 0; font-size: 0.85rem; color: #555; } | |
| body.dark-mode .item p { color: #aaa; } | |
| .item strong { color: var(--text-color); } | |
| body.dark-mode .item strong { color: var(--text-color-dark); } | |
| .item .description { font-size: 0.8rem; color: #888; max-height: 40px; overflow: hidden; } | |
| .item-actions { margin-top: 10px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; } | |
| .photo-preview img { max-width: 60px; max-height: 60px; border-radius: 4px; margin: 3px 3px 0 0; border: 1px solid var(--border-color); object-fit: cover;} | |
| .variant-input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; } | |
| .variant-input-group input { flex-grow: 1; margin: 0; } | |
| .remove-variant-btn { background-color: #FF3B30; padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; } | |
| .add-variant-btn { background-color: #DDEEFF; color: var(--primary-color); margin-top: 5px;} | |
| .add-variant-btn:hover { background-color: #c0dfff; } | |
| .message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; font-size: 0.9rem;} | |
| .message.success { background-color: var(--success-bg); color: var(--success-text); border: 1px solid #b3f4c7;} | |
| .message.error { background-color: var(--error-bg); color: var(--error-text); border: 1px solid #ffb3b3;} | |
| .message.warning { background-color: var(--warning-bg); color: var(--warning-text); border: 1px solid #ffeeba; } | |
| .status-indicator { display: inline-block; padding: 2px 7px; border-radius: 10px; font-size: 0.75rem; font-weight: 500; margin-left: 5px; vertical-align: middle; } | |
| .status-indicator.in-stock { background-color: #c6f6d5; color: #2f855a; } | |
| .status-indicator.out-of-stock { background-color: #fed7d7; color: #c53030; } | |
| .status-indicator.top-product { background-color: #fff3c4; color: #9c4221; margin-left: 5px;} | |
| .status-indicator.new { background-color: #ffe0b2; color: #e65100; } | |
| .status-indicator.paid { background-color: #c8e6c9; color: #2e7d32; } | |
| .status-indicator.accepted { background-color: #b3e5fc; color: #0277bd; } | |
| .status-indicator.prepared { background-color: #c6f6d5; color: #2f855a; } | |
| .status-indicator.shipped { background-color: #a7f3d0; color: #065f46; } | |
| details { background-color: var(--surface-color); border: 1px solid var(--border-color); border-radius: 8px; margin-bottom: 10px; } | |
| body.dark-mode details { background-color: var(--surface-dark); border-color: var(--border-color-dark); } | |
| details > summary { cursor: pointer; font-weight: 500; color: var(--text-color); display: flex; justify-content: space-between; align-items: center; padding: 15px 20px; list-style: none; position: relative; } | |
| details[open] > summary { border-bottom: 1px solid var(--border-color); } | |
| .order-details-content { padding: 10px 15px; } | |
| .order-item-detail { display: flex; gap: 10px; padding: 8px 0; border-top: 1px dashed #eee; font-size: 0.9rem; align-items: center; } | |
| .order-item-detail:first-child { border-top: none; } | |
| .order-item-detail img { width: 30px; height: 30px; object-fit: contain; border-radius: 3px; } | |
| .order-item-name { flex-grow: 1; } | |
| .order-item-qty-price { width: 150px; text-align: right; flex-shrink: 0; } | |
| .order-total-summary { font-size: 1rem; font-weight: 600; margin-top: 15px; padding-top: 10px; border-top: 1px solid var(--border-color); text-align: right; color: var(--primary-color); } | |
| .order-status-form { display: flex; gap: 10px; align-items: center; margin-top: 15px; padding-top: 15px; border-top: 1px dashed var(--border-color); flex-wrap: wrap; } | |
| .order-status-form select { max-width: 180px; margin-top: 0; flex-grow: 1; } | |
| .flex-container { display: flex; flex-wrap: wrap; gap: 20px; } | |
| .flex-item { flex: 1; min-width: 300px; } | |
| .user-list-details summary { font-size: 1.2rem; font-weight: 600; color: var(--primary-color); } | |
| .user-list-item { display: flex; align-items: center; gap: 15px; padding: 10px; border-bottom: 1px solid var(--border-color); } | |
| body.dark-mode .user-list-item { border-bottom-color: var(--border-color-dark); } | |
| .user-list-item:last-child { border-bottom: none; } | |
| .user-avatar { width: 50px; height: 50px; border-radius: 50%; object-fit: cover; } | |
| .user-info { flex-grow: 1; } | |
| .user-info p { margin: 0; } | |
| .user-info strong { font-size: 1rem; } | |
| .user-info .username { color: #888; font-size: 0.9rem; } | |
| </style> | |
| <script> | |
| function toggleTheme() { | |
| document.body.classList.toggle('dark-mode'); | |
| localStorage.setItem('adminTheme', document.body.classList.contains('dark-mode') ? 'dark' : 'light'); | |
| } | |
| document.addEventListener('DOMContentLoaded', () => { | |
| if (localStorage.getItem('adminTheme') === 'dark') { | |
| document.body.classList.add('dark-mode'); | |
| } | |
| }); | |
| </script> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <div class="logo-title-container" style="display: flex; align-items: center; gap: 10px;"> | |
| <img src="https://huggingface.co/spaces/Kgshop/mobilnymir/resolve/main/IMG_20251019_120056_121.jpg" alt="Мобильный мир Logo" style="height: 40px; width: 40px; border-radius: 50%; object-fit: cover; box-shadow: 0 0 5px rgba(0, 122, 255, 0.7);"> | |
| <h1><i class="fas fa-tools"></i> Админ-панель</h1> | |
| </div> | |
| <div> | |
| <a href="{{ url_for('catalog') }}" class="button" style="margin-right: 10px;"><i class="fas fa-store"></i> Каталог</a> | |
| <button class="button" onclick="toggleTheme()"><i class="fas fa-adjust"></i> Тема</button> | |
| </div> | |
| </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-wallet"></i> Настройки оплаты</h2> | |
| <form method="POST"> | |
| <input type="hidden" name="action" value="save_settings"> | |
| <label for="ton_wallet_address">Ваш TON кошелек для приема платежей:</label> | |
| <input type="text" id="ton_wallet_address" name="ton_wallet_address" value="{{ ton_wallet_address }}" placeholder="Введите адрес вашего TON кошелька"> | |
| <button type="submit" class="add-button"><i class="fas fa-save"></i> Сохранить адрес</button> | |
| </form> | |
| </div> | |
| <div class="section"> | |
| <details class="user-list-details"> | |
| <summary><i class="fas fa-users"></i> Пользователи, заходившие в приложение ({{ users|length }})</summary> | |
| <div class="user-list-content" style="margin-top: 15px;"> | |
| {% if users %} | |
| {% for user in users|sort(attribute='last_seen', reverse=true) %} | |
| <div class="user-list-item"> | |
| <img src="{{ user.photo_url or 'https://via.placeholder.com/50' }}" alt="Avatar" class="user-avatar"> | |
| <div class="user-info"> | |
| <p><strong>{{ user.first_name }} {{ user.last_name or '' }}</strong></p> | |
| <p class="username">{{ '@' + user.username if user.username else 'Нет юзернейма' }} | ID: {{ user.id }}</p> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <p>Пока никто не заходил в приложение.</p> | |
| {% endif %} | |
| </div> | |
| </details> | |
| </div> | |
| <div class="section"> | |
| <h2><i class="fas fa-history"></i> История заказов</h2> | |
| {% if orders %} | |
| {% set sorted_orders = orders | sort(attribute='created_at', reverse=true) %} | |
| {% for order in sorted_orders %} | |
| {% set current_status = order.get('status', 'new') %} | |
| {% set total_items = order.cart | sum(attribute='quantity') %} | |
| <details style="margin-bottom: 10px;"> | |
| <summary> | |
| <span> | |
| Заказ №{{ order.id }} | |
| <span class="status-indicator {{ current_status }}">{{ status_map_ru.get(current_status, current_status) }}</span> | |
| </span> | |
| <span style="font-size: 0.85rem; color: #555; flex-shrink: 0; margin-left: 10px;"> | |
| Дата: {{ order.created_at }} | Итого: {{ "%.4f"|format(order.total_price) }} {{ currency_code }} | |
| </span> | |
| </summary> | |
| <div class="order-details-content"> | |
| <h3>Состав заказа:</h3> | |
| <div> | |
| {% for item in order.cart %} | |
| {% set item_price = item.price * item.quantity %} | |
| {% set variant_info = [] %} | |
| {% if item.color and item.color != 'N/A' %} | |
| {% set _ = variant_info.append('Цвет: ' + item.color) %} | |
| {% endif %} | |
| {% if item.model and item.model != 'N/A' %} | |
| {% set _ = variant_info.append('Модель: ' + item.model) %} | |
| {% endif %} | |
| {% set variant_display = variant_info | join(', ') %} | |
| <div class="order-item-detail"> | |
| <img src="{{ item.photo_url }}" alt="{{ item.name }}"> | |
| <div class="order-item-name"> | |
| <strong>{{ item.name }}</strong> | |
| {% if variant_display %}<p style="margin: 0; color: #888; font-size: 0.8rem;">{{ variant_display }}</p>{% endif %} | |
| </div> | |
| <div class="order-item-qty-price"> | |
| {{ item.quantity }} × {{ "%.4f"|format(item.price) }} = <strong>{{ "%.4f"|format(item_price) }} {{ currency_code }}</strong> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| <div class="order-total-summary"> | |
| Общая сумма: {{ "%.4f"|format(order.total_price) }} {{ currency_code }} | |
| </div> | |
| <div class="order-status-form"> | |
| <form method="POST" style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;"> | |
| <input type="hidden" name="action" value="update_order_status"> | |
| <input type="hidden" name="order_id" value="{{ order.id }}"> | |
| <label for="status_{{ order.id }}" style="margin: 0; display: inline;">Статус:</label> | |
| <select name="new_status" id="status_{{ order.id }}"> | |
| {% for status_key, status_value in status_map_ru.items() %} | |
| <option value="{{ status_key }}" {% if current_status == status_key %}selected{% endif %}>{{ status_value }}</option> | |
| {% endfor %} | |
| </select> | |
| <button type="submit" class="button" style="flex-grow: 0;"><i class="fas fa-check"></i> Сохранить</button> | |
| <a href="{{ url_for('view_order', order_id=order.id) }}" target="_blank" class="button" style="background-color: #555; flex-grow: 0;"><i class="fas fa-eye"></i> Просмотр</a> | |
| </form> | |
| </div> | |
| </div> | |
| </details> | |
| {% endfor %} | |
| {% else %} | |
| <p>Активных заказов нет.</p> | |
| {% endif %} | |
| </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" style="padding: 15px;"> | |
| <form method="POST"> | |
| <input type="hidden" name="action" value="add_category"> | |
| <label for="add_category_name">Название новой категории:</label> | |
| <input type="text" id="add_category_name" name="category_name" required> | |
| <button type="submit" class="add-button"><i class="fas fa-plus"></i> Добавить</button> | |
| </form> | |
| </div> | |
| </details> | |
| <h3>Существующие категории:</h3> | |
| {% if categories %} | |
| <div class="item-list"> | |
| {% for category in categories %} | |
| <div class="item" style="display: flex; justify-content: space-between; align-items: center; padding: 10px;"> | |
| <span style="font-weight: 500;">{{ category }}</span> | |
| <form method="POST" style="margin: 0;" onsubmit="return confirm('Вы уверены, что хотите удалить категорию \'{{ category }}\'? Товары этой категории будут помечены как \'Без категории\'.');"> | |
| <input type="hidden" name="action" value="delete_category"> | |
| <input type="hidden" name="category_name" value="{{ category }}"> | |
| <button type="submit" class="delete-button" style="padding: 4px 8px; font-size: 0.75rem; margin: 0;"><i class="fas fa-trash-alt"></i></button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>Категорий пока нет.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div class="flex-item"> | |
| <div class="section"> | |
| <h2><i class="fas fa-info-circle"></i> Информация о магазине</h2> | |
| <p style="font-size: 0.9rem;">Магазин работает в режиме каталога с оплатой через TON Connect.</p> | |
| <p style="font-size: 0.9rem;">Адрес магазина: <strong>{{ store_address }}</strong></p> | |
| <p style="font-size: 0.9rem;">Валюта: <strong>{{ currency_name }} ({{ currency_code }})</strong></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" style="padding: 15px;"> | |
| <form method="POST" enctype="multipart/form-data"> | |
| <input type="hidden" name="action" value="add_product"> | |
| <label for="add_name">Название товара *:</label> | |
| <input type="text" id="add_name" name="name" required> | |
| <label for="add_price">Цена ({{ currency_code }}) *:</label> | |
| <input type="number" id="add_price" name="price" step="0.0001" min="0" required> | |
| <label for="add_description">Описание:</label> | |
| <textarea id="add_description" name="description" rows="4"></textarea> | |
| <label for="add_category">Категория:</label> | |
| <select id="add_category" name="category"> | |
| <option value="Без категории">Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category }}">{{ category }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="add_photos">Фотографии (до 10 шт.):</label> | |
| <input type="file" id="add_photos" name="photos" accept="image/*" multiple> | |
| <h4 style="margin-top: 20px; font-weight: 500; font-size: 1rem; color: var(--primary-color);">Варианты:</h4> | |
| <label>Цвета/Варианты:</label> | |
| <div id="add-color-inputs"> | |
| <div class="variant-input-group"> | |
| <input type="text" name="colors" placeholder="Например: Розовый"> | |
| <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| </div> | |
| <button type="button" class="button add-variant-btn" onclick="addVariantInput('add-color-inputs', 'colors', 'Например: Красный')"><i class="fas fa-palette"></i> Добавить цвет</button> | |
| <label style="margin-top: 15px;">Модели/Объем (например: 128GB, Pro):</label> | |
| <div id="add-model-inputs"> | |
| <div class="variant-input-group"> | |
| <input type="text" name="models" placeholder="Например: 128GB"> | |
| <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| </div> | |
| <button type="button" class="button add-variant-btn" onclick="addVariantInput('add-model-inputs', 'models', 'Например: Pro')"><i class="fas fa-mobile-alt"></i> Добавить модель</button> | |
| <div style="margin-top: 20px;"> | |
| <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/60x60.png?text=N/A" alt="Нет фото"> | |
| {% endif %} | |
| </div> | |
| <div style="flex-grow: 1;"> | |
| <h3 style="margin-top: 0; margin-bottom: 5px;"> | |
| {{ 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> {{ "%.4f"|format(product['price']) }} {{ currency_code }}</p> | |
| <p class="description" title="{{ product.get('description', '') }}"><strong>Описание:</strong> {{ product.get('description', 'N/A')[:100] }}{% if product.get('description', '')|length > 100 %}...{% endif %}</p> | |
| {% set colors = product.get('colors', []) %} | |
| {% set models = product.get('models', []) %} | |
| <p><strong>Цвета:</strong> {{ colors|select('ne', '')|join(', ') if colors|select('ne', '')|list|length > 0 else 'Нет' }}</p> | |
| <p><strong>Модели:</strong> {{ models|select('ne', '')|join(', ') if models|select('ne', '')|list|length > 0 else 'Нет' }}</p> | |
| </div> | |
| </div> | |
| <div class="item-actions"> | |
| <button type="button" class="button" onclick="toggleEditForm('edit-form-{{ product.id }}')"><i class="fas fa-edit"></i> Редактировать</button> | |
| <form method="POST" style="margin:0;" onsubmit="return confirm('Вы уверены, что хотите удалить товар \'{{ product['name'] }}\'?');"> | |
| <input type="hidden" name="action" value="delete_product"> | |
| <input type="hidden" name="product_id" value="{{ product.id }}"> | |
| <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button> | |
| </form> | |
| </div> | |
| <div id="edit-form-{{ product.id }}" class="edit-form-container" style="display: none;"> | |
| <h4 style="color: var(--primary-color);"><i class="fas fa-edit"></i> Редактирование</h4> | |
| <form method="POST" enctype="multipart/form-data"> | |
| <input type="hidden" name="action" value="edit_product"> | |
| <input type="hidden" name="product_id" value="{{ product.id }}"> | |
| <label>Название *:</label> | |
| <input type="text" name="name" value="{{ product['name'] }}" required> | |
| <label>Цена ({{ currency_code }}) *:</label> | |
| <input type="number" name="price" step="0.0001" min="0" value="{{ product['price'] }}" required> | |
| <label>Описание:</label> | |
| <textarea name="description" rows="4">{{ product.get('description', '') }}</textarea> | |
| <label>Категория:</label> | |
| <select name="category"> | |
| <option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option> | |
| {% endfor %} | |
| </select> | |
| <label>Заменить фотографии (выберите новые файлы, до 10 шт.):</label> | |
| <input type="file" name="photos" accept="image/*" multiple> | |
| {% if product.get('photos') %} | |
| <p style="font-size: 0.85rem; margin-top: 5px;">Текущие фото:</p> | |
| <div class="photo-preview"> | |
| {% for photo in product['photos'] %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="Фото {{ loop.index }}"> | |
| {% endfor %} | |
| </div> | |
| {% endif %} | |
| <h4 style="margin-top: 20px; font-weight: 500; font-size: 1rem; color: var(--primary-color);">Варианты:</h4> | |
| <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="variant-input-group"> | |
| <input type="text" name="colors" value="{{ color }}"> | |
| <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| {% endfor %} | |
| {% else %} | |
| <div class="variant-input-group"> | |
| <input type="text" name="colors" placeholder="Например: Красный"> | |
| <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| </div> | |
| <button type="button" class="button add-variant-btn" onclick="addVariantInput('edit-color-inputs-{{ product.id }}', 'colors', 'Например: Красный')"><i class="fas fa-palette"></i> Добавить цвет</button> | |
| <label style="margin-top: 15px;">Модели/Объем:</label> | |
| <div id="edit-model-inputs-{{ product.id }}"> | |
| {% set current_models = product.get('models', []) %} | |
| {% if current_models and current_models|select('ne', '')|list|length > 0 %} | |
| {% for model in current_models %} | |
| {% if model.strip() %} | |
| <div class="variant-input-group"> | |
| <input type="text" name="models" value="{{ model }}"> | |
| <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| {% endfor %} | |
| {% else %} | |
| <div class="variant-input-group"> | |
| <input type="text" name="models" placeholder="Например: 128GB"> | |
| <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| </div> | |
| <button type="button" class="button add-variant-btn" onclick="addVariantInput('edit-model-inputs-{{ product.id }}', 'models', 'Например: Pro')"><i class="fas fa-mobile-alt"></i> Добавить модель</button> | |
| <div style="margin-top: 20px;"> | |
| <input type="checkbox" id="edit_in_stock_{{ product.id }}" name="in_stock" {% if product.get('in_stock', True) %}checked{% endif %}> | |
| <label for="edit_in_stock_{{ product.id }}" class="inline-label">В наличии</label> | |
| </div> | |
| <div style="margin-top: 5px;"> | |
| <input type="checkbox" id="edit_is_top_{{ product.id }}" name="is_top" {% if product.get('is_top', False) %}checked{% endif %}> | |
| <label for="edit_is_top_{{ product.id }}" class="inline-label">Топ товар</label> | |
| </div> | |
| <br> | |
| <button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Сохранить изменения</button> | |
| </form> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>Товаров пока нет.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <script> | |
| function toggleEditForm(formId) { | |
| const formContainer = document.getElementById(formId); | |
| if (formContainer) { | |
| formContainer.style.display = formContainer.style.display === 'none' || formContainer.style.display === '' ? 'block' : 'none'; | |
| } | |
| } | |
| function addVariantInput(containerId, fieldName, placeholder) { | |
| const container = document.getElementById(containerId); | |
| if (container) { | |
| const existingInputs = container.querySelectorAll('input[name="' + fieldName + '"]'); | |
| if (existingInputs.length === 1 && existingInputs[0].value.trim() === '') { | |
| existingInputs[0].value = ''; | |
| } | |
| const newInputGroup = document.createElement('div'); | |
| newInputGroup.className = 'variant-input-group'; | |
| newInputGroup.innerHTML = ` | |
| <input type="text" name="${fieldName}" placeholder="${placeholder}"> | |
| <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button> | |
| `; | |
| container.appendChild(newInputGroup); | |
| const newInput = newInputGroup.querySelector('input[name="' + fieldName + '"]'); | |
| if (newInput) { | |
| newInput.focus(); | |
| } | |
| } | |
| } | |
| function removeVariantInput(button) { | |
| const group = button.closest('.variant-input-group'); | |
| if (group) { | |
| const container = group.parentNode; | |
| const fieldName = group.querySelector('input').name; | |
| const placeholder = fieldName === 'colors' ? 'Например: Цвет' : 'Например: Модель'; | |
| group.remove(); | |
| if (container && container.children.length === 0) { | |
| const placeholderGroup = document.createElement('div'); | |
| placeholderGroup.className = 'variant-input-group'; | |
| placeholderGroup.innerHTML = ` | |
| <input type="text" name="${fieldName}" placeholder="${placeholder}"> | |
| <button type="button" class="remove-variant-btn" onclick="removeVariantInput(this)"><i class="fas fa-times"></i></button> | |
| `; | |
| container.appendChild(placeholderGroup); | |
| } | |
| } | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| def catalog(): | |
| data = load_data() | |
| all_products = data.get('products', []) | |
| categories = sorted(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=categories, | |
| repo_id=REPO_ID, | |
| store_address=STORE_ADDRESS, | |
| currency_code=CURRENCY_CODE | |
| ) | |
| def product_detail(index): | |
| data = load_data() | |
| all_products = data.get('products', []) | |
| products_in_stock = [p for p in all_products if p.get('in_stock', True)] | |
| products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower())) | |
| try: | |
| product = products_sorted[index] | |
| except IndexError: | |
| return "Товар не найден.", 404 | |
| return render_template_string( | |
| PRODUCT_DETAIL_TEMPLATE, | |
| product=product, | |
| products_index=index, | |
| 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: | |
| return jsonify({"error": "Empty cart"}), 400 | |
| cart_with_photos = [] | |
| for item in order_data.get('cart', []): | |
| photo_filename = item.get('photo') | |
| if photo_filename: | |
| item['photo_url'] = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{photo_filename}" | |
| else: | |
| item['photo_url'] = "https://via.placeholder.com/60x60.png?text=N/A" | |
| cart_with_photos.append(item) | |
| order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}" | |
| new_order = { | |
| "id": order_id, | |
| "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
| "cart": cart_with_photos, | |
| "total_price": sum(i['price'] * i['quantity'] for i in cart_with_photos), | |
| "status": "new" | |
| } | |
| data = load_data() | |
| data['orders'][order_id] = new_order | |
| save_data(data) | |
| return jsonify({"order_id": order_id}), 201 | |
| def view_order(order_id): | |
| data = load_data() | |
| order = data.get('orders', {}).get(order_id) | |
| ton_wallet_address = data.get('settings', {}).get('ton_wallet_address', '') | |
| return render_template_string( | |
| ORDER_TEMPLATE, | |
| order=order, | |
| status_map_ru=STATUS_MAP_RU, | |
| currency_code=CURRENCY_CODE, | |
| ton_wallet_address=ton_wallet_address | |
| ) | |
| def update_order_status_after_payment(): | |
| payload = request.get_json() | |
| order_id = payload.get('order_id') | |
| if not order_id: | |
| return jsonify({"status": "error", "message": "No order_id"}), 400 | |
| data = load_data() | |
| if order_id in data.get('orders', {}): | |
| data['orders'][order_id]['status'] = 'paid' | |
| save_data(data) | |
| logging.info(f"Order {order_id} status updated to 'paid' after client-side confirmation.") | |
| return jsonify({"status": "ok"}) | |
| else: | |
| logging.warning(f"Attempted to update status for non-existent order {order_id}.") | |
| return jsonify({"status": "error", "message": "Order not found"}), 404 | |
| def is_valid_tma_hash(init_data: str, bot_token: str) -> bool: | |
| try: | |
| parsed_data = parse_qs(init_data) | |
| received_hash = parsed_data.pop('hash', [None])[0] | |
| if not received_hash: return False | |
| data_check_string = "\n".join(f"{k}={v[0]}" for k, v in sorted(parsed_data.items())) | |
| secret_key = hmac.new("WebAppData".encode(), bot_token.encode(), hashlib.sha256).digest() | |
| calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest() | |
| return hmac.compare_digest(received_hash, calculated_hash) | |
| except: return False | |
| def verify_tma(): | |
| payload = request.get_json() | |
| init_data = payload.get('initData') | |
| if not init_data or not is_valid_tma_hash(init_data, BOT_TOKEN): | |
| return jsonify({"status": "error"}), 403 | |
| params = parse_qs(init_data) | |
| user_data = json.loads(unquote(params['user'][0])) | |
| user_id = str(user_data['id']) | |
| users = load_users() | |
| current_user_data = { | |
| 'id': user_id, | |
| 'first_name': user_data.get('first_name'), | |
| 'last_name': user_data.get('last_name'), | |
| 'username': user_data.get('username'), | |
| 'photo_url': user_data.get('photo_url'), | |
| 'last_seen': datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
| } | |
| users[user_id] = current_user_data | |
| save_users(users) | |
| return jsonify({"status": "ok", "user": users[user_id]}) | |
| def admin(): | |
| data = load_data() | |
| users_data = load_users() | |
| products = data.get('products', []) | |
| categories = data.get('categories', []) | |
| if request.method == 'POST': | |
| action = request.form.get('action') | |
| if action == 'save_settings': | |
| data['settings']['ton_wallet_address'] = request.form.get('ton_wallet_address', '').strip() | |
| save_data(data) | |
| flash('Адрес TON кошелька сохранен.', 'success') | |
| elif action == 'update_order_status': | |
| oid = request.form.get('order_id') | |
| if oid in data.get('orders', {}): | |
| data['orders'][oid]['status'] = request.form.get('new_status') | |
| save_data(data) | |
| flash('Статус заказа обновлен.', 'success') | |
| elif action == 'add_category': | |
| cat = request.form.get('category_name', '').strip() | |
| if cat and cat not in categories: | |
| categories.append(cat) | |
| data['categories'] = categories | |
| save_data(data) | |
| flash(f'Категория "{cat}" добавлена.', 'success') | |
| else: | |
| flash('Неверное имя категории или она уже существует.', 'error') | |
| elif action == 'delete_category': | |
| cat = request.form.get('category_name') | |
| if cat in categories: | |
| categories.remove(cat) | |
| for p in products: | |
| if p.get('category') == cat: | |
| p['category'] = 'Без категории' | |
| data['categories'] = categories | |
| data['products'] = products | |
| save_data(data) | |
| flash(f'Категория "{cat}" удалена.', 'success') | |
| elif action == 'add_product' or action == 'edit_product': | |
| try: | |
| product_id = request.form.get('product_id') if action == 'edit_product' else str(uuid.uuid4()) | |
| name = request.form.get('name', '').strip() | |
| price = float(request.form.get('price', 0)) | |
| if not name or price <= 0: | |
| flash('Название и цена обязательны.', 'error') | |
| return redirect(url_for('admin')) | |
| photos_files = request.files.getlist('photos') | |
| photos_list = [] | |
| if action == 'edit_product': | |
| existing_product = next((p for p in products if p.get('id') == product_id), None) | |
| if existing_product: | |
| photos_list = existing_product.get('photos', []) | |
| if photos_files and photos_files[0].filename: | |
| if HF_TOKEN_WRITE: | |
| api = HfApi() | |
| new_photos = [] | |
| for photo in photos_files[:10]: | |
| if photo and photo.filename: | |
| safe_name = secure_filename(photo.filename) | |
| photo_filename = f"{uuid.uuid4().hex}_{safe_name}" | |
| temp_path = f"temp_{photo_filename}" | |
| photo.save(temp_path) | |
| api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE) | |
| new_photos.append(photo_filename) | |
| os.remove(temp_path) | |
| photos_list = new_photos | |
| else: | |
| flash('HF_TOKEN_WRITE не установлен. Фото не загружены.', 'warning') | |
| colors = [c.strip() for c in request.form.getlist('colors') if c.strip()] | |
| models = [m.strip() for m in request.form.getlist('models') if m.strip()] | |
| product_data = { | |
| 'id': product_id, | |
| 'name': name, | |
| 'price': price, | |
| 'description': request.form.get('description', ''), | |
| 'category': request.form.get('category', 'Без категории'), | |
| 'photos': photos_list, | |
| 'colors': colors, | |
| 'models': models, | |
| 'in_stock': 'in_stock' in request.form, | |
| 'is_top': 'is_top' in request.form | |
| } | |
| if action == 'edit_product': | |
| data['products'] = [product_data if p.get('id') == product_id else p for p in products] | |
| flash(f'Товар "{name}" обновлен.', 'success') | |
| else: | |
| products.append(product_data) | |
| data['products'] = products | |
| flash(f'Товар "{name}" добавлен.', 'success') | |
| base_url = request.url_root | |
| threading.Thread(target=broadcast_new_product_notification, args=(product_data, base_url)).start() | |
| save_data(data) | |
| except Exception as e: | |
| flash(f'Произошла ошибка: {e}', 'error') | |
| elif action == 'delete_product': | |
| pid = request.form.get('product_id') | |
| initial_len = len(data['products']) | |
| data['products'] = [p for p in products if p.get('id') != pid] | |
| if len(data['products']) < initial_len: | |
| save_data(data) | |
| flash('Товар удален.', 'success') | |
| else: | |
| flash('Товар для удаления не найден.', 'error') | |
| return redirect(url_for('admin')) | |
| return render_template_string( | |
| ADMIN_TEMPLATE, | |
| products=data.get('products', []), | |
| categories=data.get('categories', []), | |
| orders=list(data.get('orders', {}).values()), | |
| users=list(users_data.values()), | |
| status_map_ru=STATUS_MAP_RU, | |
| repo_id=REPO_ID, | |
| store_address=STORE_ADDRESS, | |
| currency_code=CURRENCY_CODE, | |
| currency_name=CURRENCY_NAME, | |
| ton_wallet_address=data.get('settings', {}).get('ton_wallet_address', '') | |
| ) | |
| if __name__ == '__main__': | |
| download_db_from_hf() | |
| if HF_TOKEN_WRITE: | |
| threading.Thread(target=periodic_backup, daemon=True).start() | |
| app.run(debug=False, host='0.0.0.0', port=int(os.environ.get('PORT', 7860))) | |