Spaces:
Running
Running
| from flask import Flask, render_template_string, request, redirect, url_for, jsonify, session | |
| import json | |
| import os | |
| import logging | |
| import threading | |
| import time | |
| from datetime import datetime, timedelta, timezone | |
| import pytz # Keep pytz if needed elsewhere, but timezone is now preferred for basic UTC handling | |
| from huggingface_hub import HfApi, hf_hub_download | |
| from huggingface_hub.utils import RepositoryNotFoundError | |
| from werkzeug.utils import secure_filename | |
| from werkzeug.security import generate_password_hash, check_password_hash | |
| app = Flask(__name__) | |
| # SECURITY: Ensure this key is strong and loaded from environment in production | |
| app.secret_key = os.getenv("FLASK_SECRET_KEY", "a_much_stronger_default_secret_key_please_change_v3") # Changed secret key significantly | |
| app.config['SESSION_COOKIE_SAMESITE'] = 'None' | |
| app.config['SESSION_COOKIE_SECURE'] = True # Keep secure cookies | |
| # Set session lifetime (e.g., 30 days) | |
| app.permanent_session_lifetime = timedelta(days=30) | |
| DATA_FILE = 'data_ultra_flowers.json' # Changed filename | |
| USER_DATA_FILE = 'data_ultra_flowerusers.json' # Changed filename | |
| REPO_ID = "Kgshop/Testbasebase" # <<< UPDATED REPOSITORY ID | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN") | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") # Use the same token if read/write access is the same | |
| # Placeholder for a new logo if available, otherwise keep the old one or remove | |
| LOGO_URL = "https://huggingface.co/spaces/shopflo0/flowerbase/resolve/main/Gemini_Generated_Image_ebfuonebfuonebfu.jpg" # Placeholder logo | |
| logging.basicConfig(level=logging.INFO) # Changed level to INFO for less verbosity in production | |
| # --- Helper Function & Jinja Filter --- | |
| def format_iso_datetime_filter(iso_str): | |
| """ | |
| Parses an ISO 8601 datetime string (handling 'Z' for UTC) | |
| and returns a timezone-aware datetime object (UTC). | |
| Returns None if parsing fails. | |
| """ | |
| if not iso_str: return None | |
| try: | |
| # Check if it's already a datetime object (e.g., from previous processing) | |
| if isinstance(iso_str, datetime): | |
| dt = iso_str | |
| # Ensure it's timezone-aware (assume UTC if naive) | |
| if dt.tzinfo is None: | |
| dt = dt.replace(tzinfo=timezone.utc) | |
| return dt | |
| else: | |
| # Process string format | |
| expiry_dt_str = str(iso_str) # Ensure it's a string | |
| if 'Z' in expiry_dt_str: | |
| expiry_dt_str = expiry_dt_str.replace('Z', '+00:00') | |
| # Handle potential missing timezone info by assuming UTC | |
| dt = datetime.fromisoformat(expiry_dt_str) | |
| if dt.tzinfo is None: | |
| dt = dt.replace(tzinfo=timezone.utc) | |
| return dt | |
| except (ValueError, TypeError) as e: | |
| logging.warning(f"Could not parse date string: {iso_str}. Error: {e}") | |
| return None | |
| # Register the function as a Jinja2 filter | |
| app.template_filter('format_iso_datetime')(format_iso_datetime_filter) | |
| # --- Data Loading/Saving Functions --- | |
| def load_data(): | |
| try: | |
| # Attempt to download only if tokens are set, otherwise use local | |
| if HF_TOKEN_READ: | |
| try: | |
| download_db_from_hf() | |
| except RepositoryNotFoundError: | |
| logging.warning(f"Репозиторий HF {REPO_ID} не найден. Попытка использовать локальный файл {DATA_FILE}.") | |
| except Exception as download_err: | |
| logging.error(f"Ошибка загрузки {DATA_FILE} с HF: {download_err}. Попытка использовать локальный файл.") | |
| if not os.path.exists(DATA_FILE): | |
| logging.warning(f"Локальный файл базы данных '{DATA_FILE}' не найден. Создается пустая база данных.") | |
| return {'products': [], 'categories': [], 'news': []} | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info(f"Данные магазина цветов успешно загружены из '{DATA_FILE}'") | |
| if not isinstance(data, dict): | |
| logging.warning("Структура JSON некорректна, создается структура по умолчанию.") | |
| return {'products': [], 'categories': [], 'news': []} | |
| # Ensure essential keys exist | |
| data.setdefault('products', []) | |
| data.setdefault('categories', []) | |
| data.setdefault('news', []) | |
| # News expiry check | |
| current_time_utc = datetime.now(timezone.utc) | |
| updated_news = [] | |
| news_list = data.get('news', []) | |
| if not isinstance(news_list, list): # Handle case where 'news' might not be a list | |
| logging.warning("Ключ 'news' в JSON не является списком. Новости будут проигнорированы.") | |
| news_list = [] | |
| for news_item in news_list: | |
| if not isinstance(news_item, dict): # Skip non-dict items | |
| logging.warning(f"Найден несловарный элемент в списке новостей: {news_item}") | |
| continue | |
| expiry_str = news_item.get('expiry') | |
| if expiry_str: | |
| expiry_datetime = format_iso_datetime_filter(expiry_str) # Use the filter function for parsing | |
| if expiry_datetime: | |
| # Compare timezone-aware datetimes | |
| if expiry_datetime > current_time_utc: | |
| updated_news.append(news_item) | |
| else: | |
| logging.info(f"Новость '{news_item.get('title', 'N/A')}' истекла и удалена.") | |
| else: | |
| # Keep news if date format is wrong, but log error | |
| logging.error(f"Ошибка парсинга даты истечения для новости '{news_item.get('title', 'N/A')}'. Новость сохранена.") | |
| updated_news.append(news_item) | |
| else: | |
| updated_news.append(news_item) # Keep news without expiry | |
| data['news'] = updated_news | |
| return data | |
| except FileNotFoundError: | |
| # This case is now handled by the check after download attempt | |
| logging.warning(f"Локальный файл базы данных '{DATA_FILE}' не найден и не удалось скачать. Создается пустая база данных.") | |
| return {'products': [], 'categories': [], 'news': []} | |
| except json.JSONDecodeError: | |
| logging.error(f"Ошибка: Невозможно декодировать JSON-файл '{DATA_FILE}'. Создается пустая база данных.") | |
| return {'products': [], 'categories': [], 'news': []} | |
| except Exception as e: | |
| logging.error(f"Неожиданная ошибка при загрузке данных магазина цветов: {e}", exc_info=True) | |
| return {'products': [], 'categories': [], 'news': []} | |
| def save_data(data): | |
| try: | |
| data_to_save = data.copy() | |
| # Ensure datetime objects are converted to ISO format strings before saving | |
| if 'news' in data_to_save and isinstance(data_to_save['news'], list): | |
| for news_item in data_to_save['news']: | |
| if not isinstance(news_item, dict): continue # Skip non-dict items | |
| # Ensure timestamp and expiry are strings | |
| if 'timestamp' in news_item and isinstance(news_item['timestamp'], datetime): | |
| # Ensure UTC before formatting | |
| ts_dt = news_item['timestamp'] | |
| if ts_dt.tzinfo is None: | |
| ts_dt = ts_dt.replace(tzinfo=timezone.utc) | |
| else: | |
| ts_dt = ts_dt.astimezone(timezone.utc) | |
| news_item['timestamp'] = ts_dt.isoformat() | |
| if 'expiry' in news_item and isinstance(news_item['expiry'], datetime): | |
| exp_dt = news_item['expiry'] | |
| if exp_dt.tzinfo is None: | |
| exp_dt = exp_dt.replace(tzinfo=timezone.utc) | |
| else: | |
| exp_dt = exp_dt.astimezone(timezone.utc) | |
| news_item['expiry'] = exp_dt.isoformat() | |
| with open(DATA_FILE, 'w', encoding='utf-8') as file: | |
| json.dump(data_to_save, file, ensure_ascii=False, indent=4) | |
| logging.info(f"Данные магазина цветов успешно сохранены в '{DATA_FILE}'") | |
| # Attempt to upload only if write token is set | |
| if HF_TOKEN_WRITE: | |
| upload_db_to_hf() | |
| except Exception as e: | |
| logging.error(f"Ошибка при сохранении данных магазина цветов: {e}", exc_info=True) | |
| # Decide if you want to raise the exception or just log it | |
| # raise | |
| def upload_db_to_hf(): | |
| if not HF_TOKEN_WRITE: | |
| logging.info("HF_TOKEN_WRITE не установлен, загрузка на Hugging Face пропущена.") | |
| return | |
| if not os.path.exists(DATA_FILE): | |
| logging.warning(f"Файл {DATA_FILE} не найден для загрузки на HF.") | |
| return | |
| try: | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=DATA_FILE, | |
| path_in_repo=DATA_FILE, | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Автоматическое резервное копирование базы данных цветов {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" | |
| ) | |
| logging.info(f"Резервная копия JSON-базы данных цветов загружена в {REPO_ID}.") | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке резервной копии базы данных цветов {DATA_FILE}: {e}") | |
| def download_db_from_hf(): | |
| if not HF_TOKEN_READ: | |
| logging.info("HF_TOKEN_READ не установлен, загрузка с Hugging Face пропущена.") | |
| return # Don't raise error, just skip download attempt | |
| try: | |
| logging.info(f"Попытка загрузки {DATA_FILE} из {REPO_ID}...") | |
| hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=DATA_FILE, | |
| repo_type="dataset", | |
| token=HF_TOKEN_READ, | |
| local_dir=".", | |
| force_filename=DATA_FILE, # Ensure it overwrites with the correct name | |
| local_dir_use_symlinks=False # Recommended for compatibility | |
| ) | |
| logging.info(f"JSON-база данных цветов '{DATA_FILE}' успешно загружена из {REPO_ID}.") | |
| except RepositoryNotFoundError as e: | |
| logging.warning(f"Репозиторий {REPO_ID} не найден на Hugging Face: {e}.") | |
| raise # Re-raise to be caught in load_data | |
| except Exception as e: | |
| # Log other potential download errors (network issues, permissions, file not found on remote) | |
| logging.error(f"Ошибка при загрузке JSON-базы данных цветов '{DATA_FILE}' с Hugging Face: {e}") | |
| # Check if it's specifically a file not found error (often HTTP 404) | |
| if "404" in str(e): | |
| logging.warning(f"Файл {DATA_FILE} не найден в репозитории {REPO_ID}.") | |
| raise # Re-raise to be caught in load_data | |
| # --- User Data Functions (Similar adjustments) --- | |
| def load_user_data(): | |
| try: | |
| if HF_TOKEN_READ: | |
| try: | |
| download_user_db_from_hf() | |
| except RepositoryNotFoundError: | |
| logging.warning(f"Репозиторий HF {REPO_ID} для пользователей не найден. Попытка использовать локальный файл {USER_DATA_FILE}.") | |
| except Exception as download_err: | |
| logging.error(f"Ошибка загрузки {USER_DATA_FILE} с HF: {download_err}. Попытка использовать локальный файл.") | |
| if not os.path.exists(USER_DATA_FILE): | |
| logging.warning(f"Локальный файл базы данных пользователей '{USER_DATA_FILE}' не найден. Создается пустая база данных.") | |
| return {'users': []} | |
| with open(USER_DATA_FILE, 'r', encoding='utf-8') as file: | |
| user_data = json.load(file) | |
| logging.info(f"Данные пользователей успешно загружены из '{USER_DATA_FILE}'") | |
| if not isinstance(user_data, dict): | |
| logging.warning("Структура JSON пользователей некорректна, создается структура по умолчанию.") | |
| return {'users': []} | |
| user_data.setdefault('users', []) | |
| # Add basic validation for users list if needed | |
| if not isinstance(user_data['users'], list): | |
| logging.warning("Ключ 'users' в JSON пользователей не является списком. Создается пустой список.") | |
| user_data['users'] = [] | |
| return user_data | |
| except FileNotFoundError: | |
| # Handled by os.path.exists check now | |
| logging.warning(f"Локальный файл базы данных пользователей '{USER_DATA_FILE}' не найден и не удалось скачать. Создается пустая база данных.") | |
| return {'users': []} | |
| except json.JSONDecodeError: | |
| logging.error(f"Ошибка: Невозможно декодировать JSON-файл пользователей '{USER_DATA_FILE}'.") | |
| return {'users': []} | |
| except Exception as e: | |
| logging.error(f"Неожиданная ошибка при загрузке данных пользователей: {e}", exc_info=True) | |
| return {'users': []} | |
| def save_user_data(user_data): | |
| try: | |
| # Ensure datetime objects in order history are strings (in UTC ISO format) | |
| for user in user_data.get('users', []): | |
| if 'order_history' in user and isinstance(user['order_history'], list): | |
| for order in user['order_history']: | |
| if not isinstance(order, dict): continue # Skip non-dict items | |
| if 'timestamp' in order and isinstance(order['timestamp'], datetime): | |
| ts_dt = order['timestamp'] | |
| if ts_dt.tzinfo is None: | |
| ts_dt = ts_dt.replace(tzinfo=timezone.utc) | |
| else: | |
| ts_dt = ts_dt.astimezone(timezone.utc) | |
| order['timestamp'] = ts_dt.isoformat() | |
| with open(USER_DATA_FILE, 'w', encoding='utf-8') as file: | |
| json.dump(user_data, file, ensure_ascii=False, indent=4) | |
| logging.info(f"Данные пользователей успешно сохранены в '{USER_DATA_FILE}'") | |
| if HF_TOKEN_WRITE: | |
| upload_user_db_to_hf() | |
| except Exception as e: | |
| logging.error(f"Ошибка при сохранении данных пользователей: {e}", exc_info=True) | |
| # raise | |
| def upload_user_db_to_hf(): | |
| if not HF_TOKEN_WRITE: | |
| logging.info("HF_TOKEN_WRITE не установлен, загрузка пользовательской базы на Hugging Face пропущена.") | |
| return | |
| if not os.path.exists(USER_DATA_FILE): | |
| logging.warning(f"Файл {USER_DATA_FILE} не найден для загрузки на HF.") | |
| return | |
| try: | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=USER_DATA_FILE, | |
| path_in_repo=USER_DATA_FILE, | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Автоматическое резервное копирование базы данных пользователей {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" | |
| ) | |
| logging.info(f"Резервная копия JSON-базы данных пользователей загружена в {REPO_ID}.") | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке резервной копии базы данных пользователей {USER_DATA_FILE}: {e}") | |
| def download_user_db_from_hf(): | |
| if not HF_TOKEN_READ: | |
| logging.info("HF_TOKEN_READ не установлен, загрузка пользовательской базы с Hugging Face пропущена.") | |
| return # Don't raise error | |
| try: | |
| logging.info(f"Попытка загрузки {USER_DATA_FILE} из {REPO_ID}...") | |
| hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=USER_DATA_FILE, | |
| repo_type="dataset", | |
| token=HF_TOKEN_READ, | |
| local_dir=".", | |
| force_filename=USER_DATA_FILE, # Ensure it overwrites with the correct name | |
| local_dir_use_symlinks=False | |
| ) | |
| logging.info(f"JSON-база данных пользователей '{USER_DATA_FILE}' успешно загружена из {REPO_ID}.") | |
| except RepositoryNotFoundError as e: | |
| logging.warning(f"Репозиторий {REPO_ID} (для пользователей) не найден на Hugging Face: {e}.") | |
| raise # Re-raise | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке JSON-базы данных пользователей '{USER_DATA_FILE}' с Hugging Face: {e}") | |
| if "404" in str(e): | |
| logging.warning(f"Файл {USER_DATA_FILE} не найден в репозитории {REPO_ID}.") | |
| raise # Re-raise | |
| # --- Background Backup Thread --- | |
| # Global lock for saving data to prevent race conditions between request threads and backup thread | |
| data_lock = threading.Lock() | |
| user_data_lock = threading.Lock() | |
| def periodic_backup(): | |
| while True: | |
| time.sleep(900) # Backup every 15 minutes | |
| logging.info("Запуск периодического резервного копирования...") | |
| try: | |
| # No need to reload data here if save functions acquire lock | |
| # Just trigger the save which handles upload internally | |
| with data_lock: | |
| current_data = load_data() # Load latest state inside lock just before saving | |
| save_data(current_data) # save_data now includes upload if token exists | |
| with user_data_lock: | |
| current_user_data = load_user_data() # Load latest state inside lock | |
| save_user_data(current_user_data) # save_user_data includes upload if token exists | |
| logging.info("Периодическое резервное копирование завершено.") | |
| except Exception as e: | |
| logging.error(f"Ошибка во время периодического резервного копирования: {e}", exc_info=True) | |
| # --- Helper Functions --- | |
| def get_category_counts(products): | |
| counts = {} | |
| if not isinstance(products, list): # Add type check | |
| return counts | |
| for product in products: | |
| if isinstance(product, dict): # Check if product is a dict | |
| category = product.get('category', 'Без категории') | |
| counts[category] = counts.get(category, 0) + 1 | |
| return counts | |
| # --- User Management Functions --- | |
| # Wrap data saving in locks to ensure thread safety | |
| def register_user(login, password, phone, address): | |
| with user_data_lock: | |
| user_data_dict = load_user_data() # Load latest data inside lock | |
| users = user_data_dict.get('users', []) | |
| if any(user.get('login') == login for user in users if isinstance(user, dict)): | |
| return False, "Логин уже занят." | |
| if len(password) < 6: # Basic password length check | |
| return False, "Пароль должен быть не менее 6 символов." | |
| hashed_password = generate_password_hash(password) | |
| new_user = { | |
| 'login': login, | |
| 'password': hashed_password, | |
| 'phone': phone, | |
| 'address': address, | |
| 'points': 0, | |
| 'order_history': [] | |
| } | |
| # Ensure users is a list before appending | |
| if not isinstance(users, list): | |
| users = [] | |
| users.append(new_user) | |
| user_data_dict['users'] = users | |
| save_user_data(user_data_dict) # Save data inside lock | |
| return True, "Регистрация прошла успешно." | |
| def authenticate_user(login, password): | |
| # No lock needed for read-only operations usually, but load_user_data handles potential downloads | |
| user_data_dict = load_user_data() | |
| users = user_data_dict.get('users', []) | |
| if not isinstance(users, list): return None # Safety check | |
| for user in users: | |
| if isinstance(user, dict) and user.get('login') == login: | |
| if check_password_hash(user.get('password', ''), password): | |
| return user # Return the user dictionary | |
| return None | |
| def get_user_profile(login): | |
| # Read-only, no lock needed unless concerned about reads during backup write | |
| user_data_dict = load_user_data() | |
| users = user_data_dict.get('users', []) | |
| if not isinstance(users, list): return None # Safety check | |
| for user in users: | |
| if isinstance(user, dict) and user.get('login') == login: | |
| return user | |
| return None | |
| def update_user_profile(login, phone, address): | |
| user_found = False | |
| with user_data_lock: | |
| user_data_dict = load_user_data() | |
| users = user_data_dict.get('users', []) | |
| if not isinstance(users, list): | |
| save_user_data(user_data_dict) # Save even if structure was bad | |
| return False, "Ошибка структуры данных пользователей." | |
| for user in users: | |
| if isinstance(user, dict) and user.get('login') == login: | |
| user['phone'] = phone | |
| user['address'] = address | |
| user_found = True | |
| break | |
| if user_found: | |
| user_data_dict['users'] = users # Ensure the modified list is assigned back | |
| save_user_data(user_data_dict) # Save updated data | |
| return True, "Профиль обновлен." | |
| else: | |
| # Save data even if user not found, in case load fixed something | |
| save_user_data(user_data_dict) | |
| return False, "Пользователь не найден." | |
| def add_points_to_user(login, points): | |
| user_found = False | |
| with user_data_lock: | |
| user_data_dict = load_user_data() | |
| users = user_data_dict.get('users', []) | |
| if not isinstance(users, list): | |
| save_user_data(user_data_dict) | |
| return False # Indicate failure | |
| for user in users: | |
| if isinstance(user, dict) and user.get('login') == login: | |
| user['points'] = user.get('points', 0) + points | |
| user_found = True | |
| break | |
| if user_found: | |
| user_data_dict['users'] = users | |
| save_user_data(user_data_dict) | |
| return True | |
| else: | |
| save_user_data(user_data_dict) | |
| return False # User not found | |
| def redeem_points_from_user(login, points_to_redeem): | |
| user_found = False | |
| success = False | |
| message = "Пользователь не найден." | |
| with user_data_lock: | |
| user_data_dict = load_user_data() | |
| users = user_data_dict.get('users', []) | |
| if not isinstance(users, list): | |
| save_user_data(user_data_dict) | |
| return False, "Ошибка структуры данных пользователей." | |
| for user in users: | |
| if isinstance(user, dict) and user.get('login') == login: | |
| user_found = True | |
| current_points = user.get('points', 0) | |
| if current_points >= points_to_redeem: | |
| user['points'] = current_points - points_to_redeem | |
| success = True | |
| message = "Баллы успешно списаны" | |
| else: | |
| message = "Недостаточно баллов для списания." | |
| break | |
| if user_found and success: | |
| user_data_dict['users'] = users | |
| save_user_data(user_data_dict) | |
| return True, message | |
| else: | |
| # Save even on failure if load fixed something or if user was found but points insufficient | |
| save_user_data(user_data_dict) | |
| return False, message | |
| def save_order_to_history(login, order_details): | |
| user_found = False | |
| # Use UTC for storage consistency | |
| timestamp_utc = datetime.now(timezone.utc) | |
| with user_data_lock: | |
| user_data_dict = load_user_data() | |
| users = user_data_dict.get('users', []) | |
| if not isinstance(users, list): | |
| save_user_data(user_data_dict) | |
| return False, "Ошибка структуры данных пользователей." | |
| for user in users: | |
| if isinstance(user, dict) and user.get('login') == login: | |
| if 'order_history' not in user or not isinstance(user['order_history'], list): | |
| user['order_history'] = [] # Ensure it exists and is a list | |
| # Add timestamp as ISO string (UTC) | |
| order_details_copy = order_details.copy() # Avoid modifying original dict if passed by reference | |
| order_details_copy['timestamp'] = timestamp_utc.isoformat() | |
| user['order_history'].append(order_details_copy) | |
| user_found = True | |
| break | |
| if user_found: | |
| user_data_dict['users'] = users | |
| save_user_data(user_data_dict) | |
| return True, "Заказ сохранен в истории." | |
| else: | |
| save_user_data(user_data_dict) | |
| return False, "Пользователь не найден." | |
| def get_order_history(login): | |
| # Read-only, lock might be overkill but load_user_data handles potential downloads | |
| user_data_dict = load_user_data() | |
| users = user_data_dict.get('users', []) | |
| if not isinstance(users, list): return [] | |
| user = next((user for user in users if isinstance(user, dict) and user.get('login') == login), None) | |
| if user: | |
| # Return history, newest first | |
| # Sort using the datetime filter function for robustness | |
| history = user.get('order_history', []) | |
| if not isinstance(history, list): return [] # Safety check | |
| # Default datetime for sorting if timestamp is missing or invalid | |
| min_utc_dt = datetime.min.replace(tzinfo=timezone.utc) | |
| sorted_history = sorted( | |
| [item for item in history if isinstance(item, dict)], # Filter out non-dict items | |
| key=lambda x: format_iso_datetime_filter(x.get('timestamp')) or min_utc_dt, | |
| reverse=True | |
| ) | |
| return sorted_history | |
| return [] | |
| # --- Flask Routes --- | |
| def menu(): | |
| # Use lock for loading main data as it might involve download/initial creation | |
| with data_lock: | |
| data = load_data() | |
| products = data.get('products', []) | |
| categories = data.get('categories', []) | |
| news_list = data.get('news', []) | |
| # User data loading is handled within called functions (get_user_profile) | |
| logged_in = 'user_login' in session | |
| user_login = session.get('user_login') | |
| user_profile = get_user_profile(user_login) if logged_in else None | |
| user_points = user_profile.get('points', 0) if user_profile else 0 | |
| category_counts = get_category_counts(products) | |
| # Sort news by timestamp (creation time) descending, most recent first | |
| min_utc_dt = datetime.min.replace(tzinfo=timezone.utc) | |
| news_for_template = sorted( | |
| [item for item in news_list if isinstance(item, dict)], # Filter non-dict news | |
| key=lambda item: format_iso_datetime_filter(item.get('timestamp')) or min_utc_dt, | |
| reverse=True | |
| ) | |
| # HTML Template (incorporating fixes for header and logo animation) | |
| menu_html = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Ultra Flowers - Магазин Цветов</title> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <!-- Updated Fonts --> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css"> | |
| <style> | |
| :root { | |
| /* New Modern Palette */ | |
| --primary-color: #D8BFD8; /* Thistle */ | |
| --secondary-color: #B0E0E6; /* Powder Blue */ | |
| --accent-color: #FFB6C1; /* Light Pink accent */ | |
| --background-light: #FAF0E6; /* Linen */ | |
| --background-card: #FFFFFF; /* White */ | |
| --text-dark: #36454F; /* Charcoal */ | |
| --text-medium: #708090; /* Slate Gray */ | |
| --text-light: #FFFFFF; | |
| --shadow-color: rgba(112, 128, 144, 0.15); /* Slate Gray shadow */ | |
| --border-color: #E0E0E0; /* Light Gray Border */ | |
| --font-primary: 'Poppins', sans-serif; | |
| --font-headings: 'Playfair Display', serif; | |
| --header-height: 180px; /* Approximate header height for padding calculation */ | |
| } | |
| * { | |
| margin: 0; | |
| padding: 0; | |
| box-sizing: border-box; | |
| } | |
| html { | |
| scroll-behavior: smooth; | |
| } | |
| body { | |
| font-family: var(--font-primary); | |
| background-color: var(--background-light); | |
| color: var(--text-dark); | |
| line-height: 1.7; | |
| overflow-x: hidden; | |
| font-weight: 300; /* Lighter default font weight */ | |
| /* FIX 2: Add padding top to body to prevent sticky header overlap */ | |
| padding-top: var(--header-height); | |
| padding-bottom: 100px; /* Space for the fixed navigation bar */ | |
| } | |
| .container { | |
| max-width: 1300px; /* Slightly wider container */ | |
| margin: 0 auto; | |
| padding: 0 20px; /* Padding only left/right */ | |
| /* Removed padding-bottom here, moved to body */ | |
| } | |
| /* --- Header --- */ | |
| .header { | |
| text-align: center; | |
| padding: 25px 20px; /* Adjusted padding */ | |
| background-color: rgba(255, 255, 255, 0.85); /* Slightly less transparent white */ | |
| backdrop-filter: blur(10px); | |
| /* FIX 2: Make header fixed instead of sticky for simpler non-overlap */ | |
| position: fixed; | |
| top: 0; | |
| left: 0; | |
| width: 100%; | |
| z-index: 999; | |
| box-shadow: 0 2px 10px var(--shadow-color); | |
| border-bottom: 1px solid var(--border-color); | |
| height: var(--header-height); /* Give header explicit height */ | |
| display: flex; /* Use flexbox for centering */ | |
| flex-direction: column; | |
| justify-content: center; | |
| align-items: center; | |
| } | |
| .header-logo { | |
| width: 80px; /* Slightly smaller logo */ | |
| height: 80px; | |
| border-radius: 50%; | |
| object-fit: cover; | |
| border: none; /* Removed border */ | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| margin-bottom: 10px; /* Adjusted margin */ | |
| transition: transform 0.5s ease-in-out; /* FIX 3: Animation transition */ | |
| cursor: pointer; /* Add pointer cursor for clickable logo */ | |
| } | |
| /* FIX 3: Add rotating class for animation */ | |
| .header-logo.rotating { | |
| transform: rotate(360deg) scale(1.05); /* Combine rotation with slight scale */ | |
| } | |
| .header h1 { | |
| font-family: var(--font-headings); | |
| font-size: 2.5rem; /* Adjusted size */ | |
| font-weight: 700; | |
| color: var(--text-dark); | |
| margin: 0 0 5px 0; /* Adjusted margin */ | |
| letter-spacing: 1px; | |
| } | |
| .motto { | |
| font-size: 0.9rem; /* Adjusted size */ | |
| color: var(--text-medium); | |
| font-style: italic; | |
| font-weight: 400; | |
| } | |
| /* --- Filters & Search --- */ | |
| /* Adjust margins/padding now that header is fixed */ | |
| .filters-section { | |
| /* Removed padding-top as body now has padding */ | |
| padding-bottom: 30px; | |
| margin-bottom: 30px; | |
| } | |
| .filters-container { | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 12px; /* Slightly increased gap */ | |
| justify-content: center; | |
| margin-bottom: 30px; /* Space before search */ | |
| } | |
| #allCategoriesButton { /* Style for the fixed button */ | |
| display: none; | |
| position: fixed; | |
| bottom: 95px; /* Above nav bar */ | |
| left: 20px; | |
| z-index: 998; /* Below header/modals */ | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| } | |
| .search-container { | |
| text-align: center; | |
| } | |
| #search-input { | |
| width: 100%; | |
| max-width: 550px; | |
| padding: 14px 25px; /* Increased padding */ | |
| font-size: 1rem; | |
| border: 1px solid var(--border-color); | |
| border-radius: 30px; | |
| background: var(--background-card); | |
| color: var(--text-dark); | |
| transition: all 0.3s ease; | |
| box-shadow: 0 2px 8px var(--shadow-color); | |
| } | |
| #search-input::placeholder { | |
| color: var(--text-medium); | |
| font-style: italic; | |
| } | |
| #search-input:focus { | |
| border-color: var(--primary-color); | |
| box-shadow: 0 4px 12px rgba(216, 191, 216, 0.4); /* Primary color shadow */ | |
| outline: none; | |
| } | |
| .category-filter { | |
| padding: 10px 22px; | |
| border: 1px solid var(--border-color); | |
| border-radius: 25px; | |
| background-color: var(--background-card); | |
| color: var(--text-medium); | |
| cursor: pointer; | |
| transition: all 0.3s ease; | |
| font-weight: 400; /* Regular weight */ | |
| font-size: 0.9rem; | |
| white-space: nowrap; | |
| box-shadow: 0 1px 4px var(--shadow-color); | |
| } | |
| .category-filter.active, .category-filter:hover { | |
| background-color: var(--primary-color); | |
| color: var(--text-dark); | |
| border-color: var(--primary-color); | |
| transform: translateY(-2px); | |
| box-shadow: 0 4px 10px rgba(216, 191, 216, 0.3); | |
| } | |
| /* --- Product Grid --- */ | |
| .products-grid { | |
| display: grid; | |
| /* Responsive grid columns */ | |
| grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); | |
| gap: 30px; /* Increased gap */ | |
| padding: 20px 0; | |
| } | |
| .product { | |
| background: var(--background-card); | |
| border-radius: 12px; /* Slightly less rounded */ | |
| padding: 0; /* Padding handled internally now */ | |
| box-shadow: 0 5px 20px var(--shadow-color); | |
| transition: all 0.4s ease; | |
| cursor: pointer; | |
| position: relative; | |
| overflow: hidden; | |
| display: flex; | |
| flex-direction: column; | |
| } | |
| .product:hover { | |
| transform: translateY(-6px); | |
| box-shadow: 0 10px 25px rgba(112, 128, 144, 0.2); /* Darker shadow on hover */ | |
| } | |
| .product-image { | |
| width: 100%; | |
| aspect-ratio: 1 / 1; /* Maintain square aspect ratio */ | |
| background: var(--background-light); /* Light background for image area */ | |
| overflow: hidden; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| transition: all 0.3s ease; | |
| border-radius: 12px 12px 0 0; /* Rounded top corners */ | |
| } | |
| .product-image img { | |
| width: 100%; | |
| height: 100%; | |
| object-fit: cover; /* Cover the area */ | |
| transition: transform 0.5s ease, filter 0.3s ease; | |
| } | |
| .product:hover .product-image img { | |
| transform: scale(1.05); | |
| filter: brightness(1.03); | |
| } | |
| .product-info { | |
| padding: 20px; | |
| text-align: center; | |
| flex-grow: 1; /* Allow info to take remaining space */ | |
| display: flex; | |
| flex-direction: column; | |
| justify-content: space-between; /* Push button to bottom */ | |
| } | |
| .product h2 { | |
| font-family: var(--font-headings); | |
| font-size: 1.3rem; /* Slightly smaller heading */ | |
| font-weight: 600; | |
| color: var(--text-dark); | |
| margin: 0 0 5px 0; | |
| overflow: hidden; | |
| text-overflow: ellipsis; | |
| white-space: nowrap; | |
| } | |
| .product-price { | |
| font-size: 1.2rem; | |
| color: var(--primary-color); /* Use primary color for price */ | |
| font-weight: 700; | |
| margin-bottom: 10px; | |
| } | |
| .product-description { | |
| font-size: 0.85rem; | |
| color: var(--text-medium); | |
| margin-bottom: 15px; | |
| line-height: 1.5; | |
| /* Allow description to wrap for 2 lines */ | |
| overflow: hidden; | |
| text-overflow: ellipsis; | |
| display: -webkit-box; | |
| -webkit-line-clamp: 2; | |
| -webkit-box-orient: vertical; | |
| min-height: calc(1.5em * 2); /* Reserve space for 2 lines */ | |
| } | |
| .product-interaction { | |
| margin-top: auto; /* Push to bottom */ | |
| padding-top: 15px; | |
| } | |
| .quantity-control { | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| gap: 15px; /* Increased gap */ | |
| } | |
| .quantity-button { | |
| background: transparent; | |
| border: 1px solid var(--border-color); | |
| color: var(--text-medium); | |
| border-radius: 50%; | |
| width: 32px; /* Fixed size */ | |
| height: 32px; | |
| font-size: 1rem; | |
| cursor: pointer; | |
| transition: all 0.3s ease; | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| padding: 0; | |
| } | |
| .quantity-button:hover { | |
| background-color: var(--background-light); | |
| border-color: var(--primary-color); | |
| color: var(--primary-color); | |
| } | |
| .quantity { | |
| font-size: 1.1rem; | |
| font-weight: 600; | |
| min-width: 25px; | |
| text-align: center; | |
| color: var(--text-dark); | |
| } | |
| .login-prompt { /* Style for the login link */ | |
| font-size: 0.85rem; | |
| text-align: center; | |
| } | |
| .login-prompt a { | |
| color: var(--primary-color); | |
| text-decoration: underline; | |
| font-weight: 600; | |
| } | |
| .login-prompt a:hover { | |
| color: var(--secondary-color); | |
| } | |
| /* --- Modals --- */ | |
| .modal { | |
| display: none; | |
| position: fixed; | |
| z-index: 1001; | |
| left: 0; | |
| top: 0; | |
| width: 100%; | |
| height: 100%; | |
| background: rgba(54, 69, 79, 0.7); /* Darker backdrop */ | |
| backdrop-filter: blur(8px); | |
| overflow-y: auto; | |
| padding-top: 5vh; /* Space from top */ | |
| padding-bottom: 5vh; | |
| } | |
| .modal-content { | |
| background: var(--background-card); | |
| margin: 0 auto; | |
| padding: 30px 35px; /* Increased padding */ | |
| border-radius: 16px; /* More rounded */ | |
| width: 90%; | |
| max-width: 650px; /* Slightly smaller max-width */ | |
| box-shadow: 0 10px 40px rgba(54, 69, 79, 0.3); | |
| border: none; /* Remove border */ | |
| position: relative; /* For close button */ | |
| animation: slideInUp 0.5s ease-out; | |
| } | |
| @keyframes slideInUp { | |
| from { transform: translateY(50px); opacity: 0; } | |
| to { transform: translateY(0); opacity: 1; } | |
| } | |
| .close { | |
| position: absolute; | |
| top: 15px; | |
| right: 20px; | |
| font-size: 2rem; | |
| font-weight: 300; | |
| color: var(--text-medium); | |
| cursor: pointer; | |
| transition: all 0.3s ease; | |
| line-height: 1; | |
| } | |
| .close:hover { | |
| color: var(--text-dark); | |
| transform: rotate(90deg); | |
| } | |
| .modal-content h2 { | |
| font-family: var(--font-headings); | |
| font-size: 1.8rem; | |
| font-weight: 600; | |
| color: var(--text-dark); | |
| margin-bottom: 25px; | |
| text-align: center; | |
| } | |
| /* --- Cart Specific Styles --- */ | |
| .cart-item { | |
| display: flex; | |
| gap: 15px; | |
| align-items: center; | |
| padding: 15px 0; | |
| border-bottom: 1px solid var(--border-color); | |
| } | |
| .cart-item:last-child { | |
| border-bottom: none; | |
| } | |
| .cart-item img { | |
| width: 80px; | |
| height: 80px; | |
| object-fit: cover; | |
| border-radius: 8px; | |
| flex-shrink: 0; | |
| } | |
| .cart-item-details { | |
| flex-grow: 1; | |
| } | |
| .cart-item-details strong { | |
| font-size: 1rem; | |
| font-weight: 600; | |
| color: var(--text-dark); | |
| display: block; | |
| margin-bottom: 5px; | |
| } | |
| .cart-item-details p { | |
| font-size: 0.85rem; | |
| color: var(--text-medium); | |
| line-height: 1.5; | |
| margin-bottom: 3px; | |
| } | |
| .cart-item-price { | |
| font-size: 1rem; | |
| font-weight: 600; | |
| color: var(--primary-color); | |
| white-space: nowrap; | |
| } | |
| .cart-total { | |
| font-size: 1.4rem; | |
| font-weight: 700; | |
| color: var(--text-dark); | |
| margin: 30px 0 20px 0; | |
| text-align: right; | |
| border-top: 1px solid var(--border-color); | |
| padding-top: 20px; | |
| } | |
| .cart-total span { | |
| color: var(--primary-color); | |
| } | |
| #redeemPointsSection { | |
| margin: 15px 0; | |
| padding: 15px; | |
| background-color: rgba(216, 191, 216, 0.1); /* Light primary background */ | |
| border-radius: 8px; | |
| display: flex; | |
| align-items: center; | |
| gap: 10px; | |
| font-size: 0.9rem; | |
| } | |
| #redeemPointsSection label { | |
| color: var(--text-medium); | |
| } | |
| #redeemPointsCheckbox { | |
| width: auto; /* Reset width */ | |
| margin: 0; | |
| accent-color: var(--primary-color); | |
| } | |
| #pointsToRedeemInput { | |
| width: 80px; | |
| padding: 8px 12px; | |
| font-size: 0.9rem; | |
| border-radius: 20px; | |
| text-align: center; | |
| border: 1px solid var(--border-color); /* Added border */ | |
| } | |
| .cart-actions { | |
| margin-top: 25px; | |
| display: flex; | |
| justify-content: space-between; | |
| gap: 15px; | |
| } | |
| /* --- General Button Styles --- */ | |
| .button { /* Base button style */ | |
| padding: 12px 25px; | |
| border: 1px solid var(--primary-color); | |
| border-radius: 30px; | |
| background-color: var(--primary-color); | |
| color: var(--text-dark); | |
| cursor: pointer; | |
| transition: all 0.3s ease; | |
| font-size: 0.9rem; | |
| font-weight: 600; | |
| text-align: center; | |
| text-decoration: none; | |
| display: inline-block; /* Allow inline behavior */ | |
| } | |
| .button:hover { | |
| background-color: var(--secondary-color); | |
| border-color: var(--secondary-color); | |
| transform: translateY(-2px); | |
| box-shadow: 0 6px 15px rgba(176, 224, 230, 0.4); | |
| } | |
| .button-secondary { /* Outline style */ | |
| background-color: transparent; | |
| border-color: var(--border-color); | |
| color: var(--text-medium); | |
| } | |
| .button-secondary:hover { | |
| background-color: var(--background-light); | |
| border-color: var(--text-medium); | |
| color: var(--text-dark); | |
| box-shadow: 0 4px 10px var(--shadow-color); | |
| } | |
| .button-danger { | |
| background-color: var(--accent-color); | |
| border-color: var(--accent-color); | |
| color: var(--text-dark); | |
| } | |
| .button-danger:hover { | |
| background-color: #f7a0ac; | |
| border-color: #f7a0ac; | |
| box-shadow: 0 6px 15px rgba(255, 182, 193, 0.4); | |
| } | |
| /* --- Auth & Profile Forms --- */ | |
| .auth-form label, .profile-info p, #editProfileForm label { | |
| font-weight: 400; | |
| margin-bottom: 5px; | |
| color: var(--text-medium); | |
| font-size: 0.9rem; | |
| display: block; | |
| } | |
| .auth-form input, #editProfileForm input { | |
| width: 100%; | |
| padding: 12px 20px; | |
| margin-bottom: 15px; | |
| border: 1px solid var(--border-color); | |
| border-radius: 8px; /* Less rounded inputs */ | |
| background: var(--background-light); | |
| color: var(--text-dark); | |
| transition: all 0.3s ease; | |
| font-size: 0.9rem; | |
| } | |
| .auth-form input:focus, #editProfileForm input:focus { | |
| border-color: var(--primary-color); | |
| background-color: var(--background-card); | |
| box-shadow: 0 0 8px rgba(216, 191, 216, 0.3); | |
| outline: none; | |
| } | |
| .auth-buttons { | |
| text-align: center; | |
| margin-top: 25px; | |
| display: flex; | |
| gap: 15px; | |
| justify-content: center; | |
| } | |
| .profile-info strong { | |
| font-weight: 600; | |
| color: var(--text-dark); | |
| margin-right: 8px; | |
| } | |
| .profile-info p { | |
| margin-bottom: 15px; | |
| font-size: 1rem; | |
| border-bottom: 1px solid var(--border-color); | |
| padding-bottom: 10px; | |
| } | |
| .profile-info p:last-of-type { | |
| border-bottom: none; | |
| } | |
| .profile-actions { | |
| margin-top: 20px; | |
| display: flex; | |
| gap: 15px; | |
| } | |
| #registerMessage, #loginMessage, #editProfileMessage { | |
| margin-top: 15px; | |
| text-align: center; | |
| font-size: 0.9rem; | |
| padding: 10px; | |
| border-radius: 8px; | |
| display: none; /* Hide initially */ | |
| } | |
| #registerMessage:not(:empty), #loginMessage:not(:empty), #editProfileMessage:not(:empty) { | |
| display: block; /* Show when content is added */ | |
| } | |
| #registerMessage.success, #loginMessage.success, #editProfileMessage.success { | |
| background-color: rgba(176, 224, 230, 0.2); /* Light secondary background */ | |
| color: var(--secondary-color); | |
| } | |
| #registerMessage.error, #loginMessage.error, #editProfileMessage.error { | |
| background-color: rgba(255, 182, 193, 0.2); /* Light accent background */ | |
| color: var(--accent-color); | |
| } | |
| /* --- Bottom Navigation --- */ | |
| .bottom-nav { | |
| position: fixed; | |
| bottom: 0; | |
| left: 0; | |
| width: 100%; | |
| background: rgba(255, 255, 255, 0.9); | |
| display: flex; | |
| justify-content: space-around; | |
| padding: 10px 0; | |
| border-top: 1px solid var(--border-color); | |
| box-shadow: 0 -4px 15px var(--shadow-color); | |
| backdrop-filter: blur(10px); | |
| z-index: 1000; | |
| } | |
| .bottom-nav .nav-item { | |
| color: var(--text-medium); | |
| text-align: center; | |
| cursor: pointer; | |
| background: none; | |
| border: none; | |
| font-size: 0.7rem; /* Smaller text */ | |
| transition: color 0.3s ease; | |
| flex: 1; /* Equal width */ | |
| padding: 5px 0; | |
| text-decoration: none; /* Added for link */ | |
| display: flex; /* Align icon and text */ | |
| flex-direction: column; | |
| align-items: center; | |
| } | |
| .bottom-nav .nav-item i { | |
| font-size: 1.5rem; /* Slightly smaller icons */ | |
| display: block; | |
| margin-bottom: 5px; | |
| } | |
| .bottom-nav .nav-item:hover, .bottom-nav .nav-item.active { /* Add active state if needed */ | |
| color: var(--primary-color); | |
| } | |
| /* --- Cart Button --- */ | |
| #cart-button { | |
| position: fixed; | |
| bottom: 85px; /* Above nav bar */ | |
| right: 20px; | |
| background-color: var(--primary-color); | |
| color: var(--text-dark); | |
| border: none; | |
| border-radius: 50%; | |
| width: 55px; /* Slightly smaller */ | |
| height: 55px; | |
| font-size: 1.6rem; | |
| cursor: pointer; | |
| box-shadow: 0 6px 20px rgba(216, 191, 216, 0.5); | |
| transition: all 0.3s ease; | |
| z-index: 1000; | |
| display: none; /* Hidden by default */ | |
| align-items: center; | |
| justify-content: center; | |
| } | |
| #cart-button:hover { | |
| transform: scale(1.1) rotate(10deg); | |
| box-shadow: 0 8px 25px rgba(216, 191, 216, 0.7); | |
| } | |
| #cart-count { /* Optional: Add a badge */ | |
| position: absolute; | |
| top: -5px; | |
| right: -5px; | |
| background-color: var(--accent-color); | |
| color: var(--text-dark); | |
| border-radius: 50%; | |
| padding: 2px 6px; | |
| font-size: 0.7rem; | |
| font-weight: bold; | |
| } | |
| /* --- News Modal --- */ | |
| #newsContent { | |
| margin-top: 20px; | |
| max-height: 70vh; /* Limit height */ | |
| overflow-y: auto; /* Add scroll if content overflows */ | |
| } | |
| .news-item { | |
| padding: 20px; | |
| margin-bottom: 20px; | |
| border: 1px solid var(--border-color); | |
| background: var(--background-light); /* Use light background */ | |
| border-radius: 12px; | |
| } | |
| .news-item h3 { | |
| font-family: var(--font-headings); | |
| color: var(--primary-color); | |
| margin-top: 0; | |
| margin-bottom: 10px; | |
| font-size: 1.4rem; | |
| } | |
| .news-item p { | |
| margin: 5px 0; | |
| font-size: 0.9rem; | |
| color: var(--text-medium); | |
| } | |
| .news-item img { | |
| max-width: 100%; | |
| height: auto; | |
| border-radius: 8px; | |
| margin: 15px 0; /* Space around image */ | |
| } | |
| .news-item .timestamp-date, .news-item .expiry-date { | |
| font-size: 0.8rem; | |
| color: var(--text-medium); | |
| margin-top: 10px; | |
| font-style: italic; | |
| } | |
| /* --- Options Modal Specific --- */ | |
| #optionsModal label { | |
| font-weight: 600; | |
| margin-top: 15px; | |
| margin-bottom: 8px; | |
| color: var(--text-dark); | |
| display: block; | |
| } | |
| #optionsModal .quantity-input-container { | |
| margin-bottom: 20px; | |
| display: flex; /* Make it flex */ | |
| justify-content: center; | |
| align-items: center; /* Align items vertically */ | |
| gap: 10px; /* Add gap between elements */ | |
| } | |
| /* Style the number input specifically */ | |
| #quantityInput { | |
| width: 60px; | |
| text-align: center; | |
| border: 1px solid var(--border-color); | |
| border-radius: 5px; | |
| padding: 5px; | |
| font-size: 1rem; | |
| font-weight: 600; | |
| /* Remove default arrows in some browsers */ | |
| -moz-appearance: textfield; | |
| appearance: textfield; | |
| } | |
| #quantityInput::-webkit-outer-spin-button, | |
| #quantityInput::-webkit-inner-spin-button { | |
| -webkit-appearance: none; | |
| margin: 0; | |
| } | |
| #optionsModal textarea#orderComment { | |
| width: 100%; | |
| min-height: 80px; | |
| padding: 12px 15px; | |
| border: 1px solid var(--border-color); | |
| border-radius: 8px; | |
| font-size: 0.9rem; | |
| background: var(--background-light); | |
| color: var(--text-dark); | |
| resize: vertical; | |
| margin-bottom: 20px; | |
| } | |
| #optionsModal select#deliveryTime { | |
| width: 100%; | |
| padding: 12px 15px; | |
| border: 1px solid var(--border-color); | |
| border-radius: 8px; | |
| background: var(--background-light); | |
| color: var(--text-dark); | |
| font-size: 0.9rem; | |
| margin-bottom: 20px; | |
| } | |
| #optionsList { | |
| margin-bottom: 25px; | |
| } | |
| .options-checkbox { | |
| display: flex; /* Use flex for alignment */ | |
| align-items: center; | |
| margin-bottom: 10px; | |
| padding: 10px; | |
| background-color: rgba(216, 191, 216, 0.05); | |
| border-radius: 8px; | |
| } | |
| .options-checkbox input[type="checkbox"] { | |
| margin-right: 10px; | |
| width: auto; /* Reset width */ | |
| accent-color: var(--primary-color); | |
| flex-shrink: 0; /* Prevent shrinking */ | |
| } | |
| .options-checkbox label { /* Label text within */ | |
| margin: 0; | |
| font-weight: 400; | |
| color: var(--text-dark); | |
| flex-grow: 1; | |
| cursor: pointer; /* Make label clickable */ | |
| } | |
| #optionsModal .button { /* Add to Cart button */ | |
| display: block; /* Make it full width */ | |
| width: 100%; | |
| margin-top: 10px; | |
| } | |
| /* --- Product Detail Modal (Swiper) --- */ | |
| #productModal .swiper-container { | |
| width: 100%; | |
| max-width: 450px; /* Limit image size */ | |
| margin: 0 auto 30px; | |
| border-radius: 12px; | |
| overflow: hidden; | |
| box-shadow: 0 5px 15px var(--shadow-color); | |
| } | |
| #productModal .swiper-slide { | |
| background: var(--background-light); | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| aspect-ratio: 1 / 1; | |
| } | |
| #productModal .swiper-slide img { | |
| max-width: 90%; | |
| max-height: 90%; | |
| object-fit: contain; | |
| } | |
| #productModal .swiper-pagination-bullet-active { | |
| background-color: var(--primary-color); | |
| } | |
| #productModal .swiper-button-next, | |
| #productModal .swiper-button-prev { | |
| color: var(--primary-color); | |
| transition: transform 0.3s ease; | |
| --swiper-navigation-size: 30px; /* Adjust size */ | |
| } | |
| #productModal .swiper-button-next:hover, | |
| #productModal .swiper-button-prev:hover { | |
| transform: scale(1.1); | |
| } | |
| #modalContent h2 { /* Product Name */ | |
| font-size: 2.2rem; | |
| margin-bottom: 15px; | |
| } | |
| #modalContent p { /* Product details text */ | |
| font-size: 1rem; | |
| color: var(--text-medium); | |
| margin-bottom: 12px; | |
| line-height: 1.6; | |
| } | |
| #modalContent p strong { | |
| font-weight: 600; | |
| color: var(--text-dark); | |
| } | |
| #modalContent .product-price-modal { /* Price in modal */ | |
| font-size: 1.8rem; | |
| color: var(--primary-color); | |
| font-weight: 700; | |
| margin-bottom: 20px; | |
| text-align: center; | |
| } | |
| /* Footer Info */ | |
| .footer-info { | |
| text-align: center; | |
| margin-top: 50px; | |
| padding: 20px; | |
| color: var(--text-medium); | |
| font-size: 0.85rem; | |
| border-top: 1px solid var(--border-color); | |
| } | |
| /* Utility class for temporary feedback */ | |
| .temp-feedback { | |
| position: fixed; | |
| bottom: 90px; /* Above nav */ | |
| left: 50%; | |
| transform: translateX(-50%); | |
| background-color: var(--secondary-color); | |
| color: var(--text-dark); | |
| padding: 10px 20px; | |
| border-radius: 20px; | |
| z-index: 1002; /* Above modals */ | |
| box-shadow: 0 4px 10px var(--shadow-color); | |
| opacity: 0; /* Start hidden */ | |
| transition: opacity 0.5s ease-out; | |
| pointer-events: none; /* Don't block clicks */ | |
| } | |
| .temp-feedback.show { | |
| opacity: 1; | |
| } | |
| /* Responsive Adjustments */ | |
| @media (max-width: 768px) { | |
| :root { --header-height: 160px; } /* Adjust header height */ | |
| body { padding-top: var(--header-height); } | |
| .header h1 { font-size: 2.0rem; } | |
| .header-logo { width: 70px; height: 70px;} | |
| .product { border-radius: 10px; } | |
| .products-grid { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; } | |
| .modal-content { width: 95%; padding: 25px 20px; } | |
| #productModal .swiper-container { max-width: 90%; } | |
| .cart-actions { flex-direction: column; } | |
| .bottom-nav i { font-size: 1.4rem; } | |
| .bottom-nav span { font-size: 0.7rem; } | |
| #cart-button { width: 50px; height: 50px; font-size: 1.4rem; bottom: 75px; right: 15px; } | |
| #allCategoriesButton { bottom: 75px; left: 15px; padding: 8px 15px; font-size: 0.8rem; } | |
| } | |
| @media (max-width: 480px) { | |
| :root { --header-height: 150px; } /* Adjust header height */ | |
| body { padding-top: var(--header-height); } | |
| .header { padding: 20px 15px; } | |
| .header h1 { font-size: 1.8rem; } | |
| .header-logo { width: 60px; height: 60px;} | |
| .motto { font-size: 0.8rem; } | |
| .filters-container { gap: 8px; } | |
| .category-filter { padding: 8px 15px; font-size: 0.8rem; } | |
| #search-input { padding: 12px 20px; font-size: 0.9rem; } | |
| .products-grid { grid-template-columns: 1fr; gap: 20px; } /* Single column */ | |
| .product h2 { font-size: 1.1rem; } | |
| .product-price { font-size: 1.1rem; } | |
| .product-description { font-size: 0.8rem; } | |
| .modal-content { padding: 20px 15px; } | |
| .modal-content h2 { font-size: 1.5rem; } | |
| .cart-item { flex-direction: column; align-items: flex-start; gap: 10px; } | |
| .cart-item img { width: 60px; height: 60px; } | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <!-- Temporary feedback message container --> | |
| <div id="tempFeedback" class="temp-feedback"></div> | |
| <div class="container"> | |
| <header class="header"> | |
| <img src="{{ LOGO_URL }}" alt="Логотип Ultra Flowers" class="header-logo" id="headerLogo"> | |
| <h1>Ultra Flowers</h1> | |
| <p class="motto">Создаем красоту для каждого момента.</p> | |
| </header> | |
| <section class="filters-section"> | |
| <div class="filters-container"> | |
| <button class="category-filter active" data-category="all">Все Цветы ({{ products|length }})</button> | |
| {% for category in categories %} | |
| <button class="category-filter" data-category="{{ category }}">{{ category }} ({{ category_counts.get(category, 0) }})</button> {# Use .get for safety #} | |
| {% endfor %} | |
| <button id="allCategoriesButton" class="category-filter" onclick="showAllCategories()">Все Категории</button> | |
| </div> | |
| <div class="search-container"> | |
| <input type="text" id="search-input" placeholder="Найти букеты, композиции..."> | |
| </div> | |
| </section> | |
| <main class="products-grid" id="products-grid"> | |
| {% for product in products %} | |
| {% if product is mapping %} {# Check if product is a dictionary-like object #} | |
| <div class="product" | |
| onclick="openModal({{ loop.index0 }})" | |
| data-name="{{ product.get('name', '')|lower }}" | |
| data-description="{{ product.get('description', '')|lower }}" | |
| data-category="{{ product.get('category', 'Без категории') }}" | |
| data-id="{{ loop.index0 }}"> | |
| <div class="product-image"> | |
| {% set photos = product.get('photos', []) %} | |
| {% if photos and photos is iterable and photos|length > 0 %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photos[0] }}" | |
| alt="{{ product.get('name', 'Фото товара') }}" | |
| loading="lazy" | |
| onerror="this.onerror=null; this.src='https://via.placeholder.com/300/E0E0E0/BDBDBD?text=Фото+ошибка';"> {# Added onerror handler #} | |
| {% else %} | |
| <img src="https://via.placeholder.com/300/E0E0E0/BDBDBD?text=Нет+фото" alt="Нет фото"> | |
| {% endif %} | |
| </div> | |
| <div class="product-info"> | |
| <div> <!-- Wrapper for top info --> | |
| <h2>{{ product.get('name', 'Без названия') }}</h2> | |
| <div class="product-price">{{ product.get('price', 0)|int }} ₸</div> {# Format price #} | |
| <p class="product-description">{{ product.get('description', 'Описание отсутствует.') }}</p> | |
| </div> | |
| <div class="product-interaction"> | |
| {% if logged_in %} | |
| <div class="quantity-control"> | |
| <button class="quantity-button" onclick="changeProductQuantity(event, {{ loop.index0 }}, -1)" aria-label="Уменьшить количество">-</button> | |
| <span class="quantity" id="quantity-{{ loop.index0 }}">0</span> | |
| <button class="quantity-button" onclick="changeProductQuantity(event, {{ loop.index0 }}, 1)" aria-label="Увеличить количество">+</button> | |
| </div> | |
| {% else %} | |
| <p class="login-prompt"> | |
| <a href="#" onclick="openProfileModal(); return false;">Войдите</a>, чтобы заказать и получить кэшбэк! | |
| </p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| </div> | |
| {% else %} | |
| <!-- Optionally log or display a message for invalid product data --> | |
| <!-- <p>Ошибка: Некорректные данные товара</p> --> | |
| {% endif %} | |
| {% endfor %} | |
| {% if not products %} | |
| <p style="grid-column: 1 / -1; text-align: center; color: var(--text-medium); font-size: 1.1rem; padding: 40px 0;">Извините, в данный момент нет доступных букетов.</p> | |
| {% endif %} | |
| </main> | |
| <footer class="footer-info"> | |
| © {{ current_year }} Ultra Flowers. Доставка цветов с любовью. | |
| </footer> | |
| </div> | |
| <!-- Product Detail Modal --> | |
| <div id="productModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span> | |
| <div id="modalContent"> | |
| <!-- Product details will be loaded here --> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Options Modal --> | |
| <div id="optionsModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('optionsModal')" aria-label="Закрыть">×</span> | |
| <h2>Параметры заказа</h2> | |
| <label for="quantityInput" style="text-align: center;">Количество:</label> | |
| <div class="quantity-input-container"> | |
| <button class="quantity-button" onclick="changeQuantity(-1)" aria-label="Уменьшить">-</button> | |
| <input type="number" id="quantityInput" min="1" value="1" style="width: 60px; text-align:center;"> {# Simpler input style #} | |
| <button class="quantity-button" onclick="changeQuantity(1)" aria-label="Увеличить">+</button> | |
| </div> | |
| <div id="optionsList"> | |
| <!-- Dynamic options checkboxes will appear here --> | |
| </div> | |
| <label for="orderComment">Комментарий:</label> | |
| <textarea id="orderComment" rows="3" placeholder="Особые пожелания к заказу (например, открытка, цвет ленты)..."></textarea> | |
| <label for="deliveryTime">Время доставки:</label> | |
| <select id="deliveryTime"> | |
| <option value="now">Как можно скорее</option> | |
| {% for i in range(1, 9) %} {# Adjusted range for more realistic delivery slots #} | |
| <option value="{{ i * 60 }}">~ {{ i }} час(а/ов)</option> {# More descriptive text #} | |
| {% endfor %} | |
| <option value="specify">Указать время (в комментарии)</option> | |
| </select> | |
| <button class="button" onclick="confirmAddToCart()" style="width: 100%; margin-top: 20px;">Добавить в корзину</button> | |
| </div> | |
| </div> | |
| <!-- Cart Modal --> | |
| <div id="cartModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span> | |
| <h2>Ваша корзина</h2> | |
| <div id="cartContent"> | |
| <!-- Cart items will be loaded here --> | |
| <p style="text-align: center; color: var(--text-medium);">Ваша корзина пуста.</p> | |
| </div> | |
| <div id="cartTotalsSection" style="display: none;"> {# Hide totals if cart is empty #} | |
| {% if logged_in %} | |
| <div id="redeemPointsSection" style="display: {% if user_points > 0 %}flex{% else %}none{% endif %};"> {# Control visibility based on points #} | |
| <input type="checkbox" id="redeemPointsCheckbox" onchange="togglePointsRedeemInput()"> | |
| <label for="redeemPointsCheckbox">Списать <span id="availablePoints">{{ user_points }}</span> баллов:</label> | |
| <input type="number" id="pointsToRedeemInput" min="0" value="0" style="display:none;" max="{{ user_points }}"> {# Added max attribute #} | |
| </div> | |
| {% endif %} | |
| <div class="cart-total"> | |
| <strong>Итого: <span id="cartTotal">0</span> ₸</strong> | |
| </div> | |
| <div class="cart-actions"> | |
| <button class="button button-secondary" onclick="clearCart()">Очистить корзину</button> | |
| <button class="button" onclick="orderViaWhatsApp()">Оформить заказ в WhatsApp</button> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Profile/Auth Modals --> | |
| <div id="profileModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('profileModal')" aria-label="Закрыть">×</span> | |
| <h2>Профиль</h2> | |
| {% if logged_in %} | |
| <div id="profileContent" class="profile-info"> | |
| <p><strong>Логин:</strong> {{ user_login }}</p> | |
| <p><strong>Баллы:</strong> <span id="profilePoints">{{ user_points }}</span></p> | |
| <p><strong>Телефон:</strong> <span id="profilePhone">{{ user_profile.get('phone', 'Не указан') }}</span></p> {# Use .get for safety #} | |
| <p><strong>Адрес:</strong> <span id="profileAddress">{{ user_profile.get('address', 'Не указан') }}</span></p> {# Use .get for safety #} | |
| <div class="profile-actions"> | |
| <button class="button button-secondary" onclick="openEditProfileModal()">Редактировать</button> | |
| <button class="button button-danger" onclick="logout()">Выйти</button> | |
| </div> | |
| </div> | |
| {% else %} | |
| <div id="authContent"> | |
| <p style="text-align: center; margin-bottom: 25px; color: var(--text-medium);">Войдите или зарегистрируйтесь, чтобы управлять заказами и копить баллы.</p> | |
| <div class="auth-buttons"> | |
| <button class="button" onclick="openLoginModal()">Войти</button> | |
| <button class="button button-secondary" onclick="openRegisterModal()">Регистрация</button> | |
| </div> | |
| </div> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div id="registerModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('registerModal')" aria-label="Закрыть">×</span> | |
| <h2>Регистрация</h2> | |
| <form id="registerForm" class="auth-form"> | |
| <label for="registerLogin">Логин:</label> | |
| <input type="text" id="registerLogin" name="registerLogin" required> | |
| <label for="registerPassword">Пароль (мин. 6 символов):</label> | |
| <input type="password" id="registerPassword" name="registerPassword" required minlength="6"> | |
| <label for="registerPhone">Телефон:</label> | |
| <input type="tel" id="registerPhone" name="registerPhone" placeholder="+7 (___) ___-__-__" required> | |
| <label for="registerAddress">Адрес доставки:</label> | |
| <input type="text" id="registerAddress" name="registerAddress" placeholder="Город, улица, дом, квартира" required> | |
| <button type="submit" class="button" style="width: 100%; margin-top: 10px;">Зарегистрироваться</button> | |
| <div id="registerMessage"></div> | |
| </form> | |
| </div> | |
| </div> | |
| <div id="loginModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('loginModal')" aria-label="Закрыть">×</span> | |
| <h2>Вход</h2> | |
| <form id="loginForm" class="auth-form"> | |
| <label for="loginUsername">Логин:</label> | |
| <input type="text" id="loginUsername" name="loginUsername" required> | |
| <label for="loginPassword">Пароль:</label> | |
| <input type="password" id="loginPassword" name="loginPassword" required> | |
| <button type="submit" class="button" style="width: 100%; margin-top: 10px;">Войти</button> | |
| <div id="loginMessage"></div> | |
| </form> | |
| </div> | |
| </div> | |
| <div id="editProfileModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('editProfileModal')" aria-label="Закрыть">×</span> | |
| <h2>Редактировать профиль</h2> | |
| <form id="editProfileForm" class="auth-form"> | |
| <label for="editPhone">Телефон:</label> | |
| <input type="tel" id="editPhone" name="editPhone" required value="{{ user_profile.get('phone', '') if user_profile else '' }}"> {# Pre-fill value #} | |
| <label for="editAddress">Адрес доставки:</label> | |
| <input type="text" id="editAddress" name="editAddress" required value="{{ user_profile.get('address', '') if user_profile else '' }}"> {# Pre-fill value #} | |
| <button type="submit" class="button" style="width: 100%; margin-top: 10px;">Сохранить</button> | |
| <div id="editProfileMessage"></div> | |
| </form> | |
| </div> | |
| </div> | |
| <!-- News Modal --> | |
| <div id="newsModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('newsModal')" aria-label="Закрыть">×</span> | |
| <h2>Новости и Акции</h2> | |
| <div id="newsContent"> | |
| {% if news_for_template %} | |
| {% for news_item in news_for_template %} | |
| {% if news_item is mapping %} {# Check if news_item is a dictionary #} | |
| <div class="news-item"> | |
| {% set photo = news_item.get('photo') %} | |
| {% if photo %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" | |
| alt="{{ news_item.get('title', 'Фото новости') }}" | |
| onerror="this.style.display='none'"> {# Hide image on error #} | |
| {% endif %} | |
| <h3>{{ news_item.get('title', 'Без заголовка') }}</h3> | |
| <p>{{ news_item.get('text', '') | safe }}</p> {# Allow basic HTML in news text #} | |
| {# --- UPDATED DATE FORMATTING using the registered filter --- #} | |
| {% set timestamp_dt = news_item.timestamp | format_iso_datetime %} | |
| {% if timestamp_dt %} | |
| <p class="timestamp-date">Опубликовано: {{ timestamp_dt.strftime('%d.%m.%Y %H:%M') }} UTC</p> | |
| {% endif %} | |
| {% set expiry = news_item.get('expiry') %} | |
| {% if expiry %} | |
| {% set expiry_dt = expiry | format_iso_datetime %} | |
| {% if expiry_dt %} | |
| <p class="expiry-date">Актуально до: {{ expiry_dt.strftime('%d.%m.%Y %H:%M') }} UTC</p> | |
| {% else %} | |
| <!-- Optional: Show 'Invalid date' if needed --> | |
| <!-- <p class="expiry-date">Актуально до: Неверная дата</p> --> | |
| {% endif %} | |
| {% endif %} | |
| {# --- END UPDATED DATE FORMATTING --- #} | |
| </div> | |
| {% endif %} {# End check if news_item is mapping #} | |
| {% endfor %} | |
| {% else %} | |
| <p style="text-align: center; color: var(--text-medium);">Пока нет новостей.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Cashback Info Modal --> | |
| <div id="cashbackModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('cashbackModal')" aria-label="Закрыть">×</span> | |
| <h2>Программа лояльности</h2> | |
| {% if logged_in %} | |
| <p>Вы получаете <strong>5% кэшбэка</strong> баллами с каждого оплаченного заказа.</p> | |
| <p>Ваш текущий баланс: <strong id="cashbackPoints">{{ user_points }}</strong> баллов.</p> | |
| <p>Баллами можно оплатить часть следующих заказов (до полной суммы минус 1 ₸).</p> | |
| {% else %} | |
| <p><a href="#" onclick="openProfileModal();closeModal('cashbackModal'); return false;" style="color: var(--primary-color); font-weight: 600;">Авторизуйтесь</a>, чтобы копить баллы и узнавать о специальных предложениях!</p> | |
| <p>Зарегистрированные пользователи получают 5% кэшбэка баллами с каждого заказа.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <!-- Floating Cart Button --> | |
| <button id="cart-button" onclick="openCartModal()" aria-label="Открыть корзину"> {# <<< FIXED: Calls openCartModal now #} | |
| <i class="fas fa-shopping-bag"></i> | |
| <span id="cart-count" style="display: none;">0</span> {# Cart count badge #} | |
| </button> | |
| <!-- Bottom Navigation Bar --> | |
| <nav class="bottom-nav"> | |
| <a href="tel:+77077777777" class="nav-item"> {# Replace with actual phone #} | |
| <i class="fas fa-phone-alt"></i> | |
| <span>Звонок</span> | |
| </a> | |
| <button type="button" class="nav-item" onclick="openCashbackModal()"> | |
| <i class="fas fa-gift"></i> | |
| <span>Кэшбэк</span> | |
| </button> | |
| <button type="button" class="nav-item" onclick="openProfileModal()"> | |
| <i class="fas fa-user-circle"></i> | |
| <span>Профиль</span> | |
| </button> | |
| <button type="button" class="nav-item" onclick="openNewsModal()"> | |
| <i class="fas fa-newspaper"></i> | |
| <span>Новости</span> | |
| </button> | |
| </nav> | |
| <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> {# Updated jQuery version #} | |
| {# <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script> #} {# Popper not strictly needed for current setup #} | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script> | |
| <script> | |
| // Wrap all JS code in a ready function to ensure DOM is loaded | |
| $(document).ready(function() { | |
| const products = {{ products|tojson }}; | |
| let selectedProductIndex = null; | |
| let currentOptionsQuantity = 1; // Quantity specifically for the options modal | |
| let availablePoints = {{ user_points }}; | |
| let productQuantities = {}; // Stores quantity { productIndex: quantity } for display on cards | |
| const repoId = "{{ repo_id }}"; | |
| // Ensure userProfile is a valid object or null | |
| let userProfile = {{ user_profile|tojson if user_profile else 'null' }}; | |
| if (typeof userProfile !== 'object' || userProfile === null) { | |
| userProfile = null; | |
| } | |
| // --- Modal Management --- | |
| window.openModal = function(modalIdOrIndex) { // Make functions global for inline onclick | |
| // Check if it's an index (number) or modal ID (string) | |
| if (typeof modalIdOrIndex === 'number') { | |
| // It's a product index | |
| if (modalIdOrIndex >= 0 && modalIdOrIndex < products.length) { | |
| loadProductDetails(modalIdOrIndex); | |
| $('#productModal').fadeIn(200); // Use fadeIn for smoother opening | |
| $('body').css('overflow', 'hidden'); // Prevent background scroll | |
| } else { | |
| console.error("Invalid product index:", modalIdOrIndex); | |
| showTemporaryFeedback("Ошибка: Товар не найден.", true); | |
| } | |
| } else if (typeof modalIdOrIndex === 'string') { | |
| // It's a modal ID | |
| const modal = $('#' + modalIdOrIndex); | |
| if (modal.length) { | |
| modal.fadeIn(200); | |
| $('body').css('overflow', 'hidden'); // Prevent background scroll | |
| // If opening cart, refresh its content | |
| if (modalIdOrIndex === 'cartModal') { | |
| renderCart(); | |
| } | |
| // If opening edit profile, pre-fill if not already done by template | |
| if (modalIdOrIndex === 'editProfileModal' && userProfile) { | |
| $('#editPhone').val(userProfile.phone || ''); | |
| $('#editAddress').val(userProfile.address || ''); | |
| } | |
| } else { | |
| console.error("Modal with ID not found:", modalIdOrIndex); | |
| } | |
| } | |
| } | |
| window.closeModal = function(modalId) { | |
| const modal = $('#' + modalId); | |
| if(modal.length) { | |
| modal.fadeOut(200); // Use fadeOut | |
| } | |
| // Restore background scroll only if no other modals are visible | |
| // Use timeout to allow fadeOut animation to complete before check | |
| setTimeout(() => { | |
| if ($('.modal:visible').length === 0) { | |
| $('body').css('overflow', 'auto'); | |
| } | |
| }, 250); | |
| // Reset specific modal states if needed | |
| if (modalId === 'optionsModal') { | |
| currentOptionsQuantity = 1; | |
| $('#quantityInput').val(1); | |
| $('#orderComment').val(''); | |
| $('#optionsList').html(''); // Clear options | |
| } | |
| // Clear messages in auth modals | |
| if (['registerModal', 'loginModal', 'editProfileModal'].includes(modalId)) { | |
| const messageDivId = '#' + modalId.replace('Modal', 'Message'); | |
| $(messageDivId).text('').removeClass('success error').hide(); // Hide message div | |
| } | |
| } | |
| // Close modal if clicking outside the content area | |
| $('.modal').on('click', function(event) { | |
| if ($(event.target).is('.modal')) { // Check if the click is directly on the modal background | |
| closeModal(this.id); | |
| } | |
| }); | |
| // Close modal on Escape key press | |
| $(document).on('keydown', function(event) { | |
| if (event.key === "Escape") { | |
| $('.modal:visible').each(function() { // Close all visible modals | |
| closeModal(this.id); | |
| }); | |
| } | |
| }); | |
| // --- Product Details --- | |
| function loadProductDetails(index) { | |
| if (index < 0 || index >= products.length || typeof products[index] !== 'object' || products[index] === null) { | |
| $('#modalContent').html('<p>Ошибка: Товар не найден или данные некорректны.</p>'); | |
| return; | |
| } | |
| const product = products[index]; | |
| let photosHtml = ''; | |
| const photos = product.photos || []; | |
| if (photos.length > 0) { | |
| photos.forEach(photo => { | |
| const photoUrl = `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${photo}`; | |
| photosHtml += ` | |
| <div class="swiper-slide"> | |
| <div class="swiper-zoom-container"> | |
| <img src="${photoUrl}" alt="${product.name || 'Фото товара'}" onerror="this.onerror=null; this.src='https://via.placeholder.com/450/E0E0E0/BDBDBD?text=Фото+ошибка';"> | |
| </div> | |
| </div>`; | |
| }); | |
| } else { | |
| photosHtml = `<div class="swiper-slide"><img src="https://via.placeholder.com/450/E0E0E0/BDBDBD?text=Нет+фото" alt="Нет фото"></div>`; | |
| } | |
| let optionsText = 'Нет'; | |
| const options = product.options || []; | |
| if (options.length > 0) { | |
| optionsText = options.map(opt => `${opt.name || '?'} (+${opt.price || 0} ₸)`).join(', '); | |
| } | |
| const detailHtml = ` | |
| <h2>${product.name || 'Без названия'}</h2> | |
| <div class="swiper-container product-swiper"> | |
| <div class="swiper-wrapper">${photosHtml}</div> | |
| <div class="swiper-pagination"></div> | |
| <div class="swiper-button-next"></div> | |
| <div class="swiper-button-prev"></div> | |
| </div> | |
| <p class="product-price-modal">${(product.price || 0)} ₸</p> | |
| <p><strong>Категория:</strong> ${product.category || 'Без категории'}</p> | |
| <p><strong>Описание:</strong> ${product.description || 'Описание отсутствует.'}</p> | |
| <p><strong>Доступные опции:</strong> ${optionsText}</p> | |
| {# Add Add-to-cart button directly in product modal? Maybe better to keep it separate #} | |
| `; | |
| $('#modalContent').html(detailHtml); | |
| initializeSwiper('#productModal .product-swiper'); // Pass specific selector | |
| } | |
| function initializeSwiper(selector) { | |
| // Destroy previous instance if exists | |
| if (window.productSwiperInstance) { | |
| window.productSwiperInstance.destroy(true, true); | |
| window.productSwiperInstance = null; | |
| } | |
| // Ensure container exists before initializing | |
| const swiperContainer = $(selector); | |
| if (swiperContainer.length > 0) { | |
| const slides = swiperContainer.find('.swiper-slide'); | |
| window.productSwiperInstance = new Swiper(swiperContainer[0], { // Get DOM element | |
| slidesPerView: 1, | |
| spaceBetween: 10, | |
| loop: slides.length > 1, // Loop only if more than 1 slide | |
| grabCursor: true, | |
| pagination: { el: swiperContainer.find('.swiper-pagination')[0], clickable: true }, | |
| navigation: { nextEl: swiperContainer.find('.swiper-button-next')[0], prevEl: swiperContainer.find('.swiper-button-prev')[0] }, | |
| zoom: { maxRatio: 3, toggle: true }, // Enable zoom | |
| keyboard: true, // Enable keyboard navigation | |
| }); | |
| } | |
| } | |
| // --- Options Modal Logic --- | |
| function openOptionsModal(index) { | |
| if (!{{ logged_in|lower }}) { | |
| // Close product modal if open before showing login | |
| closeModal('productModal'); | |
| openModal('profileModal'); // Redirect to login/register if not logged in | |
| return; | |
| } | |
| if (index < 0 || index >= products.length || typeof products[index] !== 'object' || products[index] === null) { | |
| showTemporaryFeedback("Ошибка: Не удалось загрузить опции товара.", true); | |
| return; | |
| } | |
| selectedProductIndex = index; | |
| const product = products[index]; | |
| const optionsList = $('#optionsList'); | |
| optionsList.html(''); // Clear previous options | |
| const options = product.options || []; | |
| if (options.length > 0) { | |
| optionsList.append('<label>Дополнительные опции:</label>'); // Use append | |
| options.forEach((option, i) => { | |
| // Check if option is valid | |
| if (typeof option === 'object' && option !== null && 'name' in option && 'price' in option) { | |
| optionsList.append(` | |
| <div class="options-checkbox"> | |
| <input type="checkbox" class="option-checkbox" id="option-${index}-${i}" data-name="${option.name}" data-price="${option.price || 0}"> | |
| <label for="option-${index}-${i}">${option.name} (+${option.price || 0} ₸)</label> {# Label associated with input #} | |
| </div> | |
| `); | |
| } | |
| }); | |
| } else { | |
| optionsList.append('<p style="font-size: 0.9em; color: var(--text-medium);">Дополнительные опции не доступны.</p>'); | |
| } | |
| // Reset quantity input for this modal instance | |
| // Use the quantity from the card if > 0, otherwise default to 1 | |
| currentOptionsQuantity = productQuantities[index] > 0 ? productQuantities[index] : 1; | |
| $('#quantityInput').val(currentOptionsQuantity); | |
| $('#orderComment').val(''); // Clear comment | |
| $('#deliveryTime').val('now'); // Reset delivery time | |
| // Close product modal before opening options modal | |
| closeModal('productModal'); | |
| openModal('optionsModal'); | |
| } | |
| window.openOptionsModal = openOptionsModal; // Make global | |
| window.changeQuantity = function(change) { // Make global | |
| const quantityInput = $('#quantityInput'); | |
| let currentValue = parseInt(quantityInput.val()) || 1; | |
| currentOptionsQuantity = Math.max(1, currentValue + change); // Ensure quantity is at least 1 | |
| quantityInput.val(currentOptionsQuantity); | |
| } | |
| // --- Cart Logic --- | |
| function getCart() { | |
| try { | |
| const cartData = localStorage.getItem('cart'); | |
| const cart = JSON.parse(cartData || '[]'); | |
| // Basic validation: ensure it's an array | |
| return Array.isArray(cart) ? cart : []; | |
| } catch (e) { | |
| console.error("Error parsing cart from localStorage:", e); | |
| return []; // Return empty array on error | |
| } | |
| } | |
| function saveCart(cart) { | |
| try { | |
| // Ensure cart is an array before saving | |
| if (!Array.isArray(cart)) { | |
| console.error("Attempted to save non-array as cart:", cart); | |
| cart = []; // Reset to empty array | |
| } | |
| localStorage.setItem('cart', JSON.stringify(cart)); | |
| updateCartButton(); // Update count and visibility | |
| if ($('#cartModal').is(':visible')) { // Only re-render cart modal if it's currently open | |
| renderCart(); | |
| } | |
| } catch (e) { | |
| console.error("Error saving cart to localStorage:", e); | |
| showTemporaryFeedback("Ошибка сохранения корзины", true); | |
| } | |
| } | |
| window.confirmAddToCart = function() { // Make global | |
| if (selectedProductIndex === null) return; | |
| if (selectedProductIndex < 0 || selectedProductIndex >= products.length || typeof products[selectedProductIndex] !== 'object') { | |
| showTemporaryFeedback("Ошибка: Выбранный товар недействителен.", true); | |
| return; | |
| } | |
| const quantity = parseInt($('#quantityInput').val()) || 1; | |
| if (quantity <= 0) { | |
| showTemporaryFeedback("Укажите количество больше 0", true); | |
| return; | |
| } | |
| let cart = getCart(); | |
| const product = products[selectedProductIndex]; | |
| // --- Get selected options --- | |
| const selectedOptions = []; | |
| $('#optionsList .option-checkbox:checked').each(function() { | |
| selectedOptions.push({ | |
| name: $(this).data('name'), | |
| price: parseFloat($(this).data('price')) || 0 | |
| }); | |
| }); | |
| const comment = $('#orderComment').val().trim(); | |
| const deliveryTime = $('#deliveryTime').val(); | |
| // Create a unique ID for this specific cart item instance (allows same product with different options/comments) | |
| const cartItemId = `${selectedProductIndex}-${Date.now()}`; // Use index + timestamp | |
| // Basic check for product validity before adding | |
| if (!product || typeof product.name === 'undefined' || typeof product.price === 'undefined') { | |
| showTemporaryFeedback("Ошибка: Не удалось добавить товар (некорректные данные).", true); | |
| return; | |
| } | |
| cart.push({ | |
| id: cartItemId, | |
| productIndex: selectedProductIndex, // Store original product index | |
| name: product.name, | |
| basePrice: parseFloat(product.price) || 0, // Ensure basePrice is a number | |
| photo: (product.photos && product.photos.length > 0) ? product.photos[0] : '', | |
| quantity: quantity, | |
| options: selectedOptions, | |
| comment: comment, | |
| deliveryTime: deliveryTime | |
| }); | |
| saveCart(cart); | |
| closeModal('optionsModal'); | |
| // Update quantity on the product card visually | |
| productQuantities[selectedProductIndex] = quantity; // Update visual quantity tracker | |
| updateProductCardQuantity(selectedProductIndex, quantity); | |
| // Briefly show feedback (e.g., item added) | |
| showTemporaryFeedback("Добавлено в корзину!"); | |
| } | |
| function showTemporaryFeedback(message, isError = false) { | |
| const feedbackDiv = $('#tempFeedback'); | |
| feedbackDiv.text(message); | |
| feedbackDiv.removeClass('show error success'); // Remove previous classes | |
| if (isError) { | |
| feedbackDiv.addClass('error'); // You might want to style .error differently | |
| feedbackDiv.css('background-color', 'var(--accent-color)'); // Example error style | |
| } else { | |
| feedbackDiv.addClass('success'); | |
| feedbackDiv.css('background-color', 'var(--secondary-color)'); // Default success style | |
| } | |
| feedbackDiv.addClass('show'); | |
| // Clear previous timeouts if any | |
| if (window.feedbackTimeout) { | |
| clearTimeout(window.feedbackTimeout); | |
| } | |
| if (window.feedbackRemoveTimeout) { | |
| clearTimeout(window.feedbackRemoveTimeout); | |
| } | |
| window.feedbackTimeout = setTimeout(() => { | |
| feedbackDiv.removeClass('show'); | |
| }, 2500); // Show for 2.5 seconds | |
| } | |
| function updateCartButton() { | |
| const cart = getCart(); | |
| const cartButton = $('#cart-button'); | |
| const cartCountBadge = $('#cart-count'); | |
| let totalItems = 0; | |
| // Ensure each item has a valid quantity | |
| cart.forEach(item => { | |
| totalItems += parseInt(item.quantity) || 0; | |
| }); | |
| if (totalItems > 0) { | |
| cartButton.css('display', 'flex'); // Show button using jQuery | |
| cartCountBadge.text(totalItems).show(); // Show badge | |
| } else { | |
| cartButton.hide(); // Hide button | |
| cartCountBadge.hide(); // Hide badge | |
| } | |
| } | |
| function renderCart() { | |
| const cart = getCart(); | |
| const cartContent = $('#cartContent'); | |
| const cartTotalsSection = $('#cartTotalsSection'); | |
| let total = 0; | |
| let cartHtml = ''; | |
| if (cart.length === 0) { | |
| cartHtml = '<p style="text-align: center; color: var(--text-medium);">Ваша корзина пуста.</p>'; | |
| cartTotalsSection.hide(); // Hide totals | |
| } else { | |
| cart.forEach(item => { | |
| // Ensure item structure is valid | |
| if (typeof item !== 'object' || item === null || !item.id) { | |
| console.warn("Skipping invalid cart item:", item); | |
| return; // Skip this item | |
| } | |
| const basePrice = parseFloat(item.basePrice) || 0; | |
| const quantity = parseInt(item.quantity) || 0; | |
| const options = Array.isArray(item.options) ? item.options : []; | |
| const optionsTotal = options.reduce((sum, opt) => sum + (parseFloat(opt.price) || 0), 0); | |
| const itemTotal = (basePrice + optionsTotal) * quantity; | |
| total += itemTotal; | |
| let optionsText = ''; | |
| if (options.length > 0) { | |
| optionsText = '<p>Опции: ' + options.map(o => `${o.name || '?'} (+${o.price || 0} ₸)`).join(', ') + '</p>'; | |
| } | |
| let commentText = item.comment ? `<p>Комментарий: ${$('<div/>').text(item.comment).html()}</p>` : ''; // Basic HTML escaping for comment | |
| let deliveryValue = item.deliveryTime || 'now'; | |
| let deliveryDisplay = 'Как можно скорее'; | |
| if(deliveryValue === 'specify') { | |
| deliveryDisplay = 'Указано в комментарии'; | |
| } else if (deliveryValue !== 'now') { | |
| const hours = parseInt(deliveryValue) / 60; | |
| deliveryDisplay = `~ ${hours} час(а/ов)`; | |
| } | |
| let deliveryText = `<p>Доставка: ${deliveryDisplay}</p>`; | |
| const photoUrl = item.photo ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` : 'https://via.placeholder.com/80/E0E0E0/BDBDBD?text=Нет+фото'; | |
| cartHtml += ` | |
| <div class="cart-item" data-item-id="${item.id}"> | |
| <img src="${photoUrl}" alt="${item.name || 'Фото товара'}" onerror="this.onerror=null; this.src='https://via.placeholder.com/80/E0E0E0/BDBDBD?text=Ошибка'; this.style.width='80px'; this.style.height='80px';"> | |
| <div class="cart-item-details"> | |
| <strong>${item.name || 'Без названия'}</strong> | |
| <p>Цена: ${basePrice} ₸ x ${quantity}</p> | |
| ${optionsText} | |
| ${commentText} | |
| ${deliveryText} | |
| </div> | |
| <span class="cart-item-price">${itemTotal.toFixed(0)} ₸</span> | |
| <button onclick="removeFromCart('${item.id}')" class="button-secondary" style="padding: 5px 10px; font-size: 0.8rem; border-radius: 50%; line-height: 1; margin-left: 10px;" aria-label="Удалить товар">×</button> | |
| </div> | |
| `; | |
| }); | |
| cartTotalsSection.show(); // Show totals | |
| } | |
| cartContent.html(cartHtml); | |
| $('#cartTotal').text(total.toFixed(0)); // Show total price | |
| // Update available points display if logged in | |
| if ({{ logged_in|lower }}) { | |
| $('#availablePoints').text(availablePoints); | |
| const redeemSection = $('#redeemPointsSection'); | |
| if (availablePoints > 0) { | |
| redeemSection.css('display', 'flex'); // Show if points > 0 | |
| } else { | |
| redeemSection.hide(); // Hide if no points | |
| } | |
| // Update max value for points input | |
| $('#pointsToRedeemInput').attr('max', availablePoints); | |
| } else { | |
| $('#redeemPointsSection').hide(); // Hide for non-logged in users | |
| } | |
| // Reset redeem checkbox and input state each time cart is rendered | |
| const redeemCheckbox = $('#redeemPointsCheckbox'); | |
| const pointsInput = $('#pointsToRedeemInput'); | |
| redeemCheckbox.prop('checked', false); // Uncheck checkbox | |
| pointsInput.val(0).hide(); // Reset value and hide input | |
| } | |
| window.renderCart = renderCart; // Make global | |
| window.removeFromCart = function(itemId) { // Make global | |
| let cart = getCart(); | |
| const initialLength = cart.length; | |
| cart = cart.filter(item => item.id !== itemId); | |
| if (cart.length < initialLength) { | |
| // Find which product index this cart item corresponded to | |
| // This is tricky if multiple items can be from the same product index | |
| // Simple approach: Assume removing from cart doesn't reset card quantity display for now | |
| saveCart(cart); // This will re-render the cart | |
| showTemporaryFeedback("Товар удален из корзины"); | |
| } | |
| } | |
| window.clearCart = function() { // Make global | |
| if (confirm("Вы уверены, что хотите очистить корзину?")) { | |
| localStorage.removeItem('cart'); | |
| productQuantities = {}; // Reset card quantities tracker | |
| updateAllProductCardQuantities(); // Update visuals on cards | |
| saveCart([]); // Save empty cart and re-render cart modal | |
| closeModal('cartModal'); | |
| showTemporaryFeedback("Корзина очищена"); | |
| } | |
| } | |
| function updateAllProductCardQuantities() { | |
| $('.product').each(function() { | |
| const index = parseInt($(this).data('id')); | |
| if (!isNaN(index)) { | |
| updateProductCardQuantity(index, productQuantities[index] || 0); | |
| } | |
| }); | |
| } | |
| window.togglePointsRedeemInput = function() { // Make global | |
| const redeemCheckbox = $('#redeemPointsCheckbox'); | |
| const pointsInput = $('#pointsToRedeemInput'); | |
| if (redeemCheckbox.is(':checked')) { | |
| pointsInput.val(availablePoints).show(); // Default to max available points? Or 0? Let's default to max. | |
| } else { | |
| pointsInput.val(0).hide(); // Reset value and hide | |
| } | |
| pointsInput.attr('max', availablePoints); // Ensure max is updated | |
| } | |
| window.orderViaWhatsApp = function() { // Make global | |
| const cart = getCart(); | |
| if (cart.length === 0) { | |
| showTemporaryFeedback("Ваша корзина пуста!", true); | |
| return; | |
| } | |
| if (!userProfile) { | |
| showTemporaryFeedback("Пожалуйста, войдите, чтобы оформить заказ.", true); | |
| closeModal('cartModal'); | |
| openModal('profileModal'); | |
| return; | |
| } | |
| let total = 0; | |
| let orderText = "🌷 *Новый Заказ - Ultra Flowers* 🌷%0A%0A"; | |
| let orderItemsForHistory = []; | |
| cart.forEach((item, index) => { | |
| const basePrice = parseFloat(item.basePrice) || 0; | |
| const quantity = parseInt(item.quantity) || 0; | |
| const options = Array.isArray(item.options) ? item.options : []; | |
| const optionsTotal = options.reduce((sum, opt) => sum + (parseFloat(opt.price) || 0), 0); | |
| const itemTotal = (basePrice + optionsTotal) * quantity; | |
| total += itemTotal; | |
| orderText += `*${index + 1}. ${item.name || 'Без названия'}* (${basePrice} ₸) x ${quantity}`; | |
| if (options.length > 0) { | |
| orderText += "%0A Опции: " + options.map(o => `${o.name || '?'} (+${o.price || 0} ₸)`).join(', '); | |
| } | |
| if (item.comment) { | |
| orderText += `%0A Комментарий: ${encodeURIComponent(item.comment)}`; // Encode comment | |
| } | |
| let deliveryValue = item.deliveryTime || 'now'; | |
| let deliveryDisplay = 'Как можно скорее'; | |
| if(deliveryValue === 'specify') { | |
| deliveryDisplay = 'Указано в комментарии'; | |
| } else if (deliveryValue !== 'now') { | |
| const hours = parseInt(deliveryValue) / 60; | |
| deliveryDisplay = `~ ${hours} час(а/ов)`; | |
| } | |
| orderText += `%0A Доставка: ${deliveryDisplay}`; | |
| orderText += `%0A *Сумма по позиции:* ${itemTotal.toFixed(0)} ₸%0A%0A`; // Item subtotal | |
| orderItemsForHistory.push({ | |
| name: item.name || 'Без названия', | |
| quantity: quantity, | |
| basePrice: basePrice, | |
| options: options, | |
| comment: item.comment, | |
| deliveryTime: deliveryValue, | |
| itemTotal: itemTotal | |
| }); | |
| }); | |
| let redeemedPoints = 0; | |
| const redeemCheckbox = $('#redeemPointsCheckbox'); | |
| if (redeemCheckbox.is(':checked')) { | |
| redeemedPoints = parseInt($('#pointsToRedeemInput').val()) || 0; | |
| if (redeemedPoints <= 0) { | |
| // Don't redeem if points are zero or negative | |
| redeemedPoints = 0; | |
| finalizeOrderWhatsApp(orderText, orderItemsForHistory, total, redeemedPoints); | |
| return; | |
| } | |
| if (redeemedPoints > availablePoints) { | |
| showTemporaryFeedback(`Недостаточно баллов! Доступно: ${availablePoints}`, true); | |
| $('#pointsToRedeemInput').val(availablePoints); // Correct input | |
| return; | |
| } | |
| // Allow redeeming points up to total amount - 1 (leave 1 KZT to pay) | |
| const maxRedeemable = total > 1 ? Math.floor(total - 1) : 0; | |
| if (redeemedPoints > maxRedeemable) { | |
| const correctedRedeem = Math.min(availablePoints, maxRedeemable); | |
| showTemporaryFeedback(`Максимальное списание: ${correctedRedeem} ₸. Скорректировано.`, true); | |
| $('#pointsToRedeemInput').val(correctedRedeem); | |
| redeemedPoints = correctedRedeem; | |
| if (redeemedPoints <= 0) { | |
| finalizeOrderWhatsApp(orderText, orderItemsForHistory, total, 0); // Finalize without redemption | |
| return; | |
| } | |
| } | |
| // Proceed with redeeming points via AJAX | |
| $.post('/redeem_points', { points: redeemedPoints }) | |
| .done(function(response) { | |
| if (response.status === 'success') { | |
| availablePoints -= redeemedPoints; // Update client-side count | |
| $('#availablePoints').text(availablePoints); | |
| $('#profilePoints').text(availablePoints); // Update profile modal too | |
| // Update total after successful redemption | |
| const finalTotal = Math.max(0, total - redeemedPoints); | |
| showTemporaryFeedback(`${redeemedPoints} баллов списано!`); | |
| finalizeOrderWhatsApp(orderText, orderItemsForHistory, finalTotal, redeemedPoints); | |
| } else { | |
| showTemporaryFeedback("Ошибка списания баллов: " + response.message, true); | |
| // Don't proceed with order if points couldn't be redeemed | |
| } | |
| }) | |
| .fail(function() { | |
| showTemporaryFeedback("Ошибка сети при списании баллов. Попробуйте еще раз.", true); | |
| }); | |
| // Don't call finalizeOrderWhatsApp here, wait for AJAX response. | |
| return; // Exit this function, wait for AJAX callback | |
| } else { | |
| // If not redeeming points, finalize immediately | |
| finalizeOrderWhatsApp(orderText, orderItemsForHistory, total, 0); // Pass 0 redeemed points | |
| } | |
| } | |
| function finalizeOrderWhatsApp(orderText, orderItemsForHistory, finalTotal, redeemedPoints) { | |
| // Calculate earned points based on the final amount paid (after redemption) | |
| const pointsEarned = Math.floor(Math.max(0, finalTotal) * 0.05); // 5% cashback | |
| orderText += `Списано баллов: ${redeemedPoints} ₸%0A`; | |
| orderText += `*Итого к оплате:* ${Math.max(0, finalTotal).toFixed(0)} ₸%0A`; | |
| if (pointsEarned > 0) { | |
| orderText += `Будет начислено баллов: ${pointsEarned}%0A`; | |
| } | |
| orderText += `%0A`; | |
| // Add customer info | |
| orderText += `*Клиент:*%0A`; | |
| orderText += `Логин: ${userProfile.login}%0A`; | |
| orderText += `Телефон: ${encodeURIComponent(userProfile.phone || 'Не указан')}%0A`; | |
| orderText += `Адрес: ${encodeURIComponent(userProfile.address || 'Не указан')}`; | |
| // --- Send updates to backend --- | |
| // 1. Add earned points (only if earned > 0) | |
| if (pointsEarned > 0) { | |
| $.post('/add_points', { points: pointsEarned }) | |
| .done(function(response) { | |
| if (response.status === 'success') { | |
| availablePoints += pointsEarned; // Update client-side count | |
| $('#availablePoints').text(availablePoints); | |
| $('#profilePoints').text(availablePoints); | |
| console.log(`${pointsEarned} баллов начислено.`); | |
| } else { | |
| console.error("Ошибка начисления баллов:", response.message); | |
| // Non-critical, proceed with order anyway | |
| } | |
| }) | |
| .fail(function() { | |
| console.error("Сетевая ошибка при начислении баллов."); | |
| }); | |
| } | |
| // 2. Save order to history | |
| const orderDetails = { | |
| items: orderItemsForHistory, | |
| total_amount: Math.max(0, finalTotal), // Amount actually paid | |
| redeemed_points: redeemedPoints, | |
| earned_points: pointsEarned, | |
| // Customer info is linked via session login, no need to store redundantly unless required | |
| // timestamp will be added by backend | |
| }; | |
| $.ajax({ | |
| url: '/save_order_history', | |
| type: 'POST', | |
| contentType: 'application/json', | |
| data: JSON.stringify(orderDetails), | |
| success: function(historyResponse) { | |
| if (historyResponse.status === 'success') { | |
| console.log("История заказа успешно сохранена.") | |
| } else { | |
| console.error("Ошибка сохранения истории заказов:", historyResponse.message); | |
| // Non-critical, proceed with order anyway | |
| } | |
| }, | |
| error: function(jqXHR, textStatus, errorThrown) { | |
| console.error("Сетевая ошибка при сохранении истории заказов:", textStatus, errorThrown); | |
| } | |
| }); | |
| // 3. Open WhatsApp | |
| const whatsappNumber = "+77077777777"; // Replace with actual phone number | |
| const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${orderText}`; | |
| window.open(whatsappUrl, '_blank'); | |
| // 4. Clear cart and close modals after a short delay | |
| setTimeout(() => { | |
| clearCart(); // Clears local storage, updates button, re-renders cart (which will be empty) | |
| closeModal('cartModal'); | |
| showTemporaryFeedback("Заказ отправлен! Корзина очищена."); | |
| }, 500); // Small delay | |
| } | |
| // --- Filtering Logic --- | |
| $('#search-input').on('input', filterProducts); | |
| $('.category-filter').on('click', function() { | |
| $('.category-filter').removeClass('active'); | |
| $(this).addClass('active'); | |
| filterProducts(); | |
| // Show/hide the 'All Categories' button | |
| $('#allCategoriesButton').css('display', ($(this).data('category') !== 'all') ? 'block' : 'none'); | |
| }); | |
| window.showAllCategories = function() { // Make global | |
| $('.category-filter').removeClass('active'); | |
| $('.category-filter[data-category="all"]').addClass('active'); | |
| filterProducts(); | |
| $('#allCategoriesButton').hide(); | |
| } | |
| function filterProducts() { | |
| const searchTerm = $('#search-input').val().toLowerCase().trim(); | |
| const activeCategory = $('.category-filter.active').data('category'); | |
| let hasVisibleProducts = false; | |
| const $grid = $('#products-grid'); | |
| const $noMatchMsg = $grid.find('.no-match-message'); | |
| $grid.find('.product').each(function() { | |
| const $productCard = $(this); | |
| const name = $productCard.data('name') || ''; | |
| const description = $productCard.data('description') || ''; | |
| const category = $productCard.data('category') || 'Без категории'; | |
| const matchesSearch = searchTerm === '' || name.includes(searchTerm) || description.includes(searchTerm); | |
| const matchesCategory = activeCategory === 'all' || category === activeCategory; | |
| if (matchesSearch && matchesCategory) { | |
| $productCard.css('display', 'flex'); // Use flex display | |
| hasVisibleProducts = true; | |
| } else { | |
| $productCard.hide(); | |
| } | |
| }); | |
| // Optional: Show a message if no products match | |
| if (!hasVisibleProducts && products.length > 0) { | |
| if ($noMatchMsg.length === 0) { | |
| $grid.append('<p class="no-match-message" style="grid-column: 1 / -1; text-align: center; color: var(--text-medium); padding: 40px 0;">Букеты не найдены по вашему запросу.</p>'); | |
| } else { | |
| $noMatchMsg.show(); | |
| } | |
| } else { | |
| $noMatchMsg.hide(); | |
| } | |
| } | |
| // Initialize card quantities based on saved cart (if any) - This is complex if cart items are unique instances | |
| // Simple approach: Just initialize display quantities to 0 | |
| function initializeCardQuantities() { | |
| if (Array.isArray(products)) { | |
| products.forEach((_, index) => { | |
| productQuantities[index] = 0; // Start all at 0 | |
| updateProductCardQuantity(index, 0); | |
| }); | |
| } | |
| // Potential future enhancement: If cart logic changes to update existing items, | |
| // you could try to load quantities from the cart here based on productIndex. | |
| // But since cart items are unique instances now, this is less direct. | |
| } | |
| function updateProductCardQuantity(index, quantity) { | |
| const quantitySpan = $(`#quantity-${index}`); | |
| if (quantitySpan.length) { | |
| quantitySpan.text(quantity); | |
| } | |
| } | |
| // --- Auth & Profile Logic --- | |
| window.openProfileModal = function() { openModal('profileModal'); } | |
| window.openRegisterModal = function() { closeModal('profileModal'); openModal('registerModal'); } | |
| window.openLoginModal = function() { closeModal('profileModal'); openModal('loginModal'); } | |
| window.openEditProfileModal = function() { | |
| // Pre-filling is now handled in openModal and template | |
| closeModal('profileModal'); | |
| openModal('editProfileModal'); | |
| } | |
| window.openNewsModal = function() { openModal('newsModal'); } | |
| window.openCashbackModal = function() { openModal('cashbackModal'); } | |
| window.openCartModal = function() { openModal('cartModal'); } | |
| window.logout = function() { | |
| window.location.href = '/logout'; | |
| } | |
| // --- Product Card Quantity Buttons --- | |
| window.changeProductQuantity = function(event, index, change) { // Make global | |
| event.stopPropagation(); // Prevent product modal from opening | |
| if (!{{ logged_in|lower }}) { | |
| openModal('profileModal'); // Prompt login if not logged in | |
| return; | |
| } | |
| // Find the product card element | |
| const productCard = $(`.product[data-id='${index}']`); | |
| if (!productCard.length) { | |
| console.error("Could not find product card for index:", index); | |
| return; | |
| } | |
| let currentCardQuantity = productQuantities[index] || 0; | |
| let newQuantity = Math.max(0, currentCardQuantity + change); | |
| if (newQuantity > 0) { | |
| // If increasing or setting > 0, open options modal to confirm/customize | |
| // Pass the *new* quantity to the options modal logic | |
| currentOptionsQuantity = newQuantity; // Set global quantity for the modal | |
| openOptionsModal(index); | |
| // The options modal itself will handle adding to cart and updating the final card quantity | |
| } else { // newQuantity is 0 (likely due to clicking '-') | |
| // Update visual display on card to 0 immediately | |
| productQuantities[index] = 0; | |
| updateProductCardQuantity(index, 0); | |
| // If quantity becomes 0 by clicking '-', remove corresponding items from cart | |
| let cart = getCart(); | |
| const initialLength = cart.length; | |
| // Remove ALL items in cart matching this productIndex | |
| cart = cart.filter(item => item.productIndex !== index); | |
| if (cart.length < initialLength) { | |
| saveCart(cart); // Update cart if items were removed | |
| showTemporaryFeedback("Удалено из корзины"); | |
| } | |
| } | |
| } | |
| // --- AJAX Form Submissions --- | |
| function handleFormSubmit(formId, url, successCallback) { | |
| $('#' + formId).on('submit', function(event) { | |
| event.preventDefault(); | |
| const $form = $(this); | |
| const $messageDiv = $('#' + formId.replace('Form', 'Message')); // e.g., #registerMessage | |
| const $submitButton = $form.find('button[type="submit"]'); | |
| const originalButtonText = $submitButton.text(); | |
| $submitButton.prop('disabled', true).text('Обработка...'); // Disable button | |
| $messageDiv.text('').removeClass('success error').hide(); // Clear previous messages | |
| $.post(url, $form.serialize()) | |
| .done(function(response) { | |
| if (response.status === 'success') { | |
| $messageDiv.text(response.message || 'Успешно!').removeClass('error').addClass('success').show(); | |
| if (successCallback) { | |
| successCallback(response); | |
| } | |
| } else { | |
| $messageDiv.text(response.message || 'Произошла ошибка.').removeClass('success').addClass('error').show(); | |
| } | |
| }) | |
| .fail(function(jqXHR, textStatus, errorThrown) { | |
| let errorMsg = 'Ошибка сети. Пожалуйста, попробуйте еще раз.'; | |
| // Try to get more specific error from server response if available | |
| if (jqXHR.responseJSON && jqXHR.responseJSON.message) { | |
| errorMsg = jqXHR.responseJSON.message; | |
| } else if (jqXHR.responseText) { | |
| // Fallback for non-JSON errors | |
| try { | |
| const errorData = JSON.parse(jqXHR.responseText); | |
| if (errorData.message) errorMsg = errorData.message; | |
| } catch(e) { /* Ignore parsing error */ } | |
| } | |
| $messageDiv.text(errorMsg).removeClass('success').addClass('error').show(); | |
| }) | |
| .always(function() { | |
| // Re-enable button | |
| $submitButton.prop('disabled', false).text(originalButtonText); | |
| }); | |
| }); | |
| } | |
| handleFormSubmit('registerForm', '/register', function(response) { | |
| $('#registerForm')[0].reset(); // Clear the form | |
| showTemporaryFeedback("Регистрация успешна! Теперь вы можете войти."); | |
| setTimeout(() => { closeModal('registerModal'); openModal('loginModal'); }, 1500); // Close after delay & open login | |
| }); | |
| handleFormSubmit('loginForm', '/login', function(response) { | |
| // Reload the page on successful login to update user state everywhere | |
| showTemporaryFeedback("Вход выполнен успешно! Перезагрузка..."); | |
| setTimeout(() => { window.location.reload(); }, 1000); | |
| }); | |
| handleFormSubmit('editProfileForm', '/update_profile', function(response) { | |
| // Update userProfile variable and profile modal display | |
| if (response.status === 'success' && userProfile) { | |
| userProfile.phone = $('#editPhone').val(); | |
| userProfile.address = $('#editAddress').val(); | |
| $('#profilePhone').text(userProfile.phone); | |
| $('#profileAddress').text(userProfile.address); | |
| showTemporaryFeedback("Профиль успешно обновлен!"); | |
| setTimeout(() => { closeModal('editProfileModal'); /* Don't reopen profile automatically */ }, 1000); | |
| } | |
| }); | |
| // --- FIX 3: Logo Animation --- | |
| $('#headerLogo').on('click', function() { | |
| const $logo = $(this); | |
| if (!$logo.hasClass('rotating')) { // Prevent re-triggering during animation | |
| $logo.addClass('rotating'); | |
| setTimeout(() => { | |
| $logo.removeClass('rotating'); | |
| }, 500); // Match CSS transition duration (0.5s) | |
| } | |
| }); | |
| // --- Initial Setup --- | |
| updateCartButton(); // Initialize cart button state | |
| initializeCardQuantities(); // Set initial card quantities to 0 (or load from cart if logic changes) | |
| filterProducts(); // Apply initial filter (show all) | |
| // Add a small delay before rendering cart on load if needed, e.g., if points update slowly | |
| // setTimeout(renderCart, 100); // Example: render cart after 100ms | |
| }); // End of $(document).ready() | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| current_year = datetime.now().year | |
| # Pass necessary variables to the template | |
| return render_template_string( | |
| menu_html, | |
| products=products, | |
| categories=categories, | |
| category_counts=category_counts, | |
| repo_id=REPO_ID, | |
| LOGO_URL=LOGO_URL, | |
| logged_in=logged_in, | |
| user_login=user_login, | |
| user_points=user_points, | |
| user_profile=user_profile, | |
| news_for_template=news_for_template, | |
| current_year=current_year | |
| ) | |
| def product_detail(index): | |
| # This route *could* load product details specifically for the modal via AJAX, | |
| # but the current implementation loads all product data initially and uses JS. | |
| # Keeping this route might be useful for direct linking or future enhancements. | |
| # For now, let's make it return the data needed by the JS `loadProductDetails` if called directly. | |
| with data_lock: # Use lock for reading main data | |
| data = load_data() | |
| products = data.get('products', []) | |
| if 0 <= index < len(products) and isinstance(products[index], dict): | |
| product = products[index] | |
| # Return JSON data for the specific product | |
| return jsonify(product) | |
| else: | |
| return jsonify({'error': 'Товар не найден или данные некорректны'}), 404 | |
| def admin(): | |
| # Basic Auth - Consider a more robust system for production | |
| auth = request.authorization | |
| # Load credentials securely from environment variables | |
| ADMIN_USERNAME = os.getenv("ADMIN_USER", "admin") # Default only for dev | |
| ADMIN_PASSWORD = os.getenv("ADMIN_PASS", "secret") # Default only for dev | |
| # Check if credentials are provided and valid | |
| if not auth or not (auth.username == ADMIN_USERNAME and auth.password == ADMIN_PASSWORD): | |
| # Log failed attempt, potentially rate-limit | |
| logging.warning(f"Failed admin login attempt for user: {auth.username if auth else 'None'} from IP: {request.remote_addr}") | |
| # Return 401 Unauthorized with WWW-Authenticate header to prompt login | |
| return ('Доступ запрещен. Требуется авторизация.', 401, {'WWW-Authenticate': 'Basic realm="Admin Login Required"'}) | |
| # --- If authenticated, proceed --- | |
| # Use locks for loading/saving data | |
| with data_lock: | |
| data = load_data() | |
| products = data.get('products', []) | |
| categories = data.get('categories', []) | |
| news_list = data.get('news', []) | |
| # Ensure data structures are lists | |
| if not isinstance(products, list): products = [] | |
| if not isinstance(categories, list): categories = [] | |
| if not isinstance(news_list, list): news_list = [] | |
| if request.method == 'POST': | |
| action = request.form.get('action') | |
| try: | |
| # --- Category Management --- | |
| if action == 'add_category': | |
| category_name = request.form.get('category_name', '').strip() | |
| if category_name and category_name not in categories: | |
| with data_lock: | |
| data = load_data() # Reload fresh data inside lock | |
| categories = data.get('categories', []) | |
| if not isinstance(categories, list): categories = [] # Ensure list | |
| if category_name not in categories: # Double check | |
| categories.append(category_name) | |
| data['categories'] = categories | |
| save_data(data) # Save inside lock | |
| else: | |
| logging.warning(f"Категория '{category_name}' уже существует (обнаружена при добавлении).") | |
| elif not category_name: | |
| logging.warning("Попытка добавить пустую категорию.") | |
| else: | |
| logging.warning(f"Категория '{category_name}' уже существует.") | |
| return redirect(url_for('admin')) | |
| elif action == 'delete_category': | |
| category_index_str = request.form.get('category_index') | |
| if category_index_str is not None: | |
| category_index = int(category_index_str) | |
| with data_lock: | |
| data = load_data() | |
| categories = data.get('categories', []) | |
| products = data.get('products', []) | |
| if not isinstance(categories, list): categories = [] | |
| if not isinstance(products, list): products = [] | |
| if 0 <= category_index < len(categories): | |
| category_to_delete = categories.pop(category_index) | |
| # Update products using this category | |
| updated_products = [] | |
| for product in products: | |
| if isinstance(product, dict) and product.get('category') == category_to_delete: | |
| product['category'] = 'Без категории' | |
| updated_products.append(product) | |
| data['categories'] = categories | |
| data['products'] = updated_products | |
| save_data(data) | |
| logging.info(f"Категория '{category_to_delete}' удалена.") | |
| else: | |
| logging.warning(f"Попытка удаления категории с неверным индексом: {category_index}") | |
| else: | |
| logging.warning("Индекс категории не предоставлен для удаления.") | |
| return redirect(url_for('admin')) | |
| # --- Product Management --- | |
| elif action == 'add': | |
| name = request.form.get('name', '').strip() | |
| price_str = request.form.get('price', '0').replace(',', '.').strip() | |
| price = float(price_str) if price_str else 0.0 | |
| description = request.form.get('description', '').strip() | |
| category = request.form.get('category', 'Без категории') | |
| photos_files = request.files.getlist('photos') | |
| option_names = request.form.getlist('option_names') | |
| option_prices = request.form.getlist('option_prices') | |
| photos_list = [] | |
| options_list = [] | |
| # Basic validation | |
| if not name or price < 0: | |
| logging.error("Ошибка добавления: Название и неотрицательная цена обязательны.") | |
| # Add flash message for user feedback here if desired | |
| return redirect(url_for('admin')) | |
| # Upload photos to HF | |
| if HF_TOKEN_WRITE: | |
| api = HfApi() | |
| uploads_dir = 'uploads_temp' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| for photo in photos_files[:10]: # Limit photos | |
| if photo and photo.filename: | |
| # Sanitize filename and make unique | |
| base, ext = os.path.splitext(photo.filename) | |
| safe_base = secure_filename(base) | |
| photo_filename = f"{safe_base}_{int(time.time())}{ext}" | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| try: | |
| photo.save(temp_path) | |
| api.upload_file( | |
| path_or_fileobj=temp_path, | |
| path_in_repo=f"photos/{photo_filename}", | |
| repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, | |
| commit_message=f"Добавлено фото для товара {name}" | |
| ) | |
| photos_list.append(photo_filename) | |
| logging.info(f"Загружено фото {photo_filename} на HF.") | |
| except Exception as upload_err: | |
| logging.error(f"Ошибка загрузки фото {photo_filename} на HF: {upload_err}") | |
| finally: | |
| if os.path.exists(temp_path): | |
| try: | |
| os.remove(temp_path) | |
| except OSError as rm_err: | |
| logging.error(f"Не удалось удалить временный файл {temp_path}: {rm_err}") | |
| # Clean up temp dir | |
| try: | |
| if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): | |
| os.rmdir(uploads_dir) | |
| except OSError as e: | |
| logging.error(f"Ошибка удаления временной папки {uploads_dir}: {e}") | |
| elif photos_files and any(p.filename for p in photos_files): | |
| logging.warning("HF_TOKEN_WRITE не установлен, загрузка фото пропущена.") | |
| # Process options | |
| for opt_name, opt_price_str in zip(option_names, option_prices): | |
| opt_name = opt_name.strip() | |
| opt_price_str = opt_price_str.replace(',', '.').strip() | |
| if opt_name and opt_price_str is not None: # Ensure price string exists | |
| try: | |
| options_list.append({ | |
| 'name': opt_name, | |
| 'price': float(opt_price_str) | |
| }) | |
| except ValueError: | |
| logging.warning(f"Неверный формат цены для опции '{opt_name}': '{opt_price_str}'. Опция пропущена.") | |
| new_product = { | |
| 'name': name, 'price': price, 'description': description, | |
| 'category': category if category in categories else 'Без категории', | |
| 'photos': photos_list, 'options': options_list | |
| } | |
| with data_lock: | |
| data = load_data() | |
| products = data.get('products', []) | |
| if not isinstance(products, list): products = [] | |
| products.append(new_product) | |
| data['products'] = products | |
| save_data(data) | |
| logging.info(f"Добавлен товар: {name}") | |
| return redirect(url_for('admin')) | |
| elif action == 'edit': | |
| product_index_str = request.form.get('product_index') | |
| if product_index_str is not None: | |
| product_index = int(product_index_str) | |
| with data_lock: | |
| data = load_data() | |
| products = data.get('products', []) | |
| categories = data.get('categories', []) # Load categories too for validation | |
| if not isinstance(products, list): products = [] | |
| if not isinstance(categories, list): categories = [] | |
| if 0 <= product_index < len(products) and isinstance(products[product_index], dict): | |
| product = products[product_index] # Get the product dict | |
| # Update fields similar to 'add' action | |
| new_name = request.form.get('name', product.get('name', '')).strip() | |
| price_str = request.form.get('price', str(product.get('price', 0))).replace(',', '.') | |
| new_price = float(price_str) if price_str else product.get('price', 0) | |
| new_description = request.form.get('description', product.get('description', '')).strip() | |
| new_category = request.form.get('category', product.get('category', 'Без категории')) | |
| # Basic validation | |
| if not new_name or new_price < 0: | |
| logging.error("Ошибка редактирования: Название и неотрицательная цена обязательны.") | |
| # Add flash message | |
| return redirect(url_for('admin')) | |
| product['name'] = new_name | |
| product['price'] = new_price | |
| product['description'] = new_description | |
| product['category'] = new_category if new_category in categories else 'Без категории' | |
| # Handle photos: keep existing + add new | |
| existing_photos_to_keep = request.form.getlist('existing_photos') | |
| new_photos_files = request.files.getlist('photos') | |
| # Filter out any empty strings or invalid values from existing_photos_to_keep | |
| current_photos = [p for p in existing_photos_to_keep if p and isinstance(p, str)] | |
| # Upload new photos | |
| if HF_TOKEN_WRITE and new_photos_files: | |
| api = HfApi() | |
| uploads_dir = 'uploads_temp' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| photo_limit = 10 | |
| for photo in new_photos_files: | |
| if len(current_photos) >= photo_limit: | |
| logging.warning(f"Достигнут лимит фото ({photo_limit}) для товара {product['name']}. Остальные фото пропущены.") | |
| break | |
| if photo and photo.filename: | |
| base, ext = os.path.splitext(photo.filename) | |
| safe_base = secure_filename(base) | |
| photo_filename = f"{safe_base}_{int(time.time())}{ext}" | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| try: | |
| photo.save(temp_path) | |
| api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}", | |
| repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, | |
| commit_message=f"Обновлено фото для товара {product['name']}") | |
| current_photos.append(photo_filename) | |
| logging.info(f"Загружено новое фото {photo_filename} при редактировании.") | |
| except Exception as upload_err: | |
| logging.error(f"Ошибка загрузки фото {photo_filename} на HF при редактировании: {upload_err}") | |
| finally: | |
| if os.path.exists(temp_path): | |
| try: os.remove(temp_path) | |
| except OSError as rm_err: logging.error(f"Не удалось удалить {temp_path}: {rm_err}") | |
| # Clean up temp dir | |
| try: | |
| if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): | |
| os.rmdir(uploads_dir) | |
| except OSError as e: | |
| logging.error(f"Ошибка удаления временной папки {uploads_dir}: {e}") | |
| elif new_photos_files and any(p.filename for p in new_photos_files): | |
| logging.warning("HF_TOKEN_WRITE не установлен, загрузка новых фото при редактировании пропущена.") | |
| product['photos'] = current_photos | |
| # Update options (replace all existing with new list from form) | |
| option_names = request.form.getlist('option_names') | |
| option_prices = request.form.getlist('option_prices') | |
| options_list = [] | |
| for opt_name, opt_price_str in zip(option_names, option_prices): | |
| opt_name = opt_name.strip() | |
| opt_price_str = opt_price_str.replace(',', '.').strip() | |
| if opt_name and opt_price_str is not None: | |
| try: | |
| options_list.append({'name': opt_name, 'price': float(opt_price_str)}) | |
| except ValueError: | |
| logging.warning(f"Неверный формат цены для опции '{opt_name}': '{opt_price_str}' при редактировании. Опция пропущена.") | |
| product['options'] = options_list | |
| # products[product_index] = product # Update the list (already modified by reference) | |
| data['products'] = products # Assign back just in case | |
| save_data(data) # Save changes | |
| logging.info(f"Товар '{product['name']}' (индекс {product_index}) обновлен.") | |
| else: | |
| logging.warning(f"Попытка редактирования товара с неверным индексом или неверными данными: {product_index}") | |
| else: | |
| logging.warning("Индекс товара не предоставлен для редактирования.") | |
| return redirect(url_for('admin')) | |
| elif action == 'delete': | |
| product_index_str = request.form.get('product_index') | |
| if product_index_str is not None: | |
| product_index = int(product_index_str) | |
| deleted_product_name = "N/A" | |
| photos_to_delete = [] | |
| with data_lock: | |
| data = load_data() | |
| products = data.get('products', []) | |
| if not isinstance(products, list): products = [] | |
| if 0 <= product_index < len(products): | |
| # Optionally: Delete associated photos from HF? Risky. | |
| # For now, just remove the product entry. | |
| deleted_product = products.pop(product_index) | |
| deleted_product_name = deleted_product.get('name', 'N/A') | |
| photos_to_delete = deleted_product.get('photos', []) # Get photos for potential later deletion | |
| data['products'] = products | |
| save_data(data) | |
| logging.info(f"Удален товар: {deleted_product_name} (индекс {product_index})") | |
| # Add logic here later to delete photos_to_delete from HF if desired | |
| else: | |
| logging.warning(f"Попытка удаления товара с неверным индексом: {product_index}") | |
| else: | |
| logging.warning("Индекс товара не предоставлен для удаления.") | |
| return redirect(url_for('admin')) | |
| # --- News Management --- | |
| elif action == 'add_news': | |
| news_title = request.form.get('news_title', '').strip() | |
| news_text = request.form.get('news_text', '').strip() # Consider sanitizing HTML | |
| news_photo_file = request.files.get('news_photo') | |
| # Get expiry values safely, default to 0 | |
| expiry_days = int(request.form.get('expiry_days') or 0) | |
| expiry_hours = int(request.form.get('expiry_hours') or 0) | |
| expiry_minutes = int(request.form.get('expiry_minutes') or 0) | |
| if not news_title or not news_text: | |
| logging.error("Ошибка добавления новости: Заголовок и текст обязательны.") | |
| # Add flash message | |
| return redirect(url_for('admin')) | |
| news_photo_filename = None | |
| if HF_TOKEN_WRITE and news_photo_file and news_photo_file.filename: | |
| base, ext = os.path.splitext(news_photo_file.filename) | |
| safe_base = secure_filename(base) | |
| news_photo_filename = f"news_{safe_base}_{int(time.time())}{ext}" | |
| uploads_dir = 'uploads_temp' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| temp_path = os.path.join(uploads_dir, news_photo_filename) | |
| try: | |
| news_photo_file.save(temp_path) | |
| api = HfApi() | |
| api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{news_photo_filename}", | |
| repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, | |
| commit_message=f"Добавлено фото для новости {news_title}") | |
| logging.info(f"Загружено фото новости {news_photo_filename} на HF.") | |
| except Exception as upload_err: | |
| logging.error(f"Ошибка загрузки фото новости {news_photo_filename} на HF: {upload_err}") | |
| news_photo_filename = None # Reset filename if upload failed | |
| finally: | |
| if os.path.exists(temp_path): | |
| try: os.remove(temp_path) | |
| except OSError as rm_err: logging.error(f"Не удалось удалить {temp_path}: {rm_err}") | |
| try: | |
| if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): | |
| os.rmdir(uploads_dir) | |
| except OSError as e: | |
| logging.error(f"Ошибка удаления временной папки {uploads_dir}: {e}") | |
| elif news_photo_file and news_photo_file.filename: | |
| logging.warning("HF_TOKEN_WRITE не установлен, загрузка фото новости пропущена.") | |
| expiry_time = None | |
| total_delta = timedelta(days=expiry_days, hours=expiry_hours, minutes=expiry_minutes) | |
| if total_delta > timedelta(0): | |
| # Store expiry in UTC | |
| expiry_time = datetime.now(timezone.utc) + total_delta | |
| new_news_item = { | |
| 'title': news_title, | |
| 'text': news_text, # Be careful with HTML injection if not sanitized | |
| 'photo': news_photo_filename, | |
| # Store as ISO string (UTC) or None | |
| 'expiry': expiry_time.isoformat() if expiry_time else None, | |
| 'timestamp': datetime.now(timezone.utc).isoformat() # Add creation timestamp (UTC ISO) | |
| } | |
| with data_lock: | |
| data = load_data() | |
| news_list = data.get('news', []) | |
| if not isinstance(news_list, list): news_list = [] | |
| news_list.append(new_news_item) | |
| data['news'] = news_list | |
| save_data(data) | |
| logging.info(f"Добавлена новость: {news_title}") | |
| return redirect(url_for('admin')) | |
| elif action == 'delete_news': | |
| news_index_str = request.form.get('news_index') # This index refers to the sorted list in the admin view | |
| if news_index_str is not None: | |
| news_index_view = int(news_index_str) | |
| with data_lock: | |
| data = load_data() | |
| all_news_raw = data.get('news', []) | |
| if not isinstance(all_news_raw, list): all_news_raw = [] | |
| # Re-sort raw news like in admin view to find the correct item | |
| min_utc_dt = datetime.min.replace(tzinfo=timezone.utc) | |
| sorted_news_for_admin = sorted( | |
| [item for item in all_news_raw if isinstance(item, dict)], | |
| key=lambda item: format_iso_datetime_filter(item.get('timestamp')) or min_utc_dt, | |
| reverse=True | |
| ) | |
| if 0 <= news_index_view < len(sorted_news_for_admin): | |
| item_to_delete = sorted_news_for_admin[news_index_view] | |
| # Find the item in the original raw list to remove it | |
| # This assumes timestamps or titles are unique enough, might need a unique ID later | |
| original_index_to_delete = -1 | |
| for i, item in enumerate(all_news_raw): | |
| if item == item_to_delete: # Compare dictionaries | |
| original_index_to_delete = i | |
| break | |
| if original_index_to_delete != -1: | |
| deleted_news = all_news_raw.pop(original_index_to_delete) | |
| logging.info(f"Удалена новость: {deleted_news.get('title', 'N/A')}") | |
| # Consider deleting photo from HF here if needed | |
| data['news'] = all_news_raw # Update the main data dictionary | |
| save_data(data) | |
| else: | |
| logging.error(f"Не удалось найти новость для удаления в исходном списке (индекс вида {news_index_view}).") | |
| else: | |
| logging.warning(f"Попытка удаления новости с неверным индексом вида: {news_index_view}") | |
| else: | |
| logging.warning("Индекс новости не предоставлен для удаления.") | |
| return redirect(url_for('admin')) | |
| except ValueError as ve: | |
| logging.error(f"Ошибка преобразования значения в админке (action={action}): {ve}") | |
| # Optionally: add flash message to show user | |
| except Exception as e: | |
| logging.error(f"Непредвиденная ошибка в админке (action={action}): {e}", exc_info=True) | |
| # Optionally: add flash message | |
| # Redirect even on error for simplicity, consider flash messages | |
| return redirect(url_for('admin')) | |
| # --- Admin Panel HTML --- | |
| # Sort news list for display in admin panel (use the same sorting as main page) | |
| min_utc_dt = datetime.min.replace(tzinfo=timezone.utc) | |
| admin_news_list = sorted( | |
| [item for item in news_list if isinstance(item, dict)], # Filter non-dicts | |
| key=lambda item: format_iso_datetime_filter(item.get('timestamp')) or min_utc_dt, | |
| reverse=True | |
| ) | |
| # Sort products alphabetically for admin view | |
| admin_products_list = sorted( | |
| [p for p in products if isinstance(p, dict)], # Filter non-dicts | |
| key=lambda p: p.get('name', '').lower() | |
| ) | |
| admin_html = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Админ-панель - Ultra Flowers</title> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap" rel="stylesheet"> | |
| <style> | |
| /* --- Reusing styles from main CSS for consistency --- */ | |
| :root { | |
| --primary-color: #D8BFD8; --secondary-color: #B0E0E6; --accent-color: #FFB6C1; | |
| --background-light: #FAF0E6; --background-card: #FFFFFF; --text-dark: #36454F; | |
| --text-medium: #708090; --text-light: #FFFFFF; --shadow-color: rgba(112, 128, 144, 0.15); | |
| --border-color: #E0E0E0; --font-primary: 'Poppins', sans-serif; --font-headings: 'Playfair Display', serif; | |
| --danger-color: #E57373; --danger-bg: rgba(229, 115, 115, 0.1); | |
| --success-color: #81C784; --success-bg: rgba(129, 199, 132, 0.1); | |
| } | |
| body { font-family: var(--font-primary); background-color: var(--background-light); color: var(--text-dark); padding: 25px; font-weight: 300; } | |
| .container { max-width: 1000px; margin: 0 auto; } | |
| h1, h2 { font-family: var(--font-headings); font-weight: 700; color: var(--text-dark); margin-bottom: 25px; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; } | |
| h1 { font-size: 2rem; } h2 { font-size: 1.5rem; margin-top: 30px; } | |
| .section { background: var(--background-card); padding: 25px; border-radius: 12px; box-shadow: 0 5px 20px var(--shadow-color); margin-bottom: 30px; } | |
| label { display: block; margin: 15px 0 5px; color: var(--text-medium); font-size: 0.9rem; font-weight: 600; } | |
| input[type="text"], input[type="number"], input[type="file"], select, textarea { | |
| width: 100%; padding: 12px 15px; border: 1px solid var(--border-color); border-radius: 8px; | |
| background: var(--background-light); color: var(--text-dark); font-size: 0.9rem; transition: all 0.3s ease; margin-bottom: 10px; | |
| box-sizing: border-box; /* Include padding and border in the element's total width and height */ | |
| } | |
| input[type="file"] { background: var(--background-card); border: none; padding: 10px 0; } /* Style file input differently */ | |
| input[type=number]::-webkit-outer-spin-button, | |
| input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } | |
| input[type=number] { -moz-appearance: textfield; } /* Firefox */ | |
| input:focus, select:focus, textarea:focus { border-color: var(--primary-color); background-color: var(--background-card); box-shadow: 0 0 8px rgba(216, 191, 216, 0.3); outline: none; } | |
| textarea { min-height: 80px; resize: vertical; } | |
| button, .button { | |
| padding: 10px 20px; border: 1px solid var(--primary-color); border-radius: 25px; background-color: var(--primary-color); | |
| color: var(--text-dark); cursor: pointer; margin: 10px 5px 0 0; transition: all 0.3s ease; | |
| font-size: 0.9rem; font-weight: 600; text-decoration: none; display: inline-block; vertical-align: middle; /* Align buttons nicely */ | |
| } | |
| button:hover, .button:hover { background-color: var(--secondary-color); border-color: var(--secondary-color); transform: translateY(-1px); box-shadow: 0 4px 10px rgba(176, 224, 230, 0.4); } | |
| .button-danger { background-color: var(--accent-color); border-color: var(--accent-color); color: var(--text-dark); } | |
| .button-danger:hover { background-color: #f7a0ac; border-color: #f7a0ac; box-shadow: 0 4px 10px rgba(255, 182, 193, 0.4); } | |
| .button-secondary { background-color: transparent; border-color: var(--border-color); color: var(--text-medium); } | |
| .button-secondary:hover { background-color: var(--background-light); border-color: var(--text-medium); color: var(--text-dark); box-shadow: 0 2px 8px var(--shadow-color); } | |
| .list-item { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid var(--border-color); gap: 15px; flex-wrap: wrap;} | |
| .list-item:last-child { border-bottom: none; } | |
| .list-item .item-info { flex-grow: 1; min-width: 200px; } /* Allow wrapping */ | |
| .list-item .item-info span { display: block; margin-bottom: 3px; } /* Ensure block display for wrapping */ | |
| .list-item .item-info span small { color: var(--text-medium); font-size: 0.85em;} | |
| .list-item img.item-thumb { width: 50px; height: 50px; object-fit: cover; border-radius: 4px; flex-shrink: 0; border: 1px solid var(--border-color); } | |
| .list-item .actions { display: flex; gap: 8px; flex-shrink: 0; align-items: center; flex-wrap: wrap; /* Allow actions to wrap */ } | |
| .list-item .actions form { margin: 0; padding: 0; display: inline;} /* Fix form layout issue */ | |
| .list-item .actions button, .list-item .actions .button { margin: 0; padding: 6px 12px; font-size: 0.8rem; } | |
| .options-list .option-item, .photos-list .photo-item { display: flex; gap: 10px; margin-bottom: 8px; align-items: center; flex-wrap: wrap; } | |
| .options-list input { width: calc(50% - 30px); min-width: 120px; margin-bottom: 0; } /* Adjust width */ | |
| .options-list .remove-option-btn { margin-left: auto; padding: 4px 8px; font-size: 0.7rem; border-radius: 50%; line-height: 1; background-color: var(--danger-bg); border: 1px solid var(--danger-color); color: var(--danger-color);} | |
| .options-list .remove-option-btn:hover { background-color: var(--danger-color); color: white; } | |
| .photos-list img { height: 40px; width: auto; margin-right: 5px; border-radius: 3px; border: 1px solid var(--border-color); } | |
| .photos-list span { font-size: 0.8rem; word-break: break-all; flex-grow: 1; margin-right: 5px; color: var(--text-medium);} | |
| .photos-list .button-danger { padding: 4px 8px; font-size: 0.7rem; margin-left: auto; border-radius: 50%; line-height: 1;} | |
| .add-option-button { background-color: var(--success-bg); border-color: var(--success-color); color: var(--success-color); } | |
| .add-option-button:hover { background-color: var(--success-color); border-color: var(--success-color); color: white; box-shadow: 0 4px 10px rgba(129, 199, 132, 0.4); } | |
| /* Edit Modal Styles */ | |
| .modal { display:none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(54, 69, 79, 0.7); backdrop-filter: blur(8px); overflow-y: auto; padding: 5vh 20px; } | |
| .modal-content { background: var(--background-card); margin: 0 auto; padding: 30px; border-radius: 12px; width: 95%; max-width: 700px; box-shadow: 0 10px 40px rgba(54, 69, 79, 0.3); position: relative; animation: slideInAdmin 0.4s ease-out; } | |
| @keyframes slideInAdmin { from { transform: translateY(30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } } | |
| .modal-content h2 { margin-top: 0; } | |
| .close-modal { position: absolute; top: 15px; right: 20px; font-size: 2rem; font-weight: 300; color: var(--text-medium); cursor: pointer; transition: all 0.3s ease; line-height: 1; text-decoration: none; border: none; background: none;} | |
| .close-modal:hover { color: var(--text-dark); transform: rotate(90deg); } | |
| .expiry-inputs div { display: inline-block; margin-right: 10px; } | |
| .expiry-inputs label { display: inline-block; margin-right: 5px; font-weight: normal; font-size: 0.85rem;} | |
| .expiry-inputs input { width: 70px; display: inline-block; padding: 8px 10px; font-size: 0.85rem;} | |
| /* Admin specific helpers */ | |
| .form-section { margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px dashed var(--border-color); } | |
| .form-section:last-child { border-bottom: none; } | |
| .field-hint { font-size: 0.8em; color: var(--text-medium); margin-top: -5px; margin-bottom: 10px; display: block; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <h1>Админ-панель Ultra Flowers</h1> | |
| <!-- Console Message for Debugging --> | |
| <p style="background: #fff3cd; border: 1px solid #ffeeba; color: #856404; padding: 10px; border-radius: 5px; font-size: 0.9em;"> | |
| ℹ️ Если кнопки "Редактировать", "Удалить" или "+ Добавить опцию" не работают, проверьте консоль разработчика в браузере (обычно клавиша F12) на наличие ошибок JavaScript. | |
| </p> | |
| <!-- Управление категориями --> | |
| <div class="section"> | |
| <h2>Управление категориями</h2> | |
| <div class="form-section"> | |
| <form method="POST" action="{{ url_for('admin') }}"> {# Explicit action URL #} | |
| <input type="hidden" name="action" value="add_category"> | |
| <label for="category_name">Название новой категории:</label> | |
| <input type="text" name="category_name" id="category_name" required> | |
| <button type="submit">Добавить категорию</button> | |
| </form> | |
| </div> | |
| <div class="category-list"> | |
| <h3>Существующие категории:</h3> | |
| {% for category in categories %} | |
| <div class="list-item"> | |
| <div class="item-info"><span>{{ category }}</span></div> | |
| <div class="actions"> | |
| <form method="POST" action="{{ url_for('admin') }}" style="display:inline;"> {# Explicit action URL #} | |
| <input type="hidden" name="action" value="delete_category"> | |
| <input type="hidden" name="category_index" value="{{ loop.index0 }}"> | |
| <button type="submit" class="button-danger" onclick="return confirm('Вы уверены, что хотите удалить категорию \'{{ category }}\'? Товары этой категории будут помечены как \'Без категории\'.');">Удалить</button> | |
| </form> | |
| </div> | |
| </div> | |
| {% else %} | |
| <p>Нет категорий.</p> | |
| {% endfor %} | |
| </div> | |
| </div> | |
| <!-- Добавление товара --> | |
| <div class="section"> | |
| <h2>Добавить Товар (Букет/Композицию)</h2> | |
| <form method="POST" enctype="multipart/form-data" action="{{ url_for('admin') }}"> {# Explicit action URL #} | |
| <input type="hidden" name="action" value="add"> | |
| <div class="form-section"> | |
| <label for="name">Название:</label> | |
| <input type="text" name="name" id="name" required> | |
| <label for="price">Цена (₸):</label> | |
| <input type="number" step="0.01" min="0" name="price" id="price" placeholder="Например, 15000" required> | |
| <label for="description">Описание:</label> | |
| <textarea name="description" id="description" rows="4" placeholder="Состав букета, размер, особенности..."></textarea> | |
| <label for="category">Категория:</label> | |
| <select name="category" id="category"> | |
| <option value="Без категории">Без категории</option> | |
| {% for category in categories %} | |
| <option value="{{ category }}">{{ category }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="photos">Фотографии (до 10):</label> | |
| <input type="file" name="photos" id="photos" multiple accept="image/*"> | |
| <span class="field-hint">Можно выбрать несколько файлов.</span> | |
| </div> | |
| <div class="form-section"> | |
| <div class="options-list" id="options-list-add"> | |
| <label>Опции (необязательно):</label> | |
| <!-- Options added dynamically --> | |
| </div> | |
| <button type="button" class="button-secondary add-option-button" onclick="addOptionField('add')">+ Добавить опцию</button> | |
| </div> | |
| <button type="submit" style="margin-top: 20px;">Добавить Товар</button> | |
| </form> | |
| </div> | |
| <!-- Список товаров --> | |
| <div class="section"> | |
| <h2>Список Товаров ({{ admin_products_list|length }})</h2> | |
| <div class="product-list"> | |
| {% for product in admin_products_list %} {# Using sorted list #} | |
| {% if product is mapping %} {# Check if product is dict #} | |
| <div class="list-item"> | |
| {% set photos = product.get('photos', []) %} | |
| {% if photos and photos is iterable and photos|length > 0 %} | |
| <img class="item-thumb" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photos[0] }}" alt="{{ product.get('name', '') }}" onerror="this.style.display='none'"> | |
| {% else %} | |
| <div style="width: 50px; height: 50px; background-color: #eee; flex-shrink: 0; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 0.7em; color: var(--text-medium);">Нет фото</div> | |
| {% endif %} | |
| <div class="item-info"> | |
| <span><strong>{{ product.get('name', 'Без названия') }}</strong> ({{ product.get('category', 'Без категории') }}) - {{ product.get('price', 0) }} ₸</span> | |
| <span><small>{{ product.get('description', '')[:100] }}{% if product.get('description', '')|length > 100 %}...{% endif %}</small></span> | |
| {% set options = product.get('options', []) %} | |
| {% if options and options is iterable and options|length > 0 %} | |
| <span><small>Опции: {{ options|map(attribute='name')|join(', ') }}</small></span> | |
| {% endif %} | |
| </div> | |
| <div class="actions"> | |
| {# FIX 1: Ensure onclick calls openEditModal with the correct ORIGINAL index #} | |
| <button type="button" class="button-secondary" onclick="openEditModal({{ products.index(product) }})">Редакт.</button> {# Find original index #} | |
| <form method="POST" action="{{ url_for('admin') }}" style="display:inline;"> {# Explicit action URL #} | |
| <input type="hidden" name="action" value="delete"> | |
| {# FIX 1: Use the ORIGINAL index for deletion #} | |
| <input type="hidden" name="product_index" value="{{ products.index(product) }}"> {# Find original index #} | |
| <button type="submit" class="button-danger" onclick="return confirm('Вы уверены, что хотите удалить товар \'{{ product.get('name', '') }}\'?');">Удалить</button> | |
| </form> | |
| </div> | |
| </div> | |
| {% endif %} {# End check if product is mapping #} | |
| {% else %} | |
| <p>Нет добавленных товаров.</p> | |
| {% endfor %} | |
| </div> | |
| </div> | |
| <!-- Управление новостями --> | |
| <div class="section"> | |
| <h2>Управление Новостями и Акциями</h2> | |
| <div class="form-section"> | |
| <form method="POST" enctype="multipart/form-data" action="{{ url_for('admin') }}"> {# Explicit action URL #} | |
| <input type="hidden" name="action" value="add_news"> | |
| <label for="news_title">Заголовок новости:</label> | |
| <input type="text" name="news_title" id="news_title" required> | |
| <label for="news_text">Текст новости (можно использовать базовый HTML):</label> | |
| <textarea name="news_text" id="news_text" rows="4" required></textarea> | |
| <label for="news_photo">Фото для новости (необязательно):</label> | |
| <input type="file" name="news_photo" id="news_photo" accept="image/*"> | |
| <label>Срок действия новости (оставьте 0, если бессрочно):</label> | |
| <div class="expiry-inputs"> | |
| <div><label for="expiry_days">Дни:</label><input type="number" name="expiry_days" id="expiry_days" value="0" min="0"></div> | |
| <div><label for="expiry_hours">Часы:</label><input type="number" name="expiry_hours" id="expiry_hours" value="0" min="0" max="23"></div> | |
| <div><label for="expiry_minutes">Мин:</label><input type="number" name="expiry_minutes" id="expiry_minutes" value="0" min="0" max="59"></div> | |
| </div> | |
| <button type="submit" style="margin-top: 20px;">Добавить новость</button> | |
| </form> | |
| </div> | |
| <div class="news-list" style="margin-top: 30px;"> | |
| <h3>Существующие новости ({{ admin_news_list|length }}):</h3> | |
| {% for news_item in admin_news_list %} {# Using sorted list for display #} | |
| {% if news_item is mapping %} {# Check if item is dict #} | |
| <div class="list-item"> | |
| {% set photo = news_item.get('photo') %} | |
| {% if photo %} | |
| <img class="item-thumb" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="{{ news_item.get('title', '') }}" onerror="this.style.display='none'"> | |
| {% else %} | |
| <div style="width: 50px; height: 50px; background-color: #eee; flex-shrink: 0; border-radius: 4px;"></div> | |
| {% endif %} | |
| <div class="item-info"> | |
| <span><strong>{{ news_item.get('title', 'Без заголовка') }}</strong></span> | |
| <span><small>{{ news_item.get('text', '')[:150] | safe }}{% if news_item.get('text', '')|length > 150 %}...{% endif %}</small></span> | |
| {# --- UPDATED DATE FORMATTING using the registered filter --- #} | |
| {% set ts_dt = news_item.timestamp | format_iso_datetime %} | |
| <span><small style="color: var(--text-medium);">Добавлено: {{ ts_dt.strftime('%d.%m.%Y %H:%M') if ts_dt else 'N/A' }} UTC</small></span> | |
| {% set expiry = news_item.get('expiry') %} | |
| {% if expiry %} | |
| {% set expiry_dt = expiry | format_iso_datetime %} | |
| {% if expiry_dt %} | |
| <span ><small style="color: var(--accent-color);">Актуально до: {{ expiry_dt.strftime('%d.%m.%Y %H:%M') }} UTC</small></span> | |
| {% endif %} | |
| {% endif %} | |
| {# --- END UPDATED DATE FORMATTING --- #} | |
| </div> | |
| <div class="actions"> | |
| <form method="POST" action="{{ url_for('admin') }}" style="display:inline;"> {# Explicit action URL #} | |
| <input type="hidden" name="action" value="delete_news"> | |
| {# Pass the index FROM THE SORTED LIST VIEW #} | |
| <input type="hidden" name="news_index" value="{{ loop.index0 }}"> | |
| <button type="submit" class="button-danger" onclick="return confirm('Удалить новость \'{{ news_item.get('title', '') }}\'?');">Удалить</button> | |
| </form> | |
| </div> | |
| </div> | |
| {% endif %} {# End check if item is mapping #} | |
| {% else %} | |
| <p>Нет добавленных новостей.</p> | |
| {% endfor %} | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Модальное окно редактирования товара --> | |
| <div id="editModal" class="modal"> | |
| <div class="modal-content"> | |
| <button type="button" class="close-modal" onclick="closeEditModal()" aria-label="Закрыть">×</button> | |
| <h2>Редактировать Товар</h2> | |
| {# Ensure form targets the correct endpoint #} | |
| <form method="POST" enctype="multipart/form-data" id="editForm" action="{{ url_for('admin') }}"> | |
| <input type="hidden" name="action" value="edit"> | |
| <input type="hidden" name="product_index" id="editProductIndex"> | |
| <div class="form-section"> | |
| <label for="editName">Название:</label> | |
| <input type="text" name="name" id="editName" required> | |
| <label for="editPrice">Цена (₸):</label> | |
| <input type="number" step="0.01" min="0" name="price" id="editPrice" required> | |
| <label for="editDescription">Описание:</label> | |
| <textarea name="description" id="editDescription" rows="4"></textarea> | |
| <label for="editCategory">Категория:</label> | |
| <select name="category" id="editCategory"> | |
| {# Options populated by JS #} | |
| </select> | |
| </div> | |
| <div class="form-section"> | |
| <label>Текущие фотографии (нажмите <span style="color: var(--danger-color); font-weight: bold;">X</span>, чтобы убрать):</label> | |
| <div id="editPhotosList" class="photos-list"> | |
| <!-- Photos will be populated by JS --> | |
| </div> | |
| <label for="editPhotos">Добавить новые фотографии (до 10 всего):</label> | |
| <input type="file" name="photos" id="editPhotos" multiple accept="image/*"> | |
| <span class="field-hint">Новые фото будут добавлены к существующим (если не удалены).</span> | |
| </div> | |
| <div class="form-section"> | |
| <div class="options-list" id="options-list-edit"> | |
| <label>Опции:</label> | |
| <!-- Options will be populated by JS --> | |
| </div> | |
| <button type="button" class="button-secondary add-option-button" onclick="addOptionField('edit')">+ Добавить опцию</button> | |
| </div> | |
| <button type="submit" style="margin-top: 20px;">Сохранить изменения</button> | |
| </form> | |
| </div> | |
| </div> | |
| <script> | |
| // Ensure script runs after DOM is loaded | |
| document.addEventListener('DOMContentLoaded', function() { | |
| // Use the raw products list from Flask for indexing in edit/delete | |
| const allProductsDataAdmin = {{ products|tojson }}; | |
| const allCategoriesAdmin = {{ categories|tojson }}; | |
| const repoIdAdmin = "{{ repo_id }}"; | |
| // --- FIX 1: Make functions globally accessible --- | |
| window.addOptionField = function(context) { | |
| const optionsList = document.getElementById(`options-list-${context}`); | |
| if (!optionsList) { | |
| console.error(`Element not found: options-list-${context}`); | |
| return; // Exit if target list doesn't exist | |
| } | |
| const optionDiv = document.createElement('div'); | |
| optionDiv.className = 'option-item'; | |
| optionDiv.innerHTML = ` | |
| <input type="text" name="option_names" placeholder="Название опции (нпр, Ваза)" required> {# Added required #} | |
| <input type="number" step="0.01" min="0" name="option_prices" placeholder="Доп. цена (₸)" required> {# Added required + min #} | |
| <button type="button" class="button-danger remove-option-btn" onclick="removeParentElement(this)" aria-label="Удалить опцию">X</button> | |
| `; | |
| optionsList.appendChild(optionDiv); | |
| } | |
| // Helper to remove parent element (used for options and photos) | |
| window.removeParentElement = function(buttonElement) { | |
| buttonElement.parentElement.remove(); | |
| } | |
| window.openEditModal = function(index) { | |
| console.log("Attempting to open edit modal for index:", index); // Debug log | |
| if (index < 0 || index >= allProductsDataAdmin.length || typeof allProductsDataAdmin[index] !== 'object') { | |
| alert("Ошибка: Неверный индекс товара для редактирования."); | |
| console.error("Invalid index or product data for edit:", index, allProductsDataAdmin[index]); | |
| return; | |
| } | |
| const product = allProductsDataAdmin[index]; | |
| console.log("Editing product:", product); // Debug log | |
| // --- Populate basic fields --- | |
| document.getElementById('editProductIndex').value = index; | |
| document.getElementById('editName').value = product.name || ''; | |
| document.getElementById('editPrice').value = product.price || 0; | |
| document.getElementById('editDescription').value = product.description || ''; | |
| // --- Populate category select --- | |
| const categorySelect = document.getElementById('editCategory'); | |
| categorySelect.innerHTML = '<option value="Без категории">Без категории</option>'; // Reset options | |
| if (Array.isArray(allCategoriesAdmin)) { | |
| allCategoriesAdmin.forEach(cat => { | |
| const option = document.createElement('option'); | |
| option.value = cat; | |
| option.textContent = cat; | |
| if (product.category === cat) { | |
| option.selected = true; // Select current category | |
| } | |
| categorySelect.appendChild(option); | |
| }); | |
| } | |
| // Fallback if product category isn't in the list | |
| if (!categorySelect.value) { | |
| categorySelect.value = 'Без категории'; | |
| } | |
| // --- Populate photos --- | |
| const photosListDiv = document.getElementById('editPhotosList'); | |
| photosListDiv.innerHTML = ''; // Clear previous | |
| const photos = product.photos || []; | |
| if (Array.isArray(photos) && photos.length > 0) { | |
| photos.forEach((photo) => { | |
| if (typeof photo === 'string' && photo) { // Ensure photo is a non-empty string | |
| const photoUrl = `https://huggingface.co/datasets/${repoIdAdmin}/resolve/main/photos/${photo}`; | |
| const photoDiv = document.createElement('div'); | |
| photoDiv.className = 'photo-item'; | |
| // Use hidden input to track photos to keep. Remove div + input on delete click. | |
| photoDiv.innerHTML = ` | |
| <input type="hidden" name="existing_photos" value="${photo}"> | |
| <img src="${photoUrl}" alt="Текущее фото" style="height: 40px; width: auto;" onerror="this.style.display='none'"> | |
| <span>${photo}</span> | |
| <button type="button" class="button-danger" onclick="removeParentElement(this)" aria-label="Удалить фото">X</button> | |
| `; | |
| photosListDiv.appendChild(photoDiv); | |
| } | |
| }); | |
| } else { | |
| photosListDiv.innerHTML = '<p style="font-size: 0.9em; color: var(--text-medium);">Нет текущих фото.</p>'; | |
| } | |
| // --- Populate options --- | |
| const optionsListDiv = document.getElementById('options-list-edit'); | |
| // Clear previous options but keep the label if it exists or add one | |
| optionsListDiv.innerHTML = '<label>Опции:</label>'; | |
| const options = product.options || []; | |
| if (Array.isArray(options) && options.length > 0) { | |
| options.forEach(option => { | |
| // Ensure option is valid before adding | |
| if (typeof option === 'object' && option !== null) { | |
| const optionDiv = document.createElement('div'); | |
| optionDiv.className = 'option-item'; | |
| optionDiv.innerHTML = ` | |
| <input type="text" name="option_names" value="${option.name || ''}" placeholder="Название опции" required> | |
| <input type="number" step="0.01" min="0" name="option_prices" value="${option.price || 0}" placeholder="Доп. цена (₸)" required> | |
| <button type="button" class="button-danger remove-option-btn" onclick="removeParentElement(this)" aria-label="Удалить опцию">X</button> | |
| `; | |
| optionsListDiv.appendChild(optionDiv); | |
| } | |
| }); | |
| } | |
| // Clear file input for new photos | |
| const editPhotosInput = document.getElementById('editPhotos'); | |
| if (editPhotosInput) { editPhotosInput.value = ''; } | |
| // Show the modal | |
| const editModal = document.getElementById('editModal'); | |
| if(editModal) { | |
| editModal.style.display = 'block'; | |
| document.body.style.overflow = 'hidden'; // Prevent background scroll | |
| console.log("Edit modal should be visible now."); // Debug log | |
| } else { | |
| console.error("Edit modal element not found!"); | |
| } | |
| } | |
| window.closeEditModal = function() { | |
| const editModal = document.getElementById('editModal'); | |
| if(editModal) { | |
| editModal.style.display = 'none'; | |
| } | |
| // Restore scroll only if no other modals are open | |
| if (document.querySelectorAll('.modal[style*="display: block"]').length === 0) { | |
| document.body.style.overflow = 'auto'; | |
| } | |
| // Optional: Reset form, but might be better to keep data if user reopens | |
| // document.getElementById('editForm').reset(); | |
| // Clear dynamic lists | |
| const photosListDiv = document.getElementById('editPhotosList'); | |
| const optionsListDiv = document.getElementById('options-list-edit'); | |
| if(photosListDiv) photosListDiv.innerHTML = ''; | |
| if(optionsListDiv) optionsListDiv.innerHTML = '<label>Опции:</label>'; // Keep label | |
| } | |
| // Close modal on Escape key | |
| document.addEventListener('keydown', function(event) { | |
| if (event.key === "Escape") { | |
| const editModal = document.getElementById('editModal'); | |
| if (editModal && editModal.style.display === 'block') { | |
| closeEditModal(); | |
| } | |
| } | |
| }); | |
| // Close modal on outside click (specific to edit modal) | |
| const editModalElement = document.getElementById('editModal'); | |
| if(editModalElement) { | |
| editModalElement.addEventListener('click', function(event) { | |
| if (event.target === editModalElement) { // Check if click is on the background | |
| closeEditModal(); | |
| } | |
| }); | |
| } | |
| }); // End DOMContentLoaded | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| return render_template_string( | |
| admin_html, | |
| products=products, # Pass original list for index finding | |
| admin_products_list=admin_products_list, # Pass sorted list for display | |
| categories=categories, | |
| repo_id=REPO_ID, | |
| admin_news_list=admin_news_list # Pass sorted news list | |
| ) | |
| # --- API Routes (Login, Register, Profile, Points, History) --- | |
| def register(): | |
| # Simplified data extraction | |
| login = request.form.get('registerLogin') | |
| password = request.form.get('registerPassword') | |
| phone = request.form.get('registerPhone') | |
| address = request.form.get('registerAddress') | |
| if not all([login, password, phone, address]): | |
| return jsonify({'status': 'error', 'message': 'Все поля обязательны для заполнения.'}), 400 | |
| # Input validation (basic) | |
| if len(password) < 6: | |
| return jsonify({'status': 'error', 'message': 'Пароль должен быть не менее 6 символов.'}), 400 | |
| if len(login) < 3: | |
| return jsonify({'status': 'error', 'message': 'Логин должен быть не менее 3 символов.'}), 400 | |
| success, message = register_user(login, password, phone, address) | |
| status_code = 201 if success else 409 # Use 409 Conflict if user exists | |
| return jsonify({'status': 'success' if success else 'error', 'message': message}), status_code | |
| def login(): | |
| # Simplified data extraction | |
| login_username = request.form.get('loginUsername') | |
| login_password = request.form.get('loginPassword') | |
| if not login_username or not login_password: | |
| return jsonify({'status': 'error', 'message': 'Логин и пароль обязательны.'}), 400 | |
| user = authenticate_user(login_username, login_password) | |
| if user: | |
| session.permanent = True # Make session persistent (uses app.permanent_session_lifetime) | |
| session['user_login'] = user['login'] # Store login in session AFTER setting permanent | |
| logging.info(f"Пользователь '{user['login']}' успешно вошел в систему. Session ID: {session.sid if hasattr(session, 'sid') else 'N/A'}") | |
| return jsonify({'status': 'success', 'message': 'Вход выполнен успешно.'}) | |
| else: | |
| logging.warning(f"Неудачная попытка входа для пользователя '{login_username}'.") | |
| return jsonify({'status': 'error', 'message': 'Неверный логин или пароль.'}), 401 | |
| def logout(): | |
| user = session.pop('user_login', None) | |
| session.clear() # Clear entire session for good measure | |
| if user: | |
| logging.info(f"Пользователь '{user}' вышел из системы.") | |
| # Redirect to main page after logout | |
| return redirect(url_for('menu')) | |
| def update_profile(): | |
| if 'user_login' not in session: | |
| return jsonify({'status': 'error', 'message': 'Не авторизован'}), 401 | |
| login = session['user_login'] | |
| # Simplified data extraction | |
| phone = request.form.get('editPhone') | |
| address = request.form.get('editAddress') | |
| if not phone or not address: | |
| return jsonify({'status': 'error', 'message': 'Телефон и адрес обязательны.'}), 400 | |
| success, message = update_user_profile(login, phone, address) | |
| if success: | |
| logging.info(f"Профиль пользователя {login} обновлен.") | |
| return jsonify({'status': 'success', 'message': message}), 200 | |
| else: | |
| # Log failure reason if possible (e.g., user not found, save error) | |
| logging.warning(f"Не удалось обновить профиль для {login}: {message}") | |
| # Determine appropriate status code (404 if not found, 500 if save failed) | |
| status_code = 404 if "не найден" in message else 500 | |
| return jsonify({'status': 'error', 'message': message}), status_code | |
| def add_points(): | |
| if 'user_login' not in session: | |
| return jsonify({'status': 'error', 'message': 'Не авторизован'}), 401 | |
| login = session['user_login'] | |
| try: | |
| # Assume form data from finalizeOrderWhatsApp AJAX call | |
| points_str = request.form.get('points') | |
| if points_str is None: | |
| return jsonify({'status': 'error', 'message': 'Параметр points отсутствует.'}), 400 | |
| points = int(points_str) | |
| if points < 0: # Allow 0 points (e.g., if order total was 0 after redemption) | |
| return jsonify({'status': 'error', 'message': 'Нельзя начислить отрицательные баллы.'}), 400 | |
| except ValueError: | |
| return jsonify({'status': 'error', 'message': 'Неверное количество баллов.'}), 400 | |
| success = add_points_to_user(login, points) | |
| if success: | |
| logging.info(f"Начислено {points} баллов пользователю {login}") | |
| return jsonify({'status': 'success', 'message': f'{points} баллов начислено.'}) | |
| else: | |
| # This case should ideally not happen if user is logged in, means data inconsistency | |
| logging.error(f"Ошибка начисления баллов: пользователь {login} не найден при попытке добавления.") | |
| return jsonify({'status': 'error', 'message': 'Ошибка начисления баллов: пользователь не найден.'}), 500 | |
| def redeem_points(): | |
| if 'user_login' not in session: | |
| return jsonify({'status': 'error', 'message': 'Не авторизован'}), 401 | |
| login = session['user_login'] | |
| try: | |
| # Assume form data from orderViaWhatsApp AJAX call | |
| points_str = request.form.get('points') | |
| if points_str is None: | |
| return jsonify({'status': 'error', 'message': 'Параметр points отсутствует.'}), 400 | |
| points = int(points_str) | |
| if points <= 0: # Must redeem a positive amount | |
| return jsonify({'status': 'error', 'message': 'Количество списываемых баллов должно быть положительным.'}), 400 | |
| except ValueError: | |
| return jsonify({'status': 'error', 'message': 'Неверное количество баллов.'}), 400 | |
| success, message = redeem_points_from_user(login, points) | |
| status_code = 200 if success else 400 # 400 for insufficient points or user error | |
| if success: | |
| logging.info(f"Списано {points} баллов у пользователя {login}") | |
| else: | |
| logging.warning(f"Ошибка списания {points} баллов у пользователя {login}: {message}") | |
| return jsonify({'status': 'success' if success else 'error', 'message': message}), status_code | |
| def save_order_history_route(): # Renamed route function slightly | |
| if 'user_login' not in session: | |
| return jsonify({'status': 'error', 'message': 'Не авторизован'}), 401 | |
| login = session['user_login'] | |
| if not request.is_json: | |
| logging.warning(f"Получен не-JSON запрос на /save_order_history от {login}") | |
| return jsonify({'status': 'error', 'message': 'Запрос должен быть в формате JSON.'}), 400 | |
| order_details = request.get_json() | |
| # Validate basic structure | |
| if not isinstance(order_details, dict) or not isinstance(order_details.get('items'), list) or not isinstance(order_details.get('total_amount'), (int, float)): | |
| logging.warning(f"Получены неполные или некорректные данные заказа для сохранения в историю от {login}: {order_details}") | |
| return jsonify({'status': 'error', 'message': 'Неполные или некорректные данные заказа.'}), 400 | |
| success, message = save_order_to_history(login, order_details) | |
| status_code = 201 if success else 500 # 500 if save failed unexpectedly | |
| if success: | |
| logging.info(f"Заказ сохранен в историю для пользователя {login}") | |
| else: | |
| logging.error(f"Ошибка сохранения заказа в историю для пользователя {login}: {message}") | |
| return jsonify({'status': 'success' if success else 'error', 'message': message}), status_code | |
| # --- App Initialization --- | |
| if __name__ == '__main__': | |
| # Start background backup thread only if HF tokens are set for writing | |
| if HF_TOKEN_WRITE: | |
| backup_thread = threading.Thread(target=periodic_backup, daemon=True) | |
| backup_thread.start() | |
| logging.info("Поток периодического резервного копирования запущен.") | |
| else: | |
| logging.info("HF_TOKEN_WRITE не установлен, резервное копирование на HF отключено.") | |
| # Use Waitress or Gunicorn for production instead of Flask's built-in server | |
| # For development: | |
| port = int(os.environ.get("PORT", 7860)) # Use environment variable for port | |
| # Set debug=False for production/semi-production, host='0.0.0.0' for external access | |
| app.run(debug=False, host='0.0.0.0', port=port) | |