from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify
import json
import os
import logging
import threading
import time
from datetime import datetime
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
from werkzeug.utils import secure_filename
from dotenv import load_dotenv
import requests
import uuid
import math
load_dotenv()
app = Flask(__name__)
app.secret_key = 'your_unique_secret_key_meka_shop_12345_no_login'
DATA_FILE = 'data.json'
SYNC_FILES = [DATA_FILE]
REPO_ID = "Kgshop/testsystem"
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
STORE_ADDRESS = "Рынок Кербент, 6 ряд , 3 контейнер / 5 ряд 25 контейнер "
CURRENCY_CODE = 'KGS'
CURRENCY_NAME = 'Кыргызский сом'
DOWNLOAD_RETRIES = 3
DOWNLOAD_DELAY = 5
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):
if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.")
token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE
files_to_download = [specific_file] if specific_file else SYNC_FILES
all_successful = True
for file_name in files_to_download:
success = False
for attempt in range(retries + 1):
try:
logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...")
local_path = hf_hub_download(
repo_id=REPO_ID,
filename=file_name,
repo_type="dataset",
token=token_to_use,
local_dir=".",
local_dir_use_symlinks=False,
force_download=True,
resume_download=False
)
logging.info(f"Successfully downloaded {file_name} to {local_path}.")
success = True
break
except RepositoryNotFoundError:
logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.")
return False
except HfHubHTTPError as e:
if e.response.status_code == 404:
logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.")
if attempt == 0 and not os.path.exists(file_name):
try:
if file_name == DATA_FILE:
with open(file_name, 'w', encoding='utf-8') as f:
json.dump({'products': [], 'categories': [], 'orders': {}, 'stock_movements': []}, f)
logging.info(f"Created empty local file {file_name} because it was not found on HF.")
except Exception as create_e:
logging.error(f"Failed to create empty local file {file_name}: {create_e}")
success = False
break
else:
logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...")
except requests.exceptions.RequestException as e:
logging.error(f"Network error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...")
except Exception as e:
logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True)
if attempt < retries:
time.sleep(delay)
if not success:
logging.error(f"Failed to download {file_name} after {retries + 1} attempts.")
all_successful = False
logging.info(f"Download process finished. Overall success: {all_successful}")
return all_successful
def upload_db_to_hf(specific_file=None):
if not HF_TOKEN_WRITE:
logging.warning("HF_TOKEN (for writing) not set. Skipping upload to Hugging Face.")
return
try:
api = HfApi()
files_to_upload = [specific_file] if specific_file else SYNC_FILES
logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...")
for file_name in files_to_upload:
if os.path.exists(file_name):
try:
api.upload_file(
path_or_fileobj=file_name,
path_in_repo=file_name,
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
)
logging.info(f"File {file_name} successfully uploaded to Hugging Face.")
except Exception as e:
logging.error(f"Error uploading file {file_name} to Hugging Face: {e}")
else:
logging.warning(f"File {file_name} not found locally, skipping upload.")
logging.info("Finished uploading files to HF.")
except Exception as e:
logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True)
def periodic_backup():
backup_interval = 1800
logging.info(f"Setting up periodic backup every {backup_interval} seconds.")
while True:
time.sleep(backup_interval)
logging.info("Starting periodic backup...")
upload_db_to_hf()
logging.info("Periodic backup finished.")
def load_data():
default_data = {'products': [], 'categories': [], 'orders': {}, 'stock_movements': []}
try:
with open(DATA_FILE, 'r', encoding='utf-8') as file:
data = json.load(file)
logging.info(f"Local data loaded successfully from {DATA_FILE}")
if not isinstance(data, dict):
logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.")
raise FileNotFoundError
if 'products' not in data: data['products'] = []
if 'categories' not in data: data['categories'] = []
if 'orders' not in data: data['orders'] = {}
if 'stock_movements' not in data: data['stock_movements'] = []
for product in data['products']:
if 'stock' not in product: product['stock'] = 0
if 'barcode' not in product: product['barcode'] = ''
return data
except FileNotFoundError:
logging.warning(f"Local file {DATA_FILE} not found. Attempting download from HF.")
except json.JSONDecodeError:
logging.error(f"Error decoding JSON in local {DATA_FILE}. File might be corrupt. Attempting download.")
if download_db_from_hf(specific_file=DATA_FILE):
try:
with open(DATA_FILE, 'r', encoding='utf-8') as file:
data = json.load(file)
logging.info(f"Data loaded successfully from {DATA_FILE} after download.")
if not isinstance(data, dict):
logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.")
return default_data
if 'products' not in data: data['products'] = []
if 'categories' not in data: data['categories'] = []
if 'orders' not in data: data['orders'] = {}
if 'stock_movements' not in data: data['stock_movements'] = []
for product in data['products']:
if 'stock' not in product: product['stock'] = 0
if 'barcode' not in product: product['barcode'] = ''
return data
except FileNotFoundError:
logging.error(f"File {DATA_FILE} still not found even after download reported success. Using default.")
return default_data
except json.JSONDecodeError:
logging.error(f"Error decoding JSON in downloaded {DATA_FILE}. Using default.")
return default_data
except Exception as e:
logging.error(f"Unknown error loading downloaded {DATA_FILE}: {e}. Using default.", exc_info=True)
return default_data
else:
logging.error(f"Failed to download {DATA_FILE} from HF after retries. Using empty default data structure.")
if not os.path.exists(DATA_FILE):
try:
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(default_data, f)
logging.info(f"Created empty local file {DATA_FILE} after failed download.")
except Exception as create_e:
logging.error(f"Failed to create empty local file {DATA_FILE}: {create_e}")
return default_data
def save_data(data):
try:
if not isinstance(data, dict):
logging.error("Attempted to save invalid data structure (not a dict). Aborting save.")
return
if 'products' not in data: data['products'] = []
if 'categories' not in data: data['categories'] = []
if 'orders' not in data: data['orders'] = {}
if 'stock_movements' not in data: data['stock_movements'] = []
with open(DATA_FILE, 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
logging.info(f"Data successfully saved to {DATA_FILE}")
upload_db_to_hf(specific_file=DATA_FILE)
except Exception as e:
logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True)
def get_product_by_identifier(data, identifier):
identifier_lower = identifier.lower()
for product in data.get('products', []):
if 'barcode' in product and product['barcode'] == identifier:
return product
if 'name' in product and product['name'].lower() == identifier_lower:
return product
return None
def get_product_by_index(data, index):
products = data.get('products', [])
try:
idx = int(index)
if 0 <= idx < len(products):
return products[idx]
except (ValueError, TypeError):
pass
return None
CATALOG_TEMPLATE = '''
Meka Shop - Каталог
Meka Shop
Наш адрес: {{ store_address }}
{% for category in categories %}
{% endfor %}
{% for product in products %}
{% if product.get('is_top', False) %}
Топ
{% endif %}
{% if product.get('photos') and product['photos']|length > 0 %}
{% else %}
{% endif %}
{% 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 stock_movements %}
{% for move in stock_movements|reverse %}
{{ "Приход" if move.type == 'receipt' else "Корректировка" }}
от {{ move.timestamp }}:
Товар: {{ move.product_name }} |
Кол-во: {{ move.quantity_change }}{{ " (было: " ~ (move.new_stock_level - move.quantity_change) ~ ", стало: " ~ move.new_stock_level ~ ")" if move.new_stock_level is not none }}
{% if move.reason %}
Причина: {{ move.reason }}
{% endif %}
{% endfor %}
{% else %}
Движений склада пока нет.
{% endif %}
Последние заказы (Продажи)
{% if orders %}
{% for order_id, order in orders|dictsort('created_at', reverse=true) %}
{% if product.get('photos') %}
{% else %}
{% endif %}
{{ product['name'] }}
Остаток: {{ product.get('stock', 0) }}
{% if product.get('in_stock', True) and product.get('stock', 0) > 0 %}
В наличии
{% else %}
Нет в наличии / Скрыт
{% endif %}
{% if product.get('is_top', False) %}
Топ
{% endif %}
'''
@app.route('/')
def catalog():
data = load_data()
all_products = data.get('products', [])
categories = sorted(data.get('categories', []))
products_sorted = sorted(all_products, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
return render_template_string(
CATALOG_TEMPLATE,
products=products_sorted,
categories=categories,
repo_id=REPO_ID,
store_address=STORE_ADDRESS,
currency_code=CURRENCY_CODE
)
@app.route('/product_detail_html/')
def product_detail_html(product_name):
data = load_data()
barcode = request.args.get('barcode')
product = None
if barcode:
product = get_product_by_identifier(data, barcode)
if not product:
# Fallback lookup by name (less reliable if names aren't unique)
for p in data.get('products', []):
if p.get('name') == product_name:
product = p
break
if not product:
return "Товар не найден.", 404
return render_template_string(
PRODUCT_DETAIL_TEMPLATE,
product=product,
repo_id=REPO_ID,
currency_code=CURRENCY_CODE
)
@app.route('/create_order', methods=['POST'])
def create_order():
order_data = request.get_json()
if not order_data or 'cart' not in order_data or not order_data['cart']:
logging.warning("Create order request missing cart data or cart is empty.")
return jsonify({"error": "Корзина пуста или не передана."}), 400
cart_items = order_data['cart']
data = load_data()
products = data.get('products', [])
# Validate stock before processing
stock_check_ok = True
items_to_process = []
for item in cart_items:
if not all(k in item for k in ('name', 'price', 'quantity')):
logging.error(f"Invalid cart item structure received: {item}")
return jsonify({"error": "Неверный формат товара в корзине."}), 400
try:
price = float(item['price'])
quantity = int(item['quantity'])
if price < 0 or quantity <= 0:
raise ValueError("Invalid price or quantity")
# Find the corresponding product in the database to check stock
product_in_db = None
# Priority: find by original index if available (from catalog)
if 'original_product_index' in item:
product_in_db = get_product_by_index(data, item['original_product_index'])
# Fallback: find by name+color or just name
if not product_in_db:
for p in products:
if p.get('name') == item['name']:
# If product has colors, check color match
if p.get('colors') and p.get('colors').filter(lambda c: c and c.strip() != "").length > 0:
if item.get('color', 'N/A') in p.get('colors', []):
product_in_db = p
break # Found by name and color
else:
product_in_db = p
break # Found by name, no colors or color N/A
if not product_in_db:
logging.error(f"Product '{item['name']}' not found in database during order creation.")
return jsonify({"error": f"Товар '{item['name']}' не найден."}), 400
if product_in_db.get('stock', 0) < quantity:
stock_check_ok = False
flash(f"Недостаточно '{item['name']}' ({item.get('color', 'N/A')}). Доступно: {product_in_db.get('stock', 0)}.", 'error')
logging.warning(f"Insufficient stock for '{item['name']}' (requested {quantity}, available {product_in_db.get('stock', 0)}).")
# Continue checking others to report all shortages at once
items_to_process.append({
"db_product": product_in_db, # Keep reference to update stock
"name": item['name'],
"price": price,
"quantity": quantity,
"color": item.get('color', 'N/A'),
"photo": item.get('photo'), # This is the filename from the product
"barcode": product_in_db.get('barcode', '') # Include barcode in order history
})
except (ValueError, TypeError) as e:
logging.error(f"Invalid price/quantity in cart item: {item}. Error: {e}")
return jsonify({"error": "Неверная цена или количество в товаре."}), 400
if not stock_check_ok:
# If any item failed stock check, redirect to catalog with flash messages
return jsonify({"error": "Ошибка остатков. Проверьте корзину."}), 400 # Use JSON error for fetch API
# Deduct stock and build order items
total_price = 0
order_items = []
stock_movements = data.get('stock_movements', [])
for item_proc in items_to_process:
item_proc['db_product']['stock'] = max(0, item_proc['db_product'].get('stock', 0) - item_proc['quantity'])
item_total = item_proc['price'] * item_proc['quantity']
total_price += item_total
order_items.append({
"name": item_proc['name'],
"price": item_proc['price'],
"quantity": item_proc['quantity'],
"color": item_proc['color'],
"photo": item_proc['photo'],
"photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item_proc['photo']}" if item_proc['photo'] else "https://via.placeholder.com/60x60.png?text=N/A",
"barcode": item_proc['barcode']
})
# Log stock movement for sale
movement_id = str(uuid.uuid4())
movement_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
stock_movements.append({
"id": movement_id,
"timestamp": movement_timestamp,
"type": "sale", # New type for sales deduction
"product_name": item_proc['name'],
"quantity_change": -item_proc['quantity'], # Negative for deduction
"new_stock_level": item_proc['db_product']['stock'],
"reason": f"Продажа (Заказ №{order_data.get('order_id', 'N/A')})",
"details": f"Цвет/вариант: {item_proc['color']}"
})
order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6]}"
order_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
new_order = {
"id": order_id,
"created_at": order_timestamp,
"items": order_items,
"total_price": round(total_price, 2),
"user_info": None,
"status": "new", # Status can be 'new', 'processed', etc.
"type": "customer_order" # Distinguish from admin sales if needed later
}
try:
if 'orders' not in data or not isinstance(data.get('orders'), dict):
data['orders'] = {}
data['orders'][order_id] = new_order
data['stock_movements'] = stock_movements # Update movements
data['products'] = products # Products list with updated stock levels
save_data(data)
logging.info(f"Order {order_id} created successfully (anonymously). Stock deducted.")
return jsonify({"order_id": order_id}), 201
except Exception as e:
logging.error(f"Failed to save order {order_id}: {e}", exc_info=True)
return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500
@app.route('/order/')
def view_order(order_id):
data = load_data()
order = data.get('orders', {}).get(order_id)
if order:
logging.info(f"Displaying order {order_id}")
else:
logging.warning(f"Order {order_id} not found.")
return render_template_string(ORDER_TEMPLATE,
order=order,
repo_id=REPO_ID,
currency_code=CURRENCY_CODE)
@app.route('/admin', methods=['GET', 'POST'])
def admin():
data = load_data()
products = data.get('products', [])
categories = data.get('categories', [])
orders = data.get('orders', {})
stock_movements = data.get('stock_movements', [])
if request.method == 'POST':
action = request.form.get('action')
logging.info(f"Admin action received: {action}")
try:
if action == 'add_category':
category_name = request.form.get('category_name', '').strip()
if category_name and category_name not in categories:
categories.append(category_name)
data['categories'] = categories
save_data(data)
logging.info(f"Category '{category_name}' added.")
flash(f"Категория '{category_name}' успешно добавлена.", 'success')
elif not category_name:
logging.warning("Attempted 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')
if category_to_delete and category_to_delete in categories:
categories.remove(category_to_delete)
updated_count = 0
for product in products:
if product.get('category') == category_to_delete:
product['category'] = 'Без категории'
updated_count += 1
data['categories'] = categories
data['products'] = products
save_data(data)
logging.info(f"Category '{category_to_delete}' deleted. Updated products: {updated_count}.")
flash(f"Категория '{category_to_delete}' удалена. {updated_count} товаров обновлено.", 'success')
else:
logging.warning(f"Attempted 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(',', '.')
stock_str = request.form.get('stock', '0')
barcode = request.form.get('barcode', '').strip()
description = request.form.get('description', '').strip()
category = request.form.get('category')
photos_files = request.files.getlist('photos')
colors = [c.strip() for c in request.form.getlist('colors') if c.strip()]
in_stock = 'in_stock' in request.form
is_top = 'is_top' in request.form
if not name or not price_str:
flash("Название и цена товара обязательны.", 'error')
return redirect(url_for('admin'))
try:
price = round(float(price_str), 2)
if price < 0: price = 0
except ValueError:
flash("Неверный формат цены.", 'error')
return redirect(url_for('admin'))
try:
stock = int(stock_str)
if stock < 0: stock = 0
except ValueError:
flash("Неверный формат остатка.", 'error')
return redirect(url_for('admin'))
# Check for duplicate barcode if provided
if barcode:
for p in products:
if p.get('barcode') == barcode:
flash(f"Товар со штрихкодом '{barcode}' уже существует ('{p.get('name', 'N/A')}').", '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 uploaded_count >= photo_limit:
logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.")
flash(f"Загружено только первые {photo_limit} фото.", "warning")
break
if photo and photo.filename:
try:
ext = os.path.splitext(photo.filename)[1].lower()
if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
logging.warning(f"Skipping non-image file upload: {photo.filename}")
flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")
continue
safe_name = secure_filename(name.replace(' ', '_'))[:50]
photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
temp_path = os.path.join(uploads_dir, photo_filename)
photo.save(temp_path)
logging.info(f"Uploading photo {photo_filename} to HF for product {name}...")
api.upload_file(
path_or_fileobj=temp_path,
path_in_repo=f"photos/{photo_filename}",
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Add photo for product {name}"
)
photos_list.append(photo_filename)
logging.info(f"Photo {photo_filename} uploaded successfully.")
os.remove(temp_path)
uploaded_count += 1
except Exception as e:
logging.error(f"Error uploading photo {photo.filename} to HF: {e}", exc_info=True)
flash(f"Ошибка при загрузке фото {photo.filename}.", 'error')
if os.path.exists(temp_path):
try: os.remove(temp_path)
except OSError: pass
elif photo and not photo.filename:
logging.warning("Received an empty photo file object when adding product.")
try:
if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
os.rmdir(uploads_dir)
except OSError as e:
logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}")
elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
flash("HF_TOKEN (write) не настроен. Фотографии не были загружены.", "warning")
new_product = {
'name': name, 'price': price, 'description': description,
'category': category if category in categories else 'Без категории',
'photos': photos_list, 'colors': colors,
'in_stock': in_stock, 'is_top': is_top,
'stock': stock, 'barcode': barcode
}
products.append(new_product)
data['products'] = products
save_data(data)
# Log initial stock movement if stock > 0
if stock > 0:
movement_id = str(uuid.uuid4())
movement_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data['stock_movements'].append({
"id": movement_id,
"timestamp": movement_timestamp,
"type": "receipt",
"product_name": name,
"quantity_change": stock,
"new_stock_level": stock,
"reason": "Начальный остаток при добавлении товара",
"details": ""
})
save_data(data) # Save again to include stock movement
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)
if not (0 <= index < len(products)):
raise IndexError("Product index out of range")
product_to_edit = products[index]
original_name = product_to_edit.get('name', 'N/A')
original_barcode = product_to_edit.get('barcode', '')
except (ValueError, IndexError):
flash(f"Ошибка редактирования: неверный индекс товара '{index_str}'.", 'error')
logging.error(f"Invalid index '{index_str}' for editing. Product list length: {len(products)}")
return redirect(url_for('admin'))
product_to_edit['name'] = request.form.get('name', product_to_edit['name']).strip()
price_str = request.form.get('price', str(product_to_edit['price'])).replace(',', '.')
new_barcode = request.form.get('barcode', '').strip()
product_to_edit['description'] = request.form.get('description', product_to_edit.get('description', '')).strip()
category = request.form.get('category')
product_to_edit['category'] = category if category in categories else 'Без категории'
product_to_edit['colors'] = [c.strip() for c in request.form.getlist('colors') if c.strip()]
product_to_edit['in_stock'] = 'in_stock' in request.form
product_to_edit['is_top'] = 'is_top' in request.form
# Stock is updated via add_stock_movement, not directly here
try:
price = round(float(price_str), 2)
if price < 0: price = 0
product_to_edit['price'] = price
except ValueError:
logging.warning(f"Invalid price format '{price_str}' during edit of product {original_name}. Price not changed.")
flash(f"Неверный формат цены для товара '{original_name}'. Цена не изменена.", 'warning')
# Check for duplicate barcode if changed and not empty
if new_barcode and new_barcode != original_barcode:
for i, p in enumerate(products):
if i != index and p.get('barcode') == new_barcode:
flash(f"Штрихкод '{new_barcode}' уже используется товаром '{p.get('name', 'N/A')}'.", 'error')
return redirect(url_for('admin'))
product_to_edit['barcode'] = new_barcode
photos_files = request.files.getlist('photos')
if photos_files and any(f.filename for f in photos_files) and HF_TOKEN_WRITE:
uploads_dir = 'uploads_temp'
os.makedirs(uploads_dir, exist_ok=True)
api = HfApi()
new_photos_list = []
photo_limit = 10
uploaded_count = 0
logging.info(f"Uploading new photos for product {product_to_edit['name']}...")
for photo in photos_files:
if uploaded_count >= photo_limit:
logging.warning(f"Photo limit ({photo_limit}) reached, ignoring remaining photos.")
flash(f"Загружено только первые {photo_limit} фото.", "warning")
break
if photo and photo.filename:
try:
ext = os.path.splitext(photo.filename)[1].lower()
if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
logging.warning(f"Skipping non-image file upload during edit: {photo.filename}")
flash(f"Файл {photo.filename} не является изображением и был пропущен.", "warning")
continue
safe_name = secure_filename(product_to_edit['name'].replace(' ', '_'))[:50]
photo_filename = f"{safe_name}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{ext}"
temp_path = os.path.join(uploads_dir, photo_filename)
photo.save(temp_path)
logging.info(f"Uploading new photo {photo_filename} to HF...")
api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}",
repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE,
commit_message=f"Update photo for product {product_to_edit['name']}")
new_photos_list.append(photo_filename)
logging.info(f"New photo {photo_filename} uploaded successfully.")
os.remove(temp_path)
uploaded_count += 1
except Exception as e:
logging.error(f"Error uploading new photo {photo.filename}: {e}", exc_info=True)
flash(f"Ошибка при загрузке нового фото {photo.filename}.", 'error')
if os.path.exists(temp_path):
try: os.remove(temp_path)
except OSError: pass
elif photo and not photo.filename:
logging.warning("Received an empty photo file object when editing product.")
try:
if os.path.exists(uploads_dir) and not os.listdir(uploads_dir):
os.rmdir(uploads_dir)
except OSError as e:
logging.warning(f"Could not remove temporary upload directory {uploads_dir}: {e}")
if new_photos_list:
logging.info(f"New photo list for product {product_to_edit['name']} generated.")
old_photos = product_to_edit.get('photos', [])
if old_photos:
logging.info(f"Attempting to delete old photos: {old_photos}")
try:
api.delete_files(
repo_id=REPO_ID,
paths_in_repo=[f"photos/{p}" for p in old_photos],
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Delete old photos for product {product_to_edit['name']}"
)
logging.info(f"Old photos for product {product_to_edit['name']} deleted from HF.")
except Exception as e:
logging.error(f"Error deleting old photos {old_photos} from HF: {e}", exc_info=True)
flash("Не удалось удалить старые фотографии с сервера. Новые фото загружены.", "warning")
product_to_edit['photos'] = new_photos_list
flash("Фотографии товара успешно обновлены.", "success")
elif uploaded_count == 0 and any(f.filename for f in photos_files):
flash("Не удалось загрузить новые фотографии (возможно, неверный формат).", "error")
elif not HF_TOKEN_WRITE and photos_files and any(f.filename for f in photos_files):
flash("HF_TOKEN (write) не настроен. Фотографии не были обновлены.", "warning")
products[index] = product_to_edit
data['products'] = products
save_data(data)
logging.info(f"Product '{original_name}' (index {index}) updated to '{product_to_edit['name']}'.")
flash(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)
if not (0 <= index < len(products)): raise IndexError("Product index out of range")
deleted_product = products.pop(index)
product_name = deleted_product.get('name', 'N/A')
photos_to_delete = deleted_product.get('photos', [])
if photos_to_delete and HF_TOKEN_WRITE:
logging.info(f"Attempting to delete photos for product '{product_name}' from HF: {photos_to_delete}")
try:
api = HfApi()
api.delete_files(
repo_id=REPO_ID,
paths_in_repo=[f"photos/{p}" for p in photos_to_delete],
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Delete photos for deleted product {product_name}"
)
logging.info(f"Photos for product '{product_name}' deleted from HF.")
except Exception as e:
logging.error(f"Error deleting photos {photos_to_delete} for product '{product_name}' from HF: {e}", exc_info=True)
flash(f"Не удалось удалить фото для товара '{product_name}' с сервера. Товар удален локально.", "warning")
elif photos_to_delete and not HF_TOKEN_WRITE:
logging.warning(f"HF_TOKEN (write) not set. Cannot delete photos {photos_to_delete} for deleted product '{product_name}'.")
flash(f"Товар '{product_name}' удален локально, но фото не удалены с сервера (токен не задан).", "warning")
data['products'] = products
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')
logging.error(f"Invalid index '{index_str}' for deletion. Product list length: {len(products)}")
elif action == 'add_stock_movement':
product_index_str = request.form.get('product_index')
movement_type = request.form.get('type')
quantity_str = request.form.get('quantity', '0')
reason = request.form.get('reason', '').strip()
if product_index_str is None or not movement_type or not quantity_str:
flash("Не все поля для движения остатков заполнены.", 'error')
return redirect(url_for('admin'))
try:
product_index = int(product_index_str)
quantity = int(quantity_str)
if quantity < 0 and movement_type != 'adjustment':
flash("Количество должно быть неотрицательным.", 'error')
return redirect(url_for('admin'))
if not (0 <= product_index < len(products)):
raise IndexError("Product index out of range")
product = products[product_index]
original_stock = product.get('stock', 0)
quantity_change = quantity
if movement_type == 'receipt':
product['stock'] = original_stock + quantity
log_type = 'receipt'
elif movement_type == 'adjustment':
# Adjustment quantity can be positive or negative. Interpret input 'quantity' as the CHANGE amount.
quantity_change = int(quantity_str) # Allow negative input for adjustment
product['stock'] = original_stock + quantity_change
product['stock'] = max(0, product['stock']) # Stock cannot go below zero
log_type = 'adjustment'
else:
flash("Неверный тип движения остатков.", 'error')
return redirect(url_for('admin'))
# Log the movement
movement_id = str(uuid.uuid4())
movement_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data['stock_movements'].append({
"id": movement_id,
"timestamp": movement_timestamp,
"type": log_type,
"product_name": product.get('name', 'N/A'),
"quantity_change": quantity_change,
"new_stock_level": product['stock'],
"reason": reason if reason else f"{log_type.capitalize()} stock",
"details": f"Было: {original_stock}, Стало: {product['stock']}"
})
# Update product's in_stock status based on stock level
product['in_stock'] = product['stock'] > 0
save_data(data)
logging.info(f"Stock movement for '{product.get('name', 'N/A')}': {log_type}, change {quantity_change}, new stock {product['stock']}.")
flash(f"Остаток товара '{product.get('name', 'N/A')}' обновлен: {product['stock']}.", 'success')
except (ValueError, IndexError) as e:
flash(f"Ошибка при учете остатков: неверные данные. {e}", 'error')
logging.error(f"Error processing stock movement: {e}", exc_info=True)
else:
logging.warning(f"Received unknown admin action: {action}")
flash(f"Неизвестное действие: {action}", 'warning')
return redirect(url_for('admin'))
except Exception as e:
logging.error(f"Произошла внутренняя ошибка при выполнении действия '{action}': {e}", exc_info=True)
flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'. Подробности в логе сервера.", 'error')
return redirect(url_for('admin'))
current_data = load_data()
# Sort products for display in admin
display_products = sorted(current_data.get('products', []), key=lambda p: p.get('name', '').lower())
display_categories = sorted(current_data.get('categories', []))
display_orders = current_data.get('orders', {})
display_stock_movements = current_data.get('stock_movements', [])
return render_template_string(
ADMIN_TEMPLATE,
products=display_products,
categories=display_categories,
orders=display_orders,
stock_movements=display_stock_movements,
repo_id=REPO_ID,
currency_code=CURRENCY_CODE
)
@app.route('/sales_terminal')
def sales_terminal():
return render_template_string(
SALES_TERMINAL_TEMPLATE,
currency_code=CURRENCY_CODE
)
@app.route('/lookup_product', methods=['POST'])
def lookup_product():
identifier_data = request.get_json()
identifier = identifier_data.get('identifier', '').strip()
if not identifier:
return jsonify({"error": "Идентификатор товара не предоставлен."}), 400
data = load_data()
# Find the product by barcode or name
found_product = get_product_by_identifier(data, identifier)
if found_product:
# Find the index of the found product in the current product list order
# This index might be different from its original index if the list was reordered
try:
# We need a stable way to reference the product, barcode is best.
# Or pass the barcode back to the client. Let's pass the barcode.
# The client can then send the barcode back in the sale request.
# This avoids issues with list index changing.
# Prepare product data for JSON response
product_data = {
"name": found_product.get('name'),
"price": found_product.get('price', 0.0),
"stock": found_product.get('stock', 0),
"barcode": found_product.get('barcode', ''),
"category": found_product.get('category', 'Без категории'),
"colors": found_product.get('colors', []),
"photo": found_product.get('photos', [None])[0], # First photo
"photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{found_product.get('photos', [None])[0]}" if found_product.get('photos') else "https://via.placeholder.com/80x80.png?text=No+Image"
}
logging.info(f"Product lookup successful for '{identifier}'. Found '{found_product.get('name')}'")
return jsonify({"product": product_data}), 200
except Exception as e:
logging.error(f"Error preparing product data for lookup response for '{identifier}': {e}", exc_info=True)
return jsonify({"error": "Внутренняя ошибка сервера при подготовке данных товара."}), 500
else:
logging.info(f"Product lookup failed for '{identifier}'.")
return jsonify({"product": None, "error": "Товар не найден."}), 404
@app.route('/register_sale', methods=['POST'])
def register_sale():
sale_data = request.get_json()
if not sale_data or 'items' not in sale_data or not sale_data['items']:
logging.warning("Register sale request missing items or items list is empty.")
return jsonify({"error": "Список продажи пуст."}), 400
sale_items = sale_data['items']
data = load_data()
products = data.get('products', [])
stock_movements = data.get('stock_movements', [])
# Validate and find products, check stock
items_to_process = []
stock_check_ok = True
errors = []
for item in sale_items:
if not all(k in item for k in ('name', 'quantity', 'color')):
logging.error(f"Invalid sale item structure received: {item}")
return jsonify({"error": "Неверный формат товара в списке продажи."}), 400
try:
quantity = int(item['quantity'])
if quantity <= 0:
raise ValueError("Invalid quantity")
# Find product by barcode if available, else by name+color
product_in_db = None
if item.get('barcode'):
product_in_db = get_product_by_identifier(data, item['barcode'])
if not product_in_db: # Fallback to name + color lookup
for p in products:
if p.get('name') == item['name']:
# If product has colors, check color match
if p.get('colors') and p.get('colors').filter(lambda c: c and c.strip() != "").length > 0:
if item.get('color', 'N/A') in p.get('colors', []):
product_in_db = p
break # Found by name and color
else:
product_in_db = p
break # Found by name, no colors or color N/A
if not product_in_db:
logging.error(f"Product '{item['name']}' not found in database during sale registration.")
errors.append(f"Товар '{item['name']}' не найден в системе.")
stock_check_ok = False
continue
if product_in_db.get('stock', 0) < quantity:
stock_check_ok = False
errors.append(f"Недостаточно '{item['name']}' ({item.get('color', 'N/A')}). Доступно: {product_in_db.get('stock', 0)}, запрошено: {quantity}.")
logging.warning(f"Insufficient stock for '{item['name']}' (requested {quantity}, available {product_in_db.get('stock', 0)}).")
continue
# Validate price consistency (optional, but good practice)
if abs(product_in_db.get('price', 0.0) - item.get('price', 0.0)) > 0.001: # Check if prices match database price closely
logging.warning(f"Price mismatch for '{item['name']}': Sale price {item.get('price')}, DB price {product_in_db.get('price')}. Using DB price.")
item_price = product_in_db.get('price', 0.0) # Use price from DB
else:
item_price = item.get('price', 0.0) # Use price from client if it matches DB
items_to_process.append({
"db_product": product_in_db, # Keep reference to update stock
"name": item['name'],
"price": item_price, # Use validated/corrected price
"quantity": quantity,
"color": item.get('color', 'N/A'),
"photo": product_in_db.get('photos', [None])[0], # Get photo filename from DB
"barcode": product_in_db.get('barcode', '') # Include barcode in sale history
})
except (ValueError, TypeError) as e:
logging.error(f"Invalid data in sale item: {item}. Error: {e}")
errors.append(f"Неверные данные для товара '{item.get('name', 'N/A')}'.")
stock_check_ok = False
if not stock_check_ok:
# Return all accumulated errors
return jsonify({"error": "Ошибки в списке продажи: " + ", ".join(errors)}), 400
# Deduct stock and build sale record
total_price = 0
sale_items_record = []
for item_proc in items_to_process:
original_stock = item_proc['db_product'].get('stock', 0)
item_proc['db_product']['stock'] = max(0, original_stock - item_proc['quantity'])
item_total = item_proc['price'] * item_proc['quantity']
total_price += item_total
sale_items_record.append({
"name": item_proc['name'],
"price": item_proc['price'],
"quantity": item_proc['quantity'],
"color": item_proc['color'],
"photo": item_proc['photo'], # This is the filename
"photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item_proc['photo']}" if item_proc['photo'] else "https://via.placeholder.com/60x60.png?text=N/A",
"barcode": item_proc['barcode']
})
# Log stock movement for sale
movement_id = str(uuid.uuid4())
movement_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
stock_movements.append({
"id": movement_id,
"timestamp": movement_timestamp,
"type": "sale", # Type for sales deduction
"product_name": item_proc['name'],
"quantity_change": -item_proc['quantity'], # Negative for deduction
"new_stock_level": item_proc['db_product']['stock'],
"reason": f"Продажа (Терминал)",
"details": f"Цвет/вариант: {item_proc['color']}"
})
sale_id = f"SALE-{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:4]}"
sale_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
new_sale = {
"id": sale_id,
"created_at": sale_timestamp,
"items": sale_items_record,
"total_price": round(total_price, 2),
"user_info": None, # No user info for anonymous sales
"status": "completed", # Mark sales terminal orders as completed
"type": "admin_sale" # Type for admin terminal sales
}
try:
if 'orders' not in data or not isinstance(data.get('orders'), dict):
data['orders'] = {}
data['orders'][sale_id] = new_sale
data['stock_movements'] = stock_movements # Update movements
data['products'] = products # Products list with updated stock levels
save_data(data)
logging.info(f"Sale {sale_id} registered successfully via terminal. Stock deducted.")
return jsonify({"order_id": sale_id, "message": "Продажа успешно зарегистрирована."}), 201
except Exception as e:
logging.error(f"Failed to save sale {sale_id}: {e}", exc_info=True)
return jsonify({"error": "Ошибка сервера при сохранении продажи."}), 500
@app.route('/force_upload', methods=['POST'])
def force_upload():
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():
logging.info("Forcing download from Hugging Face...")
try:
if download_db_from_hf():
flash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success')
load_data()
else:
flash("Не удалось скачать данные с Hugging Face после нескольких попыток. Проверьте логи.", 'error')
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__':
logging.info("Application starting up. Performing initial data load/download...")
download_db_from_hf()
load_data()
logging.info("Initial data load complete.")
if HF_TOKEN_WRITE:
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
backup_thread.start()
logging.info("Periodic backup thread started.")
else:
logging.warning("Periodic backup will NOT run (HF_TOKEN for writing not set).")
port = int(os.environ.get('PORT', 7860))
logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}")
app.run(debug=False, host='0.0.0.0', port=port)