diff --git "a/app (1) (8).py" "b/app (1) (8).py" new file mode 100644--- /dev/null +++ "b/app (1) (8).py" @@ -0,0 +1,1986 @@ +# --- START OF FILE app.py --- + +from flask import Flask, render_template_string, request, redirect, url_for, session, send_file, flash, jsonify +import json +import os +import logging +import threading +import time +from datetime import datetime +from huggingface_hub import HfApi, hf_hub_download +from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError +from werkzeug.utils import secure_filename +from dotenv import load_dotenv +import requests +import base64 # Added for encoding order data + +load_dotenv() + +app = Flask(__name__) +app.secret_key = 'your_unique_secret_key_soola_cosmetics_67890' +DATA_FILE = 'data_soola.json' +USERS_FILE = 'users_soola.json' + +SYNC_FILES = [DATA_FILE, USERS_FILE] + +REPO_ID = "Kgshop/Soolatest" +HF_TOKEN_WRITE = os.getenv("HF_TOKEN") +HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") + +STORE_ADDRESS = "Рынок Дордой, Джунхай, терминал, 38" + +CURRENCY_CODE = 'KGS' +CURRENCY_NAME = 'Кыргызский сом (с)' + +DOWNLOAD_RETRIES = 3 +DOWNLOAD_DELAY = 5 + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY): + if not HF_TOKEN_READ and not HF_TOKEN_WRITE: + logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.") + + token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE + + files_to_download = [specific_file] if specific_file else SYNC_FILES + logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...") + all_successful = True + + for file_name in files_to_download: + success = False + for attempt in range(retries + 1): + try: + logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...") + local_path = hf_hub_download( + repo_id=REPO_ID, + filename=file_name, + repo_type="dataset", + token=token_to_use, + local_dir=".", + local_dir_use_symlinks=False, + force_download=True, + resume_download=False + ) + logging.info(f"Successfully downloaded {file_name} to {local_path}.") + success = True + break + except RepositoryNotFoundError: + logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.") + return False + except HfHubHTTPError as e: + if e.response.status_code == 404: + logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.") + success = False + break + else: + logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") + except requests.exceptions.RequestException as e: + logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...") + except Exception as e: + logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True) + + if attempt < retries: + time.sleep(delay) + + if not success: + logging.error(f"Failed to download {file_name} after {retries + 1} attempts.") + all_successful = False + + logging.info(f"Download process finished. Overall success: {all_successful}") + return all_successful + +def load_data(): + default_data = {'products': [], 'categories': []} + 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'] = [] + return data + except FileNotFoundError: + logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.") + except json.JSONDecodeError: + logging.error(f"Error decoding JSON in local {DATA_FILE}. File might be corrupt. Attempting download.") + + if download_db_from_hf(specific_file=DATA_FILE): + try: + with open(DATA_FILE, 'r', encoding='utf-8') as file: + data = json.load(file) + logging.info(f"Data loaded successfully from {DATA_FILE} after download.") + if not isinstance(data, dict): + logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.") + return default_data + if 'products' not in data: data['products'] = [] + if 'categories' not in data: data['categories'] = [] + return data + except FileNotFoundError: + logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.") + return default_data + except json.JSONDecodeError: + logging.error(f"Error decoding JSON in downloaded {DATA_FILE}. Using default.") + return default_data + except Exception as e: + logging.error(f"Unknown error loading downloaded {DATA_FILE}: {e}. Using default.", exc_info=True) + return default_data + else: + logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.") + return default_data + +def save_data(data): + try: + if not isinstance(data, dict): + logging.error("Attempted to save invalid data structure (not a dict). Aborting save.") + return + if 'products' not in data: data['products'] = [] + if 'categories' not in data: data['categories'] = [] + + with open(DATA_FILE, 'w', encoding='utf-8') as file: + json.dump(data, file, ensure_ascii=False, indent=4) + logging.info(f"Data successfully saved to {DATA_FILE}") + upload_db_to_hf(specific_file=DATA_FILE) + except Exception as e: + logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True) + +def load_users(): + default_users = {} + try: + with open(USERS_FILE, 'r', encoding='utf-8') as file: + users = json.load(file) + logging.info(f"Local users loaded successfully from {USERS_FILE}") + return users if isinstance(users, dict) else default_users + except FileNotFoundError: + logging.warning(f"Local file {USERS_FILE} not found. Attempting download from HF.") + except json.JSONDecodeError: + logging.error(f"Error decoding JSON in local {USERS_FILE}. File might be corrupt. Attempting download.") + + if download_db_from_hf(specific_file=USERS_FILE): + try: + with open(USERS_FILE, 'r', encoding='utf-8') as file: + users = json.load(file) + logging.info(f"Users loaded successfully from {USERS_FILE} after download.") + return users if isinstance(users, dict) else default_users + except FileNotFoundError: + logging.error(f"File {USERS_FILE} still not found after download reported success. Using default.") + return default_users + except json.JSONDecodeError: + logging.error(f"Error decoding JSON in downloaded {USERS_FILE}. Using default.") + return default_users + except Exception as e: + logging.error(f"Unknown error loading downloaded {USERS_FILE}: {e}. Using default.", exc_info=True) + return default_users + else: + logging.error(f"Failed to download {USERS_FILE} from HF after retries. Using empty default user structure.") + return default_users + +def save_users(users): + try: + if not isinstance(users, dict): + logging.error("Attempted to save invalid users structure (not a dict). Aborting save.") + return + with open(USERS_FILE, 'w', encoding='utf-8') as file: + json.dump(users, file, ensure_ascii=False, indent=4) + logging.info(f"User data successfully saved to {USERS_FILE}") + upload_db_to_hf(specific_file=USERS_FILE) + except 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.") + return + try: + api = HfApi() + files_to_upload = [specific_file] if specific_file else SYNC_FILES + logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...") + + for file_name in files_to_upload: + if os.path.exists(file_name): + try: + api.upload_file( + path_or_fileobj=file_name, + path_in_repo=file_name, + repo_id=REPO_ID, + repo_type="dataset", + token=HF_TOKEN_WRITE, + commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" + ) + logging.info(f"File {file_name} successfully uploaded to Hugging Face.") + except Exception as e: + logging.error(f"Error uploading file {file_name} to Hugging Face: {e}") + else: + logging.warning(f"File {file_name} not found locally, skipping upload.") + logging.info("Finished uploading files to HF.") + except Exception as e: + logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True) + +def periodic_backup(): + backup_interval = 1800 + logging.info(f"Setting up periodic backup every {backup_interval} seconds.") + while True: + time.sleep(backup_interval) + logging.info("Starting periodic backup...") + upload_db_to_hf() + logging.info("Periodic backup finished.") + +@app.route('/') +def catalog(): + data = load_data() + all_products = data.get('products', []) + categories = data.get('categories', []) + is_authenticated = 'user' in session + + 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())) + + catalog_html = ''' + + + + + + Soola Cosmetics - Каталог + + + + + + +
+
+

Soola Cosmetics

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

{{ product['name'] }}

+ {% if is_authenticated %} +
{{ "%.2f"|format(product['price']) }} {{ currency_code }}
+ {% else %} +
Цена доступна после входа
+ {% endif %} +

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

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

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

+ {% endif %} +
+
+ + + + + + + + + +
+ + + + + + ''' + 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/') +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 session + try: + 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 "Товар не найден или отсутствует в наличии.", 404 + + detail_html = ''' +
+

{{ product['name'] }}

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

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

+ {% if is_authenticated %} +

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

+ {% else %} +

Цена: Доступна после входа

+ {% endif %} +

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

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

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

+ {% endif %} +
+
+ ''' + return render_template_string( + detail_html, + product=product, + repo_id=REPO_ID, + is_authenticated=is_authenticated, + currency_code=CURRENCY_CODE + ) + +ORDER_VIEW_TEMPLATE = ''' + + + + + + Детали Заказа - Soola Cosmetics + + + + +
+

Детали Заказа

+ + {% if error %} +

{{ error }}

+ {% else %} + {% if cart_items %} +

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

+ {% for item in cart_items %} +
+ {{ item.name }} +
+ {{ item.name }}{{ item.color_text }} +

Цена: {{ "%.2f"|format(item.price) }} {{ currency_code }}

+

Количество: {{ item.quantity }}

+
+
{{ "%.2f"|format(item.item_total) }} {{ currency_code }}
+
+ {% endfor %} + +
+

Общая сумма заказа: {{ "%.2f"|format(total_price) }} {{ currency_code }}

+
+ + {% if user_info %} +
+

Информация о клиенте

+

Имя: {{ user_info.get('first_name', '') }} {{ user_info.get('last_name', '') }}

+

Логин: {{ user_info.get('login', 'N/A') }}

+

Телефон: {{ user_info.get('phone', 'Не указан') }}

+

Страна: {{ user_info.get('country', 'Не указана') }}

+

Город: {{ user_info.get('city', 'Не указан') }}

+
+ {% endif %} + + {% else %} +

Не удалось загрузить детали заказа или корзина пуста.

+ {% endif %} + + {% endif %} +
+ + +''' + +@app.route('/order_view/') +def order_view(encoded_cart): + cart_items_processed = [] + total_price = 0 + error_message = None + user_info_data = session.get('user_info') # Get user info from session + + try: + decoded_bytes = base64.urlsafe_b64decode(encoded_cart + '=' * (-len(encoded_cart) % 4)) + cart_json = decoded_bytes.decode('utf-8') + cart_items = json.loads(cart_json) + + if not isinstance(cart_items, list): + raise ValueError("Decoded data is not a list") + + for item in cart_items: + if not isinstance(item, dict) or 'name' not in item or 'price' not in item or 'quantity' not in item: + logging.warning(f"Skipping invalid item in decoded cart: {item}") + continue + + item_total = float(item['price']) * int(item['quantity']) + total_price += item_total + photo_url = (f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item['photo']}" + if item.get('photo') else "https://via.placeholder.com/70x70.png?text=N/A") + color_text = f" (Цвет: {item['color']})" if item.get('color') and item['color'] != 'N/A' else '' + + cart_items_processed.append({ + 'name': item['name'], + 'price': float(item['price']), + 'quantity': int(item['quantity']), + 'photo_url': photo_url, + 'color_text': color_text, + 'item_total': item_total + }) + + except (base64.binascii.Error, UnicodeDecodeError, json.JSONDecodeError, ValueError, TypeError) as e: + logging.error(f"Error decoding or processing order data from URL: {e}", exc_info=True) + error_message = "Не удалось расшифровать или обработать данные заказа. Ссылка может быть повреждена или неверна." + except Exception as e: + logging.error(f"Unexpected error processing order view: {e}", exc_info=True) + error_message = "Произошла непредвиденная ошибка при отображении заказа." + + generation_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + + return render_template_string( + ORDER_VIEW_TEMPLATE, + cart_items=cart_items_processed, + total_price=total_price, + currency_code=CURRENCY_CODE, + repo_id=REPO_ID, + error=error_message, + user_info=user_info_data, + generation_time=generation_time + ) + + +LOGIN_TEMPLATE = ''' + + + + + + Вход - Soola Cosmetics + + + + +
+

Вход в Soola Cosmetics

+ {% if error %} +

{{ error }}

+ {% endif %} +
+ + + + + +
+ ← Вернуться в каталог +
+ + +''' + +@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="Логин и пароль не могут быть пустыми."), 400 + + users = load_users() + + if login in users and users[login].get('password') == password: + user_info = users[login] + session['user'] = login + session['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''' + Перенаправление... + +

Вход выполнен успешно. Перенаправление в каталог...

+ + ''' + return login_response_html + else: + logging.warning(f"Failed login attempt for user {login}.") + error_message = "Неверный логин или пароль." + return render_template_string(LOGIN_TEMPLATE, error=error_message), 401 + + return 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", 400 + + login = data.get('login') + if not login: + logging.warning("Attempted auto_login with empty login.") + return "Login not provided", 400 + + users = load_users() + if login in users: + user_info = users[login] + session['user'] = login + session['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", 200 + else: + 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 = ''' + Выход... + +

Выход выполнен. Перенаправление на главную страницу...

+ + ''' + return logout_response_html + +ADMIN_TEMPLATE = ''' + + + + + + Админ-панель - Soola Cosmetics + + + + + +
+
+

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

+ Перейти в каталог +
+ + {% with messages = get_flashed_messages(with_categories=true) %} + {% if messages %} + {% for category, message in messages %} +
{{ message }}
+ {% endfor %} + {% endif %} + {% endwith %} + +
+

Синхронизация с Датацентром

+
+
+ +
+
+ +
+
+

Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.

+
+ + +
+
+
+

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

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

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

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

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

+ {% endif %} +
+
+ +
+
+

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

+
+ Добавить нового пользователя +
+
+ + + + + +

Логин и пароль обязательны.

+ + + + + + + + + + + +
+
+
+ +

Список пользователей:

+ {% if users %} +
+ {% for login, user_data in users.items() %} +
+

Логин: {{ login }}

+

Имя: {{ user_data.get('first_name', 'N/A') }} {{ user_data.get('last_name', '') }}

+

Телефон: {{ user_data.get('phone', 'N/A') }}

+

Локация: {{ user_data.get('city', 'N/A') }}, {{ user_data.get('country', 'N/A') }}

+
+
+ + + +
+
+
+ {% endfor %} +
+ {% else %} +

Пользователей пока нет.

+ {% endif %} +
+
+
+ + +
+

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

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

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

+ {% 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')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}

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

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

+ {% if product.get('photos') and product['photos']|length > 1 %} +

(Всего фото: {{ product['photos']|length }})

+ {% endif %} +
+
+ +
+ +
+ + + +
+
+ +
+

Редактирование: {{ product['name'] }}

+
+ + + + + + + + + + + + + {% if product.get('photos') %} +

Текущие фото:

+
+ {% for photo in product['photos'] %} + Фото {{ loop.index }} + {% endfor %} +
+ {% endif %} + +
+ {% set current_colors = product.get('colors', []) %} + {% if current_colors and current_colors|select('ne', '')|list|length > 0 %} + {% for color in current_colors %} + {% if color.strip() %} +
+ + +
+ {% endif %} + {% endfor %} + {% else %} +
+ + +
+ {% endif %} +
+ +
+
+ + +
+
+ + +
+
+ +
+
+
+ {% endfor %} +
+ {% else %} +

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

+ {% endif %} +
+ +
+ + + + +''' + +@app.route('/admin', methods=['GET', 'POST']) +def admin(): + data = load_data() + users = load_users() + products = data.get('products', []) + categories = data.get('categories', []) + + if request.method == 'POST': + action = request.form.get('action') + logging.info(f"Admin action received: {action}") + + try: + if action == 'add_category': + category_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 + 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}' удалена.", '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()] + 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 + + photo_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}...") + 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}") + + new_product = { + 'name': name, 'price': price, 'description': description, + 'category': category if category in categories else 'Без категории', + 'photos': photos_list, 'colors': colors, + 'in_stock': in_stock, 'is_top': is_top + } + products.append(new_product) + data['products'] = products + save_data(data) + logging.info(f"Product '{name}' added.") + flash(f"Товар '{name}' успешно добавлен.", 'success') + + elif action == 'edit_product': + index_str = request.form.get('index') + if index_str is None: + flash("Ошибка редактирования: индекс товара не передан.", 'error') + return redirect(url_for('admin')) + + try: + index = int(index_str) + if not (0 <= index < len(products)): + raise IndexError("Product index out of range") + product_to_edit = products[index] + original_name = product_to_edit.get('name', 'N/A') + + except (ValueError, IndexError): + flash(f"Ошибка редактирования: неверный индекс товара '{index_str}'.", 'error') + logging.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() + 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['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 + + photo_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...") + 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"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}") + 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") + + products[index] = product_to_edit + data['products'] = products + save_data(data) + logging.info(f"Product '{original_name}' (index {index}) updated to '{product_to_edit['name']}'.") + flash(f"Товар '{product_to_edit['name']}' успешно обновлен.", 'success') + + elif action == 'delete_product': + index_str = request.form.get('index') + if index_str is None: + flash("Ошибка удаления: индекс товара не передан.", 'error') + return redirect(url_for('admin')) + try: + index = int(index_str) + if not (0 <= index < len(products)): raise IndexError("Product index out of range") + deleted_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}") + 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") + + data['products'] = products + save_data(data) + logging.info(f"Product '{product_name}' (original index {index}) deleted.") + flash(f"Товар '{product_name}' удален.", 'success') + except (ValueError, IndexError): + flash(f"Ошибка удаления: неверный индекс товара '{index_str}'.", 'error') + logging.error(f"Invalid index '{index_str}' for deletion. Product list length: {len(products)}") + + elif action == 'add_user': + login = request.form.get('login', '').strip() + password = request.form.get('password', '').strip() # Storing plain text password + first_name = request.form.get('first_name', '').strip() + last_name = request.form.get('last_name', '').strip() + phone = request.form.get('phone', '').strip() + country = request.form.get('country', '').strip() + city = request.form.get('city', '').strip() + + if not login or not password: + flash("Логин и пароль пользователя обязательны.", 'error') + return redirect(url_for('admin')) + if login in users: + flash(f"Пользователь с логином '{login}' уже существует.", 'error') + return redirect(url_for('admin')) + + users[login] = { + 'password': password, + 'first_name': first_name, 'last_name': last_name, + 'phone': phone, + 'country': country, 'city': city + } + save_users(users) + logging.info(f"User '{login}' added.") + flash(f"Пользователь '{login}' успешно добавлен.", 'success') + + elif 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.") + flash(f"Пользователь '{login_to_delete}' удален.", 'success') + else: + logging.warning(f"Attempted to delete non-existent or empty user: {login_to_delete}") + flash(f"Не удалось удалить пользователя '{login_to_delete}'.", 'error') + + else: + logging.warning(f"Received unknown admin action: {action}") + flash(f"Неизвестное действие: {action}", 'warning') + + return redirect(url_for('admin')) + + except Exception as e: + logging.error(f"Error processing admin action '{action}': {e}", exc_info=True) + flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'. Подробности в логе сервера.", 'error') + return redirect(url_for('admin')) + + current_data = load_data() + 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, + products=display_products, + categories=display_categories, + users=display_users, + repo_id=REPO_ID, + currency_code=CURRENCY_CODE + ) + +@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) + flash(f"Ошибка при загрузке на Hugging Face: {e}", 'error') + return redirect(url_for('admin')) + +@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__': + load_data() + load_users() + + if HF_TOKEN_WRITE: + backup_thread = threading.Thread(target=periodic_backup, daemon=True) + backup_thread.start() + logging.info("Periodic backup thread started.") + else: + logging.warning("Periodic backup will NOT run (HF_TOKEN for writing not set).") + + port = int(os.environ.get('PORT', 7860)) + logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}") + app.run(debug=False, host='0.0.0.0', port=port) + +# --- END OF FILE app.py ---