Spaces:
Sleeping
Sleeping
Update app.py
Browse files123455 unmodified lines1112131415164 unmodified lines212223242526277 unmodified lines35363738394029 unmodified lines70717273747513 unmodified lines89909192939495963 unmodified lines10010110210310410512 unmodified lines1181191201211221236 unmodified lines1301311321331341354 unmodified lines14014114214314414533 unmodified lines1791801811821831848 unmodified lines19319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624733 unmodified lines28128228328428528628728828929029129229329425 unmodified lines3203213223233243253263273283295 unmodified lines335336337338339340341342106 unmodified lines449450451452453454455456117 unmodified lines57457557657757857958052 unmodified lines63363463563663763863964064164264364464564668 unmodified lines7157167177187197207211 unmodified line72372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777849 unmodified lines8288298308318328338348358368378388398408418428438448458468478488498503 unmodified lines8548558568578588598608618628638648656 unmodified lines87287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590635 unmodified lines94294394494594694794894995095195295395495536 unmodified lines9929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310742 unmodified lines1077107810791080108110821083380 unmodified lines14641465146614671468146912 unmodified lines148214831484148514861487148814891490149114921493149414954 unmodified lines150015011502150315041505150610 unmodified lines15171518151915201521152215231524152515261527152815291530153134 unmodified lines15661567156815691570157115721573157415751576157715787 unmodified lines158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161024 unmodified lines16351636163716381639164011 unmodified lines16521653165416551656165716 unmodified lines167416751676167716781679168017 unmodified lines16981699170017011702170317047 unmodified lines17121713171417151716171717181719172017211722172314 unmodified lines1738173917401741174217438 unmodified lines1752175317541755175617571758175920 unmodified lines17801781178217831784178517865 unmodified lines1792179317941795179617976 unmodified lines1804180518061807180818091810181118121813181418151816181718181819182018211822182318246 unmodified lines1831183218331834183518361837183818392 unmodified lines1842184318441845184618471848184918501851185218531854185518561857185818591860186118625 unmodified lines186818691870187118721873from flask import Flask, render_template_string, request, redirect, url_for, session, send_file, flashimport jsonimport osimport logging5 unmodified linesfrom werkzeug.utils import secure_filenamefrom dotenv import load_dotenvimport requests # Added for more specific network error handlingload_dotenv()4 unmodified linesSYNC_FILES = [DATA_FILE, USERS_FILE]REPO_ID = "Kgshop/Soola"HF_TOKEN_WRITE = os.getenv("HF_TOKEN")HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")7 unmodified lineslogging.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: # Allow read with write token toologging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.")29 unmodified linesexcept 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.")success = False # Mark as failed for this specific file, but don't stop othersbreak # No point retrying a 404else:13 unmodified lineslogging.info(f"Download process finished. Overall success: {all_successful}")return all_successfuldef load_data():default_data = {'products': [], 'categories': []}try:with open(DATA_FILE, 'r', encoding='utf-8') as file:data = json.load(file)3 unmodified linesraise FileNotFoundError # Treat as missing to trigger downloadif 'products' not in data: data['products'] = []if 'categories' not in data: data['categories'] = []return dataexcept FileNotFoundError:logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.")12 unmodified linesreturn default_dataif 'products' not in data: data['products'] = []if 'categories' not in data: data['categories'] = []return dataexcept FileNotFoundError:logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.")6 unmodified linesreturn default_dataelse:logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.")return default_data # Return empty structure in memorydef save_data(data):4 unmodified linesreturnif 'products' not in data: data['products'] = []if 'categories' not in data: data['categories'] = []with open(DATA_FILE, 'w', encoding='utf-8') as file:json.dump(data, file, ensure_ascii=False, indent=4)33 unmodified linesreturn default_userselse:logging.error(f"Failed to download {USERS_FILE} from HF after retries. Using empty default user structure.")return default_users # Return empty structure in memorydef save_users(users):8 unmodified linesexcept Exception as e:logging.error(f"Error saving user data to {USERS_FILE}: {e}", exc_info=True)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.")returntry:api = HfApi()files_to_upload = [specific_file] if specific_file else SYNC_FILESlogging.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 = 1800logging.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.")@app.route('/')def catalog():data = load_data()all_products = data.get('products', [])categories = data.get('categories', [])is_authenticated = 'user' in sessionproducts_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()))catalog_html = '''<!DOCTYPE html><html lang="ru"><head>33 unmodified linesbody.dark-mode .category-filter { background-color: #253f37; border-color: #2c4a41; color: #97b7ae; }.category-filter.active, .category-filter:hover { background-color: #1C6758; color: white; border-color: #1C6758; box-shadow: 0 2px 10px rgba(28, 103, 88, 0.3); }body.dark-mode .category-filter.active, body.dark-mode .category-filter:hover { background-color: #3D8361; border-color: #3D8361; color: #1a2b26; box-shadow: 0 2px 10px rgba(61, 131, 97, 0.4); }.products-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; padding: 10px; }.product { background: #fff; border-radius: 15px; padding: 0; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; height: 100%; border: 1px solid #e1f0e9;}body.dark-mode .product { background: #253f37; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); border-color: #2c4a41; }.product:hover { transform: translateY(-5px) scale(1.02); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12); }body.dark-mode .product:hover { box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3); }.product-image { width: 100%; aspect-ratio: 1 / 1; background-color: #fff; border-radius: 10px 10px 0 0; overflow: hidden; display: flex; justify-content: center; align-items: center; margin-bottom: 0; }.product-image img { max-width: 100%; max-height: 100%; object-fit: contain; transition: transform 0.3s ease; }.product-image img:hover { transform: scale(1.08); }.product-info { padding: 15px; flex-grow: 1; display: flex; flex-direction: column; justify-content: center; }.product h2 { font-size: 1.1rem; font-weight: 600; margin: 0 0 8px 0; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #2d332f; }body.dark-mode .product h2 { color: #c8d8d3; }25 unmodified lines.cart-item:last-child { border-bottom: none; }.cart-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #fff; padding: 5px; grid-column: 1; }.cart-item-details { grid-column: 2; }.cart-item-details strong { display: block; margin-bottom: 5px; }.cart-item-price { font-size: 0.9rem; color: #44524c; }body.dark-mode .cart-item-price { color: #8aa39a; }.cart-item-total { font-weight: bold; text-align: right; grid-column: 3; }.cart-item-remove { grid-column: 4; background:none; border:none; color:#f56565; cursor:pointer; font-size: 1.3em; padding: 5px; line-height: 1; }.cart-item-remove:hover { color: #c53030; }.quantity-input, .color-select { width: 100%; max-width: 180px; padding: 10px; border: 1px solid #d1e7dd; border-radius: 8px; font-size: 1rem; margin: 10px 0; box-sizing: border-box; }5 unmodified lines.cart-actions .product-button { width: auto; flex-grow: 1; }.clear-cart { background-color: #7a8d85; }.clear-cart:hover { background-color: #5e6e68; box-shadow: 0 4px 15px rgba(94, 110, 104, 0.4); }.order-button { background-color: #38a169; }.order-button:hover { background-color: #2f855a; box-shadow: 0 4px 15px rgba(47, 133, 90, 0.4); }.notification { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background-color: #38a169; color: white; padding: 10px 20px; border-radius: 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); z-index: 1002; opacity: 0; transition: opacity 0.5s ease; font-size: 0.9rem;}.notification.show { opacity: 1;}.no-results-message { grid-column: 1 / -1; text-align: center; padding: 40px; font-size: 1.1rem; color: #5e6e68; }106 unmodified lines<button class="product-button clear-cart" onclick="clearCart()"><i class="fas fa-trash"></i> Очистить корзину</button><button class="product-button order-button" onclick="orderViaWhatsApp()"><i class="fab fa-whatsapp"></i> Заказать через WhatsApp</button></div></div>117 unmodified linesfunction openQuantityModal(index) {if (!isAuthenticated) {alert('Пожалуйста, войдите в систему, чтобы добавить товар в корзину.');window.location.href = '/login';return;}selectedProductIndex = index;52 unmodified linesreturn;}const cartItemId = `${product.name}-${color}`;const existingItemIndex = cart.findIndex(item => item.id === cartItemId);if (existingItemIndex > -1) {cart[existingItemIndex].quantity += quantity;} else {cart.push({id: cartItemId,name: product.name,price: product.price,photo: product.photos && product.photos.length > 0 ? product.photos[0] : null,68 unmodified linesfunction removeFromCart(itemId) {cart = cart.filter(item => item.id !== itemId);localStorage.setItem('soolaCart', JSON.stringify(cart));openCartModal();updateCartButton();}1 unmodified lineif (confirm("Вы уверены, что хотите очистить корзину?")) {cart = [];localStorage.removeItem('soolaCart');openCartModal();updateCartButton();}}function orderViaWhatsApp() {if (cart.length === 0) {alert("Корзина пуста! Добавьте товары перед заказом.");return;}let total = 0;let orderText = "🛍️ *Новый Заказ от Soola Cosmetics* 🛍️%0A";orderText += "----------------------------------------%0A";orderText += "*Детали заказа:*%0A";orderText += "----------------------------------------%0A";cart.forEach((item, index) => {const itemTotal = item.price * item.quantity;total += itemTotal;const colorText = item.color !== 'N/A' ? ` (${item.color})` : '';orderText += `${index + 1}. *${item.name}*${colorText}%0A`;orderText += ` Кол-во: ${item.quantity}%0A`;orderText += ` Цена: ${item.price.toFixed(2)} ${currencyCode}%0A`;orderText += ` *Сумма: ${itemTotal.toFixed(2)} ${currencyCode}*%0A%0A`;});orderText += "----------------------------------------%0A";orderText += `*ИТОГО: ${total.toFixed(2)} ${currencyCode}*%0A`;orderText += "----------------------------------------%0A";if (userInfo && userInfo.login) {orderText += "*Данные клиента:*%0A";orderText += `Имя: ${userInfo.first_name || ''} ${userInfo.last_name || ''}%0A`;orderText += `Логин: ${userInfo.login}%0A`;if (userInfo.phone) {orderText += `Телефон: ${userInfo.phone}%0A`;}orderText += `Страна: ${userInfo.country || 'Не указана'}%0A`;orderText += `Город: ${userInfo.city || 'Не указан'}%0A`;} else {orderText += "*Клиент не авторизован*%0A";}orderText += "----------------------------------------%0A";const now = new Date();const dateTimeString = now.toLocaleString('ru-RU', { dateStyle: 'short', timeStyle: 'short' });orderText += `Дата заказа: ${dateTimeString}%0A`;orderText += `_Сформировано автоматически_`;const whatsappNumber = "996997703090";const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${orderText}`; // No need to encodeURIComponent here if already done piece by piecewindow.open(whatsappUrl, '_blank');}49 unmodified linesfilterProducts();});});filterProducts();}function showNotification(message, duration = 3000) {const placeholder = document.getElementById('notification-placeholder');if (!placeholder) return;const notification = document.createElement('div');notification.className = 'notification';notification.textContent = message;placeholder.appendChild(notification);setTimeout(() => { notification.classList.add('show'); }, 10);setTimeout(() => {notification.classList.remove('show');setTimeout(() => { notification.remove(); }, 500);}, duration);}3 unmodified linesupdateCartButton();setupFilters();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 => {6 unmodified lines</script></body></html>'''return render_template_string(catalog_html,products=products_sorted,categories=categories,repo_id=REPO_ID,is_authenticated=is_authenticated,store_address=STORE_ADDRESS,session=session,currency_code=CURRENCY_CODE)@app.route('/product/<int:index>')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()))is_authenticated = 'user' in sessiontry:product = products_sorted[index]if not product.get('in_stock', True):raise IndexError("Товар не в наличии")except IndexError:logging.warning(f"Attempted access to non-existent or out-of-stock product with index {index}")return "Товар не найден или отсутствует в наличии.", 404detail_html = '''<div style="padding: 10px;"><h2 style="font-size: 1.6rem; font-weight: 600; margin-bottom: 15px; text-align: center; color: #1C6758;">{{ product['name'] }}</h2><div class="swiper-container" style="max-width: 450px; margin: 0 auto 20px; border-radius: 10px; overflow: hidden; background-color: #fff;">35 unmodified lines{% endif %}</div></div>'''return render_template_string(detail_html,product=product,repo_id=REPO_ID,is_authenticated=is_authenticated,currency_code=CURRENCY_CODE)LOGIN_TEMPLATE = '''<!DOCTYPE html>36 unmodified lines</html>'''@app.route('/login', methods=['GET', 'POST'])def login():if request.method == 'POST':login = request.form.get('login')password = request.form.get('password')if not login or not password:return render_template_string(LOGIN_TEMPLATE, error="Логин и пароль не могут быть пустыми."), 400users = load_users()if login in users and users[login].get('password') == password:user_info = users[login]session['user'] = loginsession['user_info'] = {'login': login,'first_name': user_info.get('first_name', ''),'last_name': user_info.get('last_name', ''),'country': user_info.get('country', ''),'city': user_info.get('city', ''),'phone': user_info.get('phone', '')}logging.info(f"User {login} logged in successfully.")login_response_html = f'''<!DOCTYPE html><html><head><title>Перенаправление...</title></head><body><script>try {{ localStorage.setItem('soolaUser', '{login}'); }} catch (e) {{ console.error("Error saving to localStorage:", e); }}window.location.href = "{url_for('catalog')}";</script><p>Вход выполнен успешно. Перенаправление в <a href="{url_for('catalog')}">каталог</a>...</p></body></html>'''return login_response_htmlelse:logging.warning(f"Failed login attempt for user {login}.")error_message = "Неверный логин или пароль."return render_template_string(LOGIN_TEMPLATE, error=error_message), 401return render_template_string(LOGIN_TEMPLATE, error=None)@app.route('/auto_login', methods=['POST'])def auto_login():data = request.get_json()if not data or 'login' not in data:logging.warning("Auto_login request missing data or login.")return "Invalid request", 400login = data.get('login')if not login:logging.warning("Attempted auto_login with empty login.")return "Login not provided", 400users = load_users()if login in users:user_info = users[login]session['user'] = loginsession['user_info'] = {'login': login,'first_name': user_info.get('first_name', ''),'last_name': user_info.get('last_name', ''),'country': user_info.get('country', ''),'city': user_info.get('city', ''),'phone': user_info.get('phone', '')}logging.info(f"Auto-login successful for user {login}.")return "OK", 200else:logging.warning(f"Failed auto-login attempt for non-existent user {login}.")return "Auto-login failed", 400@app.route('/logout')def logout():logged_out_user = session.get('user')session.pop('user', None)session.pop('user_info', None)if logged_out_user:logging.info(f"User {logged_out_user} logged out.")logout_response_html = '''<!DOCTYPE html><html><head><title>Выход...</title></head><body><script>try { localStorage.removeItem('soolaUser'); } catch (e) { console.error("Error removing from localStorage:", e); }2 unmodified lines<p>Выход выполнен. Перенаправление на <a href="/">главную страницу</a>...</p></body></html>'''return logout_response_htmlADMIN_TEMPLATE = '''<!DOCTYPE html>380 unmodified linesif (group) {const container = group.parentNode;group.remove();if (container && container.children.length === 0) {const placeholderGroup = document.createElement('div');placeholderGroup.className = 'color-input-group';12 unmodified lines</html>'''@app.route('/admin', methods=['GET', 'POST'])def admin():# Load data and users *before* processing POST to have the current statedata = load_data()users = load_users()# Ensure products and categories are lists/dicts even if load failedproducts = data.get('products', [])categories = data.get('categories', [])if request.method == 'POST':action = request.form.get('action')4 unmodified linescategory_name = request.form.get('category_name', '').strip()if category_name and category_name not in categories:categories.append(category_name)categories.sort()data['categories'] = categories # Update the main data dictsave_data(data)logging.info(f"Category '{category_name}' added.")10 unmodified linesif category_to_delete and category_to_delete in categories:categories.remove(category_to_delete)updated_count = 0for product in products:if product.get('category') == category_to_delete:product['category'] = 'Без категории'updated_count += 1data['categories'] = categories # Update the main data dictdata['products'] = products # Update the main data dictsave_data(data)logging.info(f"Category '{category_to_delete}' deleted. Updated products: {updated_count}.")flash(f"Категория '{category_to_delete}' удалена.", 'success')else:logging.warning(f"Attempted to delete non-existent or empty category: {category_to_delete}")flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error')34 unmodified linesif photo and photo.filename:try:ext = os.path.splitext(photo.filename)[1].lower()# Basic check for common image extensionsif ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:logging.warning(f"Skipping non-image file upload: {photo.filename}")flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")continuephoto_filename = secure_filename(f"{name.replace(' ','_')}_{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}...")7 unmodified lines)photos_list.append(photo_filename)logging.info(f"Photo {photo_filename} uploaded successfully.")os.remove(temp_path)uploaded_count += 1except Exception as e:logging.error(f"Error uploading photo {photo.filename} to HF: {e}", exc_info=True)flash(f"Ошибка при загрузке фото {photo.filename}.", 'error')# Optionally remove temp file if it exists after errorif os.path.exists(temp_path):try: os.remove(temp_path)except OSError: passelif photo and not photo.filename:logging.warning("Received an empty photo file object when adding product.")try:# Check if directory exists and is empty before removingif 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}")new_product = {'name': name, 'price': price, 'description': description,'category': category if category in categories else 'Без категории','photos': photos_list, 'colors': colors,24 unmodified lineslogging.error(f"Invalid index '{index_str}' for editing. Product list length: {len(products)}")return redirect(url_for('admin'))product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip()price_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()11 unmodified lineslogging.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'16 unmodified linesflash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")continuephoto_filename = secure_filename(f"{product_to_edit['name'].replace(' ','_')}_{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...")17 unmodified lineslogging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}")if new_photos_list:logging.info(f"Photo list for product {product_to_edit['name']} updated.")old_photos = product_to_edit.get('photos', [])if old_photos:logging.info(f"Attempting to delete old photos: {old_photos}")7 unmodified lines)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_listflash("Фотографии товара успешно обновлены.", "success")elif uploaded_count == 0 and any(f.filename for f in photos_files):flash("Не удалось загрузить новые фотографии.", "error")# Update the product in the main listproducts[index] = product_to_edit14 unmodified linesdeleted_product = products.pop(index)product_name = deleted_product.get('name', 'N/A')photos_to_delete = deleted_product.get('photos', [])if photos_to_delete and HF_TOKEN_WRITE:logging.info(f"Attempting to delete photos for product '{product_name}' from HF: {photos_to_delete}")8 unmodified lines)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")data['products'] = products # Update the main data dictsave_data(data)20 unmodified linesreturn redirect(url_for('admin'))users[login] = {'password': password,'first_name': first_name, 'last_name': last_name,'phone': phone,'country': country, 'city': city5 unmodified lineselif action == 'delete_user':login_to_delete = request.form.get('login')if login_to_delete and login_to_delete in users:del users[login_to_delete]save_users(users)logging.info(f"User '{login_to_delete}' deleted.")6 unmodified lineslogging.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'))# GET request or after POST redirect# Reload data and users again in case they were modified by POST and saved# This ensures the template always shows the latest state after an actioncurrent_data = load_data()current_users = load_users()display_products = current_data.get('products', [])display_categories = sorted(current_data.get('categories', []))display_users = dict(sorted(current_users.items()))return render_template_string(ADMIN_TEMPLATE,6 unmodified lines@app.route('/force_upload', methods=['POST'])def force_upload():logging.info("Forcing upload to Hugging Face...")try:upload_db_to_hf()flash("Данные успешно загружены на Hugging Face.", 'success')except Exception as e:logging.error(f"Error during forced upload: {e}", exc_info=True)2 unmodified lines@app.route('/force_download', methods=['POST'])def force_download():logging.info("Forcing download from Hugging Face...")try:if download_db_from_hf():flash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success')else:flash("Не удалось скачать данные с Hugging Face после нескольких попыток.", 'error')except Exception as e:logging.error(f"Error during forced download: {e}", exc_info=True)flash(f"Ошибка при скачивании с Hugging Face: {e}", 'error')return redirect(url_for('admin'))if __name__ == '__main__':# Initial load on startupload_data()load_users()if HF_TOKEN_WRITE:backup_thread = threading.Thread(target=periodic_backup, daemon=True)5 unmodified linesport = int(os.environ.get('PORT', 7860))logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}")# Use waitress or gunicorn in production instead of development server# For simplicity, using Flask's dev server hereapp.run(debug=False, host='0.0.0.0', port=port)1234565 unmodified lines121314151617184 unmodified lines232425262728297 unmodified lines373839404142434429 unmodified lines7475767778798081828384858687888990919213 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521533 unmodified lines15715815916016116216312 unmodified lines1761771781791801811826 unmodified lines1891901911921931941951961971981992002012024 unmodified lines20720820921021121221333 unmodified lines2472482492502512522532542552562572582592608 unmodified lines26927027127227327427527627733 unmodified lines31131231331431531631731831932032132232332432532632725 unmodified lines3533543553563573583593603613625 unmodified lines368369370371372373374375106 unmodified lines482483484485486487488489117 unmodified lines60760860961061161261352 unmodified lines66666766866967067167267367467567667767867968 unmodified lines7487497507517527537541 unmodified line75675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981049 unmodified lines8608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978983 unmodified lines9029039049059069079089099109119129139149156 unmodified lines92292392492592692792892993035 unmodified lines96696796896997097197236 unmodified lines10091010101110121013101410152 unmodified lines101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146380 unmodified lines152715281529153015311532153312 unmodified lines1546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517764 unmodified lines178117821783178417851786178710 unmodified lines179817991800180118021803180418051806180718081809181018111812181334 unmodified lines184818491850185118521853185418551856185718581859186018617 unmodified lines186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189624 unmodified lines192119221923192419251926192711 unmodified lines193919401941194219431944194516 unmodified lines1962196319641965196619671968196917 unmodified lines198719881989199019911992199319947 unmodified lines2002200320042005200620072008200920102011201220132014201520162017201814 unmodified lines20332034203520362037203820398 unmodified lines204820492050205120522053205420552056205720582059206020 unmodified lines20812082208320842085208620875 unmodified lines20932094209520962097209820992100210121026 unmodified lines210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021316 unmodified lines21382139214021412142214321442145214621472 unmodified lines215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021815 unmodified lines21872188218921902191219221932194# --- START OF FILE app.py ---from flask import Flask, render_template_string, request, redirect, url_for, session, send_file, flash, jsonifyimport jsonimport osimport logging5 unmodified linesfrom werkzeug.utils import secure_filenamefrom dotenv import load_dotenvimport requests # Added for more specific network error handlingimport uuid # For unique order IDsload_dotenv()4 unmodified linesSYNC_FILES = [DATA_FILE, USERS_FILE]REPO_ID = "Kgshop/Soola" # Replace with your actual repo ID if differentHF_TOKEN_WRITE = os.getenv("HF_TOKEN")HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")7 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')# --- Hugging Face Sync Functions ---def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):if not HF_TOKEN_READ and not HF_TOKEN_WRITE: # Allow read with write token toologging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.")29 unmodified linesexcept 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.")# Check if it's the first attempt; if so, create an empty default file locallyif 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': {}}, f)logging.info(f"Created empty local file {file_name} because it was not found on HF.")elif file_name == USERS_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 # Mark as failed for this specific file, but don't stop othersbreak # No point retrying a 404else:13 unmodified lineslogging.info(f"Download process finished. Overall success: {all_successful}")return all_successfuldef 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.")returntry:api = HfApi()files_to_upload = [specific_file] if specific_file else SYNC_FILESlogging.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 = 1800logging.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.")# --- Data Loading and Saving Functions ---def load_data():default_data = {'products': [], 'categories': [], 'orders': {}}try:with open(DATA_FILE, 'r', encoding='utf-8') as file:data = json.load(file)3 unmodified linesraise FileNotFoundError # Treat as missing to trigger downloadif 'products' not in data: data['products'] = []if 'categories' not in data: data['categories'] = []if 'orders' not in data: data['orders'] = {} # Initialize orders if missingreturn dataexcept FileNotFoundError:logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.")12 unmodified linesreturn default_dataif 'products' not in data: data['products'] = []if 'categories' not in data: data['categories'] = []if 'orders' not in data: data['orders'] = {} # Initialize orders if missingreturn dataexcept FileNotFoundError:logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.")6 unmodified linesreturn default_dataelse:logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.")# Create empty file locally if download failed and file doesn't existif 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 # Return empty structure in memorydef save_data(data):4 unmodified linesreturnif 'products' not in data: data['products'] = []if 'categories' not in data: data['categories'] = []if 'orders' not in data: data['orders'] = {} # Ensure orders key existswith open(DATA_FILE, 'w', encoding='utf-8') as file:json.dump(data, file, ensure_ascii=False, indent=4)33 unmodified linesreturn default_userselse:logging.error(f"Failed to download {USERS_FILE} from HF after retries. Using empty default user structure.")# Create empty file locally if download failed and file doesn't existif not os.path.exists(USERS_FILE):try:with open(USERS_FILE, 'w', encoding='utf-8') as f:json.dump(default_users, f)logging.info(f"Created empty local file {USERS_FILE} after failed download.")except Exception as create_e:logging.error(f"Failed to create empty local file {USERS_FILE}: {create_e}")return default_users # Return empty structure in memorydef save_users(users):8 unmodified linesexcept Exception as e:logging.error(f"Error saving user data to {USERS_FILE}: {e}", exc_info=True)# --- Templates ---CATALOG_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head>33 unmodified linesbody.dark-mode .category-filter { background-color: #253f37; border-color: #2c4a41; color: #97b7ae; }.category-filter.active, .category-filter:hover { background-color: #1C6758; color: white; border-color: #1C6758; box-shadow: 0 2px 10px rgba(28, 103, 88, 0.3); }body.dark-mode .category-filter.active, body.dark-mode .category-filter:hover { background-color: #3D8361; border-color: #3D8361; color: #1a2b26; box-shadow: 0 2px 10px rgba(61, 131, 97, 0.4); }.products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 20px; padding: 10px; }@media (min-width: 600px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); } }@media (min-width: 900px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); } }.product { background: #fff; border-radius: 15px; padding: 0; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; height: 100%; border: 1px solid #e1f0e9;}body.dark-mode .product { background: #253f37; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); border-color: #2c4a41; }.product:hover { transform: translateY(-5px) scale(1.02); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12); }body.dark-mode .product:hover { box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3); }.product-image { width: 100%; aspect-ratio: 1 / 1; background-color: #fff; border-radius: 10px 10px 0 0; overflow: hidden; display: flex; justify-content: center; align-items: center; margin-bottom: 0; }.product-image img { max-width: 100%; max-height: 100%; object-fit: contain; transition: transform 0.3s ease; }/* Removed hover effect from image itself to avoid double scaling */.product-info { padding: 15px; flex-grow: 1; display: flex; flex-direction: column; justify-content: center; }.product h2 { font-size: 1.1rem; font-weight: 600; margin: 0 0 8px 0; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #2d332f; }body.dark-mode .product h2 { color: #c8d8d3; }25 unmodified lines.cart-item:last-child { border-bottom: none; }.cart-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #fff; padding: 5px; grid-column: 1; }.cart-item-details { grid-column: 2; }.cart-item-details strong { display: block; margin-bottom: 5px; font-size: 1rem; }.cart-item-price { font-size: 0.9rem; color: #44524c; }body.dark-mode .cart-item-price { color: #8aa39a; }.cart-item-total { font-weight: bold; text-align: right; grid-column: 3; font-size: 1rem;}.cart-item-remove { grid-column: 4; background:none; border:none; color:#f56565; cursor:pointer; font-size: 1.3em; padding: 5px; line-height: 1; }.cart-item-remove:hover { color: #c53030; }.quantity-input, .color-select { width: 100%; max-width: 180px; padding: 10px; border: 1px solid #d1e7dd; border-radius: 8px; font-size: 1rem; margin: 10px 0; box-sizing: border-box; }5 unmodified lines.cart-actions .product-button { width: auto; flex-grow: 1; }.clear-cart { background-color: #7a8d85; }.clear-cart:hover { background-color: #5e6e68; box-shadow: 0 4px 15px rgba(94, 110, 104, 0.4); }.formulate-order-button { background-color: #38a169; }.formulate-order-button:hover { background-color: #2f855a; box-shadow: 0 4px 15px rgba(47, 133, 90, 0.4); }.notification { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background-color: #38a169; color: white; padding: 10px 20px; border-radius: 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); z-index: 1002; opacity: 0; transition: opacity 0.5s ease; font-size: 0.9rem;}.notification.show { opacity: 1;}.no-results-message { grid-column: 1 / -1; text-align: center; padding: 40px; font-size: 1.1rem; color: #5e6e68; }106 unmodified lines<button class="product-button clear-cart" onclick="clearCart()"><i class="fas fa-trash"></i> Очистить корзину</button><button class="product-button formulate-order-button" onclick="formulateOrder()"><i class="fas fa-file-alt"></i> Сформировать заказ</button></div></div>117 unmodified linesfunction openQuantityModal(index) {if (!isAuthenticated) {alert('Пожалуйста, войдите в систему, чтобы добавить товар в корзину.');window.location.href = '{{ url_for("login") }}';return;}selectedProductIndex = index;52 unmodified linesreturn;}const cartItemId = `${product.name}-${color}`; // Use name + color as IDconst existingItemIndex = cart.findIndex(item => item.id === cartItemId);if (existingItemIndex > -1) {cart[existingItemIndex].quantity += quantity;} else {cart.push({id: cartItemId, // Unique ID for the item *variant* in the cartname: product.name,price: product.price,photo: product.photos && product.photos.length > 0 ? product.photos[0] : null,68 unmodified linesfunction removeFromCart(itemId) {cart = cart.filter(item => item.id !== itemId);localStorage.setItem('soolaCart', JSON.stringify(cart));openCartModal(); // Refresh cart modal viewupdateCartButton();}1 unmodified lineif (confirm("Вы уверены, что хотите очистить корзину?")) {cart = [];localStorage.removeItem('soolaCart');openCartModal(); // Refresh cart modal viewupdateCartButton();}}function formulateOrder() {if (cart.length === 0) {alert("Корзина пуста! Добавьте товары перед формированием заказа.");return;}const orderData = {cart: cart,userInfo: isAuthenticated ? userInfo : null // Include user info if logged in};// Disable button to prevent multiple clicksconst 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(orderData)}).then(response => {if (!response.ok) {return response.json().then(err => { throw new Error(err.error || 'Не удалось создать заказ'); });}return response.json();}).then(data => {if (data.order_id) {localStorage.removeItem('soolaCart'); // Clear cart on successcart = []; // Clear local cart variableupdateCartButton(); // Update button displaycloseModal('cartModal'); // Close cart modalwindow.location.href = `/order/${data.order_id}`; // Redirect to order page} else {throw new Error('Не получен ID заказа от сервера.');}}).catch(error => {console.error('Ошибка при формировании заказа:', error);alert(`Ошибка: ${error.message}`);if (formulateButton) formulateButton.disabled = false; // Re-enable button on error});}49 unmodified linesfilterProducts();});});filterProducts(); // Initial filter application}function showNotification(message, duration = 3000) {const placeholder = document.getElementById('notification-placeholder');if (!placeholder) {// Create placeholder if it doesn't existconst newPlaceholder = document.createElement('div');newPlaceholder.id = 'notification-placeholder';newPlaceholder.style.position = 'fixed';newPlaceholder.style.bottom = '80px'; // Adjust position as needednewPlaceholder.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);// Force reflow before adding class for transitionvoid notification.offsetWidth;notification.classList.add('show');setTimeout(() => {notification.classList.remove('show');// Remove element after transition finishesnotification.addEventListener('transitionend', () => notification.remove());}, duration);}3 unmodified linesupdateCartButton();setupFilters();// Close modal on background clickwindow.addEventListener('click', function(event) {if (event.target.classList.contains('modal')) {closeModal(event.target.id);}});// Close modal on Escape key presswindow.addEventListener('keydown', function(event) {if (event.key === 'Escape') {document.querySelectorAll('.modal[style*="display: block"]').forEach(modal => {6 unmodified lines</script></body></html>'''PRODUCT_DETAIL_TEMPLATE = '''<div style="padding: 10px;"><h2 style="font-size: 1.6rem; font-weight: 600; margin-bottom: 15px; text-align: center; color: #1C6758;">{{ product['name'] }}</h2><div class="swiper-container" style="max-width: 450px; margin: 0 auto 20px; border-radius: 10px; overflow: hidden; background-color: #fff;">35 unmodified lines{% endif %}</div></div>'''LOGIN_TEMPLATE = '''<!DOCTYPE html>36 unmodified lines</html>'''LOGOUT_REDIRECT_TEMPLATE = '''<!DOCTYPE html><html><head><title>Выход...</title></head><body><script>try { localStorage.removeItem('soolaUser'); } catch (e) { console.error("Error removing from localStorage:", e); }2 unmodified lines<p>Выход выполнен. Перенаправление на <a href="/">главную страницу</a>...</p></body></html>'''LOGIN_REDIRECT_TEMPLATE = '''<!DOCTYPE html><html><head><title>Перенаправление...</title></head><body><script>try {{ localStorage.setItem('soolaUser', '{login}'); }} catch (e) {{ console.error("Error saving to localStorage:", e); }}window.location.href = "{catalog_url}";</script><p>Вход выполнен успешно. Перенаправление в <a href="{catalog_url}">каталог</a>...</p></body></html>'''ORDER_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Заказ №{{ order.id }} - Soola Cosmetics</title><link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"><style>body { font-family: 'Poppins', sans-serif; background: #f0f9f4; color: #2d332f; line-height: 1.6; padding: 20px; }.container { max-width: 800px; margin: 20px auto; padding: 30px; background: #fff; border-radius: 15px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1); border: 1px solid #d1e7dd; }h1 { text-align: center; color: #1C6758; margin-bottom: 25px; font-size: 1.8rem; font-weight: 600; }h2 { color: #164B41; margin-top: 30px; margin-bottom: 15px; font-size: 1.4rem; border-bottom: 1px solid #d1e7dd; padding-bottom: 8px;}.order-meta { font-size: 0.9rem; color: #5e6e68; margin-bottom: 20px; text-align: center; }.order-item { display: grid; grid-template-columns: 60px 1fr auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #e1f0e9; }.order-item:last-child { border-bottom: none; }.order-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #fff; padding: 5px; border: 1px solid #e1f0e9;}.item-details strong { display: block; margin-bottom: 5px; font-size: 1.05rem; color: #2d332f;}.item-details span { font-size: 0.9rem; color: #44524c; display: block;}.item-total { font-weight: bold; text-align: right; font-size: 1rem; color: #1C6758;}.order-summary { margin-top: 30px; padding-top: 20px; border-top: 2px solid #1C6758; text-align: right; }.order-summary p { margin-bottom: 10px; font-size: 1.1rem; }.order-summary strong { font-size: 1.3rem; color: #1C6758; }.customer-info { margin-top: 30px; background-color: #f8fcfb; padding: 20px; border-radius: 8px; border: 1px solid #e1f0e9;}.customer-info p { margin-bottom: 8px; font-size: 0.95rem; }.customer-info strong { color: #164B41; }.actions { margin-top: 30px; text-align: center; }.button { padding: 12px 25px; border: none; border-radius: 8px; background-color: #25D366; /* WhatsApp Green */ color: white; font-weight: 600; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease; font-size: 1rem; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; }.button:hover { background-color: #128C7E; }.button:active { transform: scale(0.98); }.button i { font-size: 1.2rem; }.catalog-link { display: block; text-align: center; margin-top: 25px; color: #3D8361; text-decoration: none; font-size: 0.9rem; }.catalog-link:hover { text-decoration: underline; }.not-found { text-align: center; color: #c53030; font-size: 1.2rem; padding: 40px 0;}</style></head><body><div class="container">{% if order %}<h1><i class="fas fa-receipt"></i> Ваш Заказ №{{ order.id }}</h1><p class="order-meta">Дата создания: {{ order.created_at }}</p><h2><i class="fas fa-shopping-bag"></i> Товары в заказе</h2><div id="orderItems">{% for item in order.cart %}<div class="order-item"><img src="{{ item.photo_url }}" alt="{{ item.name }}"><div class="item-details"><strong>{{ item.name }} {% if item.color != 'N/A' %}({{ item.color }}){% endif %}</strong><span>{{ "%.2f"|format(item.price) }} {{ currency_code }} × {{ item.quantity }}</span></div><div class="item-total">{{ "%.2f"|format(item.price * item.quantity) }} {{ currency_code }}</div></div>{% endfor %}</div><div class="order-summary"><p>Общая сумма товаров: <strong>{{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>{# Add shipping/discount info here if applicable in the future #}<p><strong>ИТОГО К ОПЛАТЕ: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p></div>{% if order.user_info %}<div class="customer-info"><h2><i class="fas fa-user"></i> Информация о клиенте</h2><p><strong>Логин:</strong> {{ order.user_info.login }}</p><p><strong>Имя:</strong> {{ order.user_info.get('first_name', '') }} {{ order.user_info.get('last_name', '') }}</p><p><strong>Телефон:</strong> {{ order.user_info.get('phone', 'Не указан') }}</p><p><strong>Страна:</strong> {{ order.user_info.get('country', 'Не указана') }}</p><p><strong>Город:</strong> {{ order.user_info.get('city', 'Не указан') }}</p></div>{% else %}<div class="customer-info"><h2><i class="fas fa-user-slash"></i> Информация о клиенте</h2><p>Клиент не был авторизован при создании заказа.</p></div>{% endif %}<div class="actions"><button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> Отправить заказ</button></div><a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в каталог</a><script>function sendOrderViaWhatsApp() {const orderId = '{{ order.id }}';const orderUrl = `{{ request.url }}`; // Gets the current page URLconst whatsappNumber = "996997703090"; // Replace with your numberlet message = `Здравствуйте! Хочу подтвердить свой заказ на Soola Cosmetics:%0A%0A`;message += `*Номер заказа:* ${orderId}%0A`;message += `*Ссылка на заказ:* ${encodeURIComponent(orderUrl)}%0A%0A`;message += `Пожалуйста, свяжитесь со мной для уточнения деталей оплаты и доставки.`;const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${message}`;window.open(whatsappUrl, '_blank');}</script>{% else %}<h1 style="color: #c53030;"><i class="fas fa-exclamation-triangle"></i> Ошибка</h1><p class="not-found">Заказ с таким ID не найден.</p><a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в каталог</a>{% endif %}</div></body></html>'''ADMIN_TEMPLATE = '''<!DOCTYPE html>380 unmodified linesif (group) {const container = group.parentNode;group.remove();// Add a placeholder input if the container becomes emptyif (container && container.children.length === 0) {const placeholderGroup = document.createElement('div');placeholderGroup.className = 'color-input-group';12 unmodified lines</html>'''# --- Flask Routes ---@app.route('/')def catalog():data = load_data()all_products = data.get('products', [])categories = sorted(data.get('categories', [])) # Sort categories alphabeticallyis_authenticated = 'user' in session# Filter out-of-stock and sort: top first, then by nameproducts_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,is_authenticated=is_authenticated,store_address=STORE_ADDRESS,session=session,currency_code=CURRENCY_CODE)@app.route('/product/<int:index>')def product_detail(index):data = load_data()all_products = data.get('products', [])# We need the same filtering and sorting logic as in catalog to match the indexproducts_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()))is_authenticated = 'user' in sessiontry:product = products_sorted[index]# No need to check in_stock again, already filteredexcept IndexError:logging.warning(f"Attempted access to non-existent or out-of-stock product with index {index}")return "Товар не найден или отсутствует в наличии.", 404return render_template_string(PRODUCT_DETAIL_TEMPLATE,product=product,repo_id=REPO_ID,is_authenticated=is_authenticated,currency_code=CURRENCY_CODE)@app.route('/login', methods=['GET', 'POST'])def login():if request.method == 'POST':login_attempt = request.form.get('login')password = request.form.get('password')if not login_attempt or not password:return render_template_string(LOGIN_TEMPLATE, error="Логин и пароль не могут быть пустыми."), 400users = load_users()if login_attempt in users and users[login_attempt].get('password') == password:user_info = users[login_attempt]session['user'] = login_attemptsession['user_info'] = {'login': login_attempt,'first_name': user_info.get('first_name', ''),'last_name': user_info.get('last_name', ''),'country': user_info.get('country', ''),'city': user_info.get('city', ''),'phone': user_info.get('phone', '')}logging.info(f"User {login_attempt} logged in successfully.")# Use template for redirect scriptreturn render_template_string(LOGIN_REDIRECT_TEMPLATE,login=login_attempt,catalog_url=url_for('catalog'))else:logging.warning(f"Failed login attempt for user {login_attempt}.")error_message = "Неверный логин или пароль."return render_template_string(LOGIN_TEMPLATE, error=error_message), 401# GET requestreturn render_template_string(LOGIN_TEMPLATE, error=None)@app.route('/auto_login', methods=['POST'])def auto_login():data = request.get_json()if not data or 'login' not in data:logging.warning("Auto_login request missing data or login.")return jsonify({"error": "Invalid request"}), 400login_attempt = data.get('login')if not login_attempt:logging.warning("Attempted auto_login with empty login.")return jsonify({"error": "Login not provided"}), 400users = load_users()if login_attempt in users:user_info = users[login_attempt]session['user'] = login_attemptsession['user_info'] = {'login': login_attempt,'first_name': user_info.get('first_name', ''),'last_name': user_info.get('last_name', ''),'country': user_info.get('country', ''),'city': user_info.get('city', ''),'phone': user_info.get('phone', '')}logging.info(f"Auto-login successful for user {login_attempt}.")return jsonify({"message": "OK"}), 200else:logging.warning(f"Failed auto-login attempt for non-existent user {login_attempt}.")# Don't reveal user existence, just fail genericallyreturn jsonify({"error": "Auto-login failed"}), 401 # Use 401 Unauthorized@app.route('/logout')def logout():logged_out_user = session.get('user')session.pop('user', None)session.pop('user_info', None)if logged_out_user:logging.info(f"User {logged_out_user} logged out.")# Use template for redirect scriptreturn render_template_string(LOGOUT_REDIRECT_TEMPLATE)@app.route('/create_order', methods=['POST'])def create_order():order_data = request.get_json()if not order_data or 'cart' not in order_data or not order_data['cart']:logging.warning("Create order request missing cart data or cart is empty.")return jsonify({"error": "Корзина пуста или не передана."}), 400cart_items = order_data['cart']user_info = order_data.get('userInfo', None) # User info might be null if not logged in# Recalculate total server-side for security/consistencytotal_price = 0processed_cart = []for item in cart_items:# Basic validation (can be expanded)if not all(k in item for k in ('name', 'price', 'quantity')):logging.error(f"Invalid cart item structure received: {item}")return jsonify({"error": "Неверный формат товара в корзине."}), 400try:price = float(item['price'])quantity = int(item['quantity'])if price < 0 or quantity <= 0:raise ValueError("Invalid price or quantity")total_price += price * quantity# Construct item data for savingprocessed_cart.append({"name": item['name'],"price": price,"quantity": quantity,"color": item.get('color', 'N/A'),"photo": item.get('photo'), # Store photo filename if available# Generate photo URL here for easier display later"photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item['photo']}" if item.get('photo') else "https://via.placeholder.com/60x60.png?text=N/A"})except (ValueError, TypeError) as e:logging.error(f"Invalid price/quantity in cart item: {item}. Error: {e}")return jsonify({"error": "Неверная цена или количество в товаре."}), 400order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}"order_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')new_order = {"id": order_id,"created_at": order_timestamp,"cart": processed_cart,"total_price": round(total_price, 2),"user_info": user_info, # Can be None"status": "new" # Initial status}try:data = load_data()# Ensure 'orders' key exists and is a dictionaryif 'orders' not in data or not isinstance(data.get('orders'), dict):data['orders'] = {}data['orders'][order_id] = new_ordersave_data(data)logging.info(f"Order {order_id} created successfully.")return jsonify({"order_id": order_id}), 201 # 201 Created status codeexcept Exception as e:logging.error(f"Failed to save order {order_id}: {e}", exc_info=True)return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500@app.route('/order/<order_id>')def view_order(order_id):# No login required for this routedata = load_data()order = data.get('orders', {}).get(order_id)if order:# Format timestamp for display if needed# order['created_at_formatted'] = ...logging.info(f"Displaying order {order_id}")else:logging.warning(f"Order {order_id} not found.")return render_template_string(ORDER_TEMPLATE,order=order,repo_id=REPO_ID,currency_code=CURRENCY_CODE)@app.route('/admin', methods=['GET', 'POST'])def admin():# Simple admin check (replace with proper authentication/authorization)# For now, allow anyone access for demonstration, add security later# if 'user' not in session or session.get('user') != 'admin_user':# flash("Доступ запрещен.", "error")# return redirect(url_for('login'))# Load data and users *before* processing POST to have the current statedata = load_data()users = load_users()# Ensure products and categories are lists/dicts even if load failedproducts = data.get('products', [])categories = data.get('categories', [])# Ensure 'orders' key exists and is a dictionaryif 'orders' not in data or not isinstance(data.get('orders'), dict):data['orders'] = {}if request.method == 'POST':action = request.form.get('action')4 unmodified linescategory_name = request.form.get('category_name', '').strip()if category_name and category_name not in categories:categories.append(category_name)# categories.sort() # Keep sorted listdata['categories'] = categories # Update the main data dictsave_data(data)logging.info(f"Category '{category_name}' added.")10 unmodified linesif category_to_delete and category_to_delete in categories:categories.remove(category_to_delete)updated_count = 0# Update products that used this categoryfor product in products:if product.get('category') == category_to_delete:product['category'] = 'Без категории'updated_count += 1data['categories'] = categories # Update the main data dictdata['products'] = products # Update affected productssave_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')34 unmodified linesif 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# Create a unique filename based on product name and timesafe_name = secure_filename(name.replace(' ', '_'))[:50] # Limit lengthphoto_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}...")7 unmodified lines)photos_list.append(photo_filename)logging.info(f"Photo {photo_filename} uploaded successfully.")os.remove(temp_path) # Clean up temp fileuploaded_count += 1except 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 # Ignore error if file cannot be removedelif photo and not photo.filename:logging.warning("Received an empty photo file object when adding product.")try:# Clean up temp dir if emptyif 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 = {# Consider adding a unique ID here later if needed'name': name, 'price': price, 'description': description,'category': category if category in categories else 'Без категории','photos': photos_list, 'colors': colors,24 unmodified lineslogging.error(f"Invalid index '{index_str}' for editing. Product list length: {len(products)}")return redirect(url_for('admin'))# Update fieldsproduct_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()11 unmodified lineslogging.warning(f"Invalid price format '{price_str}' during edit of product {original_name}. Price not changed.")flash(f"Неверный формат цены для товара '{original_name}'. Цена не изменена.", 'warning')# Handle photo replacementphotos_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'16 unmodified linesflash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")continuesafe_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...")17 unmodified lineslogging.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.")# Delete old photos from HF *after* new ones are uploadedold_photos = product_to_edit.get('photos', [])if old_photos:logging.info(f"Attempting to delete old photos: {old_photos}")7 unmodified lines)logging.info(f"Old photos for product {product_to_edit['name']} deleted from HF.")except Exception as e:# Log error but continue, new photos are already uploadedlogging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True)flash("Не удалось удалить старые фотографии с сервера. Новые фото загружены.", "warning")# Update product data with new photo listproduct_to_edit['photos'] = new_photos_listflash("Фотографии товара успешно обновлены.", "success")elif uploaded_count == 0 and any(f.filename for f in photos_files):# Files were selected, but none were uploaded (e.g., wrong format)flash("Не удалось загрузить новые фотографии (возможно, неверный формат).", "error")elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):flash("HF_TOKEN (write) не настроен. Фотографии не были обновлены.", "warning")# Update the product in the main listproducts[index] = product_to_edit14 unmodified linesdeleted_product = products.pop(index)product_name = deleted_product.get('name', 'N/A')# Attempt to delete associated photos from HFphotos_to_delete = deleted_product.get('photos', [])if photos_to_delete and HF_TOKEN_WRITE:logging.info(f"Attempting to delete photos for product '{product_name}' from HF: {photos_to_delete}")8 unmodified lines)logging.info(f"Photos for product '{product_name}' deleted from HF.")except Exception as e:# Log error but proceed with local deletionlogging.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 # Update the main data dictsave_data(data)20 unmodified linesreturn redirect(url_for('admin'))users[login] = {'password': password, # WARNING: Storing plain text'first_name': first_name, 'last_name': last_name,'phone': phone,'country': country, 'city': city5 unmodified lineselif action == 'delete_user':login_to_delete = request.form.get('login')if login_to_delete and login_to_delete in users:# Optional: Prevent deleting the current admin user?# if login_to_delete == session.get('user'):# flash("Нельзя удалить текущего пользователя.", 'error')# return redirect(url_for('admin'))del users[login_to_delete]save_users(users)logging.info(f"User '{login_to_delete}' deleted.")6 unmodified lineslogging.warning(f"Received unknown admin action: {action}")flash(f"Неизвестное действие: {action}", 'warning')# Redirect after POST to prevent form resubmissionreturn redirect(url_for('admin'))except Exception as e:# Catch potential errors during file operations, HF API calls, etc.logging.error(f"Error processing admin action '{action}': {e}", exc_info=True)flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'. Подробности в логе сервера.", 'error')return redirect(url_for('admin'))# --- GET request ---# Reload data and users again to ensure the template shows the latest statecurrent_data = load_data()current_users = load_users()# Sort products for consistent display in admin panel (e.g., by name)display_products = sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower())display_categories = sorted(current_data.get('categories', []))display_users = dict(sorted(current_users.items())) # Sort users by loginreturn render_template_string(ADMIN_TEMPLATE,6 unmodified lines@app.route('/force_upload', methods=['POST'])def force_upload():# Add admin check here if neededlogging.info("Forcing upload to Hugging Face...")try:upload_db_to_hf() # Uploads both files by defaultflash("Данные успешно загружены на Hugging Face.", 'success')except Exception as e:logging.error(f"Error during forced upload: {e}", exc_info=True)2 unmodified lines@app.route('/force_download', methods=['POST'])def force_download():# Add admin check here if neededlogging.info("Forcing download from Hugging Face...")try:if download_db_from_hf(): # Downloads both files by defaultflash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success')# Reload data/users in memory after download might be needed depending on app structure# load_data()# load_users()else:flash("Не удалось скачать данные с Hugging Face после нескольких попыток. Проверьте логи.", 'error')except Exception as e:logging.error(f"Error during forced download: {e}", exc_info=True)flash(f"Ошибка при скачивании с Hugging Face: {e}", 'error')return redirect(url_for('admin'))# --- App Initialization ---if __name__ == '__main__':# Initial download/load on startuplogging.info("Application starting up. Performing initial data load/download...")download_db_from_hf() # Attempt to download both files firstload_data() # Load data (will use downloaded or default)load_users() # Load users (will use downloaded or default)logging.info("Initial data load complete.")if HF_TOKEN_WRITE:backup_thread = threading.Thread(target=periodic_backup, daemon=True)5 unmodified linesport = int(os.environ.get('PORT', 7860))logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}")# Use waitress or gunicorn in production instead of development server# For simplicity, using Flask's dev server here (debug=False for production-like behavior)# Consider using waitress: pip install waitress; waitress-serve --host=0.0.0.0 --port=7860 app:appapp.run(debug=False, host='0.0.0.0', port=port)# --- END OF FILE app.py ---
app.py+571-250