diff --git "a/Soola.txt" "b/Soola.txt"
new file mode 100644--- /dev/null
+++ "b/Soola.txt"
@@ -0,0 +1,2300 @@
+
+from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify, session
+import json
+import os
+import logging
+import threading
+import time
+from datetime import datetime
+from huggingface_hub import HfApi, hf_hub_download
+from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
+from werkzeug.utils import secure_filename
+from dotenv import load_dotenv
+import requests
+import uuid
+
+load_dotenv()
+
+app = Flask(__name__)
+app.secret_key = os.getenv("FLASK_SECRET_KEY", 'your_unique_secret_key_integrity_shop_67890_no_login')
+DATA_FILE = 'data.json'
+
+SYNC_FILES = [DATA_FILE]
+
+REPO_ID = "Kgshop/integrity"
+HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
+HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
+
+CURRENCY_CODE = 'KGS'
+ADMIN_CURRENCY_CODE = 'USD'
+
+DOWNLOAD_RETRIES = 3
+DOWNLOAD_DELAY = 5
+
+logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
+
+translations = {
+ 'ru': {
+ 'site_name': 'Integrity',
+ 'catalog_title': 'Integrity - Каталог',
+ 'admin_title': 'Админ-панель - Integrity',
+ 'order_title': 'Заказ №{order_id} - Integrity',
+ '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': 'Категория:',
+ 'supplier': 'Поставщик:',
+ 'no_category': 'Без категории',
+ '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': 'Здравствуйте! Хочу подтвердить свой заказ на Integrity:',
+ 'whatsapp_order_number': 'Номер заказа:',
+ 'whatsapp_order_link': 'Ссылка на заказ:',
+ 'whatsapp_contact_request': 'Пожалуйста, свяжитесь со мной для уточнения деталей оплаты и доставки.',
+ 'whatsapp_request_price_calculation': 'Пожалуйста, рассчитайте стоимость заказа.',
+ 'admin_panel_h1': 'Админ-панель Integrity',
+ '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_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_usd_label': 'Цена (USD) *:',
+ 'product_discount_percent_label': 'Скидка (%):',
+ 'product_description_label': 'Описание:',
+ 'product_category_label': 'Категория:',
+ 'product_supplier_label': 'Поставщик:',
+ 'no_category_option': 'Без категории',
+ 'no_supplier_option': 'Без поставщика',
+ 'photos_label': 'Фотографии (до 10 шт.):',
+ 'colors_variants_label': 'Цвета/Варианты (оставьте пустым, если нет):',
+ 'color_placeholder_example': 'Например: Синий',
+ 'add_color_field_button': 'Добавить поле для цвета/варианта',
+ 'in_stock_label': 'В наличии',
+ 'top_product_label': 'Топ товар (показывать наверху)',
+ 'add_product_button': 'Добавить товар',
+ 'product_list_title': 'Список товаров:',
+ 'view_first_photo_title': 'Посмотреть первое фото',
+ 'photo_alt': 'Фото',
+ 'no_photo_alt': 'Нет фото',
+ 'status_in_stock': 'В наличии',
+ 'status_out_of_stock': 'Нет в наличии',
+ '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})',
+ 'edit_button': 'Редактировать',
+ 'confirm_delete_product': "Вы уверены, что хотите удалить товар '{product_name}'?",
+ 'delete_button': 'Удалить',
+ 'editing_product_title': 'Редактирование: {product_name}',
+ 'product_name_edit_label': 'Название *:',
+ 'product_price_usd_edit_label': 'Цена (USD) *:',
+ 'product_discount_percent_edit_label': 'Скидка (%):',
+ 'product_description_edit_label': 'Описание:',
+ 'product_category_edit_label': 'Категория:',
+ 'product_supplier_edit_label': 'Поставщик:',
+ 'replace_photos_label': 'Заменить фотографии (выберите новые файлы, до 10 шт.):',
+ 'current_photos_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': 'Топ товар',
+ '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}' удалена. {updated_count} товаров обновлено.",
+ 'flash_category_delete_failed': "Не удалось удалить категорию '{category_name}'.",
+ 'flash_supplier_added_success': "Поставщик '{supplier_name}' успешно добавлен.",
+ 'flash_supplier_name_empty': 'Имя поставщика не может быть пустым.',
+ 'flash_supplier_already_exists': "Поставщик '{supplier_name}' уже существует.",
+ 'flash_supplier_delete_success': "Поставщик '{supplier_name}' удален. {updated_count} товаров обновлено.",
+ '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_photo_upload_error': 'Ошибка при загрузке фото {filename}.',
+ 'flash_hf_token_write_not_set_photos_not_uploaded': 'HF_TOKEN (write) не настроен. Фотографии не были загружены.',
+ 'flash_product_added_success': "Товар '{product_name}' успешно добавлен.",
+ 'flash_edit_error_no_index': 'Ошибка редактирования: индекс товара не передан.',
+ 'flash_edit_error_invalid_index': "Ошибка редактирования: неверный индекс товара '{index_str}'.",
+ 'flash_invalid_price_format_edit_warning': "Неверный формат цены для товара '{product_name}'. Цена не изменена.",
+ 'flash_invalid_discount_format_edit_warning': "Неверный формат скидки для товара '{product_name}'. Скидка не изменена.",
+ 'flash_photos_updated_success': 'Фотографии товара успешно обновлены.',
+ 'flash_failed_to_upload_new_photos_format_error': 'Не удалось загрузить новые фотографии (возможно, неверный формат).',
+ 'flash_hf_token_write_not_set_photos_not_updated': 'HF_TOKEN (write) не настроен. Фотографии не были обновлены.',
+ 'flash_product_updated_success': "Товар '{product_name}' успешно обновлен.",
+ 'flash_delete_error_no_index': 'Ошибка удаления: индекс товара не передан.',
+ 'flash_failed_delete_hf_photos_warning': "Не удалось удалить фото для товара '{product_name}' с сервера. Товар удале�� локально.",
+ 'flash_hf_token_write_not_set_photos_not_deleted_warning': "Товар '{product_name}' удален локально, но фото не удалены с сервера (токен не задан).",
+ 'flash_product_deleted_success': "Товар '{product_name}' удален.",
+ 'flash_delete_error_invalid_index': "Ошибка удаления: неверный индекс товара '{index_str}'.",
+ '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_usd_to_kgs_rate_label': 'Курс USD к KGS (например: 87.50):',
+ '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': 'Запросить расчет стоимости',
+ 'price_on_request': 'Цена по запросу',
+ }
+}
+
+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': [], 'suppliers': [], 'orders': {}, 'config': {'usd_to_kgs_rate': 87.0, '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 load_data():
+ default_data = {'products': [], 'categories': [], 'suppliers': [], 'orders': {}, 'config': {'usd_to_kgs_rate': 87.0, 'prices_enabled': True}}
+ try:
+ with open(DATA_FILE, 'r', encoding='utf-8') as file:
+ data = json.load(file)
+ logging.info(f"Local data loaded successfully from {DATA_FILE}")
+ if not isinstance(data, dict):
+ logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.")
+ raise FileNotFoundError
+ if 'products' not in data: data['products'] = []
+ if 'categories' not in data: data['categories'] = []
+ if 'suppliers' not in data: data['suppliers'] = []
+ if 'orders' not in data: data['orders'] = {}
+ if 'config' not in data:
+ data['config'] = default_data['config']
+ else:
+ if 'usd_to_kgs_rate' not in data['config']:
+ data['config']['usd_to_kgs_rate'] = default_data['config'].get('usd_to_kgs_rate', 87.0)
+ if 'usd_to_uzs_rate' in data['config']:
+ data['config']['usd_to_kgs_rate'] = data['config'].pop('usd_to_uzs_rate')
+ try:
+ data['config']['usd_to_kgs_rate'] = float(data['config']['usd_to_kgs_rate'])
+ except (ValueError, TypeError):
+ data['config']['usd_to_kgs_rate'] = default_data['config']['usd_to_kgs_rate']
+ if 'prices_enabled' not in data['config']:
+ data['config']['prices_enabled'] = default_data['config']['prices_enabled']
+ for prod in data.get('products', []):
+ if 'supplier' not in prod:
+ prod['supplier'] = 'Без поставщика'
+ if 'price' in prod and 'price_usd' not in prod:
+ try:
+ prod['price_usd'] = float(prod['price'])
+ del prod['price']
+ except:
+ prod['price_usd'] = 0.0
+ elif 'price_usd' not in prod:
+ prod['price_usd'] = 0.0
+ if 'discount_percent' not in prod:
+ prod['discount_percent'] = 0
+ else:
+ 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
+ return data
+ except FileNotFoundError:
+ logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.")
+ except json.JSONDecodeError:
+ logging.error(f"Error decoding JSON in local {DATA_FILE}. File might be corrupt. Attempting download.")
+
+ if download_db_from_hf(specific_file=DATA_FILE):
+ try:
+ with open(DATA_FILE, 'r', encoding='utf-8') as file:
+ data = json.load(file)
+ logging.info(f"Data loaded successfully from {DATA_FILE} after download.")
+ if not isinstance(data, dict):
+ logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.")
+ return default_data
+ if 'products' not in data: data['products'] = []
+ if 'categories' not in data: data['categories'] = []
+ if 'suppliers' not in data: data['suppliers'] = []
+ if 'orders' not in data: data['orders'] = {}
+ if 'config' not in data:
+ data['config'] = default_data['config']
+ else:
+ if 'usd_to_kgs_rate' not in data['config']:
+ data['config']['usd_to_kgs_rate'] = default_data['config'].get('usd_to_kgs_rate', 87.0)
+ if 'usd_to_uzs_rate' in data['config']:
+ data['config']['usd_to_kgs_rate'] = data['config'].pop('usd_to_uzs_rate')
+ try:
+ data['config']['usd_to_kgs_rate'] = float(data['config']['usd_to_kgs_rate'])
+ except (ValueError, TypeError):
+ data['config']['usd_to_kgs_rate'] = default_data['config']['usd_to_kgs_rate']
+ if 'prices_enabled' not in data['config']:
+ data['config']['prices_enabled'] = default_data['config']['prices_enabled']
+ for prod in data.get('products', []):
+ if 'supplier' not in prod:
+ prod['supplier'] = 'Без поставщика'
+ if 'price' in prod and 'price_usd' not in prod:
+ try:
+ prod['price_usd'] = float(prod['price'])
+ del prod['price']
+ except:
+ prod['price_usd'] = 0.0
+ elif 'price_usd' not in prod:
+ prod['price_usd'] = 0.0
+ if 'discount_percent' not in prod:
+ prod['discount_percent'] = 0
+ else:
+ 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
+ return data
+ except FileNotFoundError:
+ logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.")
+ return default_data
+ except json.JSONDecodeError:
+ logging.error(f"Error decoding JSON in downloaded {DATA_FILE}. Using default.")
+ return default_data
+ except Exception as e:
+ logging.error(f"Unknown error loading downloaded {DATA_FILE}: {e}. Using default.", exc_info=True)
+ return default_data
+ else:
+ logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.")
+ if not os.path.exists(DATA_FILE):
+ try:
+ with open(DATA_FILE, 'w', encoding='utf-8') as f:
+ json.dump(default_data, f)
+ logging.info(f"Created empty local file {DATA_FILE} after failed download.")
+ except Exception as create_e:
+ logging.error(f"Failed to create empty local file {DATA_FILE}: {create_e}")
+ return default_data
+
+
+def save_data(data):
+ try:
+ if not isinstance(data, dict):
+ logging.error("Attempted to save invalid data structure (not a dict). Aborting save.")
+ return
+ default_config = {'usd_to_kgs_rate': 87.0, 'prices_enabled': True}
+ if 'products' not in data: data['products'] = []
+ if 'categories' not in data: data['categories'] = []
+ if 'suppliers' not in data: data['suppliers'] = []
+ if 'orders' not in data: data['orders'] = {}
+ if 'config' not in data:
+ data['config'] = default_config
+ else:
+ if 'usd_to_kgs_rate' not in data['config']:
+ data['config']['usd_to_kgs_rate'] = default_config['usd_to_kgs_rate']
+ if 'usd_to_uzs_rate' in data['config']:
+ data['config']['usd_to_kgs_rate'] = data['config'].pop('usd_to_uzs_rate')
+ try:
+ data['config']['usd_to_kgs_rate'] = float(data['config']['usd_to_kgs_rate'])
+ except (ValueError, TypeError):
+ data['config']['usd_to_kgs_rate'] = default_config['usd_to_kgs_rate']
+ if 'prices_enabled' not in data['config']:
+ data['config']['prices_enabled'] = default_config['prices_enabled']
+ for prod in data.get('products', []):
+ if 'supplier' not in prod:
+ prod['supplier'] = 'Без поставщика'
+ if 'price' in prod and 'price_usd' not in prod:
+ try:
+ prod['price_usd'] = float(prod['price'])
+ del prod['price']
+ except:
+ prod['price_usd'] = 0.0
+ elif 'price_usd' not in prod:
+ prod['price_usd'] = 0.0
+ try:
+ prod['price_usd'] = float(prod['price_usd'])
+ except (ValueError, TypeError):
+ prod['price_usd'] = 0.0
+ if 'discount_percent' not in prod:
+ prod['discount_percent'] = 0
+ else:
+ 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
+ with open(DATA_FILE, 'w', encoding='utf-8') as file:
+ json.dump(data, file, ensure_ascii=False, indent=4)
+ logging.info(f"Data successfully saved to {DATA_FILE}")
+ upload_db_to_hf(specific_file=DATA_FILE)
+ except Exception as e:
+ logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True)
+
+@app.context_processor
+def inject_global_vars():
+ lang_translations = translations['ru']
+ app_config = load_data().get('config', {'usd_to_kgs_rate': 87.0, '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'
+ ]
+ 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 = '''
+
+
+
+
+
+ {{ get_translation('catalog_title') }}
+
+
+
+
+
+
+
+
+
+ {% if not app_config.prices_enabled %}
+
+ {{ get_translation('prices_disabled_notice_catalog') }}
+
+ {% endif %}
+
+
+
{{ get_translation('supplier') }}
+
+
+ {% for supplier_name in suppliers %}
+
+ {% endfor %}
+
+
+
{{ get_translation('category') }}
+
+
+ {% for category_name_orig in categories %}
+
+ {% endfor %}
+
+
+
+
+
+
+
+
+ {% for product in products %}
+
+ {% if product.get('is_top', False) %}
+
{{ get_translation('status_top_product') }}
+ {% endif %}
+
+ {% if product.get('photos') and product['photos']|length > 0 %}
+
![{{ product['name'] }}](https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }})
+ {% else %}
+
|urlencode }})
+ {% endif %}
+
+
+
{{ product['name'] }}
+
+ {% set discount = product.get('discount_percent', 0) %}
+ {% set original_price_kgs = product.price_usd * app_config.usd_to_kgs_rate %}
+ {% if app_config.prices_enabled %}
+ {% if discount > 0 %}
+ {% set discounted_price_kgs = original_price_kgs * (100 - discount) / 100 %}
+
{{ "%.2f"|format(original_price_kgs) }} {{ currency_code }}
+
{{ "%.2f"|format(discounted_price_kgs) }} {{ currency_code }}
+
{{ get_translation('discount_badge_text', discount=discount) }}
+ {% else %}
+
{{ "%.2f"|format(original_price_kgs) }} {{ currency_code }}
+ {% endif %}
+ {% else %}
+
{{ get_translation('price_on_request') }}
+ {% endif %}
+
+
{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}
+
+
+
+
+
+
+ {% endfor %}
+ {% if not products %}
+
{{ get_translation('no_products_yet') }}
+ {% endif %}
+
+
+
+
+
+
×
+
{{ get_translation('loading') }}
+
+
+
+
+
+ ×
+
{{ get_translation('specify_quantity_color') }}
+
+
+
+
+
+
+
+
+
+
+
×
+
{{ get_translation('your_cart') }}
+
{{ get_translation('cart_empty') }}
+ {% if app_config.prices_enabled %}
+
+ {{ get_translation('total') }} 0.00 {{ currency_code }}
+
+ {% else %}
+
+ {{ get_translation('prices_disabled_notice_cart') }}
+
+ {% endif %}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+'''
+
+PRODUCT_DETAIL_TEMPLATE = '''
+
+
{{ product['name'] }}
+
+
+ {% if product.get('photos') and product['photos']|length > 0 %}
+ {% for photo in product['photos'] %}
+
+
+
![{{ get_translation('product_detail_photo_alt', product_name=product['name'], loop_index=loop.index) }}](https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }})
+
+
+ {% endfor %}
+ {% else %}
+
+
|urlencode }})
+
+ {% endif %}
+
+ {% if product.get('photos') and product['photos']|length > 1 %}
+
+
+
+ {% endif %}
+
+
+
{{ get_translation('supplier') }} {{ product.get('supplier', get_translation('no_supplier')) }}
+
{{ get_translation('category') }} {{ get_translation(product.get('category')) if product.get('category') == 'Без категории' else product.get('category', get_translation('no_category')) }}
+ {% set discount = product.get('discount_percent', 0) %}
+ {% set original_price_kgs = product.price_usd * app_config.usd_to_kgs_rate %}
+ {% if app_config.prices_enabled %}
+ {% if discount > 0 %}
+ {% set discounted_price_kgs = original_price_kgs * (100 - discount) / 100 %}
+
+ {{ get_translation('price') }}
+ {{ "%.2f"|format(original_price_kgs) }} {{ currency_code }}
+ {{ "%.2f"|format(discounted_price_kgs) }} {{ currency_code }}
+ {{ get_translation('discount_badge_text', discount=discount) }}
+
+ {% else %}
+
{{ get_translation('price') }} {{ "%.2f"|format(original_price_kgs) }} {{ currency_code }}
+ {% endif %}
+ {% else %}
+
{{ get_translation('price') }} {{ get_translation('price_on_request') }}
+ {% endif %}
+
{{ get_translation('description') }}
{{ product.get('description', get_translation('description_absent'))|replace('\\n', '
')|safe }}
+ {% set colors = product.get('colors', []) %}
+ {% if colors and colors|select('ne', '')|list|length > 0 %}
+
{{ get_translation('available_colors_variants') }} {{ colors|select('ne', '')|join(', ') }}
+ {% endif %}
+
+
+'''
+
+ORDER_TEMPLATE = '''
+
+
+
+
+
+ {{ get_translation('order_title', order_id=order.id if order else 'N/A') }}
+
+
+
+
+
+
+ {% if order %}
+
{{ get_translation('order_page_title', order_id=order.id) }}
+
{{ get_translation('creation_date') }} {{ order.created_at }}
+
+
{{ get_translation('products_in_order') }}
+
+ {% for item in order.cart %}
+
+

+
+ {{ item.name }} {% if item.color != 'N/A' %}({{ item.color }}){% endif %}
+ {% if order.prices_were_enabled_at_order %}
+ {{ "%.2f"|format(item.price_kgs_at_order) }} {{ currency_code }} × {{ item.quantity }}
+ {% else %}
+ {{ get_translation('quantity') }} {{ item.quantity }}
+ {% endif %}
+
+ {% if order.prices_were_enabled_at_order %}
+
+ {{ "%.2f"|format(item.price_kgs_at_order * item.quantity) }} {{ currency_code }}
+
+ {% else %}
+
+ {{ get_translation('price_on_request') }}
+
+ {% endif %}
+
+ {% endfor %}
+
+
+ {% if order.prices_were_enabled_at_order %}
+
+
{{ get_translation('total_products_sum') }} {{ "%.2f"|format(order.total_price_kgs) }} {{ currency_code }}
+
{{ get_translation('total_to_pay') }} {{ "%.2f"|format(order.total_price_kgs) }} {{ currency_code }}
+
+ {% else %}
+
+
{{ get_translation('prices_disabled_notice_cart') }}
+
+ {% endif %}
+
+
+
+
{{ get_translation('order_status') }}
+
{{ get_translation('anonymous_order_notice') }}
+
{{ get_translation('contact_whatsapp_notice') }}
+
+
+
+
+
+
+
{{ get_translation('back_to_catalog') }}
+
+
+
+ {% else %}
+
{{ get_translation('error_page_title') }}
+
{{ get_translation('order_not_found_by_id') }}
+
{{ get_translation('back_to_catalog') }}
+ {% endif %}
+
+
+
+'''
+
+ADMIN_TEMPLATE = '''
+
+
+
+
+
+ {{ get_translation('admin_title') }}
+
+
+
+
+
+
+
+
+ {% with messages = get_flashed_messages(with_categories=true) %}
+ {% if messages %}
+ {% for category, message in messages %}
+
{{ message }}
+ {% endfor %}
+ {% endif %}
+ {% endwith %}
+
+
+
{{ get_translation('admin_settings_title') }}
+
+
+
+
+
{{ get_translation('sync_with_dc') }}
+
+
+
+
+
{{ get_translation('sync_info_text') }}
+
+
+
+
+
{{ get_translation('manage_suppliers') }}
+
+ {{ get_translation('add_new_supplier') }}
+
+
+
+
+
+
{{ get_translation('existing_suppliers') }}
+ {% if suppliers %}
+
+ {% for supplier_name in suppliers %}
+
+ {{ supplier_name }}
+
+
+ {% endfor %}
+
+ {% else %}
+
{{ get_translation('no_suppliers_yet') }}
+ {% endif %}
+
+
+
+
{{ get_translation('manage_categories') }}
+
+ {{ get_translation('add_new_category') }}
+
+
+
+
+
+
{{ get_translation('existing_categories') }}
+ {% if categories %}
+
+ {% for category_name_orig in categories %}
+
+ {{ category_name_orig }}
+
+
+ {% endfor %}
+
+ {% else %}
+
{{ get_translation('no_categories_yet') }}
+ {% endif %}
+
+
+
+
{{ get_translation('information_section_title') }}
+
{{ get_translation('user_management_disabled_info') }}
+
{{ get_translation('anonymous_orders_whatsapp_info') }}
+
+
+
+
+
{{ get_translation('manage_products') }}
+
+ {{ get_translation('add_new_product') }}
+
+
+
+
{{ get_translation('product_list_title') }}
+ {% if products %}
+
+ {% for product in products %}
+
+
+
+ {% if product.get('photos') %}
+
+
+
+ {% else %}
+

+ {% endif %}
+
+
+
+ {{ product['name'] }}
+ {% if product.get('in_stock', True) %}
+ {{ get_translation('status_in_stock') }}
+ {% else %}
+ {{ get_translation('status_out_of_stock') }}
+ {% endif %}
+ {% if product.get('is_top', False) %}
+ {{ get_translation('status_top_product') }}
+ {% endif %}
+
+
{{ get_translation('supplier') }} {{ product.get('supplier', get_translation('no_supplier')) }}
+
{{ get_translation('category') }} {{ product.get('category', get_translation('no_category')) }}
+
{{ get_translation('price') }} {{ "%.2f"|format(product.price_usd) }} {{ admin_currency_code }}
+ ({{ "%.2f"|format(product.price_usd * app_config.usd_to_kgs_rate) }} {{ currency_code }})
+
+ {% if product.get('discount_percent', 0) > 0 %}
+
{{ get_translation('discount_label_item') }} {{ product.discount_percent }}%
+ {% endif %}
+
{{ get_translation('description_label_item') }} {{ product.get('description', get_translation('description_not_available'))[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}
+ {% set colors = product.get('colors', []) %}
+
{{ get_translation('colors_variants_item_label') }} {{ colors|select('ne', '')|join(', ') if colors|select('ne', '')|list|length > 0 else get_translation('colors_not_available') }}
+ {% if product.get('photos') and product['photos']|length > 1 %}
+
{{ get_translation('total_photos_count', count=product['photos']|length ) }}
+ {% endif %}
+
+
+
+
+
+
+
+
+
+
+ {% endfor %}
+
+ {% else %}
+
{{ get_translation('no_products_yet_admin') }}
+ {% endif %}
+
+
+
+
+
+
+'''
+
+
+@app.route('/')
+def catalog():
+ data = load_data()
+ all_products = data.get('products', [])
+ categories_orig = sorted(data.get('categories', []))
+ suppliers_orig = sorted(data.get('suppliers', []))
+ app_config = data.get('config', {'usd_to_kgs_rate': 87.0, 'prices_enabled': True})
+
+ products_in_stock = [p for p in all_products if p.get('in_stock', True)]
+ products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
+
+ return render_template_string(
+ CATALOG_TEMPLATE,
+ products=products_sorted,
+ categories=categories_orig,
+ suppliers=suppliers_orig,
+ repo_id=REPO_ID,
+ currency_code=CURRENCY_CODE,
+ app_config=app_config
+ )
+
+@app.route('/product/')
+def product_detail(index):
+ data = load_data()
+ all_products = data.get('products', [])
+ app_config = data.get('config', {'usd_to_kgs_rate': 87.0, 'prices_enabled': True})
+ products_in_stock = [p for p in all_products if p.get('in_stock', True)]
+ products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
+ try:
+ product = products_sorted[index]
+ except IndexError:
+ 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=product,
+ repo_id=REPO_ID,
+ currency_code=CURRENCY_CODE,
+ app_config=app_config
+ )
+
+@app.route('/create_order', methods=['POST'])
+def create_order():
+ order_data = request.get_json()
+ current_data_full = load_data()
+ app_config = current_data_full.get('config', {'usd_to_kgs_rate': 87.0, 'prices_enabled': True})
+ current_rate = float(app_config.get('usd_to_kgs_rate', 87.0))
+ 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_usd', 'quantity')):
+ logging.error(f"Invalid cart item structure received: {item}")
+ return jsonify({"error": "Invalid cart item format."}), 400
+ try:
+ price_usd_in_cart = float(item['price_usd'])
+ original_price_usd = float(item.get('original_price_usd', price_usd_in_cart))
+ discount_percent = int(item.get('discount_percent', 0))
+ quantity = int(item['quantity'])
+ if price_usd_in_cart < 0 or quantity <= 0:
+ raise ValueError("Invalid price or quantity")
+ price_kgs_at_order = round(price_usd_in_cart * current_rate, 2)
+ original_price_kgs_at_order = round(original_price_usd * current_rate, 2)
+ if prices_currently_enabled:
+ total_price_kgs += price_kgs_at_order * quantity
+ processed_cart.append({
+ "name": item['name'],
+ "price_usd_final": price_usd_in_cart,
+ "original_price_usd": original_price_usd,
+ "discount_percent_at_order": discount_percent,
+ "price_kgs_at_order": price_kgs_at_order,
+ "original_price_kgs_at_order": original_price_kgs_at_order,
+ "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/discount in cart item: {item}. Error: {e}")
+ return jsonify({"error": "Invalid price, quantity, or discount 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,
+ "usd_to_kgs_rate_at_order": current_rate,
+ "prices_were_enabled_at_order": prices_currently_enabled,
+ "user_info": None,
+ "status": "new"
+ }
+ try:
+ data = load_data()
+ if 'orders' not in data or not isinstance(data.get('orders'), dict):
+ data['orders'] = {}
+ data['orders'][order_id] = new_order
+ save_data(data)
+ logging.info(f"Order {order_id} created successfully. 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
+
+@app.route('/order/')
+def view_order(order_id):
+ data = load_data()
+ order = data.get('orders', {}).get(order_id)
+ app_config = data.get('config', {'usd_to_kgs_rate': 87.0, '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)
+
+@app.route('/admin', methods=['GET', 'POST'])
+def admin():
+ data = load_data()
+ products = data.get('products', [])
+ categories = data.get('categories', [])
+ suppliers = data.get('suppliers', [])
+ app_config = data.get('config', {'usd_to_kgs_rate': 87.0, 'prices_enabled': True})
+ if 'orders' not in data or not isinstance(data.get('orders'), dict):
+ data['orders'] = {}
+ if request.method == 'POST':
+ action = request.form.get('action')
+ logging.info(f"Admin action received: {action}")
+ try:
+ if action == 'update_settings':
+ new_rate_str = request.form.get('usd_to_kgs_rate', str(app_config['usd_to_kgs_rate']))
+ prices_enabled_form = 'prices_enabled' in request.form
+ try:
+ new_rate = float(new_rate_str)
+ if new_rate <=0: raise ValueError("Rate must be positive")
+ data['config']['usd_to_kgs_rate'] = new_rate
+ except ValueError:
+ flash(get_translation('flash_invalid_price_format'), 'error')
+ data['config']['prices_enabled'] = prices_enabled_form
+ 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 category_name not in categories:
+ categories.append(category_name)
+ data['categories'] = categories
+ save_data(data)
+ logging.info(f"Category '{category_name}' added.")
+ flash(get_translation('flash_category_added_success', category_name=category_name), 'success')
+ elif not category_name:
+ logging.warning("Attempted to add empty category.")
+ flash(get_translation('flash_category_name_empty'), 'error')
+ else:
+ logging.warning(f"Category '{category_name}' already exists.")
+ flash(get_translation('flash_category_already_exists', category_name=category_name), 'error')
+ elif action == 'delete_category':
+ category_to_delete = request.form.get('category_name')
+ if category_to_delete and category_to_delete in categories:
+ categories.remove(category_to_delete)
+ updated_count = 0
+ for product in products:
+ if product.get('category') == category_to_delete:
+ product['category'] = 'Без категории'
+ updated_count += 1
+ data['categories'] = categories
+ data['products'] = products
+ save_data(data)
+ logging.info(f"Category '{category_to_delete}' deleted. Updated products: {updated_count}.")
+ flash(get_translation('flash_category_delete_success', category_name=category_to_delete, updated_count=updated_count), 'success')
+ else:
+ logging.warning(f"Attempted to delete non-existent or empty category: {category_to_delete}")
+ flash(get_translation('flash_category_delete_failed', category_name=category_to_delete), '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
+ save_data(data)
+ logging.info(f"Supplier '{supplier_name}' added.")
+ flash(get_translation('flash_supplier_added_success', supplier_name=supplier_name), 'success')
+ elif not supplier_name:
+ logging.warning("Attempted to add empty supplier.")
+ flash(get_translation('flash_supplier_name_empty'), 'error')
+ else:
+ logging.warning(f"Supplier '{supplier_name}' already exists.")
+ 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
+ save_data(data)
+ logging.info(f"Supplier '{supplier_to_delete}' deleted. Updated products: {updated_count}.")
+ flash(get_translation('flash_supplier_delete_success', supplier_name=supplier_to_delete, updated_count=updated_count), 'success')
+ else:
+ logging.warning(f"Attempted to delete non-existent or empty supplier: {supplier_to_delete}")
+ flash(get_translation('flash_supplier_delete_failed', supplier_name=supplier_to_delete), 'error')
+ elif action == 'add_product':
+ name = request.form.get('name', '').strip()
+ price_usd_str = request.form.get('price_usd', '').replace(',', '.')
+ discount_percent_str = request.form.get('discount_percent', '0')
+ description = request.form.get('description', '').strip()
+ category = request.form.get('category')
+ supplier = request.form.get('supplier')
+ photos_files = request.files.getlist('photos')
+ colors = [c.strip() for c in request.form.getlist('colors') if c.strip()]
+ in_stock = 'in_stock' in request.form
+ is_top = 'is_top' in request.form
+ if not name or not price_usd_str:
+ flash(get_translation('flash_product_name_price_required'), 'error')
+ return redirect(url_for('admin'))
+ try:
+ price_usd = round(float(price_usd_str), 2)
+ if price_usd < 0: price_usd = 0
+ except ValueError:
+ flash(get_translation('flash_invalid_price_format'), 'error')
+ return redirect(url_for('admin'))
+ try:
+ discount_percent = int(discount_percent_str)
+ if not (0 <= discount_percent <= 100):
+ discount_percent = 0
+ flash(get_translation('flash_invalid_discount_format'), 'warning')
+ except ValueError:
+ discount_percent = 0
+ flash(get_translation('flash_invalid_discount_format'), 'warning')
+ photos_list = []
+ if photos_files and HF_TOKEN_WRITE:
+ uploads_dir = 'uploads_temp'
+ os.makedirs(uploads_dir, exist_ok=True)
+ api = HfApi()
+ photo_limit = 10
+ uploaded_count = 0
+ for photo_idx, photo in enumerate(photos_files):
+ if uploaded_count >= photo_limit:
+ logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.")
+ flash(get_translation('flash_photo_limit_reached', photo_limit=photo_limit), "warning")
+ break
+ if photo and photo.filename:
+ try:
+ ext = os.path.splitext(photo.filename)[1].lower()
+ if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
+ logging.warning(f"Skipping non-image file upload: {photo.filename}")
+ flash(get_translation('flash_file_not_image_skipped', filename=photo.filename), "warning")
+ continue
+ safe_name = secure_filename(name.replace(' ', '_'))[:50]
+ photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}_{photo_idx}{ext}"
+ temp_path = os.path.join(uploads_dir, photo_filename)
+ photo.save(temp_path)
+ logging.info(f"Uploading photo {photo_filename} to HF for product {name}...")
+ api.upload_file(
+ path_or_fileobj=temp_path,
+ path_in_repo=f"photos/{photo_filename}",
+ repo_id=REPO_ID,
+ repo_type="dataset",
+ token=HF_TOKEN_WRITE,
+ commit_message=f"Add photo for product {name}"
+ )
+ photos_list.append(photo_filename)
+ logging.info(f"Photo {photo_filename} uploaded successfully.")
+ os.remove(temp_path)
+ uploaded_count += 1
+ except Exception as e:
+ logging.error(f"Error uploading photo {photo.filename} to HF: {e}", exc_info=True)
+ flash(get_translation('flash_photo_upload_error', filename=photo.filename), 'error')
+ if os.path.exists(temp_path):
+ try: os.remove(temp_path)
+ except OSError: pass
+ elif photo and not photo.filename:
+ logging.warning("Received an empty photo file object when adding product.")
+ try:
+ if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
+ os.rmdir(uploads_dir)
+ except OSError as e:
+ logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}")
+ elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
+ flash(get_translation('flash_hf_token_write_not_set_photos_not_uploaded'), "warning")
+ new_product = {
+ 'name': name, 'price_usd': price_usd, 'discount_percent': discount_percent,
+ 'description': description,
+ 'category': category if category in categories or category == 'Без категории' else 'Без категории',
+ 'supplier': supplier if supplier in suppliers or supplier == 'Без поставщика' else 'Без поставщика',
+ 'photos': photos_list, 'colors': colors,
+ 'in_stock': in_stock, 'is_top': is_top
+ }
+ products.append(new_product)
+ data['products'] = products
+ save_data(data)
+ logging.info(f"Product '{name}' added.")
+ flash(get_translation('flash_product_added_success', product_name=name), 'success')
+ elif action == 'edit_product':
+ index_str = request.form.get('index')
+ if index_str is None:
+ flash(get_translation('flash_edit_error_no_index'), 'error')
+ return redirect(url_for('admin'))
+ try:
+ index = int(index_str)
+ if not (0 <= index < len(products)):
+ raise IndexError("Product index out of range")
+ product_to_edit = products[index]
+ original_name = product_to_edit.get('name', 'N/A')
+ except (ValueError, IndexError):
+ flash(get_translation('flash_edit_error_invalid_index', index_str=index_str), 'error')
+ logging.error(f"Invalid index '{index_str}' for editing. Product list length: {len(products)}")
+ return redirect(url_for('admin'))
+ product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip()
+ price_usd_str = request.form.get('price_usd', str(product_to_edit.get('price_usd',0.0))).replace(',', '.')
+ discount_percent_str = request.form.get('discount_percent', str(product_to_edit.get('discount_percent',0)))
+ product_to_edit['description'] = request.form.get('description', product_to_edit.get('description', '')).strip()
+ category = request.form.get('category')
+ supplier = request.form.get('supplier')
+ product_to_edit['category'] = category if category in categories or category == 'Без категории' else 'Без категории'
+ 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()]
+ product_to_edit['in_stock'] = 'in_stock' in request.form
+ product_to_edit['is_top'] = 'is_top' in request.form
+ try:
+ price_usd = round(float(price_usd_str), 2)
+ if price_usd < 0: price_usd = 0
+ product_to_edit['price_usd'] = price_usd
+ except ValueError:
+ logging.warning(f"Invalid price format '{price_usd_str}' during edit of product {original_name}. Price not changed.")
+ flash(get_translation('flash_invalid_price_format_edit_warning', product_name=original_name), 'warning')
+ try:
+ discount_percent = int(discount_percent_str)
+ if not (0 <= discount_percent <= 100):
+ discount_percent = product_to_edit.get('discount_percent', 0)
+ flash(get_translation('flash_invalid_discount_format_edit_warning', product_name=original_name), 'warning')
+ product_to_edit['discount_percent'] = discount_percent
+ except ValueError:
+ flash(get_translation('flash_invalid_discount_format_edit_warning', product_name=original_name), 'warning')
+ photos_files = request.files.getlist('photos')
+ if photos_files and any(f.filename for f in photos_files) and HF_TOKEN_WRITE:
+ uploads_dir = 'uploads_temp'
+ os.makedirs(uploads_dir, exist_ok=True)
+ api = HfApi()
+ new_photos_list = []
+ photo_limit = 10
+ uploaded_count = 0
+ logging.info(f"Uploading new photos for product {product_to_edit['name']}...")
+ for photo_idx, photo in enumerate(photos_files):
+ if uploaded_count >= photo_limit:
+ logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.")
+ flash(get_translation('flash_photo_limit_reached', photo_limit=photo_limit), "warning")
+ break
+ if photo and photo.filename:
+ try:
+ ext = os.path.splitext(photo.filename)[1].lower()
+ if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
+ logging.warning(f"Skipping non-image file upload during edit: {photo.filename}")
+ flash(get_translation('flash_file_not_image_skipped', filename=photo.filename), "warning")
+ continue
+ safe_name = secure_filename(product_to_edit['name'].replace(' ', '_'))[:50]
+ photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}_{photo_idx}{ext}"
+ temp_path = os.path.join(uploads_dir, photo_filename)
+ photo.save(temp_path)
+ logging.info(f"Uploading new photo {photo_filename} to HF...")
+ api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}",
+ repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
+ commit_message=f"Update photo for product {product_to_edit['name']}")
+ new_photos_list.append(photo_filename)
+ logging.info(f"New photo {photo_filename} uploaded successfully.")
+ os.remove(temp_path)
+ uploaded_count += 1
+ except Exception as e:
+ logging.error(f"Error uploading new photo {photo.filename}: {e}", exc_info=True)
+ flash(get_translation('flash_photo_upload_error', filename=photo.filename), 'error')
+ if os.path.exists(temp_path):
+ try: os.remove(temp_path)
+ except OSError: pass
+ try:
+ if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
+ os.rmdir(uploads_dir)
+ except OSError as e:
+ logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}")
+ if new_photos_list:
+ logging.info(f"New photo list for product {product_to_edit['name']} generated.")
+ old_photos = product_to_edit.get('photos', [])
+ if old_photos:
+ logging.info(f"Attempting to delete old photos: {old_photos}")
+ try:
+ api.delete_files(
+ repo_id=REPO_ID,
+ paths_in_repo=[f"photos/{p}" for p in old_photos],
+ repo_type="dataset",
+ token=HF_TOKEN_WRITE,
+ commit_message=f"Delete old photos for product {product_to_edit['name']}"
+ )
+ logging.info(f"Old photos for product {product_to_edit['name']} deleted from HF.")
+ except Exception as e:
+ logging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True)
+ flash(get_translation('flash_failed_delete_hf_photos_warning', product_name=product_to_edit['name']), "warning")
+ product_to_edit['photos'] = new_photos_list
+ flash(get_translation('flash_photos_updated_success'), "success")
+ elif uploaded_count == 0 and any(f.filename for f in photos_files):
+ flash(get_translation('flash_failed_to_upload_new_photos_format_error'), "error")
+ elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
+ flash(get_translation('flash_hf_token_write_not_set_photos_not_updated'), "warning")
+ products[index] = product_to_edit
+ data['products'] = products
+ save_data(data)
+ logging.info(f"Product '{original_name}' (index {index}) updated to '{product_to_edit['name']}'.")
+ flash(get_translation('flash_product_updated_success', product_name=product_to_edit['name']), 'success')
+ elif action == 'delete_product':
+ index_str = request.form.get('index')
+ if index_str is None:
+ flash(get_translation('flash_delete_error_no_index'), 'error')
+ return redirect(url_for('admin'))
+ try:
+ index = int(index_str)
+ if not (0 <= index < len(products)): raise IndexError("Product index out of range")
+ deleted_product = products.pop(index)
+ product_name = deleted_product.get('name', 'N/A')
+ photos_to_delete = deleted_product.get('photos', [])
+ if photos_to_delete and HF_TOKEN_WRITE:
+ logging.info(f"Attempting to delete photos for product '{product_name}' from HF: {photos_to_delete}")
+ try:
+ api = HfApi()
+ api.delete_files(
+ repo_id=REPO_ID,
+ paths_in_repo=[f"photos/{p}" for p in photos_to_delete],
+ repo_type="dataset",
+ token=HF_TOKEN_WRITE,
+ commit_message=f"Delete photos for deleted product {product_name}"
+ )
+ logging.info(f"Photos for product '{product_name}' deleted from HF.")
+ except Exception as e:
+ logging.error(f"Error deleting photos {photos_to_delete} for product '{product_name}' from HF: {e}", exc_info=True)
+ flash(get_translation('flash_failed_delete_hf_photos_warning', product_name=product_name), "warning")
+ elif photos_to_delete and not HF_TOKEN_WRITE:
+ logging.warning(f"HF_TOKEN (write) not set. Cannot delete photos {photos_to_delete} for deleted product '{product_name}'.")
+ flash(get_translation('flash_hf_token_write_not_set_photos_not_deleted_warning', product_name=product_name), "warning")
+ data['products'] = products
+ save_data(data)
+ logging.info(f"Product '{product_name}' (original index {index}) deleted.")
+ flash(get_translation('flash_product_deleted_success', product_name=product_name), 'success')
+ except (ValueError, IndexError):
+ flash(get_translation('flash_delete_error_invalid_index', index_str=index_str), 'error')
+ logging.error(f"Invalid index '{index_str}' for deletion. Product list length: {len(products)}")
+ else:
+ logging.warning(f"Received unknown admin action: {action}")
+ 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'))
+
+ current_data = load_data()
+ display_products = sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower())
+ display_categories_orig = sorted(current_data.get('categories', []))
+ display_suppliers_orig = sorted(current_data.get('suppliers', []))
+ current_app_config = current_data.get('config', {'usd_to_kgs_rate': 87.0, 'prices_enabled': True})
+
+ return render_template_string(
+ ADMIN_TEMPLATE,
+ products=display_products,
+ categories=display_categories_orig,
+ suppliers=display_suppliers_orig,
+ repo_id=REPO_ID,
+ currency_code=CURRENCY_CODE,
+ admin_currency_code=ADMIN_CURRENCY_CODE,
+ app_config=current_app_config
+ )
+
+@app.route('/force_upload', methods=['POST'])
+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'))
+
+@app.route('/force_download', methods=['POST'])
+def force_download():
+ logging.info("Forcing download from Hugging Face...")
+ try:
+ if download_db_from_hf():
+ flash(get_translation('flash_data_downloaded_hf_success'), 'success')
+ load_data()
+ 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...")
+ if not os.path.exists(DATA_FILE):
+ download_db_from_hf()
+ load_data()
+ logging.info("Initial data load complete.")
+
+ if HF_TOKEN_WRITE:
+ backup_thread = threading.Thread(target=periodic_backup, daemon=True)
+ backup_thread.start()
+ logging.info("Periodic backup thread started.")
+ else:
+ logging.warning("Periodic backup will NOT run (HF_TOKEN for writing not set).")
+
+ port = int(os.environ.get('PORT', 7860))
+ logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}")
+ app.run(debug=False, host='0.0.0.0', port=port)