diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,4 +1,4 @@ -from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash, abort, Response +from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash, abort, Response, session import json import os import logging @@ -17,14 +17,19 @@ from urllib.parse import quote app = Flask(__name__) app.secret_key = os.urandom(24) +# --- Configuration --- +ADMIN_PASS = os.getenv("ADMIN_PASS", "admin") DATA_DIR = 'pos_data' os.makedirs(DATA_DIR, exist_ok=True) +# --- File Definitions --- INVENTORY_FILE = os.path.join(DATA_DIR, 'inventory.json') TRANSACTIONS_FILE = os.path.join(DATA_DIR, 'transactions.json') USERS_FILE = os.path.join(DATA_DIR, 'users.json') KASSAS_FILE = os.path.join(DATA_DIR, 'kassas.json') EXPENSES_FILE = os.path.join(DATA_DIR, 'expenses.json') +STOCK_MOVEMENTS_FILE = os.path.join(DATA_DIR, 'stock_movements.json') + DATA_FILES = { 'inventory': (INVENTORY_FILE, threading.Lock()), @@ -32,16 +37,17 @@ DATA_FILES = { 'users': (USERS_FILE, threading.Lock()), 'kassas': (KASSAS_FILE, threading.Lock()), 'expenses': (EXPENSES_FILE, threading.Lock()), + 'stock_movements': (STOCK_MOVEMENTS_FILE, threading.Lock()), } HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", "YOUR_WRITE_TOKEN_HERE") HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", "YOUR_READ_TOKEN_HERE") REPO_ID = "Kgshop/postest" - BISHKEK_TZ = pytz.timezone('Asia/Bishkek') logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +# --- Utility Functions --- def get_current_time(): return datetime.now(BISHKEK_TZ) @@ -59,7 +65,7 @@ def to_decimal(value_str, default='0.00'): except InvalidOperation: logging.warning(f"Could not convert '{value_str}' to Decimal. Returned {default}.") return Decimal(default) - + def load_json_data(file_key): filepath, lock = DATA_FILES[file_key] filename = os.path.basename(filepath) @@ -79,7 +85,7 @@ def load_json_data(file_key): with open(filepath, 'r', encoding='utf-8') as f: return json.load(f) except (FileNotFoundError, json.JSONDecodeError): - return [] if file_key != 'users' else {} + return [] if file_key in ['inventory', 'transactions', 'kassas', 'expenses', 'stock_movements'] else {} def save_json_data(file_key, data): filepath, lock = DATA_FILES[file_key] @@ -128,7 +134,7 @@ def periodic_backup(): upload_db_to_hf(key) except Exception as e: logging.error(f"Error during scheduled backup: {e}", exc_info=True) - + def find_item_by_field(data, field, value): for item in data: if isinstance(item, dict) and item.get(field) == value: @@ -146,6 +152,11 @@ def format_currency_py(value): except (InvalidOperation, TypeError, ValueError): return "0,00" +def get_total_stock(product): + if 'variants' in product and isinstance(product['variants'], list): + return sum(v.get('stock', 0) for v in product['variants']) + return product.get('stock', 0) + def generate_receipt_html(transaction): items_html = "" for item in transaction['items']: @@ -201,17 +212,51 @@ def generate_receipt_html(transaction): """ + +# --- Authentication --- +def admin_login_required(f): + @functools.wraps(f) + def decorated_function(*args, **kwargs): + if not session.get('admin_logged_in'): + return redirect(url_for('admin_login', next=request.url)) + return f(*args, **kwargs) + return decorated_function + +@app.route('/admin_login', methods=['GET', 'POST']) +def admin_login(): + if request.method == 'POST': + password = request.form.get('password') + if password == ADMIN_PASS: + session['admin_logged_in'] = True + next_url = request.args.get('next') + flash('Успешный вход.', 'success') + return redirect(next_url or url_for('admin_panel')) + else: + flash('Неверный пароль.', 'danger') + return render_template_string(ADMIN_LOGIN_TEMPLATE) +@app.route('/admin_logout') +def admin_logout(): + session.pop('admin_logged_in', None) + flash('Вы вышли из системы.', 'info') + return redirect(url_for('sales_screen')) + +# --- Context Processors --- @app.context_processor def inject_utils(): - return {'format_currency_py': format_currency_py, 'get_current_time': get_current_time} + return { + 'format_currency_py': format_currency_py, + 'get_current_time': get_current_time, + 'get_total_stock': get_total_stock + } +# --- Main Routes --- @app.route('/') def sales_screen(): inventory = load_json_data('inventory') users = load_json_data('users') kassas = load_json_data('kassas') - active_inventory = [p for p in inventory if isinstance(p, dict) and p.get('stock', 0) > 0] + active_inventory = [p for p in inventory if isinstance(p, dict) and get_total_stock(p) > 0] active_inventory.sort(key=lambda x: x.get('name', '').lower()) html = BASE_TEMPLATE.replace('__TITLE__', "Касса").replace('__CONTENT__', SALES_SCREEN_CONTENT).replace('__SCRIPTS__', SALES_SCREEN_SCRIPTS) return render_template_string(html, inventory=active_inventory, users=users, kassas=kassas) @@ -224,7 +269,6 @@ def inventory_management(): barcode = request.form.get('barcode', '').strip() price = to_decimal(request.form.get('price', '0')) cost_price = to_decimal(request.form.get('cost_price', '0')) - stock = int(to_decimal(request.form.get('stock', '0'))) if not name or not barcode or price <= 0: flash("Название, штрих-код и цена - обязательные поля.", "danger") @@ -234,6 +278,17 @@ def inventory_management(): if find_item_by_field(inventory, 'barcode', barcode): flash(f"Товар со штрих-кодом {barcode} уже существует.", "warning") return redirect(url_for('inventory_management')) + + variants = [] + variant_names = request.form.getlist('variant_name[]') + variant_stocks = request.form.getlist('variant_stock[]') + for v_name, v_stock in zip(variant_names, variant_stocks): + if v_name.strip(): + variants.append({ + 'id': uuid.uuid4().hex, + 'name': v_name.strip(), + 'stock': int(to_decimal(v_stock or '0')), + }) new_product = { 'id': uuid.uuid4().hex, @@ -241,7 +296,7 @@ def inventory_management(): 'barcode': barcode, 'price': str(price), 'cost_price': str(cost_price), - 'stock': stock, + 'variants': variants, 'timestamp_added': get_current_time().isoformat(), 'timestamp_updated': get_current_time().isoformat() } @@ -269,7 +324,6 @@ def edit_product(product_id): barcode = request.form.get('barcode', '').strip() price = to_decimal(request.form.get('price')) cost_price = to_decimal(request.form.get('cost_price')) - stock = int(to_decimal(request.form.get('stock'))) if not name or not barcode or price <= 0: flash("Название, штрих-код и цена обязательны.", "danger") @@ -280,12 +334,24 @@ def edit_product(product_id): flash(f"Штрих-код {barcode} уже используется другим товаром.", "warning") return redirect(url_for('inventory_management')) + variants = [] + variant_ids = request.form.getlist('variant_id[]') + variant_names = request.form.getlist('variant_name[]') + variant_stocks = request.form.getlist('variant_stock[]') + + for idx, v_name in enumerate(variant_names): + v_name = v_name.strip() + if v_name: + v_id = variant_ids[idx] if idx < len(variant_ids) and variant_ids[idx] else uuid.uuid4().hex + v_stock = int(to_decimal(variant_stocks[idx] or '0')) + variants.append({'id': v_id, 'name': v_name, 'stock': v_stock}) + inventory[i].update({ 'name': name, 'barcode': barcode, 'price': str(price), 'cost_price': str(cost_price), - 'stock': stock, + 'variants': variants, 'timestamp_updated': get_current_time().isoformat() }) product_found = True @@ -302,6 +368,71 @@ def edit_product(product_id): flash("Товар не найден.", "danger") return redirect(url_for('inventory_management')) +@app.route('/inventory/receive_stock', methods=['POST']) +def receive_stock(): + try: + product_id = request.form.get('product_id') + quantities = {k.replace('quantity_', ''): int(v) for k, v in request.form.items() if k.startswith('quantity_') and v} + cost_price = to_decimal(request.form.get('cost_price', '0')) + + if not product_id or not quantities or cost_price <= 0: + flash("Выберите товар, укажите количество и себестоимость.", "danger") + return redirect(url_for('inventory_management')) + + inventory = load_json_data('inventory') + stock_movements = load_json_data('stock_movements') + now_iso = get_current_time().isoformat() + + product_found = False + for i, p in enumerate(inventory): + if p.get('id') == product_id: + product_found = True + total_added_stock = 0 + total_added_cost = Decimal('0.00') + + for variant_id, qty in quantities.items(): + if qty > 0: + for v_idx, v in enumerate(p.get('variants', [])): + if v.get('id') == variant_id: + old_stock = v.get('stock', 0) + inventory[i]['variants'][v_idx]['stock'] = old_stock + qty + total_added_stock += qty + total_added_cost += Decimal(qty) * cost_price + stock_movements.append({ + 'id': uuid.uuid4().hex, 'type': 'receipt', 'timestamp': now_iso, + 'product_id': product_id, 'variant_id': variant_id, + 'product_name': p['name'], 'variant_name': v['name'], + 'quantity': qty, 'unit_cost': str(cost_price) + }) + break + + # Update average cost price + if total_added_stock > 0: + current_total_stock = get_total_stock(p) - total_added_stock + current_cost_price = to_decimal(p.get('cost_price', '0')) + + if current_total_stock + total_added_stock > 0: + new_avg_cost = ((current_cost_price * Decimal(current_total_stock)) + total_added_cost) / Decimal(current_total_stock + total_added_stock) + inventory[i]['cost_price'] = str(new_avg_cost.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)) + + inventory[i]['timestamp_updated'] = now_iso + break + + if product_found: + save_json_data('inventory', inventory) + save_json_data('stock_movements', stock_movements) + upload_db_to_hf('inventory') + upload_db_to_hf('stock_movements') + flash("Остатки успешно обновлены.", "success") + else: + flash("Товар не найден.", "danger") + + except Exception as e: + flash(f"Ошибка при оприходовании: {e}", "danger") + + return redirect(url_for('inventory_management')) + + @app.route('/inventory/delete/', methods=['POST']) def delete_product(product_id): inventory = load_json_data('inventory') @@ -320,7 +451,7 @@ def get_product_by_barcode(barcode): inventory = load_json_data('inventory') product = find_item_by_field(inventory, 'barcode', barcode) if product: - if product.get('stock', 0) > 0: + if get_total_stock(product) > 0: return jsonify({'success': True, 'product': product}) else: return jsonify({'success': False, 'message': 'Товар закончился на складе'}), 404 @@ -330,7 +461,7 @@ def get_product_by_barcode(barcode): def complete_sale(): try: data = request.get_json() - cart = data.get('cart', []) + cart = data.get('cart', {}) user_id = data.get('userId') kassa_id = data.get('kassaId') payment_method = data.get('paymentMethod', 'cash') @@ -341,6 +472,7 @@ def complete_sale(): inventory = load_json_data('inventory') users = load_json_data('users') kassas = load_json_data('kassas') + stock_movements = load_json_data('stock_movements') user = find_item_by_field(users, 'id', user_id) kassa = find_item_by_field(kassas, 'id', kassa_id) @@ -350,18 +482,21 @@ def complete_sale(): sale_items = [] total_amount = Decimal('0.00') - inventory_updates = {} + inventory_updates = [] + movement_updates = [] - for item_id, cart_item in cart.items(): - product = find_item_by_field(inventory, 'id', item_id) - if not product: - return jsonify({'success': False, 'message': f"Товар с ID {item_id} не найден."}), 404 + for variant_id, cart_item in cart.items(): + product_id = cart_item['productId'] + product = find_item_by_field(inventory, 'id', product_id) + if not product: return jsonify({'success': False, 'message': f"Товар с ID {product_id} не найден."}), 404 - quantity_sold = cart_item['quantity'] - current_stock = product.get('stock', 0) + variant = next((v for v in product.get('variants', []) if v.get('id') == variant_id), None) + if not variant: return jsonify({'success': False, 'message': f"Вариант товара не найден."}), 404 + quantity_sold = cart_item['quantity'] + current_stock = variant.get('stock', 0) if quantity_sold > current_stock: - return jsonify({'success': False, 'message': f"Недостаточно товара '{product['name']}'. В наличии: {current_stock}"}), 400 + return jsonify({'success': False, 'message': f"Недостаточно товара '{product['name']} - {variant['name']}'. В наличии: {current_stock}"}), 400 price_at_sale = to_decimal(product.get('price', '0')) cost_price_at_sale = to_decimal(product.get('cost_price', '0')) @@ -369,42 +504,43 @@ def complete_sale(): total_amount += item_total sale_items.append({ - 'product_id': item_id, - 'name': product['name'], - 'barcode': product.get('barcode'), - 'quantity': quantity_sold, - 'price_at_sale': str(price_at_sale), - 'cost_price_at_sale': str(cost_price_at_sale), - 'total': str(item_total) + 'product_id': product_id, 'variant_id': variant_id, + 'name': f"{product['name']} ({variant['name']})", 'barcode': product.get('barcode'), + 'quantity': quantity_sold, 'price_at_sale': str(price_at_sale), + 'cost_price_at_sale': str(cost_price_at_sale), 'total': str(item_total) }) - inventory_updates[item_id] = current_stock - quantity_sold - + inventory_updates.append({'product_id': product_id, 'variant_id': variant_id, 'new_stock': current_stock - quantity_sold}) + now_iso = get_current_time().isoformat() new_transaction = { - 'id': uuid.uuid4().hex, - 'timestamp': now_iso, - 'type': 'sale', - 'status': 'completed', - 'original_transaction_id': None, - 'user_id': user_id, - 'user_name': user.get('name', 'N/A'), - 'kassa_id': kassa_id, - 'kassa_name': kassa.get('name', 'N/A'), - 'items': sale_items, - 'total_amount': str(total_amount), - 'payment_method': payment_method + 'id': uuid.uuid4().hex, 'timestamp': now_iso, 'type': 'sale', 'status': 'completed', + 'original_transaction_id': None, 'user_id': user_id, 'user_name': user.get('name', 'N/A'), + 'kassa_id': kassa_id, 'kassa_name': kassa.get('name', 'N/A'), 'items': sale_items, + 'total_amount': str(total_amount), 'payment_method': payment_method } new_transaction['receipt_html'] = generate_receipt_html(new_transaction) transactions = load_json_data('transactions') transactions.append(new_transaction) + + for item in sale_items: + stock_movements.append({ + 'id': uuid.uuid4().hex, 'type': 'sale', 'timestamp': now_iso, + 'product_id': item['product_id'], 'variant_id': item['variant_id'], + 'product_name': product['name'], 'variant_name': variant['name'], + 'quantity': -item['quantity'], 'unit_cost': item['cost_price_at_sale'], + 'unit_price': item['price_at_sale'], 'transaction_id': new_transaction['id'] + }) - for prod_id, new_stock in inventory_updates.items(): - for i, p in enumerate(inventory): - if p.get('id') == prod_id: - inventory[i]['stock'] = new_stock - inventory[i]['timestamp_updated'] = now_iso + for update in inventory_updates: + for p in inventory: + if p.get('id') == update['product_id']: + for v in p.get('variants', []): + if v.get('id') == update['variant_id']: + v['stock'] = update['new_stock'] + p['timestamp_updated'] = now_iso + break break if payment_method == 'cash': @@ -412,12 +548,8 @@ def complete_sale(): if k.get('id') == kassa_id: current_balance = to_decimal(k.get('balance', '0')) kassas[i]['balance'] = str(current_balance + total_amount) - if 'history' not in kassas[i] or not isinstance(kassas[i]['history'], list): - kassas[i]['history'] = [] - kassas[i]['history'].append({ - 'type': 'sale', - 'amount': str(total_amount), - 'timestamp': now_iso, + kassas[i].setdefault('history', []).append({ + 'type': 'sale', 'amount': str(total_amount), 'timestamp': now_iso, 'transaction_id': new_transaction['id'] }) break @@ -425,19 +557,18 @@ def complete_sale(): save_json_data('transactions', transactions) save_json_data('inventory', inventory) save_json_data('kassas', kassas) + save_json_data('stock_movements', stock_movements) upload_db_to_hf('transactions') upload_db_to_hf('inventory') upload_db_to_hf('kassas') + upload_db_to_hf('stock_movements') receipt_url = url_for('view_receipt', transaction_id=new_transaction['id'], _external=True) return jsonify({ - 'success': True, - 'message': 'Продажа успешно зарегистрирована.', - 'transactionId': new_transaction['id'], - 'receiptUrl': receipt_url + 'success': True, 'message': 'Продажа успешно зарегистрирована.', + 'transactionId': new_transaction['id'], 'receiptUrl': receipt_url }) - except Exception as e: logging.error(f"Error completing sale: {e}", exc_info=True) return jsonify({'success': False, 'message': f'Внутренняя ошибка сервера: {e}'}), 500 @@ -458,6 +589,7 @@ def transaction_history(): return render_template_string(html, transactions=transactions) @app.route('/reports') +@admin_login_required def reports(): today = get_current_time().date() start_date_str = request.args.get('start_date', (today.replace(day=1)).strftime('%Y-%m-%d')) @@ -471,14 +603,8 @@ def reports(): expenses = load_json_data('expenses') users = load_json_data('users') - filtered_transactions = [ - t for t in transactions - if start_date <= datetime.fromisoformat(t['timestamp']) < end_date - ] - filtered_expenses = [ - e for e in expenses - if start_date <= datetime.fromisoformat(e['timestamp']) < end_date - ] + filtered_transactions = [t for t in transactions if start_date <= datetime.fromisoformat(t['timestamp']) < end_date] + filtered_expenses = [e for e in expenses if start_date <= datetime.fromisoformat(e['timestamp']) < end_date] total_revenue = sum(to_decimal(t['total_amount']) for t in filtered_transactions) total_cogs = sum( @@ -499,7 +625,6 @@ def reports(): sales_by_cashier[cashier_name]['count'] -= 1 sales_by_cashier[cashier_name]['total'] += to_decimal(t['total_amount']) - cashier_payouts = defaultdict(Decimal) for t in filtered_transactions: user = find_item_by_field(users, 'id', t.get('user_id')) @@ -522,22 +647,49 @@ def reports(): net_profit = gross_profit - total_expenses - total_salary_expenses stats = { - 'total_revenue': total_revenue, - 'total_cogs': total_cogs, - 'gross_profit': gross_profit, - 'total_expenses': total_expenses, - 'total_salary_expenses': total_salary_expenses, + 'total_revenue': total_revenue, 'total_cogs': total_cogs, 'gross_profit': gross_profit, + 'total_expenses': total_expenses, 'total_salary_expenses': total_salary_expenses, 'net_profit': net_profit, 'sales_by_cashier': sorted(sales_by_cashier.items(), key=lambda item: item[1]['total'], reverse=True), 'cashier_payouts': sorted(cashier_payouts.items(), key=lambda item: item[1], reverse=True) } - filtered_expenses.sort(key=lambda x: x['timestamp'], reverse=True) - html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS) return render_template_string(html, stats=stats, start_date=start_date_str, end_date=end_date_str, expenses=filtered_expenses) +@app.route('/reports/payback') +@admin_login_required +def payback_report(): + stock_movements = load_json_data('stock_movements') + inventory = load_json_data('inventory') + + payback_data = defaultdict(lambda: {'cost': Decimal('0'), 'revenue': Decimal('0')}) + + for move in stock_movements: + if move.get('type') == 'receipt' and 'unit_cost' in move: + payback_data[move['product_id']]['cost'] += to_decimal(str(move['quantity'])) * to_decimal(move['unit_cost']) + elif move.get('type') == 'sale' and 'unit_price' in move: + payback_data[move['product_id']]['revenue'] += to_decimal(str(abs(move['quantity']))) * to_decimal(move['unit_price']) + + results = [] + for product_id, data in payback_data.items(): + product = find_item_by_field(inventory, 'id', product_id) + if product: + profit = data['revenue'] - data['cost'] + results.append({ + 'name': product['name'], + 'total_cost': data['cost'], + 'total_revenue': data['revenue'], + 'profit': profit + }) + + results.sort(key=lambda x: x['profit'], reverse=True) + html = BASE_TEMPLATE.replace('__TITLE__', "Окупаемость по товарам").replace('__CONTENT__', PAYBACK_REPORT_CONTENT).replace('__SCRIPTS__', "") + return render_template_string(html, results=results) + + @app.route('/admin', methods=['GET']) +@admin_login_required def admin_panel(): users = load_json_data('users') kassas = load_json_data('kassas') @@ -547,6 +699,7 @@ def admin_panel(): return render_template_string(html, users=users, kassas=kassas, expenses=expenses[:10]) @app.route('/admin/user', methods=['POST']) +@admin_login_required def manage_user(): action = request.form.get('action') users = load_json_data('users') @@ -557,14 +710,10 @@ def manage_user(): payment_type = request.form.get('payment_type') payment_value = to_decimal(request.form.get('payment_value', '0')) if name and pin and pin.isdigit() and payment_type: - new_user = { - 'id': uuid.uuid4().hex, 'name': name, 'pin': pin, - 'payment_type': payment_type, 'payment_value': str(payment_value) - } + new_user = {'id': uuid.uuid4().hex, 'name': name, 'pin': pin, 'payment_type': payment_type, 'payment_value': str(payment_value)} users.append(new_user) flash(f"Кассир '{name}' добавлен.", "success") - else: - flash("Все поля обязательны.", "danger") + else: flash("Все поля обязательны.", "danger") elif action == 'edit': user_id = request.form.get('id') @@ -575,23 +724,21 @@ def manage_user(): user['payment_type'] = request.form.get('payment_type') user['payment_value'] = str(to_decimal(request.form.get('payment_value', '0'))) flash(f"Данные кассира '{user['name']}' обновлены.", "success") - else: - flash("Кассир не найден.", "warning") + else: flash("Кассир не найден.", "warning") elif action == 'delete': user_id = request.form.get('id') initial_len = len(users) users = [u for u in users if u.get('id') != user_id] - if len(users) < initial_len: - flash("Кассир удален.", "success") - else: - flash("Кассир не найден.", "warning") + if len(users) < initial_len: flash("Кассир удален.", "success") + else: flash("Кассир не найден.", "warning") save_json_data('users', users) upload_db_to_hf('users') return redirect(url_for('admin_panel')) @app.route('/admin/kassa', methods=['POST']) +@admin_login_required def manage_kassa(): action = request.form.get('action') kassas = load_json_data('kassas') @@ -600,41 +747,28 @@ def manage_kassa(): name = request.form.get('name', '').strip() balance = to_decimal(request.form.get('balance', '0')) if name: - new_kassa = { - 'id': uuid.uuid4().hex, - 'name': name, - 'balance': str(balance), - 'history': [] - } + new_kassa = {'id': uuid.uuid4().hex, 'name': name, 'balance': str(balance), 'history': []} if balance > 0: - new_kassa['history'].append({ - 'type': 'deposit', - 'amount': str(balance), - 'timestamp': get_current_time().isoformat(), - 'description': 'Начальный баланс' - }) + new_kassa['history'].append({'type': 'deposit', 'amount': str(balance), 'timestamp': get_current_time().isoformat(), 'description': 'Начальный баланс'}) kassas.append(new_kassa) flash(f"Касса '{name}' добавлена.", "success") - else: - flash("Название кассы обязательно.", "danger") + else: flash("Название кассы обязательно.", "danger") elif action == 'delete': kassa_id = request.form.get('id') initial_len = len(kassas) kassas = [k for k in kassas if k.get('id') != kassa_id] - if len(kassas) < initial_len: - flash("Касса удалена.", "success") - else: - flash("Касса не найдена.", "warning") + if len(kassas) < initial_len: flash("Касса удалена.", "success") + else: flash("Касса не найдена.", "warning") save_json_data('kassas', kassas) upload_db_to_hf('kassas') return redirect(url_for('admin_panel')) @app.route('/admin/kassa_op', methods=['POST']) +@admin_login_required def kassa_operation(): - kassa_id = request.form.get('kassa_id') - op_type = request.form.get('op_type') + kassa_id, op_type = request.form.get('kassa_id'), request.form.get('op_type') amount = to_decimal(request.form.get('amount', '0')) description = request.form.get('description', '').strip() @@ -648,9 +782,7 @@ def kassa_operation(): if kassa.get('id') == kassa_id: current_balance = to_decimal(kassa.get('balance', '0')) new_balance = current_balance - - if op_type == 'deposit': - new_balance += amount + if op_type == 'deposit': new_balance += amount elif op_type == 'withdrawal': if amount > current_balance: flash("Сумма изъятия превышает баланс кассы.", "danger") @@ -658,11 +790,8 @@ def kassa_operation(): new_balance -= amount kassas[i]['balance'] = str(new_balance) - if 'history' not in kassas[i]: kassas[i]['history'] = [] - kassas[i]['history'].append({ - 'type': op_type, - 'amount': str(amount), - 'timestamp': get_current_time().isoformat(), + kassas[i].setdefault('history', []).append({ + 'type': op_type, 'amount': str(amount), 'timestamp': get_current_time().isoformat(), 'description': description or f"{'Внесение' if op_type == 'deposit' else 'Изъятие'} средств" }) kassa_found = True @@ -672,12 +801,11 @@ def kassa_operation(): save_json_data('kassas', kassas) upload_db_to_hf('kassas') flash("Операция по кассе успешно проведена.", "success") - else: - flash("Касса не найдена.", "danger") - + else: flash("Касса не найдена.", "danger") return redirect(url_for('admin_panel')) @app.route('/admin/expense', methods=['POST']) +@admin_login_required def manage_expense(): amount = to_decimal(request.form.get('amount', '0')) description = request.form.get('description', '').strip() @@ -686,12 +814,7 @@ def manage_expense(): flash("Укажите положительную сумму и описание расхода.", "danger") return redirect(url_for('admin_panel')) - new_expense = { - 'id': uuid.uuid4().hex, - 'timestamp': get_current_time().isoformat(), - 'amount': str(amount), - 'description': description - } + new_expense = {'id': uuid.uuid4().hex, 'timestamp': get_current_time().isoformat(), 'amount': str(amount), 'description': description} expenses = load_json_data('expenses') expenses.append(new_expense) save_json_data('expenses', expenses) @@ -704,10 +827,8 @@ def cashier_login(): if request.method == 'POST': pin = request.form.get('pin') user = find_user_by_pin(pin) - if user: - return redirect(url_for('cashier_dashboard', user_id=user['id'])) - else: - flash("Неверный ПИН-код.", "danger") + if user: return redirect(url_for('cashier_dashboard', user_id=user['id'])) + else: flash("Неверный ПИН-код.", "danger") html = BASE_TEMPLATE.replace('__TITLE__', "Вход для кассира").replace('__CONTENT__', CASHIER_LOGIN_CONTENT).replace('__SCRIPTS__', '') return render_template_string(html) @@ -715,8 +836,7 @@ def cashier_login(): def cashier_dashboard(user_id): users = load_json_data('users') user = find_item_by_field(users, 'id', user_id) - if not user: - abort(404, "Кассир не найден") + if not user: abort(404, "Кассир не найден") transactions = load_json_data('transactions') user_transactions = [t for t in transactions if t.get('user_id') == user_id] @@ -732,10 +852,8 @@ def return_transaction(transaction_id): flash("Не удалось определить кассира для оформления возврата.", "danger") return redirect(url_for('cashier_login')) - transactions = load_json_data('transactions') - inventory = load_json_data('inventory') - kassas = load_json_data('kassas') - + transactions = load_json_data('transactions'); inventory = load_json_data('inventory') + kassas = load_json_data('kassas'); stock_movements = load_json_data('stock_movements') original_transaction = find_item_by_field(transactions, 'id', transaction_id) if not original_transaction: @@ -746,97 +864,128 @@ def return_transaction(transaction_id): return redirect(url_for('cashier_dashboard', user_id=cashier_id)) total_amount = to_decimal(original_transaction['total_amount']) + now_iso = get_current_time().isoformat() + return_items, inventory_updates = [], [] - return_items = [] - inventory_updates = {} for item in original_transaction['items']: return_items.append({**item, 'quantity': -item['quantity'], 'total': str(-to_decimal(item['total']))}) product = find_item_by_field(inventory, 'id', item['product_id']) if product: - inventory_updates[item['product_id']] = product.get('stock', 0) + item['quantity'] - - now_iso = get_current_time().isoformat() + variant = next((v for v in product.get('variants', []) if v['id'] == item['variant_id']), None) + if variant: + inventory_updates.append({'product_id': item['product_id'], 'variant_id': item['variant_id'], 'new_stock': variant.get('stock', 0) + item['quantity']}) + return_transaction = { - 'id': uuid.uuid4().hex, - 'timestamp': now_iso, - 'type': 'return', - 'status': 'completed', - 'original_transaction_id': transaction_id, - 'user_id': original_transaction['user_id'], - 'user_name': original_transaction['user_name'], - 'kassa_id': original_transaction['kassa_id'], - 'kassa_name': original_transaction['kassa_name'], - 'items': return_items, - 'total_amount': str(-total_amount), - 'payment_method': original_transaction['payment_method'] + 'id': uuid.uuid4().hex, 'timestamp': now_iso, 'type': 'return', 'status': 'completed', + 'original_transaction_id': transaction_id, 'user_id': original_transaction['user_id'], + 'user_name': original_transaction['user_name'], 'kassa_id': original_transaction['kassa_id'], + 'kassa_name': original_transaction['kassa_name'], 'items': return_items, + 'total_amount': str(-total_amount), 'payment_method': original_transaction['payment_method'] } transactions.append(return_transaction) + for item in return_items: + stock_movements.append({ + 'id': uuid.uuid4().hex, 'type': 'return', 'timestamp': now_iso, + 'product_id': item['product_id'], 'variant_id': item['variant_id'], + 'product_name': item['name'].split(' (')[0], 'variant_name': item['name'].split(' (')[1].replace(')', ''), + 'quantity': abs(item['quantity']), 'unit_cost': item['cost_price_at_sale'], + 'unit_price': item['price_at_sale'], 'transaction_id': return_transaction['id'] + }) + for i, t in enumerate(transactions): - if t['id'] == transaction_id: - transactions[i]['status'] = 'returned' - break + if t['id'] == transaction_id: transactions[i]['status'] = 'returned'; break - for prod_id, new_stock in inventory_updates.items(): - for i, p in enumerate(inventory): - if p['id'] == prod_id: - inventory[i]['stock'] = new_stock - inventory[i]['timestamp_updated'] = now_iso + for update in inventory_updates: + for p in inventory: + if p.get('id') == update['product_id']: + for v in p.get('variants', []): + if v.get('id') == update['variant_id']: v['stock'] = update['new_stock']; p['timestamp_updated'] = now_iso; break break if original_transaction['payment_method'] == 'cash': for i, k in enumerate(kassas): if k['id'] == original_transaction['kassa_id']: - current_balance = to_decimal(k.get('balance', '0')) - kassas[i]['balance'] = str(current_balance - total_amount) - kassas[i].setdefault('history', []).append({ - 'type': 'return', 'amount': str(-total_amount), 'timestamp': now_iso, - 'transaction_id': return_transaction['id'] - }) + kassas[i]['balance'] = str(to_decimal(k.get('balance', '0')) - total_amount) + kassas[i].setdefault('history', []).append({'type': 'return', 'amount': str(-total_amount), 'timestamp': now_iso, 'transaction_id': return_transaction['id']}) break - save_json_data('transactions', transactions) - save_json_data('inventory', inventory) - save_json_data('kassas', kassas) - upload_db_to_hf('transactions') - upload_db_to_hf('inventory') - upload_db_to_hf('kassas') + save_json_data('transactions', transactions); save_json_data('inventory', inventory) + save_json_data('kassas', kassas); save_json_data('stock_movements', stock_movements) + upload_db_to_hf('transactions'); upload_db_to_hf('inventory') + upload_db_to_hf('kassas'); upload_db_to_hf('stock_movements') flash("Возврат успешно оформлен.", "success") return redirect(url_for('cashier_dashboard', user_id=cashier_id)) @app.route('/backup', methods=['POST']) +@admin_login_required def backup_hf(): try: - for key in DATA_FILES.keys(): - upload_db_to_hf(key) + for key in DATA_FILES.keys(): upload_db_to_hf(key) flash(f"Резервное копирование {len(DATA_FILES)} файлов инициировано.", "success") - except Exception as e: - flash(f"Ошибка при резервном копировании: {e}", "danger") + except Exception as e: flash(f"Ошибка при резервном копировании: {e}", "danger") return redirect(url_for('admin_panel')) @app.route('/download', methods=['GET']) +@admin_login_required def download_hf(): - errors = [] - success_count = 0 + errors, success_count = [], 0 for key in DATA_FILES.keys(): filepath, _ = DATA_FILES[key] filename = os.path.basename(filepath) try: - hf_hub_download( - repo_id=REPO_ID, filename=filename, repo_type="dataset", token=HF_TOKEN_READ, - local_dir=DATA_DIR, local_dir_use_symlinks=False, force_download=True, - ) + hf_hub_download(repo_id=REPO_ID, filename=filename, repo_type="dataset", token=HF_TOKEN_READ, local_dir=DATA_DIR, local_dir_use_symlinks=False, force_download=True) success_count += 1 - except Exception as e: - errors.append(f"Ошибка за��рузки {filename}: {e}") - if success_count > 0: - flash(f"Успешно загружено {success_count} файлов. Данные перезаписаны.", "success") - if errors: - flash("Произошли ошибки: " + "; ".join(errors), "danger") + except Exception as e: errors.append(f"Ошибка загрузки {filename}: {e}") + if success_count > 0: flash(f"Успешно загружено {success_count} файлов. Данные перезаписаны.", "success") + if errors: flash("Произошли ошибки: " + "; ".join(errors), "danger") return redirect(url_for('admin_panel')) +# --- HTML/JS Templates --- + +ADMIN_LOGIN_TEMPLATE = """ + + + + + + Вход в админ-панель + + + +
+
+
+
+
+

Вход в админ-панель

+ {% with messages = get_flashed_messages(with_categories=true) %} + {% if messages %} + {% for category, message in messages %} +
{{ message }}
+ {% endfor %} + {% endif %} + {% endwith %} +
+
+ + +
+
+ +
+
+
+
+
+
+
+ + +""" + BASE_TEMPLATE = """ @@ -861,6 +1010,7 @@ BASE_TEMPLATE = """ [data-bs-theme="dark"] body { background-color: #212529; color: #dee2e6; } [data-bs-theme="dark"] .card, [data-bs-theme="dark"] .list-group-item, [data-bs-theme="dark"] .table { background-color: #343a40; } [data-bs-theme="dark"] .table-hover>tbody>tr:hover>* { color: var(--bs-table-hover-color); background-color: rgba(255, 255, 255, 0.075); } + .product-card { cursor: pointer; } .product-card:hover { border-color: var(--bs-primary); } @@ -872,9 +1022,20 @@ BASE_TEMPLATE = """ - + + {% if session.get('admin_logged_in') %} + + {% endif %}
© {{ get_current_time().year }}
{{ get_current_time().strftime('%Y-%m-%d %H:%M') }} @@ -902,22 +1063,14 @@ BASE_TEMPLATE = """
- + + @@ -959,24 +1118,14 @@ SALES_SCREEN_CONTENT = """
-
-
Товары
- -
+
Товары
- +
{% for p in inventory %} -
-
-
{{ p.name }}
-

{{ format_currency_py(p.price) }} с

-
+
+
{{ p.name }}

{{ format_currency_py(p.price) }} с

{% endfor %}
@@ -992,10 +1141,7 @@ SALES_SCREEN_CONTENT = """
-
-

Итого:

-

0,00 с

-
+

Итого:

0,00 с

@@ -1009,29 +1155,24 @@ SALES_SCREEN_CONTENT = """ SALES_SCREEN_SCRIPTS = """ @@ -1207,443 +1342,404 @@ document.addEventListener('DOMContentLoaded', () => { INVENTORY_CONTENT = """ -
-
-
- - - - {% for p in inventory %} - - - - - {% endfor %} - -
НазваниеШтрих-кодЦенаСебест.ОстатокДействия
{{ p.name }}{{ p.barcode }}{{ format_currency_py(p.price) }} с{{ format_currency_py(p.cost_price) }} с{{ p.stock }} - -
- -
-
+
+ + + + {% for p in inventory %} + + + + + + + {% endfor %} + +
НазваниеШтрих-кодЦенаСебест.ОстатокДействия
{{ p.name }}
+ + {% for v in p.variants %}{{v.name}}: {{v.stock}} шт. {% endfor %} + +
{{ p.barcode }}{{ format_currency_py(p.price) }} с{{ format_currency_py(p.cost_price) }} с{{ get_total_stock(p) }} + + +
+ +
+
+
+ +
-