Ca / app.py
Shveiauto's picture
Update app.py
554ac0a verified
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)
products = app_data.get('products', [])
migrated = False
for p in products:
if 'id' not in p or not p['id']:
p['id'] = uuid.uuid4().hex
migrated = True
if migrated:
logging.info("Migrated products to include unique IDs. Saving data.")
save_data(app_data)
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 = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Soola Cosmetics - Каталог</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<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/Swiper/10.2.0/swiper-bundle.min.css" integrity="sha512-L8ZW2wXCB3pdJzccRFhJcYmQJdWuk73P/GNTuO9soL350tF/IMYut8zz7IQSd914lAWVRWb6I+z/g5q8Sa04KQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Poppins', sans-serif; background: #f0f9f4; color: #2d332f; line-height: 1.6; transition: background 0.3s, color 0.3s; }
body.dark-mode { background: #1a2b26; color: #c8d8d3; }
.container { max-width: 1300px; margin: 0 auto; padding: 20px; }
.header { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; border-bottom: 1px solid #d1e7dd; }
body.dark-mode .header { border-bottom-color: #2c4a41; }
.header h1 { font-size: 1.8rem; font-weight: 600; color: #1C6758; }
.auth-links { display: flex; gap: 15px; align-items: center; }
.auth-links a { color: #3D8361; text-decoration: none; font-weight: 500; }
.auth-links a:hover { text-decoration: underline; }
body.dark-mode .auth-links a { color: #55a683; }
.auth-links span { font-weight: 500; }
body.dark-mode .auth-links span { color: #b0c8c1;}
.theme-toggle { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #7a8d85; transition: color 0.3s ease; }
.theme-toggle:hover { color: #3D8361; }
body.dark-mode .theme-toggle { color: #8aa39a; }
body.dark-mode .theme-toggle:hover { color: #55a683; }
.store-address { padding: 15px; text-align: center; background-color: #ffffff; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); font-size: 1rem; color: #44524c; }
body.dark-mode .store-address { background-color: #253f37; color: #b0c8c1; }
.filters-container { margin: 20px 0; display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; }
.search-container { margin: 20px 0; text-align: center; }
#search-input { width: 90%; max-width: 600px; padding: 12px 18px; font-size: 1rem; border: 1px solid #d1e7dd; border-radius: 25px; outline: none; box-shadow: 0 2px 5px rgba(0,0,0,0.05); transition: all 0.3s ease; }
body.dark-mode #search-input { background-color: #253f37; border-color: #2c4a41; color: #c8d8d3; }
#search-input:focus { border-color: #1C6758; box-shadow: 0 0 0 3px rgba(28, 103, 88, 0.2); }
body.dark-mode #search-input:focus { border-color: #3D8361; box-shadow: 0 0 0 3px rgba(61, 131, 97, 0.3); }
.category-filter { padding: 8px 16px; border: 1px solid #d1e7dd; border-radius: 20px; background-color: #fff; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.9rem; font-weight: 400; color: #1C6758; }
body.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; }
.product-price { font-size: 1.2rem; color: #1C6758; font-weight: 700; text-align: center; margin: 5px 0; }
body.dark-mode .product-price { color: #55a683; }
.product-description { font-size: 0.85rem; color: #7a8d85; text-align: center; margin-bottom: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
body.dark-mode .product-description { color: #8aa39a; }
.product-actions { padding: 0 15px 15px 15px; display: flex; flex-direction: column; gap: 8px; }
.product-button { display: block; width: 100%; padding: 10px; border: none; border-radius: 8px; background-color: #1C6758; color: white; font-size: 0.9rem; font-weight: 500; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); text-align: center; text-decoration: none; }
.product-button:hover { background-color: #164B41; box-shadow: 0 4px 15px rgba(22, 75, 65, 0.4); transform: translateY(-2px); }
.product-button i { margin-right: 5px; }
.add-to-cart { background-color: #38a169; }
.add-to-cart:hover { background-color: #2f855a; box-shadow: 0 4px 15px rgba(47, 133, 90, 0.4); }
#cart-button { position: fixed; bottom: 25px; right: 25px; background-color: #1C6758; color: white; border: none; border-radius: 50%; width: 55px; height: 55px; font-size: 1.5rem; cursor: pointer; display: none; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(28, 103, 88, 0.4); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1000; }
#cart-button .fa-shopping-cart { margin-right: 0; }
#cart-button span { position: absolute; top: -5px; right: -5px; background-color: #38a169; color: white; border-radius: 50%; padding: 2px 6px; font-size: 0.7rem; font-weight: bold; }
.modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); backdrop-filter: blur(5px); overflow-y: auto; }
.modal-content { background: #f8fcfb; margin: 5% auto; padding: 25px; border-radius: 15px; width: 90%; max-width: 700px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); animation: slideIn 0.3s ease-out; position: relative; }
body.dark-mode .modal-content { background: #253f37; color: #c8d8d3; }
@keyframes slideIn { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
.close { position: absolute; top: 15px; right: 15px; font-size: 1.8rem; color: #aaa; cursor: pointer; transition: color 0.3s; line-height: 1; }
.close:hover { color: #333; }
body.dark-mode .close { color: #7a8d85; }
body.dark-mode .close:hover { color: #b0c8c1; }
.modal-content h2 { margin-top: 0; margin-bottom: 20px; color: #1C6758; display: flex; align-items: center; gap: 10px;}
body.dark-mode .modal-content h2 { color: #55a683; }
.cart-item { display: grid; grid-template-columns: auto 1fr auto auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #d1e7dd; }
body.dark-mode .cart-item { border-bottom-color: #2c4a41; }
.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; }
body.dark-mode .quantity-input, body.dark-mode .color-select { background-color: #1a2b26; border-color: #2c4a41; color: #c8d8d3; }
.cart-summary { margin-top: 20px; text-align: right; border-top: 1px solid #d1e7dd; padding-top: 15px; }
body.dark-mode .cart-summary { border-top-color: #2c4a41; }
.cart-summary strong { font-size: 1.2rem; }
.cart-actions { margin-top: 25px; display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.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, bottom 0.5s ease; font-size: 0.9rem;}
.notification.show { opacity: 1; bottom: 90px; }
#notification-placeholder { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); z-index: 1002; width: auto; max-width: 90%; display: flex; flex-direction: column-reverse; align-items: center; gap: 10px; pointer-events: none; }
.no-results-message { grid-column: 1 / -1; text-align: center; padding: 40px; font-size: 1.1rem; color: #5e6e68; }
body.dark-mode .no-results-message { color: #8aa39a; }
.top-product-indicator { position: absolute; top: 8px; right: 8px; background-color: rgba(255, 215, 0, 0.8); color: #333; padding: 2px 6px; font-size: 0.7rem; border-radius: 4px; font-weight: bold; z-index: 10; backdrop-filter: blur(2px); }
.product { position: relative; }
@media (min-width: 768px) { .products-grid { grid-template-columns: repeat(3, 1fr); } }
@media (min-width: 1024px) { .products-grid { grid-template-columns: repeat(4, 1fr); } }
@media (min-width: 1200px) { .products-grid { grid-template-columns: repeat(5, 1fr); } }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Soola Cosmetics</h1>
<div class="auth-links">
{% if is_authenticated %}
<span>Привет, {{ user_first_name }}!</span>
{% if is_admin %}<a href="{{ url_for('admin') }}">Админ</a>{% endif %}
<a href="{{ url_for('logout') }}">Выйти</a>
{% else %}
<a href="{{ url_for('login') }}">Войти</a>
{% endif %}
</div>
<button class="theme-toggle" onclick="toggleTheme()" aria-label="Переключить тему">
<i class="fas fa-moon"></i>
</button>
</div>
<div class="store-address">Наш адрес: {{ store_address }}</div>
<div class="filters-container">
<button class="category-filter active" data-category="all">Все категории</button>
{% for category in categories %}
<button class="category-filter" data-category="{{ category }}">{{ category }}</button>
{% endfor %}
</div>
<div class="search-container">
<input type="text" id="search-input" placeholder="Поиск по названию или описанию...">
</div>
<div class="products-grid" id="products-grid">
{% for product in products %}
<div class="product"
data-id="{{ product.id }}"
data-name="{{ product['name']|lower }}"
data-description="{{ product.get('description', '')|lower }}"
data-category="{{ product.get('category', 'Без категории') }}">
{% if product.get('is_top', False) %}
<span class="top-product-indicator"><i class="fas fa-star"></i> Топ</span>
{% endif %}
<div class="product-image">
{% if product.get('photos') and product['photos']|length > 0 %}
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}"
alt="{{ product['name'] }}"
loading="lazy"
onerror="this.onerror=null; this.src='https://via.placeholder.com/250x250.png?text=Img+Error'">
{% else %}
<img src="https://via.placeholder.com/250x250.png?text=No+Image" alt="No Image" loading="lazy">
{% endif %}
</div>
<div class="product-info">
<h2>{{ product['name'] }}</h2>
{% if is_authenticated %}
<div class="product-price">{{ "%.2f"|format(product['price']) }} {{ currency_code }}</div>
{% else %}
<div class="product-price">Цена доступна после входа</div>
{% endif %}
<p class="product-description">{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}</p>
</div>
<div class="product-actions">
<button class="product-button" onclick="openModal(this.closest('.product').dataset.id)">Подробнее</button>
{% if is_authenticated %}
<button class="product-button add-to-cart" onclick="openQuantityModal(this.closest('.product').dataset.id)">
<i class="fas fa-cart-plus"></i> В корзину
</button>
{% endif %}
</div>
</div>
{% endfor %}
<p class="no-results-message" style="display: {% if not products %}block{% else %}none{% endif %};">Товары пока не добавлены.</p>
</div>
</div>
<div id="productModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span>
<div id="modalContent">Загрузка...</div>
</div>
</div>
<div id="quantityModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">×</span>
<h2>Укажите количество и цвет</h2>
<label for="quantityInput">Количество:</label>
<input type="number" id="quantityInput" class="quantity-input" min="1" value="1">
<label for="colorSelect">Цвет/Вариант:</label>
<select id="colorSelect" class="color-select"></select>
<button class="product-button add-to-cart" onclick="confirmAddToCart()"><i class="fas fa-check"></i> Добавить в корзину</button>
</div>
</div>
<div id="cartModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span>
<h2><i class="fas fa-shopping-cart"></i> Ваша корзина</h2>
<div id="cartContent"><p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p></div>
<div class="cart-summary">
<strong>Итого: <span id="cartTotal">0.00</span> {{ currency_code }}</strong>
</div>
<div class="cart-actions">
<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>
</div>
<button id="cart-button" onclick="openCartModal()" aria-label="Открыть корзину">
<i class="fas fa-shopping-cart"></i>
<span id="cart-count">0</span>
</button>
<div id="notification-placeholder"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js" integrity="sha512-QgdH1tGLN04rv7KMwvIdnLKSbY0bY25L2nQvQvJ6sJ/8L3Xpdxwz3B+zGzNfL8/4td/KBJ3GlgbZ9zcKNjYj7Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
const repoId = '{{ repo_id }}';
const currencyCode = '{{ currency_code }}';
const isAuthenticated = {{ is_authenticated|tojson }};
let selectedProductId = null;
let cart = JSON.parse(localStorage.getItem('soolaCart') || '[]');
let currentProductsData = [];
function toggleTheme() {
document.body.classList.toggle('dark-mode');
const icon = document.querySelector('.theme-toggle i');
const isDarkMode = document.body.classList.contains('dark-mode');
icon.classList.toggle('fa-moon', !isDarkMode);
icon.classList.toggle('fa-sun', isDarkMode);
localStorage.setItem('soolaTheme', isDarkMode ? 'dark' : 'light');
}
function applyInitialTheme() {
const savedTheme = localStorage.getItem('soolaTheme');
if (savedTheme === 'dark') {
document.body.classList.add('dark-mode');
const icon = document.querySelector('.theme-toggle i');
if (icon) icon.classList.replace('fa-moon', 'fa-sun');
} else {
const icon = document.querySelector('.theme-toggle i');
if (icon) icon.classList.replace('fa-sun', 'fa-moon');
}
}
function attemptAutoLogin() {
const storedUser = localStorage.getItem('soolaUser');
if (storedUser && !isAuthenticated) {
console.log('Attempting auto-login for:', storedUser);
fetch('/auto_login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ login: storedUser })
})
.then(response => {
if (response.ok) {
console.log('Auto-login successful, reloading...');
window.location.reload();
} else {
response.text().then(text => console.warn(`Auto-login failed: ${response.status} ${text}. Removing stored user.`));
localStorage.removeItem('soolaUser');
}
})
.catch(error => {
console.error('Auto-login fetch error:', error);
localStorage.removeItem('soolaUser');
});
}
}
function openModal(productId) {
const modal = document.getElementById('productModal');
const modalContent = document.getElementById('modalContent');
if (!modal || !modalContent) return;
modalContent.innerHTML = '<p style="text-align:center; padding: 40px;">Загрузка...</p>';
modal.style.display = "block";
document.body.style.overflow = 'hidden';
fetch('/product/' + productId)
.then(response => {
if (!response.ok) throw new Error(`Ошибка ${response.status}: ${response.statusText}`);
return response.text();
})
.then(data => {
modalContent.innerHTML = data;
initializeSwiper();
})
.catch(error => {
console.error('Ошибка загрузки деталей продукта:', error);
modalContent.innerHTML = `<p style="color: red; text-align:center; padding: 40px;">Не удалось загрузить информацию о товаре. ${error.message}</p>`;
});
}
function closeModal(modalId) {
const modal = document.getElementById(modalId);
if (modal) {
modal.style.display = "none";
if (modalId === 'productModal') {
const modalContent = document.getElementById('modalContent');
if(modalContent) modalContent.innerHTML = '';
}
}
const anyModalOpen = document.querySelector('.modal[style*="display: block"]');
if (!anyModalOpen) {
document.body.style.overflow = 'auto';
}
}
function initializeSwiper() {
const swiperContainer = document.querySelector('#productModal .swiper-container');
if (swiperContainer && typeof Swiper !== 'undefined') {
if (swiperContainer.swiper) {
swiperContainer.swiper.destroy(true, true);
}
new Swiper(swiperContainer, {
slidesPerView: 1,
spaceBetween: 20,
loop: swiperContainer.querySelectorAll('.swiper-slide').length > 1,
grabCursor: true,
pagination: { el: '.swiper-pagination', clickable: true },
navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
zoom: { maxRatio: 3, containerClass: 'swiper-zoom-container' },
observer: true,
observeParents: true
});
}
}
async function getProductDataForCart(productId) {
try {
const response = await fetch('/product_data/' + productId);
if (!response.ok) throw new Error(`Failed to fetch product data: ${response.status}`);
return await response.json();
} catch (error) {
console.error("Error fetching product data for cart:", error);
return null;
}
}
async function openQuantityModal(productId) {
if (!isAuthenticated) {
alert('Пожалуйста, войдите в систему, чтобы добавить товар в корзину.');
window.location.href = '/login';
return;
}
selectedProductId = productId;
const product = await getProductDataForCart(productId);
if (!product) {
console.error("Product data not found for id:", productId);
alert("Ошибка: информация о товаре не найдена.");
return;
}
window.currentProductForCart = product;
const colorSelect = document.getElementById('colorSelect');
const colorLabel = document.querySelector('label[for="colorSelect"]');
colorSelect.innerHTML = '';
const validColors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : [];
if (validColors.length > 0) {
validColors.forEach(color => {
const option = document.createElement('option');
option.value = color.trim();
option.text = color.trim();
colorSelect.appendChild(option);
});
colorSelect.style.display = 'block';
if(colorLabel) colorLabel.style.display = 'block';
} else {
colorSelect.style.display = 'none';
if(colorLabel) colorLabel.style.display = 'none';
const option = document.createElement('option');
option.value = 'N/A';
option.text = 'N/A';
colorSelect.appendChild(option);
}
document.getElementById('quantityInput').value = 1;
const modal = document.getElementById('quantityModal');
if(modal) {
modal.style.display = 'block';
document.body.style.overflow = 'hidden';
}
}
function confirmAddToCart() {
const product = window.currentProductForCart;
if (selectedProductId === null || !product) {
alert("Ошибка добавления: товарные данные не найдены. Попробуйте снова.");
closeModal('quantityModal');
return;
}
const quantityInput = document.getElementById('quantityInput');
const quantity = parseInt(quantityInput.value);
const colorSelect = document.getElementById('colorSelect');
const color = (colorSelect.style.display !== 'none' && colorSelect.value) ? colorSelect.value : 'N/A';
if (isNaN(quantity) || quantity <= 0) {
alert("Пожалуйста, укажите корректное количество (больше 0).");
quantityInput.focus();
return;
}
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,
quantity: quantity,
color: color
});
}
localStorage.setItem('soolaCart', JSON.stringify(cart));
closeModal('quantityModal');
updateCartButton();
showNotification(`${product.name} ${color !== 'N/A' ? '('+color+') ' : ''}добавлен в корзину!`);
window.currentProductForCart = null;
}
function updateCartButton() {
const cartCountElement = document.getElementById('cart-count');
const cartButton = document.getElementById('cart-button');
if (!cartCountElement || !cartButton) return;
let totalItems = 0;
cart.forEach(item => { totalItems += item.quantity; });
if (totalItems > 0 && isAuthenticated) {
cartCountElement.textContent = totalItems;
cartButton.style.display = 'flex';
} else {
cartCountElement.textContent = '0';
cartButton.style.display = 'none';
}
}
function openCartModal() {
const cartContent = document.getElementById('cartContent');
const cartTotalElement = document.getElementById('cartTotal');
if (!cartContent || !cartTotalElement) return;
let total = 0;
if (cart.length === 0) {
cartContent.innerHTML = '<p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p>';
cartTotalElement.textContent = '0.00';
document.querySelector('.formulate-order-button').disabled = true;
} else {
document.querySelector('.formulate-order-button').disabled = false;
cartContent.innerHTML = cart.map(item => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
const photoUrl = item.photo
? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${encodeURIComponent(item.photo)}`
: 'https://via.placeholder.com/60x60.png?text=N/A';
const colorText = item.color !== 'N/A' ? ` (Цвет: ${item.color})` : '';
return `
<div class="cart-item">
<img src="${photoUrl}" alt="${item.name}" loading="lazy" onerror="this.onerror=null; this.src='https://via.placeholder.com/60x60.png?text=Err'">
<div class="cart-item-details">
<strong>${item.name}${colorText}</strong>
<p class="cart-item-price">${item.price.toFixed(2)} ${currencyCode} &times; ${item.quantity}</p>
</div>
<span class="cart-item-total">${itemTotal.toFixed(2)} ${currencyCode}</span>
<button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="Удалить товар">&times;</button>
</div>
`;
}).join('');
cartTotalElement.textContent = total.toFixed(2);
}
const modal = document.getElementById('cartModal');
if (modal) {
modal.style.display = 'block';
document.body.style.overflow = 'hidden';
}
}
function removeFromCart(itemId) {
cart = cart.filter(item => item.id !== itemId);
localStorage.setItem('soolaCart', JSON.stringify(cart));
openCartModal();
updateCartButton();
}
function clearCart() {
if (confirm("Вы уверены, что хотите очистить корзину?")) {
cart = [];
localStorage.removeItem('soolaCart');
openCartModal();
updateCartButton();
}
}
function formulateOrder() {
if (cart.length === 0) {
alert("Корзина пуста! Добавьте товары перед формированием заказа.");
return;
}
if (!isAuthenticated) {
alert("Пожалуйста, войдите в систему, чтобы сформировать заказ.");
window.location.href = '/login';
return;
}
const formulateButton = document.querySelector('.formulate-order-button');
if (formulateButton) formulateButton.disabled = true;
showNotification("Формируем заказ...", 5000);
fetch('/create_order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cart: cart })
})
.then(response => {
if (!response.ok) {
return response.json().then(err => { throw new Error(err.error || `Ошибка сервера ${response.status}`); });
}
return response.json();
})
.then(data => {
if (data.order_id) {
localStorage.removeItem('soolaCart');
cart = [];
updateCartButton();
closeModal('cartModal');
window.location.href = `/order/${data.order_id}`;
} else {
throw new Error('Не получен ID заказа от сервера.');
}
})
.catch(error => {
console.error('Ошибка при формировании заказа:', error);
alert(`Не удалось сформировать заказ: ${error.message}`);
if (formulateButton) formulateButton.disabled = false;
});
}
function filterProducts() {
const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();
const activeCategoryButton = document.querySelector('.category-filter.active');
const activeCategory = activeCategoryButton ? activeCategoryButton.dataset.category : 'all';
const grid = document.getElementById('products-grid');
const productElements = grid.querySelectorAll('.product');
const noResultsMessage = grid.querySelector('.no-results-message');
let visibleProducts = 0;
productElements.forEach(productElement => {
const name = productElement.getAttribute('data-name') || '';
const description = productElement.getAttribute('data-description') || '';
const category = productElement.getAttribute('data-category') || '';
const matchesSearch = !searchTerm || name.includes(searchTerm) || description.includes(searchTerm);
const matchesCategory = activeCategory === 'all' || category === activeCategory;
if (matchesSearch && matchesCategory) {
productElement.style.display = 'flex';
visibleProducts++;
} else {
productElement.style.display = 'none';
}
});
if (noResultsMessage) {
noResultsMessage.style.display = (visibleProducts === 0 && productElements.length > 0) ? 'block' : 'none';
}
}
function setupFilters() {
const searchInput = document.getElementById('search-input');
const categoryFilters = document.querySelectorAll('.category-filter');
if(searchInput) {
searchInput.addEventListener('input', filterProducts);
}
categoryFilters.forEach(filter => {
filter.addEventListener('click', function() {
categoryFilters.forEach(f => f.classList.remove('active'));
this.classList.add('active');
filterProducts();
});
});
filterProducts();
}
function showNotification(message, duration = 3000, type = 'success') {
const placeholder = document.getElementById('notification-placeholder');
if (!placeholder) return;
const notification = document.createElement('div');
notification.className = 'notification';
notification.textContent = message;
if(type === 'error') {
notification.style.backgroundColor = '#f56565';
} else {
notification.style.backgroundColor = '#38a169';
}
placeholder.appendChild(notification);
void notification.offsetWidth;
notification.classList.add('show');
setTimeout(() => {
notification.classList.remove('show');
notification.addEventListener('transitionend', () => notification.remove());
}, duration);
}
document.addEventListener('DOMContentLoaded', () => {
applyInitialTheme();
attemptAutoLogin();
updateCartButton();
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 => {
closeModal(modal.id);
});
}
});
});
</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;">
<div class="swiper-wrapper">
{% if product.get('photos') and product['photos']|length > 0 %}
{% for photo in product['photos'] %}
<div class="swiper-slide" style="display: flex; justify-content: center; align-items: center; padding: 10px;">
<div class="swiper-zoom-container">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}"
alt="{{ product['name'] }} - фото {{ loop.index }}"
style="max-width: 100%; max-height: 400px; object-fit: contain; display: block; margin: auto; cursor: grab;"
loading="lazy"
onerror="this.onerror=null; this.src='https://via.placeholder.com/400x400.png?text=Img+Error'">
</div>
</div>
{% endfor %}
{% else %}
<div class="swiper-slide" style="display: flex; justify-content: center; align-items: center;">
<img src="https://via.placeholder.com/400x400.png?text=No+Image" alt="Изображение отсутствует" style="max-width: 100%; max-height: 400px; object-fit: contain;">
</div>
{% endif %}
</div>
{% if product.get('photos') and product['photos']|length > 1 %}
<div class="swiper-pagination" style="position: relative; bottom: 5px;"></div>
<div class="swiper-button-next" style="color: #1C6758;"></div>
<div class="swiper-button-prev" style="color: #1C6758;"></div>
{% endif %}
</div>
<div style="margin-top: 20px; font-size: 1rem; line-height: 1.7;">
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
{% if is_authenticated %}
<p style="font-size: 1.2rem; font-weight: bold; color: #1C6758;"><strong>Цена:</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p>
{% else %}
<p><strong>Цена:</strong> <a href="{{ url_for('login') }}" style="color: #3D8361; text-decoration: underline;">Доступна после входа</a></p>
{% endif %}
<p><strong>Описание:</strong><br> {{ product.get('description', 'Описание отсутствует.')|replace('\\n', '<br>')|safe }}</p>
{% set colors = product.get('colors', []) %}
{% set valid_colors = colors|select('ne', '')|list %}
{% if valid_colors %}
<p><strong>Доступные цвета/варианты:</strong> {{ valid_colors|join(', ') }}</p>
{% endif %}
</div>
</div>
'''
LOGIN_TEMPLATE = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Вход - Soola Cosmetics</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
<style>
body { font-family: 'Poppins', sans-serif; background: linear-gradient(135deg, #d1e7dd, #e9f5f0); display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 20px; }
.container { max-width: 400px; width: 100%; background: #fff; padding: 30px 40px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.1); text-align: center; }
h2 { color: #1C6758; margin-bottom: 25px; font-weight: 600; }
label { display: block; text-align: left; margin: 15px 0 5px; font-weight: 500; color: #44524c; }
input[type="text"], input[type="password"] { width: 100%; padding: 12px; margin-bottom: 15px; border: 1px solid #c4d9d1; border-radius: 8px; box-sizing: border-box; font-size: 1rem; }
input:focus { border-color: #1C6758; outline: none; box-shadow: 0 0 0 2px rgba(28, 103, 88, 0.2); }
button { width: 100%; padding: 12px; background-color: #1C6758; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 1rem; font-weight: 600; transition: background-color 0.3s ease; margin-top: 10px; }
button:hover { background-color: #164B41; }
.error { color: #721c24; background-color: #f8d7da; border: 1px solid #f5c6cb; padding: 10px; border-radius: 8px; margin-bottom: 15px; font-size: 0.9rem; text-align: left;}
.back-link { display: inline-block; margin-top: 20px; color: #3D8361; text-decoration: none; font-size: 0.9rem; }
.back-link:hover { text-decoration: underline; }
</style>
</head>
<body>
<div class="container">
<h2>Вход в Soola Cosmetics</h2>
{% if error %}
<p class="error">{{ error }}</p>
{% endif %}
<form method="POST" id="loginForm">
<label for="login">Логин:</label>
<input type="text" id="login" name="login" required>
<label for="password">Пароль:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Войти</button>
</form>
<a href="{{ url_for('catalog') }}" class="back-link">← Вернуться в каталог</a>
</div>
<script>
const form = document.getElementById('loginForm');
if (form) {
form.addEventListener('submit', function(event) {
const loginInput = document.getElementById('login');
if (loginInput && loginInput.value) {
}
});
}
</script>
</body>
</html>
'''
ADMIN_TEMPLATE = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Админ-панель - 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" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
body { font-family: 'Poppins', sans-serif; background-color: #e9f5f0; color: #2d332f; padding: 20px; line-height: 1.6; }
.container { max-width: 1200px; margin: 0 auto; background-color: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.05); }
.header { padding-bottom: 15px; margin-bottom: 25px; border-bottom: 1px solid #d1e7dd; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;}
h1, h2, h3 { font-weight: 600; color: #1C6758; margin-bottom: 15px; }
h1 { font-size: 1.8rem; }
h2 { font-size: 1.5rem; margin-top: 30px; display: flex; align-items: center; gap: 8px; }
h3 { font-size: 1.2rem; color: #164B41; margin-top: 20px; }
.section { margin-bottom: 30px; padding: 20px; background-color: #f8fcfb; border: 1px solid #d1e7dd; border-radius: 8px; }
form { margin-bottom: 20px; }
label { font-weight: 500; margin-top: 10px; display: block; color: #44524c; font-size: 0.9rem;}
input[type="text"], input[type="number"], input[type="password"], input[type="tel"], textarea, select { width: 100%; padding: 10px 12px; margin-top: 5px; border: 1px solid #c4d9d1; border-radius: 6px; font-size: 0.95rem; box-sizing: border-box; transition: border-color 0.3s ease; }
input:focus, textarea:focus, select:focus { border-color: #1C6758; outline: none; box-shadow: 0 0 0 2px rgba(28, 103, 88, 0.1); }
textarea { min-height: 80px; resize: vertical; }
input[type="file"] { padding: 8px; background-color: #f0f9f4; cursor: pointer; border: 1px solid #c4d9d1;}
input[type="file"]::file-selector-button { padding: 5px 10px; border-radius: 4px; background-color: #e0f0e9; border: 1px solid #c4d9d1; cursor: pointer; margin-right: 10px;}
input[type="checkbox"] { margin-right: 5px; vertical-align: middle; }
label.inline-label { display: inline-block; margin-top: 10px; font-weight: normal; }
button, .button { padding: 10px 18px; border: none; border-radius: 6px; background-color: #1C6758; color: white; font-weight: 500; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease; margin-top: 15px; font-size: 0.95rem; display: inline-flex; align-items: center; gap: 5px; text-decoration: none; line-height: 1.2;}
button:hover, .button:hover { background-color: #164B41; }
button:active, .button:active { transform: scale(0.98); }
button[type="submit"] { min-width: 120px; justify-content: center; }
.delete-button { background-color: #f56565; }
.delete-button:hover { background-color: #e53e3e; }
.add-button { background-color: #38a169; }
.add-button:hover { background-color: #2f855a; }
.item-list { display: grid; gap: 20px; }
.item { background: #fff; padding: 15px 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.07); border: 1px solid #e1f0e9; }
.item p { margin: 5px 0; font-size: 0.9rem; color: #44524c; }
.item strong { color: #2d332f; }
.item .description { font-size: 0.85rem; color: #5e6e68; max-height: 60px; overflow: hidden; text-overflow: ellipsis; }
.item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
.item-actions button:not(.delete-button) { background-color: #1C6758; }
.item-actions button:not(.delete-button):hover { background-color: #164B41; }
.edit-form-container { margin-top: 15px; padding: 20px; background: #f0f9f4; border: 1px dashed #c4d9d1; border-radius: 6px; display: none; }
details { background-color: #f8fcfb; border: 1px solid #d1e7dd; border-radius: 8px; margin-bottom: 20px; }
details > summary { cursor: pointer; font-weight: 600; color: #164B41; display: block; padding: 15px; border-bottom: 1px solid #d1e7dd; list-style: none; position: relative; }
details > summary::-webkit-details-marker { display: none; }
details > summary::after { content: '\\f078'; font-family: 'Font Awesome 6 Free'; font-weight: 900; position: absolute; right: 20px; top: 50%; transform: translateY(-50%); transition: transform 0.2s ease; color: #1C6758; }
details[open] > summary::after { transform: translateY(-50%) rotate(180deg); }
details[open] > summary { border-bottom: 1px solid #d1e7dd; }
details .details-content { padding: 20px; }
.color-input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
.color-input-group input { flex-grow: 1; margin: 0; }
.remove-color-btn { background-color: #f56565; padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; }
.remove-color-btn:hover { background-color: #e53e3e; }
.add-color-btn { background-color: #63b3ed; }
.add-color-btn:hover { background-color: #4299e1; }
.photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #d1e7dd; object-fit: cover;}
.sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
.download-hf-button { background-color: #7a8d85; }
.download-hf-button:hover { background-color: #5e6e68; }
.flex-container { display: flex; flex-wrap: wrap; gap: 20px; }
.flex-item { flex: 1; min-width: 350px; }
.message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; font-size: 0.9rem;}
.message.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;}
.message.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;}
.message.warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
.status-indicator { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; font-weight: 500; margin-left: 10px; vertical-align: middle; }
.status-indicator.in-stock { background-color: #c6f6d5; color: #2f855a; }
.status-indicator.out-of-stock { background-color: #fed7d7; color: #c53030; }
.status-indicator.top-product { background-color: #feebc8; color: #9c4221; margin-left: 5px;}
.search-container { margin-bottom: 20px; }
.no-results-message { display: none; grid-column: 1 / -1; text-align: center; padding: 20px; font-size: 1rem; color: #5e6e68; }
.password-warning { font-size: 0.8rem; color: #c53030; margin-top: 5px; }
#notification-placeholder { position: fixed; top: 20px; right: 20px; z-index: 9999; width: auto; max-width: 90%; display: flex; flex-direction: column; align-items: flex-end; gap: 10px; pointer-events: none; }
.notification { background-color: #38a169; color: white; padding: 12px 20px; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); opacity: 0; transition: opacity 0.5s ease, transform 0.5s ease; font-size: 0.95rem; transform: translateX(100%); pointer-events: auto;}
.notification.show { opacity: 1; transform: translateX(0); }
.notification.error { background-color: #f56565;}
.stock-toggle-btn { background-color: transparent; border: none; padding: 0; cursor: pointer; }
</style>
</head>
<body>
<div class="container">
<div id="notification-placeholder"></div>
<div class="header">
<h1><i class="fas fa-tools"></i> Админ-панель Soola Cosmetics</h1>
<a href="{{ url_for('catalog') }}" class="button" style="background-color: #3D8361;"><i class="fas fa-store"></i> Перейти в каталог</a>
</div>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="message {{ category }}">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
<div class="section">
<h2><i class="fas fa-sync-alt"></i> Синхронизация с Датацентром</h2>
<div class="sync-buttons">
<form method="POST" action="{{ url_for('force_upload') }}" style="display: inline;" onsubmit="return confirm('Вы уверены, что хотите принудительно загрузить локальные данные на сервер? Это перезапишет данные на сервере.');">
<button type="submit" class="button" title="Загрузить локальные файлы на Hugging Face"><i class="fas fa-upload"></i> Загрузить БД</button>
</form>
<form method="POST" action="{{ url_for('force_download') }}" style="display: inline;" onsubmit="return confirm('Вы уверены, что хотите принудительно скачать данные с сервера? Это перезапишет ваши локальные файлы.');">
<button type="submit" class="button download-hf-button" title="Скачать файлы (перезапишет локальные)"><i class="fas fa-download"></i> Скачать БД</button>
</form>
</div>
<p style="font-size: 0.85rem; color: #5e6e68;">Резервное копирование происходит автоматически каждые {{ backup_interval // 60 }} минут. Используйте эти кнопки для немедленной синхронизации.</p>
<p style="font-size: 0.85rem; color: #5e6e68;">Сохранение данных (товары, пользователи, категории) происходит только локально, синхронизация с датацентром - по расписанию или принудительно.</p>
</div>
<div class="flex-container">
<div class="flex-item">
<div class="section">
<h2><i class="fas fa-tags"></i> Управление категориями</h2>
<details>
<summary><i class="fas fa-plus-circle"></i> Добавить новую категорию</summary>
<div class="details-content">
<form method="POST">
<input type="hidden" name="action" value="add_category">
<label for="add_category_name">Название новой категории:</label>
<input type="text" id="add_category_name" name="category_name" required>
<button type="submit" class="add-button"><i class="fas fa-plus"></i> Добавить</button>
</form>
</div>
</details>
<h3>Существующие категории:</h3>
{% if categories %}
<div class="item-list">
{% for category in categories %}
<div class="item" style="display: flex; justify-content: space-between; align-items: center;">
<span>{{ category }}</span>
<form method="POST" style="margin: 0;" onsubmit="return confirm('Вы уверены, что хотите удалить категорию \'{{ category }}\'? Товары этой категории будут помечены как \'Без категории\'.');">
<input type="hidden" name="action" value="delete_category">
<input type="hidden" name="category_name" value="{{ category }}">
<button type="submit" class="delete-button" style="padding: 5px 10px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button>
</form>
</div>
{% endfor %}
</div>
{% else %}
<p>Категорий пока нет.</p>
{% endif %}
</div>
</div>
<div class="flex-item">
<details class="section">
<summary><h2><i class="fas fa-users"></i> Управление пользователями</h2></summary>
<div class="details-content">
<details>
<summary><i class="fas fa-user-plus"></i> Добавить нового пользователя</summary>
<div class="details-content">
<form method="POST">
<input type="hidden" name="action" value="add_user">
<label for="login">Логин *:</label>
<input type="text" id="login" name="login" required>
<label for="password">Пароль *:</label>
<input type="password" id="password" name="password" required title="Пароль будет сохранен в открытом виде.">
<p class="password-warning">Внимание: Пароль хранится и будет виден в открытом виде!</p>
<label for="first_name">Имя:</label>
<input type="text" id="first_name" name="first_name">
<label for="last_name">Фамилия:</label>
<input type="text" id="last_name" name="last_name">
<label for="phone">Телефон:</label>
<input type="tel" id="phone" name="phone">
<label for="country">Страна:</label>
<input type="text" id="country" name="country">
<label for="city">Город:</label>
<input type="text" id="city" name="city">
<button type="submit" class="add-button"><i class="fas fa-save"></i> Сохранить пользователя</button>
</form>
</div>
</details>
<h3>Список пользователей:</h3>
{% if users %}
<div class="item-list">
{% for login, user_data in users.items() %}
<div class="item">
<p><strong>Логин:</strong> {{ login }}</p>
<p><strong>Пароль:</strong> <code style="background:#eee; padding: 2px 4px; border-radius: 3px;">{{ user_data.get('password', 'N/A') }}</code></p>
<p><strong>Имя:</strong> {{ user_data.get('first_name', 'N/A') }} {{ user_data.get('last_name', '') }}</p>
<p><strong>Телефон:</strong> {{ user_data.get('phone', 'N/A') }}</p>
<p><strong>Локация:</strong> {{ user_data.get('city', 'N/A') }}, {{ user_data.get('country', 'N/A') }}</p>
<div class="item-actions">
<form method="POST" style="margin: 0;" onsubmit="return confirm('Вы уверены, что хотите удалить пользователя \'{{ login }}\'?');">
<input type="hidden" name="action" value="delete_user">
<input type="hidden" name="login" value="{{ login }}">
<button type="submit" class="delete-button"><i class="fas fa-user-slash"></i> Удалить</button>
</form>
</div>
</div>
{% endfor %}
</div>
{% else %}
<p>Пользователей пока нет.</p>
{% endif %}
</div>
</details>
</div>
</div>
<div class="section">
<h2><i class="fas fa-box-open"></i> Управление товарами</h2>
<details>
<summary><i class="fas fa-plus-circle"></i> Добавить новый товар</summary>
<div class="details-content">
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="add_product">
<label for="add_name">Название товара *:</label>
<input type="text" id="add_name" name="name" required>
<label for="add_price">Цена ({{ currency_code }}) *:</label>
<input type="number" id="add_price" name="price" step="0.01" min="0" required>
<label for="add_description">Описание:</label>
<textarea id="add_description" name="description" rows="4"></textarea>
<label for="add_category">Категория:</label>
<select id="add_category" name="category">
<option value="Без категории">Без категории</option>
{% for category in categories %}
<option value="{{ category }}">{{ category }}</option>
{% endfor %}
</select>
<label for="add_photos">Фотографии (до 10 шт.):</label>
<input type="file" id="add_photos" name="photos" accept="image/*" multiple>
<label>Цвета/Варианты (оставьте пустым, если нет):</label>
<div id="add-color-inputs">
<div class="color-input-group">
<input type="text" name="colors" placeholder="Например: Розовый">
<button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button>
</div>
</div>
<button type="button" class="button add-color-btn" style="margin-top: 5px;" onclick="addColorInput('add-color-inputs')"><i class="fas fa-palette"></i> Добавить поле для цвета/варианта</button>
<br>
<div style="margin-top: 15px;">
<input type="checkbox" id="add_in_stock" name="in_stock" checked>
<label for="add_in_stock" class="inline-label">В наличии</label>
</div>
<div style="margin-top: 5px;">
<input type="checkbox" id="add_is_top" name="is_top">
<label for="add_is_top" class="inline-label">Топ товар (показывать наверху)</label>
</div>
<br>
<button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Добавить товар</button>
</form>
</div>
</details>
<div class="search-container" id="admin-search-container">
<label for="admin-product-search">Поиск по названию/описанию:</label>
<input type="text" id="admin-product-search" placeholder="Введите текст для поиска..." style="width: 100%; max-width: 500px; display: block; margin-top: 5px;">
</div>
<h3>Список товаров:</h3>
{% if products %}
<div class="item-list" id="admin-product-list">
{% for product in products %}
<div class="item product-item" id="product-item-{{ product.id }}"
data-name="{{ product['name']|lower }}"
data-description="{{ product.get('description', '')|lower }}">
<div style="display: flex; gap: 15px; align-items: flex-start;">
<div class="photo-preview" style="flex-shrink: 0;">
{% if product.get('photos') and product['photos']|length > 0 %}
<a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" target="_blank" title="Посмотреть первое фото">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" alt="Фото" loading="lazy" onerror="this.onerror=null; this.src='https://via.placeholder.com/70x70.png?text=Err'">
</a>
{% else %}
<img src="https://via.placeholder.com/70x70.png?text=N/A" alt="Нет фото">
{% endif %}
</div>
<div style="flex-grow: 1;">
<h3 style="margin-top: 0; margin-bottom: 5px; color: #2d332f;">
<span class="product-name-display">{{ product['name'] }}</span>
<button class="stock-toggle-btn" data-product-id="{{ product.id }}">
{% if product.get('in_stock', True) %}
<span class="status-indicator in-stock">В наличии</span>
{% else %}
<span class="status-indicator out-of-stock">Нет в наличии</span>
{% endif %}
</button>
{% if product.get('is_top', False) %}
<span class="status-indicator top-product"><i class="fas fa-star"></i> Топ</span>
{% endif %}
</h3>
<p><strong>Категория:</strong> <span class="product-category-display">{{ product.get('category', 'Без категории') }}</span></p>
<p><strong>Цена:</strong> <span class="product-price-display">{{ "%.2f"|format(product['price']) }}</span> {{ currency_code }}</p>
<p class="description product-description-display" title="{{ product.get('description', '') }}"><strong>Описание:</strong> {{ product.get('description', 'N/A')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}</p>
{% set colors = product.get('colors', []) %}
{% set valid_colors = colors|select('ne', '')|list %}
<p><strong>Цвета/Вар-ты:</strong> {{ valid_colors|join(', ') if valid_colors else 'Нет' }}</p>
{% if product.get('photos') and product['photos']|length > 1 %}
<p style="font-size: 0.8rem; color: #5e6e68;">(Всего фото: {{ product['photos']|length }})</p>
{% endif %}
</div>
</div>
<div class="item-actions">
<button type="button" class="button" onclick="toggleEditForm('edit-form-{{ product.id }}')"><i class="fas fa-edit"></i> Редактировать</button>
<form method="POST" style="margin:0;" onsubmit="return confirm('Вы уверены, что хотите удалить товар \'{{ product['name'] }}\'? Фотографии также будут удалены с сервера.');">
<input type="hidden" name="action" value="delete_product">
<input type="hidden" name="product_id" value="{{ product.id }}">
<button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button>
</form>
</div>
<div id="edit-form-{{ product.id }}" class="edit-form-container">
<h4><i class="fas fa-edit"></i> Редактирование: {{ product['name'] }}</h4>
<form method="POST" enctype="multipart/form-data" class="ajax-edit-form">
<input type="hidden" name="action" value="edit_product">
<input type="hidden" name="product_id" value="{{ product.id }}">
<label>Название *:</label>
<input type="text" name="name" value="{{ product['name'] }}" required>
<label>Цена ({{ currency_code }}) *:</label>
<input type="number" name="price" step="0.01" min="0" value="{{ product['price'] }}" required>
<label>Описание:</label>
<textarea name="description" rows="4">{{ product.get('description', '') }}</textarea>
<label>Категория:</label>
<select name="category">
<option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option>
{% for category in categories %}
<option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option>
{% endfor %}
</select>
<label>Заменить фотографии (выберите новые файлы, до 10 шт.):</label>
<input type="file" name="photos" accept="image/*" multiple>
{% if product.get('photos') %}
<p style="font-size: 0.85rem; margin-top: 5px;">Текущие фото ({{ product['photos']|length }} шт.):</p>
<div class="photo-preview">
{% for photo in product['photos'] %}
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="Фото {{ loop.index }}" loading="lazy" onerror="this.onerror=null; this.src='https://via.placeholder.com/70x70.png?text=Err'">
{% endfor %}
</div>
<p style="font-size: 0.8rem; color: #5e6e68;">Выбор новых файлов заменит ВСЕ текущие фотографии.</p>
{% endif %}
<label>Цвета/Варианты:</label>
<div id="edit-color-inputs-{{ product.id }}">
{% set current_colors = product.get('colors', []) %}
{% set valid_current_colors = current_colors|select('ne', '')|list %}
{% if valid_current_colors %}
{% for color in valid_current_colors %}
<div class="color-input-group">
<input type="text" name="colors" value="{{ color }}">
<button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button>
</div>
{% endfor %}
{% else %}
<div class="color-input-group">
<input type="text" name="colors" placeholder="Например: Красный">
<button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button>
</div>
{% endif %}
</div>
<button type="button" class="button add-color-btn" style="margin-top: 5px;" onclick="addColorInput('edit-color-inputs-{{ product.id }}')"><i class="fas fa-palette"></i> Добавить поле для цвета</button>
<br>
<div style="margin-top: 15px;">
<input type="checkbox" id="edit_in_stock_{{ product.id }}" name="in_stock" {% if product.get('in_stock', True) %}checked{% endif %}>
<label for="edit_in_stock_{{ product.id }}" class="inline-label">В наличии</label>
</div>
<div style="margin-top: 5px;">
<input type="checkbox" id="edit_is_top_{{ product.id }}" name="is_top" {% if product.get('is_top', False) %}checked{% endif %}>
<label for="edit_is_top_{{ product.id }}" class="inline-label">Топ товар</label>
</div>
<br>
<button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Сохранить изменения</button>
</form>
</div>
</div>
{% endfor %}
<p id="admin-no-results" class="no-results-message" style="display: none;">Товары по вашему запросу не найдены.</p>
</div>
{% else %}
<p id="admin-no-products-initial">Товаров пока нет.</p>
{% endif %}
</div>
</div>
<script>
function showAdminNotification(message, type = 'success', duration = 3000) {
const placeholder = document.getElementById('notification-placeholder');
if (!placeholder) return;
const notification = document.createElement('div');
notification.className = `notification ${type}`;
notification.textContent = message;
placeholder.appendChild(notification);
requestAnimationFrame(() => {
notification.classList.add('show');
});
setTimeout(() => {
notification.classList.remove('show');
notification.addEventListener('transitionend', () => notification.remove());
}, duration);
}
function toggleEditForm(formId) {
const formContainer = document.getElementById(formId);
if (formContainer) {
formContainer.style.display = formContainer.style.display === 'none' || formContainer.style.display === '' ? 'block' : 'none';
}
}
function addColorInput(containerId) {
const container = document.getElementById(containerId);
if (container) {
const newInputGroup = document.createElement('div');
newInputGroup.className = 'color-input-group';
newInputGroup.innerHTML = `
<input type="text" name="colors" placeholder="Новый цвет/вариант">
<button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button>
`;
container.appendChild(newInputGroup);
const newInput = newInputGroup.querySelector('input[name="colors"]');
if (newInput) {
newInput.focus();
}
}
}
function removeColorInput(button) {
const group = button.closest('.color-input-group');
if (group) {
const container = group.parentNode;
group.remove();
if (container && container.children.length === 0) {
const placeholderGroup = document.createElement('div');
placeholderGroup.className = 'color-input-group';
placeholderGroup.innerHTML = `
<input type="text" name="colors" placeholder="Например: Цвет">
<button type="button" class="remove-color-btn" onclick="removeColorInput(this)"><i class="fas fa-times"></i></button>
`;
container.appendChild(placeholderGroup);
}
} else {
console.warn("Could not find parent .color-input-group for remove button");
}
}
function filterAdminProducts() {
const searchTerm = document.getElementById('admin-product-search').value.toLowerCase().trim();
const productItems = document.querySelectorAll('#admin-product-list .product-item');
const noResultsMessage = document.getElementById('admin-no-results');
const initialNoProducts = document.getElementById('admin-no-products-initial');
let visibleCount = 0;
productItems.forEach(item => {
const name = item.dataset.name || '';
const description = item.dataset.description || '';
if (!searchTerm || name.includes(searchTerm) || description.includes(searchTerm)) {
item.style.display = '';
visibleCount++;
} else {
item.style.display = 'none';
}
});
if (noResultsMessage) {
noResultsMessage.style.display = (visibleCount === 0 && productItems.length > 0) ? 'block' : 'none';
}
if(initialNoProducts) {
initialNoProducts.style.display = (productItems.length === 0 && !searchTerm) ? 'block' : 'none';
}
}
document.addEventListener('DOMContentLoaded', () => {
const searchInput = document.getElementById('admin-product-search');
const searchContainer = document.getElementById('admin-search-container');
const productList = document.getElementById('admin-product-list');
const hasProducts = productList && productList.querySelector('.product-item');
if (searchInput) {
searchInput.addEventListener('input', filterAdminProducts);
}
if (!hasProducts && searchContainer) {
searchContainer.style.display = 'none';
} else if (searchContainer) {
searchContainer.style.display = 'block';
}
filterAdminProducts();
document.querySelectorAll('.ajax-edit-form').forEach(form => {
form.addEventListener('submit', function(event) {
event.preventDefault();
const submitButton = form.querySelector('button[type="submit"]');
submitButton.disabled = true;
submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Сохранение...';
const formData = new FormData(form);
fetch("{{ url_for('edit_product_ajax') }}", {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
showAdminNotification(data.message || 'Товар успешно обновлен');
const productItem = document.getElementById(`product-item-${data.product.id}`);
if(productItem) {
productItem.querySelector('.product-name-display').textContent = data.product.name;
productItem.querySelector('.product-category-display').textContent = data.product.category;
productItem.querySelector('.product-price-display').textContent = parseFloat(data.product.price).toFixed(2);
const descEl = productItem.querySelector('.product-description-display');
descEl.title = data.product.description;
descEl.innerHTML = `<strong>Описание:</strong> ${data.product.description.substring(0,150)}${data.product.description.length > 150 ? '...' : ''}`;
}
} else {
showAdminNotification(data.message || 'Произошла ошибка', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showAdminNotification('Сетевая ошибка. Попробуйте снова.', 'error');
})
.finally(() => {
submitButton.disabled = false;
submitButton.innerHTML = '<i class="fas fa-save"></i> Сохранить изменения';
});
});
});
document.getElementById('admin-product-list').addEventListener('click', function(event){
const toggleButton = event.target.closest('.stock-toggle-btn');
if (!toggleButton) return;
const productId = toggleButton.dataset.productId;
const statusSpan = toggleButton.querySelector('.status-indicator');
const isCurrentlyInStock = statusSpan.classList.contains('in-stock');
const newStockStatus = !isCurrentlyInStock;
fetch("{{ url_for('toggle_stock_ajax') }}", {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
product_id: productId,
in_stock: newStockStatus
})
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
statusSpan.classList.toggle('in-stock', newStockStatus);
statusSpan.classList.toggle('out-of-stock', !newStockStatus);
statusSpan.textContent = newStockStatus ? 'В наличии' : 'Нет в наличии';
showAdminNotification('Статус наличия обновлен');
} else {
showAdminNotification(data.message || 'Ошибка обновления статуса', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showAdminNotification('Сетевая ошибка при обновлении статуса.', 'error');
});
});
});
</script>
</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" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<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; 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 }}" loading="lazy" onerror="this.onerror=null; this.src='https://via.placeholder.com/60x60.png?text=Err'">
<div class="item-details">
<strong>{{ item.name }} {% if item.color != 'N/A' %}({{ item.color }}){% endif %}</strong>
<span>{{ "%.2f"|format(item.price) }} {{ currency_code }} &times; {{ 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>
<p><strong>ИТОГО К ОПЛАТЕ: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>
</div>
{% if order.user_info and order.user_info.login %}
<div class="customer-info">
<h2><i class="fas fa-user-circle"></i> Информация о клиенте</h2>
<p><strong>Логин:</strong> {{ order.user_info.login }}</p>
<p><strong>Имя:</strong> {{ order.user_info.get('first_name', 'N/A') }} {{ 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>
<p>Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.</p>
</div>
{% else %}
<div class="customer-info">
<h2><i class="fas fa-info-circle"></i> Статус заказа</h2>
<p>Этот заказ был оформлен без входа в систему или данные пользователя не сохранились.</p>
<p>Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.</p>
</div>
{% endif %}
<div class="actions">
<button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> Отправить заказ в WhatsApp</button>
</div>
<a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в каталог</a>
<script>
function sendOrderViaWhatsApp() {
const orderId = '{{ order.id }}';
const orderUrl = encodeURIComponent( '{{ request.url_root }}order/' + orderId );
const whatsappNumber = "996997703090";
let message = `Здравствуйте! Хочу подтвердить свой заказ на Soola Cosmetics:%0A%0A`;
message += `*Номер заказа:* ${orderId}%0A`;
message += `*Ссылка на заказ:* ${orderUrl}%0A%0A`;
{% if order.user_info and order.user_info.login %}
message += "*Информация о клиенте:*%0A";
message += "Логин: {{ order.user_info.login | replace(' ', '%20') }}%0A";
{% if order.user_info.first_name or order.user_info.last_name %}
message += "Имя: {{ order.user_info.get('first_name', '') | replace(' ', '%20') }} {{ order.user_info.get('last_name', '') | replace(' ', '%20') }}%0A";
{% endif %}
{% if order.user_info.phone %}
message += "Телефон: {{ order.user_info.phone }}%0A";
{% endif %}
message += "%0A";
{% endif %}
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>
'''
@app.route('/')
def catalog():
data = get_data()
all_products = data.get('products', [])
categories = sorted(data.get('categories', []))
is_authenticated = 'user' in session
user_info = session.get('user_info', {})
user_first_name = user_info.get('first_name', session.get('user', ''))
is_admin = user_info.get('login') == 'admin'
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,
is_admin=is_admin
)
@app.route('/product/<string:product_id>')
def product_detail(product_id):
data = get_data()
all_products = data.get('products', [])
product = next((p for p in all_products if p.get('id') == product_id and p.get('in_stock', True)), None)
if not product:
logging.warning(f"Attempted access to non-existent or out-of-stock product id {product_id}")
return "Товар не найден или отсутствует в наличии.", 404
is_authenticated = 'user' in session
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/<string:product_id>')
def product_data_for_cart(product_id):
data = get_data()
all_products = data.get('products', [])
product = next((p for p in all_products if p.get('id') == product_id), None)
if product:
product_info = {
'id': product.get('id'),
'name': product.get('name'),
'price': product.get('price'),
'colors': product.get('colors', []),
'photos': product.get('photos', [])
}
return jsonify(product_info)
else:
logging.warning(f"Attempted access to product data for non-existent id {product_id}")
return jsonify({"error": "Product not found"}), 404
@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'''
<!DOCTYPE html><html><head><title>Перенаправление...</title></head><body>
<script>
try {{
localStorage.setItem('soolaUser', '{login_attempt}');
console.log('Stored login: {login_attempt}');
}} 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_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'''
<!DOCTYPE html><html><head><title>Выход...</title></head><body>
<script>
try {{
localStorage.removeItem('soolaUser');
console.log('Removed stored login.');
}} catch (e) {{ console.error("Error removing from localStorage:", e); }}
window.location.href = "{url_for('catalog')}";
</script>
<p>Выход выполнен. Перенаправление на <a href="{url_for('catalog')}">главную страницу</a>...</p>
</body></html>
'''
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/<order_id>')
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 = {
'id': uuid.uuid4().hex,
'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 == 'delete_product':
product_id = request.form.get('product_id')
if not product_id:
flash("Ошибка удаления: ID товара не передан.", 'error')
return redirect(url_for('admin'))
product_to_delete_info = next((p for p in products if p.get('id') == product_id), None)
if not product_to_delete_info:
flash(f"Ошибка удаления: товар с ID {product_id} не найден.", 'error')
return redirect(url_for('admin'))
product_name_to_delete = product_to_delete_info.get('name', 'N/A')
photos_to_delete = product_to_delete_info.get('photos', [])
products[:] = [p for p in products if p.get('id') != product_id]
save_needed_data = True
logging.info(f"Product '{product_name_to_delete}' (ID {product_id}) 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')
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('/admin/edit_product_ajax', methods=['POST'])
def edit_product_ajax():
product_id = request.form.get('product_id')
if not product_id:
return jsonify({'status': 'error', 'message': 'ID товара не передан.'}), 400
current_data = get_data()
products = current_data.get('products', [])
categories = current_data.get('categories', [])
product_to_edit = next((p for p in products if p.get('id') == product_id), None)
if not product_to_edit:
return jsonify({'status': 'error', 'message': f'Товар с ID {product_id} не найден.'}), 404
try:
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
product_to_edit['price'] = round(float(price_str), 2)
except (ValueError, TypeError) as e:
logging.error(f"Invalid data for product {product_id} on AJAX edit: {e}")
return jsonify({'status': 'error', 'message': 'Неверный формат данных (например, цена).'}), 400
photos_files = request.files.getlist('photos')
if photos_files and any(f.filename for f in photos_files):
if not HF_TOKEN_WRITE:
return jsonify({'status': 'error', 'message': 'Токен HF не настроен, загрузка фото невозможна.'}), 500
api = HfApi()
new_photos_list = []
uploads_dir = 'uploads_temp'
os.makedirs(uploads_dir, exist_ok=True)
try:
for photo in photos_files[:10]:
if photo and photo.filename:
ext = os.path.splitext(photo.filename)[1].lower()
if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']: 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)
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)
if os.path.exists(temp_path): os.remove(temp_path)
if new_photos_list:
old_photos = product_to_edit.get('photos', [])
product_to_edit['photos'] = new_photos_list
if old_photos:
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']}")
except Exception as e:
logging.error(f"Error during AJAX photo upload for {product_id}: {e}")
return jsonify({'status': 'error', 'message': 'Ошибка при загрузке новых фото.'}), 500
finally:
if os.path.exists(uploads_dir) and not os.listdir(uploads_dir): os.rmdir(uploads_dir)
if save_data(current_data):
return jsonify({'status': 'success', 'message': 'Товар обновлен!', 'product': product_to_edit})
else:
return jsonify({'status': 'error', 'message': 'Не удалось сохранить изменения.'}), 500
@app.route('/admin/toggle_stock_ajax', methods=['POST'])
def toggle_stock_ajax():
req_data = request.get_json()
product_id = req_data.get('product_id')
in_stock = req_data.get('in_stock')
if not product_id or in_stock is None:
return jsonify({'status': 'error', 'message': 'Неверные данные запроса.'}), 400
current_data = get_data()
products = current_data.get('products', [])
product_to_update = next((p for p in products if p.get('id') == product_id), None)
if not product_to_update:
return jsonify({'status': 'error', 'message': f'Товар с ID {product_id} не найден.'}), 404
product_to_update['in_stock'] = bool(in_stock)
if save_data(current_data):
return jsonify({'status': 'success'})
else:
return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных.'}), 500
@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)