diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,5 +1,4 @@ - from flask import Flask, render_template_string, request, redirect, url_for, session, send_file, flash import json import os @@ -11,7 +10,7 @@ from huggingface_hub import HfApi, hf_hub_download from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError from werkzeug.utils import secure_filename from dotenv import load_dotenv -import filelock # Добавлен импорт +import requests # Added for more specific network error handling load_dotenv() @@ -19,7 +18,6 @@ app = Flask(__name__) app.secret_key = 'your_unique_secret_key_soola_cosmetics_67890' DATA_FILE = 'data_soola.json' USERS_FILE = 'users_soola.json' -LOCK_FILE_SUFFIX = ".lock" SYNC_FILES = [DATA_FILE, USERS_FILE] @@ -32,233 +30,206 @@ STORE_ADDRESS = "Рынок Дордой, Джунхай, терминал, 38" CURRENCY_CODE = 'KGS' CURRENCY_NAME = 'Кыргызский сом (с)' +DOWNLOAD_RETRIES = 3 +DOWNLOAD_DELAY = 5 # seconds + logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') -# --- Helper for file locking --- -def get_lock(filename): - return filelock.FileLock(filename + LOCK_FILE_SUFFIX, timeout=10) # 10 секунд таймаут +def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY): + if not HF_TOKEN_READ and not HF_TOKEN_WRITE: # Allow read with write token too + logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.") + # Continue attempt without token for public repos -# --- Modified Download Function with Retries --- -def download_db_from_hf(specific_file=None, max_retries=3, retry_delay=5): - if not HF_TOKEN_READ: - logging.warning("Переменная окружения HF_TOKEN_READ не установлена. Попытка скачивания с Hugging Face без токена.") + token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE files_to_download = [specific_file] if specific_file else SYNC_FILES - logging.info(f"Начало скачивания файлов {files_to_download} с HF репозитория {REPO_ID}...") + logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...") all_successful = True for file_name in files_to_download: - download_successful = False - for attempt in range(max_retries): + success = False + for attempt in range(retries + 1): try: - logging.info(f"Попытка {attempt + 1}/{max_retries} скачивания файла {file_name}...") - lock = get_lock(file_name) - with lock: - local_path = hf_hub_download( - repo_id=REPO_ID, - filename=file_name, - repo_type="dataset", - token=HF_TOKEN_READ, - local_dir=".", - local_dir_use_symlinks=False, - force_download=True, - resume_download=False # Добавлено для большей надежности при перезаписи - ) - logging.info(f"Файл {file_name} успешно скачан из Hugging Face в {local_path}.") - download_successful = True - break # Выход из цикла ретраев при успехе + logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...") + local_path = hf_hub_download( + repo_id=REPO_ID, + filename=file_name, + repo_type="dataset", + token=token_to_use, + local_dir=".", + local_dir_use_symlinks=False, + force_download=True, + resume_download=False # Force fresh download each attempt + ) + logging.info(f"Successfully downloaded {file_name} to {local_path}.") + success = True + break # Exit retry loop on success except RepositoryNotFoundError: - logging.error(f"Репозиторий {REPO_ID} не найден на Hugging Face. Скачивание прервано.") - all_successful = False - return False # Нет смысла ретраить, если репо нет + logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.") + return False # No point retrying if repo doesn't exist except HfHubHTTPError as e: - if "404" in str(e) or "not found" in str(e).lower(): - logging.warning(f"Файл {file_name} не найден в репозитории {REPO_ID} (попытка {attempt + 1}/{max_retries}). Пропуск скачивания этого файла.") - # Не считаем это полным провалом, п��осто файла нет на HF - download_successful = True # Считаем "успешным" в плане отсутствия ошибки скачивания - break - else: - logging.error(f"Ошибка HTTP при скачивании {file_name} (попытка {attempt + 1}/{max_retries}): {e}") + if e.response.status_code == 404: + logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.") + success = False # Mark as failed for this specific file, but don't stop others + break # No point retrying a 404 + else: + logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") + except requests.exceptions.RequestException as e: # Catch network errors + logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") except Exception as e: - logging.error(f"Ошибка при скачивании файла {file_name} с Hugging Face (попытка {attempt + 1}/{max_retries}): {e}", exc_info=True) + logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True) - if attempt < max_retries - 1: - logging.info(f"Ожидание {retry_delay} секунд перед следующей попыткой...") - time.sleep(retry_delay) - else: - logging.error(f"Не удалось скачать файл {file_name} после {max_retries} попыток.") - all_successful = False + if attempt < retries: + time.sleep(delay) - if not download_successful: - all_successful = False # Помечаем общую неуспешность если хотя бы один файл не скачался + if not success: + logging.error(f"Failed to download {file_name} after {retries + 1} attempts.") + all_successful = False # Mark overall download as failed if any file fails - logging.info(f"Скачивание файлов с HF завершено. Общий результат: {'Успех' if all_successful else 'Неудача'}.") + logging.info(f"Download process finished. Overall success: {all_successful}") return all_successful - -# --- Modified Load Functions --- def load_data(): - file_path = DATA_FILE - logging.info(f"Попытка загрузки данных из {file_path}...") - download_success = download_db_from_hf(specific_file=file_path) - - if download_success: - logging.info(f"Скачивание {file_path} с HF успешно (или файл отсутствовал на HF). Попытка загрузки локальной версии.") - else: - logging.warning(f"Не удалось скачать {file_path} с HF после всех попыток. Попытка загрузить существующий локальный файл (если есть).") - + default_data = {'products': [], 'categories': []} try: - lock = get_lock(file_path) - with lock: - with open(file_path, 'r', encoding='utf-8') as file: - data = json.load(file) - logging.info(f"Данные успешно загружены из локального файла {file_path}") + with open(DATA_FILE, 'r', encoding='utf-8') as file: + data = json.load(file) + logging.info(f"Local data loaded successfully from {DATA_FILE}") if not isinstance(data, dict): - logging.warning(f"{file_path} не является словарем. Инициализация пустой структурой.") - return {'products': [], 'categories': []} + logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.") + raise FileNotFoundError # Treat as missing to trigger download if 'products' not in data: data['products'] = [] if 'categories' not in data: data['categories'] = [] return data except FileNotFoundError: - logging.critical(f"КРИТИЧЕСКАЯ ОШИБКА: Файл {file_path} не найден локально И не удалось его скачать с HF. Инициализация пустой структурой.") - # Не создаем пустой файл здесь! - return {'products': [], 'categories': []} + logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.") except json.JSONDecodeError: - logging.error(f"Ошибка декодирования JSON в локальном {file_path}. Файл может быть поврежден. Возврат пустой структуры.") - return {'products': [], 'categories': []} - except Exception as e: - logging.error(f"Неизвестная ошибка при загрузке данных ({file_path}): {e}", exc_info=True) - return {'products': [], 'categories': []} + logging.error(f"Error decoding JSON in local {DATA_FILE}. File might be corrupt. Attempting download.") + # Proceed to download only if local loading failed + if download_db_from_hf(specific_file=DATA_FILE): + try: + # Try loading the newly downloaded file + with open(DATA_FILE, 'r', encoding='utf-8') as file: + data = json.load(file) + logging.info(f"Data loaded successfully from {DATA_FILE} after download.") + if not isinstance(data, dict): + logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.") + return default_data + if 'products' not in data: data['products'] = [] + if 'categories' not in data: data['categories'] = [] + return data + except FileNotFoundError: + logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.") + return default_data + except json.JSONDecodeError: + logging.error(f"Error decoding JSON in downloaded {DATA_FILE}. Using default.") + return default_data + except Exception as e: + logging.error(f"Unknown error loading downloaded {DATA_FILE}: {e}. Using default.", exc_info=True) + return default_data + else: + logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.") + return default_data # Return empty structure in memory -def load_users(): - file_path = USERS_FILE - logging.info(f"Попытка загрузки данных пользователей из {file_path}...") - download_success = download_db_from_hf(specific_file=file_path) +def save_data(data): + try: + # Ensure the structure is valid before saving + if not isinstance(data, dict): + logging.error("Attempted to save invalid data structure (not a dict). Aborting save.") + return + if 'products' not in data: data['products'] = [] + if 'categories' not in data: data['categories'] = [] - if download_success: - logging.info(f"Скачивание {file_path} с HF успешно (или файл отсутствовал на HF). Попытка загрузки локальной версии.") - else: - logging.warning(f"Не удалось скачать {file_path} с HF после всех попыток. Попытка загрузить существующий локальный файл (если есть).") + with open(DATA_FILE, 'w', encoding='utf-8') as file: + json.dump(data, file, ensure_ascii=False, indent=4) + logging.info(f"Data successfully saved to {DATA_FILE}") + upload_db_to_hf(specific_file=DATA_FILE) + except Exception as e: + logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True) +def load_users(): + default_users = {} try: - lock = get_lock(file_path) - with lock: - with open(file_path, 'r', encoding='utf-8') as file: - users = json.load(file) - logging.info(f"Данные пользователей успешно загружены из локального файла {file_path}") - return users if isinstance(users, dict) else {} + with open(USERS_FILE, 'r', encoding='utf-8') as file: + users = json.load(file) + logging.info(f"Local users loaded successfully from {USERS_FILE}") + return users if isinstance(users, dict) else default_users except FileNotFoundError: - logging.critical(f"КРИТИЧЕСКАЯ ОШИБКА: Файл {file_path} не найден локально И не удалось его скачать с HF. Инициализация пустым словарем.") - # Не создаем пустой файл здесь! - return {} + logging.warning(f"Local file {USERS_FILE} not found. Attempting download from HF.") except json.JSONDecodeError: - logging.error(f"Ошибка декодирования JSON в локальном {file_path}. Файл может быть поврежден. Возврат пустого словаря.") - return {} + logging.error(f"Error decoding JSON in local {USERS_FILE}. File might be corrupt. Attempting download.") + + # Proceed to download only if local loading failed + if download_db_from_hf(specific_file=USERS_FILE): + try: + # Try loading the newly downloaded file + with open(USERS_FILE, 'r', encoding='utf-8') as file: + users = json.load(file) + logging.info(f"Users loaded successfully from {USERS_FILE} after download.") + return users if isinstance(users, dict) else default_users + except FileNotFoundError: + logging.error(f"File {USERS_FILE} still not found after download reported success. Using default.") + return default_users + except json.JSONDecodeError: + logging.error(f"Error decoding JSON in downloaded {USERS_FILE}. Using default.") + return default_users + except Exception as e: + logging.error(f"Unknown error loading downloaded {USERS_FILE}: {e}. Using default.", exc_info=True) + return default_users + else: + logging.error(f"Failed to download {USERS_FILE} from HF after retries. Using empty default user structure.") + return default_users # Return empty structure in memory + +def save_users(users): + try: + if not isinstance(users, dict): + logging.error("Attempted to save invalid users structure (not a dict). Aborting save.") + return + with open(USERS_FILE, 'w', encoding='utf-8') as file: + json.dump(users, file, ensure_ascii=False, indent=4) + logging.info(f"User data successfully saved to {USERS_FILE}") + upload_db_to_hf(specific_file=USERS_FILE) except Exception as e: - logging.error(f"Неизвестная ошибка при загрузке пользователей ({file_path}): {e}", exc_info=True) - return {} + logging.error(f"Error saving user data to {USERS_FILE}: {e}", exc_info=True) -# --- Modified Upload Function with Safety Check --- def upload_db_to_hf(specific_file=None): if not HF_TOKEN_WRITE: - logging.warning("Переменная окружения HF_TOKEN (для записи) не установлена. Загрузка на Hugging Face пропущена.") + logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.") return try: api = HfApi() files_to_upload = [specific_file] if specific_file else SYNC_FILES - logging.info(f"Начало загрузки файлов {files_to_upload} на HF репозиторий {REPO_ID}...") + logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...") for file_name in files_to_upload: if os.path.exists(file_name): - # --- Safety Check --- - try: - lock = get_lock(file_name) - with lock: # Блокируем чтение на время проверки - with open(file_name, 'r', encoding='utf-8') as f: - content_check = json.load(f) - - if file_name == DATA_FILE and content_check == {'products': [], 'categories': []}: - logging.warning(f"ПРЕДОТВРАЩЕНИЕ ЗАГРУЗКИ: Локальный файл {file_name} пуст (содержит только {'{products: [], categories: []}'}). Загрузка на HF пропущена.") - continue # Пропустить этот файл - if file_name == USERS_FILE and content_check == {}: - logging.warning(f"ПРЕДОТВРАЩЕНИЕ ЗАГРУЗКИ: Локальный файл {file_name} пуст (содержит только {'{}'}). Загрузка на HF пропущена.") - continue # Пропустить этот файл - - except json.JSONDecodeError: - logging.error(f"Ошибка чтения JSON в локальном файле {file_name} перед загрузкой. Загрузка на HF для этого файла пропущена.") - continue - except Exception as e: - logging.error(f"Ошибка при проверке файла {file_name} перед загрузкой: {e}. Загрузка на HF для этого файла пропущена.") - continue - # --- End Safety Check --- - try: - lock = get_lock(file_name) - with lock: # Блокируем на время чтения для загрузки - api.upload_file( - path_or_fileobj=file_name, - path_in_repo=file_name, - repo_id=REPO_ID, - repo_type="dataset", - token=HF_TOKEN_WRITE, - commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" - ) - logging.info(f"Файл {file_name} успешно загружен на Hugging Face.") + api.upload_file( + path_or_fileobj=file_name, + path_in_repo=file_name, + repo_id=REPO_ID, + repo_type="dataset", + token=HF_TOKEN_WRITE, + commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" + ) + logging.info(f"File {file_name} successfully uploaded to Hugging Face.") except Exception as e: - logging.error(f"Ошибка при загрузке файла {file_name} на Hugging Face: {e}") + logging.error(f"Error uploading file {file_name} to Hugging Face: {e}") else: - logging.warning(f"Файл {file_name} не найден локально, пропуск загрузки.") - logging.info("Загрузка файлов на HF завершена.") + logging.warning(f"File {file_name} not found locally, skipping upload.") + logging.info("Finished uploading files to HF.") except Exception as e: - logging.error(f"Общая ошибка при инициализации или загрузке на Hugging Face: {e}", exc_info=True) + logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True) - -# --- Modified Save Functions --- -def save_data(data): - try: - lock = get_lock(DATA_FILE) - with lock: - with open(DATA_FILE, 'w', encoding='utf-8') as file: - json.dump(data, file, ensure_ascii=False, indent=4) - logging.info(f"Данные успешно сохранены в {DATA_FILE}") - # Загрузка на HF вызывается после сохранения, но с проверкой внутри upload_db_to_hf - upload_db_to_hf(specific_file=DATA_FILE) - except filelock.Timeout: - logging.error(f"Не удалось получить блокировку для сохранения файла {DATA_FILE}. Сохранение и загрузка на HF пропущены.") - flash("Внимание: Не удалось сохранить изменения из-за блокировки файла. Попробуйте позже.", "error") - except Exception as e: - logging.error(f"Ошибка при сохранении данных в {DATA_FILE}: {e}", exc_info=True) - -def save_users(users): - try: - lock = get_lock(USERS_FILE) - with lock: - with open(USERS_FILE, 'w', encoding='utf-8') as file: - json.dump(users, file, ensure_ascii=False, indent=4) - logging.info(f"Данные пользователей успешно сохранены в {USERS_FILE}") - # Загрузка на HF вызывается после сохранения, но с проверкой внутри upload_db_to_hf - upload_db_to_hf(specific_file=USERS_FILE) - except filelock.Timeout: - logging.error(f"Не удалось получить блокировку для сохранения файла {USERS_FILE}. Сохранение и загрузка на HF пропущены.") - flash("Внимание: Не удалось сохранить изменения пользователя из-за блокировки файла. Попробуйте позже.", "error") - except Exception as e: - logging.error(f"Ошибка при сохранении данных пользователей в {USERS_FILE}: {e}", exc_info=True) - - -# --- Periodic Backup --- def periodic_backup(): backup_interval = 1800 - logging.info(f"Настройка периодического резервного копирования каждые {backup_interval} секунд.") + logging.info(f"Setting up periodic backup every {backup_interval} seconds.") while True: time.sleep(backup_interval) - logging.info("Запуск периодического резервного копирования...") - # upload_db_to_hf уже содержит проверку на пустые файлы + logging.info("Starting periodic backup...") upload_db_to_hf() - logging.info("Периодическое резервное копирование завершено.") - - -# --- Flask Routes (Без изменений в HTML/JS, только вызовы функций) --- + logging.info("Periodic backup finished.") @app.route('/') def catalog(): @@ -300,7 +271,6 @@ def catalog(): body.dark-mode .theme-toggle:hover { color: #55a683; } .store-address { padding: 15px; text-align: center; background-color: #ffffff; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); font-size: 1rem; color: #44524c; } body.dark-mode .store-address { background-color: #253f37; color: #b0c8c1; } - .filters-container { margin: 20px 0; display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; } .search-container { margin: 20px 0; text-align: center; } #search-input { width: 90%; max-width: 600px; padding: 12px 18px; font-size: 1rem; border: 1px solid #d1e7dd; border-radius: 25px; outline: none; box-shadow: 0 2px 5px rgba(0,0,0,0.05); transition: all 0.3s ease; } @@ -311,7 +281,6 @@ def catalog(): body.dark-mode .category-filter { background-color: #253f37; border-color: #2c4a41; color: #97b7ae; } .category-filter.active, .category-filter:hover { background-color: #1C6758; color: white; border-color: #1C6758; box-shadow: 0 2px 10px rgba(28, 103, 88, 0.3); } body.dark-mode .category-filter.active, body.dark-mode .category-filter:hover { background-color: #3D8361; border-color: #3D8361; color: #1a2b26; box-shadow: 0 2px 10px rgba(61, 131, 97, 0.4); } - .products-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; padding: 10px; } .product { background: #fff; border-radius: 15px; padding: 0; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; height: 100%; border: 1px solid #e1f0e9;} body.dark-mode .product { background: #253f37; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); border-color: #2c4a41; } @@ -331,13 +300,11 @@ def catalog(): .product-button { display: block; width: 100%; padding: 10px; border: none; border-radius: 8px; background-color: #1C6758; color: white; font-size: 0.9rem; font-weight: 500; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); text-align: center; text-decoration: none; } .product-button:hover { background-color: #164B41; box-shadow: 0 4px 15px rgba(22, 75, 65, 0.4); transform: translateY(-2px); } .product-button i { margin-right: 5px; } - .add-to-cart { background-color: #38a169; } .add-to-cart:hover { background-color: #2f855a; box-shadow: 0 4px 15px rgba(47, 133, 90, 0.4); } #cart-button { position: fixed; bottom: 25px; right: 25px; background-color: #1C6758; color: white; border: none; border-radius: 50%; width: 55px; height: 55px; font-size: 1.5rem; cursor: pointer; display: none; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(28, 103, 88, 0.4); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1000; } - #cart-button .fa-shopping-cart { margin-right: 0; } - #cart-button span { position: absolute; top: -5px; right: -5px; background-color: #38a169; color: white; border-radius: 50%; padding: 2px 6px; font-size: 0.7rem; font-weight: bold; } - + #cart-button .fa-shopping-cart { margin-right: 0; } + #cart-button span { position: absolute; top: -5px; right: -5px; background-color: #38a169; color: white; border-radius: 50%; padding: 2px 6px; font-size: 0.7rem; font-weight: bold; } .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); backdrop-filter: blur(5px); overflow-y: auto; } .modal-content { background: #f8fcfb; margin: 5% auto; padding: 25px; border-radius: 15px; width: 90%; max-width: 700px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); animation: slideIn 0.3s ease-out; position: relative; } body.dark-mode .modal-content { background: #253f37; color: #c8d8d3; } @@ -347,41 +314,35 @@ def catalog(): body.dark-mode .close { color: #7a8d85; } body.dark-mode .close:hover { color: #b0c8c1; } .modal-content h2 { margin-top: 0; margin-bottom: 20px; color: #1C6758; display: flex; align-items: center; gap: 10px;} - body.dark-mode .modal-content h2 { color: #55a683; } + body.dark-mode .modal-content h2 { color: #55a683; } .cart-item { display: grid; grid-template-columns: auto 1fr auto auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #d1e7dd; } body.dark-mode .cart-item { border-bottom-color: #2c4a41; } - .cart-item:last-child { border-bottom: none; } + .cart-item:last-child { border-bottom: none; } .cart-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #fff; padding: 5px; grid-column: 1; } - .cart-item-details { grid-column: 2; } - .cart-item-details strong { display: block; margin-bottom: 5px; } - .cart-item-price { font-size: 0.9rem; color: #44524c; } - body.dark-mode .cart-item-price { color: #8aa39a; } - .cart-item-total { font-weight: bold; text-align: right; grid-column: 3; } - .cart-item-remove { grid-column: 4; background:none; border:none; color:#f56565; cursor:pointer; font-size: 1.3em; padding: 5px; line-height: 1; } - .cart-item-remove:hover { color: #c53030; } + .cart-item-details { grid-column: 2; } + .cart-item-details strong { display: block; margin-bottom: 5px; } + .cart-item-price { font-size: 0.9rem; color: #44524c; } + body.dark-mode .cart-item-price { color: #8aa39a; } + .cart-item-total { font-weight: bold; text-align: right; grid-column: 3; } + .cart-item-remove { grid-column: 4; background:none; border:none; color:#f56565; cursor:pointer; font-size: 1.3em; padding: 5px; line-height: 1; } + .cart-item-remove:hover { color: #c53030; } .quantity-input, .color-select { width: 100%; max-width: 180px; padding: 10px; border: 1px solid #d1e7dd; border-radius: 8px; font-size: 1rem; margin: 10px 0; box-sizing: border-box; } - body.dark-mode .quantity-input, body.dark-mode .color-select { background-color: #1a2b26; border-color: #2c4a41; color: #c8d8d3; } + body.dark-mode .quantity-input, body.dark-mode .color-select { background-color: #1a2b26; border-color: #2c4a41; color: #c8d8d3; } .cart-summary { margin-top: 20px; text-align: right; border-top: 1px solid #d1e7dd; padding-top: 15px; } body.dark-mode .cart-summary { border-top-color: #2c4a41; } .cart-summary strong { font-size: 1.2rem; } .cart-actions { margin-top: 25px; display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; } - .cart-actions .product-button { width: auto; flex-grow: 1; } + .cart-actions .product-button { width: auto; flex-grow: 1; } .clear-cart { background-color: #7a8d85; } .clear-cart:hover { background-color: #5e6e68; box-shadow: 0 4px 15px rgba(94, 110, 104, 0.4); } .order-button { background-color: #38a169; } .order-button:hover { background-color: #2f855a; box-shadow: 0 4px 15px rgba(47, 133, 90, 0.4); } - .notification { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background-color: #38a169; color: white; padding: 10px 20px; border-radius: 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); z-index: 1002; opacity: 0; transition: opacity 0.5s ease; font-size: 0.9rem;} .notification.show { opacity: 1;} .no-results-message { grid-column: 1 / -1; text-align: center; padding: 40px; font-size: 1.1rem; color: #5e6e68; } body.dark-mode .no-results-message { color: #8aa39a; } .top-product-indicator { position: absolute; top: 8px; right: 8px; background-color: rgba(255, 215, 0, 0.8); color: #333; padding: 2px 6px; font-size: 0.7rem; border-radius: 4px; font-weight: bold; z-index: 10; backdrop-filter: blur(2px); } .product { position: relative; } - .flash-messages { list-style: none; padding: 0; margin: 0 0 20px 0; } - .flash-messages li { padding: 10px 15px; margin-bottom: 10px; border-radius: 6px; font-size: 0.9rem;} - .flash-messages .success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;} - .flash-messages .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;} - .flash-messages .warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
@@ -401,16 +362,6 @@ def catalog(): - {% with messages = get_flashed_messages(with_categories=true) %} - {% if messages %} - - {% endif %} - {% endwith %} -Описание:
{{ product.get('description', 'Описание отсутствует.')|replace('\\n', '
')|safe }}
Доступные цвета/варианты: {{ valid_colors|join(', ') }}
+ {% if colors and colors|select('ne', '')|list|length > 0 %} +Доступные цвета/варианты: {{ colors|select('ne', '')|join(', ') }}
{% endif %}Вход выполнен успешно. Перенаправление в каталог...
@@ -1082,24 +1025,23 @@ def login(): ''' return login_response_html else: - logging.warning(f"Неудачная попытка входа для пользователя {login}.") + logging.warning(f"Failed login attempt for user {login}.") error_message = "Неверный логин или пароль." return render_template_string(LOGIN_TEMPLATE, error=error_message), 401 return render_template_string(LOGIN_TEMPLATE, error=None) - @app.route('/auto_login', methods=['POST']) def auto_login(): data = request.get_json() if not data or 'login' not in data: - logging.warning("Запрос auto_login без данных или логина.") - return "Неверный запрос", 400 + logging.warning("Auto_login request missing data or login.") + return "Invalid request", 400 login = data.get('login') if not login: - logging.warning("Попытка auto_login с пустым логином.") - return "Логин не предоставлен", 400 + logging.warning("Attempted auto_login with empty login.") + return "Login not provided", 400 users = load_users() if login in users: @@ -1113,12 +1055,11 @@ def auto_login(): 'city': user_info.get('city', ''), 'phone': user_info.get('phone', '') } - logging.info(f"Автоматический вход для пользователя {login} выполнен.") + logging.info(f"Auto-login successful for user {login}.") return "OK", 200 else: - logging.warning(f"Неудачная попытка автоматического входа для несуществующего пользователя {login}.") - # Не удаляем localStorage здесь, чтобы не мешать нормальному входу - return "Ошибка авто-входа", 400 + logging.warning(f"Failed auto-login attempt for non-existent user {login}.") + return "Auto-login failed", 400 @app.route('/logout') def logout(): @@ -1126,11 +1067,11 @@ def logout(): session.pop('user', None) session.pop('user_info', None) if logged_out_user: - logging.info(f"Пользователь {logged_out_user} вышел из системы.") + logging.info(f"User {logged_out_user} logged out.") logout_response_html = '''Выход выполнен. Перенаправление на главную страницу...
@@ -1182,32 +1123,32 @@ ADMIN_TEMPLATE = ''' .item-actions button:not(.delete-button) { background-color: #1C6758; } .item-actions button:not(.delete-button):hover { background-color: #164B41; } .edit-form-container { margin-top: 15px; padding: 20px; background: #f0f9f4; border: 1px dashed #c4d9d1; border-radius: 6px; display: none; } - details { background-color: #f8fcfb; border: 1px solid #d1e7dd; border-radius: 8px; margin-bottom: 20px; } - details > summary { cursor: pointer; font-weight: 600; color: #164B41; display: block; padding: 15px; border-bottom: 1px solid #d1e7dd; list-style: none; position: relative; } - details > summary::after { content: '\\f078'; font-family: 'Font Awesome 6 Free'; font-weight: 900; position: absolute; right: 20px; top: 50%; transform: translateY(-50%); transition: transform 0.2s ease; color: #1C6758; } - details[open] > summary::after { transform: translateY(-50%) rotate(180deg); } - details[open] > summary { border-bottom: 1px solid #d1e7dd; } - details .form-content { padding: 20px; } - .color-input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; } - .color-input-group input { flex-grow: 1; margin: 0; } - .remove-color-btn { background-color: #f56565; padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; } - .remove-color-btn:hover { background-color: #e53e3e; } - .add-color-btn { background-color: #63b3ed; } - .add-color-btn:hover { background-color: #4299e1; } - .photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #d1e7dd; object-fit: cover;} - .sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; } - .download-hf-button { background-color: #7a8d85; } - .download-hf-button:hover { background-color: #5e6e68; } - .flex-container { display: flex; flex-wrap: wrap; gap: 20px; } - .flex-item { flex: 1; min-width: 350px; } - .message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; font-size: 0.9rem;} - .message.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;} - .message.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;} - .message.warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; } - .status-indicator { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; font-weight: 500; margin-left: 10px; vertical-align: middle; } - .status-indicator.in-stock { background-color: #c6f6d5; color: #2f855a; } - .status-indicator.out-of-stock { background-color: #fed7d7; color: #c53030; } - .status-indicator.top-product { background-color: #feebc8; color: #9c4221; margin-left: 5px;} + details { background-color: #f8fcfb; border: 1px solid #d1e7dd; border-radius: 8px; margin-bottom: 20px; } + details > summary { cursor: pointer; font-weight: 600; color: #164B41; display: block; padding: 15px; border-bottom: 1px solid #d1e7dd; list-style: none; position: relative; } + details > summary::after { content: '\\f078'; font-family: 'Font Awesome 6 Free'; font-weight: 900; position: absolute; right: 20px; top: 50%; transform: translateY(-50%); transition: transform 0.2s ease; color: #1C6758; } + details[open] > summary::after { transform: translateY(-50%) rotate(180deg); } + details[open] > summary { border-bottom: 1px solid #d1e7dd; } + details .form-content { padding: 20px; } + .color-input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; } + .color-input-group input { flex-grow: 1; margin: 0; } + .remove-color-btn { background-color: #f56565; padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; } + .remove-color-btn:hover { background-color: #e53e3e; } + .add-color-btn { background-color: #63b3ed; } + .add-color-btn:hover { background-color: #4299e1; } + .photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #d1e7dd; object-fit: cover;} + .sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; } + .download-hf-button { background-color: #7a8d85; } + .download-hf-button:hover { background-color: #5e6e68; } + .flex-container { display: flex; flex-wrap: wrap; gap: 20px; } + .flex-item { flex: 1; min-width: 350px; } + .message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; font-size: 0.9rem;} + .message.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;} + .message.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;} + .message.warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; } + .status-indicator { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; font-weight: 500; margin-left: 10px; vertical-align: middle; } + .status-indicator.in-stock { background-color: #c6f6d5; color: #2f855a; } + .status-indicator.out-of-stock { background-color: #fed7d7; color: #c53030; } + .status-indicator.top-product { background-color: #feebc8; color: #9c4221; margin-left: 5px;} @@ -1228,14 +1169,14 @@ ADMIN_TEMPLATE = '''Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных (с проверкой на пустые файлы). Используйте эти кнопки для немедленной синхронизации.
+Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.
Цена: {{ "%.2f"|format(product['price']) }} {{ currency_code }}
Описание: {{ product.get('description', 'N/A')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}
{% set colors = product.get('colors', []) %} - {% set valid_colors = colors|select('ne', '')|list %} -Цвета/Вар-ты: {{ valid_colors|join(', ') if valid_colors|length > 0 else 'Нет' }}
+Цвета/Вар-ты: {{ colors|select('ne', '')|join(', ') if colors|select('ne', '')|list|length > 0 else 'Нет' }}
{% if product.get('photos') and product['photos']|length > 1 %}(Всего фото: {{ product['photos']|length }})
{% endif %} @@ -1447,7 +1383,7 @@ ADMIN_TEMPLATE = ''' - {% if product.get('photos') and product.photos|length > 0 %} + {% if product.get('photos') %}Текущие фото: