Gamemeta / app.py
Kgshop's picture
Rename Soola.txt to app.py
3c69040 verified
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
from urllib.parse import quote_plus
from flask import Flask, render_template_string, request, redirect, url_for, flash, jsonify, make_response
load_dotenv()
app = Flask(__name__)
app.secret_key = 'your_unique_secret_key_meka_shop_12345_no_login'
DATA_FILE = 'data.json'
SYNC_FILES = [DATA_FILE]
REPO_ID = "Kgshop/gamemeta"
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
STORE_ADDRESS = "Рынок Кербент, 5 ряд , 48 контейнер "
SHOP_NAME = "Murat боксеры оптом"
WHATSAPP_NUMBER = "996771388181"
PAYMENT_INFO = "оплату за заказ можете перевести на MBANK +996707028181"
CURRENCY_CODE = 'KGS'
CURRENCY_NAME = 'Кыргызский сом'
DOWNLOAD_RETRIES = 3
DOWNLOAD_DELAY = 5
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
translations = {
'ru': {
'admin_panel_title': 'Админ-панель ' + SHOP_NAME,
'go_to_catalog': 'Перейти в каталог',
'sync_section_title': 'Синхронизация с Датацентром',
'upload_db_button': 'Загрузить БД',
'download_db_button': 'Скачать БД',
'sync_info': 'Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.',
'categories_section_title': 'Управление категориями',
'add_category_summary': 'Добавить новую категорию',
'add_category_name_label': 'Название новой категории:',
'add_category_button': 'Добавить',
'existing_categories_title': 'Существующие категории:',
'no_categories': 'Категорий пока нет.',
'info_section_title': 'Информация',
'info_text_1': 'Управление пользователями отключено, так как сайт не требует входа.',
'info_text_2': 'Заказы создаются анонимно и должны быть подтверждены через WhatsApp.',
'products_section_title': 'Управление товарами',
'add_product_summary': 'Добавить новый товар',
'product_name_label': 'Название товара *:',
'product_price_label': 'Цена ({}) *:'.format(CURRENCY_CODE),
'product_description_label': 'Описание:',
'product_category_label': 'Категория:',
'product_photos_label': 'Фотографии (до 10 шт.):',
'product_colors_label': 'Цвета/Варианты (оставьте пустым, если нет):',
'add_color_button': 'Добавить поле для цвета/варианта',
'in_stock_label': 'В наличии',
'is_top_label': 'Топ товар (показывать наверху)',
'add_product_button': 'Добавить товар',
'product_list_title': 'Список товаров:',
'no_products': 'Товаров пока нет.',
'category_label': 'Категория:',
'price_label': 'Цена:',
'description_label': 'Описание:',
'colors_label': 'Цвета/Вар-ты:',
'no_colors': 'Нет',
'current_photos': 'Текущие фото:',
'edit_button': 'Редактировать',
'delete_button': 'Удалить',
'edit_form_title': 'Редактирование:',
'replace_photos_label': 'Заменить фотографии (выберите новые файлы, до 10 шт.):',
'save_changes_button': 'Сохранить изменения',
'default_category': 'Без категории',
'status_in_stock': 'В наличии',
'status_out_of_stock': 'Нет в наличии',
'status_top': 'Топ товар',
'confirm_upload': 'Вы уверены, что хотите принудительно загрузить локальные данные на сервер? Это перезапишет данные на сервере.',
'confirm_download': 'Вы уверены, что хотите принудительно скачать данные с сервера? Это перезапишет ваши локальные файлы.',
'confirm_delete_category': 'Вы уверены, что хотите удалить категорию \'{}\'? Товары этой категории будут помечены как \'Без категории\'.',
'confirm_delete_product': 'Вы уверены, что хотите удалить товар \'{}\'?',
'flash_category_added': "Категория '{}' успешно добавлена.",
'flash_category_empty': "Название категории не может быть пустым.",
'flash_category_exists': "Категория '{}' уже существует.",
'flash_category_deleted': "Категория '{}' удалена. {} товаров обновлено.",
'flash_category_delete_failed': "Не удалось удалить категорию '{}'.",
'flash_product_name_price_required': "Название и цена товара обязательны.",
'flash_product_invalid_price': "Неверный формат цены.",
'flash_photo_limit': "Загружено только первые {} фото.",
'flash_photo_skipped_non_image': "Файл {} не является изображением и был пропущен.",
'flash_photo_upload_error': "Ошибка при загрузке фото {}.",
'flash_product_added': "Товар '{}' успешно добавлен.",
'flash_edit_index_missing': "Ошибка редактирования: индекс товара не передан.",
'flash_edit_index_invalid': "Ошибка редактирования: неверный индекс товара '{}'.",
'flash_edit_price_invalid': "'{}' ürünü için geçersiz fiyat formatı. Fiyat değiştirilmedi.",
'flash_photos_updated': "Фотографии товара успешно обновлены.",
'flash_old_photos_delete_error': "Не удалось удалить старые фотографии с сервера. Новые фото загружены.",
'flash_new_photos_upload_failed': "Не удалось загрузить новые фотографии (возможно, неверный формат).",
'flash_no_hf_token_photos_not_updated': "HF_TOKEN (write) не настроен. Фотографии не были обновлены.",
'flash_product_updated': "Товар '{}' успешно обновлен.",
'flash_delete_index_missing': "Ошибка удаления: индекс товара не передан.",
'flash_delete_index_invalid': "Ошибка удаления: неверный индекс товара '{}'.",
'flash_product_deleted': "Товар '{}' удален.",
'flash_photo_delete_error_deleted_local': "Товар '{}' удален локально, но фото не удалены с сервера (ошибка/токен).",
'flash_unknown_action': "Неизвестное действие: {}",
'flash_internal_error': "Произошла внутренняя ошибка при выполнении действия '{}'. Подробности в логе сервера.",
'flash_upload_success': "Данные успешно загружены на Hugging Face.",
'flash_upload_error': "Ошибка при загрузке на Hugging Face: {}",
'flash_download_success': "Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.",
'flash_download_error_hf': "Не удалось скачать данные с Hugging Face после нескольких попыток. Проверьте логи.",
'flash_download_error_general': "Ошибка при скачивании с Hugging Face: {}",
},
'tr': {
'admin_panel_title': 'Yönetici Paneli ' + SHOP_NAME,
'go_to_catalog': 'Kataloğa Git',
'sync_section_title': 'Veri Merkezi Senkronizasyonu',
'upload_db_button': 'Veritabanını Yükle',
'download_db_button': 'Veritabanını İndir',
'sync_info': 'Yedekleme otomatik olarak her 30 dakikada bir ve her veri kaydından sonra yapılır. Anında senkronizasyon için bu düğmeleri kullanın.',
'categories_section_title': 'Kategorileri Yönet',
'add_category_summary': 'Yeni Kategori Ekle',
'add_category_name_label': 'Yeni Kategori Adı:',
'add_category_button': 'Ekle',
'existing_categories_title': 'Mevcut Kategoriler:',
'no_categories': 'Henüz kategori yok.',
'info_section_title': 'Bilgi',
'info_text_1': 'Site giriş gerektirmediği için kullanıcı yönetimi devre dışıdır.',
'info_text_2': 'Siparişler anonim olarak oluşturulur ve WhatsApp üzerinden teyit edilmelidir.',
'products_section_title': 'Ürünleri Yönet',
'add_product_summary': 'Yeni Ürün Ekle',
'product_name_label': 'Ürün Adı *:',
'product_price_label': 'Fiyat ({}) *:'.format(CURRENCY_CODE),
'product_description_label': 'Açıklama:',
'product_category_label': 'Kategori:',
'product_photos_label': 'Fotoğraflar (En fazla 10 adet):',
'product_colors_label': 'Renkler/Seçenekler (Yoksa boş bırakın):',
'add_color_button': 'Renk/Seçenek Alanı Ekle',
'in_stock_label': 'Stokta Var',
'is_top_label': 'En Popüler Ürün (üstte göster)',
'add_product_button': 'Ürün Ekle',
'product_list_title': 'Ürün Listesi:',
'no_products': 'Henüz ürün yok.',
'category_label': 'Kategori:',
'price_label': 'Fiyat:',
'description_label': 'Açıklama:',
'colors_label': 'Renkler/Seçenekler:',
'no_colors': 'Yok',
'current_photos': 'Mevcut fotoğraflar:',
'edit_button': 'Düzenle',
'delete_button': 'Sil',
'edit_form_title': 'Düzenleniyor:',
'replace_photos_label': 'Fotoğrafları Değiştir (yeni dosyaları seçin, en fazla 10 adet):',
'save_changes_button': 'Değişiklikleri Kaydet',
'default_category': 'Kategorisiz',
'status_in_stock': 'Stokta',
'status_out_of_stock': 'Stokta Yok',
'status_top': 'Popüler',
'confirm_upload': 'Yerel verileri sunucuya zorla yüklemek istediğinizden emin misiniz? Bu, sunucudaki verilerin üzerine yazacaktır.',
'confirm_download': 'Sunucudan verileri zorla indirmek istediğinizden emin misiniz? Bu, yerel dosyalarınızın üzerine yazacaktır.',
'confirm_delete_category': '\'{}\' kategorisini silmek istediğinizden emin misiniz? Bu kategorideki ürünler \'Kategorisiz\' olarak işaretlenecektir.',
'confirm_delete_product': '\'{}\' ürününü silmek istediğinizden emin misiniz?',
'flash_category_added': "'{}' kategorisi başarıyla eklendi.",
'flash_category_empty': "Kategori adı boş olamaz.",
'flash_category_exists': "'{}' kategorisi zaten mevcut.",
'flash_category_deleted': "'{}' kategorisi silindi. {} ürün güncellendi.",
'flash_category_delete_failed': "'{}' kategorisi silinemedi.",
'flash_product_name_price_required': "Ürün adı ve fiyatı zorunludur.",
'flash_product_invalid_price': "Geçersiz fiyat formatı.",
'flash_photo_limit': "Sadece ilk {} fotoğraf yüklendi.",
'flash_photo_skipped_non_image': "{} dosyası bir görsel değil ve atlandı.",
'flash_photo_upload_error': "{} fotoğrafı yüklenirken hata oluştu.",
'flash_product_added': "'{}' ürünü başarıyla eklendi.",
'flash_edit_index_missing': "Düzenleme hatası: Ürün indeksi gönderilmedi.",
'flash_edit_index_invalid': "Düzenleme hatası: Geçersiz ürün indeksi '{}'.",
'flash_edit_price_invalid': "'{}' ürünü için geçersiz fiyat formatı. Fiyat değiştirilmedi.",
'flash_photos_updated': "Ürün fotoğrafları başarıyla güncellendi.",
'flash_old_photos_delete_error': "Eski fotoğraflar sunucudan silinemedi. Yeni fotoğraflar yüklendi.",
'flash_new_photos_upload_failed': "Yeni fotoğraflar yüklenemedi (geçersiz format olabilir).",
'flash_no_hf_token_photos_not_updated': "HF_TOKEN (yazma) ayarlı değil. Fotoğraflar güncellenmedi.",
'flash_product_updated': "'{}' ürünü başarıyla güncellendi.",
'flash_delete_index_missing': "Silme hatası: Ürün indeksi gönderilmedi.",
'flash_delete_index_invalid': "Silme hatası: Geçersiz ürün indeksi '{}'.",
'flash_product_deleted': "'{}' ürünü silindi.",
'flash_photo_delete_error_deleted_local': "'{}' ürünü yerel olarak silindi ancak fotoğraflar sunucudan silinmedi (hata/token).",
'flash_unknown_action': "Bilinmeyen eylem: {}",
'flash_internal_error': "'{}' eylemi gerçekleştirilirken dahili bir hata oluştu. Sunucu günlüklerini kontrol edin.",
'flash_upload_success': "Veriler Hugging Face'e başarıyla yüklendi.",
'flash_upload_error': "Hugging Face'e yükleme hatası: {}",
'flash_download_success': "Veriler Hugging Face'ten başarıyla indirildi. Yerel dosyalar güncellendi.",
'flash_download_error_hf': "Birkaç denemeden sonra Hugging Face'ten veri indirilemedi. Günlükleri kontrol edin.",
'flash_download_error_general': "Hugging Face'ten indirme hatası: {}",
}
}
def get_admin_lang():
requested_lang = request.args.get('lang')
if requested_lang and requested_lang in translations:
lang_code = requested_lang
else:
lang_code = request.cookies.get('admin_lang', 'ru')
if lang_code not in translations:
lang_code = 'ru'
return lang_code, translations[lang_code]
def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):
if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.")
token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE
files_to_download = [specific_file] if specific_file else SYNC_FILES
logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...")
all_successful = True
for file_name in files_to_download:
success = False
for attempt in range(retries + 1):
try:
logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...")
local_path = hf_hub_download(
repo_id=REPO_ID,
filename=file_name,
repo_type="dataset",
token=token_to_use,
local_dir=".",
local_dir_use_symlinks=False,
force_download=True,
resume_download=False
)
logging.info(f"Successfully downloaded {file_name} to {local_path}.")
success = True
break
except RepositoryNotFoundError:
logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.")
return False
except HfHubHTTPError as e:
if e.response.status_code == 404:
logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.")
if attempt == 0 and not os.path.exists(file_name):
try:
if file_name == DATA_FILE:
with open(file_name, 'w', encoding='utf-8') as f:
json.dump({'products': [], 'categories': [], 'orders': {}}, f)
logging.info(f"Created empty local file {file_name} because it was not found on HF.")
except Exception as create_e:
logging.error(f"Failed to create empty local file {file_name}: {create_e}")
success = False
break
else:
logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...")
except requests.exceptions.RequestException as e:
logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...")
except Exception as e:
logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True)
if attempt < retries:
time.sleep(delay)
if not success:
logging.error(f"Failed to download {file_name} after {retries + 1} attempts.")
all_successful = False
logging.info(f"Download process finished. Overall success: {all_successful}")
return all_successful
def upload_db_to_hf(specific_file=None):
if not HF_TOKEN_WRITE:
logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.")
return
try:
api = HfApi()
files_to_upload = [specific_file] if specific_file else SYNC_FILES
logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...")
for file_name in files_to_upload:
if os.path.exists(file_name):
try:
api.upload_file(
path_or_fileobj=file_name,
path_in_repo=file_name,
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
)
logging.info(f"File {file_name} successfully uploaded to Hugging Face.")
except Exception as e:
logging.error(f"Error uploading file {file_name} to Hugging Face: {e}")
else:
logging.warning(f"File {file_name} not found locally, skipping upload.")
logging.info("Finished uploading files to HF.")
except Exception as e:
logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True)
def periodic_backup():
backup_interval = 1800
logging.info(f"Setting up periodic backup every {backup_interval} seconds.")
while True:
time.sleep(backup_interval)
logging.info("Starting periodic backup...")
upload_db_to_hf()
logging.info("Periodic backup finished.")
def load_data():
default_data = {'products': [], 'categories': [], 'orders': {}}
try:
with open(DATA_FILE, 'r', encoding='utf-8') as file:
data = json.load(file)
logging.info(f"Local data loaded successfully from {DATA_FILE}")
if not isinstance(data, dict):
logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.")
raise FileNotFoundError
if 'products' not in data: data['products'] = []
if 'categories' not in data: data['categories'] = []
if 'orders' not in data: data['orders'] = {}
return data
except FileNotFoundError:
logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.")
except json.JSONDecodeError:
logging.error(f"Error decoding JSON in local {DATA_FILE}. File might be corrupt. Attempting download.")
if download_db_from_hf(specific_file=DATA_FILE):
try:
with open(DATA_FILE, 'r', encoding='utf-8') as file:
data = json.load(file)
logging.info(f"Data loaded successfully from {DATA_FILE} after download.")
if not isinstance(data, dict):
logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.")
return default_data
if 'products' not in data: data['products'] = []
if 'categories' not in data: data['categories'] = []
if 'orders' not in data: data['orders'] = {}
return data
except FileNotFoundError:
logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.")
return default_data
except json.JSONDecodeError:
logging.error(f"Error decoding JSON in downloaded {DATA_FILE}. Using default.")
return default_data
except Exception as e:
logging.error(f"Unknown error loading downloaded {DATA_FILE}: {e}. Using default.", exc_info=True)
return default_data
else:
logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.")
if not os.path.exists(DATA_FILE):
try:
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(default_data, f)
logging.info(f"Created empty local file {DATA_FILE} after failed download.")
except Exception as create_e:
logging.error(f"Failed to create empty local file {DATA_FILE}: {create_e}")
return default_data
def save_data(data):
try:
if not isinstance(data, dict):
logging.error("Attempted to save invalid data structure (not a dict). Aborting save.")
return
if 'products' not in data: data['products'] = []
if 'categories' not in data: data['categories'] = []
if 'orders' not in data: data['orders'] = {}
with open(DATA_FILE, 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
logging.info(f"Data successfully saved to {DATA_FILE}")
upload_db_to_hf(specific_file=DATA_FILE)
except Exception as e:
logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True)
CATALOG_TEMPLATE = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VR Каталог - {{ shop_name }}</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<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">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Poppins', sans-serif; background: #000; color: #eee; line-height: 1.6; overflow: hidden; cursor: grab; }
body.grabbing { cursor: grabbing; }
.container { width: 100vw; height: 100vh; display: flex; flex-direction: column; justify-content: center; align-items: center; }
.header { position: fixed; top: 0; left: 0; width: 100%; padding: 20px 40px; display: flex; justify-content: space-between; align-items: center; z-index: 100; background: linear-gradient(to bottom, rgba(0,0,0,0.7), transparent); }
.header h1 { font-size: 1.8rem; font-weight: 600; color: #E91E63; text-shadow: 0 0 10px #E91E63; }
.vr-viewport { perspective: 1500px; width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; }
.vr-carousel { position: relative; width: 300px; height: 400px; transform-style: preserve-3d; transition: transform 0.5s cubic-bezier(0.25, 1, 0.5, 1); }
.product-card { position: absolute; width: 100%; height: 100%; backface-visibility: hidden; background: rgba(26, 26, 26, 0.8); backdrop-filter: blur(10px); border-radius: 15px; border: 1px solid rgba(233, 30, 99, 0.3); box-shadow: 0 0 30px rgba(233, 30, 99, 0.2); transition: all 0.5s ease; display: flex; flex-direction: column; cursor: pointer; transform-origin: center; }
.product-card.is-active { transform: var(--transform-active) !important; cursor: default; z-index: 10; box-shadow: 0 0 50px rgba(233, 30, 99, 0.5); border-color: #E91E63; }
.product-card.is-hidden { transform: var(--transform-initial) scale(0) !important; opacity: 0; pointer-events: none; }
.product-card-front, .product-card-back { position: absolute; width: 100%; height: 100%; backface-visibility: hidden; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; text-align: center; }
.product-card-back { transform: rotateY(180deg); overflow-y: auto; padding: 15px; }
.product-card .product-image { width: 80%; aspect-ratio: 1/1; margin-bottom: 15px; display: flex; align-items: center; justify-content: center; }
.product-card .product-image img { max-width: 100%; max-height: 100%; object-fit: contain; border-radius: 8px; }
.product-card h2 { font-size: 1.3rem; color: #eee; margin-bottom: 5px; }
.product-card .price { font-size: 1.4rem; color: #F06292; font-weight: 700; margin-bottom: 15px; }
.product-card .view-details-btn { padding: 10px 20px; background: #E91E63; color: white; border: none; border-radius: 5px; cursor: pointer; transition: all 0.3s; }
.product-card.is-active .product-card-front { transform: rotateY(-180deg); }
.product-card.is-active .product-card-back { transform: rotateY(0deg); }
.top-product-indicator { position: absolute; top: 10px; right: 10px; 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; }
.product-detail-content h3 { color: #E91E63; font-size: 1.5rem; }
.product-detail-content p, .product-detail-content div { margin-bottom: 10px; font-size: 0.9rem; color: #ccc; }
.product-detail-content .price-detail { font-size: 1.3rem; font-weight: bold; color: #F06292; }
.product-detail-content .actions { display: flex; flex-direction: column; gap: 10px; margin-top: 15px; }
.product-button { display: block; width: 100%; padding: 12px; border: none; border-radius: 8px; background-color: #C2185B; color: white; font-size: 1rem; font-weight: 500; cursor: pointer; transition: all 0.3s; text-align: center; text-decoration: none; }
.product-button:hover { background-color: #E91E63; }
.add-to-cart { background-color: #E91E63; }
.quantity-input, .color-select { width: 100%; padding: 10px; border: 1px solid #444; border-radius: 8px; font-size: 1rem; margin: 10px 0; background-color: #222; color: #eee; }
.close-detail-view { position: absolute; top: 10px; right: 10px; background: none; border: none; color: #aaa; font-size: 1.8rem; cursor: pointer; z-index: 11; }
.filters { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); z-index: 100; display: flex; gap: 10px; background: rgba(0,0,0,0.5); backdrop-filter: blur(5px); padding: 10px; border-radius: 20px; border: 1px solid rgba(233, 30, 99, 0.3); }
.category-filter { padding: 8px 16px; border: 1px solid #444; border-radius: 20px; background-color: #222; color: #F06292; cursor: pointer; transition: all 0.3s; }
.category-filter.active, .category-filter:hover { background-color: #E91E63; color: white; border-color: #E91E63; }
#cart-button { position: fixed; top: 25px; right: 40px; background-color: #E91E63; 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 0 20px #E91E63; transition: all 0.3s; z-index: 1000; }
#cart-button:hover { transform: scale(1.1); }
#cart-button span { position: absolute; top: -5px; right: -5px; background-color: #C2185B; color: white; border-radius: 50%; padding: 2px 6px; font-size: 0.7rem; }
.modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.7); backdrop-filter: blur(5px); overflow-y: auto; }
.modal-content { background: #1a1a1a; margin: 5% auto; padding: 25px; border-radius: 15px; width: 90%; max-width: 700px; box-shadow: 0 0 30px rgba(0,0,0,0.5); position: relative; border: 1px solid #333;}
.close { position: absolute; top: 15px; right: 15px; font-size: 1.8rem; color: #aaa; cursor: pointer; transition: color 0.3s; }
.cart-item { display: grid; grid-template-columns: auto 1fr auto auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #333; }
.cart-item:last-child { border-bottom: none; }
.cart-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; }
.cart-summary { margin-top: 20px; text-align: right; border-top: 1px solid #333; padding-top: 15px; }
.cart-summary strong { font-size: 1.2rem; color: #E91E63;}
.cart-actions { margin-top: 25px; display: flex; justify-content: space-between; gap: 10px; }
#notification-placeholder { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); z-index: 1002; }
.notification { background-color: #E91E63; color: white; padding: 10px 20px; border-radius: 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.4); opacity: 0; transition: opacity 0.5s ease; font-size: 0.9rem;}
.notification.show { opacity: 1;}
.no-results-message { color: #555; font-size: 1.5rem; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>{{ shop_name }}</h1>
</div>
<div class="vr-viewport">
<div class="vr-carousel" id="vr-carousel">
{% for product in products %}
<div class="product-card" id="product-card-{{ loop.index0 }}" data-index="{{ loop.index0 }}" data-category="{{ product.get('category', 'Без категории') }}">
<div class="product-card-front">
{% 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">
{% else %}
<img src="https://via.placeholder.com/250x250.png?text=No+Image" alt="No Image" loading="lazy">
{% endif %}
</div>
<h2>{{ product['name'] }}</h2>
<p class="price">{{ "%.2f"|format(product['price']) }} {{ currency_code }}</p>
<button class="view-details-btn">Подробнее</button>
</div>
<div class="product-card-back">
<button class="close-detail-view" title="Закрыть">&times;</button>
<div class="product-detail-content" id="detail-content-{{ loop.index0 }}">
</div>
</div>
</div>
{% endfor %}
</div>
{% if not products %}
<p class="no-results-message">Товары пока не добавлены.</p>
{% endif %}
</div>
<div class="filters">
<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>
<div id="cartModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('cartModal')">&times;</span>
<h2><i class="fas fa-shopping-cart"></i> Ваша корзина</h2>
<div id="cartContent"><p>Ваша корзина пуста.</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" onclick="clearCart()"><i class="fas fa-trash"></i> Очистить</button>
<button class="product-button add-to-cart" onclick="formulateOrder()"><i class="fas fa-file-alt"></i> Сформировать заказ</button>
</div>
</div>
</div>
<button id="cart-button" onclick="openCartModal()">
<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"></script>
<script>
const products = {{ products|tojson }};
const repoId = '{{ repo_id }}';
const currencyCode = '{{ currency_code }}';
let cart = JSON.parse(localStorage.getItem('mekaCart') || '[]');
const carousel = document.getElementById('vr-carousel');
const cards = document.querySelectorAll('.product-card');
let rotation = 0;
let activeCardIndex = -1;
const radius = 400;
function setupCarousel() {
cards.forEach((card, i) => {
const angle = (i / cards.length) * 360;
const transform = `rotateY(${angle}deg) translateZ(${radius}px)`;
card.style.setProperty('--transform-initial', transform);
card.style.transform = transform;
card.addEventListener('click', (e) => {
if (card.classList.contains('is-active')) return;
e.stopPropagation();
selectCard(i);
});
card.querySelector('.close-detail-view').addEventListener('click', (e) => {
e.stopPropagation();
deselectActiveCard();
});
});
filterProducts();
}
function selectCard(index) {
if (activeCardIndex !== -1) {
cards[activeCardIndex].classList.remove('is-active');
}
activeCardIndex = index;
const card = cards[index];
card.classList.add('is-active');
const angle = (index / cards.length) * 360;
const activeTransform = `translateZ(150px) rotateY(${-rotation - angle}deg)`;
card.style.setProperty('--transform-active', activeTransform);
loadProductDetails(index);
}
function deselectActiveCard() {
if (activeCardIndex === -1) return;
cards[activeCardIndex].classList.remove('is-active');
activeCardIndex = -1;
}
let isDragging = false;
let startX, currentRotation = 0;
function onPointerDown(e) {
if (activeCardIndex !== -1) return;
isDragging = true;
startX = e.clientX || e.touches[0].clientX;
currentRotation = rotation;
document.body.classList.add('grabbing');
carousel.style.transition = 'none';
}
function onPointerMove(e) {
if (!isDragging || activeCardIndex !== -1) return;
const x = e.clientX || e.touches[0].clientX;
const deltaX = x - startX;
rotation = currentRotation + (deltaX * 0.2);
carousel.style.transform = `rotateY(${rotation}deg)`;
}
function onPointerUp() {
isDragging = false;
document.body.classList.remove('grabbing');
carousel.style.transition = 'transform 0.5s cubic-bezier(0.25, 1, 0.5, 1)';
}
function onWheel(e) {
if (activeCardIndex !== -1) return;
e.preventDefault();
rotation -= e.deltaY * 0.1;
carousel.style.transform = `rotateY(${rotation}deg)`;
}
document.body.addEventListener('pointerdown', onPointerDown);
document.body.addEventListener('pointermove', onPointerMove);
document.body.addEventListener('pointerup', onPointerUp);
document.body.addEventListener('pointerleave', onPointerUp);
document.body.addEventListener('wheel', onWheel, { passive: false });
document.addEventListener('click', (e) => {
if (activeCardIndex !== -1 && !cards[activeCardIndex].contains(e.target)) {
deselectActiveCard();
}
});
function loadProductDetails(index) {
const detailContainer = document.getElementById(`detail-content-${index}`);
if (detailContainer.innerHTML.trim() !== '') return;
const product = products[index];
const colors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : [];
let colorsHtml = '';
if (colors.length > 0) {
colorsHtml = `<label for="colorSelect-${index}">Цвет/Вариант:</label>
<select id="colorSelect-${index}" class="color-select">
${colors.map(c => `<option value="${c}">${c}</option>`).join('')}
</select>`;
}
detailContainer.innerHTML = `
<h3>${product.name}</h3>
<p><strong>Категория:</strong> ${product.category || 'Без категории'}</p>
<p class="price-detail"><strong>Цена:</strong> ${product.price.toFixed(2)} ${currencyCode}</p>
<p><strong>Описание:</strong><br>${product.description || 'Описание отсутствует.'}</p>
<label for="quantityInput-${index}">Количество:</label>
<input type="number" id="quantityInput-${index}" class="quantity-input" min="1" value="1">
${colorsHtml}
<div class="actions">
<button class="product-button add-to-cart" onclick="event.stopPropagation(); addToCart(${index})">
<i class="fas fa-cart-plus"></i> В корзину
</button>
</div>
`;
}
function addToCart(index) {
const product = products[index];
const quantity = parseInt(document.getElementById(`quantityInput-${index}`).value);
const colorSelect = document.getElementById(`colorSelect-${index}`);
const color = colorSelect ? colorSelect.value : 'N/A';
if (isNaN(quantity) || quantity <= 0) {
alert("Укажите корректное количество.");
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('mekaCart', JSON.stringify(cart));
updateCartButton();
showNotification(`${product.name} добавлен в корзину!`);
deselectActiveCard();
}
function updateCartButton() {
const cartCountElement = document.getElementById('cart-count');
const cartButton = document.getElementById('cart-button');
let totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
if (totalItems > 0) {
cartCountElement.textContent = totalItems;
cartButton.style.display = 'flex';
} else {
cartButton.style.display = 'none';
}
}
function openCartModal() {
const cartContent = document.getElementById('cartContent');
const cartTotalElement = document.getElementById('cartTotal');
let total = 0;
if (cart.length === 0) {
cartContent.innerHTML = '<p>Ваша корзина пуста.</p>';
cartTotalElement.textContent = '0.00';
} else {
cartContent.innerHTML = cart.map(item => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
const photoUrl = item.photo ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` : 'https://via.placeholder.com/60x60.png?text=N/A';
return `<div class="cart-item">
<img src="${photoUrl}" alt="${item.name}">
<div><strong>${item.name} ${item.color !== 'N/A' ? `(${item.color})` : ''}</strong><br>${item.price.toFixed(2)} x ${item.quantity}</div>
<span>${itemTotal.toFixed(2)}</span>
<button onclick="removeFromCart('${item.id}')">&times;</button>
</div>`;
}).join('');
cartTotalElement.textContent = total.toFixed(2);
}
document.getElementById('cartModal').style.display = 'block';
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = 'none';
}
function removeFromCart(itemId) {
cart = cart.filter(item => item.id !== itemId);
localStorage.setItem('mekaCart', JSON.stringify(cart));
openCartModal();
updateCartButton();
}
function clearCart() {
if (confirm("Вы уверены?")) {
cart = [];
localStorage.removeItem('mekaCart');
openCartModal();
updateCartButton();
}
}
function formulateOrder() {
if (cart.length === 0) return;
fetch('/create_order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cart: cart })
})
.then(res => res.json())
.then(data => {
if (data.order_id) {
localStorage.removeItem('mekaCart');
cart = [];
updateCartButton();
closeModal('cartModal');
window.location.href = `/order/${data.order_id}`;
} else { throw new Error(data.error); }
}).catch(err => alert(`Ошибка: ${err.message}`));
}
function showNotification(message, duration = 3000) {
const placeholder = document.getElementById('notification-placeholder');
const notification = document.createElement('div');
notification.className = 'notification';
notification.textContent = message;
placeholder.appendChild(notification);
void notification.offsetWidth;
notification.classList.add('show');
setTimeout(() => {
notification.classList.remove('show');
notification.addEventListener('transitionend', () => notification.remove());
}, duration);
}
function filterProducts() {
const activeCategory = document.querySelector('.category-filter.active').dataset.category;
let visibleCount = 0;
deselectActiveCard();
cards.forEach(card => {
const cardCategory = card.dataset.category;
if (activeCategory === 'all' || cardCategory === activeCategory) {
card.classList.remove('is-hidden');
visibleCount++;
} else {
card.classList.add('is-hidden');
}
});
const visibleCards = Array.from(cards).filter(c => !c.classList.contains('is-hidden'));
visibleCards.forEach((card, i) => {
const angle = (i / visibleCards.length) * 360;
const transform = `rotateY(${angle}deg) translateZ(${radius}px)`;
card.style.setProperty('--transform-initial', transform);
card.style.transform = transform;
});
rotation = 0;
carousel.style.transform = `rotateY(0deg)`;
}
document.querySelectorAll('.category-filter').forEach(btn => {
btn.addEventListener('click', function() {
document.querySelector('.category-filter.active').classList.remove('active');
this.classList.add('active');
filterProducts();
});
});
document.addEventListener('DOMContentLoaded', () => {
if(products.length > 0) {
setupCarousel();
}
updateCartButton();
});
</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: #E91E63;">{{ product['name'] }}</h2>
<div class="swiper-container" style="max-width: 450px; margin: 0 auto 20px; border-radius: 10px; overflow: hidden; background-color: #222; border: 1px solid #444;">
<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 data-src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}"
alt="{{ product['name'] }} - фото {{ loop.index }}"
class="swiper-lazy"
style="max-width: 100%; max-height: 400px; object-fit: contain; display: block; margin: auto; cursor: grab;">
<div class="swiper-lazy-preloader swiper-lazy-preloader-white"></div>
</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: #E91E63;"></div>
<div class="swiper-button-prev" style="color: #E91E63;"></div>
{% endif %}
</div>
<div style="margin-top: 20px; font-size: 1rem; line-height: 1.7; color: #ccc;">
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
<p style="font-size: 1.2rem; font-weight: bold; color: #F06292;"><strong>Цена:</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p>
<p><strong>Описание:</strong><br> {{ product.get('description', 'Описание отсутствует.')|replace('\\n', '<br>')|safe }}</p>
{% set colors = product.get('colors', []) %}
{% if colors and colors|select('ne', '')|list|length > 0 %}
<p><strong>Доступные цвета/варианты:</strong> {{ colors|select('ne', '')|join(', ') }}</p>
{% endif %}
</div>
</div>
'''
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 }} - {{ shop_name }}</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
body { font-family: 'Poppins', sans-serif; background: #000000; color: #eeeeee; line-height: 1.6; padding: 20px; }
.container { max-width: 800px; margin: 20px auto; padding: 30px; background: #1a1a1a; border-radius: 15px; box-shadow: 0 0 30px rgba(233, 30, 99, 0.2); border: 1px solid rgba(233, 30, 99, 0.3); }
h1 { text-align: center; color: #E91E63; margin-bottom: 25px; font-size: 1.8rem; font-weight: 600; text-shadow: 0 0 5px #E91E63; }
h2 { color: #F06292; margin-top: 30px; margin-bottom: 15px; font-size: 1.4rem; border-bottom: 1px solid #333; padding-bottom: 8px;}
.order-meta { font-size: 0.9rem; color: #777; 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 #222; }
.order-item:last-child { border-bottom: none; }
.order-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 8px; background-color: #222; padding: 5px; border: 1px solid #444;}
.item-details strong { display: block; margin-bottom: 5px; font-size: 1.05rem; color: #eee;}
.item-details span { font-size: 0.9rem; color: #aaa; display: block;}
.item-total { font-weight: bold; text-align: right; font-size: 1rem; color: #F06292;}
.order-summary { margin-top: 30px; padding-top: 20px; border-top: 2px solid #E91E63; text-align: right; }
.order-summary p { margin-bottom: 10px; font-size: 1.1rem; color: #ccc; }
.order-summary strong { font-size: 1.3rem; color: #E91E63; }
.customer-info { margin-top: 30px; background-color: #222; padding: 20px; border-radius: 8px; border: 1px solid #444;}
.customer-info p { margin-bottom: 8px; font-size: 0.95rem; color: #ccc;}
.customer-info strong { color: #F06292; }
.actions { margin-top: 30px; text-align: center; }
.button { padding: 12px 25px; border: none; border-radius: 8px; background-color: #E91E63; color: white; font-weight: 600; cursor: pointer; transition: all 0.3s ease; font-size: 1rem; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; box-shadow: 0 0 15px rgba(233, 30, 99, 0.4); }
.button:hover { background-color: #C2185B; transform: translateY(-2px); box-shadow: 0 4px 20px rgba(233, 30, 99, 0.6); }
.button:active { transform: scale(0.98); }
.button i { font-size: 1.2rem; }
.catalog-link { display: block; text-align: center; margin-top: 25px; color: #E91E63; text-decoration: none; font-size: 0.9rem; }
.catalog-link:hover { text-decoration: underline; }
.not-found { text-align: center; color: #e3342f; font-size: 1.2rem; padding: 40px 0;}
</style>
</head>
<body>
<div class="container">
{% if order %}
<h1><i class="fas fa-receipt"></i> Ваш Заказ №{{ order.id }}</h1>
<p class="order-meta">Дата создания: {{ order.created_at }}</p>
<h2><i class="fas fa-shopping-bag"></i> Товары в заказе</h2>
<div id="orderItems">
{% for item in order.cart %}
<div class="order-item">
<img src="{{ item.photo_url }}" alt="{{ item.name }}">
<div class="item-details">
<strong>{{ item.name }} {% if item.color != 'N/A' %}({{ item.color }}){% endif %}</strong>
<span>{{ "%.2f"|format(item.price) }} {{ currency_code }} × {{ item.quantity }}</span>
</div>
<div class="item-total">
{{ "%.2f"|format(item.price * item.quantity) }} {{ currency_code }}
</div>
</div>
{% endfor %}
</div>
<div class="order-summary">
<p>Общая сумма товаров: <strong>{{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>
<p><strong>ИТОГО К ОПЛАТЕ: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>
</div>
<div class="customer-info">
<h2><i class="fas fa-info-circle"></i> Статус заказа</h2>
<p>Этот заказ был оформлен без входа в систему.</p>
<p>Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.</p>
</div>
<div class="actions">
<button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> Отправить заказ</button>
</div>
<a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в VR каталог</a>
<script>
function sendOrderViaWhatsApp() {
const orderId = '{{ order.id }}';
const orderUrl = `{{ request.url }}`;
const whatsappNumber = "{{ whatsapp_number }}";
const paymentInfo = "{{ payment_info | safe }}";
let message = `Здравствуйте! Хочу подтвердить свой заказ на {{ shop_name }}:%0A%0A`;
message += `*Номер заказа:* ${orderId}%0A`;
message += `*Ссылка на заказ:* ${encodeURIComponent(orderUrl)}%0A%0A`;
message += `*Состав заказа:*%0A`;
{% for item in order.cart %}
message += `- {{ item.name }}{% if item.color != 'N/A' %} ({{ item.color }}){% endif %} x {{ item.quantity }} - {{ "%.2f"|format(item.price * item.quantity) }} {{ currency_code }}%0A`;
{% endfor %}
message += `%0A*Итого:* {{ "%.2f"|format(order.total_price) }} {{ currency_code }}%0A%0A`;
message += `Пожалуйста, свяжитесь со мной для уточнения деталей.%0A%0A`;
message += `${encodeURIComponent(paymentInfo)}`;
const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${message}`;
window.open(whatsappUrl, '_blank');
}
</script>
{% else %}
<h1 style="color: #dc3545;"><i class="fas fa-exclamation-triangle"></i> Ошибка</h1>
<p class="not-found">Заказ с таким ID не найден.</p>
<a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в VR каталог</a>
{% endif %}
</div>
</body>
</html>
'''
ADMIN_TEMPLATE = '''
<!DOCTYPE html>
<html lang="{{ current_lang }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ lang['admin_panel_title'] }}</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
body { font-family: 'Poppins', sans-serif; background-color: #000000; color: #eeeeee; padding: 20px; line-height: 1.6; }
.container { max-width: 1200px; margin: 0 auto; background-color: #1a1a1a; padding: 25px; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.3); border: 1px solid #333; }
.header { padding-bottom: 15px; margin-bottom: 25px; border-bottom: 1px solid #333; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;}
h1, h2, h3 { font-weight: 600; color: #E91E63; 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: #F06292; margin-top: 20px; }
.section { margin-bottom: 30px; padding: 20px; background-color: #222; border: 1px solid #333; border-radius: 8px; }
form { margin-bottom: 20px; }
label { font-weight: 500; margin-top: 10px; display: block; color: #ccc; 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 #444; border-radius: 6px; font-size: 0.95rem; box-sizing: border-box; transition: border-color 0.3s ease; background-color: #222; color: #eee; }
input::placeholder, textarea::placeholder, select::placeholder { color: #888; }
input:focus, textarea:focus, select:focus { border-color: #E91E63; outline: none; box-shadow: 0 0 0 2px rgba(233, 30, 99, 0.1); }
textarea { min-height: 80px; resize: vertical; }
input[type="file"] { padding: 8px; background-color: #222; cursor: pointer; border: 1px solid #444; color: #eee;}
input[type="file"]::file-selector-button { padding: 5px 10px; border-radius: 4px; background-color: #444; color: #eee; border: 1px solid #555; 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; color: #eee;}
button, .button { padding: 10px 18px; border: none; border-radius: 6px; background-color: #C2185B; 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: #E91E63; }
button:active, .button:active { transform: scale(0.98); }
button[type="submit"] { min-width: 120px; justify-content: center; }
.delete-button { background-color: #dc3545; }
.delete-button:hover { background-color: #e3342f; }
.add-button { background-color: #E91E63; }
.add-button:hover { background-color: #C2185B; }
.item-list { display: grid; gap: 20px; }
.item { background: #222; padding: 15px 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.2); border: 1px solid #444; }
.item p { margin: 5px 0; font-size: 0.9rem; color: #ccc; }
.item strong { color: #eee; }
.item .description { font-size: 0.85rem; color: #aaa; 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: #C2185B; }
.item-actions button:not(.delete-button):hover { background-color: #E91E63; }
.edit-form-container { margin-top: 15px; padding: 20px; background: #2a1a1a; border: 1px dashed #444; border-radius: 6px; display: none; }
details { background-color: #222; border: 1px solid #333; border-radius: 8px; margin-bottom: 20px; }
details > summary { cursor: pointer; font-weight: 600; color: #F06292; display: block; padding: 15px; border-bottom: 1px solid #333; list-style: none; position: relative; }
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: #E91E63; }
details[open] > summary::after { transform: translateY(-50%) rotate(180deg); }
details[open] > summary { border-bottom: 1px solid #333; }
details .form-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; background-color: #333; color: #eee; border-color: #555;}
.color-input-group input:focus { border-color: #E91E63; box-shadow: 0 0 0 2px rgba(233, 30, 99, 0.1); }
.remove-color-btn { background-color: #dc3545; padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; }
.remove-color-btn:hover { background-color: #e3342f; }
.add-color-btn { background-color: #444; color: #F06292; border: 1px solid #555; }
.add-color-btn:hover { background-color: #E91E63; color: white; border-color: #E91E63; }
.photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #444; object-fit: cover;}
.sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
.download-hf-button { background-color: #6c757d; }
.download-hf-button:hover { background-color: #5a6268; }
.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: #1a3a2a; color: #90ee90; border: 1px solid #2b5d3e;}
.message.error { background-color: #4a1a1a; color: #ff6b6b; border: 1px solid #721c24;}
.message.warning { background-color: #4a3a1a; color: #ffeb80; border: 1px solid #856404; }
.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: #1a3a2a; color: #90ee90; }
.status-indicator.out-of-stock { background-color: #4a1a1a; color: #ff6b6b; }
.status-indicator.top-product { background-color: #4a3a1a; color: #ffeb80; margin-left: 5px;}
.language-selector { margin-left: auto; }
.language-selector select { padding: 8px; border-radius: 6px; background-color: #222; color: #eee; border: 1px solid #444;}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div class="logo-title-container" style="display: flex; align-items: center; gap: 15px;">
<h1><i class="fas fa-tools"></i> {{ lang['admin_panel_title'] }}</h1>
</div>
<div style="display: flex; align-items: center; gap: 10px;">
<div class="language-selector">
<form id="langForm" method="GET" action="{{ url_for('admin') }}">
<select name="lang" onchange="document.getElementById('langForm').submit()">
<option value="ru" {% if current_lang == 'ru' %}selected{% endif %}>Русский</option>
<option value="tr" {% if current_lang == 'tr' %}selected{% endif %}>Türkçe</option>
</select>
</form>
</div>
<a href="{{ url_for('catalog') }}" class="button" style="background-color: #E91E63;"><i class="fas fa-store"></i> {{ lang['go_to_catalog'] }}</a>
</div>
</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> {{ lang['sync_section_title'] }}</h2>
<div class="sync-buttons">
<form method="POST" action="{{ url_for('force_upload') }}" style="display: inline;" onsubmit="return confirm('{{ lang['confirm_upload'] }}');">
<button type="submit" class="button" title="{{ lang['upload_db_button'] }}"><i class="fas fa-upload"></i> {{ lang['upload_db_button'] }}</button>
</form>
<form method="POST" action="{{ url_for('force_download') }}" style="display: inline;" onsubmit="return confirm('{{ lang['confirm_download'] }}');">
<button type="submit" class="button download-hf-button" title="{{ lang['download_db_button'] }} (перезапишет локальные)"><i class="fas fa-download"></i> {{ lang['download_db_button'] }}</button>
</form>
</div>
<p style="font-size: 0.85rem; color: #999;">{{ lang['sync_info'] }}</p>
</div>
<div class="flex-container">
<div class="flex-item">
<div class="section">
<h2><i class="fas fa-tags"></i> {{ lang['categories_section_title'] }}</h2>
<details>
<summary><i class="fas fa-plus-circle"></i> {{ lang['add_category_summary'] }}</summary>
<div class="form-content">
<form method="POST">
<input type="hidden" name="action" value="add_category">
<label for="add_category_name">{{ lang['add_category_name_label'] }}</label>
<input type="text" id="add_category_name" name="category_name" required>
<button type="submit" class="add-button"><i class="fas fa-plus"></i> {{ lang['add_category_button'] }}</button>
</form>
</div>
</details>
<h3>{{ lang['existing_categories_title'] }}</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('{{ lang['confirm_delete_category'].format(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>{{ lang['no_categories'] }}</p>
{% endif %}
</div>
</div>
<div class="flex-item">
<div class="section">
<h2><i class="fas fa-info-circle"></i> {{ lang['info_section_title'] }}</h2>
<p>{{ lang['info_text_1'] }}</p>
<p>{{ lang['info_text_2'] }}</p>
</div>
</div>
</div>
<div class="section">
<h2><i class="fas fa-box-open"></i> {{ lang['products_section_title'] }}</h2>
<details>
<summary><i class="fas fa-plus-circle"></i> {{ lang['add_product_summary'] }}</summary>
<div class="form-content">
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="add_product">
<label for="add_name">{{ lang['product_name_label'] }}</label>
<input type="text" id="add_name" name="name" required>
<label for="add_price">{{ lang['product_price_label'] }}</label>
<input type="number" id="add_price" name="price" step="0.01" min="0" required>
<label for="add_description">{{ lang['product_description_label'] }}</label>
<textarea id="add_description" name="description" rows="4"></textarea>
<label for="add_category">{{ lang['product_category_label'] }}</label>
<select id="add_category" name="category">
<option value="{{ lang['default_category'] }}">{{ lang['default_category'] }}</option>
{% for category in categories %}
<option value="{{ category }}">{{ category }}</option>
{% endfor %}
</select>
<label for="add_photos">{{ lang['product_photos_label'] }}</label>
<input type="file" id="add_photos" name="photos" accept="image/*" multiple>
<label>{{ lang['product_colors_label'] }}</label>
<div id="add-color-inputs">
<div class="color-input-group">
<input type="text" name="colors" placeholder="{{ lang['add_color_button'] }}">
<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> {{ lang['add_color_button'] }}</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">{{ lang['in_stock_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">{{ lang['is_top_label'] }}</label>
</div>
<br>
<button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> {{ lang['add_product_button'] }}</button>
</form>
</div>
</details>
<h3>{{ lang['product_list_title'] }}</h3>
{% if products %}
<div class="item-list">
{% for product in products %}
<div class="item">
<div style="display: flex; gap: 15px; align-items: flex-start;">
<div class="photo-preview" style="flex-shrink: 0;">
{% if product.get('photos') %}
<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="Фото">
</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: #eee;">
{{ product['name'] }}
{% if product.get('in_stock', True) %}
<span class="status-indicator in-stock">{{ lang['status_in_stock'] }}</span>
{% else %}
<span class="status-indicator out-of-stock">{{ lang['status_out_of_stock'] }}</span>
{% endif %}
{% if product.get('is_top', False) %}
<span class="status-indicator top-product"><i class="fas fa-star"></i> {{ lang['status_top'] }}</span>
{% endif %}
</h3>
<p><strong>{{ lang['category_label'] }}</strong> {{ product.get('category', lang['default_category']) }}</p>
<p><strong>{{ lang['price_label'] }}</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p>
<p class="description" title="{{ product.get('description', '') }}"><strong>{{ lang['description_label'] }}</strong> {{ product.get('description', 'N/A')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}</p>
{% set colors = product.get('colors', []) %}
<p><strong>{{ lang['colors_label'] }}</strong> {{ colors|select('ne', '')|join(', ') if colors|select('ne', '')|list|length > 0 else lang['no_colors'] }}</p>
{% if product.get('photos') and product['photos']|length > 1 %}
<p style="font-size: 0.8rem; color: #999;">(Всего фото: {{ product['photos']|length }})</p>
{% endif %}
</div>
</div>
<div class="item-actions">
<button type="button" class="button" onclick="toggleEditForm('edit-form-{{ loop.index0 }}')"><i class="fas fa-edit"></i> {{ lang['edit_button'] }}</button>
<form method="POST" style="margin:0;" onsubmit="return confirm('{{ lang['confirm_delete_product'].format(product['name']) }}');">
<input type="hidden" name="action" value="delete_product">
<input type="hidden" name="index" value="{{ loop.index0 }}">
<button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> {{ lang['delete_button'] }}</button>
</form>
</div>
<div id="edit-form-{{ loop.index0 }}" class="edit-form-container">
<h4><i class="fas fa-edit"></i> {{ lang['edit_form_title'] }} {{ product['name'] }}</h4>
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="edit_product">
<input type="hidden" name="index" value="{{ loop.index0 }}">
<label>{{ lang['product_name_label'] }}</label>
<input type="text" name="name" value="{{ product['name'] }}" required>
<label>{{ lang['product_price_label'] }}</label>
<input type="number" name="price" step="0.01" min="0" value="{{ product['price'] }}" required>
<label>{{ lang['product_description_label'] }}</label>
<textarea name="description" rows="4">{{ product.get('description', '') }}</textarea>
<label>{{ lang['product_category_label'] }}</label>
<select name="category">
<option value="{{ lang['default_category'] }}" {% if product.get('category', lang['default_category']) == lang['default_category'] %}selected{% endif %}>{{ lang['default_category'] }}</option>
{% for category in categories %}
<option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option>
{% endfor %}
</select>
<label>{{ lang['replace_photos_label'] }}</label>
<input type="file" name="photos" accept="image/*" multiple>
{% if product.get('photos') %}
<p style="font-size: 0.85rem; margin-top: 5px; color: #ccc;">{{ lang['current_photos'] }}</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 }}">
{% endfor %}
</div>
{% endif %}
<label>{{ lang['product_colors_label'] }}</label>
<div id="edit-color-inputs-{{ loop.index0 }}">
{% set current_colors = product.get('colors', []) %}
{% if current_colors and current_colors|select('ne', '')|list|length > 0 %}
{% for color in current_colors %}
{% if color.strip() %}
<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>
{% endif %}
{% endfor %}
{% else %}
<div class="color-input-group">
<input type="text" name="colors" placeholder="{{ lang['add_color_button'] }}">
<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-{{ loop.index0 }}')"><i class="fas fa-palette"></i> {{ lang['add_color_button'] }}</button>
<br>
<div style="margin-top: 15px;">
<input type="checkbox" id="edit_in_stock_{{ loop.index0 }}" name="in_stock" {% if product.get('in_stock', True) %}checked{% endif %}>
<label for="edit_in_stock_{{ loop.index0 }}" class="inline-label">{{ lang['in_stock_label'] }}</label>
</div>
<div style="margin-top: 5px;">
<input type="checkbox" id="edit_is_top_{{ loop.index0 }}" name="is_top" {% if product.get('is_top', False) %}checked{% endif %}>
<label for="edit_is_top_{{ loop.index0 }}" class="inline-label">{{ lang['is_top_label'] }}</label>
</div>
<br>
<button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> {{ lang['save_changes_button'] }}</button>
</form>
</div>
</div>
{% endfor %}
</div>
{% else %}
<p>{{ lang['no_products'] }}</p>
{% endif %}
</div>
</div>
<script>
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="{{ lang['add_color_button'] }}">
<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="{{ lang['add_color_button'] }}">
<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");
}
}
</script>
</body>
</html>
'''
@app.route('/')
def catalog():
data = load_data()
all_products = data.get('products', [])
categories = sorted(data.get('categories', []))
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,
store_address=STORE_ADDRESS,
shop_name=SHOP_NAME,
currency_code=CURRENCY_CODE
)
@app.route('/product/<int:index>')
def product_detail(index):
data = load_data()
all_products = data.get('products', [])
products_in_stock = [p for p in all_products if p.get('in_stock', True)]
products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
try:
product = products_sorted[index]
except IndexError:
logging.warning(f"Attempted access to non-existent or out-of-stock product with index {index}")
return "Товар не найден или отсутствует в наличии.", 404
return render_template_string(
PRODUCT_DETAIL_TEMPLATE,
product=product,
repo_id=REPO_ID,
currency_code=CURRENCY_CODE
)
@app.route('/create_order', methods=['POST'])
def create_order():
order_data = request.get_json()
if not order_data or 'cart' not in order_data or not order_data['cart']:
logging.warning("Create order request missing cart data or cart is empty.")
return jsonify({"error": "Корзина пуста или не передана."}), 400
cart_items = order_data['cart']
total_price = 0
processed_cart = []
for item in cart_items:
if not all(k in item for k in ('name', 'price', 'quantity')):
logging.error(f"Invalid cart item structure received: {item}")
return jsonify({"error": "Неверный формат товара в корзине."}), 400
try:
price = float(item['price'])
quantity = int(item['quantity'])
if price < 0 or quantity <= 0:
raise ValueError("Invalid price or quantity")
total_price += price * quantity
processed_cart.append({
"name": item['name'],
"price": price,
"quantity": quantity,
"color": item.get('color', 'N/A'),
"photo": item.get('photo'),
"photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item['photo']}" if item.get('photo') else "https://via.placeholder.com/60x60.png?text=N/A"
})
except (ValueError, TypeError) as e:
logging.error(f"Invalid price/quantity in cart item: {item}. Error: {e}")
return jsonify({"error": "Неверная цена или количество в товаре."}), 400
order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}"
order_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
new_order = {
"id": order_id,
"created_at": order_timestamp,
"cart": processed_cart,
"total_price": round(total_price, 2),
"user_info": None,
"status": "new"
}
try:
data = load_data()
if 'orders' not in data or not isinstance(data.get('orders'), dict):
data['orders'] = {}
data['orders'][order_id] = new_order
save_data(data)
logging.info(f"Order {order_id} created successfully (anonymously).")
return jsonify({"order_id": order_id}), 201
except Exception as e:
logging.error(f"Failed to save order {order_id}: {e}", exc_info=True)
return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500
@app.route('/order/<order_id>')
def view_order(order_id):
data = load_data()
order = data.get('orders', {}).get(order_id)
if order:
logging.info(f"Displaying order {order_id}")
else:
logging.warning(f"Order {order_id} not found.")
return render_template_string(ORDER_TEMPLATE,
order=order,
repo_id=REPO_ID,
shop_name=SHOP_NAME,
currency_code=CURRENCY_CODE,
whatsapp_number=WHATSAPP_NUMBER,
payment_info=PAYMENT_INFO)
@app.route('/admin', methods=['GET', 'POST'])
def admin():
current_lang, lang = get_admin_lang()
data = load_data()
products = data.get('products', [])
categories = data.get('categories', [])
if 'orders' not in data or not isinstance(data.get('orders'), dict):
data['orders'] = {}
if request.method == 'POST':
action = request.form.get('action')
logging.info(f"Admin action received: {action}")
try:
if action == 'add_category':
category_name = request.form.get('category_name', '').strip()
if category_name and category_name not in categories:
categories.append(category_name)
data['categories'] = categories
save_data(data)
logging.info(f"Category '{category_name}' added.")
flash(lang['flash_category_added'].format(category_name), 'success')
elif not category_name:
logging.warning("Attempted to add empty category.")
flash(lang['flash_category_empty'], 'error')
else:
logging.warning(f"Category '{category_name}' already exists.")
flash(lang['flash_category_exists'].format(category_name), 'error')
elif action == 'delete_category':
category_to_delete = request.form.get('category_name')
if category_to_delete and category_to_delete in categories:
categories.remove(category_to_delete)
updated_count = 0
for product in products:
if product.get('category') == category_to_delete:
product['category'] = lang['default_category']
updated_count += 1
data['categories'] = categories
data['products'] = products
save_data(data)
logging.info(f"Category '{category_to_delete}' deleted. Updated products: {updated_count}.")
flash(lang['flash_category_deleted'].format(category_to_delete, updated_count), 'success')
else:
logging.warning(f"Attempted to delete non-existent or empty category: {category_to_delete}")
flash(lang['flash_category_delete_failed'].format(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(lang['flash_product_name_price_required'], 'error')
return redirect(url_for('admin'))
try:
price = round(float(price_str), 2)
if price < 0: price = 0
except ValueError:
flash(lang['flash_product_invalid_price'], 'error')
return redirect(url_for('admin'))
photos_list = []
if photos_files and HF_TOKEN_WRITE:
uploads_dir = 'uploads_temp'
os.makedirs(uploads_dir, exist_ok=True)
api = HfApi()
photo_limit = 10
uploaded_count = 0
for photo in photos_files:
if uploaded_count >= photo_limit:
logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.")
flash(lang['flash_photo_limit'].format(photo_limit), "warning")
break
if photo and photo.filename:
try:
ext = os.path.splitext(photo.filename)[1].lower()
if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
logging.warning(f"Skipping non-image file upload: {photo.filename}")
flash(lang['flash_photo_skipped_non_image'].format(photo.filename), "warning")
continue
safe_name = secure_filename(name.replace(' ', '_'))[:50]
photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
temp_path = os.path.join(uploads_dir, photo_filename)
photo.save(temp_path)
logging.info(f"Uploading photo {photo_filename} to HF for product {name}...")
api.upload_file(
path_or_fileobj=temp_path,
path_in_repo=f"photos/{photo_filename}",
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Add photo for product {name}"
)
photos_list.append(photo_filename)
logging.info(f"Photo {photo_filename} uploaded successfully.")
os.remove(temp_path)
uploaded_count += 1
except Exception as e:
logging.error(f"Error uploading photo {photo.filename} to HF: {e}", exc_info=True)
flash(lang['flash_photo_upload_error'].format(photo.filename), 'error')
if os.path.exists(temp_path):
try: os.remove(temp_path)
except OSError: pass
elif photo and not photo.filename:
logging.warning("Received an empty photo file object when adding product.")
try:
if os.path.exists(uploads_dir) and os.path.isdir(uploads_dir) and not os.listdir(uploads_dir):
os.rmdir(uploads_dir)
except OSError as e:
logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}")
elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
flash(lang['flash_no_hf_token_photos_not_updated'], "warning")
new_product = {
'name': name, 'price': price, 'description': description,
'category': category if category in categories else lang['default_category'],
'photos': photos_list, 'colors': colors,
'in_stock': in_stock, 'is_top': is_top
}
products.append(new_product)
data['products'] = products
save_data(data)
logging.info(f"Product '{name}' added.")
flash(lang['flash_product_added'].format(name), 'success')
elif action == 'edit_product':
index_str = request.form.get('index')
if index_str is None:
flash(lang['flash_edit_index_missing'], 'error')
return redirect(url_for('admin'))
try:
index = int(index_str)
if not (0 <= index < len(products)):
raise IndexError("Product index out of range")
product_to_edit = products[index]
original_name = product_to_edit.get('name', 'N/A')
except (ValueError, IndexError):
flash(lang['flash_edit_index_invalid'].format(index_str), 'error')
logging.error(f"Invalid index '{index_str}' for editing. Product list length: {len(products)}")
return redirect(url_for('admin'))
product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip()
price_str = request.form.get('price', str(product_to_edit.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 lang['default_category']
product_to_edit['colors'] = [c.strip() for c in request.form.getlist('colors') if c.strip()]
product_to_edit['in_stock'] = 'in_stock' in request.form
product_to_edit['is_top'] = 'is_top' in request.form
try:
price = round(float(price_str), 2)
if price < 0: price = 0
product_to_edit['price'] = price
except ValueError:
logging.warning(f"Invalid price format '{price_str}' during edit of product {original_name}. Price not changed.")
flash(lang['flash_edit_price_invalid'].format(original_name), 'warning')
photos_files = request.files.getlist('photos')
if photos_files and any(f.filename for f in photos_files) and HF_TOKEN_WRITE:
uploads_dir = 'uploads_temp'
os.makedirs(uploads_dir, exist_ok=True)
api = HfApi()
new_photos_list = []
photo_limit = 10
uploaded_count = 0
logging.info(f"Uploading new photos for product {product_to_edit['name']}...")
for photo in photos_files:
if uploaded_count >= photo_limit:
logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.")
flash(lang['flash_photo_limit'].format(photo_limit), "warning")
break
if photo and photo.filename:
try:
ext = os.path.splitext(photo.filename)[1].lower()
if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
logging.warning(f"Skipping non-image file upload during edit: {photo.filename}")
flash(lang['flash_photo_skipped_non_image'].format(photo.filename), "warning")
continue
safe_name = secure_filename(product_to_edit['name'].replace(' ', '_'))[:50]
photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
temp_path = os.path.join(uploads_dir, photo_filename)
photo.save(temp_path)
logging.info(f"Uploading new photo {photo_filename} to HF...")
api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}",
repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
commit_message=f"Update photo for product {product_to_edit['name']}")
new_photos_list.append(photo_filename)
logging.info(f"New photo {photo_filename} uploaded successfully.")
os.remove(temp_path)
uploaded_count += 1
except Exception as e:
logging.error(f"Error uploading new photo {photo.filename}: {e}", exc_info=True)
flash(lang['flash_photo_upload_error'].format(photo.filename), 'error')
if os.path.exists(temp_path):
try: os.remove(temp_path)
except OSError: pass
elif photo and not photo.filename:
logging.warning("Received an empty photo file object when editing product.")
try:
if os.path.exists(uploads_dir) and os.path.isdir(uploads_dir) and not os.listdir(uploads_dir):
os.rmdir(uploads_dir)
except OSError as e:
logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}")
if new_photos_list:
logging.info(f"New photo list for product {product_to_edit['name']} generated.")
old_photos = product_to_edit.get('photos', [])
if old_photos:
logging.info(f"Attempting to delete old photos: {old_photos}")
try:
api.delete_files(
repo_id=REPO_ID,
paths_in_repo=[f"photos/{p}" for p in old_photos],
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Delete old photos for product {product_to_edit['name']}"
)
logging.info(f"Old photos for product {product_to_edit['name']} deleted from HF.")
except Exception as e:
logging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True)
flash(lang['flash_old_photos_delete_error'], "warning")
product_to_edit['photos'] = new_photos_list
flash(lang['flash_photos_updated'], "success")
elif uploaded_count == 0 and any(f.filename for f in photos_files):
flash(lang['flash_new_photos_upload_failed'], "error")
elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
flash(lang['flash_no_hf_token_photos_not_updated'], "warning")
products[index] = product_to_edit
data['products'] = products
save_data(data)
logging.info(f"Product '{original_name}' (index {index}) updated to '{product_to_edit['name']}'.")
flash(lang['flash_product_updated'].format(product_to_edit['name']), 'success')
elif action == 'delete_product':
index_str = request.form.get('index')
if index_str is None:
flash(lang['flash_delete_index_missing'], 'error')
return redirect(url_for('admin'))
try:
index = int(index_str)
if not (0 <= index < len(products)): raise IndexError("Product index out of range")
deleted_product = products.pop(index)
product_name = deleted_product.get('name', 'N/A')
photos_to_delete = deleted_product.get('photos', [])
if photos_to_delete and HF_TOKEN_WRITE:
logging.info(f"Attempting to delete photos for product '{product_name}' from HF: {photos_to_delete}")
try:
api = HfApi()
api.delete_files(
repo_id=REPO_ID,
paths_in_repo=[f"photos/{p}" for p in photos_to_delete],
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Delete photos for deleted product {product_name}"
)
logging.info(f"Photos for product '{product_name}' deleted from HF.")
except Exception as e:
logging.error(f"Error deleting photos {photos_to_delete} for product '{product_name}' from HF: {e}", exc_info=True)
flash(lang['flash_photo_delete_error_deleted_local'].format(product_name), "warning")
elif photos_to_delete and not HF_TOKEN_WRITE:
logging.warning(f"HF_TOKEN (write) not set. Cannot delete photos {photos_to_delete} for deleted product '{product_name}'.")
flash(lang['flash_photo_delete_error_deleted_local'].format(product_name), "warning")
data['products'] = products
save_data(data)
logging.info(f"Product '{product_name}' (original index {index}) deleted.")
flash(lang['flash_product_deleted'].format(product_name), 'success')
except (ValueError, IndexError):
flash(lang['flash_delete_index_invalid'].format(index_str), 'error')
logging.error(f"Invalid index '{index_str}' for deletion. Product list length: {len(products)}")
else:
logging.warning(f"Received unknown admin action: {action}")
flash(lang['flash_unknown_action'].format(action), 'warning')
return redirect(url_for('admin', lang=current_lang))
except Exception as e:
logging.error(f"Произошла внутренняя ошибка при выполнении действия '{action}': {e}", exc_info=True)
flash(lang['flash_internal_error'].format(action), 'error')
return redirect(url_for('admin', lang=current_lang))
current_data = load_data()
display_products = sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower())
display_categories = sorted(current_data.get('categories', []))
resp = make_response(render_template_string(
ADMIN_TEMPLATE,
products=display_products,
categories=display_categories,
repo_id=REPO_ID,
currency_code=CURRENCY_CODE,
lang=lang,
current_lang=current_lang
))
resp.set_cookie('admin_lang', current_lang)
return resp
@app.route('/force_upload', methods=['POST'])
def force_upload():
current_lang, lang = get_admin_lang()
logging.info("Forcing upload to Hugging Face...")
try:
upload_db_to_hf()
flash(lang['flash_upload_success'], 'success')
except Exception as e:
logging.error(f"Error during forced upload: {e}", exc_info=True)
flash(lang['flash_upload_error'].format(e), 'error')
return redirect(url_for('admin', lang=current_lang))
@app.route('/force_download', methods=['POST'])
def force_download():
current_lang, lang = get_admin_lang()
logging.info("Forcing download from Hugging Face...")
try:
if download_db_from_hf():
flash(lang['flash_download_success'], 'success')
load_data()
else:
flash(lang['flash_download_error_hf'], 'error')
except Exception as e:
logging.error(f"Error during forced download: {e}", exc_info=True)
flash(lang['flash_download_error_general'].format(e), 'error')
return redirect(url_for('admin', lang=current_lang))
if __name__ == '__main__':
logging.info("Application starting up. Performing initial data load/download...")
download_db_from_hf()
load_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 will NOT run (HF_TOKEN for writing not set).")
port = int(os.environ.get('PORT', 7860))
logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}")
app.run(debug=False, host='0.0.0.0', port=port)