Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,6 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify
|
| 4 |
import json
|
| 5 |
import os
|
| 6 |
-
import logging
|
| 7 |
import threading
|
| 8 |
import time
|
| 9 |
from datetime import datetime
|
|
@@ -20,7 +17,6 @@ app = Flask(__name__)
|
|
| 20 |
app.secret_key = 'your_unique_secret_key_soola_cosmetics_67890_no_login'
|
| 21 |
DATA_FILE = 'data.json'
|
| 22 |
|
| 23 |
-
|
| 24 |
SYNC_FILES = [DATA_FILE]
|
| 25 |
|
| 26 |
REPO_ID = "Kgshop/balluu"
|
|
@@ -35,25 +31,19 @@ CURRENCY_NAME = 'Кыргызский сом'
|
|
| 35 |
DOWNLOAD_RETRIES = 3
|
| 36 |
DOWNLOAD_DELAY = 5
|
| 37 |
|
| 38 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):
|
| 43 |
if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
|
| 44 |
-
|
| 45 |
|
| 46 |
token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE
|
| 47 |
|
| 48 |
files_to_download = [specific_file] if specific_file else SYNC_FILES
|
| 49 |
-
logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...")
|
| 50 |
all_successful = True
|
| 51 |
|
| 52 |
for file_name in files_to_download:
|
| 53 |
success = False
|
| 54 |
for attempt in range(retries + 1):
|
| 55 |
try:
|
| 56 |
-
logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...")
|
| 57 |
local_path = hf_hub_download(
|
| 58 |
repo_id=REPO_ID,
|
| 59 |
filename=file_name,
|
|
@@ -64,50 +54,40 @@ def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWN
|
|
| 64 |
force_download=True,
|
| 65 |
resume_download=False
|
| 66 |
)
|
| 67 |
-
logging.info(f"Successfully downloaded {file_name} to {local_path}.")
|
| 68 |
success = True
|
| 69 |
break
|
| 70 |
except RepositoryNotFoundError:
|
| 71 |
-
logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.")
|
| 72 |
return False
|
| 73 |
except HfHubHTTPError as e:
|
| 74 |
if e.response.status_code == 404:
|
| 75 |
-
logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.")
|
| 76 |
if attempt == 0 and not os.path.exists(file_name):
|
| 77 |
try:
|
| 78 |
if file_name == DATA_FILE:
|
| 79 |
with open(file_name, 'w', encoding='utf-8') as f:
|
| 80 |
json.dump({'products': [], 'categories': [], 'orders': {}}, f)
|
| 81 |
-
logging.info(f"Created empty local file {file_name} because it was not found on HF.")
|
| 82 |
except Exception as create_e:
|
| 83 |
-
|
| 84 |
success = False
|
| 85 |
break
|
| 86 |
-
else:
|
| 87 |
-
logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...")
|
| 88 |
except requests.exceptions.RequestException as e:
|
| 89 |
-
|
| 90 |
except Exception as e:
|
| 91 |
-
|
| 92 |
|
| 93 |
if attempt < retries:
|
| 94 |
time.sleep(delay)
|
| 95 |
|
| 96 |
if not success:
|
| 97 |
-
logging.error(f"Failed to download {file_name} after {retries + 1} attempts.")
|
| 98 |
all_successful = False
|
| 99 |
|
| 100 |
-
logging.info(f"Download process finished. Overall success: {all_successful}")
|
| 101 |
return all_successful
|
| 102 |
|
| 103 |
def upload_db_to_hf(specific_file=None):
|
| 104 |
if not HF_TOKEN_WRITE:
|
| 105 |
-
logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.")
|
| 106 |
return
|
| 107 |
try:
|
| 108 |
api = HfApi()
|
| 109 |
files_to_upload = [specific_file] if specific_file else SYNC_FILES
|
| 110 |
-
logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...")
|
| 111 |
|
| 112 |
for file_name in files_to_upload:
|
| 113 |
if os.path.exists(file_name):
|
|
@@ -120,80 +100,68 @@ def upload_db_to_hf(specific_file=None):
|
|
| 120 |
token=HF_TOKEN_WRITE,
|
| 121 |
commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 122 |
)
|
| 123 |
-
logging.info(f"File {file_name} successfully uploaded to Hugging Face.")
|
| 124 |
except Exception as e:
|
| 125 |
-
|
| 126 |
else:
|
| 127 |
-
|
| 128 |
-
logging.info("Finished uploading files to HF.")
|
| 129 |
except Exception as e:
|
| 130 |
-
|
| 131 |
|
| 132 |
def periodic_backup():
|
| 133 |
backup_interval = 1800
|
| 134 |
-
logging.info(f"Setting up periodic backup every {backup_interval} seconds.")
|
| 135 |
while True:
|
| 136 |
time.sleep(backup_interval)
|
| 137 |
-
logging.info("Starting periodic backup...")
|
| 138 |
upload_db_to_hf()
|
| 139 |
-
logging.info("Periodic backup finished.")
|
| 140 |
-
|
| 141 |
-
|
| 142 |
|
| 143 |
def load_data():
|
| 144 |
default_data = {'products': [], 'categories': [], 'orders': {}}
|
|
|
|
| 145 |
try:
|
| 146 |
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 147 |
data = json.load(file)
|
| 148 |
-
logging.info(f"Local data loaded successfully from {DATA_FILE}")
|
| 149 |
if not isinstance(data, dict):
|
| 150 |
-
logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.")
|
| 151 |
raise FileNotFoundError
|
| 152 |
if 'products' not in data: data['products'] = []
|
| 153 |
if 'categories' not in data: data['categories'] = []
|
| 154 |
if 'orders' not in data: data['orders'] = {}
|
| 155 |
-
return data
|
| 156 |
except FileNotFoundError:
|
| 157 |
-
|
| 158 |
except json.JSONDecodeError:
|
| 159 |
-
|
| 160 |
|
| 161 |
-
if
|
| 162 |
-
|
| 163 |
-
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 164 |
-
data = json.load(file)
|
| 165 |
-
logging.info(f"Data loaded successfully from {DATA_FILE} after download.")
|
| 166 |
-
if not isinstance(data, dict):
|
| 167 |
-
logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.")
|
| 168 |
-
return default_data
|
| 169 |
-
if 'products' not in data: data['products'] = []
|
| 170 |
-
if 'categories' not in data: data['categories'] = []
|
| 171 |
-
if 'orders' not in data: data['orders'] = {}
|
| 172 |
-
return data
|
| 173 |
-
except FileNotFoundError:
|
| 174 |
-
logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.")
|
| 175 |
-
return default_data
|
| 176 |
-
except json.JSONDecodeError:
|
| 177 |
-
logging.error(f"Error decoding JSON in downloaded {DATA_FILE}. Using default.")
|
| 178 |
-
return default_data
|
| 179 |
-
except Exception as e:
|
| 180 |
-
logging.error(f"Unknown error loading downloaded {DATA_FILE}: {e}. Using default.", exc_info=True)
|
| 181 |
-
return default_data
|
| 182 |
-
else:
|
| 183 |
-
logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.")
|
| 184 |
-
if not os.path.exists(DATA_FILE):
|
| 185 |
try:
|
| 186 |
-
with open(DATA_FILE, '
|
| 187 |
-
json.
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
def save_data(data):
|
| 194 |
try:
|
| 195 |
if not isinstance(data, dict):
|
| 196 |
-
logging.error("Attempted to save invalid data structure (not a dict). Aborting save.")
|
| 197 |
return
|
| 198 |
if 'products' not in data: data['products'] = []
|
| 199 |
if 'categories' not in data: data['categories'] = []
|
|
@@ -201,12 +169,9 @@ def save_data(data):
|
|
| 201 |
|
| 202 |
with open(DATA_FILE, 'w', encoding='utf-8') as file:
|
| 203 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
| 204 |
-
logging.info(f"Data successfully saved to {DATA_FILE}")
|
| 205 |
upload_db_to_hf(specific_file=DATA_FILE)
|
| 206 |
except Exception as e:
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
|
| 211 |
CATALOG_TEMPLATE = '''
|
| 212 |
<!DOCTYPE html>
|
|
@@ -245,6 +210,7 @@ CATALOG_TEMPLATE = '''
|
|
| 245 |
.products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 20px; padding: 10px; }
|
| 246 |
@media (min-width: 600px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); } }
|
| 247 |
@media (min-width: 900px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); } }
|
|
|
|
| 248 |
.product { background: #fff; border-radius: 15px; padding: 0; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; height: 100%; border: 1px solid #FCE7F3;}
|
| 249 |
body.dark-mode .product { background: #412539; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); border-color: #59344f; }
|
| 250 |
.product:hover { transform: translateY(-5px) scale(1.02); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12); }
|
|
@@ -318,16 +284,20 @@ CATALOG_TEMPLATE = '''
|
|
| 318 |
<i class="fas fa-moon"></i>
|
| 319 |
</button>
|
| 320 |
</div>
|
|
|
|
| 321 |
<div class="store-address">Наш адрес: {{ store_address }}</div>
|
|
|
|
| 322 |
<div class="filters-container">
|
| 323 |
<button class="category-filter active" data-category="all">Все категории</button>
|
| 324 |
{% for category in categories %}
|
| 325 |
<button class="category-filter" data-category="{{ category }}">{{ category }}</button>
|
| 326 |
{% endfor %}
|
| 327 |
</div>
|
|
|
|
| 328 |
<div class="search-container">
|
| 329 |
<input type="text" id="search-input" placeholder="Поиск по названию или описанию...">
|
| 330 |
</div>
|
|
|
|
| 331 |
<div class="products-grid" id="products-grid">
|
| 332 |
{% for product in products %}
|
| 333 |
<div class="product"
|
|
@@ -352,8 +322,8 @@ CATALOG_TEMPLATE = '''
|
|
| 352 |
<p class="product-description">{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}</p>
|
| 353 |
</div>
|
| 354 |
<div class="product-actions">
|
| 355 |
-
<button class="product-button" onclick="
|
| 356 |
-
<button class="product-button add-to-cart" onclick="
|
| 357 |
<i class="fas fa-cart-plus"></i> В корзину
|
| 358 |
</button>
|
| 359 |
</div>
|
|
@@ -364,12 +334,14 @@ CATALOG_TEMPLATE = '''
|
|
| 364 |
{% endif %}
|
| 365 |
</div>
|
| 366 |
</div>
|
|
|
|
| 367 |
<div id="productModal" class="modal">
|
| 368 |
<div class="modal-content">
|
| 369 |
<span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span>
|
| 370 |
<div id="modalContent">Загрузка...</div>
|
| 371 |
</div>
|
| 372 |
</div>
|
|
|
|
| 373 |
<div id="quantityModal" class="modal">
|
| 374 |
<div class="modal-content">
|
| 375 |
<span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">×</span>
|
|
@@ -381,6 +353,7 @@ CATALOG_TEMPLATE = '''
|
|
| 381 |
<button class="product-button add-to-cart" onclick="confirmAddToCart()"><i class="fas fa-check"></i> Добавить в корзину</button>
|
| 382 |
</div>
|
| 383 |
</div>
|
|
|
|
| 384 |
<div id="cartModal" class="modal">
|
| 385 |
<div class="modal-content">
|
| 386 |
<span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span>
|
|
@@ -399,18 +372,22 @@ CATALOG_TEMPLATE = '''
|
|
| 399 |
</div>
|
| 400 |
</div>
|
| 401 |
</div>
|
|
|
|
| 402 |
<button id="cart-button" onclick="openCartModal()" aria-label="Открыть корзину">
|
| 403 |
<i class="fas fa-shopping-cart"></i>
|
| 404 |
<span id="cart-count">0</span>
|
| 405 |
</button>
|
|
|
|
| 406 |
<div id="notification-placeholder"></div>
|
|
|
|
| 407 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
|
| 408 |
<script>
|
| 409 |
-
const
|
| 410 |
const repoId = '{{ repo_id }}';
|
| 411 |
const currencyCode = '{{ currency_code }}';
|
| 412 |
-
let
|
| 413 |
let cart = JSON.parse(localStorage.getItem('soolaCart') || '[]');
|
|
|
|
| 414 |
function toggleTheme() {
|
| 415 |
document.body.classList.toggle('dark-mode');
|
| 416 |
const icon = document.querySelector('.theme-toggle i');
|
|
@@ -419,6 +396,7 @@ CATALOG_TEMPLATE = '''
|
|
| 419 |
icon.classList.toggle('fa-sun', isDarkMode);
|
| 420 |
localStorage.setItem('soolaTheme', isDarkMode ? 'dark' : 'light');
|
| 421 |
}
|
|
|
|
| 422 |
function applyInitialTheme() {
|
| 423 |
const savedTheme = localStorage.getItem('soolaTheme');
|
| 424 |
if (savedTheme === 'dark') {
|
|
@@ -427,14 +405,16 @@ CATALOG_TEMPLATE = '''
|
|
| 427 |
if (icon) icon.classList.replace('fa-moon', 'fa-sun');
|
| 428 |
}
|
| 429 |
}
|
| 430 |
-
|
| 431 |
-
|
|
|
|
| 432 |
const modal = document.getElementById('productModal');
|
| 433 |
if (modal) {
|
| 434 |
modal.style.display = "block";
|
| 435 |
document.body.style.overflow = 'hidden';
|
| 436 |
}
|
| 437 |
}
|
|
|
|
| 438 |
function closeModal(modalId) {
|
| 439 |
const modal = document.getElementById(modalId);
|
| 440 |
if (modal) {
|
|
@@ -445,11 +425,12 @@ CATALOG_TEMPLATE = '''
|
|
| 445 |
document.body.style.overflow = 'auto';
|
| 446 |
}
|
| 447 |
}
|
| 448 |
-
|
|
|
|
| 449 |
const modalContent = document.getElementById('modalContent');
|
| 450 |
if (!modalContent) return;
|
| 451 |
modalContent.innerHTML = '<p style="text-align:center; padding: 40px;">Загрузка...</p>';
|
| 452 |
-
fetch('/product/' +
|
| 453 |
.then(response => {
|
| 454 |
if (!response.ok) throw new Error(`Ошибка ${response.status}: ${response.statusText}`);
|
| 455 |
return response.text();
|
|
@@ -463,6 +444,7 @@ CATALOG_TEMPLATE = '''
|
|
| 463 |
modalContent.innerHTML = `<p style="color: red; text-align:center; padding: 40px;">Не удалось загрузить информацию о товаре. ${error.message}</p>`;
|
| 464 |
});
|
| 465 |
}
|
|
|
|
| 466 |
function initializeSwiper() {
|
| 467 |
const swiperContainer = document.querySelector('#productModal .swiper-container');
|
| 468 |
if (swiperContainer) {
|
|
@@ -478,18 +460,22 @@ CATALOG_TEMPLATE = '''
|
|
| 478 |
});
|
| 479 |
}
|
| 480 |
}
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
|
|
|
| 484 |
if (!product) {
|
| 485 |
-
console.error("Product not found for
|
| 486 |
alert("Ошибка: товар не найден.");
|
| 487 |
return;
|
| 488 |
}
|
|
|
|
| 489 |
const colorSelect = document.getElementById('colorSelect');
|
| 490 |
const colorLabel = document.querySelector('label[for="colorSelect"]');
|
| 491 |
colorSelect.innerHTML = '';
|
|
|
|
| 492 |
const validColors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : [];
|
|
|
|
| 493 |
if (validColors.length > 0) {
|
| 494 |
validColors.forEach(color => {
|
| 495 |
const option = document.createElement('option');
|
|
@@ -503,6 +489,7 @@ CATALOG_TEMPLATE = '''
|
|
| 503 |
colorSelect.style.display = 'none';
|
| 504 |
if(colorLabel) colorLabel.style.display = 'none';
|
| 505 |
}
|
|
|
|
| 506 |
document.getElementById('quantityInput').value = 1;
|
| 507 |
const modal = document.getElementById('quantityModal');
|
| 508 |
if(modal) {
|
|
@@ -510,29 +497,36 @@ CATALOG_TEMPLATE = '''
|
|
| 510 |
document.body.style.overflow = 'hidden';
|
| 511 |
}
|
| 512 |
}
|
|
|
|
| 513 |
function confirmAddToCart() {
|
| 514 |
-
if (
|
|
|
|
| 515 |
const quantityInput = document.getElementById('quantityInput');
|
| 516 |
const quantity = parseInt(quantityInput.value);
|
| 517 |
const colorSelect = document.getElementById('colorSelect');
|
| 518 |
const color = colorSelect.style.display !== 'none' && colorSelect.value ? colorSelect.value : 'N/A';
|
|
|
|
| 519 |
if (isNaN(quantity) || quantity <= 0) {
|
| 520 |
alert("Пожалуйста, укажите корректное количество (больше 0).");
|
| 521 |
quantityInput.focus();
|
| 522 |
return;
|
| 523 |
}
|
| 524 |
-
|
|
|
|
| 525 |
if (!product) {
|
| 526 |
alert("Ошибка добавления: товар не найден.");
|
| 527 |
return;
|
| 528 |
}
|
| 529 |
-
|
|
|
|
| 530 |
const existingItemIndex = cart.findIndex(item => item.id === cartItemId);
|
|
|
|
| 531 |
if (existingItemIndex > -1) {
|
| 532 |
cart[existingItemIndex].quantity += quantity;
|
| 533 |
} else {
|
| 534 |
cart.push({
|
| 535 |
id: cartItemId,
|
|
|
|
| 536 |
name: product.name,
|
| 537 |
price: product.price,
|
| 538 |
photo: product.photos && product.photos.length > 0 ? product.photos[0] : null,
|
|
@@ -540,17 +534,21 @@ CATALOG_TEMPLATE = '''
|
|
| 540 |
color: color
|
| 541 |
});
|
| 542 |
}
|
|
|
|
| 543 |
localStorage.setItem('soolaCart', JSON.stringify(cart));
|
| 544 |
closeModal('quantityModal');
|
| 545 |
updateCartButton();
|
| 546 |
showNotification(`${product.name} добавлен в корзину!`);
|
| 547 |
}
|
|
|
|
| 548 |
function updateCartButton() {
|
| 549 |
const cartCountElement = document.getElementById('cart-count');
|
| 550 |
const cartButton = document.getElementById('cart-button');
|
| 551 |
if (!cartCountElement || !cartButton) return;
|
|
|
|
| 552 |
let totalItems = 0;
|
| 553 |
cart.forEach(item => { totalItems += item.quantity; });
|
|
|
|
| 554 |
if (totalItems > 0) {
|
| 555 |
cartCountElement.textContent = totalItems;
|
| 556 |
cartButton.style.display = 'flex';
|
|
@@ -559,11 +557,14 @@ CATALOG_TEMPLATE = '''
|
|
| 559 |
cartButton.style.display = 'none';
|
| 560 |
}
|
| 561 |
}
|
|
|
|
| 562 |
function openCartModal() {
|
| 563 |
const cartContent = document.getElementById('cartContent');
|
| 564 |
const cartTotalElement = document.getElementById('cartTotal');
|
| 565 |
if (!cartContent || !cartTotalElement) return;
|
|
|
|
| 566 |
let total = 0;
|
|
|
|
| 567 |
if (cart.length === 0) {
|
| 568 |
cartContent.innerHTML = '<p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p>';
|
| 569 |
cartTotalElement.textContent = '0.00';
|
|
@@ -575,6 +576,7 @@ CATALOG_TEMPLATE = '''
|
|
| 575 |
? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}`
|
| 576 |
: 'https://via.placeholder.com/60x60.png?text=N/A';
|
| 577 |
const colorText = item.color !== 'N/A' ? ` (Цвет: ${item.color})` : '';
|
|
|
|
| 578 |
return `
|
| 579 |
<div class="cart-item">
|
| 580 |
<img src="${photoUrl}" alt="${item.name}">
|
|
@@ -595,12 +597,14 @@ CATALOG_TEMPLATE = '''
|
|
| 595 |
document.body.style.overflow = 'hidden';
|
| 596 |
}
|
| 597 |
}
|
|
|
|
| 598 |
function removeFromCart(itemId) {
|
| 599 |
cart = cart.filter(item => item.id !== itemId);
|
| 600 |
localStorage.setItem('soolaCart', JSON.stringify(cart));
|
| 601 |
openCartModal();
|
| 602 |
updateCartButton();
|
| 603 |
}
|
|
|
|
| 604 |
function clearCart() {
|
| 605 |
if (confirm("Вы уверены, что хотите очистить корзину?")) {
|
| 606 |
cart = [];
|
|
@@ -609,17 +613,22 @@ CATALOG_TEMPLATE = '''
|
|
| 609 |
updateCartButton();
|
| 610 |
}
|
| 611 |
}
|
|
|
|
| 612 |
function formulateOrder() {
|
| 613 |
if (cart.length === 0) {
|
| 614 |
alert("Корзина пуста! Добавьте товары перед формированием заказа.");
|
| 615 |
return;
|
| 616 |
}
|
|
|
|
| 617 |
const orderData = {
|
| 618 |
cart: cart
|
| 619 |
};
|
|
|
|
| 620 |
const formulateButton = document.querySelector('.formulate-order-button');
|
| 621 |
if (formulateButton) formulateButton.disabled = true;
|
|
|
|
| 622 |
showNotification("Формируем заказ...", 5000);
|
|
|
|
| 623 |
fetch('/create_order', {
|
| 624 |
method: 'POST',
|
| 625 |
headers: { 'Content-Type': 'application/json' },
|
|
@@ -648,20 +657,26 @@ CATALOG_TEMPLATE = '''
|
|
| 648 |
if (formulateButton) formulateButton.disabled = false;
|
| 649 |
});
|
| 650 |
}
|
|
|
|
|
|
|
| 651 |
function filterProducts() {
|
| 652 |
const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();
|
| 653 |
const activeCategoryButton = document.querySelector('.category-filter.active');
|
| 654 |
const activeCategory = activeCategoryButton ? activeCategoryButton.dataset.category : 'all';
|
| 655 |
const grid = document.getElementById('products-grid');
|
| 656 |
let visibleProducts = 0;
|
|
|
|
| 657 |
const existingNoResults = grid.querySelector('.no-results-message');
|
| 658 |
if (existingNoResults) existingNoResults.remove();
|
|
|
|
| 659 |
document.querySelectorAll('.products-grid .product').forEach(productElement => {
|
| 660 |
const name = productElement.getAttribute('data-name');
|
| 661 |
const description = productElement.getAttribute('data-description');
|
| 662 |
const category = productElement.getAttribute('data-category');
|
|
|
|
| 663 |
const matchesSearch = !searchTerm || name.includes(searchTerm) || description.includes(searchTerm);
|
| 664 |
const matchesCategory = activeCategory === 'all' || category === activeCategory;
|
|
|
|
| 665 |
if (matchesSearch && matchesCategory) {
|
| 666 |
productElement.style.display = 'flex';
|
| 667 |
visibleProducts++;
|
|
@@ -669,22 +684,26 @@ CATALOG_TEMPLATE = '''
|
|
| 669 |
productElement.style.display = 'none';
|
| 670 |
}
|
| 671 |
});
|
| 672 |
-
|
|
|
|
| 673 |
const p = document.createElement('p');
|
| 674 |
p.className = 'no-results-message';
|
| 675 |
p.textContent = 'По вашему запросу товары не найдены.';
|
| 676 |
grid.appendChild(p);
|
| 677 |
-
} else if (
|
| 678 |
const p = document.createElement('p');
|
| 679 |
p.className = 'no-results-message';
|
| 680 |
p.textContent = 'Товары пока не добавлены.';
|
| 681 |
grid.appendChild(p);
|
| 682 |
}
|
| 683 |
}
|
|
|
|
| 684 |
function setupFilters() {
|
| 685 |
const searchInput = document.getElementById('search-input');
|
| 686 |
const categoryFilters = document.querySelectorAll('.category-filter');
|
|
|
|
| 687 |
if(searchInput) searchInput.addEventListener('input', filterProducts);
|
|
|
|
| 688 |
categoryFilters.forEach(filter => {
|
| 689 |
filter.addEventListener('click', function() {
|
| 690 |
categoryFilters.forEach(f => f.classList.remove('active'));
|
|
@@ -694,6 +713,7 @@ CATALOG_TEMPLATE = '''
|
|
| 694 |
});
|
| 695 |
filterProducts();
|
| 696 |
}
|
|
|
|
| 697 |
function showNotification(message, duration = 3000) {
|
| 698 |
const placeholder = document.getElementById('notification-placeholder');
|
| 699 |
if (!placeholder) {
|
|
@@ -707,26 +727,34 @@ CATALOG_TEMPLATE = '''
|
|
| 707 |
document.body.appendChild(newPlaceholder);
|
| 708 |
placeholder = newPlaceholder;
|
| 709 |
}
|
|
|
|
|
|
|
| 710 |
const notification = document.createElement('div');
|
| 711 |
notification.className = 'notification';
|
| 712 |
notification.textContent = message;
|
| 713 |
placeholder.appendChild(notification);
|
|
|
|
| 714 |
void notification.offsetWidth;
|
|
|
|
| 715 |
notification.classList.add('show');
|
|
|
|
| 716 |
setTimeout(() => {
|
| 717 |
notification.classList.remove('show');
|
| 718 |
notification.addEventListener('transitionend', () => notification.remove());
|
| 719 |
}, duration);
|
| 720 |
}
|
|
|
|
| 721 |
document.addEventListener('DOMContentLoaded', () => {
|
| 722 |
applyInitialTheme();
|
| 723 |
updateCartButton();
|
| 724 |
setupFilters();
|
|
|
|
| 725 |
window.addEventListener('click', function(event) {
|
| 726 |
if (event.target.classList.contains('modal')) {
|
| 727 |
closeModal(event.target.id);
|
| 728 |
}
|
| 729 |
});
|
|
|
|
| 730 |
window.addEventListener('keydown', function(event) {
|
| 731 |
if (event.key === 'Escape') {
|
| 732 |
document.querySelectorAll('.modal[style*="display: block"]').forEach(modal => {
|
|
@@ -735,6 +763,7 @@ CATALOG_TEMPLATE = '''
|
|
| 735 |
}
|
| 736 |
});
|
| 737 |
});
|
|
|
|
| 738 |
</script>
|
| 739 |
</body>
|
| 740 |
</html>
|
|
@@ -767,6 +796,7 @@ PRODUCT_DETAIL_TEMPLATE = '''
|
|
| 767 |
<div class="swiper-button-prev" style="color: #F472B6;"></div>
|
| 768 |
{% endif %}
|
| 769 |
</div>
|
|
|
|
| 770 |
<div style="margin-top: 20px; font-size: 1rem; line-height: 1.7;">
|
| 771 |
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
|
| 772 |
<p style="font-size: 1.2rem; font-weight: bold; color: #DB2777;"><strong>Цена:</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p>
|
|
@@ -821,6 +851,7 @@ ORDER_TEMPLATE = '''
|
|
| 821 |
{% if order %}
|
| 822 |
<h1><i class="fas fa-receipt"></i> Ваш Заказ №{{ order.id }}</h1>
|
| 823 |
<p class="order-meta">Дата создания: {{ order.created_at }}</p>
|
|
|
|
| 824 |
<h2><i class="fas fa-shopping-bag"></i> Товары в заказе</h2>
|
| 825 |
<div id="orderItems">
|
| 826 |
{% for item in order.cart %}
|
|
@@ -836,32 +867,40 @@ ORDER_TEMPLATE = '''
|
|
| 836 |
</div>
|
| 837 |
{% endfor %}
|
| 838 |
</div>
|
|
|
|
| 839 |
<div class="order-summary">
|
| 840 |
<p>Общая с��мма товаров: <strong>{{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>
|
| 841 |
<p><strong>ИТОГО К ОПЛАТЕ: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>
|
| 842 |
</div>
|
|
|
|
| 843 |
<div class="customer-info">
|
| 844 |
<h2><i class="fas fa-info-circle"></i> Статус заказа</h2>
|
| 845 |
<p>Этот заказ был оформлен без входа в систему.</p>
|
| 846 |
<p>Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.</p>
|
| 847 |
</div>
|
|
|
|
| 848 |
<div class="actions">
|
| 849 |
<button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> Отправить заказ</button>
|
| 850 |
</div>
|
|
|
|
| 851 |
<a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в каталог</a>
|
|
|
|
| 852 |
<script>
|
| 853 |
function sendOrderViaWhatsApp() {
|
| 854 |
const orderId = '{{ order.id }}';
|
| 855 |
const orderUrl = `{{ request.url }}`;
|
| 856 |
const whatsappNumber = "996703550150";
|
|
|
|
| 857 |
let message = `Здравствуйте! Хочу подтвердить свой заказ на Brand_Baaluu:%0A%0A`;
|
| 858 |
message += `*Номер заказа:* ${orderId}%0A`;
|
| 859 |
message += `*Ссылка на заказ:* ${encodeURIComponent(orderUrl)}%0A%0A`;
|
| 860 |
message += `Пожалуйста, свяжитесь со мной для уточнения деталей оплаты и доставки.`;
|
|
|
|
| 861 |
const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${message}`;
|
| 862 |
window.open(whatsappUrl, '_blank');
|
| 863 |
}
|
| 864 |
</script>
|
|
|
|
| 865 |
{% else %}
|
| 866 |
<h1 style="color: #c53030;"><i class="fas fa-exclamation-triangle"></i> Ошибка</h1>
|
| 867 |
<p class="not-found">Заказ с таким ID не найден.</p>
|
|
@@ -953,6 +992,8 @@ ADMIN_TEMPLATE = '''
|
|
| 953 |
</div>
|
| 954 |
<a href="{{ url_for('catalog') }}" class="button" style="background-color: #EC4899;"><i class="fas fa-store"></i> Перейти в каталог</a>
|
| 955 |
</div>
|
|
|
|
|
|
|
| 956 |
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 957 |
{% if messages %}
|
| 958 |
{% for category, message in messages %}
|
|
@@ -960,6 +1001,7 @@ ADMIN_TEMPLATE = '''
|
|
| 960 |
{% endfor %}
|
| 961 |
{% endif %}
|
| 962 |
{% endwith %}
|
|
|
|
| 963 |
<div class="section">
|
| 964 |
<h2><i class="fas fa-sync-alt"></i> Синхронизация с Датацентром</h2>
|
| 965 |
<div class="sync-buttons">
|
|
@@ -972,6 +1014,7 @@ ADMIN_TEMPLATE = '''
|
|
| 972 |
</div>
|
| 973 |
<p style="font-size: 0.85rem; color: #a0aec0;">Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.</p>
|
| 974 |
</div>
|
|
|
|
| 975 |
<div class="flex-container">
|
| 976 |
<div class="flex-item">
|
| 977 |
<div class="section">
|
|
@@ -987,6 +1030,7 @@ ADMIN_TEMPLATE = '''
|
|
| 987 |
</form>
|
| 988 |
</div>
|
| 989 |
</details>
|
|
|
|
| 990 |
<h3>Существующие категории:</h3>
|
| 991 |
{% if categories %}
|
| 992 |
<div class="item-list">
|
|
@@ -1006,6 +1050,7 @@ ADMIN_TEMPLATE = '''
|
|
| 1006 |
{% endif %}
|
| 1007 |
</div>
|
| 1008 |
</div>
|
|
|
|
| 1009 |
<div class="flex-item">
|
| 1010 |
<div class="section">
|
| 1011 |
<h2><i class="fas fa-info-circle"></i> Информация</h2>
|
|
@@ -1014,6 +1059,7 @@ ADMIN_TEMPLATE = '''
|
|
| 1014 |
</div>
|
| 1015 |
</div>
|
| 1016 |
</div>
|
|
|
|
| 1017 |
<div class="section">
|
| 1018 |
<h2><i class="fas fa-box-open"></i> Управление товарами</h2>
|
| 1019 |
<details>
|
|
@@ -1058,6 +1104,7 @@ ADMIN_TEMPLATE = '''
|
|
| 1058 |
</form>
|
| 1059 |
</div>
|
| 1060 |
</details>
|
|
|
|
| 1061 |
<h3>Список товаров:</h3>
|
| 1062 |
{% if products %}
|
| 1063 |
<div class="item-list">
|
|
@@ -1095,19 +1142,21 @@ ADMIN_TEMPLATE = '''
|
|
| 1095 |
{% endif %}
|
| 1096 |
</div>
|
| 1097 |
</div>
|
|
|
|
| 1098 |
<div class="item-actions">
|
| 1099 |
-
<button type="button" class="button" onclick="toggleEditForm('edit-form-{{ product
|
| 1100 |
<form method="POST" style="margin:0;" onsubmit="return confirm('Вы уверены, что хотите удалить товар \'{{ product['name'] }}\'?');">
|
| 1101 |
<input type="hidden" name="action" value="delete_product">
|
| 1102 |
-
<input type="hidden" name="product_id" value="{{ product
|
| 1103 |
<button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button>
|
| 1104 |
</form>
|
| 1105 |
</div>
|
| 1106 |
-
|
|
|
|
| 1107 |
<h4><i class="fas fa-edit"></i> Редактирование: {{ product['name'] }}</h4>
|
| 1108 |
<form method="POST" enctype="multipart/form-data">
|
| 1109 |
<input type="hidden" name="action" value="edit_product">
|
| 1110 |
-
<input type="hidden" name="product_id" value="{{ product
|
| 1111 |
<label>Название *:</label>
|
| 1112 |
<input type="text" name="name" value="{{ product['name'] }}" required>
|
| 1113 |
<label>Цена ({{ currency_code }}) *:</label>
|
|
@@ -1132,7 +1181,7 @@ ADMIN_TEMPLATE = '''
|
|
| 1132 |
</div>
|
| 1133 |
{% endif %}
|
| 1134 |
<label>Цвета/Варианты:</label>
|
| 1135 |
-
<div id="edit-color-inputs-{{ product
|
| 1136 |
{% set current_colors = product.get('colors', []) %}
|
| 1137 |
{% if current_colors and current_colors|select('ne', '')|list|length > 0 %}
|
| 1138 |
{% for color in current_colors %}
|
|
@@ -1150,15 +1199,15 @@ ADMIN_TEMPLATE = '''
|
|
| 1150 |
</div>
|
| 1151 |
{% endif %}
|
| 1152 |
</div>
|
| 1153 |
-
<button type="button" class="button add-color-btn" style="margin-top: 5px;" onclick="addColorInput('edit-color-inputs-{{ product
|
| 1154 |
<br>
|
| 1155 |
<div style="margin-top: 15px;">
|
| 1156 |
-
<input type="checkbox" id="edit_in_stock_{{ product
|
| 1157 |
-
<label for="edit_in_stock_{{ product
|
| 1158 |
</div>
|
| 1159 |
<div style="margin-top: 5px;">
|
| 1160 |
-
<input type="checkbox" id="edit_is_top_{{ product
|
| 1161 |
-
<label for="edit_is_top_{{ product
|
| 1162 |
</div>
|
| 1163 |
<br>
|
| 1164 |
<button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Сохранить изменения</button>
|
|
@@ -1171,7 +1220,9 @@ ADMIN_TEMPLATE = '''
|
|
| 1171 |
<p>Товаров пока нет.</p>
|
| 1172 |
{% endif %}
|
| 1173 |
</div>
|
|
|
|
| 1174 |
</div>
|
|
|
|
| 1175 |
<script>
|
| 1176 |
function toggleEditForm(formId) {
|
| 1177 |
const formContainer = document.getElementById(formId);
|
|
@@ -1179,6 +1230,7 @@ ADMIN_TEMPLATE = '''
|
|
| 1179 |
formContainer.style.display = formContainer.style.display === 'none' || formContainer.style.display === '' ? 'block' : 'none';
|
| 1180 |
}
|
| 1181 |
}
|
|
|
|
| 1182 |
function addColorInput(containerId) {
|
| 1183 |
const container = document.getElementById(containerId);
|
| 1184 |
if (container) {
|
|
@@ -1195,11 +1247,13 @@ ADMIN_TEMPLATE = '''
|
|
| 1195 |
}
|
| 1196 |
}
|
| 1197 |
}
|
|
|
|
| 1198 |
function removeColorInput(button) {
|
| 1199 |
const group = button.closest('.color-input-group');
|
| 1200 |
if (group) {
|
| 1201 |
const container = group.parentNode;
|
| 1202 |
group.remove();
|
|
|
|
| 1203 |
if (container && container.children.length === 0) {
|
| 1204 |
const placeholderGroup = document.createElement('div');
|
| 1205 |
placeholderGroup.className = 'color-input-group';
|
|
@@ -1218,17 +1272,16 @@ ADMIN_TEMPLATE = '''
|
|
| 1218 |
</html>
|
| 1219 |
'''
|
| 1220 |
|
| 1221 |
-
|
| 1222 |
-
|
| 1223 |
@app.route('/')
|
| 1224 |
def catalog():
|
| 1225 |
data = load_data()
|
| 1226 |
all_products = data.get('products', [])
|
| 1227 |
-
categories = sorted(data.get('categories', []))
|
| 1228 |
|
| 1229 |
products_in_stock = [p for p in all_products if p.get('in_stock', True)]
|
| 1230 |
products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
|
| 1231 |
|
|
|
|
|
|
|
| 1232 |
return render_template_string(
|
| 1233 |
CATALOG_TEMPLATE,
|
| 1234 |
products=products_sorted,
|
|
@@ -1238,17 +1291,14 @@ def catalog():
|
|
| 1238 |
currency_code=CURRENCY_CODE
|
| 1239 |
)
|
| 1240 |
|
| 1241 |
-
@app.route('/product/<
|
| 1242 |
-
def product_detail(
|
| 1243 |
data = load_data()
|
| 1244 |
all_products = data.get('products', [])
|
| 1245 |
-
|
| 1246 |
-
|
| 1247 |
|
| 1248 |
-
|
| 1249 |
-
product = products_sorted[index]
|
| 1250 |
-
except IndexError:
|
| 1251 |
-
logging.warning(f"Attempted access to non-existent or out-of-stock product with index {index}")
|
| 1252 |
return "Товар не найден или отсутствует в наличии.", 404
|
| 1253 |
|
| 1254 |
return render_template_string(
|
|
@@ -1263,7 +1313,6 @@ def create_order():
|
|
| 1263 |
order_data = request.get_json()
|
| 1264 |
|
| 1265 |
if not order_data or 'cart' not in order_data or not order_data['cart']:
|
| 1266 |
-
logging.warning("Create order request missing cart data or cart is empty.")
|
| 1267 |
return jsonify({"error": "Корзина пуста или не передана."}), 400
|
| 1268 |
|
| 1269 |
cart_items = order_data['cart']
|
|
@@ -1272,7 +1321,6 @@ def create_order():
|
|
| 1272 |
processed_cart = []
|
| 1273 |
for item in cart_items:
|
| 1274 |
if not all(k in item for k in ('name', 'price', 'quantity')):
|
| 1275 |
-
logging.error(f"Invalid cart item structure received: {item}")
|
| 1276 |
return jsonify({"error": "Неверный формат товара в корзине."}), 400
|
| 1277 |
try:
|
| 1278 |
price = float(item['price'])
|
|
@@ -1289,7 +1337,6 @@ def create_order():
|
|
| 1289 |
"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"
|
| 1290 |
})
|
| 1291 |
except (ValueError, TypeError) as e:
|
| 1292 |
-
logging.error(f"Invalid price/quantity in cart item: {item}. Error: {e}")
|
| 1293 |
return jsonify({"error": "Неверная цена или количество в товаре."}), 400
|
| 1294 |
|
| 1295 |
order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}"
|
|
@@ -1311,11 +1358,9 @@ def create_order():
|
|
| 1311 |
|
| 1312 |
data['orders'][order_id] = new_order
|
| 1313 |
save_data(data)
|
| 1314 |
-
logging.info(f"Order {order_id} created successfully (anonymously).")
|
| 1315 |
return jsonify({"order_id": order_id}), 201
|
| 1316 |
|
| 1317 |
except Exception as e:
|
| 1318 |
-
logging.error(f"Failed to save order {order_id}: {e}", exc_info=True)
|
| 1319 |
return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500
|
| 1320 |
|
| 1321 |
@app.route('/order/<order_id>')
|
|
@@ -1323,11 +1368,6 @@ def view_order(order_id):
|
|
| 1323 |
data = load_data()
|
| 1324 |
order = data.get('orders', {}).get(order_id)
|
| 1325 |
|
| 1326 |
-
if order:
|
| 1327 |
-
logging.info(f"Displaying order {order_id}")
|
| 1328 |
-
else:
|
| 1329 |
-
logging.warning(f"Order {order_id} not found.")
|
| 1330 |
-
|
| 1331 |
return render_template_string(ORDER_TEMPLATE,
|
| 1332 |
order=order,
|
| 1333 |
repo_id=REPO_ID,
|
|
@@ -1343,16 +1383,6 @@ def admin():
|
|
| 1343 |
|
| 1344 |
if request.method == 'POST':
|
| 1345 |
action = request.form.get('action')
|
| 1346 |
-
logging.info(f"Admin action received: {action}")
|
| 1347 |
-
|
| 1348 |
-
data_modified_by_migration = False
|
| 1349 |
-
for product in products:
|
| 1350 |
-
if 'id' not in product or not product['id']:
|
| 1351 |
-
product['id'] = uuid.uuid4().hex
|
| 1352 |
-
data_modified_by_migration = True
|
| 1353 |
-
|
| 1354 |
-
if data_modified_by_migration:
|
| 1355 |
-
logging.info("Added missing unique IDs to one or more products.")
|
| 1356 |
|
| 1357 |
try:
|
| 1358 |
if action == 'add_category':
|
|
@@ -1361,13 +1391,10 @@ def admin():
|
|
| 1361 |
categories.append(category_name)
|
| 1362 |
data['categories'] = categories
|
| 1363 |
save_data(data)
|
| 1364 |
-
logging.info(f"Category '{category_name}' added.")
|
| 1365 |
flash(f"Категория '{category_name}' успешно добавлена.", 'success')
|
| 1366 |
elif not category_name:
|
| 1367 |
-
logging.warning("Attempted to add empty category.")
|
| 1368 |
flash("Название категории не может быть пустым.", 'error')
|
| 1369 |
else:
|
| 1370 |
-
logging.warning(f"Category '{category_name}' already exists.")
|
| 1371 |
flash(f"Категория '{category_name}' уже существует.", 'error')
|
| 1372 |
|
| 1373 |
elif action == 'delete_category':
|
|
@@ -1382,10 +1409,8 @@ def admin():
|
|
| 1382 |
data['categories'] = categories
|
| 1383 |
data['products'] = products
|
| 1384 |
save_data(data)
|
| 1385 |
-
logging.info(f"Category '{category_to_delete}' deleted. Updated products: {updated_count}.")
|
| 1386 |
flash(f"Категория '{category_to_delete}' удалена. {updated_count} товаров обновлено.", 'success')
|
| 1387 |
else:
|
| 1388 |
-
logging.warning(f"Attempted to delete non-existent or empty category: {category_to_delete}")
|
| 1389 |
flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error')
|
| 1390 |
|
| 1391 |
elif action == 'add_product':
|
|
@@ -1418,14 +1443,12 @@ def admin():
|
|
| 1418 |
uploaded_count = 0
|
| 1419 |
for photo in photos_files:
|
| 1420 |
if uploaded_count >= photo_limit:
|
| 1421 |
-
logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.")
|
| 1422 |
flash(f"Загружено только первые {photo_limit} фото.", "warning")
|
| 1423 |
break
|
| 1424 |
if photo and photo.filename:
|
| 1425 |
try:
|
| 1426 |
ext = os.path.splitext(photo.filename)[1].lower()
|
| 1427 |
if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
|
| 1428 |
-
logging.warning(f"Skipping non-image file upload: {photo.filename}")
|
| 1429 |
flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")
|
| 1430 |
continue
|
| 1431 |
|
|
@@ -1433,7 +1456,6 @@ def admin():
|
|
| 1433 |
photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
|
| 1434 |
temp_path = os.path.join(uploads_dir, photo_filename)
|
| 1435 |
photo.save(temp_path)
|
| 1436 |
-
logging.info(f"Uploading photo {photo_filename} to HF for product {name}...")
|
| 1437 |
api.upload_file(
|
| 1438 |
path_or_fileobj=temp_path,
|
| 1439 |
path_in_repo=f"photos/{photo_filename}",
|
|
@@ -1443,24 +1465,22 @@ def admin():
|
|
| 1443 |
commit_message=f"Add photo for product {name}"
|
| 1444 |
)
|
| 1445 |
photos_list.append(photo_filename)
|
| 1446 |
-
logging.info(f"Photo {photo_filename} uploaded successfully.")
|
| 1447 |
os.remove(temp_path)
|
| 1448 |
uploaded_count += 1
|
| 1449 |
except Exception as e:
|
| 1450 |
-
logging.error(f"Error uploading photo {photo.filename} to HF: {e}", exc_info=True)
|
| 1451 |
flash(f"Ошибка при загрузке фото {photo.filename}.", 'error')
|
| 1452 |
if os.path.exists(temp_path):
|
| 1453 |
try: os.remove(temp_path)
|
| 1454 |
except OSError: pass
|
| 1455 |
elif photo and not photo.filename:
|
| 1456 |
-
|
| 1457 |
try:
|
| 1458 |
if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
|
| 1459 |
os.rmdir(uploads_dir)
|
| 1460 |
except OSError as e:
|
| 1461 |
-
|
| 1462 |
elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
|
| 1463 |
-
flash("HF_TOKEN (
|
| 1464 |
|
| 1465 |
|
| 1466 |
new_product = {
|
|
@@ -1473,23 +1493,18 @@ def admin():
|
|
| 1473 |
products.append(new_product)
|
| 1474 |
data['products'] = products
|
| 1475 |
save_data(data)
|
| 1476 |
-
logging.info(f"Product '{name}' added.")
|
| 1477 |
flash(f"Товар '{name}' успешно добавлен.", 'success')
|
| 1478 |
|
| 1479 |
elif action == 'edit_product':
|
| 1480 |
product_id = request.form.get('product_id')
|
| 1481 |
-
|
| 1482 |
-
flash("Ошибка редактирования: ID товара не передан.", 'error')
|
| 1483 |
-
return redirect(url_for('admin'))
|
| 1484 |
-
|
| 1485 |
product_to_edit = next((p for p in products if p.get('id') == product_id), None)
|
| 1486 |
-
|
| 1487 |
-
if not product_to_edit:
|
| 1488 |
flash(f"Ошибка редактирования: товар с ID '{product_id}' не найден.", 'error')
|
| 1489 |
-
logging.error(f"Invalid product ID '{product_id}' for editing.")
|
| 1490 |
return redirect(url_for('admin'))
|
| 1491 |
-
|
| 1492 |
original_name = product_to_edit.get('name', 'N/A')
|
|
|
|
| 1493 |
product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip()
|
| 1494 |
price_str = request.form.get('price', str(product_to_edit['price'])).replace(',', '.')
|
| 1495 |
product_to_edit['description'] = request.form.get('description', product_to_edit.get('description', '')).strip()
|
|
@@ -1504,7 +1519,6 @@ def admin():
|
|
| 1504 |
if price < 0: price = 0
|
| 1505 |
product_to_edit['price'] = price
|
| 1506 |
except ValueError:
|
| 1507 |
-
logging.warning(f"Invalid price format '{price_str}' during edit of product {original_name}. Price not changed.")
|
| 1508 |
flash(f"Неверный формат цены для товара '{original_name}'. Цена не изменена.", 'warning')
|
| 1509 |
|
| 1510 |
photos_files = request.files.getlist('photos')
|
|
@@ -1515,17 +1529,14 @@ def admin():
|
|
| 1515 |
new_photos_list = []
|
| 1516 |
photo_limit = 10
|
| 1517 |
uploaded_count = 0
|
| 1518 |
-
logging.info(f"Uploading new photos for product {product_to_edit['name']}...")
|
| 1519 |
for photo in photos_files:
|
| 1520 |
if uploaded_count >= photo_limit:
|
| 1521 |
-
logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.")
|
| 1522 |
flash(f"Загружено только первые {photo_limit} фото.", "warning")
|
| 1523 |
break
|
| 1524 |
if photo and photo.filename:
|
| 1525 |
try:
|
| 1526 |
ext = os.path.splitext(photo.filename)[1].lower()
|
| 1527 |
if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
|
| 1528 |
-
logging.warning(f"Skipping non-image file upload during edit: {photo.filename}")
|
| 1529 |
flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")
|
| 1530 |
continue
|
| 1531 |
|
|
@@ -1533,16 +1544,13 @@ def admin():
|
|
| 1533 |
photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
|
| 1534 |
temp_path = os.path.join(uploads_dir, photo_filename)
|
| 1535 |
photo.save(temp_path)
|
| 1536 |
-
logging.info(f"Uploading new photo {photo_filename} to HF...")
|
| 1537 |
api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}",
|
| 1538 |
repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
|
| 1539 |
commit_message=f"Update photo for product {product_to_edit['name']}")
|
| 1540 |
new_photos_list.append(photo_filename)
|
| 1541 |
-
logging.info(f"New photo {photo_filename} uploaded successfully.")
|
| 1542 |
os.remove(temp_path)
|
| 1543 |
uploaded_count += 1
|
| 1544 |
except Exception as e:
|
| 1545 |
-
logging.error(f"Error uploading new photo {photo.filename}: {e}", exc_info=True)
|
| 1546 |
flash(f"Ошибка при загрузке нового фото {photo.filename}.", 'error')
|
| 1547 |
if os.path.exists(temp_path):
|
| 1548 |
try: os.remove(temp_path)
|
|
@@ -1551,13 +1559,11 @@ def admin():
|
|
| 1551 |
if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
|
| 1552 |
os.rmdir(uploads_dir)
|
| 1553 |
except OSError as e:
|
| 1554 |
-
|
| 1555 |
|
| 1556 |
if new_photos_list:
|
| 1557 |
-
logging.info(f"New photo list for product {product_to_edit['name']} generated.")
|
| 1558 |
old_photos = product_to_edit.get('photos', [])
|
| 1559 |
if old_photos:
|
| 1560 |
-
logging.info(f"Attempting to delete old photos: {old_photos}")
|
| 1561 |
try:
|
| 1562 |
api.delete_files(
|
| 1563 |
repo_id=REPO_ID,
|
|
@@ -1566,9 +1572,7 @@ def admin():
|
|
| 1566 |
token=HF_TOKEN_WRITE,
|
| 1567 |
commit_message=f"Delete old photos for product {product_to_edit['name']}"
|
| 1568 |
)
|
| 1569 |
-
logging.info(f"Old photos for product {product_to_edit['name']} deleted from HF.")
|
| 1570 |
except Exception as e:
|
| 1571 |
-
logging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True)
|
| 1572 |
flash("Не удалось удалить старые фотографии с сервера. Новые фото загружены.", "warning")
|
| 1573 |
product_to_edit['photos'] = new_photos_list
|
| 1574 |
flash("Фотографии товара успешно обновлены.", "success")
|
|
@@ -1577,63 +1581,47 @@ def admin():
|
|
| 1577 |
elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
|
| 1578 |
flash("HF_TOKEN (write) не настроен. Фотографии не были обновлены.", "warning")
|
| 1579 |
|
| 1580 |
-
data['products'] = products
|
| 1581 |
save_data(data)
|
| 1582 |
-
logging.info(f"Product '{original_name}' (ID {product_id}) updated to '{product_to_edit['name']}'.")
|
| 1583 |
flash(f"Товар '{product_to_edit['name']}' успешно обновлен.", 'success')
|
| 1584 |
|
| 1585 |
elif action == 'delete_product':
|
| 1586 |
product_id = request.form.get('product_id')
|
| 1587 |
-
|
| 1588 |
-
|
|
|
|
|
|
|
| 1589 |
return redirect(url_for('admin'))
|
| 1590 |
|
| 1591 |
-
|
| 1592 |
-
|
| 1593 |
-
if index_to_delete is not None:
|
| 1594 |
-
deleted_product = products.pop(index_to_delete)
|
| 1595 |
-
product_name = deleted_product.get('name', 'N/A')
|
| 1596 |
-
|
| 1597 |
-
photos_to_delete = deleted_product.get('photos', [])
|
| 1598 |
-
if photos_to_delete and HF_TOKEN_WRITE:
|
| 1599 |
-
logging.info(f"Attempting to delete photos for product '{product_name}' from HF: {photos_to_delete}")
|
| 1600 |
-
try:
|
| 1601 |
-
api = HfApi()
|
| 1602 |
-
api.delete_files(
|
| 1603 |
-
repo_id=REPO_ID,
|
| 1604 |
-
paths_in_repo=[f"photos/{p}" for p in photos_to_delete],
|
| 1605 |
-
repo_type="dataset",
|
| 1606 |
-
token=HF_TOKEN_WRITE,
|
| 1607 |
-
commit_message=f"Delete photos for deleted product {product_name}"
|
| 1608 |
-
)
|
| 1609 |
-
logging.info(f"Photos for product '{product_name}' deleted from HF.")
|
| 1610 |
-
except Exception as e:
|
| 1611 |
-
logging.error(f"Error deleting photos {photos_to_delete} for product '{product_name}' from HF: {e}", exc_info=True)
|
| 1612 |
-
flash(f"Не удалось удалить фото для товара '{product_name}' с сервера. Товар удален локально.", "warning")
|
| 1613 |
-
elif photos_to_delete and not HF_TOKEN_WRITE:
|
| 1614 |
-
logging.warning(f"HF_TOKEN (write) not set. Cannot delete photos {photos_to_delete} for deleted product '{product_name}'.")
|
| 1615 |
-
flash(f"Товар '{product_name}' удален локально, но фото не удалены с сервера (токен не задан).", "warning")
|
| 1616 |
-
|
| 1617 |
-
data['products'] = products
|
| 1618 |
-
save_data(data)
|
| 1619 |
-
logging.info(f"Product '{product_name}' (ID {product_id}) deleted.")
|
| 1620 |
-
flash(f"Товар '{product_name}' удален.", 'success')
|
| 1621 |
-
else:
|
| 1622 |
-
flash(f"Ошибка удаления: товар с ID '{product_id}' не найден.", 'error')
|
| 1623 |
-
logging.error(f"Invalid product ID '{product_id}' for deletion.")
|
| 1624 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1625 |
else:
|
| 1626 |
-
logging.warning(f"Received unknown admin action: {action}")
|
| 1627 |
flash(f"Неизвестное действие: {action}", 'warning')
|
| 1628 |
|
| 1629 |
return redirect(url_for('admin'))
|
| 1630 |
|
| 1631 |
except Exception as e:
|
| 1632 |
-
|
| 1633 |
-
flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'. Подробности в логе сервера.", 'error')
|
| 1634 |
return redirect(url_for('admin'))
|
| 1635 |
|
| 1636 |
-
|
| 1637 |
current_data = load_data()
|
| 1638 |
display_products = sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower())
|
| 1639 |
display_categories = sorted(current_data.get('categories', []))
|
|
@@ -1648,18 +1636,15 @@ def admin():
|
|
| 1648 |
|
| 1649 |
@app.route('/force_upload', methods=['POST'])
|
| 1650 |
def force_upload():
|
| 1651 |
-
logging.info("Forcing upload to Hugging Face...")
|
| 1652 |
try:
|
| 1653 |
upload_db_to_hf()
|
| 1654 |
flash("Данные успешно загружены на Hugging Face.", 'success')
|
| 1655 |
except Exception as e:
|
| 1656 |
-
logging.error(f"Error during forced upload: {e}", exc_info=True)
|
| 1657 |
flash(f"Ошибка при загрузке на Hugging Face: {e}", 'error')
|
| 1658 |
return redirect(url_for('admin'))
|
| 1659 |
|
| 1660 |
@app.route('/force_download', methods=['POST'])
|
| 1661 |
def force_download():
|
| 1662 |
-
logging.info("Forcing download from Hugging Face...")
|
| 1663 |
try:
|
| 1664 |
if download_db_from_hf():
|
| 1665 |
flash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success')
|
|
@@ -1667,25 +1652,18 @@ def force_download():
|
|
| 1667 |
else:
|
| 1668 |
flash("Не удалось скачать данные с Hugging Face после нескольких попыток. Проверьте логи.", 'error')
|
| 1669 |
except Exception as e:
|
| 1670 |
-
logging.error(f"Error during forced download: {e}", exc_info=True)
|
| 1671 |
flash(f"Ошибка при скачивании с Hugging Face: {e}", 'error')
|
| 1672 |
return redirect(url_for('admin'))
|
| 1673 |
|
| 1674 |
-
|
| 1675 |
-
|
| 1676 |
if __name__ == '__main__':
|
| 1677 |
-
logging.info("Application starting up. Performing initial data load/download...")
|
| 1678 |
download_db_from_hf()
|
| 1679 |
load_data()
|
| 1680 |
-
logging.info("Initial data load complete.")
|
| 1681 |
|
| 1682 |
if HF_TOKEN_WRITE:
|
| 1683 |
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
|
| 1684 |
backup_thread.start()
|
| 1685 |
-
logging.info("Periodic backup thread started.")
|
| 1686 |
else:
|
| 1687 |
-
|
| 1688 |
|
| 1689 |
port = int(os.environ.get('PORT', 7860))
|
| 1690 |
-
|
| 1691 |
-
app.run(debug=False, host='0.0.0.0', port=port)
|
|
|
|
|
|
|
|
|
|
| 1 |
from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify
|
| 2 |
import json
|
| 3 |
import os
|
|
|
|
| 4 |
import threading
|
| 5 |
import time
|
| 6 |
from datetime import datetime
|
|
|
|
| 17 |
app.secret_key = 'your_unique_secret_key_soola_cosmetics_67890_no_login'
|
| 18 |
DATA_FILE = 'data.json'
|
| 19 |
|
|
|
|
| 20 |
SYNC_FILES = [DATA_FILE]
|
| 21 |
|
| 22 |
REPO_ID = "Kgshop/balluu"
|
|
|
|
| 31 |
DOWNLOAD_RETRIES = 3
|
| 32 |
DOWNLOAD_DELAY = 5
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):
|
| 35 |
if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
|
| 36 |
+
return False
|
| 37 |
|
| 38 |
token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE
|
| 39 |
|
| 40 |
files_to_download = [specific_file] if specific_file else SYNC_FILES
|
|
|
|
| 41 |
all_successful = True
|
| 42 |
|
| 43 |
for file_name in files_to_download:
|
| 44 |
success = False
|
| 45 |
for attempt in range(retries + 1):
|
| 46 |
try:
|
|
|
|
| 47 |
local_path = hf_hub_download(
|
| 48 |
repo_id=REPO_ID,
|
| 49 |
filename=file_name,
|
|
|
|
| 54 |
force_download=True,
|
| 55 |
resume_download=False
|
| 56 |
)
|
|
|
|
| 57 |
success = True
|
| 58 |
break
|
| 59 |
except RepositoryNotFoundError:
|
|
|
|
| 60 |
return False
|
| 61 |
except HfHubHTTPError as e:
|
| 62 |
if e.response.status_code == 404:
|
|
|
|
| 63 |
if attempt == 0 and not os.path.exists(file_name):
|
| 64 |
try:
|
| 65 |
if file_name == DATA_FILE:
|
| 66 |
with open(file_name, 'w', encoding='utf-8') as f:
|
| 67 |
json.dump({'products': [], 'categories': [], 'orders': {}}, f)
|
|
|
|
| 68 |
except Exception as create_e:
|
| 69 |
+
pass
|
| 70 |
success = False
|
| 71 |
break
|
|
|
|
|
|
|
| 72 |
except requests.exceptions.RequestException as e:
|
| 73 |
+
pass
|
| 74 |
except Exception as e:
|
| 75 |
+
pass
|
| 76 |
|
| 77 |
if attempt < retries:
|
| 78 |
time.sleep(delay)
|
| 79 |
|
| 80 |
if not success:
|
|
|
|
| 81 |
all_successful = False
|
| 82 |
|
|
|
|
| 83 |
return all_successful
|
| 84 |
|
| 85 |
def upload_db_to_hf(specific_file=None):
|
| 86 |
if not HF_TOKEN_WRITE:
|
|
|
|
| 87 |
return
|
| 88 |
try:
|
| 89 |
api = HfApi()
|
| 90 |
files_to_upload = [specific_file] if specific_file else SYNC_FILES
|
|
|
|
| 91 |
|
| 92 |
for file_name in files_to_upload:
|
| 93 |
if os.path.exists(file_name):
|
|
|
|
| 100 |
token=HF_TOKEN_WRITE,
|
| 101 |
commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 102 |
)
|
|
|
|
| 103 |
except Exception as e:
|
| 104 |
+
pass
|
| 105 |
else:
|
| 106 |
+
pass
|
|
|
|
| 107 |
except Exception as e:
|
| 108 |
+
pass
|
| 109 |
|
| 110 |
def periodic_backup():
|
| 111 |
backup_interval = 1800
|
|
|
|
| 112 |
while True:
|
| 113 |
time.sleep(backup_interval)
|
|
|
|
| 114 |
upload_db_to_hf()
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
def load_data():
|
| 117 |
default_data = {'products': [], 'categories': [], 'orders': {}}
|
| 118 |
+
data = default_data
|
| 119 |
try:
|
| 120 |
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 121 |
data = json.load(file)
|
|
|
|
| 122 |
if not isinstance(data, dict):
|
|
|
|
| 123 |
raise FileNotFoundError
|
| 124 |
if 'products' not in data: data['products'] = []
|
| 125 |
if 'categories' not in data: data['categories'] = []
|
| 126 |
if 'orders' not in data: data['orders'] = {}
|
|
|
|
| 127 |
except FileNotFoundError:
|
| 128 |
+
pass
|
| 129 |
except json.JSONDecodeError:
|
| 130 |
+
pass
|
| 131 |
|
| 132 |
+
if data == default_data or not data.get('products'):
|
| 133 |
+
if download_db_from_hf(specific_file=DATA_FILE):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
try:
|
| 135 |
+
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 136 |
+
data = json.load(file)
|
| 137 |
+
if not isinstance(data, dict):
|
| 138 |
+
return default_data
|
| 139 |
+
if 'products' not in data: data['products'] = []
|
| 140 |
+
if 'categories' not in data: data['categories'] = []
|
| 141 |
+
if 'orders' not in data: data['orders'] = {}
|
| 142 |
+
except FileNotFoundError:
|
| 143 |
+
return default_data
|
| 144 |
+
except json.JSONDecodeError:
|
| 145 |
+
return default_data
|
| 146 |
+
except Exception as e:
|
| 147 |
+
return default_data
|
| 148 |
+
else:
|
| 149 |
+
if not os.path.exists(DATA_FILE):
|
| 150 |
+
try:
|
| 151 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 152 |
+
json.dump(default_data, f)
|
| 153 |
+
except Exception as create_e:
|
| 154 |
+
pass
|
| 155 |
+
|
| 156 |
+
for product in data['products']:
|
| 157 |
+
if 'id' not in product:
|
| 158 |
+
product['id'] = uuid.uuid4().hex
|
| 159 |
+
|
| 160 |
+
return data
|
| 161 |
|
| 162 |
def save_data(data):
|
| 163 |
try:
|
| 164 |
if not isinstance(data, dict):
|
|
|
|
| 165 |
return
|
| 166 |
if 'products' not in data: data['products'] = []
|
| 167 |
if 'categories' not in data: data['categories'] = []
|
|
|
|
| 169 |
|
| 170 |
with open(DATA_FILE, 'w', encoding='utf-8') as file:
|
| 171 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
|
|
|
| 172 |
upload_db_to_hf(specific_file=DATA_FILE)
|
| 173 |
except Exception as e:
|
| 174 |
+
pass
|
|
|
|
|
|
|
| 175 |
|
| 176 |
CATALOG_TEMPLATE = '''
|
| 177 |
<!DOCTYPE html>
|
|
|
|
| 210 |
.products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 20px; padding: 10px; }
|
| 211 |
@media (min-width: 600px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); } }
|
| 212 |
@media (min-width: 900px) { .products-grid { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); } }
|
| 213 |
+
|
| 214 |
.product { background: #fff; border-radius: 15px; padding: 0; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; height: 100%; border: 1px solid #FCE7F3;}
|
| 215 |
body.dark-mode .product { background: #412539; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); border-color: #59344f; }
|
| 216 |
.product:hover { transform: translateY(-5px) scale(1.02); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12); }
|
|
|
|
| 284 |
<i class="fas fa-moon"></i>
|
| 285 |
</button>
|
| 286 |
</div>
|
| 287 |
+
|
| 288 |
<div class="store-address">Наш адрес: {{ store_address }}</div>
|
| 289 |
+
|
| 290 |
<div class="filters-container">
|
| 291 |
<button class="category-filter active" data-category="all">Все категории</button>
|
| 292 |
{% for category in categories %}
|
| 293 |
<button class="category-filter" data-category="{{ category }}">{{ category }}</button>
|
| 294 |
{% endfor %}
|
| 295 |
</div>
|
| 296 |
+
|
| 297 |
<div class="search-container">
|
| 298 |
<input type="text" id="search-input" placeholder="Поиск по названию или описанию...">
|
| 299 |
</div>
|
| 300 |
+
|
| 301 |
<div class="products-grid" id="products-grid">
|
| 302 |
{% for product in products %}
|
| 303 |
<div class="product"
|
|
|
|
| 322 |
<p class="product-description">{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}</p>
|
| 323 |
</div>
|
| 324 |
<div class="product-actions">
|
| 325 |
+
<button class="product-button" onclick="openModalById('{{ product['id'] }}')">Подробнее</button>
|
| 326 |
+
<button class="product-button add-to-cart" onclick="openQuantityModalById('{{ product['id'] }}')">
|
| 327 |
<i class="fas fa-cart-plus"></i> В корзину
|
| 328 |
</button>
|
| 329 |
</div>
|
|
|
|
| 334 |
{% endif %}
|
| 335 |
</div>
|
| 336 |
</div>
|
| 337 |
+
|
| 338 |
<div id="productModal" class="modal">
|
| 339 |
<div class="modal-content">
|
| 340 |
<span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span>
|
| 341 |
<div id="modalContent">Загрузка...</div>
|
| 342 |
</div>
|
| 343 |
</div>
|
| 344 |
+
|
| 345 |
<div id="quantityModal" class="modal">
|
| 346 |
<div class="modal-content">
|
| 347 |
<span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">×</span>
|
|
|
|
| 353 |
<button class="product-button add-to-cart" onclick="confirmAddToCart()"><i class="fas fa-check"></i> Добавить в корзину</button>
|
| 354 |
</div>
|
| 355 |
</div>
|
| 356 |
+
|
| 357 |
<div id="cartModal" class="modal">
|
| 358 |
<div class="modal-content">
|
| 359 |
<span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span>
|
|
|
|
| 372 |
</div>
|
| 373 |
</div>
|
| 374 |
</div>
|
| 375 |
+
|
| 376 |
<button id="cart-button" onclick="openCartModal()" aria-label="Открыть корзину">
|
| 377 |
<i class="fas fa-shopping-cart"></i>
|
| 378 |
<span id="cart-count">0</span>
|
| 379 |
</button>
|
| 380 |
+
|
| 381 |
<div id="notification-placeholder"></div>
|
| 382 |
+
|
| 383 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
|
| 384 |
<script>
|
| 385 |
+
const productsData = {{ products|tojson }};
|
| 386 |
const repoId = '{{ repo_id }}';
|
| 387 |
const currencyCode = '{{ currency_code }}';
|
| 388 |
+
let selectedProductId = null;
|
| 389 |
let cart = JSON.parse(localStorage.getItem('soolaCart') || '[]');
|
| 390 |
+
|
| 391 |
function toggleTheme() {
|
| 392 |
document.body.classList.toggle('dark-mode');
|
| 393 |
const icon = document.querySelector('.theme-toggle i');
|
|
|
|
| 396 |
icon.classList.toggle('fa-sun', isDarkMode);
|
| 397 |
localStorage.setItem('soolaTheme', isDarkMode ? 'dark' : 'light');
|
| 398 |
}
|
| 399 |
+
|
| 400 |
function applyInitialTheme() {
|
| 401 |
const savedTheme = localStorage.getItem('soolaTheme');
|
| 402 |
if (savedTheme === 'dark') {
|
|
|
|
| 405 |
if (icon) icon.classList.replace('fa-moon', 'fa-sun');
|
| 406 |
}
|
| 407 |
}
|
| 408 |
+
|
| 409 |
+
function openModalById(productId) {
|
| 410 |
+
loadProductDetailsById(productId);
|
| 411 |
const modal = document.getElementById('productModal');
|
| 412 |
if (modal) {
|
| 413 |
modal.style.display = "block";
|
| 414 |
document.body.style.overflow = 'hidden';
|
| 415 |
}
|
| 416 |
}
|
| 417 |
+
|
| 418 |
function closeModal(modalId) {
|
| 419 |
const modal = document.getElementById(modalId);
|
| 420 |
if (modal) {
|
|
|
|
| 425 |
document.body.style.overflow = 'auto';
|
| 426 |
}
|
| 427 |
}
|
| 428 |
+
|
| 429 |
+
function loadProductDetailsById(productId) {
|
| 430 |
const modalContent = document.getElementById('modalContent');
|
| 431 |
if (!modalContent) return;
|
| 432 |
modalContent.innerHTML = '<p style="text-align:center; padding: 40px;">Загрузка...</p>';
|
| 433 |
+
fetch('/product/' + productId)
|
| 434 |
.then(response => {
|
| 435 |
if (!response.ok) throw new Error(`Ошибка ${response.status}: ${response.statusText}`);
|
| 436 |
return response.text();
|
|
|
|
| 444 |
modalContent.innerHTML = `<p style="color: red; text-align:center; padding: 40px;">Не удалось загрузить информацию о товаре. ${error.message}</p>`;
|
| 445 |
});
|
| 446 |
}
|
| 447 |
+
|
| 448 |
function initializeSwiper() {
|
| 449 |
const swiperContainer = document.querySelector('#productModal .swiper-container');
|
| 450 |
if (swiperContainer) {
|
|
|
|
| 460 |
});
|
| 461 |
}
|
| 462 |
}
|
| 463 |
+
|
| 464 |
+
function openQuantityModalById(productId) {
|
| 465 |
+
selectedProductId = productId;
|
| 466 |
+
const product = productsData.find(p => p.id === productId);
|
| 467 |
if (!product) {
|
| 468 |
+
console.error("Product not found for ID:", productId);
|
| 469 |
alert("Ошибка: товар не найден.");
|
| 470 |
return;
|
| 471 |
}
|
| 472 |
+
|
| 473 |
const colorSelect = document.getElementById('colorSelect');
|
| 474 |
const colorLabel = document.querySelector('label[for="colorSelect"]');
|
| 475 |
colorSelect.innerHTML = '';
|
| 476 |
+
|
| 477 |
const validColors = product.colors ? product.colors.filter(c => c && c.trim() !== "") : [];
|
| 478 |
+
|
| 479 |
if (validColors.length > 0) {
|
| 480 |
validColors.forEach(color => {
|
| 481 |
const option = document.createElement('option');
|
|
|
|
| 489 |
colorSelect.style.display = 'none';
|
| 490 |
if(colorLabel) colorLabel.style.display = 'none';
|
| 491 |
}
|
| 492 |
+
|
| 493 |
document.getElementById('quantityInput').value = 1;
|
| 494 |
const modal = document.getElementById('quantityModal');
|
| 495 |
if(modal) {
|
|
|
|
| 497 |
document.body.style.overflow = 'hidden';
|
| 498 |
}
|
| 499 |
}
|
| 500 |
+
|
| 501 |
function confirmAddToCart() {
|
| 502 |
+
if (selectedProductId === null) return;
|
| 503 |
+
|
| 504 |
const quantityInput = document.getElementById('quantityInput');
|
| 505 |
const quantity = parseInt(quantityInput.value);
|
| 506 |
const colorSelect = document.getElementById('colorSelect');
|
| 507 |
const color = colorSelect.style.display !== 'none' && colorSelect.value ? colorSelect.value : 'N/A';
|
| 508 |
+
|
| 509 |
if (isNaN(quantity) || quantity <= 0) {
|
| 510 |
alert("Пожалуйста, укажите корректное количество (больше 0).");
|
| 511 |
quantityInput.focus();
|
| 512 |
return;
|
| 513 |
}
|
| 514 |
+
|
| 515 |
+
const product = productsData.find(p => p.id === selectedProductId);
|
| 516 |
if (!product) {
|
| 517 |
alert("Ошибка добавления: товар не найден.");
|
| 518 |
return;
|
| 519 |
}
|
| 520 |
+
|
| 521 |
+
const cartItemId = `${product.id}-${color}`;
|
| 522 |
const existingItemIndex = cart.findIndex(item => item.id === cartItemId);
|
| 523 |
+
|
| 524 |
if (existingItemIndex > -1) {
|
| 525 |
cart[existingItemIndex].quantity += quantity;
|
| 526 |
} else {
|
| 527 |
cart.push({
|
| 528 |
id: cartItemId,
|
| 529 |
+
productId: product.id,
|
| 530 |
name: product.name,
|
| 531 |
price: product.price,
|
| 532 |
photo: product.photos && product.photos.length > 0 ? product.photos[0] : null,
|
|
|
|
| 534 |
color: color
|
| 535 |
});
|
| 536 |
}
|
| 537 |
+
|
| 538 |
localStorage.setItem('soolaCart', JSON.stringify(cart));
|
| 539 |
closeModal('quantityModal');
|
| 540 |
updateCartButton();
|
| 541 |
showNotification(`${product.name} добавлен в корзину!`);
|
| 542 |
}
|
| 543 |
+
|
| 544 |
function updateCartButton() {
|
| 545 |
const cartCountElement = document.getElementById('cart-count');
|
| 546 |
const cartButton = document.getElementById('cart-button');
|
| 547 |
if (!cartCountElement || !cartButton) return;
|
| 548 |
+
|
| 549 |
let totalItems = 0;
|
| 550 |
cart.forEach(item => { totalItems += item.quantity; });
|
| 551 |
+
|
| 552 |
if (totalItems > 0) {
|
| 553 |
cartCountElement.textContent = totalItems;
|
| 554 |
cartButton.style.display = 'flex';
|
|
|
|
| 557 |
cartButton.style.display = 'none';
|
| 558 |
}
|
| 559 |
}
|
| 560 |
+
|
| 561 |
function openCartModal() {
|
| 562 |
const cartContent = document.getElementById('cartContent');
|
| 563 |
const cartTotalElement = document.getElementById('cartTotal');
|
| 564 |
if (!cartContent || !cartTotalElement) return;
|
| 565 |
+
|
| 566 |
let total = 0;
|
| 567 |
+
|
| 568 |
if (cart.length === 0) {
|
| 569 |
cartContent.innerHTML = '<p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p>';
|
| 570 |
cartTotalElement.textContent = '0.00';
|
|
|
|
| 576 |
? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}`
|
| 577 |
: 'https://via.placeholder.com/60x60.png?text=N/A';
|
| 578 |
const colorText = item.color !== 'N/A' ? ` (Цвет: ${item.color})` : '';
|
| 579 |
+
|
| 580 |
return `
|
| 581 |
<div class="cart-item">
|
| 582 |
<img src="${photoUrl}" alt="${item.name}">
|
|
|
|
| 597 |
document.body.style.overflow = 'hidden';
|
| 598 |
}
|
| 599 |
}
|
| 600 |
+
|
| 601 |
function removeFromCart(itemId) {
|
| 602 |
cart = cart.filter(item => item.id !== itemId);
|
| 603 |
localStorage.setItem('soolaCart', JSON.stringify(cart));
|
| 604 |
openCartModal();
|
| 605 |
updateCartButton();
|
| 606 |
}
|
| 607 |
+
|
| 608 |
function clearCart() {
|
| 609 |
if (confirm("Вы уверены, что хотите очистить корзину?")) {
|
| 610 |
cart = [];
|
|
|
|
| 613 |
updateCartButton();
|
| 614 |
}
|
| 615 |
}
|
| 616 |
+
|
| 617 |
function formulateOrder() {
|
| 618 |
if (cart.length === 0) {
|
| 619 |
alert("Корзина пуста! Добавьте товары перед формированием заказа.");
|
| 620 |
return;
|
| 621 |
}
|
| 622 |
+
|
| 623 |
const orderData = {
|
| 624 |
cart: cart
|
| 625 |
};
|
| 626 |
+
|
| 627 |
const formulateButton = document.querySelector('.formulate-order-button');
|
| 628 |
if (formulateButton) formulateButton.disabled = true;
|
| 629 |
+
|
| 630 |
showNotification("Формируем заказ...", 5000);
|
| 631 |
+
|
| 632 |
fetch('/create_order', {
|
| 633 |
method: 'POST',
|
| 634 |
headers: { 'Content-Type': 'application/json' },
|
|
|
|
| 657 |
if (formulateButton) formulateButton.disabled = false;
|
| 658 |
});
|
| 659 |
}
|
| 660 |
+
|
| 661 |
+
|
| 662 |
function filterProducts() {
|
| 663 |
const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();
|
| 664 |
const activeCategoryButton = document.querySelector('.category-filter.active');
|
| 665 |
const activeCategory = activeCategoryButton ? activeCategoryButton.dataset.category : 'all';
|
| 666 |
const grid = document.getElementById('products-grid');
|
| 667 |
let visibleProducts = 0;
|
| 668 |
+
|
| 669 |
const existingNoResults = grid.querySelector('.no-results-message');
|
| 670 |
if (existingNoResults) existingNoResults.remove();
|
| 671 |
+
|
| 672 |
document.querySelectorAll('.products-grid .product').forEach(productElement => {
|
| 673 |
const name = productElement.getAttribute('data-name');
|
| 674 |
const description = productElement.getAttribute('data-description');
|
| 675 |
const category = productElement.getAttribute('data-category');
|
| 676 |
+
|
| 677 |
const matchesSearch = !searchTerm || name.includes(searchTerm) || description.includes(searchTerm);
|
| 678 |
const matchesCategory = activeCategory === 'all' || category === activeCategory;
|
| 679 |
+
|
| 680 |
if (matchesSearch && matchesCategory) {
|
| 681 |
productElement.style.display = 'flex';
|
| 682 |
visibleProducts++;
|
|
|
|
| 684 |
productElement.style.display = 'none';
|
| 685 |
}
|
| 686 |
});
|
| 687 |
+
|
| 688 |
+
if (visibleProducts === 0 && productsData.length > 0) {
|
| 689 |
const p = document.createElement('p');
|
| 690 |
p.className = 'no-results-message';
|
| 691 |
p.textContent = 'По вашему запросу товары не найдены.';
|
| 692 |
grid.appendChild(p);
|
| 693 |
+
} else if (productsData.length === 0 && !grid.querySelector('.no-results-message')) {
|
| 694 |
const p = document.createElement('p');
|
| 695 |
p.className = 'no-results-message';
|
| 696 |
p.textContent = 'Товары пока не добавлены.';
|
| 697 |
grid.appendChild(p);
|
| 698 |
}
|
| 699 |
}
|
| 700 |
+
|
| 701 |
function setupFilters() {
|
| 702 |
const searchInput = document.getElementById('search-input');
|
| 703 |
const categoryFilters = document.querySelectorAll('.category-filter');
|
| 704 |
+
|
| 705 |
if(searchInput) searchInput.addEventListener('input', filterProducts);
|
| 706 |
+
|
| 707 |
categoryFilters.forEach(filter => {
|
| 708 |
filter.addEventListener('click', function() {
|
| 709 |
categoryFilters.forEach(f => f.classList.remove('active'));
|
|
|
|
| 713 |
});
|
| 714 |
filterProducts();
|
| 715 |
}
|
| 716 |
+
|
| 717 |
function showNotification(message, duration = 3000) {
|
| 718 |
const placeholder = document.getElementById('notification-placeholder');
|
| 719 |
if (!placeholder) {
|
|
|
|
| 727 |
document.body.appendChild(newPlaceholder);
|
| 728 |
placeholder = newPlaceholder;
|
| 729 |
}
|
| 730 |
+
|
| 731 |
+
|
| 732 |
const notification = document.createElement('div');
|
| 733 |
notification.className = 'notification';
|
| 734 |
notification.textContent = message;
|
| 735 |
placeholder.appendChild(notification);
|
| 736 |
+
|
| 737 |
void notification.offsetWidth;
|
| 738 |
+
|
| 739 |
notification.classList.add('show');
|
| 740 |
+
|
| 741 |
setTimeout(() => {
|
| 742 |
notification.classList.remove('show');
|
| 743 |
notification.addEventListener('transitionend', () => notification.remove());
|
| 744 |
}, duration);
|
| 745 |
}
|
| 746 |
+
|
| 747 |
document.addEventListener('DOMContentLoaded', () => {
|
| 748 |
applyInitialTheme();
|
| 749 |
updateCartButton();
|
| 750 |
setupFilters();
|
| 751 |
+
|
| 752 |
window.addEventListener('click', function(event) {
|
| 753 |
if (event.target.classList.contains('modal')) {
|
| 754 |
closeModal(event.target.id);
|
| 755 |
}
|
| 756 |
});
|
| 757 |
+
|
| 758 |
window.addEventListener('keydown', function(event) {
|
| 759 |
if (event.key === 'Escape') {
|
| 760 |
document.querySelectorAll('.modal[style*="display: block"]').forEach(modal => {
|
|
|
|
| 763 |
}
|
| 764 |
});
|
| 765 |
});
|
| 766 |
+
|
| 767 |
</script>
|
| 768 |
</body>
|
| 769 |
</html>
|
|
|
|
| 796 |
<div class="swiper-button-prev" style="color: #F472B6;"></div>
|
| 797 |
{% endif %}
|
| 798 |
</div>
|
| 799 |
+
|
| 800 |
<div style="margin-top: 20px; font-size: 1rem; line-height: 1.7;">
|
| 801 |
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
|
| 802 |
<p style="font-size: 1.2rem; font-weight: bold; color: #DB2777;"><strong>Цена:</strong> {{ "%.2f"|format(product['price']) }} {{ currency_code }}</p>
|
|
|
|
| 851 |
{% if order %}
|
| 852 |
<h1><i class="fas fa-receipt"></i> Ваш Заказ №{{ order.id }}</h1>
|
| 853 |
<p class="order-meta">Дата создания: {{ order.created_at }}</p>
|
| 854 |
+
|
| 855 |
<h2><i class="fas fa-shopping-bag"></i> Товары в заказе</h2>
|
| 856 |
<div id="orderItems">
|
| 857 |
{% for item in order.cart %}
|
|
|
|
| 867 |
</div>
|
| 868 |
{% endfor %}
|
| 869 |
</div>
|
| 870 |
+
|
| 871 |
<div class="order-summary">
|
| 872 |
<p>Общая с��мма товаров: <strong>{{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>
|
| 873 |
<p><strong>ИТОГО К ОПЛАТЕ: {{ "%.2f"|format(order.total_price) }} {{ currency_code }}</strong></p>
|
| 874 |
</div>
|
| 875 |
+
|
| 876 |
<div class="customer-info">
|
| 877 |
<h2><i class="fas fa-info-circle"></i> Статус заказа</h2>
|
| 878 |
<p>Этот заказ был оформлен без входа в систему.</p>
|
| 879 |
<p>Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.</p>
|
| 880 |
</div>
|
| 881 |
+
|
| 882 |
<div class="actions">
|
| 883 |
<button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> Отправить заказ</button>
|
| 884 |
</div>
|
| 885 |
+
|
| 886 |
<a href="{{ url_for('catalog') }}" class="catalog-link">← Вернуться в каталог</a>
|
| 887 |
+
|
| 888 |
<script>
|
| 889 |
function sendOrderViaWhatsApp() {
|
| 890 |
const orderId = '{{ order.id }}';
|
| 891 |
const orderUrl = `{{ request.url }}`;
|
| 892 |
const whatsappNumber = "996703550150";
|
| 893 |
+
|
| 894 |
let message = `Здравствуйте! Хочу подтвердить свой заказ на Brand_Baaluu:%0A%0A`;
|
| 895 |
message += `*Номер заказа:* ${orderId}%0A`;
|
| 896 |
message += `*Ссылка на заказ:* ${encodeURIComponent(orderUrl)}%0A%0A`;
|
| 897 |
message += `Пожалуйста, свяжитесь со мной для уточнения деталей оплаты и доставки.`;
|
| 898 |
+
|
| 899 |
const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${message}`;
|
| 900 |
window.open(whatsappUrl, '_blank');
|
| 901 |
}
|
| 902 |
</script>
|
| 903 |
+
|
| 904 |
{% else %}
|
| 905 |
<h1 style="color: #c53030;"><i class="fas fa-exclamation-triangle"></i> Ошибка</h1>
|
| 906 |
<p class="not-found">Заказ с таким ID не найден.</p>
|
|
|
|
| 992 |
</div>
|
| 993 |
<a href="{{ url_for('catalog') }}" class="button" style="background-color: #EC4899;"><i class="fas fa-store"></i> Перейти в каталог</a>
|
| 994 |
</div>
|
| 995 |
+
|
| 996 |
+
|
| 997 |
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 998 |
{% if messages %}
|
| 999 |
{% for category, message in messages %}
|
|
|
|
| 1001 |
{% endfor %}
|
| 1002 |
{% endif %}
|
| 1003 |
{% endwith %}
|
| 1004 |
+
|
| 1005 |
<div class="section">
|
| 1006 |
<h2><i class="fas fa-sync-alt"></i> Синхронизация с Датацентром</h2>
|
| 1007 |
<div class="sync-buttons">
|
|
|
|
| 1014 |
</div>
|
| 1015 |
<p style="font-size: 0.85rem; color: #a0aec0;">Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.</p>
|
| 1016 |
</div>
|
| 1017 |
+
|
| 1018 |
<div class="flex-container">
|
| 1019 |
<div class="flex-item">
|
| 1020 |
<div class="section">
|
|
|
|
| 1030 |
</form>
|
| 1031 |
</div>
|
| 1032 |
</details>
|
| 1033 |
+
|
| 1034 |
<h3>Существующие категории:</h3>
|
| 1035 |
{% if categories %}
|
| 1036 |
<div class="item-list">
|
|
|
|
| 1050 |
{% endif %}
|
| 1051 |
</div>
|
| 1052 |
</div>
|
| 1053 |
+
|
| 1054 |
<div class="flex-item">
|
| 1055 |
<div class="section">
|
| 1056 |
<h2><i class="fas fa-info-circle"></i> Информация</h2>
|
|
|
|
| 1059 |
</div>
|
| 1060 |
</div>
|
| 1061 |
</div>
|
| 1062 |
+
|
| 1063 |
<div class="section">
|
| 1064 |
<h2><i class="fas fa-box-open"></i> Управление товарами</h2>
|
| 1065 |
<details>
|
|
|
|
| 1104 |
</form>
|
| 1105 |
</div>
|
| 1106 |
</details>
|
| 1107 |
+
|
| 1108 |
<h3>Список товаров:</h3>
|
| 1109 |
{% if products %}
|
| 1110 |
<div class="item-list">
|
|
|
|
| 1142 |
{% endif %}
|
| 1143 |
</div>
|
| 1144 |
</div>
|
| 1145 |
+
|
| 1146 |
<div class="item-actions">
|
| 1147 |
+
<button type="button" class="button" onclick="toggleEditForm('edit-form-{{ product['id'] }}')"><i class="fas fa-edit"></i> Редактировать</button>
|
| 1148 |
<form method="POST" style="margin:0;" onsubmit="return confirm('Вы уверены, что хотите удалить товар \'{{ product['name'] }}\'?');">
|
| 1149 |
<input type="hidden" name="action" value="delete_product">
|
| 1150 |
+
<input type="hidden" name="product_id" value="{{ product['id'] }}">
|
| 1151 |
<button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button>
|
| 1152 |
</form>
|
| 1153 |
</div>
|
| 1154 |
+
|
| 1155 |
+
<div id="edit-form-{{ product['id'] }}" class="edit-form-container">
|
| 1156 |
<h4><i class="fas fa-edit"></i> Редактирование: {{ product['name'] }}</h4>
|
| 1157 |
<form method="POST" enctype="multipart/form-data">
|
| 1158 |
<input type="hidden" name="action" value="edit_product">
|
| 1159 |
+
<input type="hidden" name="product_id" value="{{ product['id'] }}">
|
| 1160 |
<label>Название *:</label>
|
| 1161 |
<input type="text" name="name" value="{{ product['name'] }}" required>
|
| 1162 |
<label>Цена ({{ currency_code }}) *:</label>
|
|
|
|
| 1181 |
</div>
|
| 1182 |
{% endif %}
|
| 1183 |
<label>Цвета/Варианты:</label>
|
| 1184 |
+
<div id="edit-color-inputs-{{ product['id'] }}">
|
| 1185 |
{% set current_colors = product.get('colors', []) %}
|
| 1186 |
{% if current_colors and current_colors|select('ne', '')|list|length > 0 %}
|
| 1187 |
{% for color in current_colors %}
|
|
|
|
| 1199 |
</div>
|
| 1200 |
{% endif %}
|
| 1201 |
</div>
|
| 1202 |
+
<button type="button" class="button add-color-btn" style="margin-top: 5px;" onclick="addColorInput('edit-color-inputs-{{ product['id'] }}')"><i class="fas fa-palette"></i> Добавить поле для цвета</button>
|
| 1203 |
<br>
|
| 1204 |
<div style="margin-top: 15px;">
|
| 1205 |
+
<input type="checkbox" id="edit_in_stock_{{ product['id'] }}" name="in_stock" {% if product.get('in_stock', True) %}checked{% endif %}>
|
| 1206 |
+
<label for="edit_in_stock_{{ product['id'] }}" class="inline-label">В наличии</label>
|
| 1207 |
</div>
|
| 1208 |
<div style="margin-top: 5px;">
|
| 1209 |
+
<input type="checkbox" id="edit_is_top_{{ product['id'] }}" name="is_top" {% if product.get('is_top', False) %}checked{% endif %}>
|
| 1210 |
+
<label for="edit_is_top_{{ product['id'] }}" class="inline-label">Топ товар</label>
|
| 1211 |
</div>
|
| 1212 |
<br>
|
| 1213 |
<button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Сохранить изменения</button>
|
|
|
|
| 1220 |
<p>Товаров пока нет.</p>
|
| 1221 |
{% endif %}
|
| 1222 |
</div>
|
| 1223 |
+
|
| 1224 |
</div>
|
| 1225 |
+
|
| 1226 |
<script>
|
| 1227 |
function toggleEditForm(formId) {
|
| 1228 |
const formContainer = document.getElementById(formId);
|
|
|
|
| 1230 |
formContainer.style.display = formContainer.style.display === 'none' || formContainer.style.display === '' ? 'block' : 'none';
|
| 1231 |
}
|
| 1232 |
}
|
| 1233 |
+
|
| 1234 |
function addColorInput(containerId) {
|
| 1235 |
const container = document.getElementById(containerId);
|
| 1236 |
if (container) {
|
|
|
|
| 1247 |
}
|
| 1248 |
}
|
| 1249 |
}
|
| 1250 |
+
|
| 1251 |
function removeColorInput(button) {
|
| 1252 |
const group = button.closest('.color-input-group');
|
| 1253 |
if (group) {
|
| 1254 |
const container = group.parentNode;
|
| 1255 |
group.remove();
|
| 1256 |
+
|
| 1257 |
if (container && container.children.length === 0) {
|
| 1258 |
const placeholderGroup = document.createElement('div');
|
| 1259 |
placeholderGroup.className = 'color-input-group';
|
|
|
|
| 1272 |
</html>
|
| 1273 |
'''
|
| 1274 |
|
|
|
|
|
|
|
| 1275 |
@app.route('/')
|
| 1276 |
def catalog():
|
| 1277 |
data = load_data()
|
| 1278 |
all_products = data.get('products', [])
|
|
|
|
| 1279 |
|
| 1280 |
products_in_stock = [p for p in all_products if p.get('in_stock', True)]
|
| 1281 |
products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
|
| 1282 |
|
| 1283 |
+
categories = sorted(data.get('categories', []))
|
| 1284 |
+
|
| 1285 |
return render_template_string(
|
| 1286 |
CATALOG_TEMPLATE,
|
| 1287 |
products=products_sorted,
|
|
|
|
| 1291 |
currency_code=CURRENCY_CODE
|
| 1292 |
)
|
| 1293 |
|
| 1294 |
+
@app.route('/product/<product_id>')
|
| 1295 |
+
def product_detail(product_id):
|
| 1296 |
data = load_data()
|
| 1297 |
all_products = data.get('products', [])
|
| 1298 |
+
|
| 1299 |
+
product = next((p for p in all_products if p.get('id') == product_id and p.get('in_stock', True)), None)
|
| 1300 |
|
| 1301 |
+
if product is None:
|
|
|
|
|
|
|
|
|
|
| 1302 |
return "Товар не найден или отсутствует в наличии.", 404
|
| 1303 |
|
| 1304 |
return render_template_string(
|
|
|
|
| 1313 |
order_data = request.get_json()
|
| 1314 |
|
| 1315 |
if not order_data or 'cart' not in order_data or not order_data['cart']:
|
|
|
|
| 1316 |
return jsonify({"error": "Корзина пуста или не передана."}), 400
|
| 1317 |
|
| 1318 |
cart_items = order_data['cart']
|
|
|
|
| 1321 |
processed_cart = []
|
| 1322 |
for item in cart_items:
|
| 1323 |
if not all(k in item for k in ('name', 'price', 'quantity')):
|
|
|
|
| 1324 |
return jsonify({"error": "Неверный формат товара в корзине."}), 400
|
| 1325 |
try:
|
| 1326 |
price = float(item['price'])
|
|
|
|
| 1337 |
"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"
|
| 1338 |
})
|
| 1339 |
except (ValueError, TypeError) as e:
|
|
|
|
| 1340 |
return jsonify({"error": "Неверная цена или количество в товаре."}), 400
|
| 1341 |
|
| 1342 |
order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}"
|
|
|
|
| 1358 |
|
| 1359 |
data['orders'][order_id] = new_order
|
| 1360 |
save_data(data)
|
|
|
|
| 1361 |
return jsonify({"order_id": order_id}), 201
|
| 1362 |
|
| 1363 |
except Exception as e:
|
|
|
|
| 1364 |
return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500
|
| 1365 |
|
| 1366 |
@app.route('/order/<order_id>')
|
|
|
|
| 1368 |
data = load_data()
|
| 1369 |
order = data.get('orders', {}).get(order_id)
|
| 1370 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1371 |
return render_template_string(ORDER_TEMPLATE,
|
| 1372 |
order=order,
|
| 1373 |
repo_id=REPO_ID,
|
|
|
|
| 1383 |
|
| 1384 |
if request.method == 'POST':
|
| 1385 |
action = request.form.get('action')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1386 |
|
| 1387 |
try:
|
| 1388 |
if action == 'add_category':
|
|
|
|
| 1391 |
categories.append(category_name)
|
| 1392 |
data['categories'] = categories
|
| 1393 |
save_data(data)
|
|
|
|
| 1394 |
flash(f"Категория '{category_name}' успешно добавлена.", 'success')
|
| 1395 |
elif not category_name:
|
|
|
|
| 1396 |
flash("Название категории не может быть пустым.", 'error')
|
| 1397 |
else:
|
|
|
|
| 1398 |
flash(f"Категория '{category_name}' уже существует.", 'error')
|
| 1399 |
|
| 1400 |
elif action == 'delete_category':
|
|
|
|
| 1409 |
data['categories'] = categories
|
| 1410 |
data['products'] = products
|
| 1411 |
save_data(data)
|
|
|
|
| 1412 |
flash(f"Категория '{category_to_delete}' удалена. {updated_count} товаров обновлено.", 'success')
|
| 1413 |
else:
|
|
|
|
| 1414 |
flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error')
|
| 1415 |
|
| 1416 |
elif action == 'add_product':
|
|
|
|
| 1443 |
uploaded_count = 0
|
| 1444 |
for photo in photos_files:
|
| 1445 |
if uploaded_count >= photo_limit:
|
|
|
|
| 1446 |
flash(f"Загружено только первые {photo_limit} фото.", "warning")
|
| 1447 |
break
|
| 1448 |
if photo and photo.filename:
|
| 1449 |
try:
|
| 1450 |
ext = os.path.splitext(photo.filename)[1].lower()
|
| 1451 |
if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
|
|
|
|
| 1452 |
flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")
|
| 1453 |
continue
|
| 1454 |
|
|
|
|
| 1456 |
photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
|
| 1457 |
temp_path = os.path.join(uploads_dir, photo_filename)
|
| 1458 |
photo.save(temp_path)
|
|
|
|
| 1459 |
api.upload_file(
|
| 1460 |
path_or_fileobj=temp_path,
|
| 1461 |
path_in_repo=f"photos/{photo_filename}",
|
|
|
|
| 1465 |
commit_message=f"Add photo for product {name}"
|
| 1466 |
)
|
| 1467 |
photos_list.append(photo_filename)
|
|
|
|
| 1468 |
os.remove(temp_path)
|
| 1469 |
uploaded_count += 1
|
| 1470 |
except Exception as e:
|
|
|
|
| 1471 |
flash(f"Ошибка при загрузке фото {photo.filename}.", 'error')
|
| 1472 |
if os.path.exists(temp_path):
|
| 1473 |
try: os.remove(temp_path)
|
| 1474 |
except OSError: pass
|
| 1475 |
elif photo and not photo.filename:
|
| 1476 |
+
pass
|
| 1477 |
try:
|
| 1478 |
if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
|
| 1479 |
os.rmdir(uploads_dir)
|
| 1480 |
except OSError as e:
|
| 1481 |
+
pass
|
| 1482 |
elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
|
| 1483 |
+
flash("HF_TOKEN (for writing) не настроен. Фотографии не были загружены.", "warning")
|
| 1484 |
|
| 1485 |
|
| 1486 |
new_product = {
|
|
|
|
| 1493 |
products.append(new_product)
|
| 1494 |
data['products'] = products
|
| 1495 |
save_data(data)
|
|
|
|
| 1496 |
flash(f"Товар '{name}' успешно добавлен.", 'success')
|
| 1497 |
|
| 1498 |
elif action == 'edit_product':
|
| 1499 |
product_id = request.form.get('product_id')
|
| 1500 |
+
|
|
|
|
|
|
|
|
|
|
| 1501 |
product_to_edit = next((p for p in products if p.get('id') == product_id), None)
|
| 1502 |
+
if product_to_edit is None:
|
|
|
|
| 1503 |
flash(f"Ошибка редактирования: товар с ID '{product_id}' не найден.", 'error')
|
|
|
|
| 1504 |
return redirect(url_for('admin'))
|
| 1505 |
+
|
| 1506 |
original_name = product_to_edit.get('name', 'N/A')
|
| 1507 |
+
|
| 1508 |
product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip()
|
| 1509 |
price_str = request.form.get('price', str(product_to_edit['price'])).replace(',', '.')
|
| 1510 |
product_to_edit['description'] = request.form.get('description', product_to_edit.get('description', '')).strip()
|
|
|
|
| 1519 |
if price < 0: price = 0
|
| 1520 |
product_to_edit['price'] = price
|
| 1521 |
except ValueError:
|
|
|
|
| 1522 |
flash(f"Неверный формат цены для товара '{original_name}'. Цена не изменена.", 'warning')
|
| 1523 |
|
| 1524 |
photos_files = request.files.getlist('photos')
|
|
|
|
| 1529 |
new_photos_list = []
|
| 1530 |
photo_limit = 10
|
| 1531 |
uploaded_count = 0
|
|
|
|
| 1532 |
for photo in photos_files:
|
| 1533 |
if uploaded_count >= photo_limit:
|
|
|
|
| 1534 |
flash(f"Загружено только первые {photo_limit} фото.", "warning")
|
| 1535 |
break
|
| 1536 |
if photo and photo.filename:
|
| 1537 |
try:
|
| 1538 |
ext = os.path.splitext(photo.filename)[1].lower()
|
| 1539 |
if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
|
|
|
|
| 1540 |
flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")
|
| 1541 |
continue
|
| 1542 |
|
|
|
|
| 1544 |
photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
|
| 1545 |
temp_path = os.path.join(uploads_dir, photo_filename)
|
| 1546 |
photo.save(temp_path)
|
|
|
|
| 1547 |
api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}",
|
| 1548 |
repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
|
| 1549 |
commit_message=f"Update photo for product {product_to_edit['name']}")
|
| 1550 |
new_photos_list.append(photo_filename)
|
|
|
|
| 1551 |
os.remove(temp_path)
|
| 1552 |
uploaded_count += 1
|
| 1553 |
except Exception as e:
|
|
|
|
| 1554 |
flash(f"Ошибка при загрузке нового фото {photo.filename}.", 'error')
|
| 1555 |
if os.path.exists(temp_path):
|
| 1556 |
try: os.remove(temp_path)
|
|
|
|
| 1559 |
if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
|
| 1560 |
os.rmdir(uploads_dir)
|
| 1561 |
except OSError as e:
|
| 1562 |
+
pass
|
| 1563 |
|
| 1564 |
if new_photos_list:
|
|
|
|
| 1565 |
old_photos = product_to_edit.get('photos', [])
|
| 1566 |
if old_photos:
|
|
|
|
| 1567 |
try:
|
| 1568 |
api.delete_files(
|
| 1569 |
repo_id=REPO_ID,
|
|
|
|
| 1572 |
token=HF_TOKEN_WRITE,
|
| 1573 |
commit_message=f"Delete old photos for product {product_to_edit['name']}"
|
| 1574 |
)
|
|
|
|
| 1575 |
except Exception as e:
|
|
|
|
| 1576 |
flash("Не удалось удалить старые фотографии с сервера. Новые фото загружены.", "warning")
|
| 1577 |
product_to_edit['photos'] = new_photos_list
|
| 1578 |
flash("Фотографии товара успешно обновлены.", "success")
|
|
|
|
| 1581 |
elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
|
| 1582 |
flash("HF_TOKEN (write) не настроен. Фотографии не были обновлены.", "warning")
|
| 1583 |
|
|
|
|
| 1584 |
save_data(data)
|
|
|
|
| 1585 |
flash(f"Товар '{product_to_edit['name']}' успешно обновлен.", 'success')
|
| 1586 |
|
| 1587 |
elif action == 'delete_product':
|
| 1588 |
product_id = request.form.get('product_id')
|
| 1589 |
+
|
| 1590 |
+
deleted_product = next((p for p in products if p.get('id') == product_id), None)
|
| 1591 |
+
if deleted_product is None:
|
| 1592 |
+
flash(f"Ошибка удаления: товар с ID '{product_id}' не найден.", 'error')
|
| 1593 |
return redirect(url_for('admin'))
|
| 1594 |
|
| 1595 |
+
product_name = deleted_product.get('name', 'N/A')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1596 |
|
| 1597 |
+
photos_to_delete = deleted_product.get('photos', [])
|
| 1598 |
+
if photos_to_delete and HF_TOKEN_WRITE:
|
| 1599 |
+
try:
|
| 1600 |
+
api = HfApi()
|
| 1601 |
+
api.delete_files(
|
| 1602 |
+
repo_id=REPO_ID,
|
| 1603 |
+
paths_in_repo=[f"photos/{p}" for p in photos_to_delete],
|
| 1604 |
+
repo_type="dataset",
|
| 1605 |
+
token=HF_TOKEN_WRITE,
|
| 1606 |
+
commit_message=f"Delete photos for deleted product {product_name}"
|
| 1607 |
+
)
|
| 1608 |
+
except Exception as e:
|
| 1609 |
+
flash(f"Не удалось удалить фото для товара '{product_name}' с сервера. Товар удален локально.", "warning")
|
| 1610 |
+
elif photos_to_delete and not HF_TOKEN_WRITE:
|
| 1611 |
+
flash(f"Товар '{product_name}' удален локально, но фото не удалены с сервера (токен не задан).", "warning")
|
| 1612 |
+
|
| 1613 |
+
data['products'] = [p for p in products if p.get('id') != product_id]
|
| 1614 |
+
save_data(data)
|
| 1615 |
+
flash(f"Товар '{product_name}' удален.", 'success')
|
| 1616 |
else:
|
|
|
|
| 1617 |
flash(f"Неизвестное действие: {action}", 'warning')
|
| 1618 |
|
| 1619 |
return redirect(url_for('admin'))
|
| 1620 |
|
| 1621 |
except Exception as e:
|
| 1622 |
+
flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'.", 'error')
|
|
|
|
| 1623 |
return redirect(url_for('admin'))
|
| 1624 |
|
|
|
|
| 1625 |
current_data = load_data()
|
| 1626 |
display_products = sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower())
|
| 1627 |
display_categories = sorted(current_data.get('categories', []))
|
|
|
|
| 1636 |
|
| 1637 |
@app.route('/force_upload', methods=['POST'])
|
| 1638 |
def force_upload():
|
|
|
|
| 1639 |
try:
|
| 1640 |
upload_db_to_hf()
|
| 1641 |
flash("Данные успешно загружены на Hugging Face.", 'success')
|
| 1642 |
except Exception as e:
|
|
|
|
| 1643 |
flash(f"Ошибка при загрузке на Hugging Face: {e}", 'error')
|
| 1644 |
return redirect(url_for('admin'))
|
| 1645 |
|
| 1646 |
@app.route('/force_download', methods=['POST'])
|
| 1647 |
def force_download():
|
|
|
|
| 1648 |
try:
|
| 1649 |
if download_db_from_hf():
|
| 1650 |
flash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success')
|
|
|
|
| 1652 |
else:
|
| 1653 |
flash("Не удалось скачать данные с Hugging Face после нескольких попыток. Проверьте логи.", 'error')
|
| 1654 |
except Exception as e:
|
|
|
|
| 1655 |
flash(f"Ошибка при скачивании с Hugging Face: {e}", 'error')
|
| 1656 |
return redirect(url_for('admin'))
|
| 1657 |
|
|
|
|
|
|
|
| 1658 |
if __name__ == '__main__':
|
|
|
|
| 1659 |
download_db_from_hf()
|
| 1660 |
load_data()
|
|
|
|
| 1661 |
|
| 1662 |
if HF_TOKEN_WRITE:
|
| 1663 |
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
|
| 1664 |
backup_thread.start()
|
|
|
|
| 1665 |
else:
|
| 1666 |
+
pass
|
| 1667 |
|
| 1668 |
port = int(os.environ.get('PORT', 7860))
|
| 1669 |
+
app.run(debug=False, host='0.0.0.0', port=port)
|
|
|