from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify import json import os import logging import threading import time from datetime import datetime from huggingface_hub import HfApi, hf_hub_download from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError from werkzeug.utils import secure_filename from dotenv import load_dotenv import requests import uuid import hmac import hashlib from urllib.parse import unquote, parse_qs load_dotenv() app = Flask(__name__) app.secret_key = 'your_unique_secret_key_soola_cosmetics_67890_no_login' DATA_FILE = 'data.json' USERS_DATA_FILE = 'users.json' SYNC_FILES = [DATA_FILE, USERS_DATA_FILE] REPO_ID = "Kgshop/aiocult" HF_TOKEN_WRITE = os.getenv("HF_TOKEN") HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") BOT_TOKEN = "8337420753:AAEEAIp7k-UL49Tli5-Q6DMSN2OunB3H_CA" STORE_ADDRESS = " Алматы, «Байсат» 1 этаж, синий сектор 117-118 Бутик " CURRENCY_CODE = 'TON' CURRENCY_NAME = 'Toncoin' DOWNLOAD_RETRIES = 3 DOWNLOAD_DELAY = 5 STATUS_MAP_RU = { "new": "Новый", "paid": "Оплачен", "accepted": "Принят", "prepared": "Собран", "shipped": "Отправлен" } logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') 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': [], 'orders': {}, 'settings': {'ton_wallet_address': ''}}, f) logging.info(f"Created empty local file {file_name} because it was not found on HF.") elif file_name == USERS_DATA_FILE: with open(file_name, 'w', encoding='utf-8') as f: json.dump([], 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 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': [], 'orders': {}, 'settings': {'ton_wallet_address': ''}} 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 'settings' not in data: data['settings'] = {'ton_wallet_address': ''} 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 'orders' not in data: data['orders'] = {} if 'settings' not in data: data['settings'] = {'ton_wallet_address': ''} 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 if 'products' not in data: data['products'] = [] if 'categories' not in data: data['categories'] = [] if 'orders' not in data: data['orders'] = {} if 'settings' not in data: data['settings'] = {'ton_wallet_address': ''} with open(DATA_FILE, 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4) logging.info(f"Data successfully saved to {DATA_FILE}") upload_db_to_hf(specific_file=DATA_FILE) except Exception as e: logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True) def load_users(): default_users = {} try: with open(USERS_DATA_FILE, 'r', encoding='utf-8') as file: users_list = json.load(file) if not isinstance(users_list, list): raise json.JSONDecodeError("Users file is not a list", "", 0) logging.info(f"Local users loaded successfully from {USERS_DATA_FILE}") return {str(user['id']): user for user in users_list} except FileNotFoundError: logging.warning(f"Local file {USERS_DATA_FILE} not found. Attempting download from HF.") except json.JSONDecodeError: logging.error(f"Error decoding JSON in local {USERS_DATA_FILE}. File might be corrupt. Attempting download.") if download_db_from_hf(specific_file=USERS_DATA_FILE): try: with open(USERS_DATA_FILE, 'r', encoding='utf-8') as file: users_list = json.load(file) if not isinstance(users_list, list): logging.error(f"Downloaded {USERS_DATA_FILE} is not a list. Using default.") return default_users logging.info(f"Users loaded successfully from {USERS_DATA_FILE} after download.") return {str(user['id']): user for user in users_list} except FileNotFoundError: logging.error(f"File {USERS_DATA_FILE} still not found after download. Using default.") return default_users except json.JSONDecodeError: logging.error(f"Error decoding JSON in downloaded {USERS_DATA_FILE}. Using default.") return default_users except Exception as e: logging.error(f"Unknown error loading downloaded {USERS_DATA_FILE}: {e}. Using default.", exc_info=True) return default_users else: logging.error(f"Failed to download {USERS_DATA_FILE} from HF. Using empty default.") if not os.path.exists(USERS_DATA_FILE): try: with open(USERS_DATA_FILE, 'w', encoding='utf-8') as f: json.dump([], f) logging.info(f"Created empty local file {USERS_DATA_FILE} after failed download.") except Exception as create_e: logging.error(f"Failed to create empty local file {USERS_DATA_FILE}: {create_e}") return default_users def save_users(users_data): try: if not isinstance(users_data, dict): logging.error("Attempted to save invalid users data (not a dict). Aborting save.") return users_list = list(users_data.values()) with open(USERS_DATA_FILE, 'w', encoding='utf-8') as file: json.dump(users_list, file, ensure_ascii=False, indent=4) logging.info(f"Users data successfully saved to {USERS_DATA_FILE}") upload_db_to_hf(specific_file=USERS_DATA_FILE) except Exception as e: logging.error(f"Error saving users data to {USERS_DATA_FILE}: {e}", exc_info=True) def broadcast_new_product_notification(product, base_url): users = load_users() if not users: return text = ( f"🎉 Новый товар в каталоге! 👋\n\n" f"{product['name']}\n" f"Цена: {product['price']:.4f} {CURRENCY_CODE}\n\n" f"Посмотрите его в каталоге:\n{base_url}" ) url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage" params_base = { "text": text, "parse_mode": "HTML" } for user_id in users.keys(): params = params_base.copy() params["chat_id"] = user_id try: response = requests.get(url, params=params) result = response.json() if result.get("ok"): logging.info(f"Sent notification to {user_id}") else: logging.error(f"Error {user_id}: {result.get('description')}") except Exception as e: logging.error(f"Ex {user_id}: {e}") 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'] }}

{{ "%.4f"|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', 'Без категории') }}

Цена: {{ "%.4f"|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 }} | Статус: {{ status_map_ru.get(order.status, order.status) }}

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

{% 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 %} {{ "%.4f"|format(item.price) }} {{ currency_code }} × {{ item.quantity }}
{{ "%.4f"|format(item.price * item.quantity) }} {{ currency_code }}
{% endfor %}

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

{% if ton_wallet_address and order.status == 'new' %}

Оплата заказа

Для оплаты заказа подключите ваш TON кошелек и подтвердите транзакцию.

Статус: Ожидание подключения кошелька
{% elif order.status != 'new' %}

Заказ обработан

Текущий статус вашего заказа: {{ status_map_ru.get(order.status, order.status) }}

Спасибо за покупку!

{% else %}

Оплата не настроена

В данный момент оплата недоступна. Пожалуйста, свяжитесь с администрацией магазина.

{% endif %} ← Вернуться в каталог {% if ton_wallet_address and order.status == 'new' %} {% endif %} {% else %}

Ошибка

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

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

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

Каталог
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %}
{{ message }}
{% endfor %} {% endif %} {% endwith %}

Настройки оплаты

Пользователи, заходившие в приложение ({{ users|length }})
{% if users %} {% for user in users|sort(attribute='last_seen', reverse=true) %}
Avatar
{% endfor %} {% else %}

Пока никто не заходил в приложение.

{% endif %}

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

{% 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 }} | Итого: {{ "%.4f"|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 }} × {{ "%.4f"|format(item.price) }} = {{ "%.4f"|format(item_price) }} {{ currency_code }}
{% endfor %}
Общая сумма: {{ "%.4f"|format(order.total_price) }} {{ currency_code }}
Просмотр
{% endfor %} {% else %}

Активных заказов нет.

{% endif %}

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

Добавить новую категорию

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

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

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

{% endif %}

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

Магазин работает в режиме каталога с оплатой через TON Connect.

Адрес магазина: {{ 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', 'Без категории') }}

Цена: {{ "%.4f"|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 'Нет' }}

{% endfor %}
{% else %}

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

{% endif %}
''' @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())) try: product = products_sorted[index] except IndexError: return "Товар не найден.", 404 return render_template_string( PRODUCT_DETAIL_TEMPLATE, product=product, products_index=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: return jsonify({"error": "Empty cart"}), 400 cart_with_photos = [] for item in order_data.get('cart', []): photo_filename = item.get('photo') if photo_filename: item['photo_url'] = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{photo_filename}" else: item['photo_url'] = "https://via.placeholder.com/60x60.png?text=N/A" cart_with_photos.append(item) order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}" new_order = { "id": order_id, "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "cart": cart_with_photos, "total_price": sum(i['price'] * i['quantity'] for i in cart_with_photos), "status": "new" } data = load_data() data['orders'][order_id] = new_order save_data(data) return jsonify({"order_id": order_id}), 201 @app.route('/order/') def view_order(order_id): data = load_data() order = data.get('orders', {}).get(order_id) ton_wallet_address = data.get('settings', {}).get('ton_wallet_address', '') return render_template_string( ORDER_TEMPLATE, order=order, status_map_ru=STATUS_MAP_RU, currency_code=CURRENCY_CODE, ton_wallet_address=ton_wallet_address ) @app.route('/update_order_status_after_payment', methods=['POST']) def update_order_status_after_payment(): payload = request.get_json() order_id = payload.get('order_id') if not order_id: return jsonify({"status": "error", "message": "No order_id"}), 400 data = load_data() if order_id in data.get('orders', {}): data['orders'][order_id]['status'] = 'paid' save_data(data) logging.info(f"Order {order_id} status updated to 'paid' after client-side confirmation.") return jsonify({"status": "ok"}) else: logging.warning(f"Attempted to update status for non-existent order {order_id}.") return jsonify({"status": "error", "message": "Order not found"}), 404 def is_valid_tma_hash(init_data: str, bot_token: str) -> bool: try: parsed_data = parse_qs(init_data) received_hash = parsed_data.pop('hash', [None])[0] if not received_hash: return False data_check_string = "\n".join(f"{k}={v[0]}" for k, v in sorted(parsed_data.items())) secret_key = hmac.new("WebAppData".encode(), bot_token.encode(), hashlib.sha256).digest() calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest() return hmac.compare_digest(received_hash, calculated_hash) except: return False @app.route('/verify_tma', methods=['POST']) def verify_tma(): payload = request.get_json() init_data = payload.get('initData') if not init_data or not is_valid_tma_hash(init_data, BOT_TOKEN): return jsonify({"status": "error"}), 403 params = parse_qs(init_data) user_data = json.loads(unquote(params['user'][0])) user_id = str(user_data['id']) users = load_users() current_user_data = { 'id': user_id, 'first_name': user_data.get('first_name'), 'last_name': user_data.get('last_name'), 'username': user_data.get('username'), 'photo_url': user_data.get('photo_url'), 'last_seen': datetime.now().strftime('%Y-%m-%d %H:%M:%S') } users[user_id] = current_user_data save_users(users) return jsonify({"status": "ok", "user": users[user_id]}) @app.route('/admin', methods=['GET', 'POST']) def admin(): data = load_data() users_data = load_users() products = data.get('products', []) categories = data.get('categories', []) if request.method == 'POST': action = request.form.get('action') if action == 'save_settings': data['settings']['ton_wallet_address'] = request.form.get('ton_wallet_address', '').strip() save_data(data) flash('Адрес TON кошелька сохранен.', 'success') elif action == 'update_order_status': oid = request.form.get('order_id') if oid in data.get('orders', {}): data['orders'][oid]['status'] = request.form.get('new_status') save_data(data) flash('Статус заказа обновлен.', 'success') elif action == 'add_category': cat = request.form.get('category_name', '').strip() if cat and cat not in categories: categories.append(cat) data['categories'] = categories save_data(data) flash(f'Категория "{cat}" добавлена.', 'success') else: flash('Неверное имя категории или она уже существует.', 'error') elif action == 'delete_category': cat = request.form.get('category_name') if cat in categories: categories.remove(cat) for p in products: if p.get('category') == cat: p['category'] = 'Без категории' data['categories'] = categories data['products'] = products save_data(data) flash(f'Категория "{cat}" удалена.', 'success') elif action == 'add_product' or action == 'edit_product': try: product_id = request.form.get('product_id') if action == 'edit_product' else str(uuid.uuid4()) name = request.form.get('name', '').strip() price = float(request.form.get('price', 0)) if not name or price <= 0: flash('Название и цена обязательны.', 'error') return redirect(url_for('admin')) photos_files = request.files.getlist('photos') photos_list = [] if action == 'edit_product': existing_product = next((p for p in products if p.get('id') == product_id), None) if existing_product: photos_list = existing_product.get('photos', []) if photos_files and photos_files[0].filename: if HF_TOKEN_WRITE: api = HfApi() new_photos = [] for photo in photos_files[:10]: if photo and photo.filename: safe_name = secure_filename(photo.filename) photo_filename = f"{uuid.uuid4().hex}_{safe_name}" temp_path = f"temp_{photo_filename}" photo.save(temp_path) api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE) new_photos.append(photo_filename) os.remove(temp_path) photos_list = new_photos else: flash('HF_TOKEN_WRITE не установлен. Фото не загружены.', 'warning') 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()] product_data = { 'id': product_id, 'name': name, 'price': price, 'description': request.form.get('description', ''), 'category': request.form.get('category', 'Без категории'), 'photos': photos_list, 'colors': colors, 'models': models, 'in_stock': 'in_stock' in request.form, 'is_top': 'is_top' in request.form } if action == 'edit_product': data['products'] = [product_data if p.get('id') == product_id else p for p in products] flash(f'Товар "{name}" обновлен.', 'success') else: products.append(product_data) data['products'] = products flash(f'Товар "{name}" добавлен.', 'success') base_url = request.url_root threading.Thread(target=broadcast_new_product_notification, args=(product_data, base_url)).start() save_data(data) except Exception as e: flash(f'Произошла ошибка: {e}', 'error') elif action == 'delete_product': pid = request.form.get('product_id') initial_len = len(data['products']) data['products'] = [p for p in products if p.get('id') != pid] if len(data['products']) < initial_len: save_data(data) flash('Товар удален.', 'success') else: flash('Товар для удаления не найден.', 'error') return redirect(url_for('admin')) return render_template_string( ADMIN_TEMPLATE, products=data.get('products', []), categories=data.get('categories', []), orders=list(data.get('orders', {}).values()), users=list(users_data.values()), status_map_ru=STATUS_MAP_RU, repo_id=REPO_ID, store_address=STORE_ADDRESS, currency_code=CURRENCY_CODE, currency_name=CURRENCY_NAME, ton_wallet_address=data.get('settings', {}).get('ton_wallet_address', '') ) if __name__ == '__main__': download_db_from_hf() if HF_TOKEN_WRITE: threading.Thread(target=periodic_backup, daemon=True).start() app.run(debug=False, host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))