Spaces:
Running
Running
| from flask import Flask, render_template_string, request, redirect, url_for, flash, jsonify | |
| import json | |
| import os | |
| import logging | |
| import threading | |
| import time | |
| from datetime import datetime | |
| from huggingface_hub import HfApi, hf_hub_download | |
| from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError | |
| from werkzeug.utils import secure_filename | |
| from dotenv import load_dotenv | |
| import requests | |
| import uuid | |
| import copy | |
| from math import ceil | |
| load_dotenv() | |
| app = Flask(__name__) | |
| app.secret_key = os.getenv("FLASK_SECRET_KEY", 'your_unique_secret_key_emir_shop_12345_no_login') | |
| DATA_FILE = 'data.json' | |
| SYNC_FILES = [DATA_FILE] | |
| REPO_ID = "Aleksmorshen/emirkuh" | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN") | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") | |
| CURRENCY_CODE = 'KGS' | |
| ADMIN_PRODUCTS_PER_PAGE = 25 | |
| DOWNLOAD_RETRIES = 3 | |
| DOWNLOAD_DELAY = 5 | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| APP_DATA = {} | |
| data_lock = threading.Lock() | |
| translations = { | |
| 'ru': { | |
| 'site_name': 'emir', | |
| 'catalog_title': 'emir - Каталог', | |
| 'admin_title': 'Админ-панель - emir', | |
| 'order_title': 'Заказ №{order_id} - emir', | |
| 'all_categories': 'Все категории', | |
| 'all_suppliers': 'Все поставщики', | |
| 'search_placeholder': 'Поиск по названию или описанию...', | |
| 'no_products_yet': 'Товары пока не добавлены.', | |
| 'details': 'Подробнее', | |
| 'add_to_cart': 'В корзину', | |
| 'loading': 'Загрузка...', | |
| 'specify_quantity_color': 'Укажите количество и цвет', | |
| 'quantity': 'Количество:', | |
| 'color_variant': 'Цвет/Вариант:', | |
| 'confirm_add_to_cart': 'Добавить в корзину', | |
| 'your_cart': 'Ваша корзина', | |
| 'cart_empty': 'Ваша корзина пуста.', | |
| 'total': 'Итого:', | |
| 'clear_cart': 'Очистить корзину', | |
| 'formulate_order': 'Сформировать заказ', | |
| 'open_cart_aria': 'Открыть корзину', | |
| 'error_product_not_found': 'Ошибка: товар не найден.', | |
| 'error_invalid_quantity': 'Пожалуйста, укажите корректное количество (больше 0).', | |
| 'error_adding_product_not_found': 'Ошибка добавления: товар не найден.', | |
| 'product_added_to_cart': '{product_name} добавлен в корзину!', | |
| 'cart_item_color_prefix': ' (Цвет: ', | |
| 'cart_item_color_suffix': ')', | |
| 'remove_item_title': 'Удалить товар', | |
| 'confirm_clear_cart': 'Вы уверены, что хотите очистить корзину?', | |
| 'cart_empty_for_order': 'Корзина пуста! Добавьте товары перед формированием заказа.', | |
| 'formulating_order': 'Формируем заказ...', | |
| 'failed_to_create_order': 'Не удалось создать заказ', | |
| 'order_id_not_received': 'Не получен ID заказа от сервера.', | |
| 'error_generic': 'Ошибка: {error_message}', | |
| 'no_products_found_for_query': 'По вашему запросу товары не найдены.', | |
| 'product_detail_photo_alt': '{product_name} - фото {loop_index}', | |
| 'no_image_alt': 'Изображение отсутствует', | |
| 'category': 'Категория:', | |
| 'subcategory': 'Подкатегория:', | |
| 'supplier': 'Поставщик:', | |
| 'no_category': 'Без категории', | |
| 'no_subcategory': 'Без подкатегории', | |
| 'no_supplier': 'Без поставщика', | |
| 'price': 'Цена:', | |
| 'description': 'Описание:', | |
| 'description_absent': 'Описание отсутствует.', | |
| 'available_colors_variants': 'Доступные цвета/варианты:', | |
| 'order_page_title': 'Ваш Заказ №{order_id}', | |
| 'creation_date': 'Дата создания:', | |
| 'products_in_order': 'Товары в заказе', | |
| 'total_products_sum': 'Общая сумма товаров:', | |
| 'total_to_pay': 'ИТОГО К ОПЛАТЕ:', | |
| 'order_status': 'Статус заказа', | |
| 'anonymous_order_notice': 'Этот заказ был оформлен без входа в систему.', | |
| 'contact_whatsapp_notice': 'Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.', | |
| 'send_order_button': 'Отправить в WhatsApp', | |
| 'back_to_catalog': '← Вернуться в каталог', | |
| 'error_page_title': 'Ошибка', | |
| 'order_not_found_by_id': 'Заказ с таким ID не найден.', | |
| 'whatsapp_greeting': 'Здравствуйте! Хочу подтвердить свой заказ на emir:', | |
| 'whatsapp_product_inquiry': 'Здравствуйте! Хочу уточнить цену на товар: {product_name}', | |
| 'whatsapp_order_number': 'Номер заказа:', | |
| 'whatsapp_order_link': 'Ссылка на заказ:', | |
| 'whatsapp_contact_request': 'Пожалуйста, свяжитесь со мной для уточнения деталей оплаты и доставки.', | |
| 'whatsapp_request_price_calculation': 'Пожалуйста, рассчитайте стоимость заказа.', | |
| 'admin_panel_h1': 'Админ-панель emir', | |
| 'go_to_catalog': 'Перейти в каталог', | |
| 'sync_with_dc': 'Синхронизация с Датацентром', | |
| 'upload_db': 'Загрузить БД', | |
| 'download_db': 'Скачать БД', | |
| 'confirm_force_upload': 'Вы уверены, что хотите принудительно загрузить локальные данные на сервер? Это перезапишет данные на сервере.', | |
| 'confirm_force_download': 'Вы уверены, что хотите принудительно скачать данные с сервера? Это перезапишет ваши локальные файлы.', | |
| 'sync_info_text': 'Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.', | |
| 'manage_categories': 'Управление категориями', | |
| 'add_new_category': 'Добавить новую категорию', | |
| 'new_category_name_label': 'Название новой категории:', | |
| 'add_button': 'Добавить', | |
| 'existing_categories': 'Существующие категории:', | |
| 'confirm_delete_category': "Вы уверены, что хотите удалить категорию '{category_name}'? Все ее подкатегории и связанные товары будут помечены как 'Без категории'.", | |
| 'no_categories_yet': 'Категорий пока нет.', | |
| 'manage_subcategories': 'Управление подкатегориями', | |
| 'add_new_subcategory': 'Добавить новую подкатегорию', | |
| 'new_subcategory_name_label': 'Название новой подкатегории:', | |
| 'parent_category_label': 'Родительская категория:', | |
| 'select_parent_category': 'Выберите родительскую категорию', | |
| 'existing_subcategories': 'Существующие подкатегории:', | |
| 'confirm_delete_subcategory': "Вы уверены, что хотите удалить подкатегорию '{subcategory_name}'? Товары этой подкатегории будут помечены как 'Без подкатегории'.", | |
| 'no_subcategories_yet': 'Подкатегорий пока нет.', | |
| 'manage_suppliers': 'Управление поставщиками', | |
| 'add_new_supplier': 'Добавить нового поставщика', | |
| 'new_supplier_name_label': 'Название нового поставщика:', | |
| 'existing_suppliers': 'Существующие поставщики:', | |
| 'confirm_delete_supplier': "Вы уверены, что хотите удалить поставщика '{supplier_name}'? Товары этого поставщика будут помечены как 'Без поставщика'.", | |
| 'no_suppliers_yet': 'Поставщиков пока нет.', | |
| 'information_section_title': 'Информация', | |
| 'user_management_disabled_info': 'Управление пользователями отключено, так как сайт не требует входа.', | |
| 'anonymous_orders_whatsapp_info': 'Заказы создаются анонимно и должны быть подтверждены через WhatsApp.', | |
| 'manage_products': 'Управление товарами', | |
| 'add_new_product': 'Добавить новый товар', | |
| 'product_name_label': 'Название товара *:', | |
| 'product_price_kgs_label': 'Цена (KGS):', | |
| 'product_discount_percent_label': 'Скидка (%):', | |
| 'product_description_label': 'Описание:', | |
| 'product_category_label': 'Категория:', | |
| 'product_subcategory_label': 'Подкатегория:', | |
| 'product_supplier_label': 'Поставщик:', | |
| 'no_category_option': 'Без категории', | |
| 'no_subcategory_option': 'Без подкатегории', | |
| 'no_supplier_option': 'Без поставщика', | |
| 'select_category_first': 'Сначала выберите категорию', | |
| 'photos_label': 'Фотографии (до 10 шт.):', | |
| 'video_label': 'Видео (1 файл, .mp4, .webm):', | |
| 'colors_variants_label': 'Цвета/Варианты (оставьте пустым, если нет):', | |
| 'color_placeholder_example': 'Например: Синий', | |
| 'add_color_field_button': 'Добавить поле для цвета/варианта', | |
| 'in_stock_label': 'В наличии', | |
| 'top_product_label': 'Топ товар (показывать наверху)', | |
| 'on_order_label': 'На заказ', | |
| 'add_product_button': 'Добавить товар', | |
| 'product_list_title': 'Список товаров:', | |
| 'view_first_photo_title': 'Посмотреть первое фото', | |
| 'photo_alt': 'Фото', | |
| 'no_photo_alt': 'Нет фото', | |
| 'status_in_stock': 'В наличии', | |
| 'status_out_of_stock': 'Нет в наличии', | |
| 'status_on_order': 'На заказ', | |
| 'status_top_product': 'Топ', | |
| 'description_label_item': 'Описание:', | |
| 'description_not_available': 'Отсутствует', | |
| 'colors_variants_item_label': 'Цвета/Вар-ты:', | |
| 'colors_not_available': 'Нет', | |
| 'discount_label_item': 'Скидка:', | |
| 'discount_badge_text': 'Скидка {discount}%', | |
| 'total_photos_count': '(Всего фото: {count})', | |
| 'view_video_button': 'Посмотреть видео', | |
| 'edit_button': 'Редактировать', | |
| 'confirm_delete_product': "Вы уверены, что хотите удалить товар '{product_name}'?", | |
| 'delete_button': 'Удалить', | |
| 'editing_product_title': 'Редактирование: {product_name}', | |
| 'product_name_edit_label': 'Название *:', | |
| 'product_price_kgs_edit_label': 'Цена (KGS):', | |
| 'product_discount_percent_edit_label': 'Скидка (%):', | |
| 'product_description_edit_label': 'Описание:', | |
| 'product_category_edit_label': 'Категория:', | |
| 'product_subcategory_edit_label': 'Подкатегория:', | |
| 'product_supplier_edit_label': 'Поставщик:', | |
| 'replace_photos_label': 'Заменить фотографии (выберите новые файлы, до 10 шт.):', | |
| 'replace_video_label': 'Заменить видео (выберите новый файл):', | |
| 'current_photos_label': 'Текущие фото:', | |
| 'current_video_label': 'Текущее видео:', | |
| 'photo_alt_indexed': 'Фото {loop_index}', | |
| 'colors_variants_edit_label': 'Цвета/Варианты:', | |
| 'color_placeholder_generic': 'Например: Цвет', | |
| 'add_color_field_edit_button': 'Добавить поле для цвета', | |
| 'in_stock_edit_label': 'В наличии', | |
| 'top_product_edit_label': 'Топ товар', | |
| 'on_order_edit_label': 'На заказ', | |
| 'save_changes_button': 'Сохранить изменения', | |
| 'no_products_yet_admin': 'Товаров пока нет.', | |
| 'js_new_color_variant_placeholder': 'Новый цвет/вариант', | |
| 'flash_category_added_success': "Категория '{category_name}' успешно добавлена.", | |
| 'flash_category_name_empty': 'Название категории не может быть пустым.', | |
| 'flash_category_already_exists': "Категория '{category_name}' уже существует.", | |
| 'flash_category_delete_success': "Категория '{category_name}' удалена.", | |
| 'flash_category_delete_failed': "Не удалось удалить категорию '{category_name}'.", | |
| 'flash_subcategory_added_success': "Подкатегория '{subcategory_name}' успешно добавлена.", | |
| 'flash_subcategory_name_empty': 'Название подкатегодии не может быть пустым.', | |
| 'flash_parent_category_not_selected': 'Необходимо выбрать родительскую категорию.', | |
| 'flash_subcategory_already_exists': "Подкатегория '{subcategory_name}' уже существует в этой категории.", | |
| 'flash_subcategory_delete_success': "Подкатегория '{subcategory_name}' удалена.", | |
| 'flash_subcategory_delete_failed': "Не удалось удалить подкатегодию.", | |
| 'flash_supplier_added_success': "Поставщик '{supplier_name}' успешно добавлен.", | |
| 'flash_supplier_name_empty': 'Имя поставщика не может быть пустым.', | |
| 'flash_supplier_already_exists': "Поставщик '{supplier_name}' уже существует.", | |
| 'flash_supplier_delete_success': "Поставщик '{supplier_name}' удален.", | |
| 'flash_supplier_delete_failed': "Не удалось удалить поставщика '{supplier_name}'.", | |
| 'flash_product_name_price_required': 'Название товара обязательно.', | |
| 'flash_invalid_price_format': 'Неверный формат цены.', | |
| 'flash_invalid_discount_format': 'Неверный формат скидки (0-100).', | |
| 'flash_photo_limit_reached': 'Загружено только первые {photo_limit} фото.', | |
| 'flash_file_not_image_skipped': 'Файл {filename} не является изображением и был пропущен.', | |
| 'flash_file_not_video_skipped': 'Файл {filename} не является видео и был пропущен.', | |
| 'flash_photo_upload_error': 'Ошибка при загрузке фото {filename}.', | |
| 'flash_video_upload_error': 'Ошибка при загрузке видео {filename}.', | |
| 'flash_hf_token_write_not_set_files_not_uploaded': 'HF_TOKEN (write) не настроен. Файлы не были загружены.', | |
| 'flash_product_added_success': "Товар '{product_name}' успешно добавлен.", | |
| 'flash_edit_error_no_id': 'Ошибка редактирования: ID товара не передан.', | |
| 'flash_edit_error_not_found': "Ошибка редактирования: товар с ID '{product_id}' не найден.", | |
| 'flash_invalid_price_format_edit_warning': "Неверный формат цены для товара '{product_name}'. Цена не изменена.", | |
| 'flash_invalid_discount_format_edit_warning': "Неверный формат скидки для товара '{product_name}'. Скидка не изменена.", | |
| 'flash_photos_updated_success': 'Фотографии товара успешно обновлены.', | |
| 'flash_video_updated_success': 'Видео товара успешно обновлено.', | |
| 'flash_failed_to_upload_new_files_format_error': 'Не удалось загрузить новые файлы (возможно, неверный формат).', | |
| 'flash_hf_token_write_not_set_files_not_updated': 'HF_TOKEN (write) не настроен. Файлы не были обновлены.', | |
| 'flash_product_updated_success': "Товар '{product_name}' успешно обновлен.", | |
| 'flash_delete_error_no_id': 'Ошибка удаления: ID товара не передан.', | |
| 'flash_failed_delete_hf_files_warning': "Не удалось удалить файлы для товара '{product_name}' с сервера. Товар удален локально.", | |
| 'flash_hf_token_write_not_set_files_not_deleted_warning': "Товар '{product_name}' удален локально, но файлы не удалены с сервера (токен не задан).", | |
| 'flash_product_deleted_success': "Товар '{product_name}' удален.", | |
| 'flash_delete_error_not_found': "Ошибка удаления: товар с таким ID не найден.", | |
| 'flash_unknown_action': 'Неизвестное действие: {action}', | |
| 'flash_internal_error': "Произошла внутренняя ошибка при выполнении действия '{action}'. Подробности в логе сервера.", | |
| 'flash_data_uploaded_hf_success': 'Данные успешно загружены на Hugging Face.', | |
| 'flash_data_upload_hf_error': 'Ошибка при загрузке на Hugging Face: {error}', | |
| 'flash_data_downloaded_hf_success': 'Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.', | |
| 'flash_data_download_hf_error_retries': 'Не удалось скачать данные с Hugging Face после нескольких попыток. Проверьте логи.', | |
| 'flash_data_download_hf_error': 'Ошибка при скачивании с Hugging Face: {error}', | |
| 'currency_name': 'Кыргызский сом', | |
| 'close_button_aria': 'Закрыть', | |
| 'admin_settings_title': 'Настройки магазина', | |
| 'admin_prices_visibility_label': 'Видимость цен на сайте:', | |
| 'admin_prices_enabled_checkbox_label': 'Цены включены', | |
| 'save_settings_button': 'Сохранить настройки', | |
| 'flash_settings_updated': 'Настройки успешно обновлены.', | |
| 'prices_disabled_notice_catalog': 'Цены временно не отображаются. Добавьте товары в корзину для запроса стоимости.', | |
| 'prices_disabled_notice_cart': 'Цены не отображаются. Стоимость будет рассчитана после оформления заказа.', | |
| 'request_price_calculation_button': 'Уточнить цену в WhatsApp', | |
| 'price_on_request': 'Цена по запросу', | |
| 'video_modal_title': 'Видео о товаре', | |
| 'save_all_changes_button': 'Сохранить все изменения ({count})', | |
| 'admin_search_placeholder': 'Поиск товаров по названию или описанию...', | |
| 'admin_search_button': 'Найти', | |
| 'admin_reset_search_button': 'Сбросить', | |
| 'admin_no_products_found_for_query': 'По вашему запросу товары не найдены.', | |
| } | |
| } | |
| def get_translation(key, **kwargs): | |
| translation_template = translations['ru'].get(key, f"MISSING_TRANSLATION: {key}") | |
| return translation_template.format(**kwargs) if kwargs else translation_template | |
| def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY): | |
| if not HF_TOKEN_READ and not HF_TOKEN_WRITE: | |
| logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.") | |
| token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE | |
| files_to_download = [specific_file] if specific_file else SYNC_FILES | |
| logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...") | |
| all_successful = True | |
| for file_name in files_to_download: | |
| success = False | |
| for attempt in range(retries + 1): | |
| try: | |
| logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...") | |
| local_path = hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=file_name, | |
| repo_type="dataset", | |
| token=token_to_use, | |
| local_dir=".", | |
| local_dir_use_symlinks=False, | |
| force_download=True, | |
| resume_download=False | |
| ) | |
| logging.info(f"Successfully downloaded {file_name} to {local_path}.") | |
| success = True | |
| break | |
| except RepositoryNotFoundError: | |
| logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.") | |
| return False | |
| except HfHubHTTPError as e: | |
| if e.response.status_code == 404: | |
| logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.") | |
| if attempt == 0 and not os.path.exists(file_name): | |
| try: | |
| if file_name == DATA_FILE: | |
| with open(file_name, 'w', encoding='utf-8') as f: | |
| json.dump({'products': [], 'categories': [], 'subcategories': [], 'suppliers': [], 'orders': {}, 'config': {'prices_enabled': True}}, f) | |
| logging.info(f"Created empty local file {file_name} because it was not found on HF.") | |
| except Exception as create_e: | |
| logging.error(f"Failed to create empty local file {file_name}: {create_e}") | |
| success = False | |
| break | |
| else: | |
| logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") | |
| except requests.exceptions.RequestException as e: | |
| logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") | |
| except Exception as e: | |
| logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True) | |
| if attempt < retries: | |
| time.sleep(delay) | |
| if not success and file_name == DATA_FILE: | |
| logging.error(f"Failed to download critical file {file_name} after {retries + 1} attempts.") | |
| all_successful = False | |
| elif not success: | |
| logging.warning(f"Failed to download non-critical file {file_name} after {retries + 1} attempts.") | |
| logging.info(f"Download process finished. Overall success for critical files: {all_successful}") | |
| return all_successful | |
| def upload_db_to_hf(specific_file=None): | |
| if not HF_TOKEN_WRITE: | |
| logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.") | |
| return | |
| try: | |
| api = HfApi() | |
| files_to_upload = [specific_file] if specific_file else SYNC_FILES | |
| logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...") | |
| for file_name in files_to_upload: | |
| if os.path.exists(file_name): | |
| try: | |
| api.upload_file( | |
| path_or_fileobj=file_name, | |
| path_in_repo=file_name, | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" | |
| ) | |
| logging.info(f"File {file_name} successfully uploaded to Hugging Face.") | |
| except Exception as e: | |
| logging.error(f"Error uploading file {file_name} to Hugging Face: {e}") | |
| else: | |
| logging.warning(f"File {file_name} not found locally, skipping upload.") | |
| logging.info("Finished uploading files to HF.") | |
| except Exception as e: | |
| logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True) | |
| def periodic_backup(): | |
| backup_interval = 1800 | |
| logging.info(f"Setting up periodic backup every {backup_interval} seconds.") | |
| while True: | |
| time.sleep(backup_interval) | |
| logging.info("Starting periodic backup...") | |
| upload_db_to_hf() | |
| logging.info("Periodic backup finished.") | |
| def _save_data_background(data_to_save): | |
| try: | |
| if '_cache' in data_to_save: | |
| data_to_save.pop('_cache') | |
| 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 successfully saved to {DATA_FILE} in background.") | |
| upload_db_to_hf(specific_file=DATA_FILE) | |
| except Exception as e: | |
| logging.error(f"Error saving data in background thread: {e}", exc_info=True) | |
| def update_and_save_data(new_data): | |
| global APP_DATA | |
| with data_lock: | |
| APP_DATA = new_data | |
| data_copy_for_saving = copy.deepcopy(APP_DATA) | |
| save_thread = threading.Thread(target=_save_data_background, args=(data_copy_for_saving,)) | |
| save_thread.start() | |
| def get_data(): | |
| with data_lock: | |
| return copy.deepcopy(APP_DATA) | |
| def run_migrations(data): | |
| migration_performed = False | |
| for product in data.get('products', []): | |
| if 'id' not in product or not product.get('id'): | |
| product['id'] = str(uuid.uuid4()) | |
| migration_performed = True | |
| if data.get('categories') and all(isinstance(c, str) for c in data['categories']): | |
| logging.info("Running migration: Converting categories to object structure.") | |
| old_categories = data['categories'] | |
| new_categories = [] | |
| new_subcategories = [] | |
| for cat_name in old_categories: | |
| if cat_name == 'Без категории': continue | |
| new_cat_id = str(uuid.uuid4()) | |
| new_categories.append({'id': new_cat_id, 'name': cat_name}) | |
| new_subcat_id = str(uuid.uuid4()) | |
| new_subcategories.append({'id': new_subcat_id, 'name': cat_name, 'parent_id': new_cat_id}) | |
| for p in data['products']: | |
| if p.get('category') == cat_name: | |
| p['subcategory_id'] = new_subcat_id | |
| p.pop('category', None) | |
| data['categories'] = new_categories | |
| data['subcategories'] = data.get('subcategories', []) + new_subcategories | |
| migration_performed = True | |
| for p in data['products']: | |
| if 'category' in p and 'subcategory_id' in p: | |
| del p['category'] | |
| migration_performed = True | |
| for cat in data.get('categories', []): | |
| if 'id' not in cat or not cat.get('id'): | |
| cat['id'] = str(uuid.uuid4()) | |
| migration_performed = True | |
| for subcat in data.get('subcategories', []): | |
| if 'id' not in subcat or not subcat.get('id'): | |
| subcat['id'] = str(uuid.uuid4()) | |
| migration_performed = True | |
| subcat.setdefault('parent_id', None) | |
| if migration_performed: | |
| logging.info("Data migration complete.") | |
| else: | |
| logging.info("No data migration needed.") | |
| return data, migration_performed | |
| def initialize_data(): | |
| default_data = {'products': [], 'categories': [], 'subcategories': [], 'suppliers': [], 'orders': {}, 'config': {'prices_enabled': True}} | |
| data_loaded = False | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info(f"Local data loaded successfully from {DATA_FILE}") | |
| data_loaded = True | |
| except (FileNotFoundError, json.JSONDecodeError): | |
| logging.warning(f"Local file {DATA_FILE} not found or corrupt. Attempting download from HF.") | |
| if not data_loaded: | |
| if download_db_from_hf(specific_file=DATA_FILE): | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info(f"Data loaded successfully from {DATA_FILE} after download.") | |
| except (FileNotFoundError, json.JSONDecodeError) as e: | |
| logging.error(f"Error reading or decoding downloaded {DATA_FILE}: {e}. Using default.") | |
| data = default_data | |
| else: | |
| logging.error(f"Failed to download {DATA_FILE} from HF. Using empty default data structure.") | |
| data = default_data | |
| if not os.path.exists(DATA_FILE): | |
| try: | |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: | |
| json.dump(default_data, f) | |
| logging.info(f"Created empty local file {DATA_FILE} after failed download.") | |
| except Exception as create_e: | |
| logging.error(f"Failed to create empty local file {DATA_FILE}: {create_e}") | |
| if not isinstance(data, dict): | |
| logging.error(f"Loaded data is not a dictionary. Resetting to default.") | |
| data = default_data | |
| data.setdefault('products', []) | |
| data.setdefault('categories', []) | |
| data.setdefault('subcategories', []) | |
| data.setdefault('suppliers', []) | |
| data.setdefault('orders', {}) | |
| data.setdefault('config', {'prices_enabled': True}) | |
| data['config'].setdefault('prices_enabled', True) | |
| if 'usd_to_kgs_rate' in data['config']: | |
| del data['config']['usd_to_kgs_rate'] | |
| if 'usd_to_uzs_rate' in data['config']: | |
| del data['config']['usd_to_uzs_rate'] | |
| for prod in data.get('products', []): | |
| prod.setdefault('supplier', 'Без поставщика') | |
| prod.setdefault('on_order', False) | |
| if 'price_usd' in prod: | |
| prod['price_kgs'] = float(prod.pop('price_usd', 0.0)) | |
| elif 'price' in prod: | |
| try: | |
| prod['price_kgs'] = float(prod.pop('price')) | |
| except (ValueError, TypeError): | |
| prod['price_kgs'] = 0.0 | |
| prod.setdefault('price_kgs', 0.0) | |
| prod.setdefault('discount_percent', 0) | |
| try: | |
| prod['discount_percent'] = int(prod['discount_percent']) | |
| if not (0 <= prod['discount_percent'] <= 100): prod['discount_percent'] = 0 | |
| except (ValueError, TypeError): | |
| prod['discount_percent'] = 0 | |
| if 'video' in prod and 'video_filename' not in prod: | |
| prod['video_filename'] = prod.pop('video') | |
| data, migration_was_performed = run_migrations(data) | |
| categories_by_id = {c['id']: c for c in data.get('categories', [])} | |
| subcategories_by_id = {s['id']: s for s in data.get('subcategories', [])} | |
| data['_cache'] = { | |
| 'categories_by_id': categories_by_id, | |
| 'subcategories_by_id': subcategories_by_id | |
| } | |
| global APP_DATA | |
| with data_lock: | |
| APP_DATA = data | |
| logging.info("Initial data loaded and cached in memory.") | |
| if migration_was_performed: | |
| logging.info("Saving data after migration...") | |
| update_and_save_data(data) | |
| def get_full_product_info(product, data): | |
| info = product.copy() | |
| cache = data.get('_cache', {}) | |
| categories_by_id = cache.get('categories_by_id', {}) | |
| subcategories_by_id = cache.get('subcategories_by_id', {}) | |
| category_id_resolved = None | |
| category_name = get_translation('no_category') | |
| subcategory_name = get_translation('no_subcategory') | |
| subcategory_id = product.get('subcategory_id') | |
| if subcategory_id and subcategory_id in subcategories_by_id: | |
| subcat = subcategories_by_id[subcategory_id] | |
| subcategory_name = subcat['name'] | |
| category_id_resolved = subcat.get('parent_id') | |
| if category_id_resolved and category_id_resolved in categories_by_id: | |
| cat = categories_by_id[category_id_resolved] | |
| category_name = cat['name'] | |
| info['category_name'] = category_name | |
| info['subcategory_name'] = subcategory_name | |
| info['supplier_name'] = product.get('supplier', get_translation('no_supplier')) | |
| info['category_id'] = category_id_resolved | |
| return info | |
| def inject_global_vars(): | |
| lang_translations = translations['ru'] | |
| data = get_data() | |
| app_config = data.get('config', {'prices_enabled': True}) | |
| js_trans_keys = [ | |
| 'error_product_not_found', 'error_invalid_quantity', 'error_adding_product_not_found', | |
| 'product_added_to_cart', 'cart_item_color_prefix', 'cart_item_color_suffix', | |
| 'remove_item_title', 'confirm_clear_cart', 'cart_empty_for_order', 'formulating_order', | |
| 'failed_to_create_order', 'order_id_not_received', 'error_generic', | |
| 'no_products_found_for_query', 'cart_empty', 'loading', 'no_products_yet', | |
| 'js_new_color_variant_placeholder', 'prices_disabled_notice_cart', 'price_on_request', | |
| 'save_all_changes_button', 'select_category_first', 'no_subcategory_option' | |
| ] | |
| js_translations_dict = {key: lang_translations.get(key, key) for key in js_trans_keys} | |
| return dict( | |
| get_translation=get_translation, | |
| js_translations=js_translations_dict, | |
| app_config=app_config | |
| ) | |
| CATALOG_TEMPLATE = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>{{ get_translation('catalog_title') }}</title> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&family=Roboto:wght@400;700&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css"> | |
| <style> | |
| :root { | |
| --bg-amulet-black: #0D1117; | |
| --bg-steel-dark: #161B22; | |
| --bg-steel-mid: #21262D; | |
| --border-steel: #30363D; | |
| --text-light: #f0f6fc; | |
| --text-steel: #c9d1d9; | |
| --accent-red: #e63946; | |
| --accent-red-hover: #c32f3a; | |
| --accent-orange: #f39c12; | |
| --accent-gray: #6c7a89; | |
| --font-primary: 'Montserrat', sans-serif; | |
| --font-secondary: 'Roboto', sans-serif; | |
| } | |
| * { margin: 0; padding: 0; box-sizing: border-box; } | |
| html { scroll-behavior: smooth; } | |
| body { | |
| font-family: var(--font-primary); | |
| background: var(--bg-amulet-black); | |
| color: var(--text-light); | |
| line-height: 1.6; | |
| } | |
| .container { max-width: 1200px; margin: 0 auto; padding: 25px; } | |
| .header { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| padding-bottom: 20px; | |
| border-bottom: 1px solid var(--border-steel); | |
| margin-bottom: 30px; | |
| } | |
| .header h1 { | |
| font-family: var(--font-primary); | |
| font-size: 2.5rem; | |
| font-weight: 700; | |
| color: var(--text-light); | |
| letter-spacing: 1px; | |
| text-transform: uppercase; | |
| } | |
| .filters-section { margin-bottom: 30px; } | |
| .filters-section h3 { | |
| text-align: center; | |
| color: var(--text-steel); | |
| margin-bottom: 15px; | |
| font-size: 1.3rem; | |
| font-weight: 600; | |
| } | |
| .filters-container { margin-bottom: 25px; display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; } | |
| .search-container { margin: 30px 0; text-align: center; } | |
| #search-input { | |
| width: 100%; | |
| max-width: 700px; | |
| padding: 14px 22px; | |
| font-size: 1rem; | |
| border: 1px solid var(--border-steel); | |
| border-radius: 30px; | |
| outline: none; | |
| box-shadow: inset 0 2px 8px rgba(0,0,0,0.4); | |
| transition: all 0.3s ease; | |
| background: var(--bg-steel-dark); | |
| color: var(--text-light); | |
| font-family: var(--font-primary); | |
| } | |
| #search-input:focus { | |
| border-color: var(--accent-red); | |
| box-shadow: 0 0 0 3px rgba(230, 57, 70, 0.25), inset 0 2px 8px rgba(0,0,0,0.4); | |
| } | |
| .filter-button { | |
| padding: 9px 20px; | |
| border: 1px solid var(--border-steel); | |
| border-radius: 20px; | |
| background-color: var(--bg-steel-mid); | |
| cursor: pointer; | |
| transition: all 0.2s ease-in-out; | |
| font-size: 0.9rem; | |
| font-weight: 600; | |
| color: var(--text-steel); | |
| } | |
| .filter-button.active, .filter-button:hover { | |
| background-color: var(--accent-red); | |
| color: #FFFFFF; | |
| border-color: var(--accent-red); | |
| transform: translateY(-2px); | |
| box-shadow: 0 4px 12px rgba(230, 57, 70, 0.2); | |
| } | |
| .category-group { | |
| margin-bottom: 15px; | |
| border: 1px solid var(--border-steel); | |
| border-radius: 12px; | |
| background: var(--bg-steel-dark); | |
| overflow: hidden; | |
| } | |
| .category-group-header { | |
| font-size: 1.2rem; | |
| font-weight: 700; | |
| color: var(--text-light); | |
| padding: 15px 20px; | |
| cursor: pointer; | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| background-color: var(--bg-steel-mid); | |
| border-bottom: 1px solid transparent; | |
| } | |
| .category-group-header.active { | |
| background-color: var(--accent-red); | |
| color: #FFFFFF; | |
| border-color: var(--accent-red); | |
| } | |
| .category-group-header.active .icon { | |
| color: #FFFFFF; | |
| } | |
| .category-group-header:hover { | |
| background-color: #383e45; | |
| } | |
| .category-group-header.active:hover { | |
| background-color: var(--accent-red-hover); | |
| } | |
| .category-group-header .icon { | |
| transition: transform 0.3s ease; | |
| color: var(--text-steel); | |
| } | |
| .category-group-content { | |
| padding: 0px 20px 0px 20px; | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| max-height: 0; | |
| overflow: hidden; | |
| transition: max-height 0.4s ease-out, padding 0.4s ease-out; | |
| } | |
| .category-group.open .category-group-content { | |
| max-height: 1000px; | |
| padding: 15px 20px 20px 20px; | |
| } | |
| .category-group.open .category-group-header { | |
| border-bottom: 1px solid var(--border-steel); | |
| } | |
| .category-group.open .category-group-header .icon { | |
| transform: rotate(180deg); | |
| } | |
| .products-grid { | |
| display: grid; | |
| grid-template-columns: repeat(2, 1fr); | |
| gap: 25px; | |
| padding: 10px 0; | |
| } | |
| .product { | |
| background: var(--bg-steel-dark); | |
| border-radius: 16px; | |
| box-shadow: 0 8px 24px rgba(0,0,0,0.3); | |
| transition: transform 0.3s ease, box-shadow 0.3s ease; | |
| overflow: hidden; | |
| display: flex; | |
| flex-direction: column; | |
| border: 1px solid var(--border-steel); | |
| position: relative; | |
| } | |
| .product:hover { | |
| transform: translateY(-8px); | |
| box-shadow: 0 12px 32px rgba(0,0,0,0.4), 0 0 15px rgba(230, 57, 70, 0.1); | |
| } | |
| .product-image-link { display: block; text-decoration: none; } | |
| .product-image { | |
| width: 100%; | |
| aspect-ratio: 1 / 1; | |
| background-color: var(--bg-steel-mid); | |
| overflow: hidden; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| position:relative; | |
| } | |
| .product-image img { | |
| max-width: 100%; | |
| max-height: 100%; | |
| object-fit: contain; | |
| transition: transform 0.3s ease; | |
| } | |
| .product:hover .product-image img { transform: scale(1.05); } | |
| .product-content { padding: 20px; flex-grow: 1; display: flex; flex-direction: column; justify-content: space-between; } | |
| .product-info h2 { | |
| font-family: var(--font-primary); | |
| font-size: 1.2rem; | |
| font-weight: 600; | |
| margin: 0 0 10px 0; | |
| text-align: left; | |
| color: var(--text-light); | |
| height: 2.6rem; | |
| overflow: hidden; | |
| } | |
| .product-price-container { | |
| text-align: left; | |
| margin: 10px 0; | |
| min-height: 40px; | |
| } | |
| .original-price { font-size: 1rem; color: var(--text-steel); text-decoration: line-through; } | |
| .product-price { | |
| font-family: var(--font-secondary); | |
| font-size: 1.6rem; | |
| color: var(--text-light); | |
| font-weight: 700; | |
| margin-right: 10px; | |
| } | |
| .product-price.discounted { color: var(--accent-red); } | |
| .product-price.on-request { font-size: 1.1rem; color: var(--text-steel); } | |
| .discount-badge { background-color: var(--accent-red); color: white; padding: 4px 10px; border-radius: 6px; font-size: 0.9rem; font-weight: bold; display: inline-block; } | |
| .product-actions { padding: 0 20px 20px 20px; display: flex; flex-direction: column; gap: 10px; } | |
| .product-button { | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| width: 100%; | |
| padding: 12px 8px; | |
| border: none; | |
| border-radius: 8px; | |
| background-color: var(--bg-steel-mid); | |
| color: var(--text-light); | |
| font-size: 0.95rem; | |
| font-weight: 600; | |
| cursor: pointer; | |
| transition: all 0.2s ease-in-out; | |
| text-align: center; | |
| text-decoration: none; | |
| gap: 8px; | |
| line-height: 1.2; | |
| } | |
| .product-button:hover { background-color: #383e45; } | |
| .add-to-cart { background-color: var(--accent-red); color: #FFFFFF;} | |
| .add-to-cart:hover { background-color: var(--accent-red-hover); } | |
| .video-button { background-color: transparent; border: 1px solid var(--accent-red); color: var(--accent-red); } | |
| .video-button:hover { background-color: var(--accent-red); color: white; } | |
| #cart-button { position: fixed; bottom: 25px; right: 25px; background-color: var(--accent-red); color: #FFFFFF; border: none; border-radius: 50%; width: 60px; height: 60px; font-size: 1.6rem; cursor: pointer; display: none; align-items: center; justify-content: center; box-shadow: 0 6px 20px rgba(230, 57, 70, 0.3); transition: all 0.3s ease; z-index: 1000; } | |
| #cart-button:hover { background-color: var(--accent-red-hover); transform: scale(1.1); } | |
| #cart-button span { position: absolute; top: 0px; right: 0px; background-color: #fff; color: var(--accent-red); border-radius: 50%; padding: 1px 7px; font-size: 0.8rem; font-weight: bold; border: 2px solid var(--accent-red); } | |
| .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(13, 17, 23, 0.85); backdrop-filter: blur(8px); overflow-y: auto; } | |
| .modal-content { background: var(--bg-steel-dark); margin: 5% auto; padding: 30px; border-radius: 16px; width: 90%; max-width: 800px; box-shadow: 0 10px 40px rgba(0,0,0,0.5); animation: slideIn 0.4s cubic-bezier(0.165, 0.84, 0.44, 1); position: relative; border: 1px solid var(--border-steel);} | |
| @keyframes slideIn { from { transform: translateY(-40px) scale(0.98); opacity: 0; } to { transform: translateY(0) scale(1); opacity: 1; } } | |
| .close { position: absolute; top: 15px; right: 25px; font-size: 2.2rem; color: var(--text-steel); cursor: pointer; transition: color 0.3s; line-height: 1; } | |
| .close:hover { color: var(--accent-red); } | |
| .modal-content h2 { margin-top: 0; margin-bottom: 25px; color: var(--accent-red); display: flex; align-items: center; gap: 12px;} | |
| .cart-item { display: grid; grid-template-columns: 80px 1fr auto auto; gap: 20px; align-items: center; padding: 15px 0; border-bottom: 1px solid var(--border-steel); } | |
| .cart-item:last-child { border-bottom: none; } | |
| .cart-item img { width: 80px; height: 80px; object-fit: contain; border-radius: 8px; background-color: var(--bg-steel-mid); padding: 5px; grid-column: 1;} | |
| .cart-item-details strong { display: block; margin-bottom: 5px; font-size: 1.1rem; color: var(--text-light);} | |
| .cart-item-price, .cart-item-quantity-info { font-size: 0.9rem; color: var(--text-steel); } | |
| .cart-item-total { font-weight: bold; text-align: right; grid-column: 3; font-size: 1.1rem; color: var(--text-light);} | |
| .cart-item-remove { grid-column: 4; background:none; border:none; color: var(--accent-red); cursor:pointer; font-size: 1.5em; padding: 5px; line-height: 1; transition: color 0.2s; } | |
| .cart-item-remove:hover { color: var(--accent-red-hover); } | |
| .quantity-input, .color-select { width: 100%; max-width: 180px; padding: 12px; border: 1px solid var(--border-steel); border-radius: 8px; font-size: 1rem; margin: 10px 0; box-sizing: border-box; background: var(--bg-amulet-black); color: var(--text-light);} | |
| .quantity-input:focus, .color-select:focus { border-color: var(--accent-red); outline: none; box-shadow: 0 0 0 2px rgba(230, 57, 70, 0.2); } | |
| .cart-summary { margin-top: 25px; text-align: right; border-top: 1px solid var(--border-steel); padding-top: 20px; } | |
| .cart-summary strong { font-size: 1.4rem; color: var(--text-light);} | |
| .cart-actions { margin-top: 25px; display: flex; justify-content: space-between; gap: 15px; flex-wrap: wrap; } | |
| .clear-cart { background-color: var(--bg-steel-mid); color: var(--text-light);} | |
| .formulate-order-button { background-color: var(--accent-red); color: #FFFFFF;} | |
| .notification { position: fixed; bottom: 90px; left: 50%; transform: translateX(-50%); background-color: var(--accent-red); color: #FFFFFF; padding: 12px 25px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); z-index: 1002; opacity: 0; transition: all 0.5s ease; font-size: 1rem; font-weight: 600; } | |
| .notification.show { opacity: 1; transform: translateX(-50%) translateY(0); } | |
| .no-results-message { grid-column: 1 / -1; text-align: center; padding: 50px; font-size: 1.2rem; color: var(--text-steel); } | |
| .top-product-indicator { position: absolute; top: 12px; right: 12px; background-color: rgba(230, 57, 70, 0.9); color: #FFFFFF; padding: 4px 10px; font-size: 0.8rem; border-radius: 6px; font-weight: bold; z-index: 10; backdrop-filter: blur(3px); } | |
| .product-status-badge { position: absolute; top: 12px; left: 12px; padding: 4px 10px; font-size: 0.8rem; border-radius: 6px; font-weight: bold; z-index: 10; color: #FFFFFF; backdrop-filter: blur(3px); } | |
| .product-status-badge.on-order { background-color: rgba(243, 156, 18, 0.9); } | |
| .product-status-badge.out-of-stock { background-color: rgba(108, 122, 137, 0.9); } | |
| .prices-disabled-info-banner { background-color: var(--bg-steel-dark); border: 1px solid var(--border-steel); color: var(--text-steel); padding: 12px; text-align: center; margin-bottom: 20px; border-radius: 8px; font-size: 0.9em;} | |
| #videoModal .modal-content { max-width: 90vw; max-height: 80vh; background: black; } | |
| #video-player { width: 100%; height: 100%; max-height: 80vh; border-radius: 8px; } | |
| @media (max-width: 600px) { .products-grid { grid-template-columns: 1fr; } } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <h1>{{ get_translation('site_name') }}</h1> | |
| </div> | |
| {% if not app_config.prices_enabled %} | |
| <div class="prices-disabled-info-banner"> | |
| {{ get_translation('prices_disabled_notice_catalog') }} | |
| </div> | |
| {% endif %} | |
| <div class="filters-section"> | |
| <h3>{{ get_translation('supplier') }}</h3> | |
| <div class="filters-container"> | |
| <button class="filter-button supplier-filter active" data-filter-type="supplier" data-filter-id="all">{{ get_translation('all_suppliers') }}</button> | |
| {% for supplier_name in suppliers %} | |
| <button class="filter-button supplier-filter" data-filter-type="supplier" data-filter-id="{{ supplier_name }}">{{ supplier_name }}</button> | |
| {% endfor %} | |
| </div> | |
| <h3>{{ get_translation('category') }}</h3> | |
| <div class="filters-container"> | |
| <button class="filter-button category-filter active" data-filter-type="category" data-filter-id="all">{{ get_translation('all_categories') }}</button> | |
| </div> | |
| {% for category in categories %} | |
| <div class="category-group" data-category-id="{{ category.id }}"> | |
| <div class="category-group-header filter-button category-filter" data-filter-type="category" data-filter-id="{{ category.id }}"> | |
| <span>{{ category.name }}</span> | |
| {% if category.subcategories|length > 0 %} | |
| <i class="fas fa-chevron-down icon"></i> | |
| {% endif %} | |
| </div> | |
| <div class="category-group-content"> | |
| {% for subcategory in category.subcategories %} | |
| <button class="filter-button subcategory-filter" data-filter-type="subcategory" data-filter-id="{{ subcategory.id }}">{{ subcategory.name }}</button> | |
| {% endfor %} | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| <div class="search-container"> | |
| <input type="text" id="search-input" placeholder="{{ get_translation('search_placeholder') }}"> | |
| </div> | |
| <div class="products-grid" id="products-grid"> | |
| {% for product in products %} | |
| <div class="product" | |
| data-name="{{ product['name']|lower }}" | |
| data-description="{{ product.get('description', '')|lower }}" | |
| data-category-id="{{ product.get('category_id', 'none') }}" | |
| data-subcategory-id="{{ product.get('subcategory_id', 'none') }}" | |
| data-supplier="{{ product.get('supplier', get_translation('no_supplier')) }}"> | |
| {% if product.get('on_order', False) %} | |
| <div class="product-status-badge on-order"><i class="fas fa-shipping-fast"></i> {{ get_translation('status_on_order') }}</div> | |
| {% elif not product.get('in_stock', True) %} | |
| <div class="product-status-badge out-of-stock"><i class="fas fa-times-circle"></i> {{ get_translation('status_out_of_stock') }}</div> | |
| {% endif %} | |
| {% if product.get('is_top', False) %} | |
| <span class="top-product-indicator"><i class="fas fa-star"></i> {{ get_translation('status_top_product') }}</span> | |
| {% endif %} | |
| <a href="#" onclick="openModal({{ loop.index0 }}); return false;" class="product-image-link"> | |
| <div class="product-image"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" | |
| alt="{{ product['name'] }}" | |
| loading="lazy"> | |
| {% else %} | |
| <img src="https://via.placeholder.com/300x300.png?text={{ get_translation('no_image_alt')|urlencode }}" alt="{{ get_translation('no_image_alt') }}" loading="lazy" style="opacity: 0.5;"> | |
| {% endif %} | |
| </div> | |
| </a> | |
| <div class="product-content"> | |
| <div class="product-info"> | |
| <h2>{{ product['name'] }}</h2> | |
| <div class="product-price-container"> | |
| {% set discount = product.get('discount_percent', 0) %} | |
| {% set original_price_kgs = product.price_kgs %} | |
| {% if app_config.prices_enabled %} | |
| {% if discount > 0 %} | |
| {% set discounted_price_kgs = original_price_kgs * (100 - discount) / 100 %} | |
| <span class="original-price">{{ "%.2f"|format(original_price_kgs) }} {{ currency_code }}</span><br> | |
| <span class="product-price discounted">{{ "%.2f"|format(discounted_price_kgs) }} {{ currency_code }}</span> | |
| <span class="discount-badge">{{ get_translation('discount_badge_text', discount=discount) }}</span> | |
| {% else %} | |
| {% if original_price_kgs > 0 %} | |
| <span class="product-price">{{ "%.2f"|format(original_price_kgs) }} {{ currency_code }}</span> | |
| {% else %} | |
| <div class="product-price on-request">{{ get_translation('price_on_request') }}</div> | |
| {% endif %} | |
| {% endif %} | |
| {% else %} | |
| <div class="product-price on-request">{{ get_translation('price_on_request') }}</div> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div class="product-actions"> | |
| <button class="product-button" onclick="openModal({{ loop.index0 }})"><i class="fas fa-info-circle"></i> {{ get_translation('details') }}</button> | |
| {% if product.get('video_filename') %} | |
| <button class="product-button video-button" onclick="openVideoModal('{{ product.video_filename }}')"> | |
| <i class="fas fa-play-circle"></i> {{ get_translation('view_video_button') }} | |
| </button> | |
| {% endif %} | |
| {% if app_config.prices_enabled %} | |
| <button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})"> | |
| <i class="fas fa-cart-plus"></i> {{ get_translation('add_to_cart') }} | |
| </button> | |
| {% else %} | |
| <button class="product-button add-to-cart" style="background-color: #25D366;" onclick="inquireProductWhatsApp({{ loop.index0 }})"> | |
| <i class="fab fa-whatsapp"></i> {{ get_translation('request_price_calculation_button') }} | |
| </button> | |
| {% endif %} | |
| </div> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% if not products %} | |
| <p class="no-results-message" id="initial-no-products-message">{{ get_translation('no_products_yet') }}</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div id="productModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('productModal')" aria-label="{{ get_translation('close_button_aria') }}">×</span> | |
| <div id="modalContent">{{ get_translation('loading') }}</div> | |
| </div> | |
| </div> | |
| <div id="videoModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeVideoModal()" aria-label="{{ get_translation('close_button_aria') }}">×</span> | |
| <video id="video-player" controls controlsList="nodownload" preload="metadata"> | |
| <source src="" type="video/mp4"> | |
| Your browser does not support the video tag. | |
| </video> | |
| </div> | |
| </div> | |
| <div id="quantityModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('quantityModal')" aria-label="{{ get_translation('close_button_aria') }}">×</span> | |
| <h2>{{ get_translation('specify_quantity_color') }}</h2> | |
| <label for="quantityInput">{{ get_translation('quantity') }}</label> | |
| <input type="number" id="quantityInput" class="quantity-input" min="1" value="1"> | |
| <label for="colorSelect">{{ get_translation('color_variant') }}</label> | |
| <select id="colorSelect" class="color-select"></select> | |
| <button class="product-button add-to-cart" onclick="confirmAddToCart()"><i class="fas fa-check"></i> {{ get_translation('confirm_add_to_cart') }}</button> | |
| </div> | |
| </div> | |
| <div id="cartModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('cartModal')" aria-label="{{ get_translation('close_button_aria') }}">×</span> | |
| <h2><i class="fas fa-shopping-cart"></i> {{ get_translation('your_cart') }}</h2> | |
| <div id="cartContent"><p style="text-align: center; padding: 20px;">{{ get_translation('cart_empty') }}</p></div> | |
| {% if app_config.prices_enabled %} | |
| <div class="cart-summary"> | |
| <strong>{{ get_translation('total') }} <span id="cartTotal">0.00</span> {{ currency_code }}</strong> | |
| </div> | |
| {% else %} | |
| <div class="cart-summary prices-disabled-info-banner" style="text-align:center; margin-top:10px;"> | |
| {{ get_translation('prices_disabled_notice_cart') }} | |
| </div> | |
| {% endif %} | |
| <div class="cart-actions"> | |
| <button class="product-button clear-cart" onclick="clearCart()"> | |
| <i class="fas fa-trash"></i> {{ get_translation('clear_cart') }} | |
| </button> | |
| <button class="product-button formulate-order-button" onclick="formulateOrder()"> | |
| <i class="fas fa-file-alt"></i> | |
| {% if app_config.prices_enabled %} | |
| {{ get_translation('formulate_order') }} | |
| {% else %} | |
| {{ get_translation('request_price_calculation_button') }} | |
| {% endif %} | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| <button id="cart-button" onclick="openCartModal()" aria-label="{{ get_translation('open_cart_aria') }}"> | |
| <i class="fas fa-shopping-cart"></i> | |
| <span id="cart-count">0</span> | |
| </button> | |
| <div id="notification-placeholder"></div> | |
| <input type="hidden" id="prices_enabled_for_js" value="{{ app_config.prices_enabled|tojson }}"> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script> | |
| <script> | |
| const products = {{ products|tojson }}; | |
| const repoId = '{{ repo_id }}'; | |
| const currencyCode = '{{ currency_code }}'; | |
| let selectedProductIndex = null; | |
| let cart = JSON.parse(localStorage.getItem('emirShopCart') || '[]'); | |
| const jsTranslations = {{ js_translations|tojson }}; | |
| const pricesEnabled = JSON.parse(document.getElementById('prices_enabled_for_js').value); | |
| function _(key, params = {}) { | |
| let text = jsTranslations[key] || `MISSING_JS_TRANSLATION: ${key}`; | |
| for (const pKey in params) { | |
| text = text.replace(new RegExp(`{${pKey}}`, 'g'), params[pKey]); | |
| } | |
| return text; | |
| } | |
| function inquireProductWhatsApp(index) { | |
| const product = products[index]; | |
| if (!product) return; | |
| const phoneNumber = "996553303156"; | |
| const inquiryMessageTemplate = `{{ get_translation('whatsapp_product_inquiry', product_name='PLACEHOLDER_NAME') }}`; | |
| const inquiryMessage = encodeURIComponent( | |
| inquiryMessageTemplate.replace('PLACEHOLDER_NAME', product.name) | |
| ); | |
| const whatsappUrl = `https://wa.me/${phoneNumber}?text=${inquiryMessage}`; | |
| window.open(whatsappUrl, '_blank'); | |
| } | |
| function openModal(index) { | |
| loadProductDetails(index); | |
| const modal = document.getElementById('productModal'); | |
| if (modal) { | |
| modal.style.display = "block"; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| } | |
| function closeModal(modalId) { | |
| const modal = document.getElementById(modalId); | |
| if (modal) { | |
| modal.style.display = "none"; | |
| } | |
| const anyModalOpen = document.querySelector('.modal[style*="display: block"]'); | |
| if (!anyModalOpen) { | |
| document.body.style.overflow = 'auto'; | |
| } | |
| } | |
| function openVideoModal(videoFilename) { | |
| const modal = document.getElementById('videoModal'); | |
| const videoPlayer = document.getElementById('video-player'); | |
| if (modal && videoPlayer) { | |
| const videoSource = videoPlayer.getElementsByTagName('source')[0]; | |
| videoSource.src = `https://huggingface.co/datasets/${repoId}/resolve/main/videos/${videoFilename}`; | |
| videoPlayer.load(); | |
| modal.style.display = 'block'; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| } | |
| function closeVideoModal() { | |
| const modal = document.getElementById('videoModal'); | |
| const videoPlayer = document.getElementById('video-player'); | |
| if (modal && videoPlayer) { | |
| videoPlayer.pause(); | |
| videoPlayer.getElementsByTagName('source')[0].src = ''; | |
| closeModal('videoModal'); | |
| } | |
| } | |
| function loadProductDetails(index) { | |
| const modalContent = document.getElementById('modalContent'); | |
| if (!modalContent) return; | |
| modalContent.innerHTML = `<p style="text-align:center; padding: 40px;">${_('loading')}</p>`; | |
| fetch('/product/' + index) | |
| .then(response => { | |
| if (!response.ok) throw new Error(`Error ${response.status}: ${response.statusText}`); | |
| return response.text(); | |
| }) | |
| .then(data => { | |
| modalContent.innerHTML = data; | |
| initializeSwiper(); | |
| }) | |
| .catch(error => { | |
| console.error('Error loading product details:', error); | |
| modalContent.innerHTML = `<p style="color: var(--accent-red); text-align:center; padding: 40px;">Failed to load product info. ${error.message}</p>`; | |
| }); | |
| } | |
| function initializeSwiper() { | |
| const swiperContainer = document.querySelector('#productModal .swiper-container'); | |
| if (swiperContainer) { | |
| new Swiper(swiperContainer, { | |
| slidesPerView: 1, | |
| spaceBetween: 20, | |
| loop: true, | |
| grabCursor: true, | |
| pagination: { el: '.swiper-pagination', clickable: true }, | |
| navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, | |
| zoom: { maxRatio: 3, containerClass: 'swiper-zoom-container' }, | |
| autoplay: { delay: 5000, disableOnInteraction: true, }, | |
| }); | |
| } | |
| } | |
| function openQuantityModal(index) { | |
| selectedProductIndex = index; | |
| const product = products[index]; | |
| if (!product) { | |
| console.error("Product not found for index:", index); | |
| alert(_('error_product_not_found')); | |
| return; | |
| } | |
| const colorSelect = document.getElementById('colorSelect'); | |
| const colorLabel = document.querySelector('label[for="colorSelect"]'); | |
| colorSelect.innerHTML = ''; | |
| const validColors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : []; | |
| if (validColors.length > 0) { | |
| validColors.forEach(color => { | |
| const option = document.createElement('option'); | |
| option.value = color.trim(); | |
| option.text = color.trim(); | |
| colorSelect.appendChild(option); | |
| }); | |
| colorSelect.style.display = 'block'; | |
| if(colorLabel) colorLabel.style.display = 'block'; | |
| } else { | |
| colorSelect.style.display = 'none'; | |
| if(colorLabel) colorLabel.style.display = 'none'; | |
| } | |
| document.getElementById('quantityInput').value = 1; | |
| const modal = document.getElementById('quantityModal'); | |
| if(modal) { | |
| modal.style.display = 'block'; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| } | |
| function confirmAddToCart() { | |
| if (selectedProductIndex === null) return; | |
| const quantityInput = document.getElementById('quantityInput'); | |
| const quantity = parseInt(quantityInput.value); | |
| const colorSelect = document.getElementById('colorSelect'); | |
| const color = colorSelect.style.display !== 'none' && colorSelect.value ? colorSelect.value : 'N/A'; | |
| if (isNaN(quantity) || quantity <= 0) { | |
| alert(_('error_invalid_quantity')); | |
| quantityInput.focus(); | |
| return; | |
| } | |
| const product = products[selectedProductIndex]; | |
| if (!product) { | |
| alert(_('error_adding_product_not_found')); | |
| return; | |
| } | |
| const cartItemId = `${product.name}-${color}`; | |
| const existingItemIndex = cart.findIndex(item => item.id === cartItemId); | |
| let priceToAdd = product.price_kgs; | |
| if (product.discount_percent && product.discount_percent > 0) { | |
| priceToAdd = product.price_kgs * (100 - product.discount_percent) / 100; | |
| } | |
| // If price is 0 (optional price field not set by admin) but prices are enabled in config, we still use 0. | |
| if (!pricesEnabled && priceToAdd === 0) { | |
| // If prices are disabled, we treat the price as irrelevant for calculation here, but we save 0 to the cart item if not set. | |
| } | |
| if (existingItemIndex > -1) { | |
| cart[existingItemIndex].quantity += quantity; | |
| } else { | |
| cart.push({ | |
| id: cartItemId, | |
| name: product.name, | |
| price_kgs: priceToAdd, | |
| original_price_kgs: product.price_kgs, | |
| discount_percent: product.discount_percent || 0, | |
| photo: product.photos && product.photos.length > 0 ? product.photos[0] : null, | |
| quantity: quantity, | |
| color: color | |
| }); | |
| } | |
| localStorage.setItem('emirShopCart', JSON.stringify(cart)); | |
| closeModal('quantityModal'); | |
| updateCartButton(); | |
| showNotification(_('product_added_to_cart', {product_name: product.name})); | |
| } | |
| function updateCartButton() { | |
| const cartCountElement = document.getElementById('cart-count'); | |
| const cartButton = document.getElementById('cart-button'); | |
| if (!cartCountElement || !cartButton) return; | |
| let totalItems = 0; | |
| cart.forEach(item => { totalItems += item.quantity; }); | |
| if (totalItems > 0) { | |
| cartCountElement.textContent = totalItems; | |
| cartButton.style.display = 'flex'; | |
| } else { | |
| cartCountElement.textContent = '0'; | |
| cartButton.style.display = 'none'; | |
| } | |
| } | |
| function openCartModal() { | |
| const cartContent = document.getElementById('cartContent'); | |
| const cartTotalElement = document.getElementById('cartTotal'); | |
| if (!cartContent || !cartTotalElement) return; | |
| let totalKGS = 0; | |
| if (cart.length === 0) { | |
| cartContent.innerHTML = `<p style="text-align: center; padding: 20px;">${_('cart_empty')}</p>`; | |
| if (pricesEnabled) cartTotalElement.textContent = '0.00'; | |
| } else { | |
| cartContent.innerHTML = cart.map(item => { | |
| const itemTotalKGS = item.price_kgs * item.quantity; | |
| if (pricesEnabled) totalKGS += itemTotalKGS; | |
| const photoUrl = item.photo | |
| ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` | |
| : 'https://via.placeholder.com/80x80.png?text=N%2FA'; | |
| const colorText = item.color !== 'N/A' ? `${_('cart_item_color_prefix')}${item.color}${_('cart_item_color_suffix')}` : ''; | |
| let priceDisplayHtml = ''; | |
| let itemTotalHtml = ''; | |
| if (pricesEnabled) { | |
| priceDisplayHtml = `<p class="cart-item-price">${item.price_kgs.toFixed(2)} ${currencyCode} × ${item.quantity}</p>`; | |
| itemTotalHtml = `<span class="cart-item-total">${itemTotalKGS.toFixed(2)} ${currencyCode}</span>`; | |
| } else { | |
| priceDisplayHtml = `<p class="cart-item-quantity-info">${_('quantity')} ${item.quantity}</p>`; | |
| itemTotalHtml = `<span class="cart-item-total">${_('price_on_request')}</span>`; | |
| } | |
| return ` | |
| <div class="cart-item"> | |
| <img src="${photoUrl}" alt="${item.name}" ${!item.photo ? 'style="opacity: 0.5;"' : ''}> | |
| <div class="cart-item-details"> | |
| <strong>${item.name}${colorText}</strong> | |
| ${priceDisplayHtml} | |
| </div> | |
| ${itemTotalHtml} | |
| <button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="${_('remove_item_title')}">×</button> | |
| </div> | |
| `; | |
| }).join(''); | |
| if (pricesEnabled) cartTotalElement.textContent = totalKGS.toFixed(2); | |
| } | |
| const modal = document.getElementById('cartModal'); | |
| if (modal) { | |
| modal.style.display = 'block'; | |
| document.body.style.overflow = 'hidden'; | |
| } | |
| } | |
| function removeFromCart(itemId) { | |
| cart = cart.filter(item => item.id !== itemId); | |
| localStorage.setItem('emirShopCart', JSON.stringify(cart)); | |
| openCartModal(); | |
| updateCartButton(); | |
| } | |
| function clearCart() { | |
| if (confirm(_('confirm_clear_cart'))) { | |
| cart = []; | |
| localStorage.removeItem('emirShopCart'); | |
| openCartModal(); | |
| updateCartButton(); | |
| } | |
| } | |
| function formulateOrder() { | |
| if (cart.length === 0) { | |
| alert(_('cart_empty_for_order')); | |
| return; | |
| } | |
| const orderData = { cart: cart }; | |
| const formulateButton = document.querySelector('.formulate-order-button'); | |
| if (formulateButton) formulateButton.disabled = true; | |
| showNotification(_('formulating_order'), 5000); | |
| fetch('/create_order', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify(orderData) | |
| }) | |
| .then(response => { | |
| if (!response.ok) { | |
| return response.json().then(err => { throw new Error(err.error || _('failed_to_create_order')); }); | |
| } | |
| return response.json(); | |
| }) | |
| .then(data => { | |
| if (data.order_id) { | |
| localStorage.removeItem('emirShopCart'); | |
| cart = []; | |
| updateCartButton(); | |
| closeModal('cartModal'); | |
| window.location.href = `/order/${data.order_id}`; | |
| } else { | |
| throw new Error(_('order_id_not_received')); | |
| } | |
| }) | |
| .catch(error => { | |
| console.error('Error formulating order:', error); | |
| alert(_('error_generic', {error_message: error.message})); | |
| if (formulateButton) formulateButton.disabled = false; | |
| }); | |
| } | |
| let currentActiveCategoryFilterType = 'category'; | |
| let currentActiveCategoryFilterId = 'all'; | |
| let currentActiveSupplierId = 'all'; | |
| function filterProducts() { | |
| const searchTerm = document.getElementById('search-input').value.toLowerCase().trim(); | |
| const grid = document.getElementById('products-grid'); | |
| let visibleProducts = 0; | |
| const existingNoResults = grid.querySelector('.no-results-message'); | |
| if (existingNoResults) existingNoResults.remove(); | |
| const initialNoProducts = document.getElementById('initial-no-products-message'); | |
| if (initialNoProducts) initialNoProducts.style.display = 'none'; | |
| document.querySelectorAll('.products-grid .product').forEach(productElement => { | |
| const name = productElement.getAttribute('data-name'); | |
| const description = productElement.getAttribute('data-description'); | |
| const productCategoryId = productElement.getAttribute('data-category-id'); | |
| const productSubcategoryId = productElement.getAttribute('data-subcategory-id'); | |
| const productSupplier = productElement.getAttribute('data-supplier'); | |
| const matchesSearch = !searchTerm || name.includes(searchTerm) || description.includes(searchTerm); | |
| const matchesSupplier = currentActiveSupplierId === 'all' || productSupplier === currentActiveSupplierId; | |
| let matchesCategoryOrSubcategory = false; | |
| if (currentActiveCategoryFilterId === 'all') { | |
| matchesCategoryOrSubcategory = true; | |
| } else if (currentActiveCategoryFilterType === 'subcategory') { | |
| matchesCategoryOrSubcategory = productSubcategoryId === currentActiveCategoryFilterId; | |
| } else if (currentActiveCategoryFilterType === 'category') { | |
| matchesCategoryOrSubcategory = productCategoryId === currentActiveCategoryFilterId; | |
| } | |
| if (matchesSearch && matchesSupplier && matchesCategoryOrSubcategory) { | |
| productElement.style.display = 'flex'; | |
| visibleProducts++; | |
| } else { | |
| productElement.style.display = 'none'; | |
| } | |
| }); | |
| if (visibleProducts === 0 && products.length > 0) { | |
| const p = document.createElement('p'); | |
| p.className = 'no-results-message'; | |
| p.textContent = _('no_products_found_for_query'); | |
| grid.appendChild(p); | |
| } else if (products.length === 0 && !grid.querySelector('.no-results-message') && !initialNoProducts) { | |
| const p = document.createElement('p'); | |
| p.className = 'no-results-message'; | |
| p.textContent = _('no_products_yet'); | |
| grid.appendChild(p); | |
| } else if (products.length === 0 && initialNoProducts) { | |
| initialNoProducts.style.display = 'block'; | |
| } | |
| } | |
| function setupFilters() { | |
| const searchInput = document.getElementById('search-input'); | |
| if(searchInput) searchInput.addEventListener('input', filterProducts); | |
| document.querySelectorAll('.filter-button[data-filter-type="category"], .filter-button[data-filter-type="subcategory"]').forEach(button => { | |
| button.addEventListener('click', function() { | |
| document.querySelectorAll('.filter-button[data-filter-type="category"], .filter-button[data-filter-type="subcategory"]').forEach(btn => btn.classList.remove('active')); | |
| this.classList.add('active'); | |
| currentActiveCategoryFilterType = this.dataset.filterType; | |
| currentActiveCategoryFilterId = this.dataset.filterId; | |
| document.querySelectorAll('.category-group').forEach(group => { | |
| group.classList.remove('open'); | |
| }); | |
| if (currentActiveCategoryFilterId !== 'all') { | |
| const parentCategoryGroup = this.closest('.category-group'); | |
| if (parentCategoryGroup) { | |
| parentCategoryGroup.classList.add('open'); | |
| } | |
| } | |
| filterProducts(); | |
| }); | |
| }); | |
| document.querySelectorAll('.filter-button[data-filter-type="supplier"]').forEach(button => { | |
| button.addEventListener('click', function() { | |
| document.querySelectorAll('.filter-button[data-filter-type="supplier"]').forEach(btn => btn.classList.remove('active')); | |
| this.classList.add('active'); | |
| currentActiveSupplierId = this.dataset.filterId; | |
| filterProducts(); | |
| }); | |
| }); | |
| filterProducts(); | |
| } | |
| function showNotification(message, duration = 3000) { | |
| const placeholder = document.getElementById('notification-placeholder'); | |
| if (!placeholder) return; | |
| const notification = document.createElement('div'); | |
| notification.className = 'notification'; | |
| notification.textContent = message; | |
| placeholder.appendChild(notification); | |
| requestAnimationFrame(() => { | |
| notification.classList.add('show'); | |
| }); | |
| setTimeout(() => { | |
| notification.classList.remove('show'); | |
| notification.addEventListener('transitionend', () => notification.remove()); | |
| }, duration); | |
| } | |
| document.addEventListener('DOMContentLoaded', () => { | |
| updateCartButton(); | |
| setupFilters(); | |
| window.addEventListener('click', function(event) { | |
| if (event.target.classList.contains('modal')) { | |
| if (event.target.id === 'videoModal') { | |
| closeVideoModal(); | |
| } else { | |
| closeModal(event.target.id); | |
| } | |
| } | |
| }); | |
| window.addEventListener('keydown', function(event) { | |
| if (event.key === 'Escape') { | |
| document.querySelectorAll('.modal[style*="display: block"]').forEach(modal => { | |
| if (modal.id === 'videoModal') { | |
| closeVideoModal(); | |
| } else { | |
| closeModal(modal.id); | |
| } | |
| }); | |
| } | |
| }); | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| PRODUCT_DETAIL_TEMPLATE = ''' | |
| <div style="padding: 10px;"> | |
| <h2 style="font-size: 1.8rem; font-weight: 700; margin-bottom: 20px; text-align: center; color: var(--text-light);">{{ product_info['name'] }}</h2> | |
| <div class="swiper-container" style="max-width: 500px; margin: 0 auto 25px; border-radius: 12px; overflow: hidden; background-color: var(--bg-steel-mid); border: 1px solid var(--border-steel);"> | |
| <div class="swiper-wrapper"> | |
| {% if product_info.get('photos') and product_info['photos']|length > 0 %} | |
| {% for photo in product_info['photos'] %} | |
| <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center; padding: 10px;"> | |
| <div class="swiper-zoom-container"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" | |
| alt="{{ get_translation('product_detail_photo_alt', product_name=product_info['name'], loop_index=loop.index) }}" | |
| style="max-width: 100%; max-height: 450px; object-fit: contain; display: block; margin: auto; cursor: grab;"> | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center;"> | |
| <img src="https://via.placeholder.com/400x400.png?text={{ get_translation('no_image_alt')|urlencode }}" alt="{{ get_translation('no_image_alt') }}" style="max-width: 100%; max-height: 450px; object-fit: contain; opacity: 0.5;"> | |
| </div> | |
| {% endif %} | |
| </div> | |
| {% if product_info.get('photos') and product_info['photos']|length > 1 %} | |
| <div class="swiper-pagination" style="--swiper-pagination-color: var(--accent-red); position: relative; bottom: 5px; margin-top: 10px;"></div> | |
| <div class="swiper-button-next" style="color: var(--accent-red);"></div> | |
| <div class="swiper-button-prev" style="color: var(--accent-red);"></div> | |
| {% endif %} | |
| </div> | |
| {% if product_info.get('video_filename') %} | |
| <div style="max-width: 600px; margin: 30px auto;"> | |
| <h3 style="text-align:center; color: var(--text-steel); margin-bottom: 15px; font-weight: 600;">{{ get_translation('video_modal_title') }}</h3> | |
| <video controls controlsList="nodownload" preload="metadata" style="width:100%; display:block; border-radius: 12px; border: 1px solid var(--border-steel);"> | |
| <source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/videos/{{ product_info.video_filename }}" type="video/mp4"> | |
| Ваш браузер не поддерживает видео. | |
| </video> | |
| </div> | |
| {% endif %} | |
| <div style="margin-top: 25px; font-size: 1.05rem; line-height: 1.8; color: var(--text-steel);"> | |
| <p><strong>{{ get_translation('supplier') }}:</strong> {{ product_info.supplier_name }}</p> | |
| <p><strong>{{ get_translation('category') }}:</strong> {{ product_info.category_name }}</p> | |
| <p><strong>{{ get_translation('subcategory') }}:</strong> {{ product_info.subcategory_name }}</p> | |
| {% set discount = product_info.get('discount_percent', 0) %} | |
| {% set original_price_kgs = product_info.price_kgs %} | |
| {% if app_config.prices_enabled %} | |
| <div style="margin: 20px 0; padding: 15px; background: var(--bg-steel-mid); border-radius: 8px;"> | |
| <strong style="font-size: 1.1rem; color: var(--text-light);">{{ get_translation('price') }}</strong> | |
| {% if discount > 0 %} | |
| {% set discounted_price_kgs = original_price_kgs * (100 - discount) / 100 %} | |
| <span style="font-size: 1.8rem; font-weight: 700; color: var(--accent-red); margin-left: 10px;">{{ "%.2f"|format(discounted_price_kgs) }} {{ currency_code }}</span> | |
| <span style="text-decoration: line-through; color: var(--text-steel); font-size: 1.2rem; margin-left: 15px;">{{ "%.2f"|format(original_price_kgs) }} {{ currency_code }}</span> | |
| {% else %} | |
| {% if original_price_kgs > 0 %} | |
| <span style="font-size: 1.8rem; font-weight: 700; color: var(--text-light); margin-left: 10px;">{{ "%.2f"|format(original_price_kgs) }} {{ currency_code }}</span> | |
| {% else %} | |
| <span style="font-size: 1.2rem; font-weight: bold; color: var(--text-steel); margin-left: 10px;">{{ get_translation('price_on_request') }}</span> | |
| {% endif %} | |
| {% endif %} | |
| </div> | |
| {% else %} | |
| <p style="font-size: 1.2rem; font-weight: bold; color: var(--text-steel);"><strong>{{ get_translation('price') }}:</strong> {{ get_translation('price_on_request') }}</p> | |
| {% endif %} | |
| <p><strong>{{ get_translation('description') }}:</strong><br> {{ product_info.get('description', get_translation('description_absent'))|replace('\\n', '<br>')|safe }}</p> | |
| {% set colors = product_info.get('colors', []) %} | |
| {% if colors and colors|select('ne', '')|list|length > 0 %} | |
| <p><strong>{{ get_translation('available_colors_variants') }}:</strong> {{ colors|select('ne', '')|join(', ') }}</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| ''' | |
| ORDER_TEMPLATE = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>{{ get_translation('order_title', order_id=order.id if order else 'N/A') }}</title> | |
| <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <style> | |
| :root { | |
| --bg-amulet-black: #0D1117; | |
| --bg-steel-dark: #161B22; | |
| --bg-steel-mid: #21262D; | |
| --border-steel: #30363D; | |
| --text-light: #f0f6fc; | |
| --text-steel: #c9d1d9; | |
| --accent-red: #e63946; | |
| --font-primary: 'Montserrat', sans-serif; | |
| } | |
| body { font-family: var(--font-primary); background: var(--bg-amulet-black); color: var(--text-light); line-height: 1.6; padding: 20px; } | |
| .container { max-width: 800px; margin: 20px auto; padding: 35px; background: var(--bg-steel-dark); border-radius: 16px; box-shadow: 0 8px 24px rgba(0,0,0,0.3); border: 1px solid var(--border-steel); } | |
| h1 { text-align: center; color: var(--text-light); margin-bottom: 25px; font-size: 2rem; font-weight: 700; } | |
| h1 .fa-receipt { color: var(--accent-red); } | |
| h2 { color: var(--text-light); margin-top: 35px; margin-bottom: 20px; font-size: 1.5rem; border-bottom: 1px solid var(--border-steel); padding-bottom: 12px;} | |
| .order-meta { font-size: 0.9rem; color: var(--text-steel); margin-bottom: 30px; text-align: center; } | |
| .order-item { display: grid; grid-template-columns: 70px 1fr auto; gap: 20px; align-items: center; padding: 15px 0; border-bottom: 1px solid var(--border-steel); } | |
| .order-item:last-child { border-bottom: none; } | |
| .order-item img { width: 70px; height: 70px; object-fit: contain; border-radius: 8px; background-color: var(--bg-steel-mid); padding: 5px; } | |
| .item-details strong { display: block; margin-bottom: 5px; font-size: 1.1rem; color: var(--text-light);} | |
| .item-details span { font-size: 0.9rem; color: var(--text-steel); display: block;} | |
| .item-total { font-weight: bold; text-align: right; font-size: 1.1rem; color: var(--text-light);} | |
| .order-summary { margin-top: 30px; padding-top: 20px; border-top: 2px solid var(--accent-red); text-align: right; } | |
| .order-summary p { margin-bottom: 10px; font-size: 1.2rem; color: var(--text-steel); } | |
| .order-summary strong { font-size: 1.5rem; color: var(--text-light); } | |
| .customer-info { margin-top: 30px; background-color: var(--bg-steel-mid); padding: 25px; border-radius: 12px; } | |
| .customer-info p { margin-bottom: 8px; font-size: 1rem; } | |
| .actions { margin-top: 35px; text-align: center; } | |
| .button { padding: 15px 30px; border: none; border-radius: 8px; background-color: #25D366; color: #FFFFFF; font-weight: 600; cursor: pointer; transition: all 0.2s ease; font-size: 1.1rem; display: inline-flex; align-items: center; gap: 12px; text-decoration: none; } | |
| .button:hover { background-color: #1DA851; transform: translateY(-2px); box-shadow: 0 4px 15px rgba(37, 211, 102, 0.2); } | |
| .button:active { transform: scale(0.98); } | |
| .button i { font-size: 1.4rem; } | |
| .catalog-link { display: block; text-align: center; margin-top: 25px; color: var(--accent-red); text-decoration: none; font-size: 1rem; font-weight: 600; } | |
| .catalog-link:hover { text-decoration: underline; } | |
| .not-found { text-align: center; color: var(--accent-red); font-size: 1.2rem; padding: 40px 0;} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| {% if order %} | |
| <h1><i class="fas fa-receipt"></i> {{ get_translation('order_page_title', order_id=order.id) }}</h1> | |
| <p class="order-meta">{{ get_translation('creation_date') }} {{ order.created_at }}</p> | |
| <h2><i class="fas fa-shopping-bag"></i> {{ get_translation('products_in_order') }}</h2> | |
| <div id="orderItems"> | |
| {% for item in order.cart %} | |
| <div class="order-item"> | |
| <img src="{{ item.photo_url }}" alt="{{ item.name }}" {% if not item.photo %}style="opacity: 0.5;"{% endif %}> | |
| <div class="item-details"> | |
| <strong>{{ item.name }} {% if item.color != 'N/A' %}({{ item.color }}){% endif %}</strong> | |
| {% if order.prices_were_enabled_at_order and item.price_kgs_at_order > 0 %} | |
| <span>{{ "%.2f"|format(item.price_kgs_at_order) }} {{ currency_code }} × {{ item.quantity }}</span> | |
| {% else %} | |
| <span>{{ get_translation('quantity') }} {{ item.quantity }}</span> | |
| {% endif %} | |
| </div> | |
| {% if order.prices_were_enabled_at_order and item.price_kgs_at_order > 0 %} | |
| <div class="item-total"> | |
| {{ "%.2f"|format(item.price_kgs_at_order * item.quantity) }} {{ currency_code }} | |
| </div> | |
| {% else %} | |
| <div class="item-total"> | |
| {{ get_translation('price_on_request') }} | |
| </div> | |
| {% endif %} | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% if order.prices_were_enabled_at_order and order.total_price_kgs > 0 %} | |
| <div class="order-summary"> | |
| <p>{{ get_translation('total_products_sum') }} <strong>{{ "%.2f"|format(order.total_price_kgs) }} {{ currency_code }}</strong></p> | |
| </div> | |
| {% else %} | |
| <div class="order-summary" style="text-align:center;"> | |
| <p>{{ get_translation('prices_disabled_notice_cart') }}</p> | |
| </div> | |
| {% endif %} | |
| <div class="customer-info"> | |
| <h2><i class="fas fa-info-circle"></i> {{ get_translation('order_status') }}</h2> | |
| <p>{{ get_translation('anonymous_order_notice') }}</p> | |
| <p>{{ get_translation('contact_whatsapp_notice') }}</p> | |
| </div> | |
| <div class="actions"> | |
| <button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> {{ get_translation('send_order_button') }}</button> | |
| </div> | |
| <a href="{{ url_for('catalog') }}" class="catalog-link">{{ get_translation('back_to_catalog') }}</a> | |
| <script> | |
| function sendOrderViaWhatsApp() { | |
| const orderId = '{{ order.id }}'; | |
| const rawOrderUrl = String('{{ request.url }}'); | |
| const encodedOrderUrl = encodeURIComponent(rawOrderUrl); | |
| const phoneNumber = "996553303156"; | |
| let message = `{{ get_translation('whatsapp_greeting') | replace("'", "\\'") }}` + "%0A%0A"; | |
| message += `*{{ get_translation('whatsapp_order_number') | replace("'", "\\'") }}* ${orderId}` + "%0A"; | |
| message += `*{{ get_translation('whatsapp_order_link') | replace("'", "\\'") }}* ${encodedOrderUrl}` + "%0A%0A"; | |
| {% if not order.prices_were_enabled_at_order or order.total_price_kgs == 0 %} | |
| message += `{{ get_translation('whatsapp_request_price_calculation') | replace("'", "\\'") }}` + "%0A%0A"; | |
| {% endif %} | |
| message += `{{ get_translation('whatsapp_contact_request') | replace("'", "\\'") }}`; | |
| const whatsappUrl = `https://wa.me/${phoneNumber}?text=${message}`; | |
| window.open(whatsappUrl, '_blank'); | |
| } | |
| </script> | |
| {% else %} | |
| <h1 style="color: var(--accent-red);"><i class="fas fa-exclamation-triangle"></i> {{ get_translation('error_page_title') }}</h1> | |
| <p class="not-found">{{ get_translation('order_not_found_by_id') }}</p> | |
| <a href="{{ url_for('catalog') }}" class="catalog-link">{{ get_translation('back_to_catalog') }}</a> | |
| {% endif %} | |
| </div> | |
| </body> | |
| </html> | |
| ''' | |
| ADMIN_TEMPLATE = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>{{ get_translation('admin_title') }}</title> | |
| <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&display=swap" rel="stylesheet"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> | |
| <style> | |
| :root { | |
| --bg-amulet-black: #0D1117; | |
| --bg-steel-dark: #161B22; | |
| --bg-steel-mid: #21262D; | |
| --border-steel: #30363D; | |
| --text-light: #f0f6fc; | |
| --text-steel: #c9d1d9; | |
| --accent-red: #e63946; | |
| --accent-red-hover: #c32f3a; | |
| --accent-green: #25D366; | |
| --accent-blue: #3498db; | |
| --accent-orange: #f39c12; | |
| --font-primary: 'Montserrat', sans-serif; | |
| } | |
| body { font-family: var(--font-primary); background-color: var(--bg-amulet-black); color: var(--text-light); padding: 20px; line-height: 1.6; } | |
| .container { max-width: 1400px; margin: 0 auto; background-color: var(--bg-steel-dark); padding: 30px; border-radius: 12px; } | |
| .header { padding-bottom: 20px; margin-bottom: 30px; border-bottom: 1px solid var(--border-steel); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;} | |
| h1, h2, h3 { font-weight: 600; color: var(--text-light); margin-bottom: 15px; } | |
| h1 { font-size: 1.8rem; } | |
| h2 { font-size: 1.5rem; margin-top: 30px; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid var(--border-steel); padding-bottom: 10px; } | |
| h3 { font-size: 1.2rem; margin-top: 20px; margin-bottom: 10px; } | |
| .section { margin-bottom: 30px; padding: 25px; background-color: var(--bg-steel-mid); border: 1px solid var(--border-steel); border-radius: 12px; } | |
| form { margin-bottom: 20px; } | |
| label { font-weight: 600; margin-top: 15px; display: block; color: var(--text-steel); font-size: 0.9rem;} | |
| input[type="text"], input[type="number"], input[type="search"], textarea, select { width: 100%; padding: 12px; margin-top: 8px; border: 1px solid var(--border-steel); border-radius: 8px; font-size: 1rem; box-sizing: border-box; transition: all 0.2s ease; background-color: var(--bg-steel-dark); color: var(--text-light); } | |
| input:focus, textarea:focus, select:focus { border-color: var(--accent-red); outline: none; box-shadow: 0 0 0 3px rgba(230, 57, 70, 0.2); } | |
| textarea { min-height: 100px; resize: vertical; } | |
| input[type="file"] { padding: 10px; background-color: var(--bg-steel-dark); cursor: pointer; border-radius: 8px; } | |
| input[type="file"]::file-selector-button { padding: 8px 15px; border-radius: 6px; background-color: var(--border-steel); border: none; cursor: pointer; margin-right: 12px; color: var(--text-light); font-weight: 600; } | |
| input[type="checkbox"] { width: 18px; height: 18px; margin-right: 10px; vertical-align: middle; accent-color: var(--accent-red); } | |
| label.inline-label { display: inline-block; margin-top: 10px; font-weight: normal; } | |
| button, .button { padding: 12px 22px; border: none; border-radius: 8px; background-color: var(--border-steel); color: var(--text-light); font-weight: 600; cursor: pointer; transition: all 0.2s ease; margin-top: 15px; font-size: 1rem; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; line-height: 1.2;} | |
| button:hover, .button:hover { background-color: #383e45; transform: translateY(-2px); } | |
| button:active, .button:active { transform: scale(0.98); } | |
| button[type="submit"] { background-color: var(--accent-red); color: #FFFFFF; } | |
| button[type="submit"]:hover { background-color: var(--accent-red-hover); } | |
| .delete-button { background-color: var(--accent-red); color: #FFFFFF;} | |
| .delete-button:hover { background-color: var(--accent-red-hover); } | |
| .item-list { display: grid; gap: 20px; } | |
| .item { background: var(--bg-steel-dark); padding: 20px; border-radius: 12px; border: 1px solid var(--border-steel); } | |
| .item p { margin: 5px 0; font-size: 0.9rem; color: var(--text-steel); } | |
| .item strong { color: var(--text-light); } | |
| .item .description { font-size: 0.85rem; color: #888888; max-height: 60px; overflow: hidden; text-overflow: ellipsis; } | |
| .item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; } | |
| .edit-form-container { margin-top: 20px; padding: 25px; background: #0D1117; border: 1px dashed var(--border-steel); border-radius: 12px; display: none; } | |
| details { background-color: var(--bg-steel-mid); border: 1px solid var(--border-steel); border-radius: 12px; margin-bottom: 20px; } | |
| details > summary { cursor: pointer; font-weight: 600; color: var(--text-light); display: block; padding: 15px 20px; list-style: none; position: relative; } | |
| details[open] > summary { border-bottom: 1px solid var(--border-steel); } | |
| 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: var(--text-steel); } | |
| details[open] > summary::after { transform: translateY(-50%) rotate(180deg); } | |
| 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: var(--accent-red); padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; } | |
| .remove-color-btn:hover { background-color: var(--accent-red-hover); } | |
| .add-color-btn { background-color: var(--border-steel); } | |
| .photo-preview img, .video-preview video { width: 80px; height: 80px; border-radius: 8px; margin: 5px; border: 1px solid var(--border-steel); object-fit: cover;} | |
| .sync-buttons { display: flex; gap: 15px; margin-bottom: 20px; flex-wrap: wrap; } | |
| .download-hf-button { background-color: var(--accent-blue); } | |
| .download-hf-button:hover { background-color: #2980b9;} | |
| .flex-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 25px; } | |
| .message { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-size: 1rem; color: #fff; font-weight: 600; } | |
| .message.success { background-color: var(--accent-green); } | |
| .message.error { background-color: var(--accent-red); } | |
| .message.warning { background-color: #f39c12; } | |
| .status-indicator { display: inline-block; padding: 4px 10px; border-radius: 12px; font-size: 0.8rem; font-weight: 600; margin-left: 10px; vertical-align: middle; } | |
| .status-indicator.in-stock { background-color: var(--accent-green); color: #fff; } | |
| .status-indicator.out-of-stock { background-color: var(--accent-red); color: #fff; } | |
| .status-indicator.on-order { background-color: var(--accent-orange); color: #fff; } | |
| .status-indicator.top-product { background-color: var(--accent-blue); color: #FFFFFF; } | |
| .discount-info { color: var(--accent-red); font-weight: bold; } | |
| .header .button { background-color: var(--accent-red); } | |
| .progress-container { margin-top: 15px; width: 100%; background-color: var(--bg-amulet-black); border-radius: 8px; border: 1px solid var(--border-steel); padding: 4px; } | |
| .progress-bar { height: 24px; width: 0%; background: linear-gradient(90deg, var(--accent-red) 0%, var(--accent-blue) 100%); border-radius: 4px; text-align: center; line-height: 24px; color: white; transition: width 0.3s ease; } | |
| .progress-text { position: absolute; width: 100%; left: 0; text-align: center; line-height: 24px; color: white; font-weight: bold; text-shadow: 1px 1px 2px rgba(0,0,0,0.5); } | |
| .pagination-controls { text-align: center; margin-top: 30px; display: flex; justify-content: center; align-items: center; gap: 10px; } | |
| .pagination-controls .button { margin-top: 0; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <h1><i class="fas fa-tools"></i> {{ get_translation('admin_panel_h1') }}</h1> | |
| <a href="{{ url_for('catalog') }}" class="button"><i class="fas fa-store"></i> {{ get_translation('go_to_catalog') }}</a> | |
| </div> | |
| {% with messages = get_flashed_messages(with_categories=true) %} | |
| {% if messages %} | |
| {% for category, message in messages %} | |
| <div class="message {{ category }}">{{ message }}</div> | |
| {% endfor %} | |
| {% endif %} | |
| {% endwith %} | |
| <div class="section"> | |
| <h2><i class="fas fa-cog"></i> {{ get_translation('admin_settings_title') }}</h2> | |
| <form method="POST" action="{{ url_for('admin_actions') }}"> | |
| <input type="hidden" name="action" value="update_settings"> | |
| <label>{{ get_translation('admin_prices_visibility_label') }}</label> | |
| <div style="margin-top: 15px;"> | |
| <input type="checkbox" id="prices_enabled" name="prices_enabled" {% if app_config.prices_enabled %}checked{% endif %}> | |
| <label for="prices_enabled" class="inline-label">{{ get_translation('admin_prices_enabled_checkbox_label') }}</label> | |
| </div> | |
| <button type="submit"><i class="fas fa-save"></i> {{ get_translation('save_settings_button') }}</button> | |
| </form> | |
| </div> | |
| <div class="section"> | |
| <h2><i class="fas fa-sync-alt"></i> {{ get_translation('sync_with_dc') }}</h2> | |
| <div class="sync-buttons"> | |
| <form method="POST" action="{{ url_for('force_upload') }}" style="display: inline;" onsubmit="return confirm('{{ get_translation('confirm_force_upload') }}');"> | |
| <button type="submit" class="button" title="{{ get_translation('upload_db') }}"><i class="fas fa-upload"></i> {{ get_translation('upload_db') }}</button> | |
| </form> | |
| <form method="POST" action="{{ url_for('force_download') }}" style="display: inline;" onsubmit="return confirm('{{ get_translation('confirm_force_download') }}');"> | |
| <button type="submit" class="button download-hf-button" title="{{ get_translation('download_db') }}"><i class="fas fa-download"></i> {{ get_translation('download_db') }}</button> | |
| </form> | |
| </div> | |
| <p style="font-size: 0.85rem; color: var(--text-steel);">{{ get_translation('sync_info_text') }}</p> | |
| </div> | |
| <div class="flex-container"> | |
| <div class="section"> | |
| <h2><i class="fas fa-tags"></i> {{ get_translation('manage_categories') }}</h2> | |
| <details> | |
| <summary><i class="fas fa-plus-circle"></i> {{ get_translation('add_new_category') }}</summary> | |
| <div class="form-content"> | |
| <form method="POST" action="{{ url_for('admin_actions') }}"> | |
| <input type="hidden" name="action" value="add_category"> | |
| <label for="add_category_name">{{ get_translation('new_category_name_label') }}</label> | |
| <input type="text" id="add_category_name" name="category_name" required> | |
| <button type="submit"><i class="fas fa-plus"></i> {{ get_translation('add_button') }}</button> | |
| </form> | |
| </div> | |
| </details> | |
| <h3>{{ get_translation('existing_categories') }}</h3> | |
| {% if categories %} | |
| <div class="item-list"> | |
| {% for category in categories %} | |
| <div class="item" style="display: flex; justify-content: space-between; align-items: center;"> | |
| <span>{{ category.name }}</span> | |
| <form method="POST" action="{{ url_for('admin_actions') }}" style="margin: 0;" onsubmit="return confirm('{{ get_translation('confirm_delete_category', category_name=category.name) }}');"> | |
| <input type="hidden" name="action" value="delete_category"> | |
| <input type="hidden" name="category_id" value="{{ category.id }}"> | |
| <button type="submit" class="delete-button" style="padding: 5px 10px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>{{ get_translation('no_categories_yet') }}</p> | |
| {% endif %} | |
| </div> | |
| <div class="section"> | |
| <h2><i class="fas fa-sitemap"></i> {{ get_translation('manage_subcategories') }}</h2> | |
| <details> | |
| <summary><i class="fas fa-plus-circle"></i> {{ get_translation('add_new_subcategory') }}</summary> | |
| <div class="form-content"> | |
| <form method="POST" action="{{ url_for('admin_actions') }}"> | |
| <input type="hidden" name="action" value="add_subcategory"> | |
| <label for="add_subcategory_name">{{ get_translation('new_subcategory_name_label') }}</label> | |
| <input type="text" id="add_subcategory_name" name="subcategory_name" required> | |
| <label for="parent_category_id">{{ get_translation('parent_category_label') }}</label> | |
| <select id="parent_category_id" name="parent_category_id" required> | |
| <option value="">{{ get_translation('select_parent_category') }}</option> | |
| {% for category in categories %} | |
| <option value="{{ category.id }}">{{ category.name }}</option> | |
| {% endfor %} | |
| </select> | |
| <button type="submit"><i class="fas fa-plus"></i> {{ get_translation('add_button') }}</button> | |
| </form> | |
| </div> | |
| </details> | |
| <h3>{{ get_translation('existing_subcategories') }}</h3> | |
| {% if subcategories %} | |
| <div class="item-list"> | |
| {% for subcategory in subcategories %} | |
| <div class="item" style="display: flex; justify-content: space-between; align-items: center;"> | |
| <span>{{ subcategory.name }} <small style="color:var(--text-steel)">({{ subcategory.parent_name }})</small></span> | |
| <form method="POST" action="{{ url_for('admin_actions') }}" style="margin: 0;" onsubmit="return confirm('{{ get_translation('confirm_delete_subcategory', subcategory_name=subcategory.name) }}');"> | |
| <input type="hidden" name="action" value="delete_subcategory"> | |
| <input type="hidden" name="subcategory_id" value="{{ subcategory.id }}"> | |
| <button type="submit" class="delete-button" style="padding: 5px 10px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>{{ get_translation('no_subcategories_yet') }}</p> | |
| {% endif %} | |
| </div> | |
| <div class="section"> | |
| <h2><i class="fas fa-truck"></i> {{ get_translation('manage_suppliers') }}</h2> | |
| <details> | |
| <summary><i class="fas fa-plus-circle"></i> {{ get_translation('add_new_supplier') }}</summary> | |
| <div class="form-content"> | |
| <form method="POST" action="{{ url_for('admin_actions') }}"> | |
| <input type="hidden" name="action" value="add_supplier"> | |
| <label for="add_supplier_name">{{ get_translation('new_supplier_name_label') }}</label> | |
| <input type="text" id="add_supplier_name" name="supplier_name" required> | |
| <button type="submit"><i class="fas fa-plus"></i> {{ get_translation('add_button') }}</button> | |
| </form> | |
| </div> | |
| </details> | |
| <h3>{{ get_translation('existing_suppliers') }}</h3> | |
| {% if suppliers %} | |
| <div class="item-list"> | |
| {% for supplier_name in suppliers %} | |
| <div class="item" style="display: flex; justify-content: space-between; align-items: center;"> | |
| <span>{{ supplier_name }}</span> | |
| <form method="POST" action="{{ url_for('admin_actions') }}" style="margin: 0;" onsubmit="return confirm('{{ get_translation('confirm_delete_supplier', supplier_name=supplier_name) }}');"> | |
| <input type="hidden" name="action" value="delete_supplier"> | |
| <input type="hidden" name="supplier_name" value="{{ supplier_name }}"> | |
| <button type="submit" class="delete-button" style="padding: 5px 10px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p>{{ get_translation('no_suppliers_yet') }}</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <div class="section"> | |
| <h2><i class="fas fa-box-open"></i> {{ get_translation('manage_products') }}</h2> | |
| <details> | |
| <summary><i class="fas fa-plus-circle"></i> {{ get_translation('add_new_product') }}</summary> | |
| <div class="form-content"> | |
| <form id="add-product-form" method="POST" enctype="multipart/form-data"> | |
| <input type="hidden" name="action" value="add_product"> | |
| <label for="add_name">{{ get_translation('product_name_label') }}</label> | |
| <input type="text" id="add_name" name="name" required> | |
| <label for="add_price_kgs">{{ get_translation('product_price_kgs_label') }}</label> | |
| <input type="number" id="add_price_kgs" name="price_kgs" step="0.01" min="0"> | |
| <label for="add_discount_percent">{{ get_translation('product_discount_percent_label') }}</label> | |
| <input type="number" id="add_discount_percent" name="discount_percent" step="1" min="0" max="100" value="0"> | |
| <label for="add_description">{{ get_translation('product_description_label') }}</label> | |
| <textarea id="add_description" name="description" rows="4"></textarea> | |
| <label for="add_supplier">{{ get_translation('product_supplier_label') }}</label> | |
| <select id="add_supplier" name="supplier"> | |
| <option value="Без поставщика">{{ get_translation('no_supplier_option') }}</option> | |
| {% for supplier_name in suppliers %} | |
| <option value="{{ supplier_name }}">{{ supplier_name }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="add_category">{{ get_translation('product_category_label') }}</label> | |
| <select id="add_category" name="category_id" class="category-selector"> | |
| <option value="">{{ get_translation('no_category_option') }}</option> | |
| {% for category in categories %} | |
| <option value="{{ category.id }}">{{ category.name }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="add_subcategory_id">{{ get_translation('product_subcategory_label') }}</label> | |
| <select id="add_subcategory_id" name="subcategory_id" class="subcategory-selector"> | |
| <option value="">{{ get_translation('select_category_first') }}</option> | |
| </select> | |
| <label for="add_photos">{{ get_translation('photos_label') }}</label> | |
| <input type="file" id="add_photos" name="photos" accept="image/*" multiple> | |
| <label for="add_video">{{ get_translation('video_label') }}</label> | |
| <input type="file" id="add_video" name="video" accept="video/mp4,video/webm"> | |
| <label>{{ get_translation('colors_variants_label') }}</label> | |
| <div id="add-color-inputs"> | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" placeholder="{{ get_translation('color_placeholder_example') }}"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| </div> | |
| <button type="button" class="button add-color-btn" style="margin-top: 5px;" onclick="addColorInput('add-color-inputs')"><i class="fas fa-palette"></i> {{ get_translation('add_color_field_button') }}</button> | |
| <br> | |
| <div style="margin-top: 15px;"> | |
| <input type="checkbox" id="add_in_stock" name="in_stock" checked> | |
| <label for="add_in_stock" class="inline-label">{{ get_translation('in_stock_label') }}</label> | |
| </div> | |
| <div style="margin-top: 5px;"> | |
| <input type="checkbox" id="add_on_order" name="on_order"> | |
| <label for="add_on_order" class="inline-label">{{ get_translation('on_order_label') }}</label> | |
| </div> | |
| <div style="margin-top: 5px;"> | |
| <input type="checkbox" id="add_is_top" name="is_top"> | |
| <label for="add_is_top" class="inline-label">{{ get_translation('top_product_label') }}</label> | |
| </div> | |
| <br> | |
| <div class="progress-container" style="display:none;"> | |
| <div style="position:relative;"> | |
| <div class="progress-bar"></div> | |
| <span class="progress-text">0%</span> | |
| </div> | |
| </div> | |
| <button type="submit"><i class="fas fa-save"></i> {{ get_translation('add_product_button') }}</button> | |
| </form> | |
| </div> | |
| </details> | |
| <h3>{{ get_translation('product_list_title') }}</h3> | |
| <form method="GET" action="{{ url_for('admin') }}" class="search-form" style="margin-bottom: 20px; display: flex; gap: 10px; align-items:center;"> | |
| <input type="search" name="q" value="{{ search_query }}" placeholder="{{ get_translation('admin_search_placeholder') }}" style="flex-grow: 1; margin-top:0;"> | |
| <button type="submit" class="button" style="margin-top:0;"><i class="fas fa-search"></i> {{ get_translation('admin_search_button') }}</button> | |
| {% if search_query %} | |
| <a href="{{ url_for('admin') }}" class="button" style="margin-top:0; background-color: var(--accent-orange);">{{ get_translation('admin_reset_search_button') }}</a> | |
| {% endif %} | |
| </form> | |
| {% if products_with_info %} | |
| <div class="item-list" id="product-list-container"> | |
| {% for product_info in products_with_info %} | |
| <div class="item"> | |
| <div style="display: flex; gap: 20px; align-items: flex-start;"> | |
| <div class="photo-preview" style="flex-shrink: 0;"> | |
| {% if product_info.get('photos') %} | |
| <a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product_info['photos'][0] }}" target="_blank" title="{{ get_translation('view_first_photo_title') }}"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product_info['photos'][0] }}" alt="{{ get_translation('photo_alt') }}"> | |
| </a> | |
| {% else %} | |
| <img src="https://via.placeholder.com/80x80.png?text=N%2FA" alt="{{ get_translation('no_photo_alt') }}" style="opacity: 0.5;"> | |
| {% endif %} | |
| </div> | |
| <div style="flex-grow: 1;"> | |
| <h3 style="margin-top: 0; margin-bottom: 5px;"> | |
| {{ product_info['name'] }} | |
| {% if product_info.get('in_stock', True) %} | |
| <span class="status-indicator in-stock">{{ get_translation('status_in_stock') }}</span> | |
| {% elif product_info.get('on_order', False) %} | |
| <span class="status-indicator on-order">{{ get_translation('status_on_order') }}</span> | |
| {% else %} | |
| <span class="status-indicator out-of-stock">{{ get_translation('status_out_of_stock') }}</span> | |
| {% endif %} | |
| {% if product_info.get('is_top', False) %} | |
| <span class="status-indicator top-product"><i class="fas fa-star"></i> {{ get_translation('status_top_product') }}</span> | |
| {% endif %} | |
| </h3> | |
| <p><strong>{{ get_translation('supplier') }}:</strong> {{ product_info.supplier_name }}</p> | |
| <p><strong>{{ get_translation('category') }}:</strong> {{ product_info.category_name }}</p> | |
| <p><strong>{{ get_translation('subcategory') }}:</strong> {{ product_info.subcategory_name }}</p> | |
| <p><strong>{{ get_translation('price') }}:</strong> {% if product_info.price_kgs > 0 %} {{ "%.2f"|format(product_info.price_kgs) }} {{ currency_code }} {% else %} {{ get_translation('price_on_request') }} {% endif %}</p> | |
| {% if product_info.get('discount_percent', 0) > 0 %} | |
| <p><strong class="discount-info">{{ get_translation('discount_label_item') }} {{ product_info.discount_percent }}%</strong></p> | |
| {% endif %} | |
| <p class="description" title="{{ product_info.get('description', '') }}"><strong>{{ get_translation('description_label_item') }}:</strong> {{ product_info.get('description', get_translation('description_not_available'))[:150] }}{% if product_info.get('description', '')|length > 150 %}...{% endif %}</p> | |
| </div> | |
| </div> | |
| <div class="item-actions"> | |
| <button type="button" class="button" onclick="toggleEditForm('edit-form-{{ product_info.id }}')"><i class="fas fa-edit"></i> {{ get_translation('edit_button') }}</button> | |
| <form method="POST" action="{{ url_for('admin_actions') }}" style="margin:0;" onsubmit="return confirm('{{ get_translation('confirm_delete_product', product_name=product_info['name']) }}');"> | |
| <input type="hidden" name="action" value="delete_product"> | |
| <input type="hidden" name="product_id" value="{{ product_info.id }}"> | |
| <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> {{ get_translation('delete_button') }}</button> | |
| </form> | |
| </div> | |
| </div> | |
| <div id="edit-form-{{ product_info.id }}" class="edit-form-container"> | |
| <h4 style="color: var(--text-light);"><i class="fas fa-edit"></i> {{ get_translation('editing_product_title', product_name=product_info['name']) }}</h4> | |
| <form id="edit-product-form-{{ product_info.id }}" method="POST" enctype="multipart/form-data"> | |
| <input type="hidden" name="action" value="edit_product"> | |
| <input type="hidden" name="product_id" value="{{ product_info.id }}"> | |
| <label>{{ get_translation('product_name_edit_label') }}</label> | |
| <input type="text" name="name" value="{{ product_info['name'] }}" required> | |
| <label>{{ get_translation('product_price_kgs_edit_label') }}</label> | |
| <input type="number" name="price_kgs" step="0.01" min="0" value="{{ product_info.price_kgs }}"> | |
| <label>{{ get_translation('product_discount_percent_edit_label') }}</label> | |
| <input type="number" name="discount_percent" step="1" min="0" max="100" value="{{ product_info.get('discount_percent', 0) }}"> | |
| <label>{{ get_translation('product_description_edit_label') }}</label> | |
| <textarea name="description" rows="4">{{ product_info.get('description', '') }}</textarea> | |
| <label>{{ get_translation('product_supplier_edit_label') }}</label> | |
| <select name="supplier"> | |
| <option value="Без поставщика" {% if product_info.get('supplier', 'Без поставщика') == 'Без поставщика' %}selected{% endif %}>{{ get_translation('no_supplier_option') }}</option> | |
| {% for supplier_name in suppliers %} | |
| <option value="{{ supplier_name }}" {% if product_info.get('supplier') == supplier_name %}selected{% endif %}>{{ supplier_name }}</option> | |
| {% endfor %} | |
| </select> | |
| <label>{{ get_translation('product_category_edit_label') }}</label> | |
| <select name="category_id" class="category-selector"> | |
| <option value="">{{ get_translation('no_category_option') }}</option> | |
| {% for category in categories %} | |
| <option value="{{ category.id }}" {% if product_info.category_id == category.id %}selected{% endif %}>{{ category.name }}</option> | |
| {% endfor %} | |
| </select> | |
| <label>{{ get_translation('product_subcategory_edit_label') }}</label> | |
| <select name="subcategory_id" class="subcategory-selector" data-selected="{{ product_info.get('subcategory_id', '') }}"> | |
| <option value="">{{ get_translation('select_category_first') }}</option> | |
| </select> | |
| <label>{{ get_translation('replace_photos_label') }}</label> | |
| <input type="file" name="photos" accept="image/*" multiple> | |
| {% if product_info.get('photos') %} | |
| <p style="font-size: 0.85rem; margin-top: 5px;">{{ get_translation('current_photos_label') }}</p> | |
| <div class="photo-preview"> | |
| {% for photo in product_info['photos'] %} | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="{{ get_translation('photo_alt_indexed', loop_index=loop.index) }}"> | |
| {% endfor %} | |
| </div> | |
| {% endif %} | |
| <label>{{ get_translation('replace_video_label') }}</label> | |
| <input type="file" name="video" accept="video/mp4,video/webm"> | |
| {% if product_info.get('video_filename') %} | |
| <p style="font-size: 0.85rem; margin-top: 5px;">{{ get_translation('current_video_label') }}</p> | |
| <div class="video-preview"> | |
| <video preload="metadata"> | |
| <source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/videos/{{ product_info.video_filename }}" type="video/mp4"> | |
| </video> | |
| </div> | |
| {% endif %} | |
| <label>{{ get_translation('colors_variants_edit_label') }}</label> | |
| <div id="edit-color-inputs-{{ product_info.id }}"> | |
| {% set current_colors = product_info.get('colors', []) %} | |
| {% if current_colors and current_colors|select('ne', '')|list|length > 0 %} | |
| {% for color in current_colors %} | |
| {% if color.strip() %} | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" value="{{ color }}"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| {% endfor %} | |
| {% else %} | |
| <div class="color-input-group"> | |
| <input type="text" name="colors" placeholder="{{ get_translation('color_placeholder_generic') }}"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> | |
| </div> | |
| {% endif %} | |
| </div> | |
| <button type="button" class="button add-color-btn" style="margin-top: 5px;" onclick="addColorInput('edit-color-inputs-{{ product_info.id }}')"><i class="fas fa-palette"></i> {{ get_translation('add_color_field_edit_button') }}</button> | |
| <br> | |
| <div style="margin-top: 15px;"> | |
| <input type="checkbox" id="edit_in_stock_{{ product_info.id }}" name="in_stock" {% if product_info.get('in_stock', True) %}checked{% endif %}> | |
| <label for="edit_in_stock_{{ product_info.id }}" class="inline-label">{{ get_translation('in_stock_edit_label') }}</label> | |
| </div> | |
| <div style="margin-top: 5px;"> | |
| <input type="checkbox" id="edit_on_order_{{ product_info.id }}" name="on_order" {% if product_info.get('on_order', False) %}checked{% endif %}> | |
| <label for="edit_on_order_{{ product_info.id }}" class="inline-label">{{ get_translation('on_order_edit_label') }}</label> | |
| </div> | |
| <div style="margin-top: 5px;"> | |
| <input type="checkbox" id="edit_is_top_{{ product_info.id }}" name="is_top" {% if product_info.get('is_top', False) %}checked{% endif %}> | |
| <label for="edit_is_top_{{ product_info.id }}" class="inline-label">{{ get_translation('top_product_edit_label') }}</label> | |
| </div> | |
| <br> | |
| <div class="progress-container" style="display:none;"> | |
| <div style="position:relative;"> | |
| <div class="progress-bar"></div> | |
| <span class="progress-text">0%</span> | |
| </div> | |
| </div> | |
| <button type="submit"><i class="fas fa-save"></i> {{ get_translation('save_changes_button') }}</button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| {% if search_query %} | |
| <p>{{ get_translation('admin_no_products_found_for_query') }}</p> | |
| {% else %} | |
| <p>{{ get_translation('no_products_yet_admin') }}</p> | |
| {% endif %} | |
| {% endif %} | |
| {% if total_pages > 1 %} | |
| <div class="pagination-controls"> | |
| {% if current_page > 1 %} | |
| <a href="{{ url_for('admin', page=current_page - 1, q=search_query) }}" class="button">« Назад</a> | |
| {% endif %} | |
| <span>Страница {{ current_page }} из {{ total_pages }}</span> | |
| {% if current_page < total_pages %} | |
| <a href="{{ url_for('admin', page=current_page + 1, q=search_query) }}" class="button">Вперед »</a> | |
| {% endif %} | |
| </div> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <button id="save-all-changes-button" class="button" style="display: none; position: fixed; bottom: 30px; left: 50%; transform: translateX(-50%); z-index: 1000; background-color: var(--accent-green); box-shadow: 0 5px 20px rgba(37, 211, 102, 0.3);"><i class="fas fa-save"></i> <span>{{ get_translation('save_all_changes_button', count=0) }}</span></button> | |
| <script> | |
| const jsAdminTranslations = {{ js_translations|tojson }}; | |
| function _admin(key, params = {}) { | |
| let text = jsAdminTranslations[key] || `MISSING_JS_ADMIN_TRANSLATION: ${key}`; | |
| for (const pKey in params) { | |
| text = text.replace(new RegExp(`{${pKey}}`, 'g'), params[pKey]); | |
| } | |
| return text; | |
| } | |
| function toggleEditForm(formId) { | |
| const formContainer = document.getElementById(formId); | |
| if (formContainer) { | |
| formContainer.style.display = formContainer.style.display === 'none' || formContainer.style.display === '' ? 'block' : 'none'; | |
| } | |
| } | |
| function addColorInput(containerId) { | |
| const container = document.getElementById(containerId); | |
| if (container) { | |
| const newInputGroup = document.createElement('div'); | |
| newInputGroup.className = 'color-input-group'; | |
| newInputGroup.innerHTML = ` | |
| <input type="text" name="colors" placeholder="${_admin('js_new_color_variant_placeholder')}"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> | |
| `; | |
| container.appendChild(newInputGroup); | |
| const newInput = newInputGroup.querySelector('input[name="colors"]'); | |
| if (newInput) { | |
| newInput.focus(); | |
| } | |
| } | |
| } | |
| function removeColorInput(button) { | |
| const group = button.closest('.color-input-group'); | |
| if (group) { | |
| const container = group.parentNode; | |
| group.remove(); | |
| if (container && container.children.length === 0) { | |
| const placeholderGroup = document.createElement('div'); | |
| placeholderGroup.className = 'color-input-group'; | |
| let placeholderText = container.id.startsWith('add-color-inputs') ? {{ get_translation('color_placeholder_example')|tojson }} : {{ get_translation('color_placeholder_generic')|tojson }}; | |
| placeholderGroup.innerHTML = ` | |
| <input type="text" name="colors" placeholder="${placeholderText}"> | |
| <button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button> | |
| `; | |
| container.appendChild(placeholderGroup); | |
| } | |
| } else { | |
| console.warn("Could not find parent .color-input-group for remove button"); | |
| } | |
| } | |
| function handleFormSubmitWithProgress(form) { | |
| const submitButton = form.querySelector('button[type="submit"]'); | |
| const progressContainer = form.querySelector('.progress-container'); | |
| const progressBar = form.querySelector('.progress-bar'); | |
| const progressText = form.querySelector('.progress-text'); | |
| const formData = new FormData(form); | |
| if(submitButton) submitButton.disabled = true; | |
| if (progressContainer) progressContainer.style.display = 'block'; | |
| if (progressBar) progressBar.style.width = '0%'; | |
| if (progressText) progressText.textContent = '0%'; | |
| const xhr = new XMLHttpRequest(); | |
| xhr.upload.addEventListener('progress', (e) => { | |
| if (e.lengthComputable) { | |
| const percentComplete = Math.round((e.loaded / e.total) * 100); | |
| if (progressBar) progressBar.style.width = percentComplete + '%'; | |
| if (progressText) progressText.textContent = percentComplete + '%'; | |
| } | |
| }); | |
| xhr.addEventListener('load', () => { | |
| if (xhr.status >= 200 && xhr.status < 300) { | |
| if (progressBar) progressBar.style.width = '100%'; | |
| if (progressText) progressText.textContent = 'Завершено!'; | |
| window.location.reload(); | |
| } else { | |
| if (progressText) progressText.textContent = 'Ошибка!'; | |
| if (progressBar) progressBar.style.backgroundColor = 'var(--accent-red)'; | |
| try { | |
| const error = JSON.parse(xhr.responseText); | |
| alert('Ошибка сервера: ' + (error.error || xhr.statusText)); | |
| } catch (e) { | |
| alert('Произошла неизвестная ошибка при загрузке.'); | |
| } | |
| if (submitButton) submitButton.disabled = false; | |
| } | |
| }); | |
| xhr.addEventListener('error', () => { | |
| if (progressText) progressText.textContent = 'Ошибка сети!'; | |
| if (progressBar) progressBar.style.backgroundColor = 'var(--accent-red)'; | |
| alert('Ошибка сети при загрузке файлов.'); | |
| if (submitButton) submitButton.disabled = false; | |
| }); | |
| xhr.open('POST', '{{ url_for("admin_api") }}'); | |
| xhr.send(formData); | |
| } | |
| async function updateSubcategoryDropdown(categorySelector, subcategorySelector, selectedSubcategoryId = '') { | |
| const categoryId = categorySelector.value; | |
| subcategorySelector.innerHTML = `<option value="">${_admin('loading')}</option>`; | |
| subcategorySelector.disabled = true; | |
| if (!categoryId) { | |
| subcategorySelector.innerHTML = `<option value="">${_admin('select_category_first')}</option>`; | |
| subcategorySelector.disabled = false; | |
| return; | |
| } | |
| try { | |
| const response = await fetch(`/api/subcategories/${categoryId}`); | |
| if (!response.ok) throw new Error('Network response was not ok'); | |
| const subcategories = await response.json(); | |
| subcategorySelector.innerHTML = `<option value="">${_admin('no_subcategory_option')}</option>`; | |
| subcategories.forEach(sub => { | |
| const option = document.createElement('option'); | |
| option.value = sub.id; | |
| option.textContent = sub.name; | |
| if (sub.id === selectedSubcategoryId) { | |
| option.selected = true; | |
| } | |
| subcategorySelector.appendChild(option); | |
| }); | |
| subcategorySelector.disabled = false; | |
| } catch (error) { | |
| console.error('Failed to fetch subcategories:', error); | |
| subcategorySelector.innerHTML = `<option value="">Ошибка загрузки</option>`; | |
| subcategorySelector.disabled = false; | |
| } | |
| } | |
| document.addEventListener('DOMContentLoaded', () => { | |
| let changedForms = new Set(); | |
| const saveAllButton = document.getElementById('save-all-changes-button'); | |
| const saveAllButtonSpan = saveAllButton.querySelector('span'); | |
| function updateSaveAllButton() { | |
| const count = changedForms.size; | |
| if (count > 0) { | |
| saveAllButton.style.display = 'inline-flex'; | |
| let buttonText = _admin('save_all_changes_button', { count: count }); | |
| saveAllButtonSpan.textContent = buttonText; | |
| } else { | |
| saveAllButton.style.display = 'none'; | |
| } | |
| } | |
| function markFormAsChanged(formElement) { | |
| if (formElement && formElement.id) { | |
| changedForms.add(formElement.id); | |
| updateSaveAllButton(); | |
| } | |
| } | |
| function submitFormForMultiSave(form) { | |
| return new Promise((resolve) => { | |
| const formData = new FormData(form); | |
| const xhr = new XMLHttpRequest(); | |
| xhr.open('POST', '{{ url_for("admin_api") }}'); | |
| xhr.onload = () => { | |
| if (xhr.status >= 200 && xhr.status < 400) { | |
| try { | |
| resolve(JSON.parse(xhr.responseText)); | |
| } catch (e) { | |
| resolve({ success: false, error: 'Failed to parse response' }); | |
| } | |
| } else { | |
| try { | |
| resolve(JSON.parse(xhr.responseText)); | |
| } catch(e) { | |
| resolve({ success: false, error: `Server returned status ${xhr.status}` }); | |
| } | |
| } | |
| }; | |
| xhr.onerror = () => { | |
| resolve({ success: false, error: 'Network error' }); | |
| }; | |
| xhr.send(formData); | |
| }); | |
| } | |
| async function handleSaveAll() { | |
| saveAllButton.disabled = true; | |
| saveAllButtonSpan.textContent = _admin('loading'); | |
| const formsToSubmit = Array.from(changedForms).map(id => document.getElementById(id)); | |
| let successCount = 0; | |
| let errorCount = 0; | |
| const errorMessages = []; | |
| for (const form of formsToSubmit) { | |
| const productName = form.querySelector('input[name="name"]').value; | |
| const response = await submitFormForMultiSave(form); | |
| if (response.success) { | |
| successCount++; | |
| changedForms.delete(form.id); | |
| } else { | |
| errorCount++; | |
| errorMessages.push(`- ${productName}: ${response.error || 'Unknown error'}`); | |
| } | |
| } | |
| if (errorCount === 0) { | |
| alert(`${successCount} товаров успешно обновлено! Страница будет перезагружена.`); | |
| window.location.reload(); | |
| } else { | |
| alert(`Завершено с ошибками:\\nУспешно: ${successCount}\\nОшибки: ${errorCount}\\n\\n${errorMessages.join('\\n')}`); | |
| saveAllButton.disabled = false; | |
| updateSaveAllButton(); | |
| } | |
| } | |
| saveAllButton.addEventListener('click', handleSaveAll); | |
| document.querySelectorAll('form[id^="edit-product-form-"]').forEach(form => { | |
| form.addEventListener('input', () => markFormAsChanged(form)); | |
| form.addEventListener('change', () => markFormAsChanged(form)); | |
| const individualSubmitButton = form.querySelector('button[type="submit"]'); | |
| if (individualSubmitButton) { | |
| individualSubmitButton.addEventListener('click', (e) => { | |
| e.preventDefault(); | |
| handleFormSubmitWithProgress(form); | |
| }); | |
| } | |
| }); | |
| document.getElementById('add-product-form')?.addEventListener('submit', (e) => { | |
| e.preventDefault(); | |
| handleFormSubmitWithProgress(e.target); | |
| }); | |
| document.querySelectorAll('.category-selector').forEach(catSelector => { | |
| const formOrItem = catSelector.closest('form, .item'); | |
| const subcatSelector = formOrItem.querySelector('.subcategory-selector'); | |
| const selectedSubId = subcatSelector ? (subcatSelector.dataset.selected || '') : ''; | |
| catSelector.addEventListener('change', () => { | |
| if (subcatSelector) updateSubcategoryDropdown(catSelector, subcatSelector); | |
| }); | |
| // Initial population for edit forms or on page load for add form if category is pre-selected | |
| if (catSelector.value && subcatSelector) { | |
| updateSubcategoryDropdown(catSelector, subcatSelector, selectedSubId); | |
| } | |
| }); | |
| function setupCheckboxExclusivity() { | |
| const productContainers = document.querySelectorAll('form[id$="-product-form"], form[id^="edit-product-form-"]'); | |
| productContainers.forEach(container => { | |
| const inStockCheckbox = container.querySelector('input[name="in_stock"]'); | |
| const onOrderCheckbox = container.querySelector('input[name="on_order"]'); | |
| if (inStockCheckbox && onOrderCheckbox) { | |
| inStockCheckbox.addEventListener('change', () => { | |
| if (inStockCheckbox.checked) { | |
| onOrderCheckbox.checked = false; | |
| } | |
| }); | |
| onOrderCheckbox.addEventListener('change', () => { | |
| if (onOrderCheckbox.checked) { | |
| inStockCheckbox.checked = false; | |
| } | |
| }); | |
| } | |
| }); | |
| } | |
| setupCheckboxExclusivity(); | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| def catalog(): | |
| data = get_data() | |
| all_products_raw = data.get('products', []) | |
| categories_raw = data.get('categories', []) | |
| subcategories_raw = data.get('subcategories', []) | |
| suppliers_orig = sorted(list(set(p['supplier'] for p in all_products_raw if 'supplier' in p))) | |
| app_config = data.get('config', {'prices_enabled': True}) | |
| cache = data.get('_cache', {}) | |
| subcategories_by_id = cache.get('subcategories_by_id', {}) | |
| categories_for_template = [] | |
| for cat in categories_raw: | |
| cat_copy = cat.copy() | |
| cat_copy['subcategories'] = sorted([sub for sub in subcategories_raw if sub.get('parent_id') == cat['id']], key=lambda x: x['name']) | |
| categories_for_template.append(cat_copy) | |
| categories_for_template.sort(key=lambda x: x['name']) | |
| products_enriched = [] | |
| for prod in all_products_raw: | |
| enriched_prod = get_full_product_info(prod, data) | |
| products_enriched.append(enriched_prod) | |
| products_to_display = [p for p in products_enriched if p.get('in_stock', True) or p.get('on_order', False)] | |
| products_sorted = sorted(products_to_display, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower())) | |
| return render_template_string( | |
| CATALOG_TEMPLATE, | |
| products=products_sorted, | |
| categories=categories_for_template, | |
| suppliers=suppliers_orig, | |
| repo_id=REPO_ID, | |
| currency_code=CURRENCY_CODE, | |
| app_config=app_config | |
| ) | |
| def product_detail(index): | |
| data = get_data() | |
| all_products = data.get('products', []) | |
| app_config = data.get('config', {'prices_enabled': True}) | |
| products_to_display = [p for p in all_products if p.get('in_stock', True) or p.get('on_order', False)] | |
| products_sorted = sorted(products_to_display, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower())) | |
| try: | |
| product = products_sorted[index] | |
| product_info = get_full_product_info(product, data) | |
| except IndexError: | |
| logging.warning(f"Attempted access to non-existent or out-of-stock product with index {index}") | |
| return get_translation('error_product_not_found'), 404 | |
| return render_template_string( | |
| PRODUCT_DETAIL_TEMPLATE, | |
| product_info=product_info, | |
| repo_id=REPO_ID, | |
| currency_code=CURRENCY_CODE, | |
| app_config=app_config | |
| ) | |
| def create_order(): | |
| order_data = request.get_json() | |
| current_data_full = get_data() | |
| app_config = current_data_full.get('config', {'prices_enabled': True}) | |
| prices_currently_enabled = app_config.get('prices_enabled', True) | |
| if not order_data or 'cart' not in order_data or not order_data['cart']: | |
| logging.warning("Create order request missing cart data or cart is empty.") | |
| return jsonify({"error": get_translation('cart_empty_for_order')}), 400 | |
| cart_items = order_data['cart'] | |
| total_price_kgs = 0 | |
| processed_cart = [] | |
| for item in cart_items: | |
| if not all(k in item for k in ('name', 'price_kgs', 'quantity')): | |
| logging.error(f"Invalid cart item structure received: {item}") | |
| return jsonify({"error": "Invalid cart item format."}), 400 | |
| try: | |
| price_kgs_in_cart = float(item['price_kgs']) | |
| original_price_kgs = float(item.get('original_price_kgs', price_kgs_in_cart)) | |
| quantity = int(item['quantity']) | |
| if quantity <= 0: | |
| raise ValueError("Invalid quantity") | |
| # If prices are enabled OR the price is positive, calculate total | |
| if prices_currently_enabled and price_kgs_in_cart > 0: | |
| total_price_kgs += price_kgs_in_cart * quantity | |
| processed_cart.append({ | |
| "name": item['name'], | |
| "price_kgs_at_order": round(price_kgs_in_cart, 2), | |
| "original_price_kgs_at_order": round(original_price_kgs, 2), | |
| "discount_percent_at_order": int(item.get('discount_percent', 0)), | |
| "quantity": quantity, | |
| "color": item.get('color', 'N/A'), | |
| "photo": item.get('photo'), | |
| "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item['photo']}" if item.get('photo') else "https://via.placeholder.com/60x60.png?text=N%2FA" | |
| }) | |
| except (ValueError, TypeError) as e: | |
| logging.error(f"Invalid price/quantity in cart item: {item}. Error: {e}") | |
| return jsonify({"error": "Invalid price or quantity in item."}), 400 | |
| order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}" | |
| order_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
| new_order = { | |
| "id": order_id, | |
| "created_at": order_timestamp, | |
| "cart": processed_cart, | |
| "total_price_kgs": round(total_price_kgs, 2) if prices_currently_enabled else 0, | |
| "prices_were_enabled_at_order": prices_currently_enabled, | |
| "user_info": None, | |
| "status": "new" | |
| } | |
| try: | |
| data = get_data() | |
| if 'orders' not in data or not isinstance(data.get('orders'), dict): | |
| data['orders'] = {} | |
| data['orders'][order_id] = new_order | |
| update_and_save_data(data) | |
| logging.info(f"Order {order_id} created successfully. Prices enabled at creation: {prices_currently_enabled}") | |
| return jsonify({"order_id": order_id}), 201 | |
| except Exception as e: | |
| logging.error(f"Failed to save order {order_id}: {e}", exc_info=True) | |
| return jsonify({"error": "Server error while saving order."}), 500 | |
| def view_order(order_id): | |
| data = get_data() | |
| order = data.get('orders', {}).get(order_id) | |
| app_config = data.get('config', {'prices_enabled': True}) | |
| if order: | |
| logging.info(f"Displaying order {order_id}") | |
| else: | |
| logging.warning(f"Order {order_id} not found.") | |
| return render_template_string(ORDER_TEMPLATE, | |
| order=order, | |
| repo_id=REPO_ID, | |
| currency_code=CURRENCY_CODE, | |
| app_config=app_config) | |
| def admin(): | |
| page = request.args.get('page', 1, type=int) | |
| search_query = request.args.get('q', '').strip() | |
| data = get_data() | |
| all_products = data.get('products', []) | |
| categories = sorted(data.get('categories', []), key=lambda c: c['name']) | |
| subcategories_raw = data.get('subcategories', []) | |
| suppliers = sorted(data.get('suppliers', [])) | |
| current_app_config = data.get('config', {'prices_enabled': True}) | |
| cache = data.get('_cache', {}) | |
| categories_by_id = cache.get('categories_by_id', {}) | |
| all_products_with_info = [] | |
| for p in sorted(all_products, key=lambda p: p.get('name', '').lower()): | |
| full_info = get_full_product_info(p, data) | |
| all_products_with_info.append(full_info) | |
| subcategories_with_parent = [] | |
| for subcat in sorted(subcategories_raw, key=lambda s: s['name']): | |
| subcat_info = subcat.copy() | |
| parent_cat = categories_by_id.get(subcat.get('parent_id')) | |
| subcat_info['parent_name'] = parent_cat['name'] if parent_cat else 'N/A' | |
| subcategories_with_parent.append(subcat_info) | |
| filtered_products = all_products_with_info | |
| if search_query: | |
| filtered_products = [ | |
| p for p in all_products_with_info | |
| if search_query.lower() in p.get('name', '').lower() or \ | |
| search_query.lower() in p.get('description', '').lower() | |
| ] | |
| total_products = len(filtered_products) | |
| total_pages = ceil(total_products / ADMIN_PRODUCTS_PER_PAGE) | |
| start_index = (page - 1) * ADMIN_PRODUCTS_PER_PAGE | |
| end_index = start_index + ADMIN_PRODUCTS_PER_PAGE | |
| paginated_products = filtered_products[start_index:end_index] | |
| return render_template_string( | |
| ADMIN_TEMPLATE, | |
| products_with_info=paginated_products, | |
| categories=categories, | |
| subcategories=subcategories_with_parent, | |
| suppliers=suppliers, | |
| repo_id=REPO_ID, | |
| currency_code=CURRENCY_CODE, | |
| app_config=current_app_config, | |
| current_page=page, | |
| total_pages=total_pages, | |
| search_query=search_query | |
| ) | |
| def api_get_subcategories(category_id): | |
| data = get_data() | |
| subcategories = [ | |
| sub for sub in data.get('subcategories', []) | |
| if sub.get('parent_id') == category_id | |
| ] | |
| return jsonify(sorted(subcategories, key=lambda s: s['name'])) | |
| def admin_api(): | |
| data = get_data() | |
| products = data.get('products', []) | |
| categories = data.get('categories', []) | |
| suppliers = data.get('suppliers', []) | |
| action = request.form.get('action') | |
| logging.info(f"Admin API action received: {action}") | |
| try: | |
| if action == 'add_product': | |
| name = request.form.get('name', '').strip() | |
| if not name: | |
| return jsonify({'error': get_translation('flash_product_name_price_required')}), 400 | |
| price_kgs_str = request.form.get('price_kgs', '0').replace(',', '.') | |
| if not price_kgs_str.strip(): price_kgs_str = '0' | |
| try: | |
| price_kgs = round(float(price_kgs_str), 2) | |
| if price_kgs < 0: price_kgs = 0 | |
| except ValueError: | |
| return jsonify({'error': get_translation('flash_invalid_price_format')}), 400 | |
| discount_percent_str = request.form.get('discount_percent', '0') | |
| try: | |
| discount_percent = int(discount_percent_str) | |
| if not (0 <= discount_percent <= 100): discount_percent = 0 | |
| except ValueError: | |
| discount_percent = 0 | |
| description = request.form.get('description', '').strip() | |
| subcategory_id = request.form.get('subcategory_id') or None | |
| supplier = request.form.get('supplier') | |
| colors = [c.strip() for c in request.form.getlist('colors') if c.strip()] | |
| in_stock = 'in_stock' in request.form | |
| on_order = 'on_order' in request.form | |
| is_top = 'is_top' in request.form | |
| if in_stock and on_order: # Ensure mutual exclusion | |
| on_order = False | |
| photos_list = [] | |
| video_filename = None | |
| photos_files = request.files.getlist('photos') | |
| video_file = request.files.get('video') | |
| if HF_TOKEN_WRITE: | |
| uploads_dir = 'uploads_temp' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| api = HfApi() | |
| photo_limit = 10 | |
| uploaded_count = 0 | |
| for photo_idx, photo in enumerate(photos_files): | |
| if uploaded_count >= photo_limit: break | |
| if photo and photo.filename: | |
| ext = os.path.splitext(photo.filename)[1].lower() | |
| if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']: continue | |
| safe_name = secure_filename(name.replace(' ', '_'))[:50] | |
| p_filename = f"{safe_name}_photo_{datetime.now().strftime('%Y%m%d%H%M%S%f')}_{photo_idx}{ext}" | |
| temp_path = os.path.join(uploads_dir, p_filename) | |
| photo.save(temp_path) | |
| api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{p_filename}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE) | |
| photos_list.append(p_filename) | |
| os.remove(temp_path) | |
| uploaded_count += 1 | |
| if video_file and video_file.filename: | |
| ext = os.path.splitext(video_file.filename)[1].lower() | |
| if ext in ['.mp4', '.webm']: | |
| safe_name = secure_filename(name.replace(' ', '_'))[:50] | |
| v_filename = f"{safe_name}_video_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}" | |
| temp_path = os.path.join(uploads_dir, v_filename) | |
| video_file.save(temp_path) | |
| api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"videos/{v_filename}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE) | |
| video_filename = v_filename | |
| os.remove(temp_path) | |
| try: | |
| if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): | |
| os.rmdir(uploads_dir) | |
| except OSError: pass | |
| new_product = { | |
| 'id': str(uuid.uuid4()), | |
| 'name': name, 'price_kgs': price_kgs, 'discount_percent': discount_percent, | |
| 'description': description, | |
| 'subcategory_id': subcategory_id, | |
| 'supplier': supplier if supplier in suppliers or supplier == 'Без поставщика' else 'Без поставщика', | |
| 'photos': photos_list, 'video_filename': video_filename, 'colors': colors, | |
| 'in_stock': in_stock, 'on_order': on_order, 'is_top': is_top | |
| } | |
| products.append(new_product) | |
| data['products'] = products | |
| update_and_save_data(data) | |
| return jsonify({'success': True, 'message': get_translation('flash_product_added_success', product_name=name)}) | |
| elif action == 'edit_product': | |
| product_id = request.form.get('product_id') | |
| if not product_id: | |
| return jsonify({'error': get_translation('flash_edit_error_no_id')}), 400 | |
| product_to_edit = next((p for p in products if p.get('id') == product_id), None) | |
| if not product_to_edit: | |
| return jsonify({'error': get_translation('flash_edit_error_not_found', product_id=product_id)}), 404 | |
| product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip() | |
| price_kgs_str = request.form.get('price_kgs') | |
| if price_kgs_str is not None: | |
| price_kgs_str = price_kgs_str.replace(',', '.') | |
| if not price_kgs_str.strip(): price_kgs_str = '0' | |
| try: | |
| price_kgs = round(float(price_kgs_str), 2) | |
| if price_kgs < 0: price_kgs = 0 | |
| product_to_edit['price_kgs'] = price_kgs | |
| except ValueError: | |
| logging.warning(get_translation('flash_invalid_price_format_edit_warning', product_name=product_to_edit['name'])) | |
| discount_percent_str = request.form.get('discount_percent', str(product_to_edit.get('discount_percent',0))) | |
| try: | |
| discount_percent = int(discount_percent_str) | |
| if not (0 <= discount_percent <= 100): discount_percent = product_to_edit.get('discount_percent', 0) | |
| product_to_edit['discount_percent'] = discount_percent | |
| except ValueError: pass | |
| product_to_edit['description'] = request.form.get('description', product_to_edit.get('description', '')).strip() | |
| product_to_edit['subcategory_id'] = request.form.get('subcategory_id') or None | |
| supplier = request.form.get('supplier') | |
| product_to_edit['supplier'] = supplier if supplier in suppliers or supplier == 'Без поставщика' else 'Без поставщика' | |
| product_to_edit['colors'] = [c.strip() for c in request.form.getlist('colors') if c.strip()] | |
| in_stock_new = 'in_stock' in request.form | |
| on_order_new = 'on_order' in request.form | |
| if in_stock_new and on_order_new: | |
| product_to_edit['in_stock'] = True | |
| product_to_edit['on_order'] = False | |
| else: | |
| product_to_edit['in_stock'] = in_stock_new | |
| product_to_edit['on_order'] = on_order_new | |
| product_to_edit['is_top'] = 'is_top' in request.form | |
| photos_files = request.files.getlist('photos') | |
| video_file = request.files.get('video') | |
| if photos_files and any(f.filename for f in photos_files) and HF_TOKEN_WRITE: | |
| uploads_dir = 'uploads_temp' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| api = HfApi() | |
| new_photos_list = [] | |
| photo_limit = 10 | |
| uploaded_count = 0 | |
| for photo_idx, photo in enumerate(photos_files): | |
| if uploaded_count >= photo_limit: break | |
| if photo and photo.filename: | |
| ext = os.path.splitext(photo.filename)[1].lower() | |
| if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']: continue | |
| safe_name = secure_filename(product_to_edit['name'].replace(' ', '_'))[:50] | |
| p_filename = f"{safe_name}_photo_{datetime.now().strftime('%Y%m%d%H%M%S%f')}_{photo_idx}{ext}" | |
| temp_path = os.path.join(uploads_dir, p_filename) | |
| photo.save(temp_path) | |
| api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{p_filename}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE) | |
| new_photos_list.append(p_filename) | |
| os.remove(temp_path) | |
| uploaded_count += 1 | |
| if new_photos_list: | |
| old_photos = product_to_edit.get('photos', []) | |
| if old_photos: | |
| for p in old_photos: | |
| try: | |
| api.delete_file(repo_id=REPO_ID, path_in_repo=f"photos/{p}", repo_type="dataset", token=HF_TOKEN_WRITE) | |
| except HfHubHTTPError as e: | |
| if e.response.status_code != 404: pass | |
| else: raise e | |
| product_to_edit['photos'] = new_photos_list | |
| try: | |
| if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): os.rmdir(uploads_dir) | |
| except OSError: pass | |
| if video_file and video_file.filename and HF_TOKEN_WRITE: | |
| uploads_dir = 'uploads_temp' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| api = HfApi() | |
| ext = os.path.splitext(video_file.filename)[1].lower() | |
| if ext in ['.mp4', '.webm']: | |
| old_video = product_to_edit.get('video_filename') | |
| if old_video: | |
| try: | |
| api.delete_file(repo_id=REPO_ID, path_in_repo=f"videos/{old_video}", repo_type="dataset", token=HF_TOKEN_WRITE) | |
| except HfHubHTTPError as e: | |
| if e.response.status_code != 404: pass | |
| else: raise e | |
| safe_name = secure_filename(product_to_edit['name'].replace(' ', '_'))[:50] | |
| v_filename = f"{safe_name}_video_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}" | |
| temp_path = os.path.join(uploads_dir, v_filename) | |
| video_file.save(temp_path) | |
| api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"videos/{v_filename}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE) | |
| product_to_edit['video_filename'] = v_filename | |
| os.remove(temp_path) | |
| try: | |
| if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): os.rmdir(uploads_dir) | |
| except OSError: pass | |
| data['products'] = products | |
| update_and_save_data(data) | |
| return jsonify({'success': True, 'message': get_translation('flash_product_updated_success', product_name=product_to_edit['name'])}) | |
| else: | |
| return jsonify({'error': get_translation('flash_unknown_action', action=action)}), 400 | |
| except Exception as e: | |
| logging.error(f"An internal error occurred while performing action '{action}': {e}", exc_info=True) | |
| return jsonify({'error': get_translation('flash_internal_error', action=action)}), 500 | |
| def admin_actions(): | |
| data = get_data() | |
| products = data.get('products', []) | |
| categories = data.get('categories', []) | |
| subcategories = data.get('subcategories', []) | |
| suppliers = data.get('suppliers', []) | |
| action = request.form.get('action') | |
| logging.info(f"Admin action received via form: {action}") | |
| try: | |
| if action == 'update_settings': | |
| prices_enabled_form = 'prices_enabled' in request.form | |
| data['config']['prices_enabled'] = prices_enabled_form | |
| update_and_save_data(data) | |
| flash(get_translation('flash_settings_updated'), 'success') | |
| elif action == 'add_category': | |
| category_name = request.form.get('category_name', '').strip() | |
| if category_name and not any(c['name'].lower() == category_name.lower() for c in categories): | |
| new_cat = {'id': str(uuid.uuid4()), 'name': category_name} | |
| categories.append(new_cat) | |
| data['categories'] = categories | |
| update_and_save_data(data) | |
| flash(get_translation('flash_category_added_success', category_name=category_name), 'success') | |
| elif not category_name: | |
| flash(get_translation('flash_category_name_empty'), 'error') | |
| else: | |
| flash(get_translation('flash_category_already_exists', category_name=category_name), 'error') | |
| elif action == 'delete_category': | |
| category_id_to_delete = request.form.get('category_id') | |
| category_to_delete = next((c for c in categories if c.get('id') == category_id_to_delete), None) | |
| if category_to_delete: | |
| data['categories'] = [c for c in categories if c.get('id') != category_id_to_delete] | |
| subs_to_delete = {s['id'] for s in subcategories if s.get('parent_id') == category_id_to_delete} | |
| data['subcategories'] = [s for s in subcategories if s.get('parent_id') != category_id_to_delete] | |
| for product in products: | |
| if product.get('subcategory_id') in subs_to_delete: | |
| product['subcategory_id'] = None | |
| data['products'] = products | |
| update_and_save_data(data) | |
| flash(get_translation('flash_category_delete_success', category_name=category_to_delete['name']), 'success') | |
| else: | |
| flash(get_translation('flash_category_delete_failed', category_name=category_id_to_delete), 'error') | |
| elif action == 'add_subcategory': | |
| subcategory_name = request.form.get('subcategory_name', '').strip() | |
| parent_id = request.form.get('parent_category_id') | |
| if not subcategory_name: | |
| flash(get_translation('flash_subcategory_name_empty'), 'error') | |
| elif not parent_id: | |
| flash(get_translation('flash_parent_category_not_selected'), 'error') | |
| elif any(s['name'].lower() == subcategory_name.lower() and s.get('parent_id') == parent_id for s in subcategories): | |
| flash(get_translation('flash_subcategory_already_exists', subcategory_name=subcategory_name), 'error') | |
| else: | |
| new_subcat = {'id': str(uuid.uuid4()), 'name': subcategory_name, 'parent_id': parent_id} | |
| subcategories.append(new_subcat) | |
| data['subcategories'] = subcategories | |
| update_and_save_data(data) | |
| flash(get_translation('flash_subcategory_added_success', subcategory_name=subcategory_name), 'success') | |
| elif action == 'delete_subcategory': | |
| subcategory_id_to_delete = request.form.get('subcategory_id') | |
| subcategory_to_delete = next((s for s in subcategories if s.get('id') == subcategory_id_to_delete), None) | |
| if subcategory_to_delete: | |
| data['subcategories'] = [s for s in subcategories if s.get('id') != subcategory_id_to_delete] | |
| for product in products: | |
| if product.get('subcategory_id') == subcategory_id_to_delete: | |
| product['subcategory_id'] = None | |
| data['products'] = products | |
| update_and_save_data(data) | |
| flash(get_translation('flash_subcategory_delete_success', subcategory_name=subcategory_to_delete['name']), 'success') | |
| else: | |
| flash(get_translation('flash_subcategory_delete_failed'), 'error') | |
| elif action == 'add_supplier': | |
| supplier_name = request.form.get('supplier_name', '').strip() | |
| if supplier_name and supplier_name not in suppliers: | |
| suppliers.append(supplier_name) | |
| data['suppliers'] = suppliers | |
| update_and_save_data(data) | |
| flash(get_translation('flash_supplier_added_success', supplier_name=supplier_name), 'success') | |
| elif not supplier_name: | |
| flash(get_translation('flash_supplier_name_empty'), 'error') | |
| else: | |
| flash(get_translation('flash_supplier_already_exists', supplier_name=supplier_name), 'error') | |
| elif action == 'delete_supplier': | |
| supplier_to_delete = request.form.get('supplier_name') | |
| if supplier_to_delete and supplier_to_delete in suppliers: | |
| suppliers.remove(supplier_to_delete) | |
| updated_count = 0 | |
| for product in products: | |
| if product.get('supplier') == supplier_to_delete: | |
| product['supplier'] = 'Без поставщика' | |
| updated_count += 1 | |
| data['suppliers'] = suppliers | |
| data['products'] = products | |
| update_and_save_data(data) | |
| flash(get_translation('flash_supplier_delete_success', supplier_name=supplier_to_delete, updated_count=updated_count), 'success') | |
| else: | |
| flash(get_translation('flash_supplier_delete_failed', supplier_name=supplier_to_delete), 'error') | |
| elif action == 'delete_product': | |
| product_id_to_delete = request.form.get('product_id') | |
| if not product_id_to_delete: | |
| flash(get_translation('flash_delete_error_no_id'), 'error') | |
| else: | |
| product_to_delete = next((p for p in products if p.get('id') == product_id_to_delete), None) | |
| if product_to_delete: | |
| product_name = product_to_delete.get('name', 'N/A') | |
| products.remove(product_to_delete) | |
| if HF_TOKEN_WRITE: | |
| api = HfApi() | |
| photos_to_delete = product_to_delete.get('photos', []) | |
| video_to_delete = product_to_delete.get('video_filename') | |
| for p_filename in photos_to_delete: | |
| try: | |
| api.delete_file(repo_id=REPO_ID, path_in_repo=f"photos/{p_filename}", repo_type="dataset", token=HF_TOKEN_WRITE) | |
| except HfHubHTTPError as e: | |
| if e.response.status_code != 404: pass | |
| else: raise e | |
| if video_to_delete: | |
| try: | |
| api.delete_file(repo_id=REPO_ID, path_in_repo=f"videos/{video_to_delete}", repo_type="dataset", token=HF_TOKEN_WRITE) | |
| except HfHubHTTPError as e: | |
| if e.response.status_code != 404: pass | |
| else: raise e | |
| data['products'] = products | |
| update_and_save_data(data) | |
| flash(get_translation('flash_product_deleted_success', product_name=product_name), 'success') | |
| else: | |
| flash(get_translation('flash_delete_error_not_found', product_id=product_id_to_delete), 'error') | |
| else: | |
| flash(get_translation('flash_unknown_action', action=action), 'warning') | |
| return redirect(url_for('admin')) | |
| except Exception as e: | |
| logging.error(f"An internal error occurred while performing action '{action}': {e}", exc_info=True) | |
| flash(get_translation('flash_internal_error', action=action), 'error') | |
| return redirect(url_for('admin')) | |
| def force_upload(): | |
| logging.info("Forcing upload to Hugging Face...") | |
| try: | |
| upload_db_to_hf() | |
| flash(get_translation('flash_data_uploaded_hf_success'), 'success') | |
| except Exception as e: | |
| logging.error(f"Error during forced upload: {e}", exc_info=True) | |
| flash(get_translation('flash_data_upload_hf_error', error=str(e)), 'error') | |
| return redirect(url_for('admin')) | |
| def force_download(): | |
| logging.info("Forcing download from Hugging Face...") | |
| try: | |
| if download_db_from_hf(): | |
| initialize_data() | |
| flash(get_translation('flash_data_downloaded_hf_success'), 'success') | |
| else: | |
| flash(get_translation('flash_data_download_hf_error_retries'), 'error') | |
| except Exception as e: | |
| logging.error(f"Error during forced download: {e}", exc_info=True) | |
| flash(get_translation('flash_data_download_hf_error', error=str(e)), 'error') | |
| return redirect(url_for('admin')) | |
| if __name__ == '__main__': | |
| logging.info("Application starting up. Performing initial data load/download...") | |
| initialize_data() | |
| if HF_TOKEN_WRITE: | |
| backup_thread = threading.Thread(target=periodic_backup, daemon=True) | |
| backup_thread.start() | |
| logging.info("Periodic backup thread started.") | |
| else: | |
| logging.warning("Periodic backup will NOT run (HF_TOKEN for writing not set).") | |
| port = int(os.environ.get('PORT', 7860)) | |
| logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}") | |
| app.run(debug=False, host='0.0.0.0', port=port) | |