diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,10 +1,10 @@ -from flask import Flask, render_template_string, request, redirect, url_for, flash, jsonify + +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 -import asyncio from datetime import datetime from huggingface_hub import HfApi, hf_hub_download from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError @@ -12,32 +12,36 @@ from werkzeug.utils import secure_filename from dotenv import load_dotenv import requests import uuid +import asyncio from aiogram import Bot, Dispatcher, types -from aiogram.filters import Command -from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo +from aiogram.filters import CommandStart +from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo, InputFile +from aiogram.client.bot import DefaultBotProperties +from aiogram.enums import ParseMode + load_dotenv() app = Flask(__name__) app.secret_key = 'your_unique_secret_key_soola_cosmetics_67890_no_login' DATA_FILE = 'data.json' -file_lock = threading.Lock() + SYNC_FILES = [DATA_FILE] + REPO_ID = "Kgshop/aiocult" HF_TOKEN_WRITE = os.getenv("HF_TOKEN") HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") +BOT_TOKEN = os.getenv("BOT_TOKEN", "8283649768:AAGYWatM-nUVQirgBiBwoAtWZgzfp3QnQjY") +WEB_APP_URL = "https://shveiauto-wall.hf.space/" + + STORE_ADDRESS = " Алматы, «Байсат» 1 этаж, синий сектор 117-118 Бутик " + CURRENCY_CODE = 'KZT' CURRENCY_NAME = 'Казахстанский тенге' -BOT_TOKEN = "8283649768:AAGYWatM-nUVQirgBiBwoAtWZgzfp3QnQjY" -WEBAPP_URL = "https://shveiauto-wall.hf.space/" - -bot = Bot(token=BOT_TOKEN) -dp = Dispatcher() - DOWNLOAD_RETRIES = 3 DOWNLOAD_DELAY = 5 @@ -50,19 +54,26 @@ STATUS_MAP_RU = { logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +bot = Bot(token=BOT_TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) +dp = Dispatcher() + + def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY): if not HF_TOKEN_READ and not HF_TOKEN_WRITE: - return False + 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: - hf_hub_download( + 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", @@ -72,37 +83,51 @@ def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWN 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': {}, 'users': []}, f) - except Exception: - pass + json.dump({'products': [], 'categories': [], 'orders': {}, 'bot_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: - pass - except Exception: - pass + 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: @@ -114,121 +139,144 @@ def upload_db_to_hf(specific_file=None): token=HF_TOKEN_WRITE, commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" ) - except Exception: - pass - except Exception: - pass + 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': {}, 'users': []} - with file_lock: + default_data = {'products': [], 'categories': [], 'orders': {}, 'bot_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 'bot_users' not in data: data['bot_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.") + + 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): - raise FileNotFoundError + 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 'users' not in data: data['users'] = [] + if 'bot_users' not in data: data['bot_users'] = [] return data - except (FileNotFoundError, json.JSONDecodeError): - pass - - if download_db_from_hf(specific_file=DATA_FILE): - with file_lock: - 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 'users' not in data: data['users'] = [] - return data - except Exception: - return default_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): - with file_lock: - try: - with open(DATA_FILE, 'w', encoding='utf-8') as f: - json.dump(default_data, f) - except Exception: - pass + 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 file_lock: - try: - if not isinstance(data, dict): - return - if 'products' not in data: data['products'] = [] - if 'categories' not in data: data['categories'] = [] - if 'orders' not in data: data['orders'] = {} - if 'users' not in data: data['users'] = [] - - with open(DATA_FILE, 'w', encoding='utf-8') as file: - json.dump(data, file, ensure_ascii=False, indent=4) - threading.Thread(target=upload_db_to_hf, args=(DATA_FILE,), daemon=True).start() - except Exception: - pass - -async def broadcast_notification(message_text, photo_url=None): + 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 'bot_users' not in data: data['bot_users'] = [] + + 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) + +async def send_new_product_notification(product_name, price, photo_filename=None): data = load_data() - users = data.get('users', []) + users = data.get('bot_users', []) if not users: + logging.info("No bot users to notify about new product.") return - for chat_id in users: + logging.info(f"Sending notification about new product '{product_name}' to {len(users)} users.") + keyboard = InlineKeyboardMarkup(inline_keyboard=[ + [InlineKeyboardButton(text="Посмотреть новинку", web_app=WebAppInfo(url=WEB_APP_URL))] + ]) + message_text = f"✨ Поступление нового товара! ✨\n\nВ нашем каталоге появился {product_name} по цене {price} {CURRENCY_CODE}." + + for user_id in users: try: - if photo_url: - await bot.send_photo(chat_id=chat_id, photo=photo_url, caption=message_text) + if photo_filename: + photo_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{photo_filename}" + await bot.send_photo(chat_id=user_id, photo=photo_url, caption=message_text, reply_markup=keyboard) else: - await bot.send_message(chat_id=chat_id, text=message_text) + await bot.send_message(user_id, message_text, reply_markup=keyboard) + await asyncio.sleep(0.1) except Exception as e: - logging.error(f"Failed to send notification to {chat_id}: {e}") - -def run_async_notification(message, photo=None): - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - loop.run_until_complete(broadcast_notification(message, photo)) - loop.close() + logging.warning(f"Could not send notification to user {user_id}: {e}") -@dp.message(Command("start")) -async def cmd_start(message: types.Message): +def run_async_task(coro): + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + return loop.run_until_complete(coro) + +@dp.message(CommandStart()) +async def send_welcome(message: types.Message): user_id = message.from_user.id - data = load_data() - if user_id not in data.get('users', []): - data['users'].append(user_id) + if user_id not in data.get('bot_users', []): + data.setdefault('bot_users', []).append(user_id) save_data(data) + logging.info(f"New bot user registered: {user_id} ({message.from_user.full_name})") - kb = InlineKeyboardMarkup(inline_keyboard=[ - [InlineKeyboardButton(text="📱 Открыть магазин", web_app=WebAppInfo(url=WEBAPP_URL))] + keyboard = InlineKeyboardMarkup(inline_keyboard=[ + [InlineKeyboardButton(text="Перейти в каталог", web_app=WebAppInfo(url=WEB_APP_URL))] ]) - - await message.answer( - "Добро пожаловать в Мобильный мир! 📱\n\n" - "Нажмите кнопку ниже, чтобы открыть наш каталог и совершить покупки.", - reply_markup=kb - ) + await message.answer("Добро пожаловать в Мобильный мир! Нажмите кнопку ниже, чтобы открыть наш каталог.", reply_markup=keyboard) -async def start_bot(): - await bot.delete_webhook(drop_pending_updates=True) +async def main_bot(): await dp.start_polling(bot) -def run_bot_loop(): - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - loop.run_until_complete(start_bot()) CATALOG_TEMPLATE = ''' @@ -237,13 +285,13 @@ CATALOG_TEMPLATE = ''' Мобильный мир - Каталог - + @@ -322,13 +409,16 @@ CATALOG_TEMPLATE = '''
- Logo + Мобильный мир Logo

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

-
Наш адрес: {{ store_address }}
@@ -356,7 +446,8 @@ CATALOG_TEMPLATE = '''
{% if product.get('photos') and product['photos']|length > 0 %} {{ product['name'] }} + alt="{{ product['name'] }}" + loading="lazy"> {% else %} No Image {% endif %} @@ -364,6 +455,7 @@ CATALOG_TEMPLATE = '''

{{ product['name'] }}

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

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

{% endfor %} + {% if not products %} +

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

+ {% endif %}
@@ -408,17 +503,17 @@ CATALOG_TEMPLATE = ''' Итого: 0.00 {{ currency_code }}
-
- @@ -432,49 +527,66 @@ CATALOG_TEMPLATE = ''' const currencyCode = '{{ currency_code }}'; let selectedProductIndex = null; let cart = JSON.parse(localStorage.getItem('soolaCart') || '[]'); - - const tg = window.Telegram.WebApp; - tg.ready(); - - function initTelegramAuth() { - const user = tg.initDataUnsafe.user; - if (user) { - const userNameEl = document.getElementById('userName'); - const userAvatarEl = document.getElementById('userAvatar'); - - if (user.first_name) { - userNameEl.textContent = user.first_name; - userNameEl.style.display = 'block'; - } - if (user.photo_url) { - userAvatarEl.src = user.photo_url; - userAvatarEl.style.display = 'block'; - } - if (tg.colorScheme === 'dark') { - document.body.classList.add('dark-mode'); - } + + function toggleTheme() { + document.body.classList.toggle('dark-mode'); + const icon = document.querySelector('.theme-toggle i'); + const isDarkMode = document.body.classList.contains('dark-mode'); + icon.classList.toggle('fa-moon', !isDarkMode); + icon.classList.toggle('fa-sun', isDarkMode); + localStorage.setItem('soolaTheme', isDarkMode ? 'dark' : 'light'); + } + + function applyInitialTheme() { + const savedTheme = localStorage.getItem('soolaTheme'); + const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; + + if (savedTheme === 'dark' || (!savedTheme && prefersDark)) { + document.body.classList.add('dark-mode'); + const icon = document.querySelector('.theme-toggle i'); + if (icon) icon.classList.replace('fa-moon', 'fa-sun'); + } else { + const icon = document.querySelector('.theme-toggle i'); + if (icon) icon.classList.replace('fa-sun', 'fa-moon'); } } function openModal(index) { loadProductDetails(index); const modal = document.getElementById('productModal'); - if (modal) modal.style.display = "block"; + if (modal) { + modal.style.display = "block"; + document.body.style.overflow = 'hidden'; + } } function closeModal(modalId) { const modal = document.getElementById(modalId); - if (modal) modal.style.display = "none"; + if (modal) { + modal.style.display = "none"; + } + const anyModalOpen = document.querySelector('.modal[style*="display: block"]'); + if (!anyModalOpen) { + document.body.style.overflow = 'auto'; + } } function loadProductDetails(index) { const modalContent = document.getElementById('modalContent'); + if (!modalContent) return; modalContent.innerHTML = '

Загрузка...

'; fetch('/product/' + index) - .then(response => response.text()) + .then(response => { + if (!response.ok) throw new Error(`Ошибка ${response.status}: ${response.statusText}`); + return response.text(); + }) .then(data => { modalContent.innerHTML = data; initializeSwiper(); + }) + .catch(error => { + console.error('Ошибка загрузки деталей продукта:', error); + modalContent.innerHTML = `

Не удалось загрузить информацию о товаре. ${error.message}

`; }); } @@ -485,8 +597,10 @@ CATALOG_TEMPLATE = ''' slidesPerView: 1, spaceBetween: 20, loop: true, + grabCursor: true, pagination: { el: '.swiper-pagination', clickable: true }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, + zoom: { maxRatio: 3, containerClass: 'swiper-zoom-container' }, autoplay: { delay: 5000, disableOnInteraction: true, }, }); } @@ -496,7 +610,9 @@ CATALOG_TEMPLATE = ''' const select = document.getElementById(selectId); const label = document.getElementById(labelId); const validVariants = variants ? variants.filter(v => v && v.trim() !== "") : []; + select.innerHTML = ''; + if (validVariants.length > 0) { validVariants.forEach(variant => { const option = document.createElement('option'); @@ -512,25 +628,51 @@ CATALOG_TEMPLATE = ''' } } + function openQuantityModal(index) { selectedProductIndex = index; const product = products[index]; + if (!product) { + console.error("Product not found for index:", index); + alert("Ошибка: товар не найден."); + return; + } + setupVariantSelect('colorSelect', 'colorLabel', product.colors); - setupVariantSelect('modelSelect', 'modelLabel', product.models); + setupVariantSelect('modelSelect', 'modelLabel', product.models); // NEW MODEL SETUP + document.getElementById('quantityInput').value = 1; - document.getElementById('quantityModal').style.display = 'block'; + const modal = document.getElementById('quantityModal'); + if(modal) { + modal.style.display = 'block'; + document.body.style.overflow = 'hidden'; + } } function confirmAddToCart() { if (selectedProductIndex === null) return; - const quantity = parseInt(document.getElementById('quantityInput').value); + + const quantityInput = document.getElementById('quantityInput'); + const quantity = parseInt(quantityInput.value); const colorSelect = document.getElementById('colorSelect'); const modelSelect = document.getElementById('modelSelect'); + const color = colorSelect.style.display !== 'none' && colorSelect.value ? colorSelect.value : 'N/A'; - const model = modelSelect.style.display !== 'none' && modelSelect.value ? modelSelect.value : 'N/A'; + const model = modelSelect.style.display !== 'none' && modelSelect.value ? modelSelect.value : 'N/A'; // NEW MODEL + + if (isNaN(quantity) || quantity <= 0) { + alert("Пожалуйста, укажите корректное количество (больше 0)."); + quantityInput.focus(); + return; + } + const product = products[selectedProductIndex]; + if (!product) { + alert("Ошибка добавления: товар не найден."); + return; + } - const cartItemId = `${product.name}-${color}-${model}`; + const cartItemId = `${product.name}-${color}-${model}`; // Include model in unique ID const existingItemIndex = cart.findIndex(item => item.id === cartItemId); if (existingItemIndex > -1) { @@ -543,20 +685,24 @@ CATALOG_TEMPLATE = ''' photo: product.photos && product.photos.length > 0 ? product.photos[0] : null, quantity: quantity, color: color, - model: model + model: model // NEW }); } + localStorage.setItem('soolaCart', JSON.stringify(cart)); closeModal('quantityModal'); updateCartButton(); - showNotification(`${product.name} добавлен!`); + showNotification(`${product.name} добавлен в корзину!`); } function updateCartButton() { const cartCountElement = document.getElementById('cart-count'); const cartButton = document.getElementById('cart-button'); + if (!cartCountElement || !cartButton) return; + let totalItems = 0; cart.forEach(item => { totalItems += item.quantity; }); + if (totalItems > 0) { cartCountElement.textContent = totalItems; cartButton.style.display = 'flex'; @@ -569,7 +715,10 @@ CATALOG_TEMPLATE = ''' function openCartModal() { const cartContent = document.getElementById('cartContent'); const cartTotalElement = document.getElementById('cartTotal'); + if (!cartContent || !cartTotalElement) return; + let total = 0; + if (cart.length === 0) { cartContent.innerHTML = '

Ваша корзина пуста.

'; cartTotalElement.textContent = '0.00'; @@ -577,27 +726,35 @@ CATALOG_TEMPLATE = ''' cartContent.innerHTML = cart.map(item => { const itemTotal = item.price * item.quantity; total += itemTotal; - const photoUrl = item.photo ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` : 'https://via.placeholder.com/60x60.png?text=N/A'; - let variantText = []; - if (item.color !== 'N/A') variantText.push(item.color); - if (item.model !== 'N/A') variantText.push(item.model); - const variantDisplay = variantText.length > 0 ? `(${variantText.join(', ')})` : ''; + const photoUrl = item.photo + ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` + : 'https://via.placeholder.com/60x60.png?text=N/A'; + let variantText = []; + if (item.color !== 'N/A') variantText.push(`Цвет: ${item.color}`); + if (item.model !== 'N/A') variantText.push(`Модель: ${item.model}`); // NEW MODEL DISPLAY + + const variantDisplay = variantText.length > 0 ? ` (${variantText.join(', ')})` : ''; + return `
- -
+ ${item.name} +
${item.name}${variantDisplay} -

${item.price.toFixed(2)} x ${item.quantity}

+

${item.price.toFixed(2)} ${currencyCode} × ${item.quantity}

- ${itemTotal.toFixed(2)} - + ${itemTotal.toFixed(2)} ${currencyCode} +
`; }).join(''); cartTotalElement.textContent = total.toFixed(2); } - document.getElementById('cartModal').style.display = 'block'; + const modal = document.getElementById('cartModal'); + if (modal) { + modal.style.display = 'block'; + document.body.style.overflow = 'hidden'; + } } function removeFromCart(itemId) { @@ -608,70 +765,198 @@ CATALOG_TEMPLATE = ''' } function clearCart() { - cart = []; - localStorage.removeItem('soolaCart'); - openCartModal(); - updateCartButton(); + if (confirm("Вы уверены, что хотите очистить корзину?")) { + cart = []; + localStorage.removeItem('soolaCart'); + openCartModal(); + updateCartButton(); + } } function formulateOrder() { - if (cart.length === 0) return; + if (cart.length === 0) { + alert("Корзина пуста! Добавьте товары перед формированием заказа."); + return; + } + + const orderData = { + cart: cart + }; + + const formulateButton = document.querySelector('.formulate-order-button'); + if (formulateButton) formulateButton.disabled = true; + + showNotification("Формируем заказ...", 5000); + fetch('/create_order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ cart: cart }) + body: JSON.stringify(orderData) + }) + .then(response => { + if (!response.ok) { + return response.json().then(err => { throw new Error(err.error || 'Не удалось создать заказ'); }); + } + return response.json(); }) - .then(r => r.json()) .then(data => { if (data.order_id) { localStorage.removeItem('soolaCart'); cart = []; + updateCartButton(); + closeModal('cartModal'); window.location.href = `/order/${data.order_id}`; + } else { + throw new Error('Не получен ID заказа от сервера.'); } + }) + .catch(error => { + console.error('Ошибка при формировании заказа:', error); + alert(`Ошибка: ${error.message}`); + if (formulateButton) formulateButton.disabled = false; }); } + function filterProducts() { const searchTerm = document.getElementById('search-input').value.toLowerCase().trim(); - const activeCategory = document.querySelector('.category-filter.active').dataset.category; + const activeCategoryButton = document.querySelector('.category-filter.active'); + const activeCategory = activeCategoryButton ? activeCategoryButton.dataset.category : 'all'; + const grid = document.getElementById('products-grid'); + let visibleProducts = 0; + + const existingNoResults = grid.querySelector('.no-results-message'); + if (existingNoResults) existingNoResults.remove(); + + const allProductElements = document.querySelectorAll('.products-grid .product'); + if (allProductElements.length === 0 && products.length > 0) return; // Wait for initial render if products exist + document.querySelectorAll('.products-grid .product').forEach(productElement => { const name = productElement.getAttribute('data-name'); + const description = productElement.getAttribute('data-description'); const category = productElement.getAttribute('data-category'); - const matchesSearch = !searchTerm || name.includes(searchTerm); + + const matchesSearch = !searchTerm || name.includes(searchTerm) || description.includes(searchTerm); const matchesCategory = activeCategory === 'all' || category === activeCategory; - productElement.style.display = (matchesSearch && matchesCategory) ? 'flex' : 'none'; + + if (matchesSearch && matchesCategory) { + productElement.style.display = 'flex'; + visibleProducts++; + } else { + productElement.style.display = 'none'; + } }); + + if (visibleProducts === 0) { + if (products.length > 0) { + const p = document.createElement('p'); + p.className = 'no-results-message'; + p.textContent = 'По вашему запросу товары не найдены.'; + grid.appendChild(p); + } else if (!grid.querySelector('.no-results-message')) { + const p = document.createElement('p'); + p.className = 'no-results-message'; + p.textContent = 'Товары пока не добавлены.'; + grid.appendChild(p); + } + } } - function showNotification(message) { - const placeholder = document.getElementById('notification-placeholder'); + function setupFilters() { + const searchInput = document.getElementById('search-input'); + const categoryFilters = document.querySelectorAll('.category-filter'); + + if(searchInput) searchInput.addEventListener('input', filterProducts); + + categoryFilters.forEach(filter => { + filter.addEventListener('click', function() { + categoryFilters.forEach(f => f.classList.remove('active')); + this.classList.add('active'); + filterProducts(); + }); + }); + filterProducts(); + } + + function showNotification(message, duration = 3000) { + let placeholder = document.getElementById('notification-placeholder'); + if (!placeholder) { + const newPlaceholder = document.createElement('div'); + newPlaceholder.id = 'notification-placeholder'; + newPlaceholder.style.position = 'fixed'; + newPlaceholder.style.bottom = '70px'; + newPlaceholder.style.left = '50%'; + newPlaceholder.style.transform = 'translateX(-50%)'; + newPlaceholder.style.zIndex = '1002'; + document.body.appendChild(newPlaceholder); + placeholder = newPlaceholder; + } + + const notification = document.createElement('div'); notification.className = 'notification'; notification.textContent = message; placeholder.appendChild(notification); + void notification.offsetWidth; + notification.classList.add('show'); + setTimeout(() => { notification.classList.remove('show'); - setTimeout(() => notification.remove(), 500); - }, 3000); + notification.addEventListener('transitionend', () => notification.remove()); + }, duration); } + + function initTelegramWebApp() { + if (window.Telegram && window.Telegram.WebApp) { + const tg = window.Telegram.WebApp; + tg.ready(); + + if (tg.initDataUnsafe && tg.initDataUnsafe.user) { + const user = tg.initDataUnsafe.user; + const userInfoDiv = document.getElementById('user-info'); + const userAvatarImg = document.getElementById('user-avatar'); + const userNameSpan = document.getElementById('user-name'); + + if (userInfoDiv && userAvatarImg && userNameSpan) { + if (user.photo_url) { + userAvatarImg.src = user.photo_url; + } else { + userAvatarImg.style.display = 'none'; + } + userNameSpan.textContent = user.first_name + (user.last_name ? ' ' + user.last_name : ''); + userInfoDiv.style.display = 'flex'; + } + } else { + console.log("Telegram Web App user data not found."); + } + } else { + console.log("Telegram Web App script not loaded or not in Telegram environment."); + } + } document.addEventListener('DOMContentLoaded', () => { - initTelegramAuth(); + applyInitialTheme(); updateCartButton(); - document.getElementById('search-input').addEventListener('input', filterProducts); - document.querySelectorAll('.category-filter').forEach(filter => { - filter.addEventListener('click', function() { - document.querySelectorAll('.category-filter').forEach(f => f.classList.remove('active')); - this.classList.add('active'); - filterProducts(); - }); + setupFilters(); + initTelegramWebApp(); + + window.addEventListener('click', function(event) { + if (event.target.classList.contains('modal')) { + closeModal(event.target.id); + } + }); + + window.addEventListener('keydown', function(event) { + if (event.key === 'Escape') { + document.querySelectorAll('.modal[style*="display: block"]').forEach(modal => { + closeModal(modal.id); + }); + } }); - window.onclick = function(event) { - if (event.target.classList.contains('modal')) closeModal(event.target.id); - } }); + @@ -685,18 +970,21 @@ PRODUCT_DETAIL_TEMPLATE = ''' {% 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 %} @@ -706,8 +994,14 @@ PRODUCT_DETAIL_TEMPLATE = '''

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

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

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

- {% if product.get('colors') %}

Цвета: {{ product.get('colors')|join(', ') }}

{% endif %} - {% if product.get('models') %}

Модели: {{ product.get('models')|join(', ') }}

{% endif %} + {% 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 = ''' @@ -723,46 +1022,114 @@ ORDER_TEMPLATE = ''' - Заказ №{{ order.id }} + Заказ №{{ order.id }} - Мобильный мир +
-

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

-

Статус: {{ status_map_ru.get(order.status, order.status) }}

-
- {% for item in order.cart %} -
- -
- {{ item.name }} -

{{ item.color if item.color != 'N/A' else '' }} {{ item.model if item.model != 'N/A' else '' }}

- {{ "%.2f"|format(item.price) }} x {{ item.quantity }} + {% 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 }} +
-
{{ "%.2f"|format(item.price * item.quantity) }}
-
- {% endfor %} -
-

Итого: {{ "%.2f"|format(order.total_price) }} {{ 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 %}
- ''' @@ -773,71 +1140,532 @@ ADMIN_TEMPLATE = ''' - Админ-панель + Админ-панель - Мобильный мир + +
-

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

- Каталог +
+
+ Мобильный мир Logo +

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

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

Добавить товар

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

Заказы

- {% for order in orders %} -
- Заказ №{{ order.id }} - {{ status_map_ru.get(order.status) }} -
- - - - -
+
+

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

+ + {% 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 'Нет' }}

+
+
+ +
+ +
+ + + +
+
+ + +
+ {% endfor %}
- {% 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())) @@ -856,16 +1684,19 @@ def product_detail(index): 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 + 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=index, + products_index=products_index, repo_id=REPO_ID, currency_code=CURRENCY_CODE ) @@ -873,118 +1704,462 @@ def product_detail(index): @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 + + 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: - price = float(item['price']) - quantity = int(item['quantity']) - total_price += price * quantity - photo_name = item.get('photo') - processed_cart.append({ - "name": item['name'], - "price": price, - "quantity": quantity, - "color": item.get('color', 'N/A'), - "model": item.get('model', 'N/A'), - "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{photo_name}" if photo_name else "" - }) + 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": datetime.now().strftime('%Y-%m-%d %H:%M:%S'), + "created_at": order_timestamp, "cart": processed_cart, "total_price": round(total_price, 2), + "user_info": None, "status": "new" } - data = load_data() - data['orders'][order_id] = new_order - save_data(data) - try: - msg = f"🆕 Новый заказ №{order_id}\nСумма: {new_order['total_price']} {CURRENCY_CODE}" - threading.Thread(target=run_async_notification, args=(msg,), daemon=True).start() - except Exception: - pass + 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 (anonymously).") + return jsonify({"order_id": order_id}), 201 - 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": "Ошибка сервера при сохранении заказа."}), 500 @app.route('/order/') def view_order(order_id): data = load_data() order = data.get('orders', {}).get(order_id) - return render_template_string(ORDER_TEMPLATE, order=order, status_map_ru=STATUS_MAP_RU, currency_code=CURRENCY_CODE) + + 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 = sorted(list(data.get('orders', {}).values()), key=lambda x: x['created_at'], reverse=True) + orders = data.get('orders', {}) + + 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 + save_data(data) + + + if 'orders' not in data or not isinstance(data.get('orders'), dict): + data['orders'] = {} if request.method == 'POST': action = request.form.get('action') - - if action == 'add_product': - name = request.form.get('name') - price = float(request.form.get('price')) - description = request.form.get('description') - category = request.form.get('category') - photos = request.files.getlist('photos') - colors = [c.strip() for c in request.form.get('colors', '').split(',') if c.strip()] - models = [m.strip() for m in request.form.get('models', '').split(',') if m.strip()] - - photos_list = [] - if photos and HF_TOKEN_WRITE: - api = HfApi() - for photo in photos: - if photo.filename: - safe_name = secure_filename(name.replace(' ', '_'))[:20] - fname = f"{safe_name}_{uuid.uuid4().hex[:6]}{os.path.splitext(photo.filename)[1]}" - photo.save(fname) - api.upload_file(path_or_fileobj=fname, path_in_repo=f"photos/{fname}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE) - photos_list.append(fname) - os.remove(fname) - - new_product = { - 'id': str(uuid.uuid4()), - 'name': name, 'price': price, 'description': description, - 'category': category, 'photos': photos_list, 'colors': colors, 'models': models, - 'in_stock': 'in_stock' in request.form, 'is_top': 'is_top' in request.form - } - products.append(new_product) - data['products'] = products - save_data(data) - - notify_msg = f"🔥 Новинка!\n\n🛍 {name}\n💰 Цена: {price} {CURRENCY_CODE}\n\nУспейте заказать!" - photo_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{photos_list[0]}" if photos_list else None - threading.Thread(target=run_async_notification, args=(notify_msg, photo_url), daemon=True).start() - - flash('Товар добавлен и уведомления отправлены', 'success') - - elif action == 'update_order_status': - oid = request.form.get('order_id') - status = request.form.get('new_status') - if oid in data['orders']: - data['orders'][oid]['status'] = status + logging.info(f"Admin action received: {action}") + + try: + if 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') + first_photo_filename = photos_list[0] if photos_list else None + run_async_task(send_new_product_notification(name, price, first_photo_filename)) + + + 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')) - return redirect(url_for('admin')) - return render_template_string(ADMIN_TEMPLATE, products=products, categories=categories, orders=orders, status_map_ru=STATUS_MAP_RU) + 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()) + + 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 + ) 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: - threading.Thread(target=periodic_backup, daemon=True).start() - - threading.Thread(target=run_bot_loop, daemon=True).start() + 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).") + bot_thread = threading.Thread(target=run_async_task, args=(main_bot(),), daemon=True) + bot_thread.start() + logging.info("Telegram bot polling started in a separate thread.") + port = int(os.environ.get('PORT', 7860)) - app.run(debug=False, host='0.0.0.0', port=port) \ No newline at end of file + 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)