optom / app.py
Kgshop's picture
Update app.py
9d3ee45 verified
from flask import Flask, render_template_string, request, redirect, url_for
import json
import os
import logging
import threading
import time
from datetime import datetime
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError
from werkzeug.utils import secure_filename
app = Flask(__name__)
DATA_FILE = 'data_kanc.json'
REPO_ID = "Kgshop/neznaika"
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
logging.basicConfig(level=logging.DEBUG)
def load_data():
try:
download_db_from_hf()
with open(DATA_FILE, 'r', encoding='utf-8') as file:
data = json.load(file)
logging.info("Данные успешно загружены из JSON")
if not isinstance(data, dict) or 'products' not in data or 'categories' not in data:
return {'products': [], 'categories': []}
return data
except FileNotFoundError:
logging.warning("Локальный файл базы данных не найден после скачивания.")
return {'products': [], 'categories': []}
except json.JSONDecodeError:
logging.error("Ошибка: Невозможно декодировать JSON файл.")
return {'products': [], 'categories': []}
except RepositoryNotFoundError:
logging.error("Репозиторий не найден. Создание локальной базы данных.")
return {'products': [], 'categories': []}
except Exception as e:
logging.error(f"Произошла ошибка при загрузке данных: {e}")
return {'products': [], 'categories': []}
def save_data(data):
try:
with open(DATA_FILE, 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
logging.info("Данные успешно сохранены в JSON")
upload_db_to_hf()
except Exception as e:
logging.error(f"Ошибка при сохранении данных: {e}")
raise
def upload_db_to_hf():
try:
api = HfApi()
api.upload_file(
path_or_fileobj=DATA_FILE,
path_in_repo=DATA_FILE,
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Автоматическое резервное копирование базы данных {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
)
logging.info("Резервная копия JSON базы успешно загружена на Hugging Face.")
except Exception as e:
logging.error(f"Ошибка при загрузке резервной копии: {e}")
def download_db_from_hf():
try:
hf_hub_download(
repo_id=REPO_ID,
filename=DATA_FILE,
repo_type="dataset",
token=HF_TOKEN_READ,
local_dir=".",
local_dir_use_symlinks=False
)
logging.info("JSON база успешно скачана из Hugging Face.")
except RepositoryNotFoundError as e:
logging.error(f"Репозиторий не найден: {e}")
raise
except Exception as e:
logging.error(f"Ошибка при скачивании JSON базы: {e}")
raise
def periodic_backup():
while True:
upload_db_to_hf()
time.sleep(800)
@app.route('/')
def catalog():
data = load_data()
products = data['products']
catalog_html = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Neznaika - канцтовары оптом</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
background: linear-gradient(135deg, #f5f7fa, #e4e7eb);
color: #333;
line-height: 1.6;
transition: background 0.3s, color 0.3s;
padding-bottom: 60px;
}
body.dark-mode {
background: linear-gradient(135deg, #1a1a2e, #2a2a3e);
color: #e0e0e0;
}
.container {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.header h1 {
font-size: 2rem;
font-weight: 700;
letter-spacing: 1px;
background: linear-gradient(90deg, #526df2, #7a8ff5);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.theme-toggle {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.3s ease;
}
.theme-toggle:hover {
color: #526df2;
}
body.dark-mode .theme-toggle {
color: #bbb;
}
.search-container {
margin: 20px 0;
text-align: center;
}
#search-input {
width: 90%;
max-width: 600px;
padding: 12px 18px;
font-size: 1rem;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 25px;
outline: none;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
transition: all 0.3s ease;
}
#search-input:focus {
border-color: #526df2;
box-shadow: 0 4px 15px rgba(82, 109, 242, 0.2);
}
.products-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
padding: 10px;
}
.product {
background: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.05);
border-radius: 15px;
padding: 15px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease, background 0.3s ease;
cursor: pointer;
position: relative;
overflow: hidden;
}
.product:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
background: rgba(255, 255, 255, 0.9);
}
body.dark-mode .product {
background: rgba(42, 42, 62, 0.8);
border-color: rgba(255, 255, 255, 0.05);
color: #e0e0e0;
}
body.dark-mode .product:hover {
background: rgba(42, 42, 62, 0.9);
box-shadow: 0 8px 25px rgba(255, 255, 255, 0.1);
}
.product-image {
width: 100%;
aspect-ratio: 1;
background-color: #fff;
border-radius: 10px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
transition: transform 0.3s ease;
}
body.dark-mode .product-image {
background-color: #333;
}
.product-image img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
transition: transform 0.3s ease;
}
.product-image img:hover {
transform: scale(1.05);
}
.product h2 {
font-size: 1.1rem;
font-weight: 500;
margin: 10px 0;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-price {
font-size: 1.2rem;
color: #e63946;
font-weight: 700;
text-align: center;
margin: 5px 0;
}
.product-price .wholesale {
font-size: 0.9rem;
color: #526df2;
font-weight: 500;
display: block;
margin-top: 5px;
}
.product-price .discount {
font-size: 0.9rem;
color: #2ecc71;
font-weight: 500;
display: block;
margin-top: 5px;
}
.product-description {
font-size: 0.85rem;
color: #666;
text-align: center;
margin-bottom: 15px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
body.dark-mode .product-description {
color: #bbb;
}
.product-button {
display: block;
width: 100%;
padding: 10px;
border: none;
border-radius: 25px;
background-color: #526df2;
color: white;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
margin: 5px 0;
text-align: center;
text-decoration: none;
}
.product-button:hover {
background-color: #3e55d1;
box-shadow: 0 4px 15px rgba(62, 85, 209, 0.4);
transform: translateY(-2px);
}
.add-to-cart {
background-color: #2ecc71;
}
.add-to-cart:hover {
background-color: #27ae60;
box-shadow: 0 4px 15px rgba(46, 204, 113, 0.4);
}
.favorite-button {
position: absolute;
top: 10px;
left: 10px;
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.3s ease;
}
.favorite-button.favorited {
color: #e63946;
}
.favorite-button:hover {
color: #e63946;
}
#cart-button {
position: fixed;
bottom: 80px;
right: 20px;
background-color: #e63946;
color: white;
border: none;
border-radius: 50%;
width: 60px;
height: 60px;
font-size: 1.5rem;
cursor: pointer;
display: none;
box-shadow: 0 4px 15px rgba(230, 57, 70, 0.4);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 1000;
}
#cart-button:hover {
transform: scale(1.1);
}
.modal {
display: none;
position: fixed;
z-index: 1001;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
backdrop-filter: blur(5px);
}
.modal-content {
background: #fff;
margin: 5% auto;
padding: 20px;
border-radius: 15px;
width: 90%;
max-width: 700px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
animation: slideIn 0.3s ease-out;
}
body.dark-mode .modal-content {
background: #2a2a3e;
color: #e0e0e0;
}
@keyframes slideIn {
from { transform: translateY(-50px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.close {
float: right;
font-size: 1.5rem;
color: #666;
cursor: pointer;
transition: color 0.3s;
}
.close:hover {
color: #333;
}
body.dark-mode .close {
color: #bbb;
}
body.dark-mode .close:hover {
color: #fff;
}
.cart-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
body.dark-mode .cart-item {
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.cart-item img {
width: 50px;
height: 50px;
object-fit: contain;
border-radius: 8px;
margin-right: 15px;
}
.quantity-input, .color-select {
width: 100%;
max-width: 150px;
padding: 8px;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 8px;
font-size: 1rem;
margin: 5px 0;
}
.clear-cart {
background-color: #e63946;
}
.clear-cart:hover {
background-color: #d62828;
box-shadow: 0 4px 15px rgba(230, 57, 70, 0.4);
}
.order-button {
background-color: #2ecc71;
}
.order-button:hover {
background-color: #27ae60;
box-shadow: 0 4px 15px rgba(46, 204, 113, 0.4);
}
.navbar {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
background-color: #fff;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
display: flex;
justify-content: space-around;
padding: 10px 0;
z-index: 1000;
}
body.dark-mode .navbar {
background-color: #2a2a3e;
}
.navbar a {
text-align: center;
color: #666;
text-decoration: none;
font-size: 0.9rem;
transition: color 0.3s ease;
}
.navbar a.active {
color: #526df2;
}
.navbar a i {
display: block;
font-size: 1.5rem;
margin-bottom: 5px;
}
body.dark-mode .navbar a {
color: #bbb;
}
.navbar a:hover {
color: #526df2;
}
.wholesale-badge {
position: absolute;
top: 10px;
right: 10px;
background-color: #526df2;
color: white;
padding: 5px 10px;
border-radius: 15px;
font-size: 0.75rem;
font-weight: 500;
}
.discount-badge {
position: absolute;
top: 40px;
right: 10px;
background-color: #2ecc71;
color: white;
padding: 5px 10px;
border-radius: 15px;
font-size: 0.75rem;
font-weight: 500;
}
.info-section {
text-align: center;
margin: 20px 0;
padding: 15px;
background: rgba(255, 255, 255, 0.8);
border-radius: 15px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}
body.dark-mode .info-section {
background: rgba(42, 42, 62, 0.8);
}
.info-section h2 {
font-size: 1.5rem;
font-weight: 500;
margin-bottom: 10px;
color: #526df2;
}
.info-section p {
font-size: 1rem;
color: #666;
}
body.dark-mode .info-section p {
color: #bbb;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Neznaika - канцтовары оптом</h1>
<button class="theme-toggle" onclick="toggleTheme()">
<i class="fas fa-moon"></i>
</button>
</div>
<div class="info-section">
<h2>Наш адрес</h2>
<p>Рынок Джунхай, проход 5, контейнер 507-508</p>
</div>
<div class="search-container">
<input type="text" id="search-input" placeholder="Поиск товаров...">
</div>
<div class="products-grid" id="products-grid">
{% for product in products %}
<div class="product"
onclick="openModal({{ loop.index0 }})"
data-name="{{ product['name']|lower }}"
data-description="{{ product['description']|lower }}"
data-category="{{ product.get('category', 'Без категории') }}">
<button class="favorite-button" onclick="event.stopPropagation(); toggleFavorite({{ loop.index0 }})">
<i class="fas fa-heart"></i>
</button>
{% if product.get('photos') and product['photos']|length > 0 %}
<div class="product-image">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}"
alt="{{ product['name'] }}"
loading="lazy">
</div>
{% endif %}
{% if product.get('wholesale_price') and product.get('min_wholesale') %}
<span class="wholesale-badge">Опт от {{ product['min_wholesale'] }}</span>
{% endif %}
{% if product.get('discount') %}
<span class="discount-badge">Скидка {{ product['discount'] }}%</span>
{% endif %}
<h2>{{ product['name'] }}</h2>
<div class="product-price">
{% if product.get('discount') %}
<span style="text-decoration: line-through; color: #666;">{{ product['price'] }} с</span>
<span>{{ (product['price'] * (1 - product['discount'] / 100))|round(2) }} с</span>
<span class="discount">Скидка: {{ product['discount'] }}%</span>
{% else %}
<span>{{ product['price'] }} с</span>
{% endif %}
{% if product.get('wholesale_price') and product.get('min_wholesale') %}
<span class="wholesale">Опт: {{ product['wholesale_price'] }} с</span>
{% endif %}
</div>
<p class="product-description">{{ product['description'][:50] }}{% if product['description']|length > 50 %}...{% endif %}</p>
<button class="product-button add-to-cart" onclick="event.stopPropagation(); openQuantityModal({{ loop.index0 }})">В корзину</button>
</div>
{% endfor %}
</div>
</div>
<div id="productModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('productModal')">×</span>
<div id="modalContent"></div>
</div>
</div>
<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>
<button class="product-button" onclick="confirmAddToCart()">Добавить</button>
</div>
</div>
<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>Итого: <span id="cartTotal">0</span> с</strong>
<button class="product-button clear-cart" onclick="clearCart()">Очистить</button>
<button class="product-button order-button" onclick="orderViaWhatsApp()">Заказать</button>
</div>
</div>
</div>
<button id="cart-button" onclick="openCartModal()">🛒</button>
<div class="navbar">
<a href="/" class="active">
<i class="fas fa-home"></i>
Главная
</a>
<a href="/categories">
<i class="fas fa-list"></i>
Каталог
</a>
<a href="/favorites">
<i class="fas fa-heart"></i>
Избранное
</a>
<a href="/discounts">
<i class="fas fa-tag"></i>
Скидки
</a>
<a href="https://api.whatsapp.com/send?phone=996706004240">
<i class="fab fa-whatsapp"></i>
WhatsApp
</a>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
<script>
const products = {{ products|tojson }};
let selectedProductIndex = null;
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');
}
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark-mode');
document.querySelector('.theme-toggle i').classList.replace('fa-moon', 'fa-sun');
}
function openModal(index) {
loadProductDetails(index);
document.getElementById('productModal').style.display = "block";
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = "none";
}
function loadProductDetails(index) {
fetch('/product/' + index)
.then(response => response.text())
.then(data => {
document.getElementById('modalContent').innerHTML = data;
initializeSwiper();
})
.catch(error => console.error('Ошибка:', error));
}
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 }
});
}
function openQuantityModal(index) {
selectedProductIndex = index;
const product = products[index];
const colorSelect = document.getElementById('colorSelect');
colorSelect.innerHTML = '';
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);
}
document.getElementById('quantityModal').style.display = 'block';
document.getElementById('quantityInput').value = 1;
}
function confirmAddToCart() {
if (selectedProductIndex === null) return;
const quantity = parseInt(document.getElementById('quantityInput').value) || 1;
const color = document.getElementById('colorSelect').value;
if (quantity <= 0) {
alert("Укажите количество больше 0");
return;
}
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
const product = products[selectedProductIndex];
const cartItemId = `${product.name}-${color}`;
const existingItem = cart.find(item => item.id === cartItemId);
let priceToUse = product.price;
if (product.discount) {
priceToUse = product.price * (1 - product.discount / 100);
}
if (product.min_wholesale && quantity >= product.min_wholesale) {
priceToUse = product.wholesale_price;
}
if (existingItem) {
existingItem.quantity += quantity;
existingItem.price = (existingItem.quantity >= product.min_wholesale) ? product.wholesale_price : (product.discount ? product.price * (1 - product.discount / 100) : product.price);
} else {
cart.push({
id: cartItemId,
name: product.name,
price: priceToUse,
retail_price: product.price,
wholesale_price: product.wholesale_price,
min_wholesale: product.min_wholesale,
discount: product.discount,
photo: product.photos && product.photos.length > 0 ? product.photos[0] : '',
quantity: quantity,
color: color
});
}
localStorage.setItem('cart', JSON.stringify(cart));
closeModal('quantityModal');
updateCartButton();
}
function updateCartButton() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
document.getElementById('cart-button').style.display = cart.length > 0 ? 'block' : 'none';
}
function openCartModal() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
const cartContent = document.getElementById('cartContent');
let total = 0;
cartContent.innerHTML = cart.length === 0 ? '<p>Корзина пуста</p>' : cart.map(item => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
return `
<div class="cart-item">
<div style="display: flex; align-items: center;">
${item.photo ? `<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}" alt="${item.name}">` : ''}
<div>
<strong>${item.name}</strong>
<p>${item.price} с × ${item.quantity} (Цвет: ${item.color})</p>
<p>${item.quantity >= item.min_wholesale ? 'Оптовая цена' : (item.discount ? 'Скидка ' + item.discount + '%' : 'Розничная цена')}</p>
</div>
</div>
<span>${itemTotal} с</span>
</div>
`;
}).join('');
document.getElementById('cartTotal').textContent = total;
document.getElementById('cartModal').style.display = 'block';
}
function orderViaWhatsApp() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
if (cart.length === 0) {
alert("Корзина пуста!");
return;
}
let total = 0;
let orderText = "Заказ:%0A";
cart.forEach((item, index) => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
orderText += `${index + 1}. ${item.name} - ${item.price} с × ${item.quantity} (Цвет: ${item.color})%0A`;
});
orderText += `Итого: ${total} с`;
window.open(`https://api.whatsapp.com/send?phone=996706004240&text=${orderText}`, '_blank');
}
function clearCart() {
localStorage.removeItem('cart');
closeModal('cartModal');
updateCartButton();
}
function toggleFavorite(index) {
let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
const productId = index.toString();
const favoriteButton = document.querySelector(`.favorite-button[onclick="event.stopPropagation(); toggleFavorite(${index})"]`);
if (favorites.includes(productId)) {
favorites = favorites.filter(id => id !== productId);
favoriteButton.classList.remove('favorited');
} else {
favorites.push(productId);
favoriteButton.classList.add('favorited');
}
localStorage.setItem('favorites', JSON.stringify(favorites));
}
function loadFavorites() {
const favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
document.querySelectorAll('.favorite-button').forEach(button => {
const index = button.getAttribute('onclick').match(/\d+/)[0];
if (favorites.includes(index)) {
button.classList.add('favorited');
}
});
}
window.onclick = function(event) {
if (event.target.className === 'modal') event.target.style.display = "none";
}
document.getElementById('search-input').addEventListener('input', filterProducts);
function filterProducts() {
const searchTerm = document.getElementById('search-input').value.toLowerCase();
document.querySelectorAll('.product').forEach(product => {
const name = product.getAttribute('data-name');
const description = product.getAttribute('data-description');
const matchesSearch = name.includes(searchTerm) || description.includes(searchTerm);
product.style.display = matchesSearch ? 'block' : 'none';
});
}
updateCartButton();
loadFavorites();
</script>
</body>
</html>
'''
return render_template_string(catalog_html, products=products, repo_id=REPO_ID)
@app.route('/categories')
def categories_page():
data = load_data()
categories = data['categories']
categories_html = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Категории</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
background: linear-gradient(135deg, #f5f7fa, #e4e7eb);
color: #333;
line-height: 1.6;
transition: background 0.3s, color 0.3s;
padding-bottom: 60px;
}
body.dark-mode {
background: linear-gradient(135deg, #1a1a2e, #2a2a3e);
color: #e0e0e0;
}
.container {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.header h1 {
font-size: 2rem;
font-weight: 700;
letter-spacing: 1px;
background: linear-gradient(90deg, #526df2, #7a8ff5);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.theme-toggle {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.3s ease;
}
.theme-toggle:hover {
color: #526df2;
}
body.dark-mode .theme-toggle {
color: #bbb;
}
.categories-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
padding: 10px;
}
.category-item {
background: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.05);
border-radius: 15px;
padding: 20px;
text-align: center;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease, background 0.3s ease;
text-decoration: none;
color: #333;
}
body.dark-mode .category-item {
background: rgba(42, 42, 62, 0.8);
border-color: rgba(255, 255, 255, 0.05);
color: #e0e0e0;
}
.category-item:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
background: rgba(255, 255, 255, 0.9);
background-color: #526df2;
color: white;
}
body.dark-mode .category-item:hover {
background: rgba(42, 42, 62, 0.9);
box-shadow: 0 8px 25px rgba(255, 255, 255, 0.1);
}
.category-item h2 {
font-size: 1.2rem;
font-weight: 500;
}
.navbar {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
background-color: #fff;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
display: flex;
justify-content: space-around;
padding: 10px 0;
z-index: 1000;
}
body.dark-mode .navbar {
background-color: #2a2a3e;
}
.navbar a {
text-align: center;
color: #666;
text-decoration: none;
font-size: 0.9rem;
transition: color 0.3s ease;
}
.navbar a.active {
color: #526df2;
}
.navbar a i {
display: block;
font-size: 1.5rem;
margin-bottom: 5px;
}
body.dark-mode .navbar a {
color: #bbb;
}
.navbar a:hover {
color: #526df2;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Категории</h1>
<button class="theme-toggle" onclick="toggleTheme()">
<i class="fas fa-moon"></i>
</button>
</div>
<div class="categories-grid">
{% for category in categories %}
<a href="{{ url_for('category_products', category=category) }}" class="category-item">
<h2>{{ category }}</h2>
</a>
{% endfor %}
</div>
</div>
<div class="navbar">
<a href="/">
<i class="fas fa-home"></i>
Главная
</a>
<a href="/categories" class="active">
<i class="fas fa-list"></i>
Каталог
</a>
<a href="/favorites">
<i class="fas fa-heart"></i>
Избранное
</a>
<a href="/discounts">
<i class="fas fa-tag"></i>
Скидки
</a>
<a href="https://api.whatsapp.com/send?phone=996706004240">
<i class="fab fa-whatsapp"></i>
WhatsApp
</a>
</div>
<script>
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');
}
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark-mode');
document.querySelector('.theme-toggle i').classList.replace('fa-moon', 'fa-sun');
}
window.onclick = function(event) {
if (event.target.className === 'modal') event.target.style.display = "none";
}
</script>
</body>
</html>
'''
return render_template_string(categories_html, categories=categories)
@app.route('/category/<category>')
def category_products(category):
data = load_data()
products = [p for p in data['products'] if p.get('category') == category]
category_html = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ category }}</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
background: linear-gradient(135deg, #f5f7fa, #e4e7eb);
color: #333;
line-height: 1.6;
transition: background 0.3s, color 0.3s;
padding-bottom: 60px;
}
body.dark-mode {
background: linear-gradient(135deg, #1a1a2e, #2a2a3e);
color: #e0e0e0;
}
.container {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.header h1 {
font-size: 2rem;
font-weight: 700;
letter-spacing: 1px;
background: linear-gradient(90deg, #526df2, #7a8ff5);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.theme-toggle {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.3s ease;
}
.theme-toggle:hover {
color: #526df2;
}
body.dark-mode .theme-toggle {
color: #bbb;
}
.products-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
padding: 10px;
}
.product {
background: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.05);
border-radius: 15px;
padding: 15px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease, background 0.3s ease;
cursor: pointer;
position: relative;
overflow: hidden;
}
.product:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
background: rgba(255, 255, 255, 0.9);
}
body.dark-mode .product {
background: rgba(42, 42, 62, 0.8);
border-color: rgba(255, 255, 255, 0.05);
color: #e0e0e0;
}
body.dark-mode .product:hover {
background: rgba(42, 42, 62, 0.9);
box-shadow: 0 8px 25px rgba(255, 255, 255, 0.1);
}
.product-image {
width: 100%;
aspect-ratio: 1;
background-color: #fff;
border-radius: 10px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
transition: transform 0.3s ease;
}
body.dark-mode .product-image {
background-color: #333;
}
.product-image img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
transition: transform 0.3s ease;
}
.product-image img:hover {
transform: scale(1.05);
}
.product h2 {
font-size: 1.1rem;
font-weight: 500;
margin: 10px 0;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-price {
font-size: 1.2rem;
color: #e63946;
font-weight: 700;
text-align: center;
margin: 5px 0;
}
.product-price .wholesale {
font-size: 0.9rem;
color: #526df2;
font-weight: 500;
display: block;
margin-top: 5px;
}
.product-price .discount {
font-size: 0.9rem;
color: #2ecc71;
font-weight: 500;
display: block;
margin-top: 5px;
}
.product-description {
font-size: 0.85rem;
color: #666;
text-align: center;
margin-bottom: 15px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
body.dark-mode .product-description {
color: #bbb;
}
.product-button {
display: block;
width: 100%;
padding: 10px;
border: none;
border-radius: 25px;
background-color: #526df2;
color: white;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
margin: 5px 0;
text-align: center;
text-decoration: none;
}
.product-button:hover {
background-color: #3e55d1;
box-shadow: 0 4px 15px rgba(62, 85, 209, 0.4);
transform: translateY(-2px);
}
.add-to-cart {
background-color: #2ecc71;
}
.add-to-cart:hover {
background-color: #27ae60;
box-shadow: 0 4px 15px rgba(46, 204, 113, 0.4);
}
.favorite-button {
position: absolute;
top: 10px;
left: 10px;
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.3s ease;
}
.favorite-button.favorited {
color: #e63946;
}
.favorite-button:hover {
color: #e63946;
}
#cart-button {
position: fixed;
bottom: 80px;
right: 20px;
background-color: #e63946;
color: white;
border: none;
border-radius: 50%;
width: 60px;
height: 60px;
font-size: 1.5rem;
cursor: pointer;
display: none;
box-shadow: 0 4px 15px rgba(230, 57, 70, 0.4);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 1000;
}
#cart-button:hover {
transform: scale(1.1);
}
.modal {
display: none;
position: fixed;
z-index: 1001;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
backdrop-filter: blur(5px);
}
.modal-content {
background: #fff;
margin: 5% auto;
padding: 20px;
border-radius: 15px;
width: 90%;
max-width: 700px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
animation: slideIn 0.3s ease-out;
}
body.dark-mode .modal-content {
background: #2a2a3e;
color: #e0e0e0;
}
@keyframes slideIn {
from { transform: translateY(-50px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.close {
float: right;
font-size: 1.5rem;
color: #666;
cursor: pointer;
transition: color 0.3s;
}
.close:hover {
color: #333;
}
body.dark-mode .close {
color: #bbb;
}
body.dark-mode .close:hover {
color: #fff;
}
.cart-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
body.dark-mode .cart-item {
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.cart-item img {
width: 50px;
height: 50px;
object-fit: contain;
border-radius: 8px;
margin-right: 15px;
}
.quantity-input, .color-select {
width: 100%;
max-width: 150px;
padding: 8px;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 8px;
font-size: 1rem;
margin: 5px 0;
}
.clear-cart {
background-color: #e63946;
}
.clear-cart:hover {
background-color: #d62828;
box-shadow: 0 4px 15px rgba(230, 57, 70, 0.4);
}
.order-button {
background-color: #2ecc71;
}
.order-button:hover {
background-color: #27ae60;
box-shadow: 0 4px 15px rgba(46, 204, 113, 0.4);
}
.navbar {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
background-color: #fff;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
display: flex;
justify-content: space-around;
padding: 10px 0;
z-index: 1000;
}
body.dark-mode .navbar {
background-color: #2a2a3e;
}
.navbar a {
text-align: center;
color: #666;
text-decoration: none;
font-size: 0.9rem;
transition: color 0.3s ease;
}
.navbar a.active {
color: #526df2;
}
.navbar a i {
display: block;
font-size: 1.5rem;
margin-bottom: 5px;
}
body.dark-mode .navbar a {
color: #bbb;
}
.navbar a:hover {
color: #526df2;
}
.wholesale-badge {
position: absolute;
top: 10px;
right: 10px;
background-color: #526df2;
color: white;
padding: 5px 10px;
border-radius: 15px;
font-size: 0.75rem;
font-weight: 500;
}
.discount-badge {
position: absolute;
top: 40px;
right: 10px;
background-color: #2ecc71;
color: white;
padding: 5px 10px;
border-radius: 15px;
font-size: 0.75rem;
font-weight: 500;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>{{ category }}</h1>
<button class="theme-toggle" onclick="toggleTheme()">
<i class="fas fa-moon"></i>
</button>
</div>
<div class="products-grid" id="products-grid">
{% for product in products %}
<div class="product"
onclick="openModal({{ loop.index0 }})"
data-name="{{ product['name']|lower }}"
data-description="{{ product['description']|lower }}"
data-category="{{ product.get('category', 'Без категории') }}">
<button class="favorite-button" onclick="event.stopPropagation(); toggleFavorite({{ loop.index0 }})">
<i class="fas fa-heart"></i>
</button>
{% if product.get('photos') and product['photos']|length > 0 %}
<div class="product-image">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}"
alt="{{ product['name'] }}"
loading="lazy">
</div>
{% endif %}
{% if product.get('wholesale_price') and product.get('min_wholesale') %}
<span class="wholesale-badge">Опт от {{ product['min_wholesale'] }}</span>
{% endif %}
{% if product.get('discount') %}
<span class="discount-badge">Скидка {{ product['discount'] }}%</span>
{% endif %}
<h2>{{ product['name'] }}</h2>
<div class="product-price">
{% if product.get('discount') %}
<span style="text-decoration: line-through; color: #666;">{{ product['price'] }} с</span>
<span>{{ (product['price'] * (1 - product['discount'] / 100))|round(2) }} с</span>
<span class="discount">Скидка: {{ product['discount'] }}%</span>
{% else %}
<span>{{ product['price'] }} с</span>
{% endif %}
{% if product.get('wholesale_price') and product.get('min_wholesale') %}
<span class="wholesale">Опт: {{ product['wholesale_price'] }} с</span>
{% endif %}
</div>
<p class="product-description">{{ product['description'][:50] }}{% if product['description']|length > 50 %}...{% endif %}</p>
<button class="product-button add-to-cart" onclick="event.stopPropagation(); openQuantityModal({{ loop.index0 }})">В корзину</button>
</div>
{% endfor %}
</div>
</div>
<div id="productModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('productModal')">×</span>
<div id="modalContent"></div>
</div>
</div>
<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>
<button class="product-button" onclick="confirmAddToCart()">Добавить</button>
</div>
</div>
<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>Итого: <span id="cartTotal">0</span> с</strong>
<button class="product-button clear-cart" onclick="clearCart()">Очистить</button>
<button class="product-button order-button" onclick="orderViaWhatsApp()">Заказать</button>
</div>
</div>
</div>
<button id="cart-button" onclick="openCartModal()">🛒</button>
<div class="navbar">
<a href="/">
<i class="fas fa-home"></i>
Главная
</a>
<a href="/categories" class="active">
<i class="fas fa-list"></i>
Каталог
</a>
<a href="/favorites">
<i class="fas fa-heart"></i>
Избранное
</a>
<a href="/discounts">
<i class="fas fa-tag"></i>
Скидки
</a>
<a href="https://api.whatsapp.com/send?phone=996706004240">
<i class="fab fa-whatsapp"></i>
WhatsApp
</a>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
<script>
const products = {{ products|tojson }};
let selectedProductIndex = null;
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');
}
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark-mode');
document.querySelector('.theme-toggle i').classList.replace('fa-moon', 'fa-sun');
}
function openModal(index) {
loadProductDetails(index);
document.getElementById('productModal').style.display = "block";
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = "none";
}
function loadProductDetails(index) {
// Adjust index based on the filtered products list
const originalIndex = {{ data['products']|tojson }}.findIndex(p => p.name === products[index].name && p.description === products[index].description);
if (originalIndex === -1) {
console.error('Original product index not found');
return;
}
fetch('/product/' + originalIndex)
.then(response => response.text())
.then(data => {
document.getElementById('modalContent').innerHTML = data;
initializeSwiper();
})
.catch(error => console.error('Ошибка:', error));
}
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 }
});
}
function openQuantityModal(index) {
selectedProductIndex = index;
const product = products[index];
const colorSelect = document.getElementById('colorSelect');
colorSelect.innerHTML = '';
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);
}
document.getElementById('quantityModal').style.display = 'block';
document.getElementById('quantityInput').value = 1;
}
function confirmAddToCart() {
if (selectedProductIndex === null) return;
const quantity = parseInt(document.getElementById('quantityInput').value) || 1;
const color = document.getElementById('colorSelect').value;
if (quantity <= 0) {
alert("Укажите количество больше 0");
return;
}
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
const product = products[selectedProductIndex];
const cartItemId = `${product.name}-${color}`;
const existingItem = cart.find(item => item.id === cartItemId);
let priceToUse = product.price;
if (product.discount) {
priceToUse = product.price * (1 - product.discount / 100);
}
if (product.min_wholesale && quantity >= product.min_wholesale) {
priceToUse = product.wholesale_price;
}
if (existingItem) {
existingItem.quantity += quantity;
existingItem.price = (existingItem.quantity >= product.min_wholesale) ? product.wholesale_price : (product.discount ? product.price * (1 - product.discount / 100) : product.price);
} else {
cart.push({
id: cartItemId,
name: product.name,
price: priceToUse,
retail_price: product.price,
wholesale_price: product.wholesale_price,
min_wholesale: product.min_wholesale,
discount: product.discount,
photo: product.photos && product.photos.length > 0 ? product.photos[0] : '',
quantity: quantity,
color: color
});
}
localStorage.setItem('cart', JSON.stringify(cart));
closeModal('quantityModal');
updateCartButton();
}
function updateCartButton() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
document.getElementById('cart-button').style.display = cart.length > 0 ? 'block' : 'none';
}
function openCartModal() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
const cartContent = document.getElementById('cartContent');
let total = 0;
cartContent.innerHTML = cart.length === 0 ? '<p>Корзина пуста</p>' : cart.map(item => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
return `
<div class="cart-item">
<div style="display: flex; align-items: center;">
${item.photo ? `<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}" alt="${item.name}">` : ''}
<div>
<strong>${item.name}</strong>
<p>${item.price} с × ${item.quantity} (Цвет: ${item.color})</p>
<p>${item.quantity >= item.min_wholesale ? 'Оптовая цена' : (item.discount ? 'Скидка ' + item.discount + '%' : 'Розничная цена')}</p>
</div>
</div>
<span>${itemTotal} с</span>
</div>
`;
}).join('');
document.getElementById('cartTotal').textContent = total;
document.getElementById('cartModal').style.display = 'block';
}
function orderViaWhatsApp() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
if (cart.length === 0) {
alert("Корзина пуста!");
return;
}
let total = 0;
let orderText = "Заказ:%0A";
cart.forEach((item, index) => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
orderText += `${index + 1}. ${item.name} - ${item.price} с × ${item.quantity} (Цвет: ${item.color})%0A`;
});
orderText += `Итого: ${total} с`;
window.open(`https://api.whatsapp.com/send?phone=996706004240&text=${orderText}`, '_blank');
}
function clearCart() {
localStorage.removeItem('cart');
closeModal('cartModal');
updateCartButton();
}
function toggleFavorite(index) {
const allProducts = {{ data['products']|tojson }};
const product = products[index]; // Get the product from the current filtered list
// Find the original index in the full product list
const originalIndex = allProducts.findIndex(p => p.name === product.name && p.description === product.description);
if (originalIndex === -1) {
console.error('Original product index not found for favorite toggle');
return;
}
let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
const productId = originalIndex.toString(); // Use original index for storage
const favoriteButton = document.querySelector(`.product[data-name="${product.name.toLowerCase()}"] .favorite-button`); // More specific selector
if (favorites.includes(productId)) {
favorites = favorites.filter(id => id !== productId);
if (favoriteButton) favoriteButton.classList.remove('favorited');
} else {
favorites.push(productId);
if (favoriteButton) favoriteButton.classList.add('favorited');
}
localStorage.setItem('favorites', JSON.stringify(favorites));
}
function loadFavorites() {
const allProducts = {{ data['products']|tojson }};
const favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
const productElements = document.querySelectorAll('.product');
productElements.forEach((productElement, currentListIndex) => {
const productName = productElement.getAttribute('data-name');
const productDescription = productElement.getAttribute('data-description');
// Find the original index based on name and description
const originalIndex = allProducts.findIndex(p => p.name.toLowerCase() === productName && p.description.toLowerCase() === productDescription);
if (originalIndex !== -1 && favorites.includes(originalIndex.toString())) {
const button = productElement.querySelector('.favorite-button');
if (button) {
button.classList.add('favorited');
}
}
});
}
window.onclick = function(event) {
if (event.target.className === 'modal') event.target.style.display = "none";
}
updateCartButton();
loadFavorites();
</script>
</body>
</html>
'''
# Pass the original full data to the template for index lookups
return render_template_string(category_html, products=products, category=category, repo_id=REPO_ID, data=load_data())
@app.route('/favorites')
def favorites_page():
data = load_data()
all_products = data['products'] # Get all products
favorites_html = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Избранное</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
background: linear-gradient(135deg, #f5f7fa, #e4e7eb);
color: #333;
line-height: 1.6;
transition: background 0.3s, color 0.3s;
padding-bottom: 60px;
}
body.dark-mode {
background: linear-gradient(135deg, #1a1a2e, #2a2a3e);
color: #e0e0e0;
}
.container {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.header h1 {
font-size: 2rem;
font-weight: 700;
letter-spacing: 1px;
background: linear-gradient(90deg, #526df2, #7a8ff5);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.theme-toggle {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.3s ease;
}
.theme-toggle:hover {
color: #526df2;
}
body.dark-mode .theme-toggle {
color: #bbb;
}
.products-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
padding: 10px;
}
.product {
background: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.05);
border-radius: 15px;
padding: 15px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease, background 0.3s ease;
cursor: pointer;
position: relative;
overflow: hidden;
}
.product:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
background: rgba(255, 255, 255, 0.9);
}
body.dark-mode .product {
background: rgba(42, 42, 62, 0.8);
border-color: rgba(255, 255, 255, 0.05);
color: #e0e0e0;
}
body.dark-mode .product:hover {
background: rgba(42, 42, 62, 0.9);
box-shadow: 0 8px 25px rgba(255, 255, 255, 0.1);
}
.product-image {
width: 100%;
aspect-ratio: 1;
background-color: #fff;
border-radius: 10px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
transition: transform 0.3s ease;
}
body.dark-mode .product-image {
background-color: #333;
}
.product-image img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
transition: transform 0.3s ease;
}
.product-image img:hover {
transform: scale(1.05);
}
.product h2 {
font-size: 1.1rem;
font-weight: 500;
margin: 10px 0;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-price {
font-size: 1.2rem;
color: #e63946;
font-weight: 700;
text-align: center;
margin: 5px 0;
}
.product-price .wholesale {
font-size: 0.9rem;
color: #526df2;
font-weight: 500;
display: block;
margin-top: 5px;
}
.product-price .discount {
font-size: 0.9rem;
color: #2ecc71;
font-weight: 500;
display: block;
margin-top: 5px;
}
.product-description {
font-size: 0.85rem;
color: #666;
text-align: center;
margin-bottom: 15px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
body.dark-mode .product-description {
color: #bbb;
}
.product-button {
display: block;
width: 100%;
padding: 10px;
border: none;
border-radius: 25px;
background-color: #526df2;
color: white;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
margin: 5px 0;
text-align: center;
text-decoration: none;
}
.product-button:hover {
background-color: #3e55d1;
box-shadow: 0 4px 15px rgba(62, 85, 209, 0.4);
transform: translateY(-2px);
}
.add-to-cart {
background-color: #2ecc71;
}
.add-to-cart:hover {
background-color: #27ae60;
box-shadow: 0 4px 15px rgba(46, 204, 113, 0.4);
}
.favorite-button {
position: absolute;
top: 10px;
left: 10px;
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.3s ease;
}
.favorite-button.favorited {
color: #e63946;
}
.favorite-button:hover {
color: #e63946;
}
#cart-button {
position: fixed;
bottom: 80px;
right: 20px;
background-color: #e63946;
color: white;
border: none;
border-radius: 50%;
width: 60px;
height: 60px;
font-size: 1.5rem;
cursor: pointer;
display: none;
box-shadow: 0 4px 15px rgba(230, 57, 70, 0.4);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 1000;
}
#cart-button:hover {
transform: scale(1.1);
}
.modal {
display: none;
position: fixed;
z-index: 1001;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
backdrop-filter: blur(5px);
}
.modal-content {
background: #fff;
margin: 5% auto;
padding: 20px;
border-radius: 15px;
width: 90%;
max-width: 700px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
animation: slideIn 0.3s ease-out;
}
body.dark-mode .modal-content {
background: #2a2a3e;
color: #e0e0e0;
}
@keyframes slideIn {
from { transform: translateY(-50px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.close {
float: right;
font-size: 1.5rem;
color: #666;
cursor: pointer;
transition: color 0.3s;
}
.close:hover {
color: #333;
}
body.dark-mode .close {
color: #bbb;
}
body.dark-mode .close:hover {
color: #fff;
}
.cart-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
body.dark-mode .cart-item {
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.cart-item img {
width: 50px;
height: 50px;
object-fit: contain;
border-radius: 8px;
margin-right: 15px;
}
.quantity-input, .color-select {
width: 100%;
max-width: 150px;
padding: 8px;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 8px;
font-size: 1rem;
margin: 5px 0;
}
.clear-cart {
background-color: #e63946;
}
.clear-cart:hover {
background-color: #d62828;
box-shadow: 0 4px 15px rgba(230, 57, 70, 0.4);
}
.order-button {
background-color: #2ecc71;
}
.order-button:hover {
background-color: #27ae60;
box-shadow: 0 4px 15px rgba(46, 204, 113, 0.4);
}
.navbar {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
background-color: #fff;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
display: flex;
justify-content: space-around;
padding: 10px 0;
z-index: 1000;
}
body.dark-mode .navbar {
background-color: #2a2a3e;
}
.navbar a {
text-align: center;
color: #666;
text-decoration: none;
font-size: 0.9rem;
transition: color 0.3s ease;
}
.navbar a.active {
color: #526df2;
}
.navbar a i {
display: block;
font-size: 1.5rem;
margin-bottom: 5px;
}
body.dark-mode .navbar a {
color: #bbb;
}
.navbar a:hover {
color: #526df2;
}
.wholesale-badge {
position: absolute;
top: 10px;
right: 10px;
background-color: #526df2;
color: white;
padding: 5px 10px;
border-radius: 15px;
font-size: 0.75rem;
font-weight: 500;
}
.discount-badge {
position: absolute;
top: 40px;
right: 10px;
background-color: #2ecc71;
color: white;
padding: 5px 10px;
border-radius: 15px;
font-size: 0.75rem;
font-weight: 500;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Избранное</h1>
<button class="theme-toggle" onclick="toggleTheme()">
<i class="fas fa-moon"></i>
</button>
</div>
<div class="products-grid" id="products-grid">
</div>
</div>
<div id="productModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('productModal')">×</span>
<div id="modalContent"></div>
</div>
</div>
<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>
<button class="product-button" onclick="confirmAddToCart()">Добавить</button>
</div>
</div>
<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>Итого: <span id="cartTotal">0</span> с</strong>
<button class="product-button clear-cart" onclick="clearCart()">Очистить</button>
<button class="product-button order-button" onclick="orderViaWhatsApp()">Заказать</button>
</div>
</div>
</div>
<button id="cart-button" onclick="openCartModal()">🛒</button>
<div class="navbar">
<a href="/">
<i class="fas fa-home"></i>
Главная
</a>
<a href="/categories">
<i class="fas fa-list"></i>
Каталог
</a>
<a href="/favorites" class="active">
<i class="fas fa-heart"></i>
Избранное
</a>
<a href="/discounts">
<i class="fas fa-tag"></i>
Скидки
</a>
<a href="https://api.whatsapp.com/send?phone=996706004240">
<i class="fab fa-whatsapp"></i>
WhatsApp
</a>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
<script>
const allProducts = {{ all_products|tojson }}; // Use all products passed from Flask
let products = []; // This will hold the favorite products
let selectedProductIndex = null; // This index will refer to the 'products' array (favorites)
let selectedProductOriginalIndex = null; // This will hold the original index from 'allProducts'
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');
}
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark-mode');
document.querySelector('.theme-toggle i').classList.replace('fa-moon', 'fa-sun');
}
function loadFavoritesPage() {
const favoriteIndices = JSON.parse(localStorage.getItem('favorites') || '[]');
const productsGrid = document.getElementById('products-grid');
productsGrid.innerHTML = '';
products = []; // Clear the local favorite products array
if (favoriteIndices.length === 0) {
productsGrid.innerHTML = '<p>Избранное пусто</p>';
return;
}
favoriteIndices.forEach(originalIndexStr => {
const originalIndex = parseInt(originalIndexStr);
if (originalIndex >= 0 && originalIndex < allProducts.length) {
const product = allProducts[originalIndex];
products.push(product); // Add to the local favorites array
const currentFavIndex = products.length - 1; // Index within the 'products' (favorites) array
const productElement = document.createElement('div');
productElement.className = 'product';
// Use originalIndex for opening modal details
productElement.setAttribute('onclick', `openModal(${originalIndex})`);
productElement.setAttribute('data-original-index', originalIndex); // Store original index
productElement.setAttribute('data-name', product.name.toLowerCase());
productElement.setAttribute('data-description', product.description.toLowerCase());
productElement.setAttribute('data-category', product.category || 'Без категории');
productElement.innerHTML = `
<button class="favorite-button favorited" onclick="event.stopPropagation(); toggleFavorite(${originalIndex})">
<i class="fas fa-heart"></i>
</button>
${product.photos && product.photos.length > 0 ? `
<div class="product-image">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${product.photos[0]}" alt="${product.name}" loading="lazy">
</div>` : ''}
${product.wholesale_price && product.min_wholesale ? `<span class="wholesale-badge">Опт от ${product.min_wholesale}</span>` : ''}
${product.discount ? `<span class="discount-badge">Скидка ${product.discount}%</span>` : ''}
<h2>${product.name}</h2>
<div class="product-price">
${product.discount ? `
<span style="text-decoration: line-through; color: #666;">${product.price} с</span>
<span>${(product.price * (1 - product.discount / 100)).toFixed(2)} с</span>
<span class="discount">Скидка: ${product.discount}%</span>` : `<span>${product.price} с</span>`}
${product.wholesale_price && product.min_wholesale ? `<span class="wholesale">Опт: ${product.wholesale_price} с</span>` : ''}
</div>
<p class="product-description">${product.description.slice(0, 50)}${product.description.length > 50 ? '...' : ''}</p>
<button class="product-button add-to-cart" onclick="event.stopPropagation(); openQuantityModal(${originalIndex})">В корзину</button>
`;
productsGrid.appendChild(productElement);
} else {
console.warn(`Favorite index ${originalIndex} out of bounds or invalid.`);
// Optionally remove invalid index from localStorage here
let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
favorites = favorites.filter(id => id !== originalIndexStr);
localStorage.setItem('favorites', JSON.stringify(favorites));
}
});
}
function openModal(originalIndex) {
loadProductDetails(originalIndex); // Use original index directly
document.getElementById('productModal').style.display = "block";
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = "none";
}
function loadProductDetails(originalIndex) { // Takes original index
if (originalIndex < 0 || originalIndex >= allProducts.length) {
console.error("Invalid index for product details:", originalIndex);
document.getElementById('modalContent').innerHTML = '<p>Ошибка: Товар не найден.</p>';
return;
}
fetch('/product/' + originalIndex) // Fetch using original index
.then(response => response.text())
.then(data => {
document.getElementById('modalContent').innerHTML = data;
initializeSwiper();
})
.catch(error => console.error('Ошибка:', error));
}
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 }
});
}
function openQuantityModal(originalIndex) { // Takes original index
if (originalIndex < 0 || originalIndex >= allProducts.length) {
console.error("Invalid index for quantity modal:", originalIndex);
return;
}
selectedProductOriginalIndex = originalIndex; // Store original index
const product = allProducts[originalIndex]; // Get product from allProducts
const colorSelect = document.getElementById('colorSelect');
colorSelect.innerHTML = '';
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);
}
document.getElementById('quantityModal').style.display = 'block';
document.getElementById('quantityInput').value = 1;
}
function confirmAddToCart() {
if (selectedProductOriginalIndex === null) return; // Use original index
const quantity = parseInt(document.getElementById('quantityInput').value) || 1;
const color = document.getElementById('colorSelect').value;
if (quantity <= 0) {
alert("Укажите количество больше 0");
return;
}
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
const product = allProducts[selectedProductOriginalIndex]; // Use original index
const cartItemId = `${product.name}-${color}`;
const existingItem = cart.find(item => item.id === cartItemId);
let priceToUse = product.price;
if (product.discount) {
priceToUse = product.price * (1 - product.discount / 100);
}
if (product.min_wholesale && quantity >= product.min_wholesale) {
priceToUse = product.wholesale_price;
}
if (existingItem) {
existingItem.quantity += quantity;
// Recalculate price based on potentially new quantity
existingItem.price = (existingItem.quantity >= (product.min_wholesale || Infinity))
? product.wholesale_price
: (product.discount ? product.price * (1 - product.discount / 100) : product.price);
} else {
cart.push({
id: cartItemId,
name: product.name,
price: priceToUse, // Use the calculated price
retail_price: product.price,
wholesale_price: product.wholesale_price,
min_wholesale: product.min_wholesale,
discount: product.discount,
photo: product.photos && product.photos.length > 0 ? product.photos[0] : '',
quantity: quantity,
color: color
});
}
localStorage.setItem('cart', JSON.stringify(cart));
closeModal('quantityModal');
updateCartButton();
}
function updateCartButton() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
document.getElementById('cart-button').style.display = cart.length > 0 ? 'block' : 'none';
}
function openCartModal() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
const cartContent = document.getElementById('cartContent');
let total = 0;
cartContent.innerHTML = cart.length === 0 ? '<p>Корзина пуста</p>' : cart.map(item => {
// Find the product in allProducts to get potentially updated pricing info if needed
const productInfo = allProducts.find(p => p.name === item.name); // Basic match
const currentPrice = (item.quantity >= (item.min_wholesale || Infinity))
? item.wholesale_price
: (item.discount ? item.retail_price * (1 - item.discount / 100) : item.retail_price);
item.price = parseFloat(currentPrice.toFixed(2)); // Ensure price is up-to-date and numeric
const itemTotal = item.price * item.quantity;
total += itemTotal;
return `
<div class="cart-item">
<div style="display: flex; align-items: center;">
${item.photo ? `<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}" alt="${item.name}">` : ''}
<div>
<strong>${item.name}</strong>
<p>${item.price.toFixed(2)} с × ${item.quantity} (Цвет: ${item.color})</p>
<p>${item.quantity >= (item.min_wholesale || Infinity) ? 'Оптовая цена' : (item.discount ? 'Скидка ' + item.discount + '%' : 'Розничная цена')}</p>
</div>
</div>
<span>${itemTotal.toFixed(2)} с</span>
</div>
`;
}).join('');
document.getElementById('cartTotal').textContent = total.toFixed(2);
document.getElementById('cartModal').style.display = 'block';
}
function orderViaWhatsApp() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
if (cart.length === 0) {
alert("Корзина пуста!");
return;
}
let total = 0;
let orderText = "Заказ:%0A";
cart.forEach((item, index) => {
// Recalculate price for the message
const currentPrice = (item.quantity >= (item.min_wholesale || Infinity))
? item.wholesale_price
: (item.discount ? item.retail_price * (1 - item.discount / 100) : item.retail_price);
const itemTotal = currentPrice * item.quantity;
total += itemTotal;
orderText += `${index + 1}. ${item.name} - ${currentPrice.toFixed(2)} с × ${item.quantity} (Цвет: ${item.color})%0A`;
});
orderText += `Итого: ${total.toFixed(2)} с`;
window.open(`https://api.whatsapp.com/send?phone=996706004240&text=${orderText}`, '_blank');
}
function clearCart() {
localStorage.removeItem('cart');
closeModal('cartModal');
updateCartButton();
}
function toggleFavorite(originalIndex) { // Takes original index
let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
const productId = originalIndex.toString();
if (favorites.includes(productId)) {
favorites = favorites.filter(id => id !== productId);
} else {
favorites.push(productId);
}
localStorage.setItem('favorites', JSON.stringify(favorites));
loadFavoritesPage(); // Reload the favorites page after toggling
}
window.onclick = function(event) {
if (event.target.className === 'modal') event.target.style.display = "none";
}
updateCartButton();
loadFavoritesPage(); // Load favorites on initial page load
</script>
</body>
</html>
'''
# Pass all products to the template for lookup
return render_template_string(favorites_html, all_products=all_products, repo_id=REPO_ID)
@app.route('/discounts')
def discounts_page():
data = load_data()
all_products = data['products'] # Get all products
products_with_discount = [(p, i) for i, p in enumerate(all_products) if p.get('discount')] # Keep original index
discounts_html = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Скидки</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
background: linear-gradient(135deg, #f5f7fa, #e4e7eb);
color: #333;
line-height: 1.6;
transition: background 0.3s, color 0.3s;
padding-bottom: 60px;
}
body.dark-mode {
background: linear-gradient(135deg, #1a1a2e, #2a2a3e);
color: #e0e0e0;
}
.container {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.header h1 {
font-size: 2rem;
font-weight: 700;
letter-spacing: 1px;
background: linear-gradient(90deg, #526df2, #7a8ff5);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.theme-toggle {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.3s ease;
}
.theme-toggle:hover {
color: #526df2;
}
body.dark-mode .theme-toggle {
color: #bbb;
}
.products-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
padding: 10px;
}
.product {
background: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.05);
border-radius: 15px;
padding: 15px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s ease, background 0.3s ease;
cursor: pointer;
position: relative;
overflow: hidden;
}
.product:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
background: rgba(255, 255, 255, 0.9);
}
body.dark-mode .product {
background: rgba(42, 42, 62, 0.8);
border-color: rgba(255, 255, 255, 0.05);
color: #e0e0e0;
}
body.dark-mode .product:hover {
background: rgba(42, 42, 62, 0.9);
box-shadow: 0 8px 25px rgba(255, 255, 255, 0.1);
}
.product-image {
width: 100%;
aspect-ratio: 1;
background-color: #fff;
border-radius: 10px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
transition: transform 0.3s ease;
}
body.dark-mode .product-image {
background-color: #333;
}
.product-image img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
transition: transform 0.3s ease;
}
.product-image img:hover {
transform: scale(1.05);
}
.product h2 {
font-size: 1.1rem;
font-weight: 500;
margin: 10px 0;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-price {
font-size: 1.2rem;
color: #e63946;
font-weight: 700;
text-align: center;
margin: 5px 0;
}
.product-price .wholesale {
font-size: 0.9rem;
color: #526df2;
font-weight: 500;
display: block;
margin-top: 5px;
}
.product-price .discount {
font-size: 0.9rem;
color: #2ecc71;
font-weight: 500;
display: block;
margin-top: 5px;
}
.product-description {
font-size: 0.85rem;
color: #666;
text-align: center;
margin-bottom: 15px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
body.dark-mode .product-description {
color: #bbb;
}
.product-button {
display: block;
width: 100%;
padding: 10px;
border: none;
border-radius: 25px;
background-color: #526df2;
color: white;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
margin: 5px 0;
text-align: center;
text-decoration: none;
}
.product-button:hover {
background-color: #3e55d1;
box-shadow: 0 4px 15px rgba(62, 85, 209, 0.4);
transform: translateY(-2px);
}
.add-to-cart {
background-color: #2ecc71;
}
.add-to-cart:hover {
background-color: #27ae60;
box-shadow: 0 4px 15px rgba(46, 204, 113, 0.4);
}
.favorite-button {
position: absolute;
top: 10px;
left: 10px;
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.3s ease;
}
.favorite-button.favorited {
color: #e63946;
}
.favorite-button:hover {
color: #e63946;
}
#cart-button {
position: fixed;
bottom: 80px;
right: 20px;
background-color: #e63946;
color: white;
border: none;
border-radius: 50%;
width: 60px;
height: 60px;
font-size: 1.5rem;
cursor: pointer;
display: none;
box-shadow: 0 4px 15px rgba(230, 57, 70, 0.4);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 1000;
}
#cart-button:hover {
transform: scale(1.1);
}
.modal {
display: none;
position: fixed;
z-index: 1001;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
backdrop-filter: blur(5px);
}
.modal-content {
background: #fff;
margin: 5% auto;
padding: 20px;
border-radius: 15px;
width: 90%;
max-width: 700px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
animation: slideIn 0.3s ease-out;
}
body.dark-mode .modal-content {
background: #2a2a3e;
color: #e0e0e0;
}
@keyframes slideIn {
from { transform: translateY(-50px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.close {
float: right;
font-size: 1.5rem;
color: #666;
cursor: pointer;
transition: color 0.3s;
}
.close:hover {
color: #333;
}
body.dark-mode .close {
color: #bbb;
}
body.dark-mode .close:hover {
color: #fff;
}
.cart-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
body.dark-mode .cart-item {
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.cart-item img {
width: 50px;
height: 50px;
object-fit: contain;
border-radius: 8px;
margin-right: 15px;
}
.quantity-input, .color-select {
width: 100%;
max-width: 150px;
padding: 8px;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 8px;
font-size: 1rem;
margin: 5px 0;
}
.clear-cart {
background-color: #e63946;
}
.clear-cart:hover {
background-color: #d62828;
box-shadow: 0 4px 15px rgba(230, 57, 70, 0.4);
}
.order-button {
background-color: #2ecc71;
}
.order-button:hover {
background-color: #27ae60;
box-shadow: 0 4px 15px rgba(46, 204, 113, 0.4);
}
.navbar {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
background-color: #fff;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
display: flex;
justify-content: space-around;
padding: 10px 0;
z-index: 1000;
}
body.dark-mode .navbar {
background-color: #2a2a3e;
}
.navbar a {
text-align: center;
color: #666;
text-decoration: none;
font-size: 0.9rem;
transition: color 0.3s ease;
}
.navbar a.active {
color: #526df2;
}
.navbar a i {
display: block;
font-size: 1.5rem;
margin-bottom: 5px;
}
body.dark-mode .navbar a {
color: #bbb;
}
.navbar a:hover {
color: #526df2;
}
.wholesale-badge {
position: absolute;
top: 10px;
right: 10px;
background-color: #526df2;
color: white;
padding: 5px 10px;
border-radius: 15px;
font-size: 0.75rem;
font-weight: 500;
}
.discount-badge {
position: absolute;
top: 40px;
right: 10px;
background-color: #2ecc71;
color: white;
padding: 5px 10px;
border-radius: 15px;
font-size: 0.75rem;
font-weight: 500;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Скидки</h1>
<button class="theme-toggle" onclick="toggleTheme()">
<i class="fas fa-moon"></i>
</button>
</div>
<div class="products-grid" id="products-grid">
{% if not products_with_discount %}
<p>Товаров со скидкой нет.</p>
{% else %}
{% for product, original_index in products_with_discount %}
<div class="product"
onclick="openModal({{ original_index }})"
data-original-index="{{ original_index }}"
data-name="{{ product['name']|lower }}"
data-description="{{ product['description']|lower }}"
data-category="{{ product.get('category', 'Без категории') }}">
<button class="favorite-button" onclick="event.stopPropagation(); toggleFavorite({{ original_index }})">
<i class="fas fa-heart"></i>
</button>
{% if product.get('photos') and product['photos']|length > 0 %}
<div class="product-image">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}"
alt="{{ product['name'] }}"
loading="lazy">
</div>
{% endif %}
{% if product.get('wholesale_price') and product.get('min_wholesale') %}
<span class="wholesale-badge">Опт от {{ product['min_wholesale'] }}</span>
{% endif %}
{% if product.get('discount') %}
<span class="discount-badge">Скидка {{ product['discount'] }}%</span>
{% endif %}
<h2>{{ product['name'] }}</h2>
<div class="product-price">
{% if product.get('discount') %}
<span style="text-decoration: line-through; color: #666;">{{ product['price'] }} с</span>
<span>{{ (product['price'] * (1 - product['discount'] / 100))|round(2) }} с</span>
<span class="discount">Скидка: {{ product['discount'] }}%</span>
{% else %}
<span>{{ product['price'] }} с</span>
{% endif %}
{% if product.get('wholesale_price') and product.get('min_wholesale') %}
<span class="wholesale">Опт: {{ product['wholesale_price'] }} с</span>
{% endif %}
</div>
<p class="product-description">{{ product['description'][:50] }}{% if product['description']|length > 50 %}...{% endif %}</p>
<button class="product-button add-to-cart" onclick="event.stopPropagation(); openQuantityModal({{ original_index }})">В корзину</button>
</div>
{% endfor %}
{% endif %}
</div>
</div>
<div id="productModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('productModal')">×</span>
<div id="modalContent"></div>
</div>
</div>
<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>
<button class="product-button" onclick="confirmAddToCart()">Добавить</button>
</div>
</div>
<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>Итого: <span id="cartTotal">0</span> с</strong>
<button class="product-button clear-cart" onclick="clearCart()">Очистить</button>
<button class="product-button order-button" onclick="orderViaWhatsApp()">Заказать</button>
</div>
</div>
</div>
<button id="cart-button" onclick="openCartModal()">🛒</button>
<div class="navbar">
<a href="/">
<i class="fas fa-home"></i>
Главная
</a>
<a href="/categories">
<i class="fas fa-list"></i>
Каталог
</a>
<a href="/favorites">
<i class="fas fa-heart"></i>
Избранное
</a>
<a href="/discounts" class="active">
<i class="fas fa-tag"></i>
Скидки
</a>
<a href="https://api.whatsapp.com/send?phone=996706004240">
<i class="fab fa-whatsapp"></i>
WhatsApp
</a>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
<script>
const allProducts = {{ all_products|tojson }}; // All products
// products_with_discount is implicitly used via the loop in HTML
let selectedProductOriginalIndex = null; // Store original index
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');
}
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark-mode');
document.querySelector('.theme-toggle i').classList.replace('fa-moon', 'fa-sun');
}
function openModal(originalIndex) { // Takes original index
loadProductDetails(originalIndex);
document.getElementById('productModal').style.display = "block";
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = "none";
}
function loadProductDetails(originalIndex) { // Takes original index
if (originalIndex < 0 || originalIndex >= allProducts.length) {
console.error("Invalid index for product details:", originalIndex);
document.getElementById('modalContent').innerHTML = '<p>Ошибка: Товар не найден.</p>';
return;
}
fetch('/product/' + originalIndex) // Use original index
.then(response => response.text())
.then(data => {
document.getElementById('modalContent').innerHTML = data;
initializeSwiper();
})
.catch(error => console.error('Ошибка:', error));
}
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 }
});
}
function openQuantityModal(originalIndex) { // Takes original index
if (originalIndex < 0 || originalIndex >= allProducts.length) {
console.error("Invalid index for quantity modal:", originalIndex);
return;
}
selectedProductOriginalIndex = originalIndex; // Store original index
const product = allProducts[originalIndex]; // Get product from allProducts
const colorSelect = document.getElementById('colorSelect');
colorSelect.innerHTML = '';
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);
}
document.getElementById('quantityModal').style.display = 'block';
document.getElementById('quantityInput').value = 1;
}
function confirmAddToCart() {
if (selectedProductOriginalIndex === null) return; // Use original index
const quantity = parseInt(document.getElementById('quantityInput').value) || 1;
const color = document.getElementById('colorSelect').value;
if (quantity <= 0) {
alert("Укажите количество больше 0");
return;
}
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
const product = allProducts[selectedProductOriginalIndex]; // Use original index
const cartItemId = `${product.name}-${color}`;
const existingItem = cart.find(item => item.id === cartItemId);
let priceToUse = product.price;
if (product.discount) {
priceToUse = product.price * (1 - product.discount / 100);
}
if (product.min_wholesale && quantity >= product.min_wholesale) {
priceToUse = product.wholesale_price;
}
if (existingItem) {
existingItem.quantity += quantity;
// Recalculate price based on potentially new quantity
existingItem.price = (existingItem.quantity >= (product.min_wholesale || Infinity))
? product.wholesale_price
: (product.discount ? product.price * (1 - product.discount / 100) : product.price);
} else {
cart.push({
id: cartItemId,
name: product.name,
price: priceToUse, // Use the calculated price
retail_price: product.price,
wholesale_price: product.wholesale_price,
min_wholesale: product.min_wholesale,
discount: product.discount,
photo: product.photos && product.photos.length > 0 ? product.photos[0] : '',
quantity: quantity,
color: color
});
}
localStorage.setItem('cart', JSON.stringify(cart));
closeModal('quantityModal');
updateCartButton();
}
function updateCartButton() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
document.getElementById('cart-button').style.display = cart.length > 0 ? 'block' : 'none';
}
function openCartModal() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
const cartContent = document.getElementById('cartContent');
let total = 0;
cartContent.innerHTML = cart.length === 0 ? '<p>Корзина пуста</p>' : cart.map(item => {
const currentPrice = (item.quantity >= (item.min_wholesale || Infinity))
? item.wholesale_price
: (item.discount ? item.retail_price * (1 - item.discount / 100) : item.retail_price);
item.price = parseFloat(currentPrice.toFixed(2)); // Ensure price is up-to-date and numeric
const itemTotal = item.price * item.quantity;
total += itemTotal;
return `
<div class="cart-item">
<div style="display: flex; align-items: center;">
${item.photo ? `<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}" alt="${item.name}">` : ''}
<div>
<strong>${item.name}</strong>
<p>${item.price.toFixed(2)} с × ${item.quantity} (Цвет: ${item.color})</p>
<p>${item.quantity >= (item.min_wholesale || Infinity) ? 'Оптовая цена' : (item.discount ? 'Скидка ' + item.discount + '%' : 'Розничная цена')}</p>
</div>
</div>
<span>${itemTotal.toFixed(2)} с</span>
</div>
`;
}).join('');
document.getElementById('cartTotal').textContent = total.toFixed(2);
document.getElementById('cartModal').style.display = 'block';
}
function orderViaWhatsApp() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]');
if (cart.length === 0) {
alert("Корзина пуста!");
return;
}
let total = 0;
let orderText = "Заказ:%0A";
cart.forEach((item, index) => {
// Recalculate price for the message
const currentPrice = (item.quantity >= (item.min_wholesale || Infinity))
? item.wholesale_price
: (item.discount ? item.retail_price * (1 - item.discount / 100) : item.retail_price);
const itemTotal = currentPrice * item.quantity;
total += itemTotal;
orderText += `${index + 1}. ${item.name} - ${currentPrice.toFixed(2)} с × ${item.quantity} (Цвет: ${item.color})%0A`;
});
orderText += `Итого: ${total.toFixed(2)} с`;
window.open(`https://api.whatsapp.com/send?phone=996706004240&text=${orderText}`, '_blank');
}
function clearCart() {
localStorage.removeItem('cart');
closeModal('cartModal');
updateCartButton();
}
function toggleFavorite(originalIndex) { // Takes original index
let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
const productId = originalIndex.toString();
const favoriteButton = document.querySelector(`.product[data-original-index="${originalIndex}"] .favorite-button`);
if (favorites.includes(productId)) {
favorites = favorites.filter(id => id !== productId);
if (favoriteButton) favoriteButton.classList.remove('favorited');
} else {
favorites.push(productId);
if (favoriteButton) favoriteButton.classList.add('favorited');
}
localStorage.setItem('favorites', JSON.stringify(favorites));
// Optional: If you want the item to disappear immediately from the discounts page when unfavorited
// loadDiscountPage(); // You'd need a function to reload this specific page's content
}
function loadFavorites() {
const favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
document.querySelectorAll('.product').forEach(productElement => {
const originalIndex = productElement.getAttribute('data-original-index');
if (originalIndex && favorites.includes(originalIndex)) {
const button = productElement.querySelector('.favorite-button');
if (button) {
button.classList.add('favorited');
}
}
});
}
window.onclick = function(event) {
if (event.target.className === 'modal') event.target.style.display = "none";
}
updateCartButton();
loadFavorites();
</script>
</body>
</html>
'''
# Pass all_products for JS and the filtered list with indices for the template loop
return render_template_string(discounts_html, all_products=all_products, products_with_discount=products_with_discount, repo_id=REPO_ID)
@app.route('/product/<int:index>')
def product_details(index):
data = load_data()
if (index < 0 or index >= len(data['products'])):
return "Product not found", 404
product = data['products'][index]
product_html = '''
<style>
.swiper-container {
width: 100%;
max-width: 400px;
margin: 20px auto;
}
.swiper-slide {
display: flex;
justify-content: center;
align-items: center;
background: #fff;
border-radius: 10px;
}
body.dark-mode .swiper-slide {
background: #333;
}
.swiper-slide img {
max-width: 100%;
max-height: 300px;
object-fit: contain;
}
.swiper-button-next, .swiper-button-prev {
color: #526df2;
}
.swiper-pagination-bullet-active {
background: #526df2;
}
.product-details h2 {
font-size: 1.5rem;
font-weight: 500;
margin-bottom: 10px;
}
.product-details .price {
font-size: 1.3rem;
color: #e63946;
font-weight: 700;
margin-bottom: 10px;
}
.product-details .price .wholesale {
font-size: 1rem;
color: #526df2;
font-weight: 500;
display: block;
margin-top: 5px;
}
.product-details .price .discount {
font-size: 1rem;
color: #2ecc71;
font-weight: 500;
display: block;
margin-top: 5px;
}
.product-details p {
font-size: 0.95rem;
color: #666;
margin-bottom: 10px;
}
body.dark-mode .product-details p {
color: #bbb;
}
.product-details .colors {
margin: 10px 0;
}
.product-details .colors span {
display: inline-block;
margin-right: 10px;
padding: 5px 10px;
border-radius: 15px;
background: #f0f0f0;
font-size: 0.9rem;
}
body.dark-mode .product-details .colors span {
background: #333;
color: #e0e0e0;
}
</style>
<div class="product-details">
<h2>{{ product['name'] }}</h2>
<div class="swiper-container">
<div class="swiper-wrapper">
{% if not product.get('photos') %}
<div class="swiper-slide">
<span>Нет фото</span>
</div>
{% else %}
{% for photo in product.get('photos', []) %}
<div class="swiper-slide">
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="{{ product['name'] }}">
</div>
{% endfor %}
{% endif %}
</div>
{% if product.get('photos') and product['photos']|length > 1 %}
<div class="swiper-pagination"></div>
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
{% endif %}
</div>
<div class="price">
{% if product.get('discount') %}
<span style="text-decoration: line-through; color: #666;">{{ product['price'] }} с</span>
<span>{{ (product['price'] * (1 - product['discount'] / 100))|round(2) }} с</span>
<span class="discount">Скидка: {{ product['discount'] }}%</span>
{% else %}
<span>{{ product['price'] }} с</span>
{% endif %}
{% if product.get('wholesale_price') and product.get('min_wholesale') %}
<span class="wholesale">Опт: {{ product['wholesale_price'] }} с (от {{ product['min_wholesale'] }})</span>
{% endif %}
</div>
<p><strong>Описание:</strong> {{ product['description'] }}</p>
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
{% if product.get('colors') %}
<div class="colors">
<strong>Цвета:</strong>
{% for color in product['colors'] %}
<span>{{ color }}</span>
{% endfor %}
</div>
{% endif %}
</div>
'''
return render_template_string(product_html, product=product, repo_id=REPO_ID)
@app.route('/admin', methods=['GET', 'POST'])
def admin():
data = load_data()
products = data['products']
categories = data['categories']
if request.method == 'POST':
action = request.form.get('action')
if action == 'add':
photos = request.files.getlist('photos')
photo_filenames = []
for photo in photos:
if photo and photo.filename:
filename = secure_filename(photo.filename)
uploads_dir = "uploads"
os.makedirs(uploads_dir, exist_ok=True)
temp_path = os.path.join(uploads_dir, filename)
photo.save(temp_path)
try:
api = HfApi()
api.upload_file(
path_or_fileobj=temp_path,
path_in_repo=f"photos/{filename}",
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE
)
photo_filenames.append(filename)
except Exception as e:
logging.error(f"Error uploading photo {filename} to HF: {e}")
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
colors = request.form.getlist('colors')
colors = [color.strip() for color in colors if color.strip()]
new_product = {
'name': request.form['name'],
'price': float(request.form['price']),
'wholesale_price': float(request.form['wholesale_price']) if request.form['wholesale_price'] else None,
'min_wholesale': int(request.form['min_wholesale']) if request.form['min_wholesale'] else None,
'description': request.form['description'],
'category': request.form['category'],
'colors': colors,
'photos': photo_filenames,
'discount': float(request.form['discount']) if request.form['discount'] else None
}
products.append(new_product)
elif action == 'edit':
index = int(request.form['index'])
if 0 <= index < len(products):
photos = request.files.getlist('photos')
# Start with existing photos unless 'delete_existing_photos' is checked (implement if needed)
photo_filenames = products[index].get('photos', [])
for photo in photos:
if photo and photo.filename:
filename = secure_filename(photo.filename)
uploads_dir = "uploads"
os.makedirs(uploads_dir, exist_ok=True)
temp_path = os.path.join(uploads_dir, filename)
photo.save(temp_path)
try:
api = HfApi()
api.upload_file(
path_or_fileobj=temp_path,
path_in_repo=f"photos/{filename}",
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE
)
if filename not in photo_filenames: # Avoid duplicates if re-uploading
photo_filenames.append(filename)
except Exception as e:
logging.error(f"Error uploading photo {filename} during edit: {e}")
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
colors = request.form.getlist('colors')
colors = [color.strip() for color in colors if color.strip()]
products[index].update({
'name': request.form['name'],
'price': float(request.form['price']),
'wholesale_price': float(request.form['wholesale_price']) if request.form['wholesale_price'] else None,
'min_wholesale': int(request.form['min_wholesale']) if request.form['min_wholesale'] else None,
'description': request.form['description'],
'category': request.form['category'],
'colors': colors,
'photos': photo_filenames, # Updated photo list
'discount': float(request.form['discount']) if request.form['discount'] else None
})
else:
logging.error(f"Edit action failed: Index {index} out of bounds.")
elif action == 'delete':
index = int(request.form['index'])
if 0 <= index < len(products):
product_to_delete = products[index]
if 'photos' in product_to_delete and product_to_delete['photos']:
api = HfApi()
for photo in product_to_delete['photos']:
try:
api.delete_file(
path_in_repo=f"photos/{photo}",
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE
)
logging.info(f"Deleted photo {photo} from HF.")
except Exception as e:
logging.error(f"Error deleting photo {photo} from HF: {e}")
products.pop(index)
else:
logging.error(f"Delete action failed: Index {index} out of bounds.")
elif action == 'add_category':
category = request.form['category_name'].strip()
if category and category not in categories:
categories.append(category)
elif action == 'delete_category':
index = int(request.form['category_index'])
if 0 <= index < len(categories):
category_to_delete = categories[index]
categories.pop(index)
# Set category to "Без категории" for products in the deleted category
for product in products:
if product.get('category') == category_to_delete:
product['category'] = 'Без категории'
else:
logging.error(f"Delete category action failed: Index {index} out of bounds.")
save_data({'products': products, 'categories': categories})
return redirect(url_for('admin'))
admin_html = '''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Админ-панель</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
background: linear-gradient(135deg, #f5f7fa, #e4e7eb);
color: #333;
line-height: 1.6;
padding: 20px;
}
.container {
max-width: 1400px;
margin: 0 auto;
}
h1 {
font-size: 2rem;
font-weight: 700;
margin-bottom: 20px;
text-align: center;
background: linear-gradient(90deg, #526df2, #7a8ff5);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.form-container, .category-list-container, .product-list-container {
background: rgba(255, 255, 255, 0.9);
border-radius: 15px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}
.form-container h1, .category-list-container h1, .product-list-container h1 {
font-size: 1.5rem; /* Smaller heading for sections */
text-align: left;
margin-bottom: 15px;
background: none;
-webkit-background-clip: unset;
-webkit-text-fill-color: #526df2; /* Solid color */
}
.form-container label, .edit-form label {
display: block;
margin: 10px 0 5px;
font-weight: 500;
}
.form-container input[type="text"],
.form-container input[type="number"],
.form-container input[type="file"],
.form-container textarea,
.form-container select,
.edit-form input[type="text"],
.edit-form input[type="number"],
.edit-form input[type="file"],
.edit-form textarea,
.edit-form select {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 8px;
font-size: 1rem;
background-color: #fff; /* Ensure inputs are white */
color: #333;
}
.form-container textarea, .edit-form textarea {
resize: vertical;
min-height: 80px;
}
.form-container button, .edit-form button, .category-item button, .product-item button {
padding: 10px 20px;
border: none;
border-radius: 25px;
background-color: #526df2;
color: white;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s ease;
margin: 5px 5px 5px 0; /* Adjust margin */
vertical-align: middle; /* Align buttons better */
}
.form-container button:hover, .edit-form button:hover, .category-item button:hover, .product-item button:hover {
background-color: #3e55d1;
box-shadow: 0 4px 15px rgba(62, 85, 209, 0.4);
}
.add-color-btn {
background-color: #2ecc71;
font-size: 0.9rem; /* Smaller button */
padding: 8px 15px;
}
.add-color-btn:hover {
background-color: #27ae60;
box-shadow: 0 4px 15px rgba(46, 204, 113, 0.4);
}
.color-input-group {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.color-input-group input {
flex: 1;
margin-right: 10px; /* Add space before potential remove button */
}
.category-list, .product-list {
display: grid;
gap: 15px; /* Slightly smaller gap */
}
.category-item, .product-item {
background: rgba(255, 255, 255, 0.95);
border: 1px solid rgba(0, 0, 0, 0.08); /* Slightly more visible border */
border-radius: 10px;
padding: 15px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
display: flex; /* Use flexbox for category items */
justify-content: space-between; /* Space out name and button */
align-items: center; /* Vertically align items */
}
.product-item {
display: block; /* Products keep block display */
}
.category-item h2, .product-item h2 {
font-size: 1.2rem;
font-weight: 500;
margin: 0 0 10px 0; /* Adjusted margin */
color: #333;
}
.category-item form, .product-item form {
display: inline-block; /* Keep forms inline */
margin-left: 10px; /* Add space between edit/delete buttons */
}
.category-item form:first-of-type {
margin-left: 0; /* No left margin for the first button in a group */
}
.product-item form:first-of-type {
margin-left: 0;
}
.delete-button {
background-color: #e63946;
}
.delete-button:hover {
background-color: #d62828;
box-shadow: 0 4px 15px rgba(230, 57, 70, 0.4);
}
details {
margin: 15px 0 10px 0; /* More space around details */
border-top: 1px solid #eee; /* Separator line */
padding-top: 15px;
}
summary {
cursor: pointer;
font-weight: 500;
color: #526df2;
margin-bottom: 10px;
list-style: none; /* Remove default marker */
position: relative;
padding-left: 20px;
}
summary::before { /* Custom marker */
content: '▶';
position: absolute;
left: 0;
top: 0;
transition: transform 0.2s;
font-size: 0.8em;
color: #526df2;
}
details[open] summary::before {
transform: rotate(90deg);
}
.edit-form {
margin-top: 10px;
padding: 15px;
background-color: #f9f9f9; /* Slightly different background for edit form */
border-radius: 8px;
}
.search-container {
margin: 20px 0;
text-align: center;
}
#search-input {
width: 90%;
max-width: 600px;
padding: 12px 18px;
font-size: 1rem;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 25px;
outline: none;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
transition: all 0.3s ease;
}
#search-input:focus {
border-color: #526df2;
box-shadow: 0 4px 15px rgba(82, 109, 242, 0.2);
}
.product-item img {
max-width: 80px; /* Smaller image previews */
max-height: 80px;
margin: 5px;
border: 1px solid #eee;
border-radius: 4px;
vertical-align: middle;
}
.photo-preview-container {
margin-top: 5px;
}
</style>
</head>
<body>
<div class="container">
<h1>Админ-панель</h1>
<div class="form-container">
<h1>Добавить товар</h1>
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="add">
<label for="add-name">Название:</label>
<input type="text" id="add-name" name="name" required>
<label for="add-price">Цена (розница):</label>
<input type="number" id="add-price" name="price" step="0.01" min="0" required>
<label for="add-wholesale-price">Цена (опт):</label>
<input type="number" id="add-wholesale-price" name="wholesale_price" step="0.01" min="0">
<label for="add-min-wholesale">Минимальное количество для опта:</label>
<input type="number" id="add-min-wholesale" name="min_wholesale" min="1">
<label for="add-discount">Скидка (%):</label>
<input type="number" id="add-discount" name="discount" min="0" max="100" step="0.1">
<label for="add-description">Описание:</label>
<textarea id="add-description" name="description" rows="4" required></textarea>
<label for="add-category">Категория:</label>
<select id="add-category" name="category">
<option value="Без категории">Без категории</option>
{% for category in categories %}
<option value="{{ category }}">{{ category }}</option>
{% endfor %}
</select>
<label for="add-photos">Фотографии (до 10):</label>
<input type="file" id="add-photos" name="photos" accept="image/*" multiple>
<label>Цвета:</label>
<div id="color-inputs">
<div class="color-input-group">
<input type="text" name="colors" placeholder="Например: Красный">
</div>
</div>
<button type="button" class="add-color-btn" onclick="addColorInput()">Добавить цвет</button>
<br>
<button type="submit">Добавить товар</button>
</form>
</div>
<div class="category-list-container">
<h1>Категории</h1>
<div class="form-container" style="margin-bottom: 15px; padding: 15px;">
<h2>Добавить категорию</h2>
<form method="POST" style="display: flex; align-items: center;">
<input type="hidden" name="action" value="add_category">
<label for="category_name" style="margin: 0 10px 0 0; white-space: nowrap;">Название:</label>
<input type="text" id="category_name" name="category_name" required style="flex-grow: 1; margin-bottom: 0;">
<button type="submit" style="margin-left: 10px;">Добавить</button>
</form>
</div>
<div class="category-list">
{% for category in categories %}
<div class="category-item">
<h2>{{ category }}</h2>
<form method="POST">
<input type="hidden" name="action" value="delete_category">
<input type="hidden" name="category_index" value="{{ loop.index0 }}">
<button type="submit" class="delete-button">Удалить</button>
</form>
</div>
{% endfor %}
</div>
</div>
<div class="product-list-container">
<h1>Список товаров</h1>
<div class="search-container">
<input type="text" id="search-input" placeholder="Поиск товаров по названию, описанию, категории...">
</div>
<div class="product-list" id="product-list">
{% for product in products %}
<div class="product-item"
data-name="{{ product['name']|lower }}"
data-description="{{ product['description']|lower }}"
data-category="{{ product.get('category', 'Без категории')|lower }}">
<h2>{{ product['name'] }}</h2>
<p><strong>Цена (розница):</strong> {{ product['price'] }} с</p>
{% if product.get('wholesale_price') and product.get('min_wholesale') %}
<p><strong>Цена (опт):</strong> {{ product['wholesale_price'] }} с (от {{ product['min_wholesale'] }})</p>
{% endif %}
{% if product.get('discount') %}
<p><strong>Скидка:</strong> {{ product['discount'] }}%</p>
{% endif %}
<p><strong>Описание:</strong> {{ product['description'] }}</p>
<p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
<p><strong>Цвета:</strong> {{ product.get('colors', ['Нет'])|join(', ') }}</p>
{% if product.get('photos') %}
<div class="photo-preview-container">
<strong>Фото:</strong>
{% for photo in product['photos'] %}
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="{{ product['name'] }}">
{% endfor %}
</div>
{% endif %}
<form method="POST" style="display: inline-block;">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="index" value="{{ loop.index0 }}">
<button type="submit" class="delete-button">Удалить</button>
</form>
<details>
<summary>Редактировать</summary>
<form method="POST" enctype="multipart/form-data" class="edit-form">
<input type="hidden" name="action" value="edit">
<input type="hidden" name="index" value="{{ loop.index0 }}">
<label for="edit-name-{{ loop.index0 }}">Название:</label>
<input type="text" id="edit-name-{{ loop.index0 }}" name="name" value="{{ product['name'] }}" required>
<label for="edit-price-{{ loop.index0 }}">Цена (розница):</label>
<input type="number" id="edit-price-{{ loop.index0 }}" name="price" step="0.01" min="0" value="{{ product['price'] }}" required>
<label for="edit-wholesale-price-{{ loop.index0 }}">Цена (опт):</label>
<input type="number" id="edit-wholesale-price-{{ loop.index0 }}" name="wholesale_price" step="0.01" min="0" value="{{ product.get('wholesale_price', '') }}">
<label for="edit-min-wholesale-{{ loop.index0 }}">Мин. кол-во для опта:</label>
<input type="number" id="edit-min-wholesale-{{ loop.index0 }}" name="min_wholesale" min="1" value="{{ product.get('min_wholesale', '') }}">
<label for="edit-discount-{{ loop.index0 }}">Скидка (%):</label>
<input type="number" id="edit-discount-{{ loop.index0 }}" name="discount" min="0" max="100" step="0.1" value="{{ product.get('discount', '') }}">
<label for="edit-description-{{ loop.index0 }}">Описание:</label>
<textarea id="edit-description-{{ loop.index0 }}" name="description" rows="4" required>{{ product['description'] }}</textarea>
<label for="edit-category-{{ loop.index0 }}">Категория:</label>
<select id="edit-category-{{ loop.index0 }}" name="category">
<option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option>
{% for category in categories %}
<option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option>
{% endfor %}
</select>
<label for="edit-photos-{{ loop.index0 }}">Добавить фото (существующие останутся):</label>
<input type="file" id="edit-photos-{{ loop.index0 }}" name="photos" accept="image/*" multiple>
<label>Цвета:</label>
<div id="edit-color-inputs-{{ loop.index0 }}">
{% if product.get('colors') %}
{% for color in product.get('colors', []) %}
<div class="color-input-group">
<input type="text" name="colors" value="{{ color }}">
{# Add remove button logic if needed #}
</div>
{% endfor %}
{% else %}
<div class="color-input-group">
<input type="text" name="colors" placeholder="Например: Синий">
</div>
{% endif %}
</div>
<button type="button" class="add-color-btn" onclick="addColorInput('edit-color-inputs-{{ loop.index0 }}')">Добавить цвет</button>
<br>
<button type="submit">Сохранить</button>
</form>
</details>
</div>
{% endfor %}
</div>
</div>
</div>
<script>
function addColorInput(containerId = 'color-inputs') {
const container = document.getElementById(containerId);
if (!container) return; // Exit if container not found
const newInputGroup = document.createElement('div');
newInputGroup.className = 'color-input-group';
newInputGroup.innerHTML = '<input type="text" name="colors" placeholder="Еще цвет...">'; // Add remove button here if desired
container.appendChild(newInputGroup);
}
document.getElementById('search-input').addEventListener('input', filterProducts);
function filterProducts() {
const searchTerm = document.getElementById('search-input').value.toLowerCase();
document.querySelectorAll('.product-item').forEach(product => {
const name = product.getAttribute('data-name');
const description = product.getAttribute('data-description');
const category = product.getAttribute('data-category'); // Ensure category is lowercased
const matchesSearch = name.includes(searchTerm) || description.includes(searchTerm) || category.includes(searchTerm);
product.style.display = matchesSearch ? 'block' : 'none';
});
}
</script>
</body>
</html>
'''
return render_template_string(admin_html, products=products, categories=categories, repo_id=REPO_ID)
@app.route('/backup', methods=['POST'])
def backup():
try:
upload_db_to_hf()
return "Резервная копия создана.", 200
except Exception as e:
logging.error(f"Backup failed: {e}")
return f"Ошибка создания резервной копии: {e}", 500
@app.route('/download', methods=['GET'])
def download():
try:
download_db_from_hf()
return "База данных скачана.", 200
except Exception as e:
logging.error(f"Download failed: {e}")
return f"Ошибка скачивания базы данных: {e}", 500
if __name__ == '__main__':
# Ensure uploads directory exists if used for temporary storage in admin
if not os.path.exists("uploads"):
os.makedirs("uploads", exist_ok=True)
# Start periodic backup in a separate thread
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
backup_thread.start()
# Initial data load attempt
try:
load_data()
logging.info("Initial data load successful.")
except Exception as e:
logging.error(f"Initial data load failed: {e}. Check HF connection and file existence.")
# Run the Flask app
app.run(debug=False, host='0.0.0.0', port=7860) # Changed debug to False for production-like run