diff --git "a/app.py" "b/app.py"
deleted file mode 100644--- "a/app.py"
+++ /dev/null
@@ -1,1824 +0,0 @@
-
-
-from flask import Flask, render_template_string, request, redirect, url_for, session, send_file, flash
-import json
-import os
-import logging
-import threading
-import time
-from datetime import datetime
-from huggingface_hub import HfApi, hf_hub_download
-from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
-from werkzeug.utils import secure_filename
-from dotenv import load_dotenv
-import shutil # Added for atomic saves
-
-load_dotenv()
-
-app = Flask(__name__)
-# IMPORTANT: Replace this with a strong, unique secret key, preferably stored securely (e.g., environment variable)
-app.secret_key = os.getenv('FLASK_SECRET_KEY', 'replace_this_with_a_real_secret_key_soola_67890')
-DATA_FILE = 'data_soola.json'
-USERS_FILE = 'users_soola.json'
-
-SYNC_FILES = [DATA_FILE, USERS_FILE]
-
-REPO_ID = "Kgshop/Soola"
-HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
-HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
-
-STORE_ADDRESS = "Рынок Дордой, Джунхай, терминал, 38"
-CURRENCY_CODE = 'KGS'
-CURRENCY_NAME = 'Кыргызский сом (с)'
-
-logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
-
-def download_db_from_hf(specific_file=None):
- if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
- logging.warning("Neither HF_TOKEN_READ nor HF_TOKEN_WRITE is set. Attempting download without token (may fail for private repos).")
- token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE # Use write token if read token isn't available
-
- files_to_download = [specific_file] if specific_file else SYNC_FILES
- logging.info(f"Attempting to download files {files_to_download} from HF repo {REPO_ID}...")
- downloaded_files_count = 0
- all_successful = True
- try:
- for file_name in files_to_download:
- try:
- local_path = hf_hub_download(
- repo_id=REPO_ID,
- filename=file_name,
- repo_type="dataset",
- token=token_to_use,
- local_dir=".",
- local_dir_use_symlinks=False,
- force_download=True,
- cache_dir=None # Avoid caching issues when forcing download
- )
- logging.info(f"File {file_name} successfully downloaded from Hugging Face to {local_path}.")
- downloaded_files_count += 1
- except RepositoryNotFoundError:
- logging.error(f"Repository {REPO_ID} not found on Hugging Face. Download aborted.")
- all_successful = False
- break
- except HfHubHTTPError as e:
- if e.response.status_code == 404:
- logging.warning(f"File {file_name} not found in repository {REPO_ID}. Skipping download for this file.")
- else:
- logging.error(f"HTTP error downloading {file_name} from Hugging Face: {e}", exc_info=True)
- all_successful = False
- except Exception as e:
- logging.error(f"Error downloading file {file_name} from Hugging Face: {e}", exc_info=True)
- all_successful = False
- logging.info(f"HF download process finished. Downloaded {downloaded_files_count}/{len(files_to_download)} files.")
- except Exception as e:
- logging.error(f"General error during Hugging Face download attempt: {e}", exc_info=True)
- all_successful = False
- return all_successful
-
-def load_data():
- file_path = DATA_FILE
- default_structure = {'products': [], 'categories': []}
- download_success = download_db_from_hf(specific_file=file_path)
-
- if not os.path.exists(file_path):
- logging.warning(f"Local file {file_path} not found, even after download attempt. Initializing with empty structure.")
- with open(file_path, 'w', encoding='utf-8') as f:
- json.dump(default_structure, f)
- return default_structure
-
- try:
- with open(file_path, 'r', encoding='utf-8') as file:
- data = json.load(file)
- logging.info(f"Data successfully loaded from {file_path}")
-
- if not isinstance(data, dict):
- logging.warning(f"{file_path} content is not a dictionary. Resetting to default structure.")
- return default_structure
- if 'products' not in data or not isinstance(data['products'], list):
- logging.warning(f"'products' key missing or not a list in {file_path}. Initializing.")
- data['products'] = []
- if 'categories' not in data or not isinstance(data['categories'], list):
- logging.warning(f"'categories' key missing or not a list in {file_path}. Initializing.")
- data['categories'] = []
- return data
- except json.JSONDecodeError:
- logging.error(f"JSON decode error in {file_path}. File might be corrupted. Returning default structure.", exc_info=True)
- # Optionally, try to re-download on decode error? Or just return default.
- # For now, returning default to prevent cascading errors.
- return default_structure
- except Exception as e:
- logging.error(f"Unknown error loading data from {file_path}: {e}", exc_info=True)
- return default_structure
-
-def save_data_atomic(data, file_path):
- temp_file_path = file_path + '.tmp'
- try:
- with open(temp_file_path, 'w', encoding='utf-8') as file:
- json.dump(data, file, ensure_ascii=False, indent=4)
- # Atomically replace the old file with the new one
- shutil.move(temp_file_path, file_path)
- logging.info(f"Data successfully saved atomically to {file_path}")
- return True
- except Exception as e:
- logging.error(f"Error during atomic save to {file_path}: {e}", exc_info=True)
- # Clean up temp file if it exists
- if os.path.exists(temp_file_path):
- try:
- os.remove(temp_file_path)
- except OSError as rm_err:
- logging.error(f"Error removing temporary file {temp_file_path}: {rm_err}")
- return False
-
-def save_data(data):
- if save_data_atomic(data, DATA_FILE):
- upload_db_to_hf(specific_file=DATA_FILE)
-
-def load_users():
- file_path = USERS_FILE
- default_structure = {}
- download_success = download_db_from_hf(specific_file=file_path)
-
- if not os.path.exists(file_path):
- logging.warning(f"Local file {file_path} not found, even after download attempt. Initializing with empty structure.")
- with open(file_path, 'w', encoding='utf-8') as f:
- json.dump(default_structure, f)
- return default_structure
-
- try:
- with open(file_path, 'r', encoding='utf-8') as file:
- users = json.load(file)
- logging.info(f"User data successfully loaded from {file_path}")
- return users if isinstance(users, dict) else default_structure
- except json.JSONDecodeError:
- logging.error(f"JSON decode error in {file_path}. File might be corrupted. Returning default structure.", exc_info=True)
- return default_structure
- except Exception as e:
- logging.error(f"Unknown error loading users from {file_path}: {e}", exc_info=True)
- return default_structure
-
-def save_users(users):
- if save_data_atomic(users, USERS_FILE):
- upload_db_to_hf(specific_file=USERS_FILE)
-
-def upload_db_to_hf(specific_file=None):
- if not HF_TOKEN_WRITE:
- logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.")
- return
- try:
- api = HfApi()
- files_to_upload = [specific_file] if specific_file else SYNC_FILES
- logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...")
-
- for file_name in files_to_upload:
- if os.path.exists(file_name):
- try:
- api.upload_file(
- path_or_fileobj=file_name,
- path_in_repo=file_name,
- repo_id=REPO_ID,
- repo_type="dataset",
- token=HF_TOKEN_WRITE,
- commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
- )
- logging.info(f"File {file_name} successfully uploaded to Hugging Face.")
- except Exception as e:
- logging.error(f"Error uploading file {file_name} to Hugging Face: {e}")
- else:
- logging.warning(f"File {file_name} not found locally, skipping upload.")
- logging.info("HF upload process finished.")
- except Exception as e:
- logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True)
-
-def periodic_backup():
- backup_interval = 1800 # 30 minutes
- logging.info(f"Setting up periodic backup every {backup_interval} seconds.")
- while True:
- time.sleep(backup_interval)
- logging.info("Starting periodic backup...")
- upload_db_to_hf()
- logging.info("Periodic backup finished.")
-
-@app.route('/')
-def catalog():
- data = load_data()
- all_products = data.get('products', [])
- categories = sorted(data.get('categories', []))
- is_authenticated = 'user' in session
-
- products_in_stock = [p for p in all_products if p.get('in_stock', True)]
- products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
-
- catalog_html = '''
-
-
-
-
-
- Soola Cosmetics - Каталог
-
-
-
-
-
-
-
-
-
-
Наш адрес: {{ store_address }}
-
-
- Все категории
- {% for category in categories %}
- {{ category }}
- {% endfor %}
-
-
-
-
-
-
-
- {% for product in products %}
-
- {% if product.get('is_top', False) %}
-
Топ
- {% endif %}
-
- {% if product.get('photos') and product['photos']|length > 0 %}
-
- {% else %}
-
- {% endif %}
-
-
-
{{ product['name'] }}
- {% if is_authenticated %}
-
{{ "%.2f"|format(product['price']) }} {{ currency_code }}
- {% else %}
-
Цена доступна после входа
- {% endif %}
-
{{ product.get('description', '')[:50] }}{% if product.get('description', '')|length > 50 %}...{% endif %}
-
-
- Подробнее
- {% if is_authenticated %}
-
- В корзину
-
- {% endif %}
-
-
- {% endfor %}
- {% if not products %}
-
Товары пока не добавлены.
- {% endif %}
-
-
-
-
-
-
-
- ×
-
Укажите количество и цвет
- Количество:
-
- Цвет/Вариант:
-
- Добавить в корзину
-
-
-
-
-
-
×
-
Ваша корзина
-
-
- Итого: 0.00 {{ currency_code }}
-
-
-
- Очистить корзину
-
-
- Заказать через WhatsApp
-
-
-
-
-
-
-
- 0
-
-
-
-
-
-
-
-
- '''
- return render_template_string(
- catalog_html,
- products=products_sorted,
- categories=categories,
- repo_id=REPO_ID,
- is_authenticated=is_authenticated,
- store_address=STORE_ADDRESS,
- session=session,
- currency_code=CURRENCY_CODE
- )
-
-
-@app.route('/product/')
-def product_detail(index):
- data = load_data()
- all_products = data.get('products', [])
- # Filter and sort again here to ensure consistency with the catalog view
- products_in_stock = [p for p in all_products if p.get('in_stock', True)]
- products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
-
- is_authenticated = 'user' in session
- try:
- if not (0 <= index < len(products_sorted)):
- raise IndexError("Index out of bounds for available products.")
- product = products_sorted[index]
- except IndexError as e:
- logging.warning(f"Product detail access error: {e} (Index: {index})")
- return "Товар не найден или отсутствует в наличии.", 404
-
- detail_html = '''
-
-
{{ product['name'] }}
-
-
- {% if product.get('photos') and product['photos']|length > 0 %}
- {% for photo in product['photos'] %}
-
-
-
-
-
- {% endfor %}
- {% else %}
-
-
-
- {% endif %}
-
- {% if product.get('photos') and product['photos']|length > 1 %}
-
-
-
- {% endif %}
-
-
-
-
Категория: {{ product.get('category', 'Без категории') }}
- {% if is_authenticated %}
-
Цена: {{ "%.2f"|format(product['price']) }} {{ currency_code }}
- {% else %}
-
Цена: Доступна после входа
- {% endif %}
-
Описание: {{ product.get('description', 'Описание отсутствует.')|replace('\\n', ' ')|safe }}
- {% set colors = product.get('colors', []) %}
- {% set valid_colors = colors|select('string')|select('ne', '')|list %}
- {% if valid_colors|length > 0 %}
-
Доступные цвета/варианты: {{ valid_colors|join(', ') }}
- {% endif %}
-
-
- '''
- return render_template_string(
- detail_html,
- product=product,
- repo_id=REPO_ID,
- is_authenticated=is_authenticated,
- currency_code=CURRENCY_CODE
- )
-
-LOGIN_TEMPLATE = '''
-
-
-
-
-
- Вход - Soola Cosmetics
-
-
-
-
-
-
-
-'''
-
-@app.route('/login', methods=['GET', 'POST'])
-def login():
- if request.method == 'POST':
- login = request.form.get('login')
- password = request.form.get('password')
- if not login or not password:
- return render_template_string(LOGIN_TEMPLATE, error="Логин и пароль не могут быть пустыми."), 400
-
- users = load_users()
-
- if login in users and users[login].get('password') == password:
- user_info = users[login]
- session['user'] = login
- session['user_info'] = {
- 'login': login,
- 'first_name': user_info.get('first_name', ''),
- 'last_name': user_info.get('last_name', ''),
- 'country': user_info.get('country', ''),
- 'city': user_info.get('city', ''),
- 'phone': user_info.get('phone', '')
- }
- logging.info(f"User {login} logged in successfully.")
- # No need for localStorage auto-login here, session handles it
- return redirect(url_for('catalog'))
- else:
- logging.warning(f"Failed login attempt for user {login}.")
- error_message = "Неверный логин или пароль."
- return render_template_string(LOGIN_TEMPLATE, error=error_message), 401
-
- return render_template_string(LOGIN_TEMPLATE, error=None)
-
-# Removed auto_login route as it caused issues and session handles persistence
-
-@app.route('/logout')
-def logout():
- logged_out_user = session.get('user')
- session.pop('user', None)
- session.pop('user_info', None)
- if logged_out_user:
- logging.info(f"User {logged_out_user} logged out.")
- # No need for localStorage interaction here
- return redirect(url_for('catalog'))
-
-
-ADMIN_TEMPLATE = '''
-
-
-
-
-
- Админ-панель - Soola Cosmetics
-
-
-
-
-
-
-
-
- {% with messages = get_flashed_messages(with_categories=true) %}
- {% if messages %}
- {% for category, message in messages %}
-
{{ message }}
- {% endfor %}
- {% endif %}
- {% endwith %}
-
-
-
Синхронизация с Датацентром
-
-
-
-
-
Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.
-
-
-
-
-
-
-
Управление категориями
-
- Добавить новую категорию
-
-
-
-
-
-
Существующие категории:
- {% if categories %}
-
- {% for category in categories %}
-
- {{ category }}
-
-
- {% endfor %}
-
- {% else %}
-
Категорий пока нет.
- {% endif %}
-
-
-
-
-
-
Управление пользователями
-
- Добавить нового пользователя
-
-
-
-
Список пользователей:
- {% if users %}
-
- {% for login, user_data in users.items() %}
-
-
Логин: {{ login }}
-
Имя: {{ user_data.get('first_name', 'N/A') }} {{ user_data.get('last_name', '') }}
-
Телефон: {{ user_data.get('phone', 'N/A') }}
-
Локация: {{ user_data.get('city', 'N/A') }}, {{ user_data.get('country', 'N/A') }}
-
-
-
-
- {% endfor %}
-
- {% else %}
-
Пользователей пока нет.
- {% endif %}
-
-
-
-
-
-
-
Управление товарами
-
- Добавить новый товар
-
-
-
-
Список товаров:
- {% if products %}
-
- {% for product in products %}
-
-
-
- {% if product.get('photos') and product['photos']|length > 0 %}
-
-
-
- {% else %}
-
- {% endif %}
-
-
-
- {{ product['name'] }}
- {% if product.get('in_stock', True) %}
- В наличии
- {% else %}
- Нет в наличии
- {% endif %}
- {% if product.get('is_top', False) %}
- Топ
- {% endif %}
-
-
Категория: {{ product.get('category', 'Без категории') }}
-
Цена: {{ "%.2f"|format(product['price']) }} {{ currency_code }}
-
Описание: {{ product.get('description', 'N/A')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}
- {% set colors = product.get('colors', []) %}
- {% set valid_colors = colors|select('string')|select('ne', '')|list %}
-
Цвета/Вар-ты: {{ valid_colors|join(', ') if valid_colors|length > 0 else 'Нет' }}
- {% if product.get('photos') and product['photos']|length > 1 %}
-
(Всего фото: {{ product['photos']|length }})
- {% endif %}
-
-
-
-
- Редактировать
-
-
-
- Удалить
-
-
-
-
-
- {% endfor %}
-
- {% else %}
-
Товаров пока нет.
- {% endif %}
-
-
-
-
-
-
-
-'''
-
-@app.route('/admin', methods=['GET', 'POST'])
-def admin():
- # Ensure only logged-in users (or specific admin users if implemented) can access
- # if 'user' not in session: # Basic check, enhance if roles needed
- # flash("Доступ запрещен. Пожалуйста, войдите.", "error")
- # return redirect(url_for('login'))
-
- data = load_data()
- users = load_users()
- # Keep original product list with original indices for editing/deleting
- original_product_list = data.get('products', [])
- categories = sorted(data.get('categories', [])) # Keep categories sorted for display
-
- if request.method == 'POST':
- action = request.form.get('action')
- logging.info(f"Admin action received: {action}")
-
- try:
- if action == 'add_category':
- category_name = request.form.get('category_name', '').strip()
- if category_name and category_name not in data.get('categories', []):
- data.setdefault('categories', []).append(category_name)
- # No need to sort here, will be sorted on next load/display
- save_data(data)
- logging.info(f"Category '{category_name}' added.")
- flash(f"Категория '{category_name}' успешно добавлена.", 'success')
- elif not category_name:
- logging.warning("Attempt to add empty category.")
- flash("Название категории не может быть пустым.", 'error')
- else:
- logging.warning(f"Category '{category_name}' already exists.")
- flash(f"Категория '{category_name}' уже существует.", 'error')
-
- elif action == 'delete_category':
- category_to_delete = request.form.get('category_name')
- current_categories = data.get('categories', [])
- if category_to_delete and category_to_delete in current_categories:
- current_categories.remove(category_to_delete)
- updated_count = 0
- current_products = data.get('products', [])
- for product in current_products:
- if product.get('category') == category_to_delete:
- product['category'] = 'Без категории'
- updated_count += 1
- save_data(data)
- logging.info(f"Category '{category_to_delete}' deleted. Updated products: {updated_count}.")
- flash(f"Категория '{category_to_delete}' удалена.", 'success')
- else:
- logging.warning(f"Attempt to delete non-existent or empty category: {category_to_delete}")
- flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error')
-
- elif action == 'add_product':
- name = request.form.get('name', '').strip()
- price_str = request.form.get('price', '').replace(',', '.')
- description = request.form.get('description', '').strip()
- category = request.form.get('category')
- photos_files = request.files.getlist('photos')
- colors = [c.strip() for c in request.form.getlist('colors') if c.strip()]
- in_stock = request.form.get('in_stock') == 'true' # Checkbox value
- is_top = request.form.get('is_top') == 'true' # Checkbox value
-
- if not name or not price_str:
- flash("Название и цена товара обязательны.", 'error')
- return redirect(url_for('admin'))
-
- try:
- price = round(float(price_str), 2)
- if price < 0: raise ValueError("Price cannot be negative")
- except ValueError:
- flash("Неверный формат цены или отрицательное значение.", 'error')
- return redirect(url_for('admin'))
-
- photos_list = []
- if photos_files and any(f.filename for f in photos_files) and HF_TOKEN_WRITE:
- uploads_dir = 'uploads_temp'
- os.makedirs(uploads_dir, exist_ok=True)
- api = HfApi()
- photo_limit = 10
- uploaded_count = 0
- for photo in photos_files:
- if not photo or not photo.filename: continue
- if uploaded_count >= photo_limit:
- logging.warning(f"Photo limit ({photo_limit}) reached, ignoring further files.")
- flash(f"Загружено только первые {photo_limit} фото.", "warning")
- break
- try:
- ext = os.path.splitext(photo.filename)[1].lower()
- if ext not in ['.png', '.jpg', '.jpeg', '.gif', '.webp']:
- logging.warning(f"Skipping non-image file: {photo.filename}")
- continue
- safe_base = secure_filename(name.replace(' ','_') or 'product')
- photo_filename = f"{safe_base}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
- temp_path = os.path.join(uploads_dir, photo_filename)
- photo.save(temp_path)
- logging.info(f"Uploading photo {photo_filename} to HF for product {name}...")
- api.upload_file(
- path_or_fileobj=temp_path,
- path_in_repo=f"photos/{photo_filename}",
- repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
- commit_message=f"Add photo for product {name}"
- )
- photos_list.append(photo_filename)
- logging.info(f"Photo {photo_filename} uploaded successfully.")
- os.remove(temp_path)
- uploaded_count += 1
- except Exception as e:
- logging.error(f"Error uploading photo {photo.filename} to HF: {e}", exc_info=True)
- flash(f"Ошибка при загрузке фото {photo.filename}.", 'error')
- # Optionally remove temp file if upload failed
- if os.path.exists(temp_path): os.remove(temp_path)
- try: # Cleanup temp dir
- if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
- os.rmdir(uploads_dir)
- except OSError as e:
- logging.warning(f"Could not remove temp upload dir {uploads_dir}: {e}")
-
- new_product = {
- 'name': name, 'price': price, 'description': description,
- 'category': category if category in data.get('categories', []) else 'Без категории',
- 'photos': photos_list, 'colors': colors,
- 'in_stock': in_stock, 'is_top': is_top
- }
- data.setdefault('products', []).append(new_product)
- save_data(data)
- logging.info(f"Product '{name}' added.")
- flash(f"Товар '{name}' успешно добавлен.", 'success')
-
- elif action == 'edit_product':
- index_str = request.form.get('index')
- if index_str is None:
- flash("Ошибка редактирования: индекс товара не передан.", 'error')
- return redirect(url_for('admin'))
-
- try:
- index = int(index_str)
- # Use the original list loaded at the start of the request
- if not (0 <= index < len(original_product_list)): raise IndexError("Index out of bounds")
- product_to_edit = original_product_list[index] # Get ref to the dict in the list
- original_name = product_to_edit.get('name', 'N/A')
- except (ValueError, IndexError):
- flash(f"Ошибка редактирования: неверный индекс товара '{index_str}'.", 'error')
- return redirect(url_for('admin'))
-
- # Update fields in the dictionary directly
- product_to_edit['name'] = request.form.get('name', product_to_edit.get('name', '')).strip()
- price_str = request.form.get('price', str(product_to_edit.get('price', 0))).replace(',', '.')
- product_to_edit['description'] = request.form.get('description', product_to_edit.get('description', '')).strip()
- category = request.form.get('category')
- product_to_edit['category'] = category if category in data.get('categories', []) else 'Без категории'
- product_to_edit['colors'] = [c.strip() for c in request.form.getlist('colors') if c.strip()]
- product_to_edit['in_stock'] = request.form.get('in_stock') == 'true'
- product_to_edit['is_top'] = request.form.get('is_top') == 'true'
-
- try:
- price = round(float(price_str), 2)
- if price < 0: raise ValueError("Price cannot be negative")
- product_to_edit['price'] = price
- except ValueError:
- logging.warning(f"Invalid price format '{price_str}' during edit for {original_name}. Price not changed.")
- flash(f"Неверный формат цены для товара '{product_to_edit['name']}'. Цена не изменена.", 'warning')
-
- photos_files = request.files.getlist('photos')
- # Check if any *new* files were actually selected
- if photos_files and any(f and f.filename for f in photos_files) and HF_TOKEN_WRITE:
- uploads_dir = 'uploads_temp'
- os.makedirs(uploads_dir, exist_ok=True)
- api = HfApi()
- new_photos_list = []
- photo_limit = 10
- uploaded_count = 0
- logging.info(f"Uploading new photos for product {product_to_edit['name']}...")
- for photo in photos_files:
- if not photo or not photo.filename: continue
- if uploaded_count >= photo_limit:
- logging.warning(f"Photo limit ({photo_limit}) reached, ignoring further files.")
- flash(f"Загружено только первые {photo_limit} фото.", "warning")
- break
- try:
- ext = os.path.splitext(photo.filename)[1].lower()
- if ext not in ['.png', '.jpg', '.jpeg', '.gif', '.webp']:
- logging.warning(f"Skipping non-image file: {photo.filename}")
- continue
- safe_base = secure_filename(product_to_edit['name'].replace(' ','_') or 'product')
- photo_filename = f"{safe_base}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
- temp_path = os.path.join(uploads_dir, photo_filename)
- photo.save(temp_path)
- logging.info(f"Uploading new photo {photo_filename} to HF...")
- api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}",
- repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
- commit_message=f"Update photo for product {product_to_edit['name']}")
- new_photos_list.append(photo_filename)
- logging.info(f"New photo {photo_filename} uploaded successfully.")
- os.remove(temp_path)
- uploaded_count += 1
- except Exception as e:
- logging.error(f"Error uploading new photo {photo.filename}: {e}", exc_info=True)
- flash(f"Ошибка при загрузке нового фото {photo.filename}.", 'error')
- if os.path.exists(temp_path): os.remove(temp_path)
- try: # Cleanup temp dir
- if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
- os.rmdir(uploads_dir)
- except OSError as e:
- logging.warning(f"Could not remove temp upload dir {uploads_dir}: {e}")
-
- # Only replace photos if new ones were successfully uploaded
- if new_photos_list:
- logging.info(f"Replacing photos for product {product_to_edit['name']}.")
- old_photos = product_to_edit.get('photos', [])
- if old_photos:
- logging.info(f"Attempting to delete old photos from HF: {old_photos}")
- try:
- # Use ignore_patterns for broader matching if needed, but paths_in_repo is safer
- api.delete_files(
- repo_id=REPO_ID,
- paths_in_repo=[f"photos/{p}" for p in old_photos if p], # Ensure no empty strings
- repo_type="dataset",
- token=HF_TOKEN_WRITE,
- commit_message=f"Delete old photos for product {product_to_edit['name']}",
- missing_ok=True # Don't fail if a photo was already deleted somehow
- )
- logging.info(f"Old photos deletion command sent for {product_to_edit['name']}.")
- except Exception as e:
- logging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True)
- flash("Не удалось удалить старые фотографии с сервера.", "warning")
- product_to_edit['photos'] = new_photos_list
- flash("Фотографии товара успешно обновлены.", "success")
- elif uploaded_count == 0 and any(f and f.filename for f in photos_files):
- # Files were selected, but none uploaded (e.g., all invalid format or upload errors)
- flash("Не удалось загрузить ни одну из выбранных новых фотографий.", "error")
- # If no new files were selected, photos remain unchanged.
-
- # Now save the entire modified data structure
- save_data(data)
- logging.info(f"Product '{original_name}' (index {index}) updated to '{product_to_edit['name']}'.")
- flash(f"Товар '{product_to_edit['name']}' успешно обновлен.", 'success')
-
- elif action == 'delete_product':
- index_str = request.form.get('index')
- if index_str is None:
- flash("Ошибка удаления: индекс товара не передан.", 'error')
- return redirect(url_for('admin'))
- try:
- index = int(index_str)
- # Use the original list loaded at the start of the request
- if not (0 <= index < len(original_product_list)): raise IndexError("Index out of bounds")
- # Remove from the main data structure
- deleted_product = data.get('products', []).pop(index)
- product_name = deleted_product.get('name', 'N/A')
-
- photos_to_delete = deleted_product.get('photos', [])
- if photos_to_delete and HF_TOKEN_WRITE:
- logging.info(f"Attempting to delete photos for deleted product '{product_name}' from HF: {photos_to_delete}")
- try:
- api = HfApi()
- api.delete_files(
- repo_id=REPO_ID,
- paths_in_repo=[f"photos/{p}" for p in photos_to_delete if p],
- repo_type="dataset",
- token=HF_TOKEN_WRITE,
- commit_message=f"Delete photos for deleted product {product_name}",
- missing_ok=True
- )
- logging.info(f"Photos deletion command sent for product '{product_name}'.")
- except Exception as e:
- logging.error(f"Error deleting photos {photos_to_delete} for product '{product_name}' from HF: {e}", exc_info=True)
- flash(f"Не удалось удалить фото для товара '{product_name}' с сервера.", "warning")
-
- save_data(data)
- logging.info(f"Product '{product_name}' (original index {index}) deleted.")
- flash(f"Товар '{product_name}' удален.", 'success')
- except (ValueError, IndexError):
- flash(f"Ошибка удаления: неверный индекс товара '{index_str}'.", 'error')
- except Exception as e:
- logging.error(f"Error during product deletion: {e}", exc_info=True)
- flash(f"Произошла ошибка при удалении товара.", 'error')
-
- elif action == 'add_user':
- login = request.form.get('login', '').strip()
- password = request.form.get('password') # Keep password as is, no stripping
- first_name = request.form.get('first_name', '').strip()
- last_name = request.form.get('last_name', '').strip()
- phone = request.form.get('phone', '').strip()
- country = request.form.get('country', '').strip()
- city = request.form.get('city', '').strip()
-
- if not login or not password:
- flash("Логин и пароль пользователя обязательны.", 'error')
- return redirect(url_for('admin'))
- if login in users:
- flash(f"Пользователь с логином '{login}' уже существует.", 'error')
- return redirect(url_for('admin'))
-
- users[login] = {
- 'password': password, # Store password as provided
- 'first_name': first_name, 'last_name': last_name,
- 'phone': phone,
- 'country': country, 'city': city
- }
- save_users(users)
- logging.info(f"User '{login}' added.")
- flash(f"Пользователь '{login}' успешно добавлен.", 'success')
-
- elif action == 'delete_user':
- login_to_delete = request.form.get('login')
- if login_to_delete and login_to_delete in users:
- del users[login_to_delete]
- save_users(users)
- logging.info(f"User '{login_to_delete}' deleted.")
- flash(f"Пользователь '{login_to_delete}' удален.", 'success')
- else:
- logging.warning(f"Attempt to delete non-existent or empty user: {login_to_delete}")
- flash(f"Не удалось удалить пользователя '{login_to_delete}'.", 'error')
-
- else:
- logging.warning(f"Received unknown admin action: {action}")
- flash(f"Неизвестное действие: {action}", 'warning')
-
- # Redirect after POST to prevent form resubmission on refresh
- return redirect(url_for('admin'))
-
- except Exception as e:
- logging.error(f"Error processing admin action '{action}': {e}", exc_info=True)
- flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'. Подробности в логе сервера.", 'error')
- # Redirect even on error to avoid broken state
- return redirect(url_for('admin'))
-
- # GET request: Render the template
- # Pass the original list to preserve indices for edit/delete forms
- # Pass sorted categories and users for display
- sorted_users = dict(sorted(users.items()))
-
- return render_template_string(
- ADMIN_TEMPLATE,
- products=original_product_list,
- categories=categories,
- users=sorted_users,
- repo_id=REPO_ID,
- currency_code=CURRENCY_CODE
- )
-
-@app.route('/force_upload', methods=['POST'])
-def force_upload():
- # Add access control if needed
- logging.info("Forcing upload to Hugging Face...")
- try:
- upload_db_to_hf()
- flash("Данные успешно загружены на Hugging Face.", 'success')
- except Exception as e:
- logging.error(f"Error during forced upload: {e}", exc_info=True)
- flash(f"Ошибка при загрузке на Hugging Face: {e}", 'error')
- return redirect(url_for('admin'))
-
-@app.route('/force_download', methods=['POST'])
-def force_download():
- # Add access control if needed
- logging.info("Forcing download from Hugging Face...")
- try:
- if download_db_from_hf():
- flash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success')
- # Reload data might be needed if the app holds state, but here it reloads on next request
- else:
- flash("Скачивание данных с Hugging Face завершилось с ошибками. Проверьте логи.", 'warning')
-
- except Exception as e:
- logging.error(f"Error during forced download: {e}", exc_info=True)
- flash(f"Ошибка при скачивании с Hugging Face: {e}", 'error')
- return redirect(url_for('admin'))
-
-
-if __name__ == '__main__':
- # Initial load on startup
- load_data()
- load_users()
-
- # Start backup thread only if write token exists
- if HF_TOKEN_WRITE:
- backup_thread = threading.Thread(target=periodic_backup, daemon=True)
- backup_thread.start()
- logging.info("Periodic backup thread started.")
- else:
- logging.warning("HF_TOKEN not set, periodic backup thread will NOT run.")
-
- # Run the Flask app
- port = int(os.environ.get('PORT', 7860))
- logging.info(f"Starting Flask app on host 0.0.0.0 port {port}")
- # Use Waitress or Gunicorn in production instead of development server
- app.run(debug=False, host='0.0.0.0', port=port)
-
-