diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,2139 +1,586 @@ - -from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify +import asyncio import json import os +import urllib.parse +from datetime import datetime +from aiogram import Bot, Dispatcher, types, F +from aiogram.filters import Command +from aiogram.utils.keyboard import ReplyKeyboardBuilder, InlineKeyboardBuilder +from flask import Flask, request, jsonify, render_template_string, redirect 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 huggingface_hub.utils import RepositoryNotFoundError from werkzeug.utils import secure_filename -from dotenv import load_dotenv -import requests -import uuid -import telebot -load_dotenv() +# Настройка логирования +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) +# Инициализация бота и Flask +BOT_TOKEN = '8283649768:AAGYWatM-nUVQirgBiBwoAtWZgzfp3QnQjY' +bot = Bot(token=BOT_TOKEN) +dp = Dispatcher() app = Flask(__name__) -app.secret_key = 'your_unique_secret_key_soola_cosmetics_67890_no_login' -DATA_FILE = 'data.json' -SYNC_FILES = [DATA_FILE] +# Путь для хранения данных +DATA_FILE = 'data.json' +# Настройки Hugging Face REPO_ID = "Kgshop/aiocult" HF_TOKEN_WRITE = os.getenv("HF_TOKEN") HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") -TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") - -STORE_ADDRESS = " Алматы, «Байсат» 1 этаж, синий сектор 117-118 Бутик " - -CURRENCY_CODE = 'KZT' -CURRENCY_NAME = 'Казахстанский тенге' - -DOWNLOAD_RETRIES = 3 -DOWNLOAD_DELAY = 5 - -STATUS_MAP_RU = { - "new": "Новый", - "accepted": "Принят", - "prepared": "Собран", - "shipped": "Отправлен" -} - -logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') - -data_lock = threading.Lock() -bot = None -if TELEGRAM_BOT_TOKEN: - bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN, threaded=False) - -def load_data_internal(): - default_data = {'products': [], 'categories': [], 'orders': {}, 'telegram_users': {}} +# Функции для работы с данными +def load_data(): try: - with open(DATA_FILE, 'r', encoding='utf-8') as file: - data = json.load(file) - if not isinstance(data, dict): - return default_data - if 'products' not in data: data['products'] = [] - if 'categories' not in data: data['categories'] = [] - if 'orders' not in data: data['orders'] = {} - if 'telegram_users' not in data: data['telegram_users'] = {} - return data - except (FileNotFoundError, json.JSONDecodeError): - return default_data + download_db_from_hf() + with open(DATA_FILE, 'r', encoding='utf-8') as f: + loaded_data = json.load(f) + if not (isinstance(loaded_data, dict) and 'products' in loaded_data and 'orders' in loaded_data): + logger.error("Неверная структура JSON файла") + loaded_data = {'products': [], 'orders': []} + if "categories" not in loaded_data: + loaded_data["categories"] = [] + return loaded_data + except Exception as e: + logger.error(f"Ошибка при загрузке данных: {e}") + return {'products': [], 'orders': [], 'categories': []} -def save_data_internal(data): +def save_data(data): try: - if 'products' not in data: data['products'] = [] - if 'categories' not in data: data['categories'] = [] - if 'orders' not in data: data['orders'] = {} - if 'telegram_users' not in data: data['telegram_users'] = {} - - with open(DATA_FILE, 'w', encoding='utf-8') as file: - json.dump(data, file, ensure_ascii=False, indent=4) + with open(DATA_FILE, 'w', encoding='utf-8') as f: + json.dump(data, f, ensure_ascii=False, indent=4) + # upload_db_to_hf() убрано отсюда except Exception as e: - logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True) - -if bot: - @bot.message_handler(commands=['start']) - def send_welcome(message): - user_id = message.from_user.id - username = message.from_user.username - first_name = message.from_user.first_name - - with data_lock: - data = load_data_internal() - if 'telegram_users' not in data: - data['telegram_users'] = {} - - str_id = str(user_id) - data['telegram_users'][str_id] = { - 'username': username, - 'first_name': first_name, - 'joined_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S') - } - save_data_internal(data) - logging.info(f"New Telegram user registered: {user_id}") - - bot.send_message(message.chat.id, "Вы зарегистрированы. Теперь мы сможем присылать вам уведомления.") - -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.") + logger.error(f"Ошибка при сохранении данных: {e}") - token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE - - files_to_download = [specific_file] if specific_file else SYNC_FILES - logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...") - all_successful = True - - for file_name in files_to_download: - success = False - for attempt in range(retries + 1): - try: - logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...") - local_path = hf_hub_download( - repo_id=REPO_ID, - filename=file_name, - repo_type="dataset", - token=token_to_use, - local_dir=".", - local_dir_use_symlinks=False, - force_download=True, - resume_download=False - ) - logging.info(f"Successfully downloaded {file_name} to {local_path}.") - success = True - break - except RepositoryNotFoundError: - logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.") - return False - except HfHubHTTPError as e: - if e.response.status_code == 404: - logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.") - if attempt == 0 and not os.path.exists(file_name): - try: - if file_name == DATA_FILE: - with open(file_name, 'w', encoding='utf-8') as f: - json.dump({'products': [], 'categories': [], 'orders': {}, 'telegram_users': {}}, f) - logging.info(f"Created empty local file {file_name} because it was not found on HF.") - except Exception as create_e: - logging.error(f"Failed to create empty local file {file_name}: {create_e}") - success = False - break - else: - logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") - except requests.exceptions.RequestException as e: - logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") - except Exception as e: - logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True) - - if attempt < retries: - time.sleep(delay) - - if not success: - logging.error(f"Failed to download {file_name} after {retries + 1} attempts.") - all_successful = False - - logging.info(f"Download process finished. Overall success: {all_successful}") - return all_successful - -def upload_db_to_hf(specific_file=None): - if not HF_TOKEN_WRITE: - logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.") - return +def upload_db_to_hf(): 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}...") + api.upload_file( + path_or_fileobj=DATA_FILE, + path_in_repo=DATA_FILE, + repo_id=REPO_ID, + repo_type="dataset", + token=HF_TOKEN_WRITE, + commit_message=f"Автоматическое резервное копирование {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" + ) + logger.info("База загружена на Hugging Face") + except Exception as e: + logger.error(f"Ошибка при загрузке резервной копии: {e}") - 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.") +def download_db_from_hf(): + try: + hf_hub_download( + repo_id=REPO_ID, + filename=DATA_FILE, + repo_type="dataset", + token=HF_TOKEN_READ, + local_dir=".", + local_dir_use_symlinks=False + ) + logger.info("База скачана из Hugging Face") except Exception as e: - logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True) + logger.error(f"Ошибка при скачивании: {e}") + raise -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...") +# Периодическое копирование каждые 30 секунд +def start_periodic_backup(): + def backup_loop(): upload_db_to_hf() - logging.info("Periodic backup finished.") - -def load_data(): - with data_lock: - default_data = {'products': [], 'categories': [], 'orders': {}, 'telegram_users': {}} - try: - with open(DATA_FILE, 'r', encoding='utf-8') as file: - data = json.load(file) - logging.info(f"Local data loaded successfully from {DATA_FILE}") - if not isinstance(data, dict): - logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.") - raise FileNotFoundError - if 'products' not in data: data['products'] = [] - if 'categories' not in data: data['categories'] = [] - if 'orders' not in data: data['orders'] = {} - if 'telegram_users' not in data: data['telegram_users'] = {} - 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.") + # Запускаем следующий вызов через 30 секунд + threading.Timer(30, backup_loop).start() + + # Запускаем первый вызов + threading.Timer(30, backup_loop).start() + logger.info("Периодическое копирование каждые 30 секунд запущено") + +# Загрузка данных +data = load_data() + +# Формирование клавиатур +def get_main_keyboard(): + builder = ReplyKeyboardBuilder() + builder.button(text="📋 Каталог") + builder.button(text="🛒 Корзина") + builder.button(text="📦 Заказы") + builder.adjust(2) + return builder.as_markup(resize_keyboard=True) + +def get_category_keyboard(): + builder = InlineKeyboardBuilder() + for category in data['categories']: + builder.button(text=category['name'], callback_data=f"cat_{category['id']}") + builder.adjust(2) + return builder.as_markup() + +def get_product_keyboard(product_id): + builder = InlineKeyboardBuilder() + builder.button(text="Добавить в корзину", callback_data=f"add_{product_id}") + return builder.as_markup() + +# Обработчики бота +@dp.message(Command("start")) +async def cmd_start(message: types.Message): + await message.answer("Здравствуйте ! это магазин Routine!. Выберите действие:", reply_markup=get_main_keyboard()) + +# Изменено условие на "📋 Каталог", чтобы соответствовать кнопке +@dp.message(F.text == "📋 Каталог") +async def show_categories(message: types.Message): + if not data['categories']: + await message.answer("Нет доступных категорий.") + return + await message.answer("Выберите категорию:", reply_markup=get_category_keyboard()) - 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): - return default_data - if 'products' not in data: data['products'] = [] - if 'categories' not in data: data['categories'] = [] - if 'orders' not in data: data['orders'] = {} - if 'telegram_users' not in data: data['telegram_users'] = {} - return 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): +@dp.callback_query(F.data.startswith("cat_")) +async def show_products_in_category(callback_query: types.CallbackQuery): + try: + cat_id = int(callback_query.data.split('_')[1]) + products_in_cat = [p for p in data['products'] if p.get('category_id') == cat_id] + + if not products_in_cat: + await bot.send_message(callback_query.from_user.id, "В этой категории нет товаров.") + await bot.answer_callback_query(callback_query.id) + return + + async def send_product_batch(products_batch): + for product in products_batch: + caption = f"🏷 {product['name']} - {product['price']} сом\nОписание: {product['description']}\n/id: {product['id']}" + photos = product.get('photos', []) 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): - with data_lock: - try: - if 'products' not in data: data['products'] = [] - if 'categories' not in data: data['categories'] = [] - if 'orders' not in data: data['orders'] = {} - if 'telegram_users' not in data: data['telegram_users'] = {} - - with open(DATA_FILE, 'w', encoding='utf-8') as file: - json.dump(data, file, ensure_ascii=False, indent=4) - upload_db_to_hf(specific_file=DATA_FILE) - except Exception as e: - logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True) - -def start_bot_polling(): - if bot: - logging.info("Starting Telebot polling...") - bot.infinity_polling() - -def broadcast_message(user_ids, text): - if not bot: - return 0 - - count = 0 - for user_id in user_ids: - try: - bot.send_message(chat_id=user_id, text=text) - count += 1 - time.sleep(0.05) - except Exception as e: - logging.error(f"Failed to send message to {user_id}: {e}") - return count - -CATALOG_TEMPLATE = ''' - - - - - - Мобильный мир - Каталог - - - - - - -
-
-
- Мобильный мир Logo -

Мобильный мир

-
- -
- -
Наш адрес: {{ store_address }}
- -
- -
- -
- - {% for category in categories %} - - {% endfor %} -
- -
- {% for product in products %} -
- {% if product.get('is_top', False) %} - Топ - {% endif %} -
- {% if product.get('photos') and product['photos']|length > 0 %} - {{ product['name'] }} - {% else %} - No Image - {% endif %} -
-
-

{{ product['name'] }}

-
{{ "%.2f"|format(product['price']) }} {{ currency_code }}
-

{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}

-
-
- -
-
- {% endfor %} - {% if not products %} -

Товары пока не добавлены.

- {% endif %} -
-
- - - - - - - - - -
- - - - - -''' - -PRODUCT_DETAIL_TEMPLATE = ''' -
-

{{ product['name'] }}

-
-
- {% if product.get('photos') and product['photos']|length > 0 %} - {% for photo in product['photos'] %} -
-
- {{ product['name'] }} - фото {{ loop.index }} -
-
- {% endfor %} - {% else %} -
- Изображение отсутствует -
- {% endif %} -
- {% if product.get('photos') and product['photos']|length > 1 %} -
-
-
- {% endif %} -
- -
-

Категория: {{ product.get('category', 'Без категории') }}

-

Цена: {{ "%.2f"|format(product['price']) }} {{ currency_code }}

-

Описание:
{{ product.get('description', 'Описание отсутствует.')|replace('\\n', '
')|safe }}

- {% set colors = product.get('colors', []) %} - {% if colors and colors|select('ne', '')|list|length > 0 %} -

Доступные цвета/варианты: {{ colors|select('ne', '')|join(', ') }}

- {% endif %} - {% set models = product.get('models', []) %} - {% if models and models|select('ne', '')|list|length > 0 %} -

Доступные модели/объемы: {{ models|select('ne', '')|join(', ') }}

- {% endif %} -
-
- -
-
- -''' - -ORDER_TEMPLATE = ''' - - - - - - Заказ №{{ order.id }} - Мобильный мир - - -
- {% if order %} -

Ваш Заказ №{{ order.id }}

-

Дата создания: {{ order.created_at }}

- -

Товары в заказе

-
- {% for item in order.cart %} - {% set variant_info = [] %} - {% if item.color and item.color != 'N/A' %} - {% set _ = variant_info.append('Цвет: ' + item.color) %} - {% endif %} - {% if item.model and item.model != 'N/A' %} - {% set _ = variant_info.append('Модель: ' + item.model) %} - {% endif %} - {% set variant_display = variant_info | join(', ') %} - -
- {{ item.name }} -
- {{ item.name }} - {% if variant_display %} - ({{ variant_display }}) - {% endif %} - {{ "%.2f"|format(item.price) }} {{ currency_code }} × {{ item.quantity }} -
-
- {{ "%.2f"|format(item.price * item.quantity) }} {{ currency_code }} -
-
- {% endfor %} -
- -
-

Общая сумма товаров: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}

-

ИТОГО К ОПЛАТЕ: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}

-
- -
-

Статус заказа

-

Ваш текущий статус: {{ status_map_ru.get(order.status, order.status) }}

-

Этот заказ был оформлен без входа в систему.

-

Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.

-
- -
- -
- - ← Вернуться в каталог - - - - {% else %} -

Ошибка

-

Заказ с таким ID не найден.

- ← Вернуться в каталог - {% endif %} -
- - -''' - -ADMIN_TEMPLATE = ''' - - - - - - Админ-панель - Мобильный мир - - - - - - -
-
-
- Мобильный мир Logo -

Админ-панель

-
-
- Каталог - +

Админ-панель

+
+

Управление категориями

+
+ + +
+

Существующие категории

+ {% if categories %} + {% for category in categories %} +
+ {{ category.name }} (ID: {{ category.id }}) +
-
- - - {% with messages = get_flashed_messages(with_categories=true) %} - {% if messages %} - {% for category, message in messages %} -
{{ message }}
- {% endfor %} - {% endif %} - {% endwith %} - -
-

Рассылка Telegram

-
- Отправить сообщение всем пользователям бота -
-
- - - -

- Сообщение будет отправлено {{ telegram_users_count }} пользователям. -

- -
-
-
-
- -
-

История заказов

- - {% if orders %} - {% set sorted_orders = orders | sort(attribute='created_at', reverse=true) %} - {% for order in sorted_orders %} - {% set current_status = order.get('status', 'new') %} - {% set total_items = order.cart | sum(attribute='quantity') %} -
- - - Заказ №{{ order.id }} - {{ status_map_ru.get(current_status, current_status) }} - - - Дата: {{ order.created_at }} | Итого: {{ "%.2f"|format(order.total_price) }} {{ currency_code }} - - -
-

Состав заказа:

-
- {% for item in order.cart %} - {% set item_price = item.price * item.quantity %} - {% set variant_info = [] %} - {% if item.color and item.color != 'N/A' %} - {% set _ = variant_info.append('Цвет: ' + item.color) %} - {% endif %} - {% if item.model and item.model != 'N/A' %} - {% set _ = variant_info.append('Модель: ' + item.model) %} - {% endif %} - {% set variant_display = variant_info | join(', ') %} - -
- {{ item.name }} -
- {{ item.name }} - {% if variant_display %}

{{ variant_display }}

{% endif %} -
-
- {{ item.quantity }} × {{ "%.2f"|format(item.price) }} {{ currency_code }} = {{ "%.2f"|format(item_price) }} {{ currency_code }} -
-
- {% endfor %} -
-
- Общая сумма: {{ "%.2f"|format(order.total_price) }} {{ currency_code }} -
- -
-
- - - - - - Просмотр -
-
-
-
+ {% endfor %} + {% else %} +

Нет категорий.

+ {% endif %} +
+
+

Управление товарами

+
+ + + + + - - - -
-
- - -

Существующие категории:

- {% if categories %} -
- {% for category in categories %} -
- {{ category }} -
- - - -
-
- {% endfor %} -
- {% else %} -

Категорий пока нет.

- {% endif %} -
-
- -
-
-

Информация о магазине

-

Магазин работает в режиме каталога, заказы оформляются анонимно и должны быть подтверждены через WhatsApp.

-

Адрес магазина: {{ store_address }}

-

Валюта: {{ currency_name }} ({{ currency_code }})

-
-
-
- -
-

Управление товарами

-
- Добавить новый товар -
-
- - - - - - - - - - - - -

Варианты:

- - -
-
- - -
-
- - - -
-
- - -
-
- - - -
- - -
-
- - -
-
- -
-
-
- -

Список товаров:

- {% if products %} -
- {% for product in products %} -
-
-
- {% if product.get('photos') %} - - Фото - - {% else %} - Нет фото - {% endif %} -
-
-

- {{ product['name'] }} - {% if product.get('in_stock', True) %} - В наличии - {% else %} - Нет в наличии - {% endif %} - {% if product.get('is_top', False) %} - Топ - {% endif %} -

-

Категория: {{ product.get('category', 'Без категории') }}

-

Цена: {{ "%.2f"|format(product['price']) }} {{ currency_code }}

-

Описание: {{ product.get('description', 'N/A')[:100] }}{% if product.get('description', '')|length > 100 %}...{% endif %}

- {% set colors = product.get('colors', []) %} - {% set models = product.get('models', []) %} -

Цвета: {{ colors|select('ne', '')|join(', ') if colors|select('ne', '')|list|length > 0 else 'Нет' }}

-

Модели: {{ models|select('ne', '')|join(', ') if models|select('ne', '')|list|length > 0 else 'Нет' }}

-
-
- -
- -
- - - -
-
- - -
+ + + + + +

Существующие товары

+ {% if products %} + {% for product in products %} +
+ {{ product.name }} - {{ product.price }} сом
+ {{ product.description }}
+ {% if product.photos and product.photos|length > 0 %} + {% for photo in product.photos %} + {{ product.name }} + {% endfor %} + {% endif %} + +
+ {% endfor %} + {% else %} +

Нет товаров.

+ {% endif %} +
+
+

Заказы

+ {% if orders %} + {% for order in orders %} +
+ Пользователь: {{ order.user_id }}
+ Дата: {{ order.date }}
+ Товары: + {% for item in order['items'] %} + {% for product in products %} + {% if product.id == item.product_id %} + {{ item.quantity }} x {{ product.name }}
+ {% endif %} + {% endfor %} {% endfor %}
- {% else %} -

Товаров пока нет.

- {% endif %} -
- + {% endfor %} + {% else %} +

Нет заказов.

+ {% endif %}
- - + + +""" - function removeVariantInput(button) { - const group = button.closest('.variant-input-group'); - if (group) { - const container = group.parentNode; - const fieldName = group.querySelector('input').name; - const placeholder = fieldName === 'colors' ? 'Например: Цвет' : 'Например: Модель'; - - group.remove(); - - if (container && container.children.length === 0) { - const placeholderGroup = document.createElement('div'); - placeholderGroup.className = 'variant-input-group'; - placeholderGroup.innerHTML = ` - - - `; - container.appendChild(placeholderGroup); - } - } - } - - - -''' +update_event = threading.Event() @app.route('/') -def catalog(): - data = load_data() - all_products = data.get('products', []) - categories = sorted(data.get('categories', [])) - - products_in_stock = [p for p in all_products if p.get('in_stock', True)] - products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower())) - - return render_template_string( - CATALOG_TEMPLATE, - products=products_sorted, - categories=categories, - repo_id=REPO_ID, - store_address=STORE_ADDRESS, - currency_code=CURRENCY_CODE - ) - -@app.route('/product/') -def product_detail(index): - data = load_data() - all_products = data.get('products', []) - products_in_stock = [p for p in all_products if p.get('in_stock', True)] - products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower())) - +def admin_panel(): try: - product = products_sorted[index] - except IndexError: - logging.warning(f"Attempted access to non-existent or out-of-stock product with index {index}") - return "Товар не найден или отсутствует в наличии.", 404 - - products_index = index - - return render_template_string( - PRODUCT_DETAIL_TEMPLATE, - product=product, - products_index=products_index, - repo_id=REPO_ID, - currency_code=CURRENCY_CODE - ) - -@app.route('/create_order', methods=['POST']) -def create_order(): - order_data = request.get_json() - - 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": "Корзина пуста или не передана."}), 400 - - cart_items = order_data['cart'] - - total_price = 0 - processed_cart = [] - for item in cart_items: - if not all(k in item for k in ('name', 'price', 'quantity')): - logging.error(f"Invalid cart item structure received: {item}") - return jsonify({"error": "Неверный формат товара в корзине."}), 400 - try: - price = float(item['price']) - quantity = int(item['quantity']) - if price < 0 or quantity <= 0: - raise ValueError("Invalid price or quantity") - total_price += price * quantity - - photo_name = item.get('photo') - photo_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{photo_name}" if photo_name else "https://via.placeholder.com/60x60.png?text=N/A" - - processed_cart.append({ - "name": item['name'], - "price": price, - "quantity": quantity, - "color": item.get('color', 'N/A'), - "model": item.get('model', 'N/A'), - "photo": photo_name, - "photo_url": photo_url - }) - except (ValueError, TypeError) as e: - logging.error(f"Invalid price/quantity in cart item: {item}. Error: {e}") - return jsonify({"error": "Неверная цена или количество в товаре."}), 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": round(total_price, 2), - "user_info": None, - "status": "new" - } + return render_template_string(admin_html, products=data['products'], orders=data['orders'], categories=data['categories'], repo_id=REPO_ID) + except Exception as e: + logger.error(f"Ошибка в шаблоне: {e}") + return "Ошибка сервера", 500 +@app.route('/add_product', methods=['POST']) +def add_product(): try: - data = load_data() - if 'orders' not in data or not isinstance(data.get('orders'), dict): - data['orders'] = {} - - data['orders'][order_id] = new_order + name = request.form['name'] + price = float(request.form['price']) + description = request.form['description'] + category_id = int(request.form['category_id']) + photos = request.files.getlist('photo') + product_id = max((p['id'] for p in data['products']), default=0) + 1 + + photos_filenames = [] + if photos: + # Обрабатываем до 3 фото + for photo in photos[:3]: + if photo and photo.filename: + photo_filename = secure_filename(photo.filename) + temp_path = os.path.join(".", photo_filename) + photo.save(temp_path) + api = HfApi() + api.upload_file( + path_or_fileobj=temp_path, + path_in_repo=f"photos/{photo_filename}", + repo_id=REPO_ID, + repo_type="dataset", + token=HF_TOKEN_WRITE, + commit_message=f"Добавлено фото для товара {name}" + ) + os.remove(temp_path) + photos_filenames.append(photo_filename) + + data['products'].append({ + 'id': product_id, + 'name': name, + 'price': price, + 'description': description, + 'category_id': category_id, + 'photos': photos_filenames + }) save_data(data) - logging.info(f"Order {order_id} created successfully (anonymously).") - return jsonify({"order_id": order_id}), 201 - + update_event.set() + return redirect("/") except Exception as e: - logging.error(f"Failed to save order {order_id}: {e}", exc_info=True) - return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500 - -@app.route('/order/') -def view_order(order_id): - data = load_data() - order = data.get('orders', {}).get(order_id) - - 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, - status_map_ru=STATUS_MAP_RU, - repo_id=REPO_ID, - currency_code=CURRENCY_CODE) - -@app.route('/admin', methods=['GET', 'POST']) -def admin(): - data = load_data() - products = data.get('products', []) - categories = data.get('categories', []) - orders = data.get('orders', {}) - telegram_users = data.get('telegram_users', {}) + logger.error(f"Ошибка при добавл��нии товара: {e}") + return jsonify({'status': 'error', 'message': str(e)}), 500 - needs_save = False - for product in products: - if 'id' not in product: - product['id'] = str(uuid.uuid4()) - needs_save = True - if needs_save: - logging.info("Assigning unique IDs to products that were missing them.") - data['products'] = products +@app.route('/delete_product/', methods=['POST']) +def delete_product(product_id): + try: + data['products'] = [p for p in data['products'] if p['id'] != product_id] save_data(data) + update_event.set() + return jsonify({'status': 'success'}) + except Exception as e: + logger.error(f"Ошибка при удалении товара: {e}") + return jsonify({'status': 'error', 'message': str(e)}), 500 - 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 == 'send_telegram_broadcast': - message_text = request.form.get('message', '').strip() - if message_text: - if telegram_users: - user_ids = list(telegram_users.keys()) - sent_count = broadcast_message(user_ids, message_text) - flash(f"Сообщение отправлено {sent_count} из {len(user_ids)} пользователей.", 'success') - else: - flash("Нет зарегистрированных пользователей Telegram для рассылки.", 'warning') - else: - flash("Текст сообщения не может быть пустым.", 'error') - - elif action == 'update_order_status': - order_id = request.form.get('order_id') - new_status = request.form.get('new_status') - - if order_id in data['orders']: - order = data['orders'][order_id] - valid_statuses = list(STATUS_MAP_RU.keys()) - - if new_status in valid_statuses: - old_status_key = order.get('status', 'new') - - order['status'] = new_status - data['orders'][order_id] = order - save_data(data) - logging.info(f"Order {order_id} status updated from {old_status_key} to {new_status}") - flash(f"Статус заказа №{order_id} успешно изменен на '{STATUS_MAP_RU.get(new_status)}'.", 'success') - else: - flash(f"Неверный статус: {new_status}", 'error') - else: - flash(f"Заказ №{order_id} не найден.", 'error') - - return redirect(url_for('admin')) - - 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(f"Категория '{category_name}' успешно добавлена.", 'success') - elif not category_name: - logging.warning("Attempted to add empty category.") - flash("Название категории не может быть пустым.", 'error') - else: - logging.warning(f"Category '{category_name}' already exists.") - flash(f"Категория '{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(f"Категория '{category_to_delete}' удалена. {updated_count} товаров обновлено.", 'success') - else: - logging.warning(f"Attempted to delete non-existent or empty category: {category_to_delete}") - flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error') - - elif action == 'add_product': - name = request.form.get('name', '').strip() - price_str = request.form.get('price', '').replace(',', '.') - description = request.form.get('description', '').strip() - category = request.form.get('category') - photos_files = request.files.getlist('photos') - colors = [c.strip() for c in request.form.getlist('colors') if c.strip()] - models = [m.strip() for m in request.form.getlist('models') if m.strip()] - in_stock = 'in_stock' in request.form - is_top = 'is_top' in request.form - - if not name or not price_str: - flash("Название и цена товара обязательны.", 'error') - return redirect(url_for('admin')) - - try: - price = round(float(price_str), 2) - if price < 0: price = 0 - except ValueError: - flash("Неверный формат цены.", 'error') - return redirect(url_for('admin')) - - 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 in photos_files: - if uploaded_count >= photo_limit: - logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.") - flash(f"Загружено только первые {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(f"Файл {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')}{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(f"Ошибка при загрузке фото {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("HF_TOKEN (write) не настроен. Фотографии не были загружены.", "warning") - - - new_product = { - 'id': str(uuid.uuid4()), - 'name': name, 'price': price, 'description': description, - 'category': category if category in categories else 'Без категории', - 'photos': photos_list, 'colors': colors, 'models': models, - '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(f"Товар '{name}' успешно добавлен.", 'success') - - elif action == 'edit_product': - product_id = request.form.get('product_id') - if not product_id: - flash("Ошибка редактирования: ID товара не передан.", 'error') - return redirect(url_for('admin')) - - product_index = -1 - for i, p in enumerate(products): - if p.get('id') == product_id: - product_index = i - break - - if product_index == -1: - flash(f"Ошибка редактирования: товар с ID '{product_id}' не найден.", 'error') - logging.error(f"Invalid product ID '{product_id}' for editing.") - return redirect(url_for('admin')) - - product_to_edit = products[product_index] - original_name = product_to_edit.get('name', 'N/A') - - product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip() - price_str = request.form.get('price', str(product_to_edit['price'])).replace(',', '.') - product_to_edit['description'] = request.form.get('description', product_to_edit.get('description', '')).strip() - category = request.form.get('category') - product_to_edit['category'] = category if category in categories else 'Без категории' - product_to_edit['colors'] = [c.strip() for c in request.form.getlist('colors') if c.strip()] - product_to_edit['models'] = [m.strip() for m in request.form.getlist('models') if m.strip()] - product_to_edit['in_stock'] = 'in_stock' in request.form - product_to_edit['is_top'] = 'is_top' in request.form - - try: - price = round(float(price_str), 2) - if price < 0: price = 0 - product_to_edit['price'] = price - except ValueError: - logging.warning(f"Invalid price format '{price_str}' during edit of product {original_name}. Price not changed.") - flash(f"Неверный формат цены для товара '{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 in photos_files: - if uploaded_count >= photo_limit: - logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.") - flash(f"Загружено только первые {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(f"Файл {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')}{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(f"Ошибка при загрузке нового фото {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("Не удалось удалить старые фотографии с сервера. Новые фото загружены.", "warning") - product_to_edit['photos'] = new_photos_list - flash("Фотографии товара успешно обновлены.", "success") - elif uploaded_count == 0 and any(f.filename for f in photos_files): - flash("Не удалось загрузить новые фотографии (возможно, неверный формат).", "error") - elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files): - flash("HF_TOKEN (write) не настроен. Фотографии не были обновлены.", "warning") - - products[product_index] = product_to_edit - data['products'] = products - save_data(data) - logging.info(f"Product '{original_name}' (ID {product_id}) updated to '{product_to_edit['name']}'.") - flash(f"Товар '{product_to_edit['name']}' успешно обновлен.", 'success') - - elif action == 'delete_product': - product_id = request.form.get('product_id') - if not product_id: - flash("Ошибка удаления: ID товара не передан.", 'error') - return redirect(url_for('admin')) - - product_to_delete = None - for product in products: - if product.get('id') == product_id: - product_to_delete = product - break - - if product_to_delete: - product_name = product_to_delete.get('name', 'N/A') - products.remove(product_to_delete) - - photos_to_delete = product_to_delete.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(f"Не удалось удалить фото для товара '{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(f"Товар '{product_name}' удален локально, но фото не удалены с сервера (токен не задан).", "warning") - - data['products'] = products - save_data(data) - logging.info(f"Product '{product_name}' (ID {product_id}) deleted.") - flash(f"Товар '{product_name}' удален.", 'success') - else: - flash(f"Ошибка удаления: неверный ID товара '{product_id}'.", 'error') - logging.error(f"Invalid product ID '{product_id}' for deletion.") - - else: - logging.warning(f"Received unknown admin action: {action}") - flash(f"Неизвестное действие: {action}", 'warning') - - return redirect(url_for('admin')) - - except Exception as e: - logging.error(f"Error processing admin action '{action}': {e}", exc_info=True) - flash(f"Произошла внутренняя ошибка при выполнении действия '{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 = sorted(current_data.get('categories', [])) - display_orders = list(current_data.get('orders', {}).values()) - telegram_users_count = len(current_data.get('telegram_users', {})) +@app.route('/add_category', methods=['POST']) +def add_category(): + try: + name = request.form['name'] + category_id = max((c['id'] for c in data['categories']), default=0) + 1 + data['categories'].append({'id': category_id, 'name': name}) + save_data(data) + update_event.set() + return redirect("/") + except Exception as e: + logger.error(f"Ошибка при добавлении категории: {e}") + return jsonify({'status': 'error', 'message': str(e)}), 500 - return render_template_string( - ADMIN_TEMPLATE, - products=display_products, - categories=display_categories, - orders=display_orders, - status_map_ru=STATUS_MAP_RU, - repo_id=REPO_ID, - store_address=STORE_ADDRESS, - currency_code=CURRENCY_CODE, - currency_name=CURRENCY_NAME, - telegram_users_count=telegram_users_count - ) +@app.route('/delete_category/', methods=['POST']) +def delete_category(category_id): + try: + data['categories'] = [c for c in data['categories'] if c['id'] != category_id] + save_data(data) + update_event.set() + return jsonify({'status': 'success'}) + except Exception as e: + logger.error(f"Ошибка при удалении категории: {e}") + return jsonify({'status': 'error', 'message': str(e)}), 500 + +@app.route('/updates') +def sse_updates(): + def stream(): + while True: + update_event.wait() + yield "data: update\n\n" + update_event.clear() + return app.response_class(stream(), mimetype="text/event-stream") + +@app.route('/broadcast_update', methods=['POST']) +def broadcast_update(): + update_event.set() + return jsonify({'status': 'success'}) + +# Запуск +async def on_startup(_): + logger.info("Бот запущен!") + +def run_flask(): + app.run(host='0.0.0.0', port=7860, debug=True, use_reloader=False) if __name__ == '__main__': - logging.info("Application starting up. Performing initial data load/download...") - 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).") + flask_thread = threading.Thread(target=run_flask, daemon=True) + flask_thread.start() + logger.info("Flask запущен") - if TELEGRAM_BOT_TOKEN: - bot_thread = threading.Thread(target=start_bot_polling, daemon=True) - bot_thread.start() - logging.info("Telegram bot polling thread started.") - else: - logging.warning("TELEGRAM_BOT_TOKEN not set. Telegram bot features disabled.") + # Запуск периодического копирования + start_periodic_backup() - 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) + try: + asyncio.run(dp.start_polling(bot, on_startup=on_startup)) + except KeyboardInterrupt: + logger.info("Остановка") + finally: + flask_thread.join() \ No newline at end of file