diff --git "a/Soola.txt" "b/Soola.txt"
new file mode 100644--- /dev/null
+++ "b/Soola.txt"
@@ -0,0 +1,2342 @@
+
+
+from flask import Flask, render_template_string, request, redirect, url_for, session, send_file, flash, jsonify, g
+import json
+import os
+import logging
+import threading
+import time
+from datetime import datetime
+from huggingface_hub import HfApi, hf_hub_download
+from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
+from werkzeug.utils import secure_filename
+from dotenv import load_dotenv
+import requests
+import uuid
+import copy
+
+load_dotenv()
+
+app = Flask(__name__)
+app.secret_key = os.getenv("FLASK_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/Soola"
+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
+UPLOAD_DELAY = 2
+BACKUP_INTERVAL = 1800
+
+logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
+
+data_lock = threading.Lock()
+users_lock = threading.Lock()
+
+app_data = {'products': [], 'categories': [], 'orders': {}}
+app_users = {}
+
+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
+ local_file_path = os.path.join(".", file_name)
+ for attempt in range(retries + 1):
+ try:
+ logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...")
+ 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,
+ cache_dir=None
+ )
+ logging.info(f"Successfully downloaded and overwrote {file_name}.")
+ 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). Checking local file.")
+ if not os.path.exists(local_file_path):
+ logging.warning(f"Local file {file_name} also not found. Creating an empty default.")
+ try:
+ default_content = {}
+ if file_name == DATA_FILE:
+ default_content = {'products': [], 'categories': [], 'orders': {}}
+ elif file_name == USERS_FILE:
+ default_content = {}
+
+ if default_content is not None:
+ with open(local_file_path, 'w', encoding='utf-8') as f:
+ json.dump(default_content, f, ensure_ascii=False, indent=4)
+ logging.info(f"Created empty local file {file_name}.")
+ except Exception as create_e:
+ logging.error(f"Failed to create empty local file {file_name}: {create_e}")
+ else:
+ logging.info(f"File {file_name} not found on HF, but exists locally. Using local version.")
+ success = True
+ 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_from_file(file_path, default_value, lock):
+ try:
+ with lock:
+ with open(file_path, 'r', encoding='utf-8') as file:
+ content = json.load(file)
+ logging.info(f"Data loaded successfully from {file_path}")
+ if file_path == DATA_FILE:
+ if not isinstance(content, dict): raise ValueError("Data file is not a dictionary")
+ if 'products' not in content: content['products'] = []
+ if 'categories' not in content: content['categories'] = []
+ if 'orders' not in content: content['orders'] = {}
+ elif file_path == USERS_FILE:
+ if not isinstance(content, dict): raise ValueError("Users file is not a dictionary")
+ return content
+ except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
+ logging.error(f"Error loading local file {file_path}: {e}. Returning default.")
+ if not os.path.exists(file_path):
+ try:
+ with lock:
+ with open(file_path, 'w', encoding='utf-8') as f:
+ json.dump(default_value, f, ensure_ascii=False, indent=4)
+ logging.info(f"Created default local file {file_path}.")
+ except Exception as create_e:
+ logging.error(f"Failed to create default local file {file_path}: {create_e}")
+ return copy.deepcopy(default_value)
+
+def load_initial_data():
+ global app_data, app_users
+ logging.info("Attempting initial data load...")
+ download_db_from_hf()
+ app_data = _load_from_file(DATA_FILE, {'products': [], 'categories': [], 'orders': {}}, data_lock)
+ app_users = _load_from_file(USERS_FILE, {}, users_lock)
+ logging.info(f"Initial load complete. Products: {len(app_data.get('products',[]))}, Categories: {len(app_data.get('categories',[]))}, Orders: {len(app_data.get('orders',{}))}, Users: {len(app_users)}")
+
+def get_data():
+ with data_lock:
+ return copy.deepcopy(app_data)
+
+def save_data(new_data):
+ global app_data
+ try:
+ if not isinstance(new_data, dict):
+ logging.error("Attempted to save invalid data structure (not a dict). Aborting save.")
+ return False
+ if 'products' not in new_data: new_data['products'] = []
+ if 'categories' not in new_data: new_data['categories'] = []
+ if 'orders' not in new_data: new_data['orders'] = {}
+
+ with data_lock:
+ app_data = copy.deepcopy(new_data)
+ with open(DATA_FILE, 'w', encoding='utf-8') as file:
+ json.dump(app_data, file, ensure_ascii=False, indent=4)
+ logging.info(f"Data successfully saved to {DATA_FILE} and memory cache updated.")
+ return True
+ except Exception as e:
+ logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True)
+ return False
+
+def get_users():
+ with users_lock:
+ return copy.deepcopy(app_users)
+
+def save_users(new_users):
+ global app_users
+ try:
+ if not isinstance(new_users, dict):
+ logging.error("Attempted to save invalid users structure (not a dict). Aborting save.")
+ return False
+ with users_lock:
+ app_users = copy.deepcopy(new_users)
+ with open(USERS_FILE, 'w', encoding='utf-8') as file:
+ json.dump(app_users, file, ensure_ascii=False, indent=4)
+ logging.info(f"User data successfully saved to {USERS_FILE} and memory cache updated.")
+ return True
+ except Exception as e:
+ logging.error(f"Error saving user data to {USERS_FILE}: {e}", exc_info=True)
+ return False
+
+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 False
+ 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}...")
+ all_successful = True
+
+ for file_name in files_to_upload:
+ if os.path.exists(file_name):
+ try:
+ lock = data_lock if file_name == DATA_FILE else users_lock
+ with lock:
+ 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.")
+ time.sleep(UPLOAD_DELAY)
+ except Exception as e:
+ logging.error(f"Error uploading file {file_name} to Hugging Face: {e}")
+ all_successful = False
+ else:
+ logging.warning(f"File {file_name} not found locally, skipping upload.")
+ all_successful = False
+
+ logging.info(f"Finished uploading files to HF. Overall success: {all_successful}")
+ return all_successful
+ except Exception as e:
+ logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True)
+ return False
+
+def periodic_backup():
+ logging.info(f"Setting up periodic backup every {BACKUP_INTERVAL} seconds.")
+ while True:
+ time.sleep(BACKUP_INTERVAL)
+ logging.info("Starting periodic backup...")
+ try:
+ upload_success = upload_db_to_hf()
+ if upload_success:
+ logging.info("Periodic backup finished successfully.")
+ else:
+ logging.warning("Periodic backup finished with errors (some files might not have been uploaded).")
+ except Exception as e:
+ logging.error(f"Error during periodic backup execution: {e}", exc_info=True)
+
+
+CATALOG_TEMPLATE = '''
+
+
+
+
+
+ Soola Cosmetics - Каталог
+
+
+
+
+
+
+
+
+
+
Наш адрес: {{ store_address }}
+
+
+ Все категории
+ {% for category in categories %}
+ {{ category }}
+ {% endfor %}
+
+
+
+
+
+
+
+ {% for product in products %}
+
+ {% if product.get('is_top', False) %}
+
Топ
+ {% endif %}
+
+ {% if product.get('photos') and product['photos']|length > 0 %}
+
+ {% else %}
+
+ {% 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 %}
+
Товары пока не добавлены.
+
+
+
+
+
+
+
+ ×
+
Укажите количество и цвет
+ Количество:
+
+ Цвет/Вариант:
+
+ Добавить в корзину
+
+
+
+
+
+
×
+
Ваша корзина
+
+
+ Итого: 0.00 {{ currency_code }}
+
+
+
+ Очистить корзину
+
+
+ Сформировать заказ
+
+
+
+
+
+
+
+ 0
+
+
+
+
+
+
+
+
+'''
+
+PRODUCT_DETAIL_TEMPLATE = '''
+
+
{{ product['name'] }}
+
+
+ {% if product.get('photos') and product['photos']|length > 0 %}
+ {% for photo in product['photos'] %}
+
+
+
+
+
+ {% 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', []) %}
+ {% set valid_colors = colors|select('ne', '')|list %}
+ {% if valid_colors %}
+
Доступные цвета/варианты: {{ valid_colors|join(', ') }}
+ {% endif %}
+
+
+ '''
+
+LOGIN_TEMPLATE = '''
+
+
+
+
+
+ Вход - Soola Cosmetics
+
+
+
+
+
+
+
+
+'''
+
+ADMIN_TEMPLATE = '''
+
+
+
+
+
+ Админ-панель - Soola Cosmetics
+
+
+
+
+
+
+
+
+ {% with messages = get_flashed_messages(with_categories=true) %}
+ {% if messages %}
+ {% for category, message in messages %}
+
{{ message }}
+ {% endfor %}
+ {% endif %}
+ {% endwith %}
+
+
+
Синхронизация с Датацентром
+
+
+
+
+
Резервное копирование происходит автоматически каждые {{ backup_interval // 60 }} минут. Используйте эти кнопки для немедленной синхронизации.
+
Сохранение данных (товары, пользователи, категории) происходит только локально, синхронизация с датацентром - по расписанию или принудительно.
+
+
+
+
+
+
+
Управление категориями
+
+ Добавить новую категорию
+
+
+
+
+
+
Существующие категории:
+ {% if categories %}
+
+ {% for category in categories %}
+
+ {{ category }}
+
+
+ {% endfor %}
+
+ {% else %}
+
Категорий пока нет.
+ {% endif %}
+
+
+
+
+
+ Управление пользователями
+
+
+ Добавить нового пользователя
+
+
+
+
Список пользователей:
+ {% if users %}
+
+ {% for login, user_data in users.items() %}
+
+
Логин: {{ login }}
+
Пароль: {{ user_data.get('password', 'N/A') }}
+
Имя: {{ 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') and product['photos']|length > 0 %}
+
+
+
+ {% 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', []) %}
+ {% set valid_colors = colors|select('ne', '')|list %}
+
Цвета/Вар-ты: {{ valid_colors|join(', ') if valid_colors else 'Нет' }}
+ {% if product.get('photos') and product['photos']|length > 1 %}
+
(Всего фото: {{ product['photos']|length }})
+ {% endif %}
+
+
+
+
+ Редактировать
+
+
+
+ Удалить
+
+
+
+
+
+ {% endfor %}
+
Товары по вашему запросу не найдены.
+
+ {% else %}
+
Товаров пока нет.
+ {% endif %}
+
+
+
+
+
+
+
+'''
+
+ORDER_TEMPLATE = '''
+
+
+
+
+
+ Заказ №{{ order.id }} - Soola Cosmetics
+
+
+
+
+
+
+ {% if order %}
+
Ваш Заказ №{{ order.id }}
+
Дата создания: {{ order.created_at }}
+
+
Товары в заказе
+
+ {% for item in order.cart %}
+
+
+
+ {{ item.name }} {% if item.color != 'N/A' %}({{ item.color }}){% endif %}
+ {{ "%.2f"|format(item.price) }} {{ currency_code }} × {{ item.quantity }}
+
+
+ {{ "%.2f"|format(item.price * item.quantity) }} {{ currency_code }}
+
+
+ {% endfor %}
+
+
+
+
Общая сумма товаров: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}
+
ИТОГО К ОПЛАТЕ: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}
+
+
+ {% if order.user_info and order.user_info.login %}
+
+
Информация о клиенте
+
Логин: {{ order.user_info.login }}
+
Имя: {{ order.user_info.get('first_name', 'N/A') }} {{ order.user_info.get('last_name', '') }}
+
Телефон: {{ order.user_info.get('phone', 'Не указан') }}
+
Страна: {{ order.user_info.get('country', 'Не указана') }}
+
Город: {{ order.user_info.get('city', 'Не указан') }}
+
Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.
+
+ {% else %}
+
+
Статус заказа
+
Этот заказ был оформлен без входа в систему или данные пользователя не сохранились.
+
Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.
+
+ {% endif %}
+
+
+
+ Отправить заказ в WhatsApp
+
+
+
← Вернуться в каталог
+
+
+
+ {% else %}
+
Ошибка
+
Заказ с таким ID не найден.
+
← Вернуться в каталог
+ {% endif %}
+
+
+
+'''
+
+@app.route('/')
+def catalog():
+ data = get_data()
+ all_products = data.get('products', [])
+ categories = sorted(data.get('categories', []))
+ is_authenticated = 'user' in session
+ user_first_name = session.get('user_info', {}).get('first_name', session.get('user', ''))
+
+ products_in_stock = [p for p in all_products if p.get('in_stock', True)]
+ products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
+
+ return render_template_string(
+ CATALOG_TEMPLATE,
+ products=products_sorted,
+ categories=categories,
+ repo_id=REPO_ID,
+ is_authenticated=is_authenticated,
+ user_first_name=user_first_name,
+ store_address=STORE_ADDRESS,
+ currency_code=CURRENCY_CODE
+ )
+
+@app.route('/product/')
+def product_detail(index):
+ data = get_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]
+ except IndexError:
+ logging.warning(f"Attempted access to non-existent or out-of-range product index {index}")
+ return "Товар не найден или отсутствует в наличии.", 404
+
+ return render_template_string(
+ PRODUCT_DETAIL_TEMPLATE,
+ product=product,
+ repo_id=REPO_ID,
+ is_authenticated=is_authenticated,
+ currency_code=CURRENCY_CODE
+ )
+
+@app.route('/product_data/')
+def product_data_for_cart(index):
+ data = get_data()
+ all_products = data.get('products', [])
+ products_in_stock = [p for p in all_products if p.get('in_stock', True)]
+ products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
+
+ try:
+ product = products_sorted[index]
+ product_info = {
+ 'name': product.get('name'),
+ 'price': product.get('price'),
+ 'colors': product.get('colors', []),
+ 'photos': product.get('photos', [])
+ }
+ return jsonify(product_info)
+ except IndexError:
+ logging.warning(f"Attempted access to product data for non-existent index {index}")
+ return jsonify({"error": "Product not found"}), 404
+ except Exception as e:
+ logging.error(f"Error fetching product data for index {index}: {e}", exc_info=True)
+ return jsonify({"error": "Server error"}), 500
+
+
+@app.route('/login', methods=['GET', 'POST'])
+def login():
+ if request.method == 'POST':
+ login_attempt = request.form.get('login')
+ password_attempt = request.form.get('password')
+ if not login_attempt or not password_attempt:
+ return render_template_string(LOGIN_TEMPLATE, error="Логин и пароль не могут быть пустыми."), 400
+
+ current_users = get_users()
+
+ if login_attempt in current_users and current_users[login_attempt].get('password') == password_attempt:
+ user_info = current_users[login_attempt]
+ session['user'] = login_attempt
+ session['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', '')
+ }
+ session.modified = True
+ logging.info(f"User {login_attempt} logged in successfully.")
+ login_response_html = f'''
+ Перенаправление...
+
+ Вход выполнен успешно. Перенаправление в каталог ...
+
+ '''
+ return login_response_html
+ else:
+ logging.warning(f"Failed login attempt for user {login_attempt}.")
+ 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 jsonify({"error": "Invalid request"}), 400
+
+ login_attempt = data.get('login')
+ if not login_attempt:
+ logging.warning("Attempted auto_login with empty login.")
+ return jsonify({"error": "Login not provided"}), 400
+
+ current_users = get_users()
+ if login_attempt in current_users:
+ user_info = current_users[login_attempt]
+ session['user'] = login_attempt
+ session['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', '')
+ }
+ session.modified = True
+ logging.info(f"Auto-login successful for user {login_attempt}.")
+ return jsonify({"message": "OK"}), 200
+ else:
+ logging.warning(f"Failed auto-login attempt for non-existent user {login_attempt}.")
+ return jsonify({"error": "Auto-login failed"}), 401
+
+@app.route('/logout')
+def logout():
+ logged_out_user = session.get('user')
+ session.pop('user', None)
+ session.pop('user_info', None)
+ session.modified = True
+ if logged_out_user:
+ logging.info(f"User {logged_out_user} logged out.")
+
+ logout_response_html = f'''
+ Выход...
+
+ Выход выполнен. Перенаправление на главную страницу ...
+
+ '''
+ return logout_response_html
+
+@app.route('/create_order', methods=['POST'])
+def create_order():
+ if 'user' not in session:
+ return jsonify({"error": "Пожалуйста, войдите в систему для создания заказа."}), 401
+
+ order_data = request.get_json()
+
+ if not order_data or 'cart' not in order_data or not isinstance(order_data['cart'], list) or not order_data['cart']:
+ logging.warning("Create order request missing cart data or cart is empty/invalid.")
+ return jsonify({"error": "Корзина пуста или не передана в верном формате."}), 400
+
+ cart_items = order_data['cart']
+ total_price = 0
+ processed_cart = []
+ data_cache = get_data()
+ products_cache = {p['name']: p for p in data_cache.get('products', [])}
+
+
+ for item in cart_items:
+ if not isinstance(item, dict) or not all(k in item for k in ('id', 'name', 'quantity', 'color')):
+ logging.error(f"Invalid cart item structure received: {item}")
+ return jsonify({"error": "Неверный формат товара в корзине."}), 400
+
+ try:
+ quantity = int(item['quantity'])
+ product_name = item['name']
+
+ if product_name not in products_cache:
+ logging.error(f"Product '{product_name}' from cart not found in server data.")
+ return jsonify({"error": f"Товар '{product_name}' не найден."}), 400
+
+ price = float(products_cache[product_name]['price'])
+ photo = products_cache[product_name].get('photos', [None])[0]
+
+
+ if price < 0 or quantity <= 0:
+ raise ValueError("Invalid price or quantity")
+
+ total_price += price * quantity
+ processed_cart.append({
+ "name": product_name,
+ "price": price,
+ "quantity": quantity,
+ "color": item.get('color', 'N/A'),
+ "photo": photo,
+ "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{photo}" if photo else "https://via.placeholder.com/60x60.png?text=N/A"
+ })
+ except (ValueError, TypeError, KeyError) as e:
+ logging.error(f"Invalid data in cart item: {item}. Error: {e}")
+ return jsonify({"error": "Неверные данные (цена, количество или товар) в корзине."}), 400
+
+ order_id = f"{datetime.now().strftime('%y%m%d%H%M%S')}-{uuid.uuid4().hex[:4]}"
+ order_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
+
+ user_info_for_order = session.get('user_info', {})
+
+ user_info_for_order_copy = {
+ k: v for k, v in user_info_for_order.items() if v
+ }
+ if 'login' not in user_info_for_order_copy and session.get('user'):
+ user_info_for_order_copy['login'] = session['user']
+
+
+ new_order = {
+ "id": order_id,
+ "created_at": order_timestamp,
+ "cart": processed_cart,
+ "total_price": round(total_price, 2),
+ "user_info": user_info_for_order_copy,
+ "status": "new"
+ }
+
+ current_data = get_data()
+ if 'orders' not in current_data or not isinstance(current_data.get('orders'), dict):
+ current_data['orders'] = {}
+
+ current_data['orders'][order_id] = new_order
+
+ if save_data(current_data):
+ logging.info(f"Order {order_id} created successfully. User: {session.get('user', 'Unknown')}")
+ return jsonify({"order_id": order_id}), 201
+ else:
+ logging.error(f"Failed to save order {order_id} to file/cache.")
+ return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500
+
+
+@app.route('/order/')
+def view_order(order_id):
+ if not order_id:
+ return "Не указан ID заказа", 400
+
+ data = get_data()
+ order = data.get('orders', {}).get(order_id)
+
+ if order:
+ if order:
+ logging.info(f"Displaying order {order_id}. User: {session.get('user', 'Anonymous')}")
+ else:
+ logging.warning(f"Order {order_id} access denied or not found after check. User: {session.get('user', 'Anonymous')}")
+
+ else:
+ logging.warning(f"Order {order_id} not found in data. User: {session.get('user', 'Anonymous')}")
+
+
+ return render_template_string(ORDER_TEMPLATE,
+ order=order,
+ repo_id=REPO_ID,
+ currency_code=CURRENCY_CODE,
+ request=request
+ )
+
+@app.route('/admin', methods=['GET', 'POST'])
+def admin():
+ current_data = get_data()
+ current_users = get_users()
+
+ if request.method == 'POST':
+ action = request.form.get('action')
+ logging.info(f"Admin action received: {action}")
+
+ data_copy = current_data
+ users_copy = current_users
+ products = data_copy.get('products', [])
+ categories = data_copy.get('categories', [])
+
+ save_needed_data = False
+ save_needed_users = False
+
+ 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_copy['categories'] = categories
+ save_needed_data = True
+ logging.info(f"Category '{category_name}' staged for adding.")
+ 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}' уже существует.", 'warning')
+
+ 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_copy['categories'] = categories
+ save_needed_data = True
+ logging.info(f"Category '{category_to_delete}' staged for deletion. Products to update: {updated_count}.")
+ flash(f"Категория '{category_to_delete}' будет удалена, {updated_count} товаров обновлено после сохранения.", 'success')
+ else:
+ logging.warning(f"Attempted to delete non-existent or empty category: {category_to_delete}")
+ flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error')
+
+ elif action == 'add_product':
+ name = request.form.get('name', '').strip()
+ price_str = request.form.get('price', '').replace(',', '.')
+ description = request.form.get('description', '').strip()
+ category = request.form.get('category')
+ photos_files = request.files.getlist('photos')
+ colors = [c.strip() for c in request.form.getlist('colors') if c.strip()]
+ 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.0
+ except ValueError:
+ flash("Неверный формат цены.", 'error')
+ return redirect(url_for('admin'))
+
+ photos_list = []
+ if photos_files and any(f.filename for f in photos_files):
+ if not HF_TOKEN_WRITE:
+ flash("HF_TOKEN (write) не настроен. Фотографии не будут загружены на сервер.", "warning")
+ else:
+ uploads_dir = 'uploads_temp'
+ os.makedirs(uploads_dir, exist_ok=True)
+ api = HfApi()
+ photo_limit = 10
+ uploaded_count = 0
+ temp_paths_to_clean = []
+ try:
+ 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:
+ ext = os.path.splitext(photo.filename)[1].lower()
+ if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
+ logging.warning(f"Skipping non-image file upload: {photo.filename}")
+ flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")
+ continue
+
+ safe_name = secure_filename(name.replace(' ', '_'))[:50].rstrip('_') or "product"
+ photo_filename = f"{safe_name}_{uuid.uuid4().hex[:8]}{ext}"
+ temp_path = os.path.join(uploads_dir, photo_filename)
+ photo.save(temp_path)
+ temp_paths_to_clean.append(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.")
+ uploaded_count += 1
+ else:
+ logging.info(f"Skipping empty file in photos list for {name}.")
+ except Exception as e:
+ logging.error(f"Error uploading photo to HF during add product: {e}", exc_info=True)
+ flash(f"Ошибка при загрузке фото на сервер. Товар будет добавлен без новых фото.", 'error')
+ photos_list = []
+ finally:
+ for path in temp_paths_to_clean:
+ if os.path.exists(path):
+ try: os.remove(path)
+ except OSError as e: logging.warning(f"Could not remove temp photo {path}: {e}")
+ if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
+ try: os.rmdir(uploads_dir)
+ except OSError as e: logging.warning(f"Could not remove temp upload dir {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)
+ save_needed_data = True
+ logging.info(f"Product '{name}' staged for adding.")
+ 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)
+ products_list_for_indexing = sorted(current_data.get('products', []), key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
+
+ if not (0 <= index < len(products_list_for_indexing)):
+ raise IndexError("Product index out of range during edit")
+
+ product_to_find_name_as_displayed = products_list_for_indexing[index]['name']
+ product_to_edit = next((p for p in products if p['name'] == product_to_find_name_as_displayed), None)
+
+ if product_to_edit is None:
+ raise ValueError(f"Could not find product with original name '{product_to_find_name_as_displayed}' in working data copy for edit. Data might have changed.")
+
+ original_name_for_logging = product_to_edit.get('name', 'N/A')
+ logging.info(f"Editing product '{original_name_for_logging}' (original index {index})")
+
+ except (ValueError, IndexError) as e:
+ logging.error(f"Error finding product for edit at index '{index_str}': {e}", exc_info=True)
+ flash(f"Ошибка редактирования: не удалось найти товар (индекс: {index_str}).", 'error')
+ 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.get('price', 0))).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.0
+ product_to_edit['price'] = price
+ except ValueError:
+ logging.warning(f"Invalid price format '{price_str}' during edit of product {original_name_for_logging}. Price not changed.")
+ flash(f"Неверный формат цены для товара '{original_name_for_logging}'. Цена не изменена.", 'warning')
+
+ photos_files = request.files.getlist('photos')
+ if photos_files and any(f.filename for f in photos_files):
+ if not HF_TOKEN_WRITE:
+ flash("HF_TOKEN (write) не настроен. Фотографии не будут обновлены на сервере.", "warning")
+ else:
+ uploads_dir = 'uploads_temp'
+ os.makedirs(uploads_dir, exist_ok=True)
+ api = HfApi()
+ new_photos_list = []
+ photo_limit = 10
+ uploaded_count = 0
+ temp_paths_to_clean = []
+ logging.info(f"Uploading NEW photos for product {product_to_edit['name']}...")
+ try:
+ for photo in photos_files:
+ if uploaded_count >= photo_limit:
+ flash(f"Будет загружено только первые {photo_limit} фото.", "warning")
+ break
+ if photo and photo.filename:
+ ext = os.path.splitext(photo.filename)[1].lower()
+ if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
+ flash(f"Файл {photo.filename} пропущен (не изображение).", "warning")
+ continue
+
+ safe_name = secure_filename(product_to_edit['name'].replace(' ', '_'))[:50].rstrip('_') or "product"
+ photo_filename = f"{safe_name}_{uuid.uuid4().hex[:8]}{ext}"
+ temp_path = os.path.join(uploads_dir, photo_filename)
+ photo.save(temp_path)
+ temp_paths_to_clean.append(temp_path)
+
+ api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}",
+ repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
+ 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.")
+ uploaded_count += 1
+ else:
+ logging.info(f"Skipping empty file in photos list during edit for {product_to_edit['name']}.")
+
+ if new_photos_list:
+ old_photos = product_to_edit.get('photos', [])
+ product_to_edit['photos'] = new_photos_list
+ flash("Новые фотографии загружены.", "success")
+ if old_photos:
+ logging.info(f"Attempting to delete old photos: {old_photos}")
+ try:
+ paths_to_delete = [f"photos/{p}" for p in old_photos if p]
+ if paths_to_delete:
+ api.delete_files(
+ repo_id=REPO_ID,
+ paths_in_repo=paths_to_delete,
+ 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.")
+ else:
+ logging.info("No valid old photo paths to delete.")
+ except Exception as e:
+ logging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True)
+ flash("Не удалось удалить старые фотографии с сервера. Новые фото загружены.", "warning")
+ elif uploaded_count == 0 and any(f.filename for f in photos_files):
+ flash("Не удалось загрузить новые фотографии (возможно, неверный формат). Старые фото сохранены.", "error")
+
+ except Exception as e:
+ logging.error(f"Error during new photo upload/processing for edit: {e}", exc_info=True)
+ flash("Ошибка при загрузке/обработке новых фото.", "error")
+ finally:
+ for path in temp_paths_to_clean:
+ if os.path.exists(path):
+ try: os.remove(path)
+ except OSError: pass
+ if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
+ try: os.rmdir(uploads_dir)
+ except OSError: pass
+
+ save_needed_data = True
+ logging.info(f"Product '{original_name_for_logging}' staged for update 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)
+ products_list_for_indexing = sorted(current_data.get('products', []), key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
+
+ if not (0 <= index < len(products_list_for_indexing)):
+ raise IndexError("Product index out of range for deletion")
+
+ product_to_delete_info = products_list_for_indexing[index]
+ product_name_to_delete = product_to_delete_info.get('name', 'N/A')
+ photos_to_delete = product_to_delete_info.get('photos', [])
+
+ initial_len = len(products)
+ products[:] = [p for p in products if p['name'] != product_name_to_delete]
+
+ if len(products) == initial_len:
+ raise ValueError(f"Product '{product_name_to_delete}' not found in working copy for deletion. Data might have changed.")
+
+ save_needed_data = True
+ logging.info(f"Product '{product_name_to_delete}' (original index {index}) staged for deletion.")
+
+ if photos_to_delete and HF_TOKEN_WRITE:
+ logging.info(f"Attempting to delete photos for product '{product_name_to_delete}' from HF: {photos_to_delete}")
+ try:
+ api = HfApi()
+ paths_to_delete = [f"photos/{p}" for p in photos_to_delete if p]
+ if paths_to_delete:
+ api.delete_files(
+ repo_id=REPO_ID,
+ paths_in_repo=paths_to_delete,
+ repo_type="dataset",
+ token=HF_TOKEN_WRITE,
+ commit_message=f"Delete photos for deleted product {product_name_to_delete}"
+ )
+ logging.info(f"Photos for product '{product_name_to_delete}' deleted from HF.")
+ flash(f"Товар '{product_name_to_delete}' и его фото будут удалены после сохранения.", 'success')
+ else:
+ flash(f"Товар '{product_name_to_delete}' будет удален после сохранения (фото не найдены).", 'success')
+
+ except Exception as e:
+ logging.error(f"Error deleting photos {photos_to_delete} for product '{product_name_to_delete}' from HF: {e}", exc_info=True)
+ flash(f"Товар '{product_name_to_delete}' будет удален, но не удалось удалить фото с сервера.", "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_to_delete}'.")
+ flash(f"Товар '{product_name_to_delete}' будет удален, но фото не удалены с сервера (токен не задан).", "warning")
+ else:
+ flash(f"Товар '{product_name_to_delete}' будет удален после сохранения.", 'success')
+
+ except (ValueError, IndexError) as e:
+ flash(f"Ошибка удаления: неверный индекс товара '{index_str}' или товар не найден. Возможно, данные изменились.", 'error')
+ logging.error(f"Error during product deletion: {e}", exc_info=True)
+
+ elif action == 'add_user':
+ login = request.form.get('login', '').strip()
+ password = request.form.get('password', '').strip()
+ 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_copy:
+ flash(f"Пользователь с логином '{login}' уже существует.", 'error')
+ return redirect(url_for('admin'))
+
+ users_copy[login] = {
+ 'password': password,
+ 'first_name': first_name, 'last_name': last_name,
+ 'phone': phone,
+ 'country': country, 'city': city
+ }
+ save_needed_users = True
+ logging.info(f"User '{login}' staged for adding.")
+ 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_copy:
+ del users_copy[login_to_delete]
+ save_needed_users = True
+ logging.info(f"User '{login_to_delete}' staged for deletion.")
+ flash(f"Пользователь '{login_to_delete}' будет удален после сохранения.", 'success')
+ elif login_to_delete:
+ logging.warning(f"Attempted to delete non-existent user: {login_to_delete}")
+ flash(f"Пользователь '{login_to_delete}' не найден.", 'error')
+ else:
+ flash("Не указан логин пользователя для удаления.", 'error')
+
+
+ else:
+ logging.warning(f"Received unknown admin action: {action}")
+ flash(f"Неизвестное действие: {action}", 'warning')
+
+
+ final_save_success = True
+ if save_needed_data:
+ data_copy['products'].sort(key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
+ if not save_data(data_copy):
+ flash("Ошибка при сохранении основных данных (товары/категории).", 'error')
+ final_save_success = False
+ if save_needed_users:
+ if not save_users(users_copy):
+ flash("Ошибка при сохранении данных пользователей.", 'error')
+ final_save_success = False
+
+ if final_save_success and (save_needed_data or save_needed_users):
+ flash("Все изменения успешно сохранены локально.", 'success')
+
+
+ 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'))
+
+
+ display_data = get_data()
+ display_users = get_users()
+ display_products = sorted(display_data.get('products', []), key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
+ display_categories = sorted(display_data.get('categories', []))
+ display_users_sorted = dict(sorted(display_users.items()))
+
+ return render_template_string(
+ ADMIN_TEMPLATE,
+ products=display_products,
+ categories=display_categories,
+ users=display_users_sorted,
+ repo_id=REPO_ID,
+ currency_code=CURRENCY_CODE,
+ backup_interval=BACKUP_INTERVAL
+ )
+
+@app.route('/force_upload', methods=['POST'])
+def force_upload():
+ logging.info("Forcing upload to Hugging Face via admin request...")
+ try:
+ success = upload_db_to_hf()
+ if success:
+ flash("Данные успешно загружены на Hugging Face.", 'success')
+ else:
+ flash("Во время загрузки на Hugging Face произошли ошибки (не все файлы могли быть загружены). Проверьте логи.", 'warning')
+ 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 via admin request...")
+ try:
+ if download_db_from_hf():
+ load_initial_data()
+ 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__':
+ logging.info("Application starting up...")
+
+ logging.info("Performing initial data load from local files or HF...")
+ load_initial_data()
+ logging.info("Initial data load complete.")
+
+ 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 thread *not* started (HF_TOKEN_WRITE not set).")
+
+ port = int(os.environ.get('PORT', 7860))
+ logging.info(f"Starting Flask app server on host 0.0.0.0 and port {port}")
+
+ try:
+ from waitress import serve
+ serve(app, host='0.0.0.0', port=port, threads=8)
+ except ImportError:
+ logging.warning("Waitress not found. Falling back to Flask development server.")
+ logging.warning("Install waitress for a production-ready server: pip install waitress")
+ app.run(debug=False, host='0.0.0.0', port=port)
+