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 = '''
+
{% endif %}
@@ -364,6 +455,7 @@ CATALOG_TEMPLATE = '''
{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}
Загрузка...
'; 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.price.toFixed(2)} x ${item.quantity}
+${item.price.toFixed(2)} ${currencyCode} × ${item.quantity}