Delete app.py
Browse files
app.py
DELETED
|
@@ -1,641 +0,0 @@
|
|
| 1 |
-
from flask import Flask, render_template_string, request, redirect, url_for, flash, send_file
|
| 2 |
-
import json
|
| 3 |
-
import os
|
| 4 |
-
import logging
|
| 5 |
-
import threading
|
| 6 |
-
import time
|
| 7 |
-
from datetime import datetime
|
| 8 |
-
from huggingface_hub import HfApi, hf_hub_download
|
| 9 |
-
from huggingface_hub.utils import RepositoryNotFoundError
|
| 10 |
-
from werkzeug.utils import secure_filename
|
| 11 |
-
import uuid
|
| 12 |
-
import random
|
| 13 |
-
|
| 14 |
-
app = Flask(__name__)
|
| 15 |
-
app.secret_key = os.getenv("FLASK_SECRET_KEY", "zzirix_super_secret_key")
|
| 16 |
-
DATA_FILE = 'data_zzirix.json'
|
| 17 |
-
REPO_ID = "Kgshop/testxet"
|
| 18 |
-
MEDIA_REPO_ID = "Kgshop/clients"
|
| 19 |
-
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
|
| 20 |
-
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
|
| 21 |
-
UPLOAD_FOLDER = 'uploads'
|
| 22 |
-
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 23 |
-
logging.basicConfig(level=logging.INFO)
|
| 24 |
-
|
| 25 |
-
LOGO_URL = "https://huggingface.co/spaces/Kgshop/Zzirixadm/resolve/main/Picsart_25-03-20_15-38-36-600.jpg"
|
| 26 |
-
|
| 27 |
-
def initialize_data_structure(data):
|
| 28 |
-
if not isinstance(data, dict):
|
| 29 |
-
data = {'categories': [], 'products': []}
|
| 30 |
-
|
| 31 |
-
data.setdefault('categories', [])
|
| 32 |
-
data.setdefault('products', [])
|
| 33 |
-
data.setdefault('orders', {})
|
| 34 |
-
|
| 35 |
-
for product in data['products']:
|
| 36 |
-
if 'id' not in product or not product['id']:
|
| 37 |
-
product['id'] = str(uuid.uuid4())
|
| 38 |
-
|
| 39 |
-
product.setdefault('name', 'Без названия')
|
| 40 |
-
product.setdefault('description', '')
|
| 41 |
-
product.setdefault('category', 'Без категории')
|
| 42 |
-
product.setdefault('price', 0.0)
|
| 43 |
-
product.setdefault('colors', [])
|
| 44 |
-
product.setdefault('models', [])
|
| 45 |
-
|
| 46 |
-
if 'photos' in product and 'media' not in product:
|
| 47 |
-
product['media'] = [{'type': 'photo', 'filename': photo} for photo in product['photos']]
|
| 48 |
-
del product['photos']
|
| 49 |
-
else:
|
| 50 |
-
product.setdefault('media', [])
|
| 51 |
-
|
| 52 |
-
return data
|
| 53 |
-
|
| 54 |
-
def load_data():
|
| 55 |
-
try:
|
| 56 |
-
if not os.path.exists(DATA_FILE):
|
| 57 |
-
download_db_from_hf()
|
| 58 |
-
if os.path.exists(DATA_FILE) and os.path.getsize(DATA_FILE) > 0:
|
| 59 |
-
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 60 |
-
data = json.load(file)
|
| 61 |
-
else:
|
| 62 |
-
data = {'categories': [], 'products': []}
|
| 63 |
-
return initialize_data_structure(data)
|
| 64 |
-
except (json.JSONDecodeError, FileNotFoundError, RepositoryNotFoundError):
|
| 65 |
-
logging.warning(f"Ошибка при чтении {DATA_FILE} или из репозитория. Создается пустая структура.")
|
| 66 |
-
return initialize_data_structure({})
|
| 67 |
-
except Exception as e:
|
| 68 |
-
logging.error(f"Неизвестная ошибка при загрузке данных: {e}")
|
| 69 |
-
return initialize_data_structure({})
|
| 70 |
-
|
| 71 |
-
def save_data(data):
|
| 72 |
-
try:
|
| 73 |
-
temp_file = DATA_FILE + '.tmp'
|
| 74 |
-
with open(temp_file, 'w', encoding='utf-8') as file:
|
| 75 |
-
json.dump(data, file, ensure_ascii=False, indent=4)
|
| 76 |
-
os.replace(temp_file, DATA_FILE)
|
| 77 |
-
upload_db_to_hf()
|
| 78 |
-
logging.info("Данные сохранены и выгружены в HF")
|
| 79 |
-
except Exception as e:
|
| 80 |
-
logging.error(f"Ошибка при сохранении данных: {e}")
|
| 81 |
-
if os.path.exists(temp_file):
|
| 82 |
-
os.remove(temp_file)
|
| 83 |
-
raise
|
| 84 |
-
|
| 85 |
-
def upload_db_to_hf():
|
| 86 |
-
if not HF_TOKEN_WRITE:
|
| 87 |
-
logging.warning("HF_TOKEN_WRITE не установлен. Пропуск выгрузки DB.")
|
| 88 |
-
return
|
| 89 |
-
try:
|
| 90 |
-
api = HfApi()
|
| 91 |
-
api.upload_file(
|
| 92 |
-
path_or_fileobj=DATA_FILE,
|
| 93 |
-
path_in_repo=DATA_FILE,
|
| 94 |
-
repo_id=REPO_ID,
|
| 95 |
-
repo_type="dataset",
|
| 96 |
-
token=HF_TOKEN_WRITE,
|
| 97 |
-
commit_message=f"Резервная копия {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 98 |
-
)
|
| 99 |
-
logging.info("База данных выгружена в Hugging Face")
|
| 100 |
-
except Exception as e:
|
| 101 |
-
logging.error(f"Ошибка при выгрузке базы данных: {e}")
|
| 102 |
-
|
| 103 |
-
def download_db_from_hf():
|
| 104 |
-
if not HF_TOKEN_READ:
|
| 105 |
-
logging.warning("HF_TOKEN_READ не установлен. Пропуск загрузки.")
|
| 106 |
-
if not os.path.exists(DATA_FILE):
|
| 107 |
-
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 108 |
-
json.dump(initialize_data_structure({}), f)
|
| 109 |
-
return
|
| 110 |
-
try:
|
| 111 |
-
hf_hub_download(
|
| 112 |
-
repo_id=REPO_ID,
|
| 113 |
-
filename=DATA_FILE,
|
| 114 |
-
repo_type="dataset",
|
| 115 |
-
token=HF_TOKEN_READ,
|
| 116 |
-
local_dir=".",
|
| 117 |
-
local_dir_use_symlinks=False,
|
| 118 |
-
force_download=True
|
| 119 |
-
)
|
| 120 |
-
logging.info("База данных загружена с Hugging Face")
|
| 121 |
-
except Exception as e:
|
| 122 |
-
logging.error(f"Ошибка при загрузке базы данных: {e}")
|
| 123 |
-
if not os.path.exists(DATA_FILE):
|
| 124 |
-
logging.info("Создается пустой файл базы данных, так как загрузка не удалась.")
|
| 125 |
-
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 126 |
-
json.dump(initialize_data_structure({}), f)
|
| 127 |
-
|
| 128 |
-
def periodic_backup():
|
| 129 |
-
while True:
|
| 130 |
-
time.sleep(1800)
|
| 131 |
-
logging.info("Запуск периодического резервного копирования.")
|
| 132 |
-
try:
|
| 133 |
-
upload_db_to_hf()
|
| 134 |
-
except Exception as e:
|
| 135 |
-
logging.error(f"Ошибка во время периодического резервного копирования: {e}")
|
| 136 |
-
|
| 137 |
-
@app.route('/')
|
| 138 |
-
def catalog():
|
| 139 |
-
data = load_data()
|
| 140 |
-
products = data.get('products', [])
|
| 141 |
-
categories = sorted(list(set(p.get('category', 'Без категории') for p in products)))
|
| 142 |
-
|
| 143 |
-
catalog_html = '''
|
| 144 |
-
<!DOCTYPE html>
|
| 145 |
-
<html lang="ru">
|
| 146 |
-
<head>
|
| 147 |
-
<meta charset="UTF-8">
|
| 148 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 149 |
-
<title>ZZIRIX - сотовые аксессуары оптом </title>
|
| 150 |
-
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
|
| 151 |
-
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
|
| 152 |
-
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
|
| 153 |
-
<style>
|
| 154 |
-
:root {
|
| 155 |
-
--primary-color: #3B82F6; --primary-dark-color: #2563eb; --accent-color: #10b981;
|
| 156 |
-
--accent-dark-color: #059669; --danger-color: #ef4444; --danger-dark-color: #dc2626;
|
| 157 |
-
--background-light: linear-gradient(135deg, #f8f9fa, #e9ecef); --background-dark: linear-gradient(135deg, #1a202c, #2d3748);
|
| 158 |
-
--card-background-light: #ffffff; --card-background-dark: #2d3748; --text-color-light: #2d3748;
|
| 159 |
-
--text-color-dark: #e2e8f0; --secondary-text-color-light: #718096; --secondary-text-color-dark: #a0aec0;
|
| 160 |
-
--border-color-light: #e2e8f0; --border-color-dark: #4a5568; --shadow-light: 0 6px 20px rgba(0, 0, 0, 0.08);
|
| 161 |
-
--shadow-hover-light: 0 10px 30px rgba(0, 0, 0, 0.15); --shadow-dark: 0 6px 20px rgba(0, 0, 0, 0.25);
|
| 162 |
-
--shadow-hover-dark: 0 10px 30px rgba(0, 0, 0, 0.4);
|
| 163 |
-
}
|
| 164 |
-
* { margin: 0; padding: 0; box-sizing: border-box; }
|
| 165 |
-
body { font-family: 'Roboto', sans-serif; background: var(--background-light); color: var(--text-color-light); line-height: 1.6; transition: background 0.3s, color 0.3s; min-height: 100vh; display: flex; flex-direction: column; }
|
| 166 |
-
body.dark-mode { background: var(--background-dark); color: var(--text-color-dark); }
|
| 167 |
-
.container { max-width: 1300px; margin: 0 auto; padding: 20px; flex-grow: 1; }
|
| 168 |
-
.header { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; border-bottom: 1px solid var(--border-color-light); margin-bottom: 20px; }
|
| 169 |
-
body.dark-mode .header { border-bottom-color: var(--border-color-dark); }
|
| 170 |
-
.header-info { display: flex; align-items: center; }
|
| 171 |
-
.header-logo { width: 50px; height: 50px; border-radius: 50%; object-fit: cover; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); transition: transform 0.3s ease, box-shadow 0.3s ease; }
|
| 172 |
-
.header-logo:hover { transform: scale(1.05); box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); }
|
| 173 |
-
.header h1 { font-size: 1.7rem; font-weight: 700; margin-left: 15px; }
|
| 174 |
-
.theme-toggle { background: none; border: none; font-size: 1.6rem; cursor: pointer; color: var(--secondary-text-color-light); transition: color 0.3s ease, transform 0.2s ease; padding: 5px; }
|
| 175 |
-
body.dark-mode .theme-toggle { color: var(--secondary-text-color-dark); }
|
| 176 |
-
.theme-toggle:hover { color: var(--primary-color); transform: rotate(15deg); }
|
| 177 |
-
.filters-container { margin: 20px 0; display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; }
|
| 178 |
-
.search-container { margin: 20px 0; text-align: center; }
|
| 179 |
-
#search-input { width: 90%; max-width: 600px; padding: 12px 18px; font-size: 1rem; border: 1px solid var(--border-color-light); border-radius: 25px; outline: none; box-shadow: inset 0 1px 3px rgba(0,0,0,0.05); transition: all 0.3s ease; background-color: var(--card-background-light); color: var(--text-color-light); }
|
| 180 |
-
body.dark-mode #search-input { border-color: var(--border-color-dark); background-color: var(--card-background-dark); color: var(--text-color-dark); }
|
| 181 |
-
#search-input:focus { border-color: var(--primary-color); box-shadow: 0 0 8px rgba(59, 130, 246, 0.3); }
|
| 182 |
-
.category-filter { padding: 10px 20px; border: 1px solid var(--border-color-light); border-radius: 25px; background-color: var(--card-background-light); cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.95rem; font-weight: 500; color: var(--text-color-light); box-shadow: var(--shadow-light); }
|
| 183 |
-
body.dark-mode .category-filter { border-color: var(--border-color-dark); background-color: var(--card-background-dark); color: var(--text-color-dark); box-shadow: var(--shadow-dark); }
|
| 184 |
-
.category-filter.active, .category-filter:hover { background-color: var(--primary-color); color: white; border-color: var(--primary-color); box-shadow: var(--shadow-hover-light); }
|
| 185 |
-
body.dark-mode .category-filter.active, body.dark-mode .category-filter:hover { background-color: var(--primary-color); border-color: var(--primary-color); box-shadow: var(--shadow-hover-dark); }
|
| 186 |
-
.products-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 20px; padding: 10px; }
|
| 187 |
-
.product { background: var(--card-background-light); border-radius: 18px; padding: 15px; box-shadow: var(--shadow-light); 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; }
|
| 188 |
-
body.dark-mode .product { background: var(--card-background-dark); box-shadow: var(--shadow-dark); }
|
| 189 |
-
.product:hover { transform: translateY(-8px) scale(1.02); box-shadow: var(--shadow-hover-light); }
|
| 190 |
-
body.dark-mode .product:hover { box-shadow: var(--shadow-hover-dark); }
|
| 191 |
-
.product-image { width: 100%; aspect-ratio: 1; background-color: #f0f0f0; border-radius: 12px; overflow: hidden; display: flex; justify-content: center; align-items: center; margin-bottom: 10px; }
|
| 192 |
-
body.dark-mode .product-image { background-color: #3a4250; }
|
| 193 |
-
.product-image img { max-width: 100%; max-height: 100%; object-fit: contain; transition: transform 0.3s ease; }
|
| 194 |
-
.product-image img:hover { transform: scale(1.05); }
|
| 195 |
-
.product h2 { font-size: 1.05rem; font-weight: 600; margin: 5px 0; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-color-light); }
|
| 196 |
-
body.dark-mode .product h2 { color: var(--text-color-dark); }
|
| 197 |
-
.product-price { font-size: 1.15rem; color: var(--danger-color); font-weight: 700; text-align: center; margin: 5px 0 10px; }
|
| 198 |
-
.product-description { font-size: 0.85rem; color: var(--secondary-text-color-light); text-align: center; margin-bottom: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
| 199 |
-
body.dark-mode .product-description { color: var(--secondary-text-color-dark); }
|
| 200 |
-
.product-actions { display: flex; flex-direction: column; gap: 8px; margin-top: auto; }
|
| 201 |
-
.product-button { display: block; width: 100%; padding: 10px; border: none; border-radius: 10px; background-color: var(--primary-color); 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; }
|
| 202 |
-
.product-button:hover { background-color: var(--primary-dark-color); box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4); }
|
| 203 |
-
.add-to-cart { background-color: var(--accent-color); }
|
| 204 |
-
.add-to-cart:hover { background-color: var(--accent-dark-color); box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4); }
|
| 205 |
-
#cart-button { position: fixed; bottom: 25px; right: 25px; background-color: var(--danger-color); color: white; border: none; border-radius: 50%; width: 55px; height: 55px; font-size: 1.3rem; cursor: pointer; display: flex; box-shadow: 0 5px 20px rgba(239, 68, 68, 0.4); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1000; align-items: center; justify-content: center; }
|
| 206 |
-
#cart-button:hover { background-color: var(--danger-dark-color); transform: translateY(-3px) scale(1.05); box-shadow: 0 8px 25px rgba(239, 68, 68, 0.6); }
|
| 207 |
-
.cart-count { position: absolute; top: -5px; right: -5px; background-color: var(--accent-color); color: white; border-radius: 50%; padding: 3px 7px; font-size: 0.75rem; min-width: 20px; text-align: center; font-weight: 600; }
|
| 208 |
-
.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(8px); overflow-y: auto; padding: 20px; }
|
| 209 |
-
.modal-content { background: var(--card-background-light); margin: 50px auto; padding: 30px; border-radius: 20px; width: 95%; max-width: 750px; box-shadow: 0 15px 40px rgba(0,0,0,0.3); animation: fadeInScale 0.3s ease-out; max-height: calc(100vh - 100px); overflow-y: auto; -webkit-overflow-scrolling: touch; position: relative; }
|
| 210 |
-
body.dark-mode .modal-content { background: var(--card-background-dark); color: var(--text-color-dark); box-shadow: 0 15px 40px rgba(0,0,0,0.5); }
|
| 211 |
-
@keyframes fadeInScale { from { opacity: 0; transform: translateY(-30px) scale(0.95); } to { opacity: 1; transform: translateY(0) scale(1); } }
|
| 212 |
-
.close { position: absolute; top: 15px; right: 20px; font-size: 1.8rem; color: var(--secondary-text-color-light); cursor: pointer; transition: color 0.3s, transform 0.2s; }
|
| 213 |
-
.close:hover { color: var(--danger-color); transform: rotate(90deg); }
|
| 214 |
-
body.dark-mode .close { color: var(--secondary-text-color-dark); }
|
| 215 |
-
body.dark-mode .close:hover { color: var(--danger-color); }
|
| 216 |
-
.modal h2 { font-size: 1.6rem; font-weight: 700; margin-bottom: 20px; text-align: center; }
|
| 217 |
-
.cart-item { display: flex; align-items: center; padding: 15px 0; border-bottom: 1px solid var(--border-color-light); }
|
| 218 |
-
body.dark-mode .cart-item { border-bottom-color: var(--border-color-dark); }
|
| 219 |
-
.cart-item:last-child { border-bottom: none; }
|
| 220 |
-
.cart-item img { width: 60px; height: 60px; object-fit: contain; border-radius: 10px; margin-right: 15px; background-color: #f0f0f0; }
|
| 221 |
-
body.dark-mode .cart-item img { background-color: #3a4250; }
|
| 222 |
-
.cart-item-details { flex-grow: 1; }
|
| 223 |
-
.cart-item-details strong { font-size: 1.1rem; font-weight: 600; }
|
| 224 |
-
.cart-item-details p { font-size: 0.9rem; color: var(--secondary-text-color-light); }
|
| 225 |
-
body.dark-mode .cart-item-details p { color: var(--secondary-text-color-dark); }
|
| 226 |
-
.cart-item-total { font-size: 1rem; font-weight: 700; color: var(--danger-color); }
|
| 227 |
-
.quantity-input, .color-select, .model-select { width: 100%; padding: 10px; border: 1px solid var(--border-color-light); border-radius: 8px; font-size: 1rem; margin: 8px 0; background-color: var(--card-background-light); color: var(--text-color-light); }
|
| 228 |
-
body.dark-mode .quantity-input, body.dark-mode .color-select, body.dark-mode .model-select { border-color: var(--border-color-dark); background-color: var(--card-background-dark); color: var(--text-color-dark); }
|
| 229 |
-
.modal-buttons { margin-top: 20px; display: flex; justify-content: flex-end; gap: 10px; }
|
| 230 |
-
.modal-buttons .product-button { width: auto; padding: 10px 20px; }
|
| 231 |
-
.clear-cart { background-color: var(--danger-color); }
|
| 232 |
-
.clear-cart:hover { background-color: var(--danger-dark-color); box-shadow: 0 4px 15px rgba(239, 68, 68, 0.4); }
|
| 233 |
-
.order-button { background-color: var(--accent-color); }
|
| 234 |
-
.order-button:hover { background-color: var(--accent-dark-color); box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4); }
|
| 235 |
-
.swiper-container { max-width: 400px; margin: 0 auto 20px; border-radius: 15px; overflow: hidden; box-shadow: 0 5px 20px rgba(0,0,0,0.1); }
|
| 236 |
-
body.dark-mode .swiper-container { box-shadow: 0 5px 20px rgba(0,0,0,0.3); }
|
| 237 |
-
.swiper-slide { background-color: #f0f0f0; display: flex; justify-content: center; align-items: center; min-height: 250px; }
|
| 238 |
-
body.dark-mode .swiper-slide { background-color: #3a4250; }
|
| 239 |
-
.swiper-slide img { max-width: 100%; max-height: 300px; object-fit: contain; }
|
| 240 |
-
.swiper-button-next, .swiper-button-prev { color: var(--primary-color) !important; background-color: rgba(255,255,255,0.8); border-radius: 50%; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; transition: background-color 0.3s; }
|
| 241 |
-
.swiper-button-next:hover, .swiper-button-prev:hover { background-color: rgba(255,255,255,1); }
|
| 242 |
-
body.dark-mode .swiper-button-next, body.dark-mode .swiper-button-prev { background-color: rgba(45, 55, 72, 0.8); }
|
| 243 |
-
body.dark-mode .swiper-button-next:hover, body.dark-mode .swiper-button-prev:hover { background-color: rgba(45, 55, 72, 1); }
|
| 244 |
-
.swiper-pagination-bullet { background-color: var(--primary-color) !important; }
|
| 245 |
-
@media (max-width: 768px) {
|
| 246 |
-
.header h1 { font-size: 1.4rem; } .category-filter { font-size: 0.85rem; padding: 8px 15px; }
|
| 247 |
-
.products-grid { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; }
|
| 248 |
-
.product h2 { font-size: 0.95rem; } .product-price { font-size: 1.05rem; } .product-description { font-size: 0.75rem; }
|
| 249 |
-
.product-button { font-size: 0.85rem; padding: 8px; }
|
| 250 |
-
#cart-button { width: 45px; height: 45px; font-size: 1.1rem; bottom: 15px; right: 15px; }
|
| 251 |
-
.modal-content { margin: 20px auto; padding: 20px; max-height: calc(100vh - 40px); }
|
| 252 |
-
.close { font-size: 1.5rem; top: 10px; right: 15px; } .modal h2 { font-size: 1.4rem; } .cart-item img { width: 45px; height: 45px; }
|
| 253 |
-
}
|
| 254 |
-
</style>
|
| 255 |
-
</head>
|
| 256 |
-
<body>
|
| 257 |
-
<div class="container">
|
| 258 |
-
<div class="header">
|
| 259 |
-
<div class="header-info">
|
| 260 |
-
<img src="''' + LOGO_URL + '''" alt="Logo" class="header-logo">
|
| 261 |
-
<h1>Каталог ZZIRIX</h1>
|
| 262 |
-
</div>
|
| 263 |
-
<button class="theme-toggle" onclick="toggleTheme()"><i class="fas fa-moon"></i></button>
|
| 264 |
-
</div>
|
| 265 |
-
<div class="filters-container">
|
| 266 |
-
<button class="category-filter active" data-category="all">Все категории</button>
|
| 267 |
-
{% for category in categories %}<button class="category-filter" data-category="{{ category }}">{{ category }}</button>{% endfor %}
|
| 268 |
-
</div>
|
| 269 |
-
<div class="search-container"><input type="text" id="search-input" placeholder="Поиск товаров..."></div>
|
| 270 |
-
<div class="products-grid" id="products-grid">
|
| 271 |
-
{% for product in products %}
|
| 272 |
-
<div class="product" data-id="{{ product.id }}" data-name="{{ product.name|lower }}" data-description="{{ product.description|lower }}" data-category="{{ product.get('category', 'Без категории')|lower }}">
|
| 273 |
-
<div class="product-image">
|
| 274 |
-
{% if product.media and product.media|length > 0 %}
|
| 275 |
-
<img src="https://huggingface.co/datasets/''' + MEDIA_REPO_ID + '''/resolve/main/photos/{{ product.media[0].filename }}" alt="{{ product.name }}" loading="lazy">
|
| 276 |
-
{% else %}
|
| 277 |
-
<img src="https://via.placeholder.com/200x200?text=No+Image" alt="Нет изображения" loading="lazy">
|
| 278 |
-
{% endif %}
|
| 279 |
-
</div>
|
| 280 |
-
<h2>{{ product.name }}</h2>
|
| 281 |
-
<div class="product-price">{{ "%.2f"|format(product.price|float) }} с</div>
|
| 282 |
-
<p class="product-description">{{ product.description[:50] }}{% if product.description|length > 50 %}...{% endif %}</p>
|
| 283 |
-
<div class="product-actions">
|
| 284 |
-
<button class="product-button" onclick="openModal('{{ product.id }}')">Подробнее</button>
|
| 285 |
-
<button class="product-button add-to-cart" onclick="openQuantityModal('{{ product.id }}')">В корзину</button>
|
| 286 |
-
</div>
|
| 287 |
-
</div>
|
| 288 |
-
{% endfor %}
|
| 289 |
-
</div>
|
| 290 |
-
</div>
|
| 291 |
-
<div id="productModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('productModal')">×</span><div id="modalContent"></div></div></div>
|
| 292 |
-
<div id="quantityModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('quantityModal')">×</span><h2>Укажите количество, цвет и модель</h2><input type="number" id="quantityInput" class="quantity-input" min="1" value="1"><select id="colorSelect" class="color-select"></select><select id="modelSelect" class="model-select"></select><div class="modal-buttons"><button class="product-button order-button" onclick="confirmAddToCart()">Добавить</button></div></div></div>
|
| 293 |
-
<div id="cartModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('cartModal')">×</span><h2>Корзина</h2><div id="cartContent"></div><div style="margin-top: 20px; text-align: right;"><strong style="font-size: 1.2rem;">Итого: <span id="cartTotal">0</span> с</strong><div class="modal-buttons"><button class="product-button clear-cart" onclick="clearCart()">Очистить</button><button class="product-button order-button" onclick="orderViaWhatsApp()">Заказать</button></div></div></div></div>
|
| 294 |
-
<button id="cart-button" onclick="openCartModal()" style="display: none;"><i class="fas fa-shopping-cart"></i><span id="cart-count" class="cart-count">0</span></button>
|
| 295 |
-
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
|
| 296 |
-
<script>
|
| 297 |
-
const products = {{ products|tojson }};
|
| 298 |
-
const productsById = products.reduce((acc, p) => { acc[p.id] = p; return acc; }, {});
|
| 299 |
-
let selectedProductId = null;
|
| 300 |
-
function toggleTheme() { document.body.classList.toggle('dark-mode'); const icon = document.querySelector('.theme-toggle i'); icon.classList.toggle('fa-moon'); icon.classList.toggle('fa-sun'); localStorage.setItem('theme', document.body.classList.contains('dark-mode') ? 'dark' : 'light'); }
|
| 301 |
-
if (localStorage.getItem('theme') === 'dark') { document.body.classList.add('dark-mode'); document.querySelector('.theme-toggle i').classList.replace('fa-moon', 'fa-sun'); }
|
| 302 |
-
function openModal(productId) {
|
| 303 |
-
fetch('/product_details/' + productId).then(response => response.text()).then(data => {
|
| 304 |
-
document.getElementById('modalContent').innerHTML = data;
|
| 305 |
-
initializeSwiper();
|
| 306 |
-
document.getElementById('productModal').style.display = "block";
|
| 307 |
-
}).catch(error => console.error('Ошибка:', error));
|
| 308 |
-
}
|
| 309 |
-
function closeModal(modalId) { document.getElementById(modalId).style.display = "none"; }
|
| 310 |
-
function initializeSwiper() { new Swiper('.swiper-container', { slidesPerView: 1, spaceBetween: 20, loop: true, grabCursor: true, pagination: { el: '.swiper-pagination', clickable: true }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, zoom: { maxRatio: 3 } }); }
|
| 311 |
-
function openQuantityModal(productId) {
|
| 312 |
-
selectedProductId = productId;
|
| 313 |
-
const product = productsById[productId];
|
| 314 |
-
const colorSelect = document.getElementById('colorSelect'); colorSelect.innerHTML = '';
|
| 315 |
-
if (product.colors && product.colors.length > 0) { product.colors.forEach(color => { const option = document.createElement('option'); option.value = color; option.text = color; colorSelect.appendChild(option); }); } else { const option = document.createElement('option'); option.value = 'Не указан'; option.text = 'Цвет не указан'; colorSelect.appendChild(option); }
|
| 316 |
-
const modelSelect = document.getElementById('modelSelect'); modelSelect.innerHTML = '';
|
| 317 |
-
if (product.models && product.models.length > 0) { product.models.forEach(model => { const option = document.createElement('option'); option.value = model; option.text = model; modelSelect.appendChild(option); }); } else { const option = document.createElement('option'); option.value = 'Не указана'; option.text = 'Модель не указана'; modelSelect.appendChild(option); }
|
| 318 |
-
document.getElementById('quantityModal').style.display = 'block'; document.getElementById('quantityInput').value = 1;
|
| 319 |
-
}
|
| 320 |
-
function confirmAddToCart() {
|
| 321 |
-
if (selectedProductId === null) return;
|
| 322 |
-
const quantity = parseInt(document.getElementById('quantityInput').value) || 1;
|
| 323 |
-
const color = document.getElementById('colorSelect').value; const model = document.getElementById('modelSelect').value;
|
| 324 |
-
if (quantity <= 0) { alert("Укажите количество больше 0."); return; }
|
| 325 |
-
let cart = JSON.parse(localStorage.getItem('cart') || '[]'); const product = productsById[selectedProductId];
|
| 326 |
-
const cartItemId = `${product.id}-${color}-${model}`; const existingItem = cart.find(item => item.cartId === cartItemId);
|
| 327 |
-
if (existingItem) { existingItem.quantity += quantity; } else { cart.push({ cartId: cartItemId, id: product.id, name: product.name, price: product.price, media: product.media, quantity: quantity, color: color, model: model }); }
|
| 328 |
-
localStorage.setItem('cart', JSON.stringify(cart)); closeModal('quantityModal'); updateCartButton();
|
| 329 |
-
}
|
| 330 |
-
function updateCartButton() { const cart = JSON.parse(localStorage.getItem('cart') || '[]'); const cartCount = cart.reduce((sum, item) => sum + item.quantity, 0); document.getElementById('cart-count').textContent = cartCount; document.getElementById('cart-button').style.display = cartCount > 0 ? 'flex' : 'none'; }
|
| 331 |
-
function openCartModal() {
|
| 332 |
-
const cart = JSON.parse(localStorage.getItem('cart') || '[]'); const cartContent = document.getElementById('cartContent'); let total = 0;
|
| 333 |
-
cartContent.innerHTML = cart.length === 0 ? '<p style="text-align: center;">Корзина пуста</p>' : cart.map(item => {
|
| 334 |
-
const itemTotal = item.price * item.quantity; total += itemTotal;
|
| 335 |
-
const photoSrc = item.media && item.media.length > 0 ? `https://huggingface.co/datasets/''' + MEDIA_REPO_ID + '''/resolve/main/photos/${item.media[0].filename}` : 'https://via.placeholder.com/60x60?text=No+Image';
|
| 336 |
-
return `<div class="cart-item"><img src="${photoSrc}" alt="${item.name}"><div class="cart-item-details"><strong>${item.name}</strong><p>${item.price} с × ${item.quantity} (Цвет: ${item.color}, Модель: ${item.model})</p></div><span class="cart-item-total">${itemTotal.toFixed(2)} с</span></div>`;
|
| 337 |
-
}).join('');
|
| 338 |
-
document.getElementById('cartTotal').textContent = total.toFixed(2); document.getElementById('cartModal').style.display = 'block';
|
| 339 |
-
}
|
| 340 |
-
function orderViaWhatsApp() {
|
| 341 |
-
const cart = JSON.parse(localStorage.getItem('cart') || '[]'); if (cart.length === 0) { alert("Корзина пуста!"); return; }
|
| 342 |
-
let total = 0; let orderText = "Здравствуйте, меня интересует заказ:%0A%0A";
|
| 343 |
-
cart.forEach((item, index) => { const itemTotal = item.price * item.quantity; total += itemTotal; orderText += `${index + 1}. ${item.name}%0AКоличество: ${item.quantity}%0AЦена: ${item.price} с%0AЦвет: ${item.color}%0AМодель: ${item.model}%0A--%0A`; });
|
| 344 |
-
orderText += `*Итого к оплате: ${total.toFixed(2)} с*%0A%0AЖду подтверждения заказа.`;
|
| 345 |
-
window.open(`https://api.whatsapp.com/send?phone=996705665777&text=${orderText}`, '_blank');
|
| 346 |
-
}
|
| 347 |
-
function clearCart() { localStorage.removeItem('cart'); openCartModal(); updateCartButton(); }
|
| 348 |
-
window.onclick = function(event) { if (event.target.classList.contains('modal')) { event.target.style.display = "none"; } }
|
| 349 |
-
document.getElementById('search-input').addEventListener('input', filterProducts);
|
| 350 |
-
document.querySelectorAll('.category-filter').forEach(filter => { filter.addEventListener('click', function() { document.querySelectorAll('.category-filter').forEach(f => f.classList.remove('active')); this.classList.add('active'); filterProducts(); }); });
|
| 351 |
-
function filterProducts() {
|
| 352 |
-
const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();
|
| 353 |
-
const activeCategory = document.querySelector('.category-filter.active').dataset.category.toLowerCase();
|
| 354 |
-
document.querySelectorAll('.product').forEach(product => {
|
| 355 |
-
const name = product.dataset.name; const description = product.dataset.description; const category = product.dataset.category;
|
| 356 |
-
const matchesSearch = name.includes(searchTerm) || description.includes(searchTerm);
|
| 357 |
-
const matchesCategory = activeCategory === 'all' || category === activeCategory;
|
| 358 |
-
product.style.display = matchesSearch && matchesCategory ? 'flex' : 'none';
|
| 359 |
-
});
|
| 360 |
-
}
|
| 361 |
-
updateCartButton();
|
| 362 |
-
</script>
|
| 363 |
-
</body>
|
| 364 |
-
</html>
|
| 365 |
-
'''
|
| 366 |
-
return render_template_string(catalog_html, products=reversed(products), categories=categories)
|
| 367 |
-
|
| 368 |
-
@app.route('/product_details/<product_id>')
|
| 369 |
-
def product_detail(product_id):
|
| 370 |
-
data = load_data()
|
| 371 |
-
product = next((p for p in data.get('products', []) if p.get('id') == product_id), None)
|
| 372 |
-
if not product:
|
| 373 |
-
return "Продукт не найден", 404
|
| 374 |
-
|
| 375 |
-
detail_html = '''
|
| 376 |
-
<div class="product-detail-modal" style="padding: 20px;">
|
| 377 |
-
<h2 style="font-size: 1.8rem; font-weight: 700; margin-bottom: 25px; text-align: center;">{{ product.name }}</h2>
|
| 378 |
-
<div class="swiper-container" style="max-width: 450px; margin: 0 auto 30px;">
|
| 379 |
-
<div class="swiper-wrapper">
|
| 380 |
-
{% if product.media and product.media|length > 0 %}
|
| 381 |
-
{% for media_item in product.media %}
|
| 382 |
-
<div class="swiper-slide swiper-zoom-container" style="background-color: #f0f0f0; display: flex; justify-content: center; align-items: center; border-radius: 10px;">
|
| 383 |
-
<img src="https://huggingface.co/datasets/''' + MEDIA_REPO_ID + '''/resolve/main/photos/{{ media_item.filename }}" alt="{{ product.name }}" style="max-width: 100%; max-height: 300px; object-fit: contain;">
|
| 384 |
-
</div>
|
| 385 |
-
{% endfor %}
|
| 386 |
-
{% else %}
|
| 387 |
-
<div class="swiper-slide" style="background-color: #f0f0f0; display: flex; justify-content: center; align-items: center; border-radius: 10px;">
|
| 388 |
-
<img src="https://via.placeholder.com/300x300?text=No+Image" alt="No Image">
|
| 389 |
-
</div>
|
| 390 |
-
{% endif %}
|
| 391 |
-
</div>
|
| 392 |
-
<div class="swiper-pagination"></div><div class="swiper-button-next"></div><div class="swiper-button-prev"></div>
|
| 393 |
-
</div>
|
| 394 |
-
<p style="margin-bottom: 10px; font-size: 1rem;"><strong>Категория:</strong> <span style="color: var(--primary-color);">{{ product.get('category', 'Без категории') }}</span></p>
|
| 395 |
-
<p style="margin-bottom: 10px; font-size: 1.1rem;"><strong>Цена:</strong> <span style="color: var(--danger-color); font-weight: 700;">{{ "%.2f"|format(product.price|float) }} с</span></p>
|
| 396 |
-
<p style="margin-bottom: 15px; font-size: 1rem;"><strong>Описание:</strong> {{ product.description }}</p>
|
| 397 |
-
<p style="margin-bottom: 10px; font-size: 0.95rem;"><strong>Доступные цвета:</strong> <span style="color: var(--secondary-text-color-light);">{{ product.get('colors', [])|join(', ') or 'Не указаны' }}</span></p>
|
| 398 |
-
<p style="margin-bottom: 10px; font-size: 0.95rem;"><strong>Доступные модели:</strong> <span style="color: var(--secondary-text-color-light);">{{ product.get('models', [])|join(', ') or 'Не указаны' }}</span></p>
|
| 399 |
-
</div>
|
| 400 |
-
'''
|
| 401 |
-
return render_template_string(detail_html, product=product)
|
| 402 |
-
|
| 403 |
-
@app.route('/admin', methods=['GET', 'POST'])
|
| 404 |
-
def admin():
|
| 405 |
-
data = load_data()
|
| 406 |
-
products = data['products']
|
| 407 |
-
categories = data['categories']
|
| 408 |
-
|
| 409 |
-
if request.method == 'POST':
|
| 410 |
-
action = request.form.get('action')
|
| 411 |
-
|
| 412 |
-
if action == 'add_category':
|
| 413 |
-
category_name = request.form.get('category_name', '').strip()
|
| 414 |
-
if category_name and category_name not in categories:
|
| 415 |
-
categories.append(category_name)
|
| 416 |
-
save_data(data)
|
| 417 |
-
flash('Категория добавлена.', 'success')
|
| 418 |
-
else:
|
| 419 |
-
flash('Ошибка: Категория уже существует или не указано название.', 'error')
|
| 420 |
-
|
| 421 |
-
elif action == 'delete_category':
|
| 422 |
-
category_to_delete = request.form.get('category_name')
|
| 423 |
-
if category_to_delete in categories:
|
| 424 |
-
categories.remove(category_to_delete)
|
| 425 |
-
for product in products:
|
| 426 |
-
if product.get('category') == category_to_delete:
|
| 427 |
-
product['category'] = 'Без катего��ии'
|
| 428 |
-
save_data(data)
|
| 429 |
-
flash('Категория удалена.', 'success')
|
| 430 |
-
else:
|
| 431 |
-
flash('Ошибка: Категория не найдена.', 'error')
|
| 432 |
-
|
| 433 |
-
elif action == 'add_product':
|
| 434 |
-
name = request.form.get('name', '').strip()
|
| 435 |
-
price_str = request.form.get('price', '0').strip()
|
| 436 |
-
description = request.form.get('description', '').strip()
|
| 437 |
-
category = request.form.get('category', 'Без категории').strip()
|
| 438 |
-
photos_files = request.files.getlist('photos')
|
| 439 |
-
colors = [c.strip() for c in request.form.getlist('colors') if c.strip()]
|
| 440 |
-
models = [m.strip() for m in request.form.getlist('models') if c.strip()]
|
| 441 |
-
|
| 442 |
-
if not name or not price_str:
|
| 443 |
-
flash('Ошибка: Название и цена являются обязательными полями.', 'error')
|
| 444 |
-
return redirect(url_for('admin'))
|
| 445 |
-
try:
|
| 446 |
-
price = float(price_str.replace(',', '.'))
|
| 447 |
-
except ValueError:
|
| 448 |
-
flash('Ошибка: Неверный формат цены.', 'error')
|
| 449 |
-
return redirect(url_for('admin'))
|
| 450 |
-
|
| 451 |
-
media_list = []
|
| 452 |
-
if photos_files and any(f.filename for f in photos_files):
|
| 453 |
-
api = HfApi()
|
| 454 |
-
for i, photo in enumerate(photos_files[:10]):
|
| 455 |
-
if photo and photo.filename:
|
| 456 |
-
unique_filename = secure_filename(f"{name.replace(' ','_')}_{int(time.time())}_{i}{os.path.splitext(photo.filename)[1]}")
|
| 457 |
-
temp_path = os.path.join(UPLOAD_FOLDER, unique_filename)
|
| 458 |
-
try:
|
| 459 |
-
photo.save(temp_path)
|
| 460 |
-
api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{unique_filename}", repo_id=MEDIA_REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
|
| 461 |
-
media_list.append({'type': 'photo', 'filename': unique_filename})
|
| 462 |
-
except Exception as e:
|
| 463 |
-
logging.error(f"Ошибка при загрузке фото {unique_filename}: {e}")
|
| 464 |
-
finally:
|
| 465 |
-
if os.path.exists(temp_path): os.remove(temp_path)
|
| 466 |
-
|
| 467 |
-
new_product = {'id': str(uuid.uuid4()), 'name': name, 'price': price, 'description': description, 'category': category, 'media': media_list, 'colors': colors, 'models': models}
|
| 468 |
-
products.append(new_product)
|
| 469 |
-
save_data(data)
|
| 470 |
-
flash('Товар успешно добавлен.', 'success')
|
| 471 |
-
|
| 472 |
-
elif action == 'edit_product':
|
| 473 |
-
product_id = request.form.get('product_id')
|
| 474 |
-
product_to_edit = next((p for p in products if p.get('id') == product_id), None)
|
| 475 |
-
if not product_to_edit:
|
| 476 |
-
flash('Ошибка: Товар для редактирования не найден.', 'error')
|
| 477 |
-
return redirect(url_for('admin'))
|
| 478 |
-
|
| 479 |
-
product_to_edit['name'] = request.form.get('name', '').strip()
|
| 480 |
-
product_to_edit['price'] = float(request.form.get('price', '0').replace(',', '.'))
|
| 481 |
-
product_to_edit['description'] = request.form.get('description', '').strip()
|
| 482 |
-
product_to_edit['category'] = request.form.get('category', 'Без категории').strip()
|
| 483 |
-
product_to_edit['colors'] = [c.strip() for c in request.form.getlist('colors') if c.strip()]
|
| 484 |
-
product_to_edit['models'] = [m.strip() for m in request.form.getlist('models') if m.strip()]
|
| 485 |
-
|
| 486 |
-
photos_files = request.files.getlist('photos')
|
| 487 |
-
if photos_files and any(f.filename for f in photos_files):
|
| 488 |
-
new_media_list = []
|
| 489 |
-
api = HfApi()
|
| 490 |
-
for i, photo in enumerate(photos_files[:10]):
|
| 491 |
-
if photo and photo.filename:
|
| 492 |
-
unique_filename = secure_filename(f"{product_to_edit['name'].replace(' ','_')}_{int(time.time())}_{i}{os.path.splitext(photo.filename)[1]}")
|
| 493 |
-
temp_path = os.path.join(UPLOAD_FOLDER, unique_filename)
|
| 494 |
-
try:
|
| 495 |
-
photo.save(temp_path)
|
| 496 |
-
api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{unique_filename}", repo_id=MEDIA_REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
|
| 497 |
-
new_media_list.append({'type': 'photo', 'filename': unique_filename})
|
| 498 |
-
except Exception as e:
|
| 499 |
-
logging.error(f"Ошибка при загрузке нового фото {unique_filename}: {e}")
|
| 500 |
-
finally:
|
| 501 |
-
if os.path.exists(temp_path): os.remove(temp_path)
|
| 502 |
-
if new_media_list: product_to_edit['media'] = new_media_list
|
| 503 |
-
|
| 504 |
-
save_data(data)
|
| 505 |
-
flash('Товар успешно обновлен.', 'success')
|
| 506 |
-
|
| 507 |
-
elif action == 'delete_product':
|
| 508 |
-
product_id = request.form.get('product_id')
|
| 509 |
-
product_to_delete = next((p for p in products if p.get('id') == product_id), None)
|
| 510 |
-
if product_to_delete:
|
| 511 |
-
data['products'] = [p for p in products if p.get('id') != product_id]
|
| 512 |
-
save_data(data)
|
| 513 |
-
flash('Товар удален.', 'success')
|
| 514 |
-
else:
|
| 515 |
-
flash('Ошибка: Товар для удаления не найден.', 'error')
|
| 516 |
-
|
| 517 |
-
return redirect(url_for('admin'))
|
| 518 |
-
|
| 519 |
-
admin_html = '''
|
| 520 |
-
<!DOCTYPE html>
|
| 521 |
-
<html lang="ru">
|
| 522 |
-
<head>
|
| 523 |
-
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Админ-панель ZZIRIX</title>
|
| 524 |
-
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
|
| 525 |
-
<style>
|
| 526 |
-
:root { --primary-color: #3B82F6; --primary-dark-color: #2563eb; --accent-color: #10b981; --accent-dark-color: #059669; --danger-color: #ef4444; --danger-dark-color: #dc2626; --background-light: #f8f9fa; --card-background-light: #ffffff; --text-color-light: #2d3748; --secondary-text-color-light: #718096; --border-color-light: #e2e8f0; --shadow-light: 0 6px 20px rgba(0, 0, 0, 0.08); }
|
| 527 |
-
body { font-family: 'Roboto', sans-serif; background: var(--background-light); color: var(--text-color-light); padding: 20px; line-height: 1.6; }
|
| 528 |
-
.container { max-width: 1200px; margin: 0 auto; }
|
| 529 |
-
.header { display: flex; align-items: center; padding: 15px 0; border-bottom: 1px solid var(--border-color-light); margin-bottom: 20px; }
|
| 530 |
-
.header-logo { width: 50px; height: 50px; border-radius: 50%; object-fit: cover; margin-right: 15px; }
|
| 531 |
-
h1, h2 { font-weight: 700; margin-bottom: 25px; }
|
| 532 |
-
form { background: var(--card-background-light); padding: 30px; border-radius: 20px; box-shadow: var(--shadow-light); margin-bottom: 30px; }
|
| 533 |
-
label { font-weight: 600; margin-top: 18px; margin-bottom: 5px; display: block; }
|
| 534 |
-
input, textarea, select { width: 100%; padding: 12px; margin-bottom: 10px; border: 1px solid var(--border-color-light); border-radius: 10px; font-size: 1rem; }
|
| 535 |
-
input:focus, textarea:focus, select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2); outline: none; }
|
| 536 |
-
button { padding: 12px 22px; border: none; border-radius: 10px; background-color: var(--primary-color); color: white; font-weight: 500; cursor: pointer; transition: all 0.3s; margin-top: 15px; font-size: 1rem; }
|
| 537 |
-
button:hover { background-color: var(--primary-dark-color); transform: translateY(-2px); }
|
| 538 |
-
.delete-button { background-color: var(--danger-color); margin-left: 10px; }
|
| 539 |
-
.delete-button:hover { background-color: var(--danger-dark-color); }
|
| 540 |
-
.product-list, .category-list { display: grid; gap: 20px; }
|
| 541 |
-
.product-item, .category-item { background: var(--card-background-light); padding: 20px; border-radius: 18px; box-shadow: var(--shadow-light); }
|
| 542 |
-
.product-item h3, .category-item h3 { font-size: 1.3rem; font-weight: 600; margin-bottom: 10px; }
|
| 543 |
-
.product-item p { font-size: 0.95rem; margin-bottom: 5px; color: var(--secondary-text-color-light); }
|
| 544 |
-
.edit-form { margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 15px; }
|
| 545 |
-
.dynamic-input-group { display: flex; gap: 10px; margin-bottom: 10px; align-items: center; }
|
| 546 |
-
.dynamic-input-group input { flex-grow: 1; margin-bottom: 0; }
|
| 547 |
-
.remove-input-btn { background-color: #ccc; color: #555; padding: 8px 12px; border-radius: 8px; font-size: 0.8rem; margin-top: 0; flex-shrink: 0; }
|
| 548 |
-
.add-input-btn { background-color: var(--accent-color); width: auto; padding: 10px 18px; margin-bottom: 15px; }
|
| 549 |
-
.product-photos-preview { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px; margin-bottom: 15px; }
|
| 550 |
-
.product-photos-preview img { max-width: 90px; height: auto; border-radius: 8px; border: 1px solid var(--border-color-light); }
|
| 551 |
-
.admin-section-title { margin-top: 40px; margin-bottom: 20px; font-size: 1.8rem; color: var(--primary-color); }
|
| 552 |
-
.flash { padding: 1rem; margin-bottom: 1rem; border-radius: .5rem; font-weight: 500; }
|
| 553 |
-
.flash.success { background-color: #d1fae5; color: #065f46; } .flash.error { background-color: #fee2e2; color: #991b1b; }
|
| 554 |
-
</style>
|
| 555 |
-
</head>
|
| 556 |
-
<body>
|
| 557 |
-
<div class="container">
|
| 558 |
-
<div class="header"><img src="''' + LOGO_URL + '''" alt="Logo" class="header-logo"><h1>Админ-панель</h1></div>
|
| 559 |
-
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
|
| 560 |
-
{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
|
| 561 |
-
{% endif %}{% endwith %}
|
| 562 |
-
<h2 class="admin-section-title">Добавление товара</h2>
|
| 563 |
-
<form method="POST" enctype="multipart/form-data"><input type="hidden" name="action" value="add_product">
|
| 564 |
-
<label>Название:</label><input type="text" name="name" required>
|
| 565 |
-
<label>Цена:</label><input type="number" name="price" step="0.01" required>
|
| 566 |
-
<label>Описание:</label><textarea name="description" rows="4"></textarea>
|
| 567 |
-
<label>Категория:</label><select name="category"><option value="Без категории">Без категории</option>{% for c in categories %}<option value="{{ c }}">{{ c }}</option>{% endfor %}</select>
|
| 568 |
-
<label>Фото (до 10):</label><input type="file" name="photos" accept="image/*" multiple>
|
| 569 |
-
<label>Цвета:</label><div id="color-inputs"><div class="dynamic-input-group"><input type="text" name="colors"><button type="button" class="remove-input-btn" onclick="this.parentNode.remove()">X</button></div></div><button type="button" class="add-input-btn" onclick="addInput('color-inputs', 'colors')">Добавить цвет</button>
|
| 570 |
-
<label>Модели:</label><div id="model-inputs"><div class="dynamic-input-group"><input type="text" name="models"><button type="button" class="remove-input-btn" onclick="this.parentNode.remove()">X</button></div></div><button type="button" class="add-input-btn" onclick="addInput('model-inputs', 'models')">Добавить модель</button>
|
| 571 |
-
<button type="submit">Добавить товар</button>
|
| 572 |
-
</form>
|
| 573 |
-
<h2 class="admin-section-title">Управление категориями</h2>
|
| 574 |
-
<form method="POST"><input type="hidden" name="action" value="add_category"><label>Название категории:</label><input type="text" name="category_name" required><button type="submit">Добавить</button></form>
|
| 575 |
-
<div class="category-list">{% for category in categories %}<div class="category-item"><h3>{{ category }}</h3><form method="POST" style="display: inline;"><input type="hidden" name="action" value="delete_category"><input type="hidden" name="category_name" value="{{ category }}"><button type="submit" class="delete-button">Удалить</button></form></div>{% endfor %}</div>
|
| 576 |
-
<h2 class="admin-section-title">Список товаров</h2><input type="text" id="admin-search-input" placeholder="Поиск..." style="max-width: 400px; margin-bottom: 20px;">
|
| 577 |
-
<div class="product-list" id="admin-product-list">
|
| 578 |
-
{% for product in products|reverse %}
|
| 579 |
-
<div class="product-item" data-name="{{ product.name|lower }}" data-description="{{ product.description|lower }}" data-category="{{ product.get('category', '')|lower }}">
|
| 580 |
-
<h3>{{ product.name }}</h3><p><strong>ID:</strong> {{ product.id }}</p><p><strong>Цена:</strong> {{ "%.2f"|format(product.price|float) }} с</p>
|
| 581 |
-
<div class="product-photos-preview">{% for media in product.media %}<img src="https://huggingface.co/datasets/''' + MEDIA_REPO_ID + '''/resolve/main/photos/{{ media.filename }}?r={{ random.randint(1,1000) }}">{% endfor %}</div>
|
| 582 |
-
<details><summary style="cursor: pointer; color: var(--primary-color);">Редактировать</summary>
|
| 583 |
-
<form method="POST" enctype="multipart/form-data" class="edit-form"><input type="hidden" name="action" value="edit_product"><input type="hidden" name="product_id" value="{{ product.id }}">
|
| 584 |
-
<label>Название:</label><input type="text" name="name" value="{{ product.name }}" required>
|
| 585 |
-
<label>Цена:</label><input type="number" name="price" step="0.01" value="{{ product.price }}" required>
|
| 586 |
-
<label>Описание:</label><textarea name="description" rows="3">{{ product.description }}</textarea>
|
| 587 |
-
<label>Категория:</label><select name="category">{% for c in categories %}<option value="{{ c }}" {% if product.category == c %}selected{% endif %}>{{ c }}</option>{% endfor %}<option value="Без категории" {% if product.category not in categories %}selected{% endif %}>Без категории</option></select>
|
| 588 |
-
<label>Фото (заменят существующие):</label><input type="file" name="photos" multiple>
|
| 589 |
-
<label>Цвета:</label><div id="edit-color-{{product.id}}">{% for color in product.colors %}<div class="dynamic-input-group"><input type="text" name="colors" value="{{color}}"><button type="button" class="remove-input-btn" onclick="this.parentNode.remove()">X</button></div>{% endfor %}</div><button type="button" class="add-input-btn" onclick="addInput('edit-color-{{product.id}}', 'colors')">Добавить</button>
|
| 590 |
-
<label>Модели:</label><div id="edit-model-{{product.id}}">{% for model in product.models %}<div class="dynamic-input-group"><input type="text" name="models" value="{{model}}"><button type="button" class="remove-input-btn" onclick="this.parentNode.remove()">X</button></div>{% endfor %}</div><button type="button" class="add-input-btn" onclick="addInput('edit-model-{{product.id}}', 'models')">Добавить</button>
|
| 591 |
-
<button type="submit">Сохранить</button>
|
| 592 |
-
</form>
|
| 593 |
-
</details>
|
| 594 |
-
<form method="POST" style="margin-top: 10px;"><input type="hidden" name="action" value="delete_product"><input type="hidden" name="product_id" value="{{ product.id }}"><button type="submit" class="delete-button">Удалить</button></form>
|
| 595 |
-
</div>
|
| 596 |
-
{% endfor %}
|
| 597 |
-
</div>
|
| 598 |
-
</div>
|
| 599 |
-
<script>
|
| 600 |
-
function addInput(containerId, name) { const c = document.getElementById(containerId); const n = document.createElement('div'); n.className = 'dynamic-input-group'; n.innerHTML = `<input type="text" name="${name}"><button type="button" class="remove-input-btn" onclick="this.parentNode.remove()">X</button>`; c.appendChild(n); }
|
| 601 |
-
document.getElementById('admin-search-input').addEventListener('input', e => { const s = e.target.value.toLowerCase().trim(); document.querySelectorAll('.product-item').forEach(p => { const d = p.dataset; p.style.display = (d.name.includes(s) || d.description.includes(s) || d.category.includes(s)) ? 'block' : 'none'; }); });
|
| 602 |
-
</script>
|
| 603 |
-
</body>
|
| 604 |
-
</html>
|
| 605 |
-
'''
|
| 606 |
-
return render_template_string(admin_html, products=products, categories=categories, random=random)
|
| 607 |
-
|
| 608 |
-
@app.route('/backup', methods=['POST'])
|
| 609 |
-
def backup():
|
| 610 |
-
try:
|
| 611 |
-
upload_db_to_hf()
|
| 612 |
-
flash('Резервная копия успешно создана.', 'success')
|
| 613 |
-
except Exception as e:
|
| 614 |
-
flash(f'Ошибка при создании резервной копии: {e}', 'error')
|
| 615 |
-
return redirect(url_for('admin'))
|
| 616 |
-
|
| 617 |
-
@app.route('/download', methods=['GET'])
|
| 618 |
-
def download():
|
| 619 |
-
try:
|
| 620 |
-
if os.path.exists(DATA_FILE):
|
| 621 |
-
return send_file(DATA_FILE, as_attachment=True, mimetype='application/json', download_name='data_zzirix_backup.json')
|
| 622 |
-
flash('Файл базы данных не найден.', 'error')
|
| 623 |
-
except Exception as e:
|
| 624 |
-
flash(f'Ошибка при скачивании базы данных: {e}', 'error')
|
| 625 |
-
return redirect(url_for('admin'))
|
| 626 |
-
|
| 627 |
-
if __name__ == '__main__':
|
| 628 |
-
logging.info("Начальная проверка и обновление структуры данных...")
|
| 629 |
-
try:
|
| 630 |
-
current_data = load_data()
|
| 631 |
-
updated_data = initialize_data_structure(current_data)
|
| 632 |
-
if json.dumps(updated_data, sort_keys=True) != json.dumps(current_data, sort_keys=True):
|
| 633 |
-
logging.info("Обновление структуры данных...")
|
| 634 |
-
save_data(updated_data)
|
| 635 |
-
except Exception as e:
|
| 636 |
-
logging.error(f"Ошибка при начальной проверке данных: {e}")
|
| 637 |
-
|
| 638 |
-
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
|
| 639 |
-
backup_thread.start()
|
| 640 |
-
logging.info("Запуск Flask приложения...")
|
| 641 |
-
app.run(debug=False, host='0.0.0.0', port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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