|
|
| from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash, abort, Response, session, g |
| import json |
| import os |
| import logging |
| import threading |
| import time |
| from datetime import datetime, timedelta |
| import pytz |
| from huggingface_hub import HfApi, hf_hub_download |
| from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError |
| import uuid |
| from decimal import Decimal, InvalidOperation, ROUND_HALF_UP |
| import functools |
| from functools import wraps |
| from collections import defaultdict |
| from urllib.parse import quote |
|
|
| app = Flask(__name__) |
| app.secret_key = os.urandom(24) |
| app.permanent_session_lifetime = timedelta(days=7) |
|
|
| ADMIN_PASS = os.getenv("ADMIN_PASS", "admin123") |
|
|
| DATA_DIR = 'pos_data' |
| os.makedirs(DATA_DIR, exist_ok=True) |
| os.makedirs(os.path.join(app.static_folder, 'product_images'), exist_ok=True) |
|
|
| 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') |
| PERSONAL_EXPENSES_FILE = os.path.join(DATA_DIR, 'personal_expenses.json') |
| SHIFTS_FILE = os.path.join(DATA_DIR, 'shifts.json') |
| HELD_BILLS_FILE = os.path.join(DATA_DIR, 'held_bills.json') |
| CUSTOMERS_FILE = os.path.join(DATA_DIR, 'customers.json') |
| STOCK_HISTORY_FILE = os.path.join(DATA_DIR, 'stock_history.json') |
| LINKS_FILE = os.path.join(DATA_DIR, 'links.json') |
|
|
| DATA_FILES = { |
| 'inventory': (INVENTORY_FILE, threading.Lock()), |
| 'transactions': (TRANSACTIONS_FILE, threading.Lock()), |
| 'users': (USERS_FILE, threading.Lock()), |
| 'kassas': (KASSAS_FILE, threading.Lock()), |
| 'expenses': (EXPENSES_FILE, threading.Lock()), |
| 'personal_expenses': (PERSONAL_EXPENSES_FILE, threading.Lock()), |
| 'shifts': (SHIFTS_FILE, threading.Lock()), |
| 'held_bills': (HELD_BILLS_FILE, threading.Lock()), |
| 'customers': (CUSTOMERS_FILE, threading.Lock()), |
| 'stock_history': (STOCK_HISTORY_FILE, threading.Lock()), |
| 'links': (LINKS_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/techbase" |
|
|
| ALMATY_TZ = pytz.timezone('Asia/Almaty') |
|
|
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') |
|
|
| def get_current_time(): |
| return datetime.now(ALMATY_TZ) |
|
|
| class DecimalEncoder(json.JSONEncoder): |
| def default(self, obj): |
| if isinstance(obj, Decimal): |
| return str(obj) |
| return json.JSONEncoder.default(self, obj) |
|
|
| def to_decimal(value_str, default='0'): |
| if value_str is None or str(value_str).strip() == '': |
| return Decimal(default) |
| try: |
| return Decimal(str(value_str).replace(',', '.').replace(' ', '')) |
| 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) |
| with lock: |
| 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 |
| ) |
| except HfHubHTTPError as e: |
| if e.response.status_code != 404: |
| logging.error(f"HTTP error downloading {filename}: {e}") |
| except Exception as e: |
| logging.error(f"Unknown error downloading {filename}: {e}") |
|
|
| try: |
| with open(filepath, 'r', encoding='utf-8') as f: |
| return json.load(f) |
| except (FileNotFoundError, json.JSONDecodeError): |
| return [] |
|
|
| def save_json_data(file_key, data): |
| filepath, lock = DATA_FILES[file_key] |
| with lock: |
| try: |
| temp_file = filepath + ".tmp" |
| with open(temp_file, 'w', encoding='utf-8') as f: |
| json.dump(data, f, ensure_ascii=False, indent=4, cls=DecimalEncoder) |
| os.replace(temp_file, filepath) |
| except Exception as e: |
| logging.error(f"Critical error saving {filepath}: {e}", exc_info=True) |
|
|
| @functools.lru_cache(maxsize=1) |
| def get_hf_api(): |
| if not HF_TOKEN_WRITE or HF_TOKEN_WRITE == "YOUR_WRITE_TOKEN_HERE": |
| return None |
| try: |
| return HfApi() |
| except Exception as e: |
| logging.error(f"Error initializing HfApi: {e}") |
| return None |
|
|
| def upload_db_to_hf(file_key): |
| api = get_hf_api() |
| if not api: |
| return |
| filepath, _ = DATA_FILES[file_key] |
| if not os.path.exists(filepath): |
| return |
| try: |
| filename = os.path.basename(filepath) |
| commit_time = get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z') |
| api.upload_file( |
| path_or_fileobj=filepath, path_in_repo=filename, repo_id=REPO_ID, repo_type="dataset", |
| token=HF_TOKEN_WRITE, commit_message=f"Automated backup {filename} {commit_time}", |
| run_as_future=True |
| ) |
| except Exception as e: |
| logging.error(f"Error initiating upload of {filepath}: {e}") |
|
|
| def periodic_backup(): |
| while True: |
| time.sleep(1800) |
| try: |
| for key in DATA_FILES.keys(): |
| 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 str(item.get(field)) == str(value): |
| return item |
| return None |
|
|
| def find_user_by_pin(pin): |
| users = load_json_data('users') |
| return find_item_by_field(users, 'pin', pin) |
|
|
| def format_currency_py(value): |
| try: |
| number = to_decimal(value) |
| return f"{number:,.0f}".replace(",", " ") |
| except (InvalidOperation, TypeError, ValueError): |
| return "0" |
|
|
| def generate_receipt_html(transaction): |
| has_discounts = any(to_decimal(item.get('discount_per_item', '0')) > 0 for item in transaction.get('items', [])) |
| delivery_cost = to_decimal(transaction.get('delivery_cost', '0')) |
| note = transaction.get('note', '') |
|
|
| if has_discounts: |
| table_headers = """ |
| <th style="text-align: center; width: 5%;">№</th> |
| <th style="text-align: left;">Наименование</th> |
| <th style="text-align: right;">Кол-во</th> |
| <th style="text-align: right;">Цена</th> |
| <th style="text-align: right;">Скидка</th> |
| <th style="text-align: right;">Сумма</th> |
| """ |
| total_colspan = 5 |
| else: |
| table_headers = """ |
| <th style="text-align: center; width: 5%;">№</th> |
| <th style="text-align: left;">Наименование</th> |
| <th style="text-align: right;">Кол-во</th> |
| <th style="text-align: right;">Цена</th> |
| <th style="text-align: right;">Сумма</th> |
| """ |
| total_colspan = 4 |
|
|
| items_html = "" |
| for i, item in enumerate(transaction['items']): |
| discount_cell = f"""<td style="text-align: right;">{format_currency_py(item.get('discount_per_item', '0'))}</td>""" if has_discounts else "" |
| items_html += f""" |
| <tr> |
| <td style="text-align: center;">{i + 1}</td> |
| <td>{item['name']}</td> |
| <td style="text-align: right;">{item['quantity']}</td> |
| <td style="text-align: right;">{format_currency_py(item['price_at_sale'])}</td> |
| {discount_cell} |
| <td style="text-align: right;">{format_currency_py(item['total'])}</td> |
| </tr> |
| """ |
| |
| total_amount_from_db = to_decimal(transaction['total_amount']) |
| |
| totals_html = "" |
| if delivery_cost > 0: |
| subtotal = total_amount_from_db - delivery_cost |
| totals_html += f""" |
| <tr> |
| <td colspan="{total_colspan}" style="text-align: right;">Подытог:</td> |
| <td style="text-align: right;">{format_currency_py(subtotal)} ₸</td> |
| </tr> |
| <tr> |
| <td colspan="{total_colspan}" style="text-align: right;">Доставка:</td> |
| <td style="text-align: right;">{format_currency_py(delivery_cost)} ₸</td> |
| </tr> |
| """ |
|
|
| totals_html += f""" |
| <tr class="total"> |
| <td colspan="{total_colspan}" style="text-align: right;">Итого к оплате:</td> |
| <td style="text-align: right;">{format_currency_py(total_amount_from_db)} ₸</td> |
| </tr> |
| """ |
|
|
| note_html = "" |
| if note: |
| safe_note = note.replace('<', '<').replace('>', '>') |
| note_html = f""" |
| <div style="margin-top: 20px; padding: 10px; border: 2px solid #333; background-color: #fdfdea; border-radius: 5px;"> |
| <h4 style="margin: 0 0 5px 0; font-size: 16px;">Примечание к заказу:</h4> |
| <p style="margin: 0; white-space: pre-wrap; font-size: 14px;">{safe_note}</p> |
| </div> |
| """ |
| |
| links = load_json_data('links') |
| links_html = "" |
| if links: |
| links_html = '<div class="print-hide" style="margin-top: 20px; text-align: center; border-top: 1px solid #ddd; padding-top: 15px;">' |
| for link in links: |
| links_html += f'<a href="{link["url"]}" target="_blank" style="display: inline-block; margin: 5px; padding: 10px 15px; background: #0d6efd; color: white; text-decoration: none; border-radius: 5px; font-weight: bold; font-size: 14px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">{link["name"]}</a>' |
| links_html += '</div>' |
| |
| return f""" |
| <!DOCTYPE html> |
| <html lang="ru"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>Накладная {transaction['id'][:8]}</title> |
| <style> |
| body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; margin: 0; padding: 10px; background-color: #f4f4f4; color: #333; }} |
| .invoice-box {{ max-width: 800px; margin: auto; padding: 20px; border: 1px solid #eee; background: white; box-shadow: 0 0 10px rgba(0,0,0,0.15); }} |
| .header {{ text-align: center; margin-bottom: 20px; }} |
| .header h1 {{ margin: 0; font-size: 22px; font-weight: 600; }} |
| .header p {{ margin: 2px 0; font-size: 14px; }} |
| .details-grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; font-size: 14px; }} |
| table {{ width: 100%; line-height: inherit; text-align: left; border-collapse: collapse; }} |
| table th {{ background: #f2f2f2; font-weight: bold; padding: 8px; border-bottom: 2px solid #ddd; }} |
| table td {{ padding: 8px; border-bottom: 1px solid #eee; }} |
| table tr.total td {{ font-weight: bold; font-size: 1.1em; border-top: 2px solid #ddd; }} |
| .footer-info {{ font-size: 14px; margin-top: 20px; }} |
| .print-hide {{ display: block; }} |
| @media print {{ |
| body {{ margin: 0; padding: 0; background-color: #fff; }} |
| .invoice-box {{ box-shadow: none; border: none; margin: 0; padding: 0; }} |
| .print-hide {{ display: none; }} |
| }} |
| @media screen and (max-width: 600px) {{ |
| body {{ padding: 0; }} |
| .invoice-box {{ padding: 15px; box-shadow: none; border: none; }} |
| .details-grid {{ grid-template-columns: 1fr; gap: 10px; }} |
| table th, table td {{ font-size: 12px; padding: 5px; }} |
| .header h1 {{ font-size: 18px; }} |
| .header p {{ font-size: 12px; }} |
| table tr.total td {{ font-size: 1em; }} |
| }} |
| </style> |
| </head> |
| <body> |
| <div class="invoice-box"> |
| <div class="print-hide" style="text-align: right; margin-bottom: 20px;"> |
| <button onclick="window.print()" style="padding: 8px 12px; font-size: 14px; cursor: pointer; background: #6c757d; color: white; border: none; border-radius: 4px;">Печать</button> |
| <button onclick="editReceipt()" style="padding: 8px 12px; font-size: 14px; cursor: pointer; background: #ffc107; color: #000; border: none; border-radius: 4px; margin-left: 10px;">Изменить накладную</button> |
| </div> |
| <div class="header"> |
| <h1>Товарная накладная № {transaction['id'][:8]}</h1> |
| <p>от {datetime.fromisoformat(transaction['timestamp']).strftime('%d.%m.%Y %H:%M')}</p> |
| </div> |
| <table> |
| <thead> |
| <tr>{table_headers}</tr> |
| </thead> |
| <tbody>{items_html}</tbody> |
| </table> |
| <table style="margin-top: 20px;"> |
| {totals_html} |
| </table> |
| {note_html} |
| <div class="footer-info"> |
| <p>Способ оплаты: {'Наличные' if transaction['payment_method'] == 'cash' else 'Карта'}</p> |
| <p>Кассир: {transaction['user_name']}</p> |
| </div> |
| {links_html} |
| </div> |
| <script> |
| function editReceipt() {{ |
| let code = prompt("Введите ПИН-код кассира или пароль администратора для изменения накладной:"); |
| if (!code) return; |
| fetch('/api/auth/universal', {{ |
| method: 'POST', |
| headers: {{'Content-Type': 'application/json'}}, |
| body: JSON.stringify({{code: code}}) |
| }}) |
| .then(r => r.json()) |
| .then(d => {{ |
| if (d.success) {{ |
| window.location.href = '/?edit_tx={transaction["id"]}'; |
| }} else {{ |
| alert("Неверный пароль или ПИН-код"); |
| }} |
| }}); |
| }} |
| </script> |
| </body> |
| </html> |
| """ |
|
|
| def admin_required(f): |
| @wraps(f) |
| def decorated_function(*args, **kwargs): |
| if 'admin_logged_in' not in session: |
| flash("Для доступа к этой странице требуется аутентификация.", "warning") |
| return redirect(url_for('admin_login', next=request.url)) |
| return f(*args, **kwargs) |
| return decorated_function |
|
|
| @app.context_processor |
| def inject_utils(): |
| return {'format_currency_py': format_currency_py, 'get_current_time': get_current_time, 'quote': quote} |
|
|
| @app.route('/api/auth/universal', methods=['POST']) |
| def auth_universal(): |
| code = request.json.get('code') |
| if code == ADMIN_PASS: |
| return jsonify({'success': True}) |
| user = find_user_by_pin(code) |
| if user: |
| return jsonify({'success': True}) |
| return jsonify({'success': False}) |
|
|
| @app.route('/') |
| def sales_screen(): |
| inventory = load_json_data('inventory') |
| kassas = load_json_data('kassas') |
| |
| edit_tx_id = request.args.get('edit_tx') |
| edit_tx = None |
| if edit_tx_id: |
| transactions = load_json_data('transactions') |
| edit_tx = find_item_by_field(transactions, 'id', edit_tx_id) |
| |
| active_inventory = [] |
| for p in inventory: |
| if isinstance(p, dict) and any(v.get('stock', 0) > 0 for v in p.get('variants', [])): |
| active_inventory.append(p) |
|
|
| active_inventory.sort(key=lambda x: x.get('name', '').lower()) |
|
|
| grouped_inventory = defaultdict(list) |
| for p in active_inventory: |
| first_letter = p.get('name', '#')[0].upper() |
| grouped_inventory[first_letter].append(p) |
|
|
| sorted_grouped_inventory = sorted(grouped_inventory.items()) |
|
|
| html = BASE_TEMPLATE.replace('__TITLE__', "Касса").replace('__CONTENT__', SALES_SCREEN_CONTENT).replace('__SCRIPTS__', SALES_SCREEN_SCRIPTS) |
| return render_template_string(html, inventory=active_inventory, kassas=kassas, grouped_inventory=sorted_grouped_inventory, edit_tx=edit_tx) |
|
|
| @app.route('/inventory', methods=['GET', 'POST']) |
| def inventory_management(): |
| is_admin = session.get('admin_logged_in', False) |
| |
| if request.method == 'POST': |
| try: |
| name = request.form.get('name', '').strip() |
| barcode = request.form.get('barcode', '').strip() |
| |
| if not name or not barcode: |
| flash("Название и штрих-код - обязательные поля.", "danger") |
| return redirect(url_for('inventory_management')) |
|
|
| inventory = load_json_data('inventory') |
| 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_prices_regular = request.form.getlist('variant_price_regular[]') |
| variant_prices_min = request.form.getlist('variant_price_min[]') |
| variant_prices_wholesale = request.form.getlist('variant_price_wholesale[]') |
| variant_cost_prices = request.form.getlist('variant_cost_price[]') |
| variant_stocks = request.form.getlist('variant_stock[]') |
| variant_image_urls = request.form.getlist('variant_image_url[]') |
|
|
| for i in range(len(variant_names)): |
| v_name = variant_names[i].strip() |
| if not v_name: continue |
| |
| if is_admin: |
| v_price_regular = str(to_decimal(variant_prices_regular[i])) if i < len(variant_prices_regular) else '0' |
| v_price_min = str(to_decimal(variant_prices_min[i])) if i < len(variant_prices_min) else '0' |
| v_price_wholesale = str(to_decimal(variant_prices_wholesale[i])) if i < len(variant_prices_wholesale) else '0' |
| v_cost = str(to_decimal(variant_cost_prices[i])) if i < len(variant_cost_prices) else '0' |
| else: |
| v_price_regular = '0' |
| v_price_min = '0' |
| v_price_wholesale = '0' |
| v_cost = '0' |
| |
| variants.append({ |
| 'id': uuid.uuid4().hex, |
| 'option_name': "Вариант", |
| 'option_value': v_name, |
| 'price_regular': v_price_regular, |
| 'price_min': v_price_min, |
| 'price_wholesale': v_price_wholesale, |
| 'cost_price': v_cost, |
| 'stock': int(to_decimal(variant_stocks[i], '0')), |
| 'image_url': variant_image_urls[i] if i < len(variant_image_urls) else '', |
| }) |
| |
| if not variants: |
| flash("Нужно добавить хотя бы один вариант товара.", "danger") |
| return redirect(url_for('inventory_management')) |
|
|
| new_product = { |
| 'id': uuid.uuid4().hex, |
| 'name': name, |
| 'barcode': barcode, |
| 'variants': variants, |
| 'timestamp_added': get_current_time().isoformat(), |
| 'timestamp_updated': get_current_time().isoformat() |
| } |
| inventory.append(new_product) |
| save_json_data('inventory', inventory) |
| upload_db_to_hf('inventory') |
| flash(f"Товар '{name}' успешно добавлен.", "success") |
| except Exception as e: |
| logging.error(f"Error adding product: {e}", exc_info=True) |
| flash(f"Ошибка при добавлении товара: {e}", "danger") |
| return redirect(url_for('inventory_management')) |
| |
| inventory_list = load_json_data('inventory') |
| inventory_list.sort(key=lambda x: x.get('name', '').lower()) |
| |
| total_units = 0 |
| total_cost_value = Decimal('0') |
| total_retail_value = Decimal('0') |
|
|
| for product in inventory_list: |
| if isinstance(product, dict) and 'variants' in product: |
| for variant in product.get('variants', []): |
| stock = variant.get('stock', 0) |
| cost_price = to_decimal(variant.get('cost_price', '0')) |
| price = to_decimal(variant.get('price_regular', variant.get('price', '0'))) |
| |
| total_units += stock |
| total_cost_value += Decimal(stock) * cost_price |
| total_retail_value += Decimal(stock) * price |
| |
| potential_profit = total_retail_value - total_cost_value |
|
|
| inventory_summary = { |
| 'total_names': len(inventory_list), |
| 'total_units': total_units, |
| 'total_cost_value': total_cost_value, |
| 'potential_profit': potential_profit |
| } |
|
|
| html = BASE_TEMPLATE.replace('__TITLE__', "Склад").replace('__CONTENT__', INVENTORY_CONTENT).replace('__SCRIPTS__', INVENTORY_SCRIPTS) |
| return render_template_string(html, inventory=inventory_list, inventory_summary=inventory_summary) |
|
|
| @app.route('/inventory/update_prices', methods=['POST']) |
| @admin_required |
| def update_prices(): |
| inventory = load_json_data('inventory') |
| variant_ids = request.form.getlist('variant_id[]') |
| prices_regular = request.form.getlist('price_regular[]') |
| prices_min = request.form.getlist('price_min[]') |
| prices_wholesale = request.form.getlist('price_wholesale[]') |
| cost_prices = request.form.getlist('cost_price[]') |
| |
| updates = {} |
| for i, vid in enumerate(variant_ids): |
| updates[vid] = ( |
| prices_regular[i], |
| prices_min[i], |
| prices_wholesale[i], |
| cost_prices[i] |
| ) |
| |
| for p in inventory: |
| updated = False |
| for v in p.get('variants', []): |
| if v.get('id') in updates: |
| v['price_regular'] = str(to_decimal(updates[v['id']][0])) |
| v['price_min'] = str(to_decimal(updates[v['id']][1])) |
| v['price_wholesale'] = str(to_decimal(updates[v['id']][2])) |
| v['cost_price'] = str(to_decimal(updates[v['id']][3])) |
| updated = True |
| if updated: |
| p['timestamp_updated'] = get_current_time().isoformat() |
| |
| save_json_data('inventory', inventory) |
| upload_db_to_hf('inventory') |
| flash("Цены успешно обновлены.", "success") |
| return redirect(url_for('inventory_management')) |
|
|
| @app.route('/inventory/edit/<product_id>', methods=['POST']) |
| @admin_required |
| def edit_product(product_id): |
| inventory = load_json_data('inventory') |
| product_found = False |
| for i, product in enumerate(inventory): |
| if isinstance(product, dict) and product.get('id') == product_id: |
| try: |
| name = request.form.get('name', '').strip() |
| barcode = request.form.get('barcode', '').strip() |
|
|
| if not name or not barcode: |
| flash("Название и штрих-код обязательны.", "danger") |
| return redirect(url_for('inventory_management')) |
|
|
| existing_barcode = find_item_by_field(inventory, 'barcode', barcode) |
| if existing_barcode and existing_barcode.get('id') != product_id: |
| flash(f"Штрих-код {barcode} уже используется другим товаром.", "warning") |
| return redirect(url_for('inventory_management')) |
|
|
| inventory[i]['name'] = name |
| inventory[i]['barcode'] = barcode |
| |
| new_variants = [] |
| variant_ids = request.form.getlist('variant_id[]') |
| variant_names = request.form.getlist('variant_name[]') |
| variant_prices_regular = request.form.getlist('variant_price_regular[]') |
| variant_prices_min = request.form.getlist('variant_price_min[]') |
| variant_prices_wholesale = request.form.getlist('variant_price_wholesale[]') |
| variant_cost_prices = request.form.getlist('variant_cost_price[]') |
| variant_stocks = request.form.getlist('variant_stock[]') |
| variant_image_urls = request.form.getlist('variant_image_url[]') |
|
|
| for j in range(len(variant_ids)): |
| v_name = variant_names[j].strip() |
| if not v_name: continue |
| new_variants.append({ |
| 'id': variant_ids[j] or uuid.uuid4().hex, |
| 'option_name': "Вариант", |
| 'option_value': v_name, |
| 'price_regular': str(to_decimal(variant_prices_regular[j])), |
| 'price_min': str(to_decimal(variant_prices_min[j])), |
| 'price_wholesale': str(to_decimal(variant_prices_wholesale[j])), |
| 'cost_price': str(to_decimal(variant_cost_prices[j])), |
| 'stock': int(to_decimal(variant_stocks[j], '0')), |
| 'image_url': variant_image_urls[j] if j < len(variant_image_urls) else '', |
| }) |
| |
| inventory[i]['variants'] = new_variants |
| inventory[i]['timestamp_updated'] = get_current_time().isoformat() |
| product_found = True |
| break |
| except Exception as e: |
| logging.error(f"Error updating product: {e}", exc_info=True) |
| flash(f"Ошибка при обновлении товара: {e}", "danger") |
| return redirect(url_for('inventory_management')) |
| |
| if product_found: |
| save_json_data('inventory', inventory) |
| upload_db_to_hf('inventory') |
| flash("Товар успешно обновлен.", "success") |
| else: |
| flash("Товар не найден.", "danger") |
| return redirect(url_for('inventory_management')) |
|
|
| @app.route('/inventory/delete/<product_id>', methods=['POST']) |
| @admin_required |
| def delete_product(product_id): |
| inventory = load_json_data('inventory') |
| initial_len = len(inventory) |
| inventory = [p for p in inventory if not (isinstance(p, dict) and p.get('id') == product_id)] |
| if len(inventory) < initial_len: |
| save_json_data('inventory', inventory) |
| upload_db_to_hf('inventory') |
| flash("Товар удален.", "success") |
| else: |
| flash("Товар не найден.", "warning") |
| return redirect(url_for('inventory_management')) |
|
|
| @app.route('/inventory/stock_in', methods=['POST']) |
| def stock_in(): |
| is_admin = session.get('admin_logged_in', False) |
| try: |
| product_id = request.form.get('product_id') |
| variant_id = request.form.get('variant_id') |
| quantity = int(request.form.get('quantity', 0)) |
| |
| cost_price_str = request.form.get('cost_price') if is_admin else None |
| delivery_cost = to_decimal(request.form.get('delivery_cost', '0')) if is_admin else Decimal('0') |
|
|
| if not product_id or not variant_id or quantity <= 0: |
| flash("Неверные данные для оприходования.", "danger") |
| return redirect(url_for('inventory_management')) |
|
|
| inventory = load_json_data('inventory') |
| product = find_item_by_field(inventory, 'id', product_id) |
| if not product: |
| flash("Товар не найден.", "danger") |
| return redirect(url_for('inventory_management')) |
|
|
| variant_found = False |
| variant_name_for_log = "" |
| for i, variant in enumerate(product.get('variants', [])): |
| if variant.get('id') == variant_id: |
| variant_name_for_log = variant.get('option_value', '') |
| |
| old_stock = variant.get('stock', 0) |
| variant['stock'] = old_stock + quantity |
| |
| old_cost = to_decimal(variant.get('cost_price', '0')) |
| new_cost = to_decimal(cost_price_str) if cost_price_str else old_cost |
|
|
| if old_stock + quantity > 0: |
| avg_cost = ((old_cost * old_stock) + (new_cost * quantity) + delivery_cost) / (old_stock + quantity) |
| variant['cost_price'] = str(avg_cost.quantize(Decimal('1'), rounding=ROUND_HALF_UP)) |
| |
| variant_found = True |
| break |
|
|
| if not variant_found: |
| flash("Вариант товара не найден.", "danger") |
| return redirect(url_for('inventory_management')) |
|
|
| if delivery_cost > 0: |
| expenses = load_json_data('expenses') |
| new_expense = { |
| 'id': uuid.uuid4().hex, |
| 'timestamp': get_current_time().isoformat(), |
| 'amount': str(delivery_cost), |
| 'description': f"Дорога: {product['name']} ({variant_name_for_log})" |
| } |
| expenses.append(new_expense) |
| save_json_data('expenses', expenses) |
| upload_db_to_hf('expenses') |
|
|
| stock_history = load_json_data('stock_history') |
| stock_history.append({ |
| 'id': uuid.uuid4().hex, |
| 'timestamp': get_current_time().isoformat(), |
| 'product_id': product_id, |
| 'variant_id': variant_id, |
| 'product_name': product['name'], |
| 'variant_name': variant_name_for_log, |
| 'quantity': quantity, |
| 'cost_price': cost_price_str or str(old_cost), |
| 'type': 'stock_in' |
| }) |
| save_json_data('stock_history', stock_history) |
| upload_db_to_hf('stock_history') |
|
|
| product['timestamp_updated'] = get_current_time().isoformat() |
| save_json_data('inventory', inventory) |
| upload_db_to_hf('inventory') |
| flash(f"Остаток товара '{product['name']} ({variant_name_for_log})' увеличен на {quantity}.", "success") |
|
|
| except Exception as e: |
| logging.error(f"Error stocking in: {e}", exc_info=True) |
| flash(f"Ошибка при оприходовании: {e}", "danger") |
|
|
| return redirect(url_for('inventory_management')) |
|
|
| @app.route('/upload_image', methods=['POST']) |
| @admin_required |
| def upload_image(): |
| if 'image' not in request.files: |
| return jsonify({'success': False, 'message': 'No file part'}), 400 |
| file = request.files['image'] |
| if file.filename == '': |
| return jsonify({'success': False, 'message': 'No selected file'}), 400 |
| if file: |
| try: |
| filename = str(uuid.uuid4()) + os.path.splitext(file.filename)[1] |
| save_path = os.path.join(app.static_folder, 'product_images', filename) |
| file.save(save_path) |
| url = url_for('static', filename=f'product_images/{filename}') |
| return jsonify({'success': True, 'url': url}) |
| except Exception as e: |
| logging.error(f"Image upload failed: {e}", exc_info=True) |
| return jsonify({'success': False, 'message': f'Server error: {e}'}), 500 |
| return jsonify({'success': False, 'message': 'Unknown error'}), 500 |
|
|
| @app.route('/api/product_by_barcode/<barcode>') |
| def get_product_by_barcode(barcode): |
| inventory = load_json_data('inventory') |
| product = find_item_by_field(inventory, 'barcode', barcode) |
| if product: |
| active_variants = [v for v in product.get('variants', []) if v.get('stock', 0) > 0] |
| if active_variants: |
| product_copy = product.copy() |
| product_copy['variants'] = active_variants |
| return jsonify({'success': True, 'product': product_copy}) |
| else: |
| return jsonify({'success': False, 'message': 'Товар закончился на складе'}), 404 |
| return jsonify({'success': False, 'message': 'Товар не найден'}), 404 |
|
|
| @app.route('/api/complete_sale', methods=['POST']) |
| def complete_sale(): |
| try: |
| data = request.get_json() |
| cart = data.get('cart', {}) |
| payment_method = data.get('paymentMethod', 'cash') |
| delivery_cost_str = data.get('deliveryCost', '0') |
| note = data.get('note', '') |
| edit_tx_id = data.get('edit_tx_id') |
|
|
| inventory = load_json_data('inventory') |
| users = load_json_data('users') |
| kassas = load_json_data('kassas') |
| transactions = load_json_data('transactions') |
|
|
| original_tx = None |
| if edit_tx_id: |
| original_tx = find_item_by_field(transactions, 'id', edit_tx_id) |
| if not original_tx: |
| return jsonify({'success': False, 'message': 'Оригинальная накладная не найдена.'}), 404 |
| |
| for item in original_tx.get('items', []): |
| if not item.get('is_custom'): |
| for p in inventory: |
| if p.get('id') == item.get('product_id'): |
| for v in p.get('variants', []): |
| if v.get('id') == item.get('variant_id'): |
| v['stock'] = v.get('stock', 0) + item.get('quantity', 0) |
| break |
| break |
| |
| if original_tx.get('payment_method') == 'cash': |
| for k in kassas: |
| if k.get('id') == original_tx.get('kassa_id'): |
| current_balance = to_decimal(k.get('balance', '0')) |
| amount = to_decimal(original_tx.get('total_amount', '0')) |
| k['balance'] = str(current_balance - amount) |
| k.setdefault('history', []).append({ |
| 'type': 'correction_revert', |
| 'amount': str(-amount), |
| 'timestamp': get_current_time().isoformat(), |
| 'description': f"Отмена до изменения {edit_tx_id[:8]}" |
| }) |
| break |
| else: |
| if not data.get('userId') or not data.get('kassaId') or not data.get('shiftId'): |
| return jsonify({'success': False, 'message': 'Неполные данные для продажи. Начните смену.'}), 400 |
|
|
| user_id = data.get('userId') if data.get('userId') else original_tx.get('user_id') |
| kassa_id = data.get('kassaId') if data.get('kassaId') else original_tx.get('kassa_id') |
| shift_id = data.get('shiftId') if data.get('shiftId') else original_tx.get('shift_id') |
|
|
| if not cart: |
| return jsonify({'success': False, 'message': 'Корзина пуста.'}), 400 |
|
|
| user = find_item_by_field(users, 'id', user_id) |
| kassa = find_item_by_field(kassas, 'id', kassa_id) |
|
|
| if not user or not kassa: |
| return jsonify({'success': False, 'message': 'Кассир или касса были удалены. Требуется повторный вход.', 'logout_required': True}), 401 |
|
|
| sale_items = [] |
| items_total = Decimal('0') |
| inventory_updates = {} |
|
|
| for item_id, cart_item in cart.items(): |
| if cart_item.get('isCustom'): |
| price_at_sale = to_decimal(cart_item.get('price', '0')) |
| quantity_sold = cart_item.get('quantity', 1) |
| item_total = price_at_sale * Decimal(quantity_sold) |
| items_total += item_total |
| sale_items.append({ |
| 'product_id': None, |
| 'variant_id': item_id, |
| 'name': cart_item.get('productName', 'Товар без штрихкода'), |
| 'barcode': 'CUSTOM', |
| 'quantity': quantity_sold, |
| 'price_at_sale': str(price_at_sale), |
| 'cost_price_at_sale': '0', |
| 'discount_per_item': '0', |
| 'total': str(item_total), |
| 'is_custom': True |
| }) |
| continue |
| |
| variant_id = item_id |
| product = find_item_by_field(inventory, 'id', cart_item['productId']) |
| if not product: |
| return jsonify({'success': False, 'message': f"Товар с ID {cart_item['productId']} не найден."}), 404 |
| |
| variant = find_item_by_field(product.get('variants', []), 'id', variant_id) |
| if not variant: |
| return jsonify({'success': False, 'message': f"Вариант товара с ID {variant_id} не найден."}), 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']} ({variant['option_value']})'. В наличии: {current_stock}"}), 400 |
|
|
| price_at_sale = to_decimal(cart_item.get('price', '0')) |
| cost_price_at_sale = to_decimal(variant.get('cost_price', '0')) |
| discount_per_item = to_decimal(cart_item.get('discount', '0')) |
|
|
| if discount_per_item > price_at_sale: |
| return jsonify({'success': False, 'message': f"Скидка на '{product['name']}' не может быть больше цены."}), 400 |
|
|
| final_price = price_at_sale - discount_per_item |
| item_total = final_price * Decimal(quantity_sold) |
| items_total += item_total |
|
|
| name_to_use = f"{product['name']} ({variant['option_value']})" if not edit_tx_id else cart_item.get('productName') or f"{product['name']} ({variant['option_value']})" |
|
|
| sale_items.append({ |
| 'product_id': product['id'], |
| 'variant_id': variant_id, |
| 'name': name_to_use, |
| 'barcode': product.get('barcode'), |
| 'quantity': quantity_sold, |
| 'price_at_sale': str(price_at_sale), |
| 'cost_price_at_sale': str(cost_price_at_sale), |
| 'discount_per_item': str(discount_per_item), |
| 'total': str(item_total) |
| }) |
| inventory_updates[variant_id] = {'product_id': product['id'], 'new_stock': current_stock - quantity_sold} |
|
|
| delivery_cost = to_decimal(delivery_cost_str) |
| total_amount = items_total + delivery_cost |
| now_iso = get_current_time().isoformat() |
| |
| new_transaction = { |
| 'id': edit_tx_id if edit_tx_id else uuid.uuid4().hex, |
| 'timestamp': original_tx['timestamp'] if original_tx else 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'), |
| 'shift_id': shift_id, |
| 'items': sale_items, |
| 'total_amount': str(total_amount), |
| 'delivery_cost': str(delivery_cost), |
| 'note': note, |
| 'payment_method': payment_method |
| } |
| |
| if edit_tx_id: |
| new_transaction['edits'] = original_tx.get('edits', []) + [{'timestamp': now_iso, 'type': 'full_edit'}] |
| |
| new_transaction['invoice_html'] = generate_receipt_html(new_transaction) |
| |
| if edit_tx_id: |
| for i, t in enumerate(transactions): |
| if t.get('id') == edit_tx_id: |
| transactions[i] = new_transaction |
| break |
| else: |
| transactions.append(new_transaction) |
|
|
| for variant_id, update_info in inventory_updates.items(): |
| for p in inventory: |
| if p.get('id') == update_info['product_id']: |
| for v in p.get('variants', []): |
| if v.get('id') == variant_id: |
| v['stock'] = update_info['new_stock'] |
| p['timestamp_updated'] = now_iso |
| break |
| break |
|
|
| if payment_method == 'cash': |
| for i, k in enumerate(kassas): |
| 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' if not edit_tx_id else 'correction_apply', |
| 'amount': str(total_amount), |
| 'timestamp': now_iso, |
| 'transaction_id': new_transaction['id'], |
| 'description': 'Продажа' if not edit_tx_id else f'Измененная накладная {edit_tx_id[:8]}' |
| }) |
| 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') |
|
|
| receipt_url = url_for('view_receipt', transaction_id=new_transaction['id'], _external=True) |
| return jsonify({ |
| 'success': True, |
| 'message': 'Накладная успешно сохранена.' if edit_tx_id else 'Продажа успешно зарегистрирована.', |
| '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 |
|
|
| @app.route('/receipt/<transaction_id>') |
| def view_receipt(transaction_id): |
| transactions = load_json_data('transactions') |
| transaction = find_item_by_field(transactions, 'id', transaction_id) |
| if transaction and 'invoice_html' in transaction: |
| return Response(transaction['invoice_html'], mimetype='text/html') |
| if transaction and 'receipt_html' in transaction: |
| return Response(transaction['receipt_html'], mimetype='text/html') |
| abort(404, description="Накладная не найдена") |
|
|
| @app.route('/transactions') |
| @admin_required |
| def transaction_history(): |
| selected_date_str = request.args.get('date', get_current_time().strftime('%Y-%m-%d')) |
| selected_kassa_id = request.args.get('kassa', '') |
| try: |
| selected_date = datetime.strptime(selected_date_str, '%Y-%m-%d').date() |
| except ValueError: |
| selected_date = get_current_time().date() |
| selected_date_str = selected_date.strftime('%Y-%m-%d') |
| |
| transactions = load_json_data('transactions') |
| kassas = load_json_data('kassas') |
| |
| filtered_transactions = [ |
| t for t in transactions |
| if datetime.fromisoformat(t['timestamp']).date() == selected_date |
| ] |
| |
| if selected_kassa_id: |
| filtered_transactions = [ |
| t for t in filtered_transactions |
| if t.get('kassa_id') == selected_kassa_id |
| ] |
| |
| total_sales = sum(to_decimal(t['total_amount']) for t in filtered_transactions if t.get('type') == 'sale') |
| |
| total_quantity_sold = 0 |
| for t in filtered_transactions: |
| if t.get('type') == 'sale': |
| for item in t.get('items', []): |
| total_quantity_sold += int(item.get('quantity', 0)) |
| |
| filtered_transactions.sort(key=lambda x: x.get('timestamp', ''), reverse=True) |
| |
| html = BASE_TEMPLATE.replace('__TITLE__', "История транзакций").replace('__CONTENT__', TRANSACTIONS_CONTENT).replace('__SCRIPTS__', TRANSACTIONS_SCRIPTS) |
| return render_template_string(html, transactions=filtered_transactions, total_sales=total_sales, total_quantity_sold=total_quantity_sold, selected_date=selected_date_str, kassas=kassas, selected_kassa_id=selected_kassa_id) |
|
|
| @app.route('/admin/transaction/edit/<transaction_id>', methods=['POST']) |
| @admin_required |
| def edit_transaction(transaction_id): |
| try: |
| data = request.get_json() |
| items_update = data.get('items', []) |
| |
| transactions = load_json_data('transactions') |
| kassas = load_json_data('kassas') |
| |
| transaction_index = -1 |
| for i, t in enumerate(transactions): |
| if t.get('id') == transaction_id: |
| transaction_index = i |
| break |
| |
| if transaction_index == -1: |
| return jsonify({'success': False, 'message': 'Транзакция не найдена'}), 404 |
| |
| original_transaction = transactions[transaction_index] |
| old_total_amount = to_decimal(original_transaction['total_amount']) |
| |
| new_items_total = Decimal('0') |
| updated_items = [] |
| |
| for item in original_transaction['items']: |
| item_id = item.get('variant_id') or item.get('product_id') |
| update_data = find_item_by_field(items_update, 'id', item_id) |
| |
| if update_data: |
| new_price = to_decimal(update_data.get('price', item['price_at_sale'])) |
| new_discount = to_decimal(update_data.get('discount', item.get('discount_per_item', '0'))) |
| |
| item['price_at_sale'] = str(new_price) |
| item['discount_per_item'] = str(new_discount) |
| item_total = (new_price - new_discount) * Decimal(item['quantity']) |
| item['total'] = str(item_total) |
| |
| new_items_total += to_decimal(item['total']) |
| |
| delivery_cost = to_decimal(original_transaction.get('delivery_cost', '0')) |
| new_total_amount = new_items_total + delivery_cost |
| transactions[transaction_index]['total_amount'] = str(new_total_amount) |
| |
| if 'edits' not in transactions[transaction_index]: |
| transactions[transaction_index]['edits'] = [] |
| |
| transactions[transaction_index]['edits'].append({ |
| 'timestamp': get_current_time().isoformat(), |
| 'admin_user': session.get('admin_username', 'admin'), |
| 'old_total': str(old_total_amount), |
| 'new_total': str(new_total_amount) |
| }) |
|
|
| transactions[transaction_index]['invoice_html'] = generate_receipt_html(transactions[transaction_index]) |
|
|
| amount_diff = new_total_amount - old_total_amount |
| if amount_diff != Decimal(0) and original_transaction['payment_method'] == 'cash': |
| kassa_id = original_transaction.get('kassa_id') |
| for i, k in enumerate(kassas): |
| if k.get('id') == kassa_id: |
| k['balance'] = str(to_decimal(k.get('balance', '0')) + amount_diff) |
| k.setdefault('history', []).append({ |
| 'type': 'correction', |
| 'amount': str(amount_diff), |
| 'timestamp': get_current_time().isoformat(), |
| 'description': f"Корректировка транзакции {transaction_id[:8]}" |
| }) |
| break |
| save_json_data('kassas', kassas) |
| upload_db_to_hf('kassas') |
|
|
| save_json_data('transactions', transactions) |
| upload_db_to_hf('transactions') |
| |
| flash("Транзакция успешно обновлена.", "success") |
| return jsonify({'success': True, 'message': 'Транзакция обновлена'}) |
| except Exception as e: |
| logging.error(f"Error editing transaction: {e}", exc_info=True) |
| return jsonify({'success': False, 'message': f'Внутренняя ошибка: {e}'}), 500 |
|
|
| @app.route('/admin/transaction/delete/<transaction_id>', methods=['POST']) |
| @admin_required |
| def delete_transaction(transaction_id): |
| transactions = load_json_data('transactions') |
| inventory = load_json_data('inventory') |
| kassas = load_json_data('kassas') |
|
|
| transaction_to_delete = find_item_by_field(transactions, 'id', transaction_id) |
| if not transaction_to_delete: |
| flash("Транзакция не найдена.", "danger") |
| return redirect(url_for('transaction_history')) |
|
|
| for item in transaction_to_delete.get('items', []): |
| if item.get('is_custom'): |
| continue |
| |
| product = find_item_by_field(inventory, 'id', item.get('product_id')) |
| if not product: continue |
| |
| variant = find_item_by_field(product.get('variants', []), 'id', item.get('variant_id')) |
| if not variant: continue |
|
|
| quantity_change = item.get('quantity', 0) |
| |
| if transaction_to_delete.get('type') == 'sale': |
| variant['stock'] = variant.get('stock', 0) + quantity_change |
| elif transaction_to_delete.get('type') == 'return': |
| variant['stock'] = variant.get('stock', 0) - quantity_change |
|
|
| if transaction_to_delete.get('payment_method') == 'cash': |
| kassa = find_item_by_field(kassas, 'id', transaction_to_delete.get('kassa_id')) |
| if kassa: |
| current_balance = to_decimal(kassa.get('balance', '0')) |
| amount_change = to_decimal(transaction_to_delete.get('total_amount')) |
| |
| kassa['balance'] = str(current_balance - amount_change) |
| |
| kassa.setdefault('history', []).append({ |
| 'type': 'deletion', |
| 'amount': str(-amount_change), |
| 'timestamp': get_current_time().isoformat(), |
| 'description': f"Удаление транзакции {transaction_id[:8]}" |
| }) |
|
|
| transactions = [t for t in transactions if t.get('id') != transaction_id] |
| |
| if transaction_to_delete.get('type') == 'return': |
| original_id = transaction_to_delete.get('original_transaction_id') |
| if original_id: |
| for i, t in enumerate(transactions): |
| if t.get('id') == original_id: |
| transactions[i]['status'] = 'completed' |
| break |
|
|
| save_json_data('inventory', inventory) |
| save_json_data('kassas', kassas) |
| save_json_data('transactions', transactions) |
| |
| upload_db_to_hf('inventory') |
| upload_db_to_hf('kassas') |
| upload_db_to_hf('transactions') |
| |
| flash("Транзакция успешно удалена.", "success") |
| return redirect(url_for('transaction_history')) |
|
|
| @app.route('/reports') |
| @admin_required |
| def reports(): |
| today = get_current_time().date() |
| start_date_str = request.args.get('start_date', (today.replace(day=1)).strftime('%Y-%m-%d')) |
| end_date_str = request.args.get('end_date', (today).strftime('%Y-%m-%d')) |
|
|
| start_date = datetime.strptime(start_date_str, '%Y-%m-%d').replace(tzinfo=ALMATY_TZ) |
| end_date = (datetime.strptime(end_date_str, '%Y-%m-%d') + timedelta(days=1)).replace(tzinfo=ALMATY_TZ) |
| num_days = (end_date - start_date).days |
|
|
| transactions = load_json_data('transactions') |
| expenses = load_json_data('expenses') |
| personal_expenses = load_json_data('personal_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_personal_expenses = [ |
| e for e in personal_expenses |
| if start_date <= datetime.fromisoformat(e['timestamp']) < end_date |
| ] |
| |
| return_transactions = [t for t in filtered_transactions if t.get('type') == 'return'] |
| total_returns_amount = sum(to_decimal(t['total_amount']) for t in return_transactions) |
| total_returns_count = len(return_transactions) |
|
|
| total_revenue = sum(to_decimal(t['total_amount']) for t in filtered_transactions) |
| total_cogs = sum( |
| to_decimal(item.get('cost_price_at_sale', '0')) * to_decimal(str(item['quantity'])) |
| for t in filtered_transactions for item in t['items'] |
| ) |
| gross_profit = total_revenue - total_cogs |
| total_expenses = sum(to_decimal(e['amount']) for e in filtered_expenses) |
| total_personal_expenses = sum(to_decimal(e['amount']) for e in filtered_personal_expenses) |
| |
| sales_by_cashier = defaultdict(lambda: {'count': 0, 'total': Decimal(0)}) |
| for t in filtered_transactions: |
| if t.get('type') == 'sale': |
| cashier_name = t.get('user_name', 'Неизвестный') |
| sales_by_cashier[cashier_name]['count'] += 1 |
| sales_by_cashier[cashier_name]['total'] += to_decimal(t['total_amount']) |
| elif t.get('type') == 'return': |
| cashier_name = t.get('user_name', 'Неизвестный') |
| 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: |
| if t.get('type') != 'sale': continue |
| user = find_item_by_field(users, 'id', t.get('user_id')) |
| if user: |
| payment_type = user.get('payment_type') |
| payment_value = to_decimal(user.get('payment_value', '0')) |
| if payment_type == 'percentage' and payment_value > 0: |
| payout = to_decimal(t['total_amount']) * (payment_value / Decimal(100)) |
| cashier_payouts[user['name']] += payout |
|
|
| for user in users: |
| if user.get('payment_type') == 'salary': |
| monthly_salary = to_decimal(user.get('payment_value', '0')) |
| if monthly_salary > 0: |
| daily_salary = monthly_salary / Decimal(30) |
| period_salary = daily_salary * Decimal(num_days) |
| cashier_payouts[user['name']] += period_salary |
|
|
| total_salary_expenses = sum(cashier_payouts.values()) |
| net_profit = gross_profit - total_expenses - total_personal_expenses - total_salary_expenses |
| |
| stats = { |
| 'total_revenue': total_revenue, |
| 'total_returns_amount': abs(total_returns_amount), |
| 'total_returns_count': total_returns_count, |
| 'total_cogs': total_cogs, |
| 'gross_profit': gross_profit, |
| 'total_expenses': total_expenses, |
| 'total_personal_expenses': total_personal_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) |
| filtered_personal_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, personal_expenses=filtered_personal_expenses) |
|
|
| @app.route('/reports/employee') |
| @admin_required |
| def employee_report(): |
| users = load_json_data('users') |
| today = get_current_time().date() |
| start_date_str = request.args.get('start_date', (today.replace(day=1)).strftime('%Y-%m-%d')) |
| end_date_str = request.args.get('end_date', today.strftime('%Y-%m-%d')) |
| user_id = request.args.get('user_id', '') |
|
|
| start_date = datetime.strptime(start_date_str, '%Y-%m-%d').replace(tzinfo=ALMATY_TZ) |
| end_date = (datetime.strptime(end_date_str, '%Y-%m-%d') + timedelta(days=1)).replace(tzinfo=ALMATY_TZ) |
|
|
| transactions = load_json_data('transactions') |
| employee_transactions = [] |
| totals = {'sales': Decimal(0), 'returns': Decimal(0), 'net': Decimal(0)} |
|
|
| if user_id: |
| for t in transactions: |
| if t.get('user_id') == user_id: |
| t_date = datetime.fromisoformat(t['timestamp']) |
| if start_date <= t_date < end_date: |
| employee_transactions.append(t) |
| amt = to_decimal(t['total_amount']) |
| if t['type'] == 'sale': |
| totals['sales'] += amt |
| totals['net'] += amt |
| elif t['type'] == 'return': |
| totals['returns'] += abs(amt) |
| totals['net'] -= abs(amt) |
|
|
| employee_transactions.sort(key=lambda x: x['timestamp'], reverse=True) |
|
|
| html = BASE_TEMPLATE.replace('__TITLE__', "Отчет по сотрудникам").replace('__CONTENT__', EMPLOYEE_REPORT_CONTENT).replace('__SCRIPTS__', '') |
| return render_template_string(html, users=users, transactions=employee_transactions, start_date=start_date_str, end_date=end_date_str, selected_user=user_id, totals=totals) |
|
|
| @app.route('/reports/item_movement') |
| @admin_required |
| def item_movement_report(): |
| inventory = load_json_data('inventory') |
| transactions = load_json_data('transactions') |
| stock_history = load_json_data('stock_history') |
|
|
| product_id = request.args.get('product_id', '') |
| variant_id = request.args.get('variant_id', '') |
|
|
| movements = [] |
| selected_product = None |
| selected_variant = None |
|
|
| if product_id: |
| selected_product = find_item_by_field(inventory, 'id', product_id) |
| if selected_product and variant_id: |
| selected_variant = find_item_by_field(selected_product.get('variants', []), 'id', variant_id) |
|
|
| for t in transactions: |
| for item in t.get('items', []): |
| if item.get('product_id') == product_id and (not variant_id or item.get('variant_id') == variant_id): |
| movements.append({ |
| 'timestamp': t['timestamp'], |
| 'type': t['type'], |
| 'qty': -item['quantity'] if t['type'] == 'sale' else item['quantity'], |
| 'price': item['price_at_sale'], |
| 'doc_id': t['id'][:8], |
| 'user': t.get('user_name', 'Система'), |
| 'variant_name': item.get('name', '') |
| }) |
|
|
| for sh in stock_history: |
| if sh.get('product_id') == product_id and (not variant_id or sh.get('variant_id') == variant_id): |
| movements.append({ |
| 'timestamp': sh['timestamp'], |
| 'type': 'stock_in', |
| 'qty': sh['quantity'], |
| 'price': sh.get('cost_price', '0'), |
| 'doc_id': 'Приход', |
| 'user': 'Админ', |
| 'variant_name': f"{sh.get('product_name')} ({sh.get('variant_name')})" |
| }) |
|
|
| movements.sort(key=lambda x: x['timestamp'], reverse=True) |
|
|
| html = BASE_TEMPLATE.replace('__TITLE__', "Движение товаров").replace('__CONTENT__', ITEM_MOVEMENT_CONTENT).replace('__SCRIPTS__', ITEM_MOVEMENT_SCRIPTS) |
| return render_template_string(html, inventory=inventory, movements=movements, product_id=product_id, variant_id=variant_id, selected_product=selected_product, selected_variant=selected_variant) |
|
|
| @app.route('/reports/product_roi') |
| @admin_required |
| def product_roi_report(): |
| inventory = load_json_data('inventory') |
| transactions = load_json_data('transactions') |
|
|
| product_stats = [] |
|
|
| for product in inventory: |
| for variant in product.get('variants', []): |
| total_revenue = Decimal('0') |
| total_cogs = Decimal('0') |
| total_qty_sold = 0 |
|
|
| for t in transactions: |
| if t['type'] in ['sale', 'return']: |
| for item in t['items']: |
| if item.get('variant_id') == variant['id']: |
| total_revenue += to_decimal(item['total']) |
| total_cogs += to_decimal(item.get('cost_price_at_sale', '0')) * to_decimal(str(item['quantity'])) |
| if t['type'] == 'sale': |
| total_qty_sold += item['quantity'] |
| elif t['type'] == 'return': |
| total_qty_sold -= item['quantity'] |
|
|
| current_stock = to_decimal(str(variant.get('stock', 0))) |
| cost_price = to_decimal(variant.get('cost_price', '0')) |
| |
| inventory_value = current_stock * cost_price |
| |
| total_investment = total_cogs + inventory_value |
| payback = total_revenue - total_investment |
|
|
| product_stats.append({ |
| 'name': product['name'], |
| 'variant_name': variant['option_value'], |
| 'total_qty_sold': total_qty_sold, |
| 'total_revenue': total_revenue, |
| 'total_investment': total_investment, |
| 'inventory_value': inventory_value, |
| 'payback': payback |
| }) |
|
|
| product_stats.sort(key=lambda x: x['payback'], reverse=True) |
| html = BASE_TEMPLATE.replace('__TITLE__', "Отчет по окупаемости товаров").replace('__CONTENT__', PRODUCT_ROI_CONTENT).replace('__SCRIPTS__', '') |
| return render_template_string(html, stats=product_stats) |
|
|
| @app.route('/admin', methods=['GET']) |
| @admin_required |
| def admin_panel(): |
| users = load_json_data('users') |
| kassas = load_json_data('kassas') |
| expenses = load_json_data('expenses') |
| personal_expenses = load_json_data('personal_expenses') |
| links = load_json_data('links') |
| expenses.sort(key=lambda x: x.get('timestamp', ''), reverse=True) |
| personal_expenses.sort(key=lambda x: x.get('timestamp', ''), reverse=True) |
| html = BASE_TEMPLATE.replace('__TITLE__', "Админ-панель").replace('__CONTENT__', ADMIN_CONTENT).replace('__SCRIPTS__', ADMIN_SCRIPTS) |
| return render_template_string(html, users=users, kassas=kassas, expenses=expenses, personal_expenses=personal_expenses, links=links) |
|
|
| @app.route('/admin/shifts') |
| @admin_required |
| def admin_shifts(): |
| shifts = load_json_data('shifts') |
| shifts.sort(key=lambda x: x.get('start_time', ''), reverse=True) |
| html = BASE_TEMPLATE.replace('__TITLE__', "История смен").replace('__CONTENT__', SHIFTS_CONTENT) |
| return render_template_string(html, shifts=shifts) |
|
|
| @app.route('/admin/user', methods=['POST']) |
| @admin_required |
| def manage_user(): |
| action = request.form.get('action') |
| users = load_json_data('users') |
| |
| if action == 'add': |
| name = request.form.get('name', '').strip() |
| pin = request.form.get('pin', '').strip() |
| 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) |
| } |
| users.append(new_user) |
| flash(f"Кассир '{name}' добавлен.", "success") |
| else: |
| flash("Все поля обязательны.", "danger") |
| |
| elif action == 'edit': |
| user_id = request.form.get('id') |
| user = find_item_by_field(users, 'id', user_id) |
| if user: |
| user['name'] = request.form.get('name', '').strip() |
| user['pin'] = request.form.get('pin', '').strip() |
| 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") |
|
|
| 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") |
|
|
| save_json_data('users', users) |
| upload_db_to_hf('users') |
| return redirect(url_for('admin_panel')) |
|
|
| @app.route('/admin/kassa', methods=['POST']) |
| @admin_required |
| def manage_kassa(): |
| action = request.form.get('action') |
| kassas = load_json_data('kassas') |
| |
| if action == 'add': |
| 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': [] |
| } |
| if balance > 0: |
| 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") |
|
|
| 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") |
| |
| save_json_data('kassas', kassas) |
| upload_db_to_hf('kassas') |
| return redirect(url_for('admin_panel')) |
|
|
| @app.route('/admin/kassa_op', methods=['POST']) |
| @admin_required |
| def kassa_operation(): |
| kassa_id = request.form.get('kassa_id') |
| op_type = request.form.get('op_type') |
| amount = to_decimal(request.form.get('amount', '0')) |
| description = request.form.get('description', '').strip() |
| |
| if not kassa_id or not op_type or amount <= 0: |
| flash("Выберите кассу, тип операции и укажите положительную сумму.", "danger") |
| return redirect(url_for('admin_panel')) |
| |
| kassas = load_json_data('kassas') |
| kassa_found = False |
| for i, kassa in enumerate(kassas): |
| 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 |
| elif op_type == 'withdrawal': |
| if amount > current_balance: |
| flash("Сумма изъятия превышает баланс кассы.", "danger") |
| return redirect(url_for('admin_panel')) |
| 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(), |
| 'description': description or f"{'Внесение' if op_type == 'deposit' else 'Изъятие'} средств" |
| }) |
| kassa_found = True |
| break |
| |
| if kassa_found: |
| save_json_data('kassas', kassas) |
| upload_db_to_hf('kassas') |
| flash("Операция по кассе успешно проведена.", "success") |
| else: |
| flash("Касса не найдена.", "danger") |
| |
| return redirect(url_for('admin_panel')) |
| |
| @app.route('/admin/expense', methods=['POST']) |
| @admin_required |
| def manage_expense(): |
| amount = to_decimal(request.form.get('amount', '0')) |
| description = request.form.get('description', '').strip() |
|
|
| if amount <= 0 or not description: |
| flash("Укажите положительную сумму и описание расхода.", "danger") |
| return redirect(url_for('admin_panel')) |
|
|
| 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) |
| upload_db_to_hf('expenses') |
| flash("Расход успешно добавлен.", "success") |
| return redirect(url_for('admin_panel')) |
|
|
| @app.route('/admin/expense/delete/<expense_id>', methods=['POST']) |
| @admin_required |
| def delete_expense(expense_id): |
| expenses = load_json_data('expenses') |
| initial_len = len(expenses) |
| expenses = [e for e in expenses if e.get('id') != expense_id] |
| if len(expenses) < initial_len: |
| save_json_data('expenses', expenses) |
| upload_db_to_hf('expenses') |
| flash("Расход удален.", "success") |
| else: |
| flash("Расход не найден.", "warning") |
| return redirect(url_for('admin_panel')) |
|
|
| @app.route('/admin/personal_expense', methods=['POST']) |
| @admin_required |
| def manage_personal_expense(): |
| amount = to_decimal(request.form.get('amount', '0')) |
| description = request.form.get('description', '').strip() |
|
|
| if amount <= 0 or not description: |
| flash("Укажите положительную сумму и описание личного расхода.", "danger") |
| return redirect(url_for('admin_panel')) |
|
|
| new_expense = { |
| 'id': uuid.uuid4().hex, |
| 'timestamp': get_current_time().isoformat(), |
| 'amount': str(amount), |
| 'description': description |
| } |
| expenses = load_json_data('personal_expenses') |
| expenses.append(new_expense) |
| save_json_data('personal_expenses', expenses) |
| upload_db_to_hf('personal_expenses') |
| flash("Личный расход успешно добавлен.", "success") |
| return redirect(url_for('admin_panel')) |
|
|
| @app.route('/admin/personal_expense/delete/<expense_id>', methods=['POST']) |
| @admin_required |
| def delete_personal_expense(expense_id): |
| expenses = load_json_data('personal_expenses') |
| initial_len = len(expenses) |
| expenses = [e for e in expenses if e.get('id') != expense_id] |
| if len(expenses) < initial_len: |
| save_json_data('personal_expenses', expenses) |
| upload_db_to_hf('personal_expenses') |
| flash("Личный расход удален.", "success") |
| else: |
| flash("Личный расход не найден.", "warning") |
| return redirect(url_for('admin_panel')) |
|
|
| @app.route('/admin/link', methods=['POST']) |
| @admin_required |
| def manage_link(): |
| action = request.form.get('action') |
| links = load_json_data('links') |
| if action == 'add': |
| name = request.form.get('name', '').strip() |
| url = request.form.get('url', '').strip() |
| if name and url: |
| links.append({'id': uuid.uuid4().hex, 'name': name, 'url': url}) |
| flash("Ссылка добавлена.", "success") |
| elif action == 'delete': |
| link_id = request.form.get('id') |
| links = [l for l in links if l.get('id') != link_id] |
| flash("Ссылка удалена.", "success") |
| save_json_data('links', links) |
| upload_db_to_hf('links') |
| return redirect(url_for('admin_panel')) |
|
|
| @app.route('/cashier_login', methods=['GET', 'POST']) |
| 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") |
| html = BASE_TEMPLATE.replace('__TITLE__', "Вход для кассира").replace('__CONTENT__', CASHIER_LOGIN_CONTENT).replace('__SCRIPTS__', '') |
| return render_template_string(html) |
|
|
| @app.route('/api/verify_pin', methods=['POST']) |
| def verify_pin(): |
| pin = request.json.get('pin') |
| user = find_user_by_pin(pin) |
| if user: |
| return jsonify({'success': True, 'user': {'id': user['id'], 'name': user['name']}}) |
| else: |
| return jsonify({'success': False, 'message': 'Неверный ПИН-код'}), 401 |
|
|
| @app.route('/api/shift/start', methods=['POST']) |
| def start_shift(): |
| data = request.json |
| user_id = data.get('userId') |
| kassa_id = data.get('kassaId') |
| |
| if not user_id: |
| return jsonify({'success': False, 'message': 'Missing user ID'}), 400 |
| |
| shifts = load_json_data('shifts') |
| open_shift = next((s for s in shifts if s.get('user_id') == user_id and s.get('end_time') is None), None) |
| if open_shift: |
| return jsonify({'success': True, 'shift': open_shift}) |
|
|
| if not kassa_id: |
| return jsonify({'success': False, 'message': 'Выберите кассу для начала новой смены'}), 400 |
|
|
| users = load_json_data('users') |
| kassas = load_json_data('kassas') |
| user = find_item_by_field(users, 'id', user_id) |
|
|
| if not user: |
| return jsonify({'success': False, 'message': 'Ваш пользователь был удален. Требуется повторный вход.', 'logout_required': True}), 401 |
|
|
| kassa = find_item_by_field(kassas, 'id', kassa_id) |
| if not kassa: |
| return jsonify({'success': False, 'message': 'Выбранная касса не найдена. Возможно, она была удалена.'}), 404 |
|
|
| new_shift = { |
| 'id': uuid.uuid4().hex, |
| 'user_id': user_id, |
| 'user_name': user['name'], |
| 'kassa_id': kassa_id, |
| 'kassa_name': kassa['name'], |
| 'start_time': get_current_time().isoformat(), |
| 'start_balance': kassa.get('balance', '0'), |
| 'end_time': None |
| } |
| shifts.append(new_shift) |
| save_json_data('shifts', shifts) |
| upload_db_to_hf('shifts') |
| return jsonify({'success': True, 'shift': new_shift}) |
|
|
| @app.route('/api/shift/end', methods=['POST']) |
| def end_shift(): |
| data = request.json |
| shift_id = data.get('shiftId') |
| if not shift_id: |
| return jsonify({'success': False, 'message': 'Missing shift ID'}), 400 |
|
|
| shifts = load_json_data('shifts') |
| kassas = load_json_data('kassas') |
| transactions = load_json_data('transactions') |
| users = load_json_data('users') |
| |
| shift_found = False |
| for i, shift in enumerate(shifts): |
| if shift.get('id') == shift_id: |
| if shift.get('end_time'): |
| return jsonify({'success': False, 'message': 'Смена уже закрыта'}), 400 |
| |
| user = find_item_by_field(users, 'id', shift.get('user_id')) |
| kassa = find_item_by_field(kassas, 'id', shift.get('kassa_id')) |
| if not user or not kassa: |
| return jsonify({'success': False, 'message': 'Кассир или касса были удалены. Невозможно завершить смену. Требуется повторный вход.', 'logout_required': True}), 401 |
|
|
| shift['end_time'] = get_current_time().isoformat() |
| |
| shift['end_balance'] = kassa.get('balance', '0') if kassa else '0' |
|
|
| shift_transactions = [ |
| t for t in transactions |
| if t.get('shift_id') == shift_id and datetime.fromisoformat(t['timestamp']) >= datetime.fromisoformat(shift['start_time']) |
| ] |
| |
| cash_sales = sum(to_decimal(t['total_amount']) for t in shift_transactions if t['type'] == 'sale' and t['payment_method'] == 'cash') |
| card_sales = sum(to_decimal(t['total_amount']) for t in shift_transactions if t['type'] == 'sale' and t['payment_method'] == 'card') |
| |
| shift['cash_sales'] = str(cash_sales) |
| shift['card_sales'] = str(card_sales) |
| shift['total_sales'] = str(cash_sales + card_sales) |
| |
| shifts[i] = shift |
| shift_found = True |
| break |
| |
| if not shift_found: |
| return jsonify({'success': False, 'message': 'Смена не найдена'}), 404 |
| |
| save_json_data('shifts', shifts) |
| upload_db_to_hf('shifts') |
| return jsonify({'success': True, 'message': 'Смена успешно закрыта'}) |
|
|
| @app.route('/cashier_dashboard/<user_id>') |
| def cashier_dashboard(user_id): |
| users = load_json_data('users') |
| user = find_item_by_field(users, 'id', user_id) |
| if not user: |
| abort(404, "Кассир не найден") |
| |
| transactions = load_json_data('transactions') |
| user_transactions = [t for t in transactions if t.get('user_id') == user_id] |
| user_transactions.sort(key=lambda x: x['timestamp'], reverse=True) |
| |
| html = BASE_TEMPLATE.replace('__TITLE__', f"Продажи кассира: {user['name']}").replace('__CONTENT__', CASHIER_DASHBOARD_CONTENT).replace('__SCRIPTS__', '') |
| return render_template_string(html, user=user, transactions=user_transactions) |
|
|
| @app.route('/return_transaction/<transaction_id>', methods=['GET', 'POST']) |
| def return_transaction(transaction_id): |
| transactions = load_json_data('transactions') |
| inventory = load_json_data('inventory') |
| kassas = load_json_data('kassas') |
|
|
| original_transaction_index = -1 |
| for i, t in enumerate(transactions): |
| if t.get('id') == transaction_id: |
| original_transaction_index = i |
| break |
| |
| if original_transaction_index == -1: |
| flash("Оригинальная транзакция не найдена.", "danger") |
| return redirect(url_for('cashier_login')) |
|
|
| original_transaction = transactions[original_transaction_index] |
|
|
| if request.method == 'GET': |
| cashier_id = request.args.get('cashier_id') |
| if not cashier_id: |
| flash("Не указан ID кассира.", "danger") |
| return redirect(url_for('cashier_login')) |
| |
| returnable_items = [] |
| already_returned = original_transaction.get('return_info', {}).get('returned_items', {}) |
| |
| for item in original_transaction['items']: |
| variant_id = item.get('variant_id') |
| returned_qty = already_returned.get(variant_id, 0) |
| max_returnable = item['quantity'] - returned_qty |
| if max_returnable > 0: |
| item_copy = item.copy() |
| item_copy['max_returnable'] = max_returnable |
| returnable_items.append(item_copy) |
|
|
| html = BASE_TEMPLATE.replace('__TITLE__', f"Возврат по накладной {transaction_id[:8]}").replace('__CONTENT__', RETURN_PAGE_CONTENT).replace('__SCRIPTS__', '') |
| return render_template_string(html, transaction=original_transaction, items=returnable_items, cashier_id=cashier_id) |
|
|
| if request.method == 'POST': |
| cashier_id = request.form.get('cashier_id') |
| if not cashier_id: |
| flash("Не удалось определить кассира.", "danger") |
| return redirect(url_for('cashier_login')) |
|
|
| return_items = [] |
| total_return_amount = Decimal('0') |
| inventory_updates = {} |
| items_to_process = defaultdict(int) |
|
|
| for key, value in request.form.items(): |
| if key.startswith('return_qty_'): |
| variant_id = key.replace('return_qty_', '') |
| try: |
| qty = int(value) |
| if qty > 0: |
| items_to_process[variant_id] = qty |
| except (ValueError, TypeError): |
| continue |
| |
| if not items_to_process: |
| flash("Не выбрано ни одного товара для возврата.", "warning") |
| return redirect(url_for('return_transaction', transaction_id=transaction_id, cashier_id=cashier_id)) |
|
|
| already_returned = original_transaction.get('return_info', {}).get('returned_items', {}) |
| total_items_in_sale = 0 |
| total_items_returned_before = sum(already_returned.values()) |
|
|
| for item in original_transaction['items']: |
| variant_id = item.get('variant_id') |
| total_items_in_sale += item['quantity'] |
|
|
| if variant_id in items_to_process: |
| qty_to_return = items_to_process[variant_id] |
| |
| returned_so_far = already_returned.get(variant_id, 0) |
| if qty_to_return > (item['quantity'] - returned_so_far): |
| flash(f"Нельзя вернуть {qty_to_return} шт. товара '{item['name']}', т.к. доступно к возврату {item['quantity'] - returned_so_far}.", "danger") |
| return redirect(url_for('return_transaction', transaction_id=transaction_id, cashier_id=cashier_id)) |
| |
| price = to_decimal(item['price_at_sale']) |
| discount = to_decimal(item.get('discount_per_item', '0')) |
| item_total = (price - discount) * qty_to_return |
| total_return_amount += item_total |
| |
| return_items.append({**item, 'quantity': qty_to_return, 'total': str(item_total)}) |
|
|
| if not item.get('is_custom'): |
| product = find_item_by_field(inventory, 'id', item['product_id']) |
| if product: |
| variant = find_item_by_field(product.get('variants', []), 'id', variant_id) |
| if variant: |
| inventory_updates[variant_id] = {'product_id': item['product_id'], 'stock_change': qty_to_return} |
|
|
| now_iso = get_current_time().isoformat() |
| return_transaction_id = uuid.uuid4().hex |
| return_transaction = { |
| 'id': return_transaction_id, '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'], |
| 'shift_id': original_transaction.get('shift_id'), |
| 'items': return_items, |
| 'total_amount': str(-total_return_amount), |
| 'payment_method': original_transaction['payment_method'] |
| } |
| transactions.append(return_transaction) |
| |
| return_info = original_transaction.setdefault('return_info', {'returned_items': {}, 'return_transaction_ids': []}) |
| return_info['return_transaction_ids'].append(return_transaction_id) |
| total_items_returned_now = 0 |
| for variant_id, qty in items_to_process.items(): |
| return_info['returned_items'][variant_id] = return_info['returned_items'].get(variant_id, 0) + qty |
| total_items_returned_now += qty |
|
|
| if (total_items_returned_before + total_items_returned_now) >= total_items_in_sale: |
| original_transaction['status'] = 'returned' |
| else: |
| original_transaction['status'] = 'partially_returned' |
| |
| transactions[original_transaction_index] = original_transaction |
|
|
| for variant_id, update_info in inventory_updates.items(): |
| for p_idx, p in enumerate(inventory): |
| if p.get('id') == update_info['product_id']: |
| for v_idx, v in enumerate(p.get('variants', [])): |
| if v.get('id') == variant_id: |
| inventory[p_idx]['variants'][v_idx]['stock'] += update_info['stock_change'] |
| inventory[p_idx]['timestamp_updated'] = now_iso |
| break |
| break |
|
|
| if original_transaction['payment_method'] == 'cash' and total_return_amount > 0: |
| for k_idx, k in enumerate(kassas): |
| if k.get('id') == original_transaction['kassa_id']: |
| current_balance = to_decimal(k.get('balance', '0')) |
| kassas[k_idx]['balance'] = str(current_balance - total_return_amount) |
| kassas[k_idx].setdefault('history', []).append({ |
| 'type': 'return', 'amount': str(-total_return_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') |
|
|
| flash("Возврат успешно оформлен.", "success") |
| return redirect(url_for('cashier_dashboard', user_id=cashier_id)) |
|
|
| @app.route('/backup', methods=['POST']) |
| @admin_required |
| def backup_hf(): |
| try: |
| 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") |
| return redirect(url_for('admin_panel')) |
|
|
| @app.route('/download', methods=['GET']) |
| @admin_required |
| def download_hf(): |
| 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, |
| ) |
| 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") |
| return redirect(url_for('admin_panel')) |
|
|
| @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 |
| session.permanent = True |
| next_url = request.args.get('next') |
| flash("Вы успешно вошли в систему.", "success") |
| return redirect(next_url or url_for('admin_panel')) |
| else: |
| flash("Неверный пароль.", "danger") |
| html = BASE_TEMPLATE.replace('__TITLE__', "Вход для администратора").replace('__CONTENT__', ADMIN_LOGIN_CONTENT).replace('__SCRIPTS__', '') |
| return render_template_string(html) |
|
|
| @app.route('/admin_logout') |
| def admin_logout(): |
| session.pop('admin_logged_in', None) |
| flash("Вы вышли из системы.", "info") |
| return redirect(url_for('sales_screen')) |
|
|
| @app.route('/api/held_bills', methods=['GET']) |
| def get_held_bills(): |
| bills = load_json_data('held_bills') |
| bills.sort(key=lambda x: x.get('timestamp', ''), reverse=True) |
| return jsonify(bills) |
|
|
| @app.route('/api/hold_bill', methods=['POST']) |
| def hold_bill(): |
| data = request.json |
| if not data or 'name' not in data or 'cart' not in data: |
| return jsonify({'success': False, 'message': 'Invalid data'}), 400 |
| |
| bills = load_json_data('held_bills') |
| new_bill = { |
| 'id': uuid.uuid4().hex, |
| 'name': data['name'], |
| 'cart': data['cart'], |
| 'timestamp': get_current_time().isoformat() |
| } |
| bills.append(new_bill) |
| save_json_data('held_bills', bills) |
| upload_db_to_hf('held_bills') |
| return jsonify({'success': True, 'bill': new_bill}) |
|
|
| @app.route('/api/restore_bill/<bill_id>', methods=['POST']) |
| def restore_bill(bill_id): |
| bills = load_json_data('held_bills') |
| bill_to_restore = find_item_by_field(bills, 'id', bill_id) |
| if not bill_to_restore: |
| return jsonify({'success': False, 'message': 'Bill not found'}), 404 |
| |
| remaining_bills = [b for b in bills if b.get('id') != bill_id] |
| save_json_data('held_bills', remaining_bills) |
| upload_db_to_hf('held_bills') |
| return jsonify({'success': True, 'bill': bill_to_restore}) |
|
|
| @app.route('/api/hold_bill/<bill_id>', methods=['DELETE']) |
| def delete_held_bill(bill_id): |
| bills = load_json_data('held_bills') |
| initial_len = len(bills) |
| bills = [b for b in bills if b.get('id') != bill_id] |
| if len(bills) < initial_len: |
| save_json_data('held_bills', bills) |
| upload_db_to_hf('held_bills') |
| return jsonify({'success': True}) |
| else: |
| return jsonify({'success': False, 'message': 'Bill not found'}), 404 |
|
|
| @app.route('/customers') |
| @admin_required |
| def customer_management(): |
| customers = load_json_data('customers') |
| customers.sort(key=lambda x: x.get('name', '').lower()) |
| html = BASE_TEMPLATE.replace('__TITLE__', "Клиенты").replace('__CONTENT__', CUSTOMERS_CONTENT).replace('__SCRIPTS__', '') |
| return render_template_string(html, customers=customers) |
|
|
| @app.route('/admin/customer', methods=['POST']) |
| @admin_required |
| def manage_customer(): |
| action = request.form.get('action') |
| customers = load_json_data('customers') |
| |
| if action == 'add': |
| name = request.form.get('name', '').strip() |
| phone = request.form.get('phone', '').strip().replace('+', '').replace(' ', '') |
| if name and phone: |
| if not find_item_by_field(customers, 'phone', phone): |
| new_customer = {'id': uuid.uuid4().hex, 'name': name, 'phone': phone} |
| customers.append(new_customer) |
| flash(f"Клиент '{name}' добавлен.", "success") |
| else: |
| flash(f"Клиент с номером {phone} уже существует.", "warning") |
| else: |
| flash("Имя и телефон обязательны.", "danger") |
| |
| elif action == 'delete': |
| customer_id = request.form.get('id') |
| initial_len = len(customers) |
| customers = [c for c in customers if c.get('id') != customer_id] |
| if len(customers) < initial_len: |
| flash("Клиент удален.", "success") |
| else: |
| flash("Клиент не найден.", "warning") |
|
|
| save_json_data('customers', customers) |
| upload_db_to_hf('customers') |
| return redirect(url_for('customer_management')) |
|
|
| @app.route('/api/customers/search') |
| def search_customers(): |
| query = request.args.get('q', '').lower() |
| if not query: |
| return jsonify([]) |
| customers = load_json_data('customers') |
| matches = [ |
| c for c in customers |
| if query in c.get('name', '').lower() or query in c.get('phone', '') |
| ] |
| return jsonify(matches[:10]) |
|
|
| @app.route('/api/customers/save', methods=['POST']) |
| def save_customer(): |
| data = request.json |
| name = data.get('name', '').strip() |
| phone = data.get('phone', '').strip() |
| if not name or not phone: |
| return jsonify({'success': False, 'message': 'Name and phone required'}), 400 |
|
|
| customers = load_json_data('customers') |
| existing_customer = find_item_by_field(customers, 'phone', phone) |
| if existing_customer: |
| existing_customer['name'] = name |
| else: |
| new_customer = {'id': uuid.uuid4().hex, 'name': name, 'phone': phone} |
| customers.append(new_customer) |
| |
| save_json_data('customers', customers) |
| upload_db_to_hf('customers') |
| return jsonify({'success': True}) |
| |
| BASE_TEMPLATE = """ |
| <!DOCTYPE html> |
| <html lang="ru" data-bs-theme="light"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>__TITLE__ - POS</title> |
| <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"> |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> |
| <style> |
| :root { --sidebar-width: 250px; } |
| body { background-color: #f8f9fa; } |
| .sidebar { position: fixed; top: 0; left: 0; width: var(--sidebar-width); height: 100vh; background-color: #343a40; padding-top: 1rem; } |
| .sidebar .nav-link { color: rgba(255,255,255,.75); } |
| .sidebar .nav-link:hover, .sidebar .nav-link.active { color: #fff; } |
| .main-content { margin-left: var(--sidebar-width); padding: 1.5rem; } |
| @media (max-width: 992px) { |
| .sidebar { transform: translateX(calc(-1 * var(--sidebar-width))); transition: transform 0.3s ease-in-out; z-index: 1040; } |
| .sidebar.active { transform: translateX(0); } |
| .main-content { margin-left: 0; } |
| } |
| [data-bs-theme="dark"] body { background-color: #212529; color: #dee2e6; } |
| [data-bs-theme="dark"] .card, [data-bs-theme="dark"] .modal-content, [data-bs-theme="dark"] .list-group-item, [data-bs-theme="dark"] .table, [data-bs-theme="dark"] .accordion-item { background-color: #343a40; } |
| [data-bs-theme="dark"] .accordion-button { background-color: #3e444a; color: #fff; } |
| [data-bs-theme="dark"] .accordion-button:not(.collapsed) { background-color: #495057;} |
| [data-bs-theme="dark"] .accordion-button::after { filter: invert(1) grayscale(100) brightness(200%); } |
| [data-bs-theme="dark"] .table-hover>tbody>tr:hover>* { color: var(--bs-table-hover-color); background-color: rgba(255, 255, 255, 0.075); } |
| [data-bs-theme="dark"] .text-dark { color: #dee2e6 !important; } |
| .product-card { cursor: pointer; } |
| .product-card:hover { border-color: var(--bs-primary); } |
| .payback-positive { color: var(--bs-success); } |
| .payback-negative { color: var(--bs-danger); } |
| .payback-zero { color: var(--bs-secondary); } |
| </style> |
| </head> |
| <body> |
| <nav class="sidebar"> |
| <div class="p-3 text-white"> |
| <a href="/" class="text-white text-decoration-none"><h4 class="fw-bold"><i class="fas fa-cash-register me-2"></i>POS System</h4></a> |
| </div> |
| <ul class="nav flex-column"> |
| <li class="nav-item"><a class="nav-link {% if request.endpoint == 'sales_screen' %}active{% endif %}" href="{{ url_for('sales_screen') }}"><i class="fas fa-fw fa-dollar-sign me-2"></i>Касса</a></li> |
| <li class="nav-item"><a class="nav-link {% if request.endpoint == 'inventory_management' %}active{% endif %}" href="{{ url_for('inventory_management') }}"><i class="fas fa-fw fa-boxes me-2"></i>Склад</a></li> |
| <li class="nav-item"><a class="nav-link {% if request.endpoint == 'transaction_history' %}active{% endif %}" href="{{ url_for('transaction_history') }}"><i class="fas fa-fw fa-history me-2"></i>Транзакции</a></li> |
| <li class="nav-item dropdown"> |
| <a class="nav-link dropdown-toggle {% if request.endpoint in ['reports', 'product_roi_report', 'employee_report', 'item_movement_report'] %}active{% endif %}" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> |
| <i class="fas fa-fw fa-chart-line me-2"></i>Отчеты |
| </a> |
| <ul class="dropdown-menu dropdown-menu-dark"> |
| <li><a class="dropdown-item" href="{{ url_for('reports') }}">Сводный отчет</a></li> |
| <li><a class="dropdown-item" href="{{ url_for('employee_report') }}">Отчет по сотрудникам</a></li> |
| <li><a class="dropdown-item" href="{{ url_for('item_movement_report') }}">Движение товаров</a></li> |
| <li><a class="dropdown-item" href="{{ url_for('product_roi_report') }}">Окупаемость товаров</a></li> |
| </ul> |
| </li> |
| <li class="nav-item"><a class="nav-link {% if request.endpoint == 'customer_management' %}active{% endif %}" href="{{ url_for('customer_management') }}"><i class="fas fa-fw fa-users me-2"></i>Клиенты</a></li> |
| <li class="nav-item"><a class="nav-link {% if request.endpoint in ['cashier_login', 'cashier_dashboard'] %}active{% endif %}" href="{{ url_for('cashier_login') }}"><i class="fas fa-fw fa-user-circle me-2"></i>Кабинет кассира</a></li> |
| <li class="nav-item"><a class="nav-link {% if request.endpoint in ['admin_panel', 'admin_shifts'] %}active{% endif %}" href="{{ url_for('admin_panel') }}"><i class="fas fa-fw fa-cogs me-2"></i>Админка</a></li> |
| |
| {% if not session.admin_logged_in %} |
| <li class="nav-item mt-3"><a class="nav-link text-warning" href="{{ url_for('admin_login') }}"><i class="fas fa-fw fa-user-shield me-2"></i>Войти как админ</a></li> |
| {% else %} |
| <li class="nav-item mt-3"><a class="nav-link text-warning" href="{{ url_for('admin_logout') }}"><i class="fas fa-fw fa-sign-out-alt me-2"></i>Выйти (Админ)</a></li> |
| {% endif %} |
| </ul> |
| <div class="mt-auto p-3 text-secondary small"> |
| © {{ get_current_time().year }}<br>{{ get_current_time().strftime('%Y-%m-%d %H:%M') }} |
| </div> |
| </nav> |
| |
| <div class="main-content"> |
| <header class="d-flex justify-content-between align-items-center mb-4"> |
| <button class="btn btn-dark d-lg-none" id="sidebar-toggle"><i class="fas fa-bars"></i></button> |
| <h2 class="h3 mb-0">__TITLE__</h2> |
| <div class="d-flex align-items-center"> |
| {% if not session.admin_logged_in %} |
| <a href="{{ url_for('admin_login') }}" class="btn btn-outline-primary btn-sm me-3"><i class="fas fa-user-shield me-1"></i>Войти как админ</a> |
| {% endif %} |
| <div id="theme-toggle" style="cursor: pointer;"><i class="fas fa-sun fa-lg"></i></div> |
| </div> |
| </header> |
| <main> |
| {% with messages = get_flashed_messages(with_categories=true) %} |
| {% if messages %} |
| {% for category, message in messages %} |
| <div class="alert alert-{{ category }} alert-dismissible fade show" role="alert"> |
| {{ message }} |
| <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> |
| </div> |
| {% endfor %} |
| {% endif %} |
| {% endwith %} |
| __CONTENT__ |
| </main> |
| </div> |
| |
| <div class="modal fade" id="receiptModal" tabindex="-1" aria-hidden="true"> |
| <div class="modal-dialog"> |
| <div class="modal-content"> |
| <div class="modal-header"> |
| <h5 class="modal-title">Готово</h5> |
| <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> |
| </div> |
| <div class="modal-body"> |
| <p>Накладная успешно сохранена.</p> |
| <div class="mb-3"> |
| <label for="whatsapp-phone" class="form-label">Отправить накладную на WhatsApp</label> |
| <div class="input-group"> |
| <span class="input-group-text">+7</span> |
| <input type="tel" class="form-control" id="whatsapp-phone" placeholder="7071234567"> |
| </div> |
| <div class="form-text">Введите номер без +7.</div> |
| </div> |
| <div class="mb-3"> |
| <label for="customer-search" class="form-label">Поиск клиента</label> |
| <input type="text" id="customer-search" class="form-control" placeholder="Начните вводить имя..."> |
| <div id="customer-search-results" class="list-group mt-1" style="max-height: 150px; overflow-y: auto;"></div> |
| </div> |
| <div class="form-check"> |
| <input class="form-check-input" type="checkbox" id="save-customer-checkbox"> |
| <label class="form-check-label" for="save-customer-checkbox">Сохранить/обновить клиента</label> |
| </div> |
| <div class="mb-3 mt-2" id="customer-name-container" style="display:none;"> |
| <label for="customer-name-input" class="form-label">Имя клиента</label> |
| <input type="text" class="form-control" id="customer-name-input"> |
| </div> |
| <input type="hidden" id="receipt-url"> |
| </div> |
| <div class="modal-footer"> |
| <a id="view-receipt-btn" href="#" target="_blank" class="btn btn-secondary">Посмотреть накладную</a> |
| <button type="button" id="send-whatsapp-btn" class="btn btn-success"><i class="fab fa-whatsapp"></i> Отправить</button> |
| </div> |
| </div> |
| </div> |
| </div> |
| |
| <div class="modal fade" id="variantSelectModal" tabindex="-1" aria-hidden="true"> |
| <div class="modal-dialog modal-lg"> |
| <div class="modal-content"> |
| <div class="modal-header"> |
| <h5 class="modal-title" id="variantSelectModalTitle">Выберите вариант</h5> |
| <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> |
| </div> |
| <div class="modal-body"> |
| <div id="variant-list" class="list-group"></div> |
| </div> |
| </div> |
| </div> |
| </div> |
| |
| <div class="modal fade" id="priceSelectModal" tabindex="-1" aria-hidden="true"> |
| <div class="modal-dialog"> |
| <div class="modal-content"> |
| <div class="modal-header"> |
| <h5 class="modal-title" id="priceSelectModalTitle">Выберите цену</h5> |
| <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> |
| </div> |
| <div class="modal-body"> |
| <div class="d-grid gap-3" id="price-options-container"> |
| </div> |
| </div> |
| </div> |
| </div> |
| </div> |
| |
| <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script> |
| <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script> |
| <script> |
| let receiptModal; |
| document.addEventListener('DOMContentLoaded', () => { |
| receiptModal = new bootstrap.Modal(document.getElementById('receiptModal')); |
| document.getElementById('sidebar-toggle')?.addEventListener('click', () => document.querySelector('.sidebar').classList.toggle('active')); |
| const themeToggle = document.getElementById('theme-toggle'); |
| const getStoredTheme = () => localStorage.getItem('theme'); |
| const setStoredTheme = theme => localStorage.setItem('theme', theme); |
| const getPreferredTheme = () => getStoredTheme() || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'); |
| const setTheme = theme => { |
| document.documentElement.setAttribute('data-bs-theme', theme); |
| themeToggle.innerHTML = theme === 'dark' ? '<i class="fas fa-moon fa-lg"></i>' : '<i class="fas fa-sun fa-lg"></i>'; |
| }; |
| setTheme(getPreferredTheme()); |
| themeToggle.addEventListener('click', () => { |
| const newTheme = getPreferredTheme() === 'light' ? 'dark' : 'light'; |
| setStoredTheme(newTheme); |
| setTheme(newTheme); |
| }); |
| |
| const receiptModalEl = document.getElementById('receiptModal'); |
| if (receiptModalEl) { |
| const saveCustomerCheckbox = document.getElementById('save-customer-checkbox'); |
| const customerNameContainer = document.getElementById('customer-name-container'); |
| const customerSearchInput = document.getElementById('customer-search'); |
| const customerSearchResults = document.getElementById('customer-search-results'); |
| const whatsappPhoneInput = document.getElementById('whatsapp-phone'); |
| const customerNameInput = document.getElementById('customer-name-input'); |
| const sendWhatsappBtn = document.getElementById('send-whatsapp-btn'); |
| |
| saveCustomerCheckbox.addEventListener('change', () => { |
| customerNameContainer.style.display = saveCustomerCheckbox.checked ? 'block' : 'none'; |
| }); |
| |
| let searchTimeout; |
| customerSearchInput.addEventListener('input', () => { |
| clearTimeout(searchTimeout); |
| const query = customerSearchInput.value.trim(); |
| if (query.length < 2) { |
| customerSearchResults.innerHTML = ''; |
| return; |
| } |
| searchTimeout = setTimeout(() => { |
| fetch(`/api/customers/search?q=${encodeURIComponent(query)}`) |
| .then(res => res.json()) |
| .then(customers => { |
| customerSearchResults.innerHTML = ''; |
| if (customers.length > 0) { |
| customers.forEach(customer => { |
| const item = document.createElement('a'); |
| item.href = '#'; |
| item.className = 'list-group-item list-group-item-action'; |
| item.textContent = `${customer.name} - ${customer.phone}`; |
| item.addEventListener('click', (e) => { |
| e.preventDefault(); |
| whatsappPhoneInput.value = customer.phone; |
| customerNameInput.value = customer.name; |
| customerSearchInput.value = customer.name; |
| customerSearchResults.innerHTML = ''; |
| }); |
| customerSearchResults.appendChild(item); |
| }); |
| } else { |
| customerSearchResults.innerHTML = '<div class="list-group-item">Клиенты не найдены.</div>'; |
| } |
| }); |
| }, 300); |
| }); |
| |
| sendWhatsappBtn.addEventListener('click', () => { |
| const phone = whatsappPhoneInput.value.replace(/\\D/g, ''); |
| const receiptUrl = document.getElementById('receipt-url').value; |
| if (!phone || !receiptUrl) { |
| alert('Введите номер телефона.'); |
| return; |
| } |
| const fullPhone = '7' + phone; |
| const message = encodeURIComponent(`Ваша накладная: ${receiptUrl}`); |
| window.open(`https://wa.me/${fullPhone}?text=${message}`, '_blank'); |
| |
| if (saveCustomerCheckbox.checked) { |
| const name = customerNameInput.value.trim(); |
| if (name && phone) { |
| fetch('/api/customers/save', { |
| method: 'POST', |
| headers: {'Content-Type': 'application/json'}, |
| body: JSON.stringify({name: name, phone: phone}) |
| }) |
| .then(res => res.json()) |
| .then(data => { |
| if (!data.success) console.error('Failed to save customer:', data.message); |
| }); |
| } |
| } |
| }); |
| |
| receiptModalEl.addEventListener('show.bs.modal', () => { |
| whatsappPhoneInput.value = ''; |
| customerSearchInput.value = ''; |
| customerNameInput.value = ''; |
| customerSearchResults.innerHTML = ''; |
| saveCustomerCheckbox.checked = false; |
| customerNameContainer.style.display = 'none'; |
| }); |
| } |
| }); |
| </script> |
| __SCRIPTS__ |
| </body> |
| </html> |
| """ |
|
|
| SALES_SCREEN_CONTENT = """ |
| <div class="row"> |
| <div class="col-lg-7 mb-4"> |
| <div class="card"> |
| <div class="card-header d-flex justify-content-between align-items-center"> |
| <h5 class="mb-0">Товары</h5> |
| <div> |
| <button id="custom-item-btn" class="btn btn-info btn-sm"><i class="fas fa-plus me-2"></i>Свой товар</button> |
| <button id="scan-btn" class="btn btn-primary btn-sm"><i class="fas fa-barcode me-2"></i>Сканировать</button> |
| </div> |
| </div> |
| <div class="card-body"> |
| <div id="scanner-container" class="mb-3" style="display: none; position: relative;"> |
| <div id="reader" style="width: 100%;"></div> |
| <div id="scanner-status" style="position: absolute; top: 10px; left: 10px; background: rgba(0,0,0,0.5); color: white; padding: 5px; border-radius: 5px; display: none;"></div> |
| <button id="stop-scan-btn" class="btn btn-danger btn-sm mt-2">Остановить</button> |
| </div> |
| <input type="text" id="product-search" class="form-control mb-3" placeholder="Поиск по названию или штрих-коду..."> |
| <div id="product-search-results" class="d-grid gap-2" style="display: none; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));"></div> |
| |
| <div id="product-accordion" class="accordion"> |
| {% for letter, products in grouped_inventory %} |
| <div class="accordion-item"> |
| <h2 class="accordion-header" id="heading-{{ letter }}"> |
| <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-{{ letter }}" aria-expanded="false" aria-controls="collapse-{{ letter }}"> |
| {{ letter }} |
| </button> |
| </h2> |
| <div id="collapse-{{ letter }}" class="accordion-collapse collapse" aria-labelledby="heading-{{ letter }}" data-bs-parent="#product-accordion"> |
| <div class="accordion-body d-grid gap-2" style="grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));"> |
| {% for p in products %} |
| <div class="card text-center product-card" data-barcode="{{ p.barcode }}"> |
| <div class="card-body p-2"> |
| <h6 class="card-title small mb-1">{{ p.name }}</h6> |
| <p class="card-text fw-bold mb-0"> |
| {% if p.variants|length > 1 %} |
| от {{ format_currency_py(p.variants|map(attribute='price_regular')|min) }} ₸ |
| {% elif p.variants|length == 1 %} |
| {{ format_currency_py(p.variants[0].get('price_regular', p.variants[0].get('price'))) }} ₸ |
| {% else %} |
| Нет в наличии |
| {% endif %} |
| </p> |
| </div> |
| </div> |
| {% endfor %} |
| </div> |
| </div> |
| </div> |
| {% endfor %} |
| </div> |
| </div> |
| </div> |
| </div> |
| <div class="col-lg-5"> |
| <div class="card"> |
| <div class="card-header"> |
| <div class="d-flex justify-content-between align-items-center"> |
| <h5 class="mb-0">Накладная</h5> |
| <div id="shift-controls"></div> |
| </div> |
| <div id="session-info" class="small text-muted mt-1"></div> |
| </div> |
| <div class="card-body"> |
| <div id="edit-mode-banner" class="alert alert-warning mb-2 p-2" style="display:none;"> |
| <strong>Режим редактирования:</strong> Накладная <span id="edit-tx-id-display"></span> |
| <button class="btn btn-sm btn-danger float-end py-0" onclick="window.location.href='/'">Отмена</button> |
| </div> |
| <div id="cart-items" class="list-group mb-3" style="max-height: 400px; overflow-y: auto;"></div> |
| <div class="mb-3"> |
| <div class="d-flex justify-content-between"><span>Подытог:</span><span id="cart-subtotal">0 ₸</span></div> |
| <div class="d-flex justify-content-between"><span>Доставка:</span><span id="cart-delivery">0 ₸</span></div> |
| <hr class="my-1"> |
| <div class="d-flex justify-content-between align-items-center h4"><span>Итого:</span><span id="cart-total">0 ₸</span></div> |
| </div> |
| <div class="btn-group w-100 mb-2"> |
| <button class="btn btn-outline-secondary btn-sm" id="add-delivery-btn"><i class="fas fa-truck"></i> Доставка</button> |
| <button class="btn btn-outline-secondary btn-sm" id="add-note-btn"><i class="fas fa-sticky-note"></i> Заметка</button> |
| </div> |
| <div class="d-grid gap-2" id="payment-buttons-container"> |
| <div class="btn-group"><button class="btn btn-success flex-grow-1" id="pay-cash-btn"><i class="fas fa-money-bill-wave me-2"></i>Наличные</button><button class="btn btn-info flex-grow-1" id="pay-card-btn"><i class="far fa-credit-card me-2"></i>Карта</button></div> |
| <div class="btn-group"> |
| <button class="btn btn-secondary" id="hold-bill-btn"><i class="fas fa-pause me-2"></i>Отложить накладную</button> |
| <button class="btn btn-secondary" id="list-held-bills-btn"><i class="fas fa-list me-2"></i>Отложенные <span id="held-bills-count" class="badge bg-primary ms-1" style="display:none;"></span></button> |
| </div> |
| <button class="btn btn-danger" id="clear-cart-btn">Очистить</button> |
| </div> |
| </div> |
| </div> |
| </div> |
| </div> |
| |
| <div class="modal fade" id="cashierLoginModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"> |
| <div class="modal-dialog modal-dialog-centered"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Вход для кассира</h5></div> |
| <div class="modal-body"> |
| <label for="cashier-pin-input" class="form-label">Введите ПИН-код</label> |
| <input type="password" id="cashier-pin-input" class="form-control form-control-lg text-center" inputmode="numeric" autofocus> |
| <div id="pin-error" class="text-danger mt-2"></div> |
| </div> |
| <div class="modal-footer"><button type="button" id="pin-submit-btn" class="btn btn-primary">Войти</button></div> |
| </div> |
| </div> |
| </div> |
| |
| <div class="modal fade" id="startShiftModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"> |
| <div class="modal-dialog modal-dialog-centered"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Начать смену</h5></div> |
| <div class="modal-body"> |
| <p>Кассир: <strong id="start-shift-cashier-name"></strong></p> |
| <label for="kassa-select-modal" class="form-label">Выберите кассу</label> |
| <select id="kassa-select-modal" class="form-select"> |
| <option value="">-- Выберите кассу --</option> |
| {% for k in kassas %}<option value="{{ k.id }}" data-name="{{ k.name }}">{{ k.name }}</option>{% endfor %} |
| </select> |
| </div> |
| <div class="modal-footer"> |
| <button type="button" id="logout-btn" class="btn btn-secondary me-auto">Сменить кассира</button> |
| <button type="button" id="start-shift-confirm-btn" class="btn btn-primary">Начать</button> |
| </div> |
| </div> |
| </div> |
| </div> |
| |
| <div class="modal fade" id="customItemModal" tabindex="-1"> |
| <div class="modal-dialog"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Товар без штрихкода</h5></div> |
| <form id="custom-item-form"> |
| <div class="modal-body"> |
| <div class="mb-3"><label class="form-label">Название (необязательно)</label><input type="text" id="custom-item-name" class="form-control" placeholder="Напр. 'Пакет'"></div> |
| <div class="mb-3"><label class="form-label">Цена за 1 шт.</label><input type="text" id="custom-item-price" class="form-control" inputmode="decimal" placeholder="0" required></div> |
| <div class="mb-3"><label class="form-label">Количество</label><input type="number" id="custom-item-qty" class="form-control" value="" placeholder="1" min="1" required></div> |
| </div> |
| <div class="modal-footer"><button type="submit" class="btn btn-primary">Добавить в накладную</button></div> |
| </form> |
| </div> |
| </div> |
| </div> |
| |
| <div class="modal fade" id="holdBillModal" tabindex="-1"> |
| <div class="modal-dialog"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Отложить накладную</h5></div> |
| <form id="hold-bill-form"> |
| <div class="modal-body"> |
| <label for="hold-bill-name" class="form-label">Название для этой накладной</label> |
| <input type="text" id="hold-bill-name" class="form-control" placeholder="Напр. 'Стол 5', 'Мария'" required> |
| </div> |
| <div class="modal-footer"><button type="submit" class="btn btn-primary">Отложить</button></div> |
| </form> |
| </div> |
| </div> |
| </div> |
| |
| <div class="modal fade" id="heldBillsListModal" tabindex="-1"> |
| <div class="modal-dialog modal-lg"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Отложенные накладные</h5></div> |
| <div class="modal-body"> |
| <div id="held-bills-list" class="list-group"> |
| </div> |
| </div> |
| </div> |
| </div> |
| </div> |
| """ |
|
|
| SALES_SCREEN_SCRIPTS = """ |
| <script> |
| document.addEventListener('DOMContentLoaded', () => { |
| const cart = {}; |
| let deliveryCost = 0; |
| let transactionNote = ''; |
| |
| const cartItemsEl = document.getElementById('cart-items'); |
| const cartSubtotalEl = document.getElementById('cart-subtotal'); |
| const cartDeliveryEl = document.getElementById('cart-delivery'); |
| const cartTotalEl = document.getElementById('cart-total'); |
| |
| let audioCtx; |
| let isScannerPaused = false; |
| |
| const variantSelectModal = new bootstrap.Modal(document.getElementById('variantSelectModal')); |
| const priceSelectModal = new bootstrap.Modal(document.getElementById('priceSelectModal')); |
| const cashierLoginModal = new bootstrap.Modal(document.getElementById('cashierLoginModal')); |
| const startShiftModal = new bootstrap.Modal(document.getElementById('startShiftModal')); |
| const customItemModal = new bootstrap.Modal(document.getElementById('customItemModal')); |
| const holdBillModal = new bootstrap.Modal(document.getElementById('holdBillModal')); |
| const heldBillsListModal = new bootstrap.Modal(document.getElementById('heldBillsListModal')); |
| const allProducts = {{ inventory|tojson|safe }}; |
| |
| const session = { |
| cashier: null, |
| kassa: null, |
| shift: null |
| }; |
| |
| const editTx = {{ edit_tx|tojson|safe if edit_tx else 'null' }}; |
| if (editTx) { |
| document.getElementById('edit-mode-banner').style.display = 'block'; |
| document.getElementById('edit-tx-id-display').textContent = editTx.id.substring(0,8); |
| editTx.items.forEach(item => { |
| let variantName = ''; |
| if (item.name.includes('(')) { |
| variantName = item.name.substring(item.name.indexOf('(')+1, item.name.lastIndexOf(')')); |
| } |
| cart[item.variant_id] = { |
| productId: item.product_id, |
| productName: item.name, |
| variantName: variantName, |
| price: String(item.price_at_sale).replace('.', ','), |
| quantity: item.quantity, |
| discount: String(item.discount_per_item || '0').replace('.', ','), |
| isCustom: item.is_custom || false |
| }; |
| }); |
| deliveryCost = parseFloat(editTx.delivery_cost || 0); |
| transactionNote = editTx.note || ''; |
| |
| const paymentContainer = document.getElementById('payment-buttons-container'); |
| paymentContainer.innerHTML = `<button class="btn btn-warning w-100 btn-lg mb-2" id="save-edit-btn"><i class="fas fa-save me-2"></i>Сохранить изменения</button>`; |
| document.getElementById('save-edit-btn').addEventListener('click', () => { |
| completeSale(editTx.payment_method, editTx.id); |
| }); |
| } |
| |
| function playBeep() { |
| if (!audioCtx) { |
| try { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); } |
| catch (e) { console.error("Web Audio API is not supported"); return; } |
| } |
| const oscillator = audioCtx.createOscillator(); |
| const gainNode = audioCtx.createGain(); |
| oscillator.connect(gainNode); |
| gainNode.connect(audioCtx.destination); |
| oscillator.type = 'sine'; |
| oscillator.frequency.setValueAtTime(880, audioCtx.currentTime); |
| gainNode.gain.setValueAtTime(0.5, audioCtx.currentTime); |
| gainNode.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + 0.15); |
| oscillator.start(audioCtx.currentTime); |
| oscillator.stop(audioCtx.currentTime + 0.15); |
| } |
| |
| function parseLocaleNumber(stringNumber) { |
| return parseFloat(String(stringNumber).replace(/\\s/g, '').replace(',', '.')) || 0; |
| } |
| |
| const formatCurrencyJS = (value) => { |
| try { |
| const number = parseFloat(String(value).replace(/\\s/g, '').replace(',', '.')); |
| if (isNaN(number)) return '0'; |
| return number.toLocaleString('ru-RU', {minimumFractionDigits: 0, maximumFractionDigits: 0}); |
| } catch (e) { |
| return '0'; |
| } |
| }; |
| |
| const updateCartView = () => { |
| cartItemsEl.innerHTML = ''; |
| let subtotal = 0; |
| if (Object.keys(cart).length === 0) { |
| cartItemsEl.innerHTML = '<p class="text-center text-muted">Корзина пуста</p>'; |
| } |
| for (const id in cart) { |
| const item = cart[id]; |
| subtotal += (parseLocaleNumber(item.price) - parseLocaleNumber(item.discount)) * item.quantity; |
| cartItemsEl.innerHTML += ` |
| <div class="list-group-item"> |
| <div class="d-flex justify-content-between align-items-start"> |
| <div> |
| <h6 class="mb-0 small">${item.productName} ${item.variantName && !item.isCustom && !item.productName.includes(item.variantName) ? '('+item.variantName+')' : ''}</h6> |
| <small>${formatCurrencyJS(item.price)} ₸</small> |
| </div> |
| <div class="d-flex align-items-center"> |
| <button class="btn btn-sm btn-outline-secondary cart-qty-btn" data-id="${id}" data-op="-1">-</button> |
| <input type="number" class="form-control form-control-sm text-center mx-1 cart-qty-input" data-id="${id}" value="${item.quantity}" style="width: 60px;" min="1"> |
| <button class="btn btn-sm btn-outline-secondary cart-qty-btn" data-id="${id}" data-op="1">+</button> |
| </div> |
| </div> |
| <div class="input-group input-group-sm mt-2"> |
| <span class="input-group-text">Скидка</span> |
| <input type="text" class="form-control cart-discount-input" data-id="${id}" value="${item.discount}" inputmode="decimal" placeholder="0"> |
| </div> |
| </div>`; |
| } |
| const total = subtotal + deliveryCost; |
| cartSubtotalEl.textContent = formatCurrencyJS(subtotal) + ' ₸'; |
| cartDeliveryEl.textContent = formatCurrencyJS(deliveryCost) + ' ₸'; |
| cartTotalEl.textContent = formatCurrencyJS(total) + ' ₸'; |
| }; |
| |
| const addToCart = (product, variant, price, priceType) => { |
| if (cart[variant.id]) { |
| cart[variant.id].quantity += 1; |
| } else { |
| cart[variant.id] = { |
| productId: product.id, |
| productName: product.name, |
| variantName: variant.option_value, |
| price: String(price).replace('.',','), |
| priceType: priceType, |
| quantity: 1, |
| discount: '0', |
| }; |
| } |
| playBeep(); |
| updateCartView(); |
| }; |
| |
| const showPriceSelector = (product, variant) => { |
| document.getElementById('priceSelectModalTitle').textContent = `${product.name} (${variant.option_value})`; |
| const container = document.getElementById('price-options-container'); |
| container.innerHTML = ''; |
| |
| const prices = [ |
| { type: 'Общая', value: variant.price_regular || variant.price }, |
| { type: 'Минимальная', value: variant.price_min }, |
| { type: 'Оптовая', value: variant.price_wholesale } |
| ]; |
| |
| prices.forEach(p => { |
| if (p.value !== undefined && p.value !== '0' && p.value !== '0.00' && p.value !== '') { |
| const btn = document.createElement('button'); |
| btn.type = 'button'; |
| btn.className = 'btn btn-primary btn-lg'; |
| btn.innerHTML = `${p.type} <br><strong>${formatCurrencyJS(p.value)} ₸</strong>`; |
| btn.onclick = () => { |
| addToCart(product, variant, p.value, p.type); |
| priceSelectModal.hide(); |
| }; |
| container.appendChild(btn); |
| } |
| }); |
| |
| if (container.innerHTML === '') { |
| addToCart(product, variant, variant.price_regular || variant.price || '0', 'Общая'); |
| } else { |
| priceSelectModal.show(); |
| } |
| }; |
| |
| const handleProductSelection = (product) => { |
| let activeVariants = product.variants; |
| if (!editTx) { |
| activeVariants = product.variants.filter(v => v.stock > 0); |
| } |
| if (activeVariants.length === 0) { |
| alert("У этого товара нет доступных вариантов."); |
| return; |
| } |
| if (activeVariants.length === 1) { |
| showPriceSelector(product, activeVariants[0]); |
| } else { |
| document.getElementById('variantSelectModalTitle').textContent = `Выберите вариант для "${product.name}"`; |
| const variantList = document.getElementById('variant-list'); |
| variantList.innerHTML = ''; |
| activeVariants.forEach(variant => { |
| const btn = document.createElement('button'); |
| btn.type = 'button'; |
| btn.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center'; |
| const imageUrl = variant.image_url ? `<img src="${variant.image_url}" class="img-thumbnail me-3" style="width: 50px; height: 50px; object-fit: cover;">` : '<div style="width: 50px; height: 50px;" class="me-3"></div>'; |
| btn.innerHTML = ` |
| <div class="d-flex align-items-center"> |
| ${imageUrl} |
| <div>${variant.option_value} - <strong>${formatCurrencyJS(variant.price_regular || variant.price)} ₸</strong></div> |
| </div> |
| <span class="badge bg-secondary">Остаток: ${variant.stock}</span>`; |
| btn.addEventListener('click', () => { |
| variantSelectModal.hide(); |
| showPriceSelector(product, variant); |
| }); |
| variantList.appendChild(btn); |
| }); |
| variantSelectModal.show(); |
| } |
| }; |
| |
| const fetchAndHandleProduct = (barcode) => { |
| fetch(`/api/product_by_barcode/${barcode}`) |
| .then(res => res.json()) |
| .then(data => { |
| if (data.success) handleProductSelection(data.product); |
| else alert(data.message); |
| }); |
| } |
| |
| const productsContainer = document.querySelector('.col-lg-7 .card .card-body'); |
| productsContainer.addEventListener('click', e => { |
| const card = e.target.closest('.product-card'); |
| if (card) { |
| fetchAndHandleProduct(card.dataset.barcode); |
| } |
| }); |
| |
| const updateCartItemQuantity = (id, newQuantity) => { |
| if (cart[id]) { |
| const qty = parseInt(newQuantity, 10); |
| if (!isNaN(qty) && qty > 0) { |
| cart[id].quantity = qty; |
| } else { |
| delete cart[id]; |
| } |
| updateCartView(); |
| } |
| }; |
| |
| cartItemsEl.addEventListener('click', e => { |
| if (e.target.classList.contains('cart-qty-btn')) { |
| const id = e.target.dataset.id; |
| const op = parseInt(e.target.dataset.op, 10); |
| if (cart[id]) { |
| let newQuantity = cart[id].quantity + op; |
| updateCartItemQuantity(id, newQuantity); |
| } |
| } |
| }); |
| |
| cartItemsEl.addEventListener('change', e => { |
| if (e.target.classList.contains('cart-qty-input')) { |
| const id = e.target.dataset.id; |
| updateCartItemQuantity(id, e.target.value); |
| } |
| if (e.target.classList.contains('cart-discount-input')) { |
| const id = e.target.dataset.id; |
| if (cart[id]) { |
| cart[id].discount = e.target.value; |
| updateCartView(); |
| } |
| } |
| }); |
| |
| if (document.getElementById('clear-cart-btn')) { |
| document.getElementById('clear-cart-btn').addEventListener('click', () => { |
| for(const id in cart) delete cart[id]; |
| deliveryCost = 0; |
| transactionNote = ''; |
| updateCartView(); |
| }); |
| } |
| |
| const productSearchInput = document.getElementById('product-search'); |
| const productAccordionEl = document.getElementById('product-accordion'); |
| const productSearchResultsEl = document.getElementById('product-search-results'); |
| |
| productSearchInput.addEventListener('input', e => { |
| const term = e.target.value.toLowerCase().trim(); |
| |
| if (term === '') { |
| productAccordionEl.style.display = ''; |
| productSearchResultsEl.style.display = 'none'; |
| productSearchResultsEl.innerHTML = ''; |
| document.querySelectorAll('#product-accordion .accordion-collapse.show').forEach(el => { |
| bootstrap.Collapse.getOrCreateInstance(el).hide(); |
| }); |
| return; |
| } |
| |
| productAccordionEl.style.display = 'none'; |
| productSearchResultsEl.style.display = 'grid'; |
| |
| const filtered = allProducts.filter(p => p.name.toLowerCase().includes(term) || p.barcode.toLowerCase().includes(term)); |
| |
| filtered.sort((a, b) => { |
| const aName = a.name.toLowerCase(); |
| const bName = b.name.toLowerCase(); |
| const aStarts = aName.startsWith(term); |
| const bStarts = bName.startsWith(term); |
| const aBarcode = a.barcode.toLowerCase() === term; |
| const bBarcode = b.barcode.toLowerCase() === term; |
| |
| if (aBarcode && !bBarcode) return -1; |
| if (!aBarcode && bBarcode) return 1; |
| if (aStarts && !bStarts) return -1; |
| if (!aStarts && bStarts) return 1; |
| |
| return aName.localeCompare(bName); |
| }); |
| |
| productSearchResultsEl.innerHTML = filtered.length > 0 ? filtered.map(p => { |
| let priceText = 'Нет в наличии'; |
| if (p.variants && p.variants.length > 0) { |
| const activeVariants = p.variants.filter(v => v.stock > 0); |
| if (activeVariants.length > 0 || editTx) { |
| let variantsToUse = editTx ? p.variants : activeVariants; |
| if (variantsToUse.length === 1) { |
| priceText = `${formatCurrencyJS(variantsToUse[0].price_regular || variantsToUse[0].price)} ₸`; |
| } else { |
| const prices = variantsToUse.map(v => parseFloat(v.price_regular || v.price)); |
| priceText = `от ${formatCurrencyJS(Math.min(...prices))} ₸`; |
| } |
| } |
| } |
| return ` |
| <div class="card text-center product-card" data-barcode="${p.barcode}"> |
| <div class="card-body p-2"> |
| <h6 class="card-title small mb-1">${p.name}</h6> |
| <p class="card-text fw-bold mb-0">${priceText}</p> |
| </div> |
| </div>`; |
| }).join('') : '<p class="text-muted text-center col-12">Товары не найдены.</p>'; |
| }); |
| |
| const completeSale = (paymentMethod, editTxId = null) => { |
| if (!editTxId && (!session.shift || !session.cashier || !session.kassa)) { |
| alert('Смена не активна. Начните смену, чтобы проводить продажи.'); |
| return; |
| } |
| if (Object.keys(cart).length === 0) { |
| alert('Корзина пуста!'); |
| return; |
| } |
| fetch('/api/complete_sale', { |
| method: 'POST', |
| headers: {'Content-Type': 'application/json'}, |
| body: JSON.stringify({ |
| cart: cart, |
| userId: session.cashier ? session.cashier.id : (editTx ? editTx.user_id : ''), |
| kassaId: session.kassa ? session.kassa.id : (editTx ? editTx.kassa_id : ''), |
| shiftId: session.shift ? session.shift.id : (editTx ? editTx.shift_id : ''), |
| paymentMethod: paymentMethod, |
| deliveryCost: deliveryCost, |
| note: transactionNote, |
| edit_tx_id: editTxId |
| }) |
| }) |
| .then(res => { |
| if (res.status === 401) { |
| return res.json().then(data => { |
| alert(data.message || 'Сессия недействительна. Пожалуйста, войдите снова.'); |
| handleLogout(); |
| return Promise.reject(new Error('Logout required')); |
| }); |
| } |
| return res.json(); |
| }) |
| .then(data => { |
| if (data.success) { |
| if (editTxId) { |
| window.location.href = data.receiptUrl; |
| return; |
| } |
| for(const id in cart) delete cart[id]; |
| deliveryCost = 0; |
| transactionNote = ''; |
| updateCartView(); |
| document.getElementById('receipt-url').value = data.receiptUrl; |
| document.getElementById('view-receipt-btn').href = data.receiptUrl; |
| receiptModal.show(); |
| } else { |
| alert(`Ошибка: ${data.message}`); |
| } |
| }) |
| .catch(err => { |
| if (err.message !== 'Logout required') { |
| alert(`Сетевая ошибка: ${err}`); |
| } |
| }); |
| }; |
| |
| if (document.getElementById('pay-cash-btn')) { |
| document.getElementById('pay-cash-btn').addEventListener('click', () => completeSale('cash')); |
| document.getElementById('pay-card-btn').addEventListener('click', () => completeSale('card')); |
| } |
| |
| const html5QrCode = new Html5Qrcode("reader"); |
| const scannerStatusEl = document.getElementById('scanner-status'); |
| |
| const onScanSuccess = (decodedText, decodedResult) => { |
| if (isScannerPaused) return; |
| isScannerPaused = true; |
| scannerStatusEl.textContent = 'Пауза...'; |
| scannerStatusEl.style.display = 'block'; |
| if (html5QrCode.getState() === 2) html5QrCode.pause(); |
| fetchAndHandleProduct(decodedText); |
| setTimeout(() => { |
| isScannerPaused = false; |
| scannerStatusEl.style.display = 'none'; |
| if (html5QrCode.getState() === 2) html5QrCode.resume(); |
| }, 1000); |
| }; |
| |
| const startScanner = () => { |
| document.getElementById('scanner-container').style.display = 'block'; |
| const config = { fps: 15, qrbox: { width: 300, height: 150 } }; |
| html5QrCode.start({ facingMode: "environment" }, config, onScanSuccess) |
| .catch(err => console.error("Scanner start error:", err)); |
| }; |
| |
| const stopScanner = () => { |
| if (html5QrCode.isScanning) { |
| html5QrCode.stop().then(() => { |
| document.getElementById('scanner-container').style.display = 'none'; |
| }).catch(err => console.error("Failed to stop scanner", err)); |
| } else { |
| document.getElementById('scanner-container').style.display = 'none'; |
| } |
| }; |
| |
| document.getElementById('scan-btn').addEventListener('click', startScanner); |
| document.getElementById('stop-scan-btn').addEventListener('click', stopScanner); |
| |
| const updateSessionUI = () => { |
| const sessionInfoEl = document.getElementById('session-info'); |
| const shiftControlsEl = document.getElementById('shift-controls'); |
| |
| if (session.shift) { |
| sessionInfoEl.innerHTML = `Кассир: <strong>${session.cashier.name}</strong> | Касса: <strong>${session.kassa.name}</strong>`; |
| shiftControlsEl.innerHTML = '<button id="end-shift-btn" class="btn btn-danger btn-sm">Закончить смену</button>'; |
| document.getElementById('end-shift-btn').addEventListener('click', handleEndShift); |
| } else if (session.cashier) { |
| sessionInfoEl.innerHTML = `Кассир: <strong>${session.cashier.name}</strong>. Смена не начата.`; |
| shiftControlsEl.innerHTML = '<button id="start-shift-btn" class="btn btn-success btn-sm">Начать смену</button>'; |
| document.getElementById('start-shift-btn').addEventListener('click', () => { |
| document.getElementById('start-shift-cashier-name').textContent = session.cashier.name; |
| startShiftModal.show(); |
| }); |
| } else { |
| sessionInfoEl.innerHTML = 'Нет активного кассира'; |
| shiftControlsEl.innerHTML = ''; |
| } |
| }; |
| |
| const handleLogin = (pin) => { |
| fetch('/api/verify_pin', { |
| method: 'POST', |
| headers: {'Content-Type': 'application/json'}, |
| body: JSON.stringify({pin: pin}) |
| }) |
| .then(res => res.json()) |
| .then(data => { |
| if (data.success) { |
| session.cashier = data.user; |
| localStorage.setItem('current_cashier', JSON.stringify(data.user)); |
| cashierLoginModal.hide(); |
| updateSessionUI(); |
| document.getElementById('start-shift-cashier-name').textContent = session.cashier.name; |
| startShiftModal.show(); |
| } else { |
| document.getElementById('pin-error').textContent = data.message; |
| } |
| }); |
| }; |
| |
| const handleLogout = () => { |
| session.cashier = null; |
| session.kassa = null; |
| session.shift = null; |
| localStorage.removeItem('current_cashier'); |
| localStorage.removeItem('current_kassa'); |
| localStorage.removeItem('current_shift'); |
| startShiftModal.hide(); |
| updateSessionUI(); |
| if (!editTx) cashierLoginModal.show(); |
| }; |
| |
| const handleStartShift = () => { |
| const kassaSelect = document.getElementById('kassa-select-modal'); |
| const kassaId = kassaSelect.value; |
| const kassaName = kassaSelect.options[kassaSelect.selectedIndex].dataset.name; |
| if (!kassaId) { alert('Выберите кассу'); return; } |
| |
| fetch('/api/shift/start', { |
| method: 'POST', |
| headers: {'Content-Type': 'application/json'}, |
| body: JSON.stringify({userId: session.cashier.id, kassaId: kassaId}) |
| }) |
| .then(res => { |
| if (res.status === 401) { |
| return res.json().then(data => { |
| alert(data.message || 'Сессия недействительна. Пожалуйста, войдите снова.'); |
| handleLogout(); |
| return Promise.reject(new Error('Logout required')); |
| }); |
| } |
| return res.json(); |
| }) |
| .then(data => { |
| if (data.success) { |
| session.kassa = {id: data.shift.kassa_id, name: data.shift.kassa_name}; |
| session.shift = data.shift; |
| localStorage.setItem('current_kassa', JSON.stringify(session.kassa)); |
| localStorage.setItem('current_shift', JSON.stringify(session.shift)); |
| startShiftModal.hide(); |
| updateSessionUI(); |
| } else { |
| alert(`Ошибка: ${data.message}`); |
| } |
| }) |
| .catch(err => { |
| if (err.message !== 'Logout required') { |
| alert(`Сетевая ошибка: ${err}`); |
| } |
| }); |
| }; |
| |
| const handleEndShift = () => { |
| if (!confirm('Вы уверены, что хотите закончить смену?')) return; |
| fetch('/api/shift/end', { |
| method: 'POST', |
| headers: {'Content-Type': 'application/json'}, |
| body: JSON.stringify({shiftId: session.shift.id}) |
| }) |
| .then(res => { |
| if (res.status === 401) { |
| return res.json().then(data => { |
| alert(data.message || 'Сессия недействительна. Пожалуйста, войдите снова.'); |
| handleLogout(); |
| return Promise.reject(new Error('Logout required')); |
| }); |
| } |
| return res.json(); |
| }) |
| .then(data => { |
| if (data.success) { |
| session.kassa = null; |
| session.shift = null; |
| localStorage.removeItem('current_kassa'); |
| localStorage.removeItem('current_shift'); |
| updateSessionUI(); |
| alert(data.message); |
| } else { |
| alert(`Ошибка: ${data.message}`); |
| } |
| }) |
| .catch(err => { |
| if (err.message !== 'Logout required') { |
| alert(`Сетевая ошибка: ${err}`); |
| } |
| }); |
| }; |
| |
| const initializeSession = () => { |
| const storedCashier = localStorage.getItem('current_cashier'); |
| const storedKassa = localStorage.getItem('current_kassa'); |
| const storedShift = localStorage.getItem('current_shift'); |
| |
| if (storedCashier) session.cashier = JSON.parse(storedCashier); |
| if (storedKassa) session.kassa = JSON.parse(storedKassa); |
| if (storedShift) session.shift = JSON.parse(storedShift); |
| |
| updateSessionUI(); |
| |
| if (!editTx) { |
| if (!session.cashier) { |
| cashierLoginModal.show(); |
| } else if (!session.shift) { |
| document.getElementById('start-shift-cashier-name').textContent = session.cashier.name; |
| startShiftModal.show(); |
| } |
| } |
| }; |
| |
| document.getElementById('pin-submit-btn').addEventListener('click', () => { |
| const pinInput = document.getElementById('cashier-pin-input'); |
| handleLogin(pinInput.value); |
| pinInput.value = ''; |
| }); |
| document.getElementById('cashier-pin-input').addEventListener('keypress', (e) => { if(e.key === 'Enter') handleLogin(e.target.value); }); |
| document.getElementById('start-shift-confirm-btn').addEventListener('click', handleStartShift); |
| document.getElementById('logout-btn').addEventListener('click', handleLogout); |
| |
| document.getElementById('custom-item-btn').addEventListener('click', () => customItemModal.show()); |
| document.getElementById('custom-item-form').addEventListener('submit', (e) => { |
| e.preventDefault(); |
| const name = document.getElementById('custom-item-name').value || 'Товар без штрихкода'; |
| const price = document.getElementById('custom-item-price').value; |
| const qty = parseInt(document.getElementById('custom-item-qty').value || 1); |
| |
| if (parseLocaleNumber(price) > 0 && qty > 0) { |
| const customId = 'custom_' + Date.now(); |
| cart[customId] = { |
| productName: name, |
| price: String(price).replace('.',','), |
| quantity: qty, |
| discount: '0', |
| isCustom: true |
| }; |
| updateCartView(); |
| customItemModal.hide(); |
| e.target.reset(); |
| } else { |
| alert('Введите корректную цену и количество.'); |
| } |
| }); |
| |
| document.getElementById('add-delivery-btn').addEventListener('click', () => { |
| const costStr = prompt('Введите стоимость доставки:', deliveryCost > 0 ? deliveryCost : ''); |
| if (costStr !== null) { |
| const cost = parseLocaleNumber(costStr); |
| deliveryCost = cost >= 0 ? cost : 0; |
| updateCartView(); |
| } |
| }); |
| |
| document.getElementById('add-note-btn').addEventListener('click', () => { |
| const noteStr = prompt('Введите примечание к накладной:', transactionNote); |
| if (noteStr !== null) { |
| transactionNote = noteStr; |
| alert(noteStr ? 'Заметка добавлена.' : 'Заметка удалена.'); |
| } |
| }); |
| |
| const updateHeldBillsCount = () => { |
| fetch('/api/held_bills') |
| .then(res => res.json()) |
| .then(data => { |
| const count = data.length; |
| const badge = document.getElementById('held-bills-count'); |
| if (badge) { |
| if (count > 0) { |
| badge.textContent = count; |
| badge.style.display = ''; |
| } else { |
| badge.style.display = 'none'; |
| } |
| } |
| }); |
| }; |
| |
| if (document.getElementById('hold-bill-btn')) { |
| document.getElementById('hold-bill-btn').addEventListener('click', () => { |
| if (Object.keys(cart).length === 0) { |
| alert('Корзина пуста. Нечего откладывать.'); |
| return; |
| } |
| document.getElementById('hold-bill-form').reset(); |
| holdBillModal.show(); |
| }); |
| } |
| |
| document.getElementById('hold-bill-form').addEventListener('submit', (e) => { |
| e.preventDefault(); |
| const name = document.getElementById('hold-bill-name').value.trim(); |
| if (!name) return; |
| |
| fetch('/api/hold_bill', { |
| method: 'POST', |
| headers: {'Content-Type': 'application/json'}, |
| body: JSON.stringify({ name: name, cart: cart }) |
| }) |
| .then(res => res.json()) |
| .then(data => { |
| if (data.success) { |
| for(const id in cart) delete cart[id]; |
| deliveryCost = 0; |
| transactionNote = ''; |
| updateCartView(); |
| updateHeldBillsCount(); |
| holdBillModal.hide(); |
| } else { |
| alert('Ошибка: ' + data.message); |
| } |
| }); |
| }); |
| |
| if (document.getElementById('list-held-bills-btn')) { |
| document.getElementById('list-held-bills-btn').addEventListener('click', () => { |
| fetch('/api/held_bills') |
| .then(res => res.json()) |
| .then(bills => { |
| const listEl = document.getElementById('held-bills-list'); |
| listEl.innerHTML = ''; |
| if (bills.length === 0) { |
| listEl.innerHTML = '<p class="text-center text-muted">Нет отложенных накладных.</p>'; |
| } else { |
| bills.forEach(bill => { |
| listEl.innerHTML += ` |
| <div class="list-group-item d-flex justify-content-between align-items-center"> |
| <span><strong>${bill.name}</strong> - ${new Date(bill.timestamp).toLocaleTimeString('ru-RU')}</span> |
| <div> |
| <button class="btn btn-sm btn-success restore-bill-btn" data-id="${bill.id}">Восстановить</button> |
| <button class="btn btn-sm btn-danger delete-held-bill-btn ms-2" data-id="${bill.id}">Удалить</button> |
| </div> |
| </div>`; |
| }); |
| } |
| heldBillsListModal.show(); |
| }); |
| }); |
| } |
| |
| document.getElementById('held-bills-list').addEventListener('click', (e) => { |
| const billId = e.target.dataset.id; |
| if (!billId) return; |
| |
| if (e.target.classList.contains('restore-bill-btn')) { |
| if (Object.keys(cart).length > 0 && !confirm('Текущая корзина будет заменена. Продолжить?')) { |
| return; |
| } |
| fetch(`/api/restore_bill/${billId}`, { method: 'POST' }) |
| .then(res => res.json()) |
| .then(data => { |
| if (data.success) { |
| for(const id in cart) delete cart[id]; |
| deliveryCost = 0; |
| transactionNote = ''; |
| Object.assign(cart, data.bill.cart); |
| updateCartView(); |
| updateHeldBillsCount(); |
| heldBillsListModal.hide(); |
| } else { |
| alert('Ошибка: ' + data.message); |
| } |
| }); |
| } |
| |
| if (e.target.classList.contains('delete-held-bill-btn')) { |
| if (!confirm('Удалить эту отложенную накладную?')) return; |
| fetch(`/api/hold_bill/${billId}`, { method: 'DELETE' }) |
| .then(res => res.json()) |
| .then(data => { |
| if (data.success) { |
| e.target.closest('.list-group-item').remove(); |
| updateHeldBillsCount(); |
| if (document.getElementById('held-bills-list').children.length === 0) { |
| document.getElementById('held-bills-list').innerHTML = '<p class="text-center text-muted">Нет отложенных накладных.</p>'; |
| } |
| } else { |
| alert('Ошибка: ' + data.message); |
| } |
| }); |
| } |
| }); |
| |
| updateCartView(); |
| initializeSession(); |
| updateHeldBillsCount(); |
| }); |
| </script> |
| """ |
|
|
| INVENTORY_CONTENT = """ |
| <div class="row mb-4"> |
| <div class="col-md-3"> |
| <div class="card text-center"> |
| <div class="card-body"> |
| <h6 class="card-subtitle mb-2 text-muted">Наименований</h6> |
| <h4 class="card-title">{{ inventory_summary.total_names }} шт.</h4> |
| </div> |
| </div> |
| </div> |
| <div class="col-md-3"> |
| <div class="card text-center"> |
| <div class="card-body"> |
| <h6 class="card-subtitle mb-2 text-muted">Единиц товара на складе</h6> |
| <h4 class="card-title">{{ inventory_summary.total_units }} шт.</h4> |
| </div> |
| </div> |
| </div> |
| {% if session.admin_logged_in %} |
| <div class="col-md-3"> |
| <div class="card text-center"> |
| <div class="card-body"> |
| <h6 class="card-subtitle mb-2 text-muted">Сумма по себестоимости</h6> |
| <h4 class="card-title">{{ format_currency_py(inventory_summary.total_cost_value) }} ₸</h4> |
| </div> |
| </div> |
| </div> |
| <div class="col-md-3"> |
| <div class="card text-center"> |
| <div class="card-body"> |
| <h6 class="card-subtitle mb-2 text-muted">Потенциальная прибыль</h6> |
| <h4 class="card-title text-success">{{ format_currency_py(inventory_summary.potential_profit) }} ₸</h4> |
| </div> |
| </div> |
| </div> |
| {% endif %} |
| </div> |
| <div class="d-flex justify-content-between mb-3"> |
| <div> |
| <button class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#addProductModal"><i class="fas fa-plus me-2"></i>Добавить товар</button> |
| <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#stockInModal"><i class="fas fa-truck-loading me-2"></i>Оприходовать</button> |
| </div> |
| {% if session.admin_logged_in %} |
| <button class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#unpricedItemsModal"><i class="fas fa-exclamation-triangle me-2"></i>Невыставленные цены</button> |
| {% endif %} |
| </div> |
| |
| <div class="input-group mb-3"> |
| <input type="text" id="inventory-search" class="form-control" placeholder="Поиск по названию, варианту или штрих-коду..."> |
| <button type="button" class="btn btn-outline-secondary" id="inventory-scan-btn"><i class="fas fa-barcode"></i></button> |
| </div> |
| <div id="inventory-scanner-container" style="display:none;" class="mb-3"></div> |
| |
| <div class="accordion" id="inventoryAccordion"> |
| {% for p in inventory %} |
| <div class="accordion-item"> |
| <h2 class="accordion-header" id="heading-{{ p.id }}"> |
| <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-{{ p.id }}"> |
| <strong>{{ p.name }}</strong> <small class="text-muted"> ({{ p.barcode }})</small> |
| </button> |
| </h2> |
| <div id="collapse-{{ p.id }}" class="accordion-collapse collapse" data-bs-parent="#inventoryAccordion"> |
| <div class="accordion-body"> |
| {% if session.admin_logged_in %} |
| <div class="d-flex justify-content-end mb-2"> |
| <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editProductModal-{{ p.id }}"><i class="fas fa-edit me-1"></i>Редактировать товар</button> |
| <form action="{{ url_for('delete_product', product_id=p.id) }}" method="POST" class="d-inline ms-2" onsubmit="return confirm('Удалить товар?');"> |
| <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button> |
| </form> |
| </div> |
| {% endif %} |
| <table class="table table-sm table-bordered"> |
| <thead> |
| <tr> |
| <th>Фото</th> |
| <th>Вариант</th> |
| <th>Общая</th> |
| <th>Миним.</th> |
| <th>Опт.</th> |
| {% if session.admin_logged_in %}<th>Себест.</th>{% endif %} |
| <th>Остаток</th> |
| </tr> |
| </thead> |
| <tbody> |
| {% for v in p.variants %} |
| <tr> |
| <td><img src="{{ v.image_url if v.image_url else url_for('static', filename='placeholder.png') }}" class="img-thumbnail" style="width: 40px; height: 40px; object-fit: cover;"></td> |
| <td>{{ v.option_value }}</td> |
| <td>{{ format_currency_py(v.get('price_regular', v.get('price'))) }} ₸</td> |
| <td>{{ format_currency_py(v.get('price_min', '0')) }} ₸</td> |
| <td>{{ format_currency_py(v.get('price_wholesale', '0')) }} ₸</td> |
| {% if session.admin_logged_in %}<td>{{ format_currency_py(v.cost_price) }} ₸</td>{% endif %} |
| <td>{{ v.stock }}</td> |
| </tr> |
| {% else %} |
| <tr><td colspan="{% if session.admin_logged_in %}8{% else %}6{% endif %}" class="text-center text-muted">Нет вариантов</td></tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| </div> |
| {% endfor %} |
| </div> |
| |
| <div class="modal fade" id="addProductModal" tabindex="-1"> |
| <div class="modal-dialog modal-xl"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Новый товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div> |
| <form action="{{ url_for('inventory_management') }}" method="POST"> |
| <div class="modal-body"> |
| <div class="row"> |
| <div class="col-md-6 mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" required></div> |
| <div class="col-md-6 mb-3"><label class="form-label">Штрих-код</label> |
| <div class="input-group"><input type="text" name="barcode" class="form-control barcode-input" required><button type="button" class="btn btn-outline-secondary scan-modal-btn"><i class="fas fa-barcode"></i></button></div> |
| </div> |
| </div> |
| <div id="modal-scanner-add" class="mb-2" style="display:none;"></div> |
| <hr> |
| <h6>Варианты товара</h6> |
| <div id="variants-container-add"></div> |
| <button type="button" class="btn btn-sm btn-outline-success mt-2" id="add-variant-btn-add">Добавить вариант</button> |
| </div> |
| <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div> |
| </form> |
| </div> |
| </div> |
| </div> |
| |
| {% if session.admin_logged_in %} |
| {% for p in inventory %} |
| <div class="modal fade" id="editProductModal-{{ p.id }}" tabindex="-1"> |
| <div class="modal-dialog modal-xl"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Редактировать товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div> |
| <form action="{{ url_for('edit_product', product_id=p.id) }}" method="POST"> |
| <div class="modal-body"> |
| <div class="row"> |
| <div class="col-md-6 mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" value="{{ p.name }}" required></div> |
| <div class="col-md-6 mb-3"><label class="form-label">Штрих-код</label><input type="text" name="barcode" class="form-control" value="{{ p.barcode }}" required></div> |
| </div> |
| <hr> |
| <h6>Варианты товара</h6> |
| <div id="variants-container-edit-{{ p.id }}"> |
| {% for v in p.variants %} |
| <div class="card mb-3 variant-row"> |
| <div class="card-body"> |
| <input type="hidden" name="variant_id[]" value="{{ v.id }}"> |
| <div class="row g-2 align-items-center"> |
| <div class="col-12 col-md-3"> |
| <img src="{{ v.image_url if v.image_url else url_for('static', filename='placeholder.png') }}" class="img-thumbnail variant-preview mb-1" style="width: 80px; height: 80px; object-fit: cover;"> |
| <input type="file" class="form-control form-control-sm variant-image-upload" accept="image/*"> |
| <input type="hidden" class="variant-image-url-input" name="variant_image_url[]" value="{{ v.image_url }}"> |
| </div> |
| <div class="col-12 col-md-9"> |
| <div class="row g-2"> |
| <div class="col-12"><label>Название варианта</label><input type="text" name="variant_name[]" class="form-control" value="{{ v.option_value }}" required></div> |
| <div class="col-12 col-sm-4"><label>Цена Общая</label><input type="text" name="variant_price_regular[]" class="form-control" value="{{ v.get('price_regular', v.get('price'))|string|replace('.', ',') if v.get('price_regular', v.get('price')) != '0' else '' }}" placeholder="0" inputmode="decimal"></div> |
| <div class="col-12 col-sm-4"><label>Цена Мин.</label><input type="text" name="variant_price_min[]" class="form-control" value="{{ v.get('price_min', '0')|string|replace('.', ',') if v.get('price_min', '0') != '0' else '' }}" placeholder="0" inputmode="decimal"></div> |
| <div class="col-12 col-sm-4"><label>Цена Опт.</label><input type="text" name="variant_price_wholesale[]" class="form-control" value="{{ v.get('price_wholesale', '0')|string|replace('.', ',') if v.get('price_wholesale', '0') != '0' else '' }}" placeholder="0" inputmode="decimal"></div> |
| <div class="col-12 col-sm-6"><label>Себестоимость</label><input type="text" name="variant_cost_price[]" class="form-control" value="{{ v.cost_price|string|replace('.', ',') if v.cost_price != '0' else '' }}" placeholder="0" inputmode="decimal"></div> |
| <div class="col-12 col-sm-6"><label>Остаток</label><input type="number" name="variant_stock[]" class="form-control" value="{{ v.stock if v.stock != 0 else '' }}" placeholder="0"></div> |
| </div> |
| </div> |
| <div class="col-12 text-end"> |
| <button type="button" class="btn btn-sm btn-danger remove-variant-btn"><i class="fas fa-times"></i> Удалить вариант</button> |
| </div> |
| </div> |
| </div> |
| </div> |
| {% endfor %} |
| </div> |
| <button type="button" class="btn btn-sm btn-outline-success mt-2 add-variant-btn-edit" data-target-container="variants-container-edit-{{ p.id }}">Добавить вариант</button> |
| </div> |
| <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div> |
| </form> |
| </div> |
| </div> |
| </div> |
| {% endfor %} |
| |
| <div class="modal fade" id="unpricedItemsModal" tabindex="-1"> |
| <div class="modal-dialog modal-xl"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Товары без цен</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div> |
| <form action="{{ url_for('update_prices') }}" method="POST"> |
| <div class="modal-body"> |
| <input type="text" id="unpriced-search" class="form-control mb-3" placeholder="Поиск по названию..."> |
| <div class="table-responsive" style="max-height: 60vh;"> |
| <table class="table table-sm" id="unpriced-table"> |
| <thead><tr><th>Товар (Вариант)</th><th>Общая</th><th>Мин.</th><th>Опт.</th><th>Себест.</th></tr></thead> |
| <tbody> |
| {% for p in inventory %} |
| {% for v in p.variants %} |
| {% if v.get('price_regular', v.get('price', '0')) == '0' or v.get('price_regular', v.get('price', '0.00')) == '0.00' or v.cost_price == '0' or v.cost_price == '0.00' %} |
| <tr> |
| <td class="align-middle">{{ p.name }} ({{ v.option_value }})</td> |
| <td><input type="text" name="price_regular[]" class="form-control form-control-sm" value="" placeholder="0" inputmode="decimal"></td> |
| <td><input type="text" name="price_min[]" class="form-control form-control-sm" value="" placeholder="0" inputmode="decimal"></td> |
| <td><input type="text" name="price_wholesale[]" class="form-control form-control-sm" value="" placeholder="0" inputmode="decimal"></td> |
| <td> |
| <input type="text" name="cost_price[]" class="form-control form-control-sm" value="" placeholder="0" inputmode="decimal"> |
| <input type="hidden" name="variant_id[]" value="{{ v.id }}"> |
| </td> |
| </tr> |
| {% endif %} |
| {% endfor %} |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить изменения</button></div> |
| </form> |
| </div> |
| </div> |
| </div> |
| {% endif %} |
| |
| <div class="modal fade" id="stockInModal" tabindex="-1" style="overflow-y: visible;"> |
| <div class="modal-dialog"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Оприходование товара</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div> |
| <form action="{{ url_for('stock_in') }}" method="POST"> |
| <div class="modal-body"> |
| <div class="mb-3" style="position: relative;"> |
| <label class="form-label">Товар (Поиск или Скан)</label> |
| <div class="input-group"> |
| <input type="text" id="stockin-search-input" class="form-control" placeholder="Название или штрихкод"> |
| <button type="button" class="btn btn-outline-secondary" id="stockin-scan-btn"><i class="fas fa-barcode"></i></button> |
| </div> |
| <div id="stockin-scanner-container" style="display:none;" class="mt-2"></div> |
| <div id="stockin-search-results" class="list-group mt-1" style="position:absolute; z-index:1000; width:100%; display:none; max-height:200px; overflow-y:auto; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"></div> |
| <input type="hidden" id="stockin-product" name="product_id" required> |
| </div> |
| <div class="mb-3"> |
| <label class="form-label">Выбранный товар</label> |
| <input type="text" id="stockin-selected-product-name" class="form-control bg-light" readonly disabled> |
| </div> |
| <div class="mb-3"> |
| <label for="stockin-variant" class="form-label">Вариант</label> |
| <select id="stockin-variant" name="variant_id" class="form-select" required disabled> |
| <option value="">-- Сначала выберите товар --</option> |
| </select> |
| </div> |
| <div class="row"> |
| <div class="col-md-{% if session.admin_logged_in %}6{% else %}12{% endif %} mb-3"> |
| <label for="stockin-quantity" class="form-label">Количество</label> |
| <input type="number" id="stockin-quantity" name="quantity" class="form-control" placeholder="1" required min="1"> |
| </div> |
| {% if session.admin_logged_in %} |
| <div class="col-md-6 mb-3"> |
| <label for="stockin-cost" class="form-label">Себестоимость (за ед.)</label> |
| <input type="text" id="stockin-cost" name="cost_price" class="form-control" inputmode="decimal" placeholder="0"> |
| </div> |
| {% endif %} |
| </div> |
| {% if session.admin_logged_in %} |
| <div class="mb-3"> |
| <label for="stockin-delivery" class="form-label">Стоимость доставки (общая)</label> |
| <input type="text" id="stockin-delivery" name="delivery_cost" class="form-control" inputmode="decimal" placeholder="0"> |
| <div class="form-text">Эта сумма будет добавлена в расходы как "Дорога" и учтена в себестоимости.</div> |
| </div> |
| {% endif %} |
| </div> |
| <div class="modal-footer"><button type="submit" class="btn btn-primary">Оприходовать</button></div> |
| </form> |
| </div> |
| </div> |
| </div> |
| """ |
|
|
| INVENTORY_SCRIPTS = """ |
| <script> |
| document.addEventListener('DOMContentLoaded', () => { |
| let currentScanner = null; |
| let currentScannerContainer = null; |
| const placeholderImg = "{{ url_for('static', filename='placeholder.png') }}"; |
| const inventoryData = {{ inventory|tojson|safe }}; |
| const isAdmin = {{ 'true' if session.admin_logged_in else 'false' }}; |
| |
| function startScannerFor(containerId, inputElement, callback) { |
| const scannerContainer = document.getElementById(containerId); |
| if (currentScanner) { |
| try { currentScanner.stop(); } catch(e) {} |
| currentScanner = null; |
| if(currentScannerContainer) currentScannerContainer.style.display = 'none'; |
| return; |
| } |
| scannerContainer.style.display = 'block'; |
| currentScannerContainer = scannerContainer; |
| const scannerId = containerId + '-reader'; |
| if(!document.getElementById(scannerId)) scannerContainer.innerHTML = `<div id="${scannerId}" style="width: 100%;"></div>`; |
| |
| const html5QrCode = new Html5Qrcode(scannerId); |
| currentScanner = html5QrCode; |
| html5QrCode.start({ facingMode: "environment" }, { fps: 10, qrbox: { width: 250, height: 250 } }, (decodedText) => { |
| if(inputElement) inputElement.value = decodedText; |
| try { html5QrCode.stop(); } catch(e) {} |
| currentScanner = null; |
| scannerContainer.style.display = 'none'; |
| if(callback) callback(decodedText); |
| }); |
| } |
| |
| document.querySelectorAll('.scan-modal-btn').forEach(btn => { |
| btn.addEventListener('click', e => { |
| const form = e.target.closest('form'); |
| const container = form.querySelector('[id^="modal-scanner-"]'); |
| const input = form.querySelector('.barcode-input'); |
| startScannerFor(container.id, input, null); |
| }); |
| }); |
| |
| const invScanBtn = document.getElementById('inventory-scan-btn'); |
| if (invScanBtn) { |
| invScanBtn.addEventListener('click', () => { |
| const input = document.getElementById('inventory-search'); |
| startScannerFor('inventory-scanner-container', input, (text) => { |
| input.dispatchEvent(new Event('input')); |
| }); |
| }); |
| } |
| |
| const stockinSearchInput = document.getElementById('stockin-search-input'); |
| const stockinSearchResults = document.getElementById('stockin-search-results'); |
| const stockinProductHidden = document.getElementById('stockin-product'); |
| const stockinProductName = document.getElementById('stockin-selected-product-name'); |
| const stockinVariantSelect = document.getElementById('stockin-variant'); |
| |
| function selectStockInProduct(product) { |
| stockinSearchInput.value = ''; |
| stockinSearchResults.style.display = 'none'; |
| stockinProductHidden.value = product.id; |
| stockinProductName.value = product.name; |
| |
| stockinVariantSelect.innerHTML = '<option value="">-- Выберите вариант --</option>'; |
| if (product.variants && product.variants.length > 0) { |
| product.variants.forEach(v => { |
| const option = document.createElement('option'); |
| option.value = v.id; |
| option.textContent = v.option_value; |
| stockinVariantSelect.appendChild(option); |
| }); |
| stockinVariantSelect.disabled = false; |
| } else { |
| stockinVariantSelect.disabled = true; |
| } |
| } |
| |
| if (stockinSearchInput) { |
| stockinSearchInput.addEventListener('input', e => { |
| const term = e.target.value.toLowerCase().trim(); |
| if (!term) { |
| stockinSearchResults.style.display = 'none'; |
| return; |
| } |
| const filtered = inventoryData.filter(p => p.name.toLowerCase().includes(term) || (p.barcode && p.barcode.toLowerCase().includes(term))); |
| stockinSearchResults.innerHTML = ''; |
| if (filtered.length > 0) { |
| filtered.forEach(p => { |
| const a = document.createElement('a'); |
| a.href = '#'; |
| a.className = 'list-group-item list-group-item-action'; |
| a.textContent = p.name + (p.barcode ? ' (' + p.barcode + ')' : ''); |
| a.addEventListener('click', (ev) => { |
| ev.preventDefault(); |
| selectStockInProduct(p); |
| }); |
| stockinSearchResults.appendChild(a); |
| }); |
| stockinSearchResults.style.display = 'block'; |
| } else { |
| stockinSearchResults.innerHTML = '<div class="list-group-item text-muted">Не найдено</div>'; |
| stockinSearchResults.style.display = 'block'; |
| } |
| }); |
| |
| document.addEventListener('click', e => { |
| if (!stockinSearchInput.contains(e.target) && !stockinSearchResults.contains(e.target)) { |
| stockinSearchResults.style.display = 'none'; |
| } |
| }); |
| } |
| |
| const stockinScanBtn = document.getElementById('stockin-scan-btn'); |
| if (stockinScanBtn) { |
| stockinScanBtn.addEventListener('click', () => { |
| startScannerFor('stockin-scanner-container', stockinSearchInput, (text) => { |
| const found = inventoryData.find(p => p.barcode === text); |
| if (found) { |
| selectStockInProduct(found); |
| } else { |
| alert('Товар с таким штрихкодом не найден'); |
| } |
| }); |
| }); |
| } |
| |
| document.querySelectorAll('.modal').forEach(modal => { |
| modal.addEventListener('hidden.bs.modal', () => { |
| if (currentScanner) { |
| try { currentScanner.stop(); } catch(e) {} |
| currentScanner = null; |
| } |
| if(currentScannerContainer) { |
| currentScannerContainer.style.display = 'none'; |
| currentScannerContainer.innerHTML = ''; |
| } |
| }); |
| }); |
| |
| const handleImageUpload = (fileInput) => { |
| const file = fileInput.files[0]; |
| if (!file) return; |
| |
| const row = fileInput.closest('.variant-row'); |
| const preview = row.querySelector('.variant-preview'); |
| const urlInput = row.querySelector('.variant-image-url-input'); |
| |
| const formData = new FormData(); |
| formData.append('image', file); |
| |
| preview.src = "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="; |
| |
| fetch("{{ url_for('upload_image') }}", { |
| method: 'POST', |
| body: formData |
| }) |
| .then(response => response.json()) |
| .then(data => { |
| if (data.success) { |
| preview.src = data.url; |
| urlInput.value = data.url; |
| } else { |
| alert('Ошибка загрузки: ' + data.message); |
| preview.src = placeholderImg; |
| } |
| }) |
| .catch(error => { |
| console.error('Upload error:', error); |
| alert('Сетевая ошибка при загрузке изображения.'); |
| preview.src = placeholderImg; |
| }); |
| }; |
| |
| const createVariantRow = () => { |
| const div = document.createElement('div'); |
| div.className = 'card mb-3 variant-row'; |
| let adminInputs = ''; |
| if (isAdmin) { |
| adminInputs = ` |
| <div class="col-12 col-sm-4"><label>Цена Мин.</label><input type="text" name="variant_price_min[]" class="form-control" value="" placeholder="0" inputmode="decimal"></div> |
| <div class="col-12 col-sm-4"><label>Цена Опт.</label><input type="text" name="variant_price_wholesale[]" class="form-control" value="" placeholder="0" inputmode="decimal"></div> |
| <div class="col-12 col-sm-6"><label>Себестоимость</label><input type="text" name="variant_cost_price[]" class="form-control" value="" placeholder="0" inputmode="decimal"></div> |
| `; |
| } |
| div.innerHTML = ` |
| <div class="card-body"> |
| <input type="hidden" name="variant_id[]" value=""> |
| <div class="row g-2 align-items-center"> |
| <div class="col-12 col-md-3"> |
| <img src="${placeholderImg}" class="img-thumbnail variant-preview mb-1" style="width: 80px; height: 80px; object-fit: cover;"> |
| <input type="file" class="form-control form-control-sm variant-image-upload" accept="image/*"> |
| <input type="hidden" class="variant-image-url-input" name="variant_image_url[]" value=""> |
| </div> |
| <div class="col-12 col-md-9"> |
| <div class="row g-2"> |
| <div class="col-12"><label>Название варианта</label><input type="text" name="variant_name[]" class="form-control" placeholder="Напр. Синий, 42" required></div> |
| <div class="col-12 col-sm-4"><label>Цена Общая</label><input type="text" name="variant_price_regular[]" class="form-control" value="" placeholder="0" inputmode="decimal"></div> |
| ${adminInputs} |
| <div class="col-12 col-sm-6"><label>Остаток</label><input type="number" name="variant_stock[]" class="form-control" value="" placeholder="0"></div> |
| </div> |
| </div> |
| <div class="col-12 text-end"> |
| <button type="button" class="btn btn-sm btn-danger remove-variant-btn"><i class="fas fa-times"></i> Удалить вариант</button> |
| </div> |
| </div> |
| </div> |
| `; |
| return div; |
| }; |
| |
| document.body.addEventListener('change', e => { |
| if (e.target.classList.contains('variant-image-upload')) { |
| handleImageUpload(e.target); |
| } |
| }); |
| |
| document.body.addEventListener('click', e => { |
| if (e.target.closest('#add-variant-btn-add')) { |
| document.getElementById('variants-container-add').appendChild(createVariantRow()); |
| return; |
| } |
| |
| const editAddBtn = e.target.closest('.add-variant-btn-edit'); |
| if (editAddBtn) { |
| const containerId = editAddBtn.dataset.targetContainer; |
| document.getElementById(containerId).appendChild(createVariantRow()); |
| return; |
| } |
| |
| if (e.target.closest('.remove-variant-btn')) { |
| e.target.closest('.variant-row').remove(); |
| return; |
| } |
| }); |
| |
| const addProductModal = document.getElementById('addProductModal'); |
| if(addProductModal){ |
| addProductModal.addEventListener('shown.bs.modal', () => { |
| const container = document.getElementById('variants-container-add'); |
| if (container.children.length === 0) { |
| container.appendChild(createVariantRow()); |
| } |
| }); |
| } |
| |
| document.getElementById('inventory-search').addEventListener('input', e => { |
| const term = e.target.value.toLowerCase(); |
| document.querySelectorAll('#inventoryAccordion .accordion-item').forEach(item => { |
| const productName = item.querySelector('.accordion-button strong').textContent.toLowerCase(); |
| const barcode = item.querySelector('.accordion-button small').textContent.toLowerCase(); |
| const variantNameElements = item.querySelectorAll('.accordion-body table tbody tr td:nth-child(2)'); |
| const variantMatch = Array.from(variantNameElements).some(td => td.textContent.toLowerCase().includes(term)); |
| const show = productName.includes(term) || barcode.includes(term) || variantMatch; |
| item.style.display = show ? '' : 'none'; |
| }); |
| }); |
| |
| const unpricedSearch = document.getElementById('unpriced-search'); |
| if(unpricedSearch){ |
| unpricedSearch.addEventListener('input', e => { |
| const term = e.target.value.toLowerCase(); |
| document.querySelectorAll('#unpriced-table tbody tr').forEach(row => { |
| const text = row.cells[0].textContent.toLowerCase(); |
| row.style.display = text.includes(term) ? '' : 'none'; |
| }); |
| }); |
| } |
| }); |
| </script> |
| """ |
|
|
| TRANSACTIONS_CONTENT = """ |
| <div class="card mb-4"> |
| <div class="card-body"> |
| <form method="GET" class="row g-2 align-items-end"> |
| <div class="col-auto"> |
| <label for="date-filter" class="form-label">Дата</label> |
| <input type="date" id="date-filter" name="date" value="{{ selected_date }}" class="form-control"> |
| </div> |
| <div class="col-auto"> |
| <label for="kassa-filter" class="form-label">Касса</label> |
| <select id="kassa-filter" name="kassa" class="form-select"> |
| <option value="">Все кассы</option> |
| {% for k in kassas %} |
| <option value="{{ k.id }}" {% if k.id == selected_kassa_id %}selected{% endif %}>{{ k.name }}</option> |
| {% endfor %} |
| </select> |
| </div> |
| <div class="col-auto"> |
| <button type="submit" class="btn btn-primary">Показать</button> |
| </div> |
| </form> |
| <hr> |
| {% set selected_kassa = kassas|selectattr('id', 'equalto', selected_kassa_id)|first %} |
| <div class="d-flex justify-content-between align-items-center flex-wrap"> |
| <h4 class="mb-0">Общая выручка за {{ selected_date }}{% if selected_kassa %} (Касса: {{ selected_kassa.name }}){% endif %}: <span class="text-success">{{ format_currency_py(total_sales) }} ₸</span></h4> |
| <h5 class="mb-0 text-muted">Продано пар: <span class="fw-bold text-dark">{{ total_quantity_sold }}</span></h5> |
| </div> |
| </div> |
| </div> |
| <div class="card"> |
| <div class="card-body"> |
| <div class="table-responsive"> |
| <table class="table table-sm table-hover"> |
| <thead><tr><th>ID</th><th>Дата</th><th>Тип</th><th>Кассир</th><th>Касса</th><th>Сумма</th><th>Статус</th><th>Позиции</th><th></th></tr></thead> |
| <tbody> |
| {% for t in transactions %} |
| <tr class="{% if t.type == 'return' %}table-danger{% endif %}"> |
| <td><a href="{{ url_for('view_receipt', transaction_id=t.id) if t.invoice_html or t.receipt_html else '#' }}" target="_blank"><small class="text-muted">{{ t.id[:8] }}</small></a></td> |
| <td>{{ t.timestamp[11:16] }}</td> |
| <td> |
| {% if t.type == 'sale' %} |
| {% set display_type = 'Наличные' if t.payment_method == 'cash' else 'Карта' %} |
| {% set badge_class = 'primary' if t.payment_method == 'cash' else 'info' %} |
| {% elif t.type == 'return' %} |
| {% set display_type = 'Возврат' %} |
| {% set badge_class = 'danger' %} |
| {% endif %} |
| <span class="badge bg-{{ badge_class }}">{{ display_type }}</span> |
| </td> |
| <td>{{ t.user_name }}</td><td>{{ t.kassa_name }}</td> |
| <td class="fw-bold">{{ format_currency_py(t.total_amount) }} ₸</td> |
| <td> |
| {% if t.status == 'completed' %}<span class="badge bg-success">Завершено</span> |
| {% elif t.status == 'returned' %}<span class="badge bg-danger">Возвращено</span> |
| {% elif t.status == 'partially_returned' %}<span class="badge bg-warning text-dark">Частичный возврат</span> |
| {% else %}<span class="badge bg-secondary">{{t.status}}</span> |
| {% endif %} |
| </td> |
| <td> |
| <ul class="list-unstyled mb-0 small"> |
| {% for item in t['items'] %}<li>{{ item.name }} ({{ item.quantity }}x{{ format_currency_py(item.price_at_sale) }}{% if item.get('discount_per_item', '0')|float > 0 %} -{{ format_currency_py(item.discount_per_item) }}{% endif %})</li>{% endfor %} |
| </ul> |
| </td> |
| <td> |
| {% if session.admin_logged_in %} |
| <form action="{{ url_for('delete_transaction', transaction_id=t.id) }}" method="POST" class="d-inline ms-1" onsubmit="return confirm('Удалить эту транзакцию? Действие необратимо.');"> |
| <button type="submit" class="btn btn-xs btn-outline-danger py-0 px-1"><i class="fas fa-trash"></i></button> |
| </form> |
| {% endif %} |
| </td> |
| </tr> |
| {% else %} |
| <tr><td colspan="9" class="text-center">Нет транзакций за выбранную дату.</td></tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| </div> |
| """ |
|
|
| TRANSACTIONS_SCRIPTS = "" |
|
|
| REPORTS_CONTENT = """ |
| <div class="card mb-4"> |
| <div class="card-body"> |
| <form method="GET" action="{{ url_for('reports') }}"> |
| <div class="row g-2 align-items-end"> |
| <div class="col-md-4"><label for="start_date" class="form-label">Начало периода</label><input type="date" id="start_date" name="start_date" value="{{ start_date }}" class="form-control"></div> |
| <div class="col-md-4"><label for="end_date" class="form-label">Конец периода</label><input type="date" id="end_date" name="end_date" value="{{ end_date }}" class="form-control"></div> |
| <div class="col-md-4"><button type="submit" class="btn btn-primary w-100">Сформировать отчет</button></div> |
| </div> |
| </form> |
| </div> |
| </div> |
| |
| <div class="row"> |
| <div class="col-lg-7"> |
| <div class="card mb-4"> |
| <div class="card-header"><h5 class="mb-0">Сводный отчет за период</h5></div> |
| <div class="card-body"> |
| <ul class="list-group list-group-flush"> |
| <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-chart-bar me-2 text-primary"></i>Выручка (за вычетом возвратов)</span> <strong>{{ format_currency_py(stats.total_revenue) }} ₸</strong></li> |
| <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-undo me-2 text-danger"></i>Возвраты ({{ stats.total_returns_count }} шт.)</span> <strong class="text-danger">-{{ format_currency_py(stats.total_returns_amount) }} ₸</strong></li> |
| <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-cogs me-2 text-secondary"></i>Себестоимость проданных товаров</span> <strong>{{ format_currency_py(stats.total_cogs) }} ₸</strong></li> |
| <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-piggy-bank me-2 text-info"></i>Валовая прибыль</span> <strong class="text-info">{{ format_currency_py(stats.gross_profit) }} ₸</strong></li> |
| <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-receipt me-2 text-warning"></i>Расходы (операционные)</span> <strong class="text-warning">-{{ format_currency_py(stats.total_expenses) }} ₸</strong></li> |
| <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-user-tie me-2" style="color: orange;"></i>Расходы (личные)</span> <strong class="text-warning">-{{ format_currency_py(stats.total_personal_expenses) }} ₸</strong></li> |
| <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-users-cog me-2 text-danger"></i>Расходы (зарплаты)</span> <strong class="text-danger">-{{ format_currency_py(stats.total_salary_expenses) }} ₸</strong></li> |
| <li class="list-group-item d-flex justify-content-between fs-5"><span><i class="fas fa-check-circle me-2 text-success"></i>Чистая прибыль</span> <strong class="text-success">{{ format_currency_py(stats.net_profit) }} ₸</strong></li> |
| </ul> |
| </div> |
| </div> |
| <div class="card mb-4"> |
| <div class="card-header"><h5 class="mb-0">Расчеты с кассирами за период</h5></div> |
| <div class="card-body p-0"> |
| <div class="table-responsive"><table class="table table-sm mb-0"> |
| <thead><tr><th>Кассир</th><th class="text-end">К выплате</th></tr></thead> |
| <tbody> |
| {% for name, payout in stats.cashier_payouts %} |
| <tr><td>{{ name }}</td><td class="text-end">{{ format_currency_py(payout) }} ₸</td></tr> |
| {% else %}<tr><td colspan="2" class="text-center text-muted">Нет данных для расчета.</td></tr> |
| {% endfor %} |
| </tbody> |
| </table></div> |
| </div> |
| </div> |
| </div> |
| <div class="col-lg-5"> |
| <div class="card mb-4"> |
| <div class="card-header"><h5 class="mb-0">Продажи по кассирам</h5></div> |
| <div class="card-body p-0"> |
| <div class="table-responsive"><table class="table table-hover mb-0"> |
| <thead><tr><th>Кассир</th><th>Чеков</th><th class="text-end">Сумма</th></tr></thead> |
| <tbody> |
| {% for name, data in stats.sales_by_cashier %} |
| <tr><td>{{ name }}</td><td>{{ data.count }}</td><td class="text-end">{{ format_currency_py(data.total) }} ₸</td></tr> |
| {% else %}<tr><td colspan="3" class="text-center text-muted">Нет продаж за выбранный период.</td></tr> |
| {% endfor %} |
| </tbody> |
| </table></div> |
| </div> |
| </div> |
| <div class="card mb-4"> |
| <div class="card-header"><h5 class="mb-0">Операционные расходы за период</h5></div> |
| <div class="card-body p-0"> |
| <div class="table-responsive" style="max-height: 200px; overflow-y: auto;"><table class="table table-sm mb-0"> |
| <thead><tr><th>Дата</th><th>Описание</th><th class="text-end">Сумма</th></tr></thead> |
| <tbody> |
| {% for expense in expenses %} |
| <tr> |
| <td><small>{{ expense.timestamp[:10] }}</small></td> |
| <td>{{ expense.description }}</td> |
| <td class="text-end">{{ format_currency_py(expense.amount) }} ₸</td> |
| </tr> |
| {% else %}<tr><td colspan="3" class="text-center text-muted">Нет расходов за выбранный период.</td></tr> |
| {% endfor %} |
| </tbody> |
| </table></div> |
| </div> |
| </div> |
| <div class="card mb-4"> |
| <div class="card-header"><h5 class="mb-0">Личные расходы за период</h5></div> |
| <div class="card-body p-0"> |
| <div class="table-responsive" style="max-height: 200px; overflow-y: auto;"><table class="table table-sm mb-0"> |
| <thead><tr><th>Дата</th><th>Описание</th><th class="text-end">Сумма</th></tr></thead> |
| <tbody> |
| {% for expense in personal_expenses %} |
| <tr> |
| <td><small>{{ expense.timestamp[:10] }}</small></td> |
| <td>{{ expense.description }}</td> |
| <td class="text-end">{{ format_currency_py(expense.amount) }} ₸</td> |
| </tr> |
| {% else %}<tr><td colspan="3" class="text-center text-muted">Нет личных расходов за выбранный период.</td></tr> |
| {% endfor %} |
| </tbody> |
| </table></div> |
| </div> |
| </div> |
| </div> |
| </div> |
| """ |
|
|
| REPORTS_SCRIPTS = "" |
|
|
| EMPLOYEE_REPORT_CONTENT = """ |
| <div class="card mb-4"> |
| <div class="card-body"> |
| <form method="GET" action="{{ url_for('employee_report') }}"> |
| <div class="row g-2 align-items-end"> |
| <div class="col-md-3"><label class="form-label">Начало периода</label><input type="date" name="start_date" value="{{ start_date }}" class="form-control"></div> |
| <div class="col-md-3"><label class="form-label">Конец периода</label><input type="date" name="end_date" value="{{ end_date }}" class="form-control"></div> |
| <div class="col-md-4"> |
| <label class="form-label">Сотрудник</label> |
| <select name="user_id" class="form-select"> |
| <option value="">-- Выберите кассира --</option> |
| {% for u in users %} |
| <option value="{{ u.id }}" {% if u.id == selected_user %}selected{% endif %}>{{ u.name }}</option> |
| {% endfor %} |
| </select> |
| </div> |
| <div class="col-md-2"><button type="submit" class="btn btn-primary w-100">Показать</button></div> |
| </div> |
| </form> |
| </div> |
| </div> |
| |
| {% if selected_user %} |
| <div class="row mb-4"> |
| <div class="col-md-4"> |
| <div class="card text-center bg-light"> |
| <div class="card-body"> |
| <h6 class="card-subtitle mb-2 text-muted">Продажи</h6> |
| <h4 class="card-title text-success">{{ format_currency_py(totals.sales) }} ₸</h4> |
| </div> |
| </div> |
| </div> |
| <div class="col-md-4"> |
| <div class="card text-center bg-light"> |
| <div class="card-body"> |
| <h6 class="card-subtitle mb-2 text-muted">Возвраты</h6> |
| <h4 class="card-title text-danger">-{{ format_currency_py(totals.returns) }} ₸</h4> |
| </div> |
| </div> |
| </div> |
| <div class="col-md-4"> |
| <div class="card text-center bg-light"> |
| <div class="card-body"> |
| <h6 class="card-subtitle mb-2 text-muted">Итоговая выручка</h6> |
| <h4 class="card-title text-primary">{{ format_currency_py(totals.net) }} ₸</h4> |
| </div> |
| </div> |
| </div> |
| </div> |
| |
| <div class="card"> |
| <div class="card-header"><h5 class="mb-0">Детализация операций</h5></div> |
| <div class="card-body p-0"> |
| <div class="table-responsive"> |
| <table class="table table-hover table-sm mb-0"> |
| <thead class="table-light"> |
| <tr> |
| <th>Дата/Время</th> |
| <th>Тип</th> |
| <th>Чек</th> |
| <th>Метод</th> |
| <th>Позиции (Товар, Кол-во, Цена)</th> |
| <th class="text-end">Сумма</th> |
| </tr> |
| </thead> |
| <tbody> |
| {% for t in transactions %} |
| <tr class="{% if t.type == 'return' %}table-danger{% endif %}"> |
| <td>{{ t.timestamp[:16]|replace('T', ' ') }}</td> |
| <td><span class="badge bg-{{ 'primary' if t.type == 'sale' else 'danger' }}">{{ 'Продажа' if t.type == 'sale' else 'Возврат' }}</span></td> |
| <td><a href="{{ url_for('view_receipt', transaction_id=t.id) if t.invoice_html or t.receipt_html else '#' }}" target="_blank">{{ t.id[:8] }}</a></td> |
| <td>{{ 'Наличные' if t.payment_method == 'cash' else 'Карта' }}</td> |
| <td> |
| <ul class="list-unstyled mb-0 small"> |
| {% for item in t.items %} |
| <li>{{ item.name }} × {{ item.quantity }} шт. ({{ format_currency_py(item.price_at_sale) }} ₸/шт.)</li> |
| {% endfor %} |
| </ul> |
| </td> |
| <td class="text-end fw-bold">{{ format_currency_py(t.total_amount) }} ₸</td> |
| </tr> |
| {% else %} |
| <tr><td colspan="6" class="text-center">Нет операций за выбранный период.</td></tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| </div> |
| {% else %} |
| <div class="alert alert-info">Выберите сотрудника и период для формирования детального отчета.</div> |
| {% endif %} |
| """ |
|
|
| ITEM_MOVEMENT_CONTENT = """ |
| <div class="card mb-4"> |
| <div class="card-body"> |
| <form method="GET" action="{{ url_for('item_movement_report') }}" id="movement-form"> |
| <div class="row g-2 align-items-end"> |
| <div class="col-md-5" style="position: relative;"> |
| <label class="form-label">Товар</label> |
| <input type="text" id="movement-search" class="form-control" placeholder="Поиск по названию или штрихкоду" value="{{ selected_product.name if selected_product else '' }}"> |
| <div id="movement-search-results" class="list-group mt-1" style="position:absolute; z-index:1000; width:100%; display:none; max-height:250px; overflow-y:auto; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"></div> |
| <input type="hidden" id="movement-product-id" name="product_id" value="{{ product_id }}"> |
| </div> |
| <div class="col-md-5"> |
| <label class="form-label">Вариант</label> |
| <select id="movement-variant-id" name="variant_id" class="form-select"> |
| <option value="">Все варианты</option> |
| {% if selected_product %} |
| {% for v in selected_product.variants %} |
| <option value="{{ v.id }}" {% if variant_id == v.id %}selected{% endif %}>{{ v.option_value }}</option> |
| {% endfor %} |
| {% endif %} |
| </select> |
| </div> |
| <div class="col-md-2"> |
| <button type="submit" class="btn btn-primary w-100">Показать</button> |
| </div> |
| </div> |
| </form> |
| </div> |
| </div> |
| |
| {% if product_id %} |
| <div class="card"> |
| <div class="card-header"><h5 class="mb-0">История движения: {{ selected_product.name }} {% if selected_variant %}({{ selected_variant.option_value }}){% endif %}</h5></div> |
| <div class="card-body p-0"> |
| <div class="table-responsive"> |
| <table class="table table-hover table-sm mb-0"> |
| <thead class="table-light"> |
| <tr> |
| <th>Дата/Время</th> |
| <th>Операция</th> |
| <th>Вариант</th> |
| <th>Документ/Чек</th> |
| <th>Исполнитель</th> |
| <th class="text-end">Цена/Себест.</th> |
| <th class="text-end">Изменение остатка</th> |
| </tr> |
| </thead> |
| <tbody> |
| {% for m in movements %} |
| <tr> |
| <td>{{ m.timestamp[:16]|replace('T', ' ') }}</td> |
| <td> |
| {% if m.type == 'sale' %}<span class="badge bg-primary">Продажа</span> |
| {% elif m.type == 'return' %}<span class="badge bg-danger">Возврат от пок.</span> |
| {% elif m.type == 'stock_in' %}<span class="badge bg-success">Оприходование</span> |
| {% else %}<span class="badge bg-secondary">{{ m.type }}</span>{% endif %} |
| </td> |
| <td>{{ m.variant_name }}</td> |
| <td>{{ m.doc_id }}</td> |
| <td>{{ m.user }}</td> |
| <td class="text-end">{{ format_currency_py(m.price) }} ₸</td> |
| <td class="text-end fw-bold {% if m.qty > 0 %}text-success{% elif m.qty < 0 %}text-danger{% endif %}"> |
| {{ '+' if m.qty > 0 else '' }}{{ m.qty }} |
| </td> |
| </tr> |
| {% else %} |
| <tr><td colspan="7" class="text-center">Нет данных о движении для выбранного товара.</td></tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| </div> |
| {% else %} |
| <div class="alert alert-info">Выберите товар для просмотра истории его движения.</div> |
| {% endif %} |
| """ |
|
|
| ITEM_MOVEMENT_SCRIPTS = """ |
| <script> |
| document.addEventListener('DOMContentLoaded', () => { |
| const inventoryData = {{ inventory|tojson|safe }}; |
| const searchInput = document.getElementById('movement-search'); |
| const searchResults = document.getElementById('movement-search-results'); |
| const productIdInput = document.getElementById('movement-product-id'); |
| const variantSelect = document.getElementById('movement-variant-id'); |
| |
| if (searchInput) { |
| searchInput.addEventListener('input', e => { |
| const term = e.target.value.toLowerCase().trim(); |
| if (!term) { |
| searchResults.style.display = 'none'; |
| return; |
| } |
| const filtered = inventoryData.filter(p => p.name.toLowerCase().includes(term) || (p.barcode && p.barcode.toLowerCase().includes(term))); |
| searchResults.innerHTML = ''; |
| if (filtered.length > 0) { |
| filtered.forEach(p => { |
| const a = document.createElement('a'); |
| a.href = '#'; |
| a.className = 'list-group-item list-group-item-action'; |
| a.textContent = p.name + (p.barcode ? ' (' + p.barcode + ')' : ''); |
| a.addEventListener('click', (ev) => { |
| ev.preventDefault(); |
| searchInput.value = p.name; |
| productIdInput.value = p.id; |
| searchResults.style.display = 'none'; |
| |
| variantSelect.innerHTML = '<option value="">Все варианты</option>'; |
| if (p.variants) { |
| p.variants.forEach(v => { |
| const opt = document.createElement('option'); |
| opt.value = v.id; |
| opt.textContent = v.option_value; |
| variantSelect.appendChild(opt); |
| }); |
| } |
| }); |
| searchResults.appendChild(a); |
| }); |
| searchResults.style.display = 'block'; |
| } else { |
| searchResults.innerHTML = '<div class="list-group-item text-muted">Не найдено</div>'; |
| searchResults.style.display = 'block'; |
| } |
| }); |
| |
| document.addEventListener('click', e => { |
| if (!searchInput.contains(e.target) && !searchResults.contains(e.target)) { |
| searchResults.style.display = 'none'; |
| } |
| }); |
| } |
| }); |
| </script> |
| """ |
|
|
| PRODUCT_ROI_CONTENT = """ |
| <div class="card"> |
| <div class="card-header"><h5 class="mb-0">Окупаемость по товарам</h5></div> |
| <div class="card-body p-0"> |
| <div class="table-responsive"> |
| <table class="table table-hover table-sm mb-0"> |
| <thead class="table-light"> |
| <tr> |
| <th>Товар (вариант)</th> |
| <th class="text-end">Продано, шт</th> |
| <th class="text-end">Выручка</th> |
| <th class="text-end">Стоимость на складе</th> |
| <th class="text-end">Общие вложения</th> |
| <th class="text-end">Результат (Окупаемость)</th> |
| </tr> |
| </thead> |
| <tbody> |
| {% for item in stats %} |
| <tr> |
| <td><strong>{{ item.name }}</strong><br><small class="text-muted">{{ item.variant_name }}</small></td> |
| <td class="text-end">{{ item.total_qty_sold }}</td> |
| <td class="text-end">{{ format_currency_py(item.total_revenue) }} ₸</td> |
| <td class="text-end">{{ format_currency_py(item.inventory_value) }} ₸</td> |
| <td class="text-end text-secondary">{{ format_currency_py(item.total_investment) }} ₸</td> |
| <td class="text-end fw-bold |
| {% if item.payback > 0 %}payback-positive |
| {% elif item.payback < 0 %}payback-negative |
| {% else %}payback-zero{% endif %}"> |
| {{ format_currency_py(item.payback) }} ₸ |
| </td> |
| </tr> |
| {% else %} |
| <tr><td colspan="6" class="text-center">Нет данных для анализа.</td></tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| <div class="card-footer small text-muted"> |
| <i class="fas fa-info-circle me-1"></i> |
| <strong>Общие вложения</strong> = Себестоимость проданных товаров + Стоимость текущих остатков на складе. |
| <strong>Результат</strong> = Выручка - Общие вложения. |
| </div> |
| </div> |
| """ |
|
|
| ADMIN_CONTENT = """ |
| <div class="row"> |
| <div class="col-12 mb-4"> |
| <a href="{{ url_for('admin_shifts') }}" class="btn btn-info"><i class="fas fa-history me-2"></i>История смен кассиров</a> |
| </div> |
| <div class="col-md-6 mb-4"> |
| <div class="card h-100"> |
| <div class="card-header d-flex justify-content-between align-items-center"><h5 class="mb-0">Кассиры</h5><button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addUserModal"><i class="fas fa-plus"></i></button></div> |
| <div class="card-body"> |
| <ul class="list-group"> |
| {% for u in users %} |
| <li class="list-group-item d-flex justify-content-between align-items-center"> |
| <div>{{ u.name }} <br> |
| <small class="text-muted"> |
| {% if u.payment_type == 'salary' %}Зарплата: {{ format_currency_py(u.payment_value) }} ₸/мес. |
| {% elif u.payment_type == 'percentage' %}Процент: {{ u.payment_value }}% |
| {% endif %} |
| </small> |
| </div> |
| <div> |
| <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editUserModal-{{ u.id }}"><i class="fas fa-edit"></i></button> |
| <form action="{{ url_for('manage_user') }}" method="POST" class="d-inline" onsubmit="return confirm('Удалить кассира?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="{{ u.id }}"><button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button></form> |
| </div> |
| </li> |
| {% endfor %} |
| </ul> |
| </div> |
| </div> |
| </div> |
| <div class="col-md-6 mb-4"> |
| <div class="card h-100"> |
| <div class="card-header"><h5 class="mb-0">Кассы</h5></div> |
| <div class="card-body"> |
| <form action="{{ url_for('manage_kassa') }}" method="POST" class="mb-3"> |
| <input type="hidden" name="action" value="add"> |
| <div class="input-group"> |
| <input type="text" name="name" class="form-control" placeholder="Название кассы" required> |
| <input type="text" name="balance" class="form-control" placeholder="Начальный баланс" value="" inputmode="decimal"> |
| <button type="submit" class="btn btn-primary">Добавить</button> |
| </div> |
| </form> |
| <ul class="list-group"> |
| {% for k in kassas %} |
| <li class="list-group-item d-flex justify-content-between align-items-center"> |
| <div>{{ k.name }} <br><small class="fw-bold">{{ format_currency_py(k.balance) }} ₸</small></div> |
| <form action="{{ url_for('manage_kassa') }}" method="POST" onsubmit="return confirm('Удалить кассу?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="{{ k.id }}"><button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button></form> |
| </li> |
| {% endfor %} |
| </ul> |
| </div> |
| </div> |
| </div> |
| |
| <div class="col-12 mb-4"> |
| <div class="card"> |
| <div class="card-header"><h5 class="mb-0">Ссылки в накладных</h5></div> |
| <div class="card-body"> |
| <form action="{{ url_for('manage_link') }}" method="POST" class="mb-3"> |
| <input type="hidden" name="action" value="add"> |
| <div class="row g-2 align-items-end"> |
| <div class="col-md-5"><label class="form-label">Название (текст ссылки)</label><input type="text" name="name" class="form-control" placeholder="Напр: Наш Instagram" required></div> |
| <div class="col-md-5"><label class="form-label">URL (адрес)</label><input type="url" name="url" class="form-control" placeholder="https://..." required></div> |
| <div class="col-md-2"><button type="submit" class="btn btn-primary w-100">Добавить</button></div> |
| </div> |
| </form> |
| <ul class="list-group"> |
| {% for l in links %} |
| <li class="list-group-item d-flex justify-content-between align-items-center"> |
| <a href="{{ l.url }}" target="_blank">{{ l.name }}</a> |
| <form action="{{ url_for('manage_link') }}" method="POST" onsubmit="return confirm('Удалить ссылку?');"> |
| <input type="hidden" name="action" value="delete"> |
| <input type="hidden" name="id" value="{{ l.id }}"> |
| <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button> |
| </form> |
| </li> |
| {% endfor %} |
| </ul> |
| </div> |
| </div> |
| </div> |
| |
| <div class="col-12 mb-4"> |
| <div class="card"> |
| <div class="card-header"><h5 class="mb-0">Операции по кассе (Внесение/Изъятие)</h5></div> |
| <div class="card-body"> |
| <form action="{{ url_for('kassa_operation') }}" method="POST"> |
| <div class="row g-2 align-items-end"> |
| <div class="col-md-3"><label class="form-label">Касса</label><select name="kassa_id" class="form-select" required><option value="">-- Выберите --</option>{% for k in kassas %}<option value="{{k.id}}">{{k.name}}</option>{% endfor %}</select></div> |
| <div class="col-md-2"><label class="form-label">Операция</label><select name="op_type" class="form-select" required><option value="deposit">Внесение</option><option value="withdrawal">Изъятие</option></select></div> |
| <div class="col-md-2"><label class="form-label">Сумма</label><input type="text" name="amount" class="form-control" required inputmode="decimal" placeholder="0"></div> |
| <div class="col-md-3"><label class="form-label">Описание</label><input type="text" name="description" class="form-control"></div> |
| <div class="col-md-2"><button type="submit" class="btn btn-success w-100">Выполнить</button></div> |
| </div> |
| </form> |
| </div> |
| </div> |
| </div> |
| <div class="col-lg-6 mb-4"> |
| <div class="card h-100"> |
| <div class="card-header"><h5 class="mb-0">Учет расходов (операционные)</h5></div> |
| <div class="card-body d-flex flex-column"> |
| <form action="{{ url_for('manage_expense') }}" method="POST" class="mb-4"> |
| <div class="row g-2 align-items-end"> |
| <div class="col-md-4"><label class="form-label">Сумма</label><input type="text" name="amount" class="form-control" required inputmode="decimal" placeholder="0"></div> |
| <div class="col-md-8"><label class="form-label">Описание</label><input type="text" name="description" class="form-control" required placeholder="Напр: Аренда за май"></div> |
| <div class="col-12"><button type="submit" class="btn btn-warning w-100 mt-2">Добавить расход</button></div> |
| </div> |
| </form> |
| <h6>Все расходы:</h6> |
| <div class="table-responsive flex-grow-1" style="max-height: 400px; overflow-y: auto;"> |
| <table class="table table-sm table-striped"> |
| <thead><tr><th>Дата</th><th>Описание</th><th class="text-end">Сумма</th><th></th></tr></thead> |
| <tbody> |
| {% for e in expenses %} |
| <tr> |
| <td><small>{{ e.timestamp[:10] }}</small></td> |
| <td>{{ e.description }}</td> |
| <td class="text-end fw-bold">{{ format_currency_py(e.amount) }} ₸</td> |
| <td class="text-end"> |
| <form action="{{ url_for('delete_expense', expense_id=e.id) }}" method="POST" onsubmit="return confirm('Удалить этот расход?');"> |
| <button type="submit" class="btn btn-sm btn-outline-danger py-0 px-1"><i class="fas fa-trash"></i></button> |
| </form> |
| </td> |
| </tr> |
| {% else %} |
| <tr><td colspan="4" class="text-center">Расходов пока нет</td></tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| </div> |
| </div> |
| <div class="col-lg-6 mb-4"> |
| <div class="card h-100"> |
| <div class="card-header"><h5 class="mb-0">Учет расходов (личные)</h5></div> |
| <div class="card-body d-flex flex-column"> |
| <form action="{{ url_for('manage_personal_expense') }}" method="POST" class="mb-4"> |
| <div class="row g-2 align-items-end"> |
| <div class="col-md-4"><label class="form-label">Сумма</label><input type="text" name="amount" class="form-control" required inputmode="decimal" placeholder="0"></div> |
| <div class="col-md-8"><label class="form-label">Описание</label><input type="text" name="description" class="form-control" required placeholder="Напр: Обед"></div> |
| <div class="col-12"><button type="submit" class="btn btn-info w-100 mt-2">Добавить расход</button></div> |
| </div> |
| </form> |
| <h6>Все расходы:</h6> |
| <div class="table-responsive flex-grow-1" style="max-height: 400px; overflow-y: auto;"> |
| <table class="table table-sm table-striped"> |
| <thead><tr><th>Дата</th><th>Описание</th><th class="text-end">Сумма</th><th></th></tr></thead> |
| <tbody> |
| {% for e in personal_expenses %} |
| <tr> |
| <td><small>{{ e.timestamp[:10] }}</small></td> |
| <td>{{ e.description }}</td> |
| <td class="text-end fw-bold">{{ format_currency_py(e.amount) }} ₸</td> |
| <td class="text-end"> |
| <form action="{{ url_for('delete_personal_expense', expense_id=e.id) }}" method="POST" onsubmit="return confirm('Удалить этот расход?');"> |
| <button type="submit" class="btn btn-sm btn-outline-danger py-0 px-1"><i class="fas fa-trash"></i></button> |
| </form> |
| </td> |
| </tr> |
| {% else %} |
| <tr><td colspan="4" class="text-center">Расходов пока нет</td></tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| </div> |
| </div> |
| <div class="col-12"> |
| <div class="card"> |
| <div class="card-header"><h5 class="mb-0">Резервное копирование</h5></div> |
| <div class="card-body"> |
| <p>Данные периодически сохраняются в облако. Можно сделать это вручную.</p> |
| <form method="POST" action="{{ url_for('backup_hf') }}" class="d-inline-block me-2"> |
| <button type="submit" class="btn btn-outline-primary"><i class="fas fa-cloud-upload-alt me-2"></i>Сохранить в облако</button> |
| </form> |
| <form method="GET" action="{{ url_for('download_hf') }}" class="d-inline-block" onsubmit="return confirm('ВНИМАНИЕ! Это действие заменит все локальные данные данными из облака. Продолжить?');"> |
| <button type="submit" class="btn btn-outline-danger"><i class="fas fa-cloud-download-alt me-2"></i>Загрузить из облака</button> |
| </form> |
| </div> |
| </div> |
| </div> |
| </div> |
| |
| <div class="modal fade" id="addUserModal" tabindex="-1"> |
| <div class="modal-dialog"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Новый кассир</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div> |
| <form action="{{ url_for('manage_user') }}" method="POST"> |
| <input type="hidden" name="action" value="add"> |
| <div class="modal-body"> |
| <div class="mb-3"><label class="form-label">Имя</label><input type="text" name="name" class="form-control" required></div> |
| <div class="mb-3"><label class="form-label">ПИН-код</label><input type="password" name="pin" class="form-control" required></div> |
| <div class="mb-3"><label class="form-label">Тип оплаты</label><select name="payment_type" class="form-select"><option value="percentage">Процент от продаж</option><option value="salary">Фиксированная зарплата</option></select></div> |
| <div class="mb-3"><label class="form-label">Значение</label><input type="text" name="payment_value" class="form-control" inputmode="decimal" placeholder="0" required><small class="form-text text-muted">Для процентов - число (напр. 5), для зарплаты - сумма в тенге.</small></div> |
| </div> |
| <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div> |
| </form> |
| </div> |
| </div> |
| </div> |
| {% for u in users %} |
| <div class="modal fade" id="editUserModal-{{ u.id }}" tabindex="-1"> |
| <div class="modal-dialog"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Редактировать кассира</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div> |
| <form action="{{ url_for('manage_user') }}" method="POST"> |
| <input type="hidden" name="action" value="edit"> |
| <input type="hidden" name="id" value="{{ u.id }}"> |
| <div class="modal-body"> |
| <div class="mb-3"><label class="form-label">Имя</label><input type="text" name="name" value="{{ u.name }}" class="form-control" required></div> |
| <div class="mb-3"><label class="form-label">ПИН-код</label><input type="password" name="pin" value="{{ u.pin }}" class="form-control" required></div> |
| <div class="mb-3"><label class="form-label">Тип оплаты</label><select name="payment_type" class="form-select"> |
| <option value="percentage" {% if u.payment_type == 'percentage' %}selected{% endif %}>Процент от продаж</option> |
| <option value="salary" {% if u.payment_type == 'salary' %}selected{% endif %}>Фиксированная зарплата</option></select> |
| </div> |
| <div class="mb-3"><label class="form-label">Значение</label><input type="text" name="payment_value" class="form-control" value="{{ u.payment_value }}" inputmode="decimal" required></div> |
| </div> |
| <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div> |
| </form> |
| </div> |
| </div> |
| </div> |
| {% endfor %} |
| """ |
|
|
| ADMIN_SCRIPTS = "" |
|
|
| SHIFTS_CONTENT = """ |
| <div class="card"> |
| <div class="card-header"><h5 class="mb-0">История смен</h5></div> |
| <div class="card-body p-0"> |
| <div class="table-responsive"> |
| <table class="table table-hover table-sm mb-0"> |
| <thead class="table-light"> |
| <tr> |
| <th>Кассир</th> |
| <th>Касса</th> |
| <th>Начало смены</th> |
| <th>Конец смены</th> |
| <th class="text-end">Продажи (наличные)</th> |
| <th class="text-end">Продажи (карта)</th> |
| <th class="text-end">Итого продаж</th> |
| </tr> |
| </thead> |
| <tbody> |
| {% for s in shifts %} |
| <tr> |
| <td>{{ s.user_name }}</td> |
| <td>{{ s.kassa_name }}</td> |
| <td>{{ s.start_time[:16]|replace('T', ' ') }}</td> |
| <td>{{ (s.end_time[:16]|replace('T', ' ')) if s.end_time else '<span class="badge bg-success">Активна</span>' }}</td> |
| <td class="text-end">{{ format_currency_py(s.get('cash_sales', 0)) }} ₸</td> |
| <td class="text-end">{{ format_currency_py(s.get('card_sales', 0)) }} ₸</td> |
| <td class="text-end fw-bold">{{ format_currency_py(s.get('total_sales', 0)) }} ₸</td> |
| </tr> |
| {% else %} |
| <tr><td colspan="7" class="text-center">Нет данных о сменах.</td></tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| </div> |
| """ |
|
|
| ADMIN_LOGIN_CONTENT = """ |
| <div class="row justify-content-center mt-5"> |
| <div class="col-md-6 col-lg-4"> |
| <div class="card"> |
| <div class="card-body"> |
| <h4 class="card-title text-center">Вход для администратора</h4> |
| <form method="POST"> |
| <div class="mb-3"> |
| <label for="password" class="form-label">Пароль</label> |
| <input type="password" name="password" id="password" class="form-control" required autofocus> |
| </div> |
| <div class="d-grid"> |
| <button type="submit" class="btn btn-primary">Войти</button> |
| </div> |
| </form> |
| </div> |
| </div> |
| </div> |
| </div> |
| """ |
|
|
| CASHIER_LOGIN_CONTENT = """ |
| <div class="row justify-content-center"> |
| <div class="col-md-6 col-lg-4"> |
| <div class="card"> |
| <div class="card-body"> |
| <h4 class="card-title text-center">Вход для кассира</h4> |
| <form method="POST" action="{{ url_for('cashier_login') }}"> |
| <div class="mb-3"> |
| <label for="pin" class="form-label">Введите ваш ПИН-код</label> |
| <input type="password" name="pin" id="pin" class="form-control form-control-lg text-center" required autofocus> |
| </div> |
| <div class="d-grid"> |
| <button type="submit" class="btn btn-primary btn-lg">Войти</button> |
| </div> |
| </form> |
| </div> |
| </div> |
| </div> |
| </div> |
| """ |
|
|
| CASHIER_DASHBOARD_CONTENT = """ |
| <div class="card"> |
| <div class="card-body"> |
| <div class="table-responsive"> |
| <table class="table table-sm table-hover"> |
| <thead><tr><th>ID</th><th>Дата</th><th>Тип</th><th>Сумма</th><th>Статус</th><th>Действие</th></tr></thead> |
| <tbody> |
| {% for t in transactions %} |
| <tr class="{% if t.type == 'return' %}table-danger{% endif %}"> |
| <td><a href="{{ url_for('view_receipt', transaction_id=t.id) if t.invoice_html or t.receipt_html else '#' }}" target="_blank"><small class="text-muted">{{ t.id[:8] }}</small></a></td> |
| <td>{{ t.timestamp[:16]|replace('T', ' ') }}</td> |
| <td><span class="badge bg-{{'primary' if t.type == 'sale' else 'warning'}}">{{'Продажа' if t.type == 'sale' else 'Возврат'}}</span></td> |
| <td class="fw-bold">{{ format_currency_py(t.total_amount) }} ₸</td> |
| <td> |
| {% if t.status == 'completed' %}<span class="badge bg-success">Завершено</span> |
| {% elif t.status == 'returned' %}<span class="badge bg-danger">Возвращено</span> |
| {% elif t.status == 'partially_returned' %}<span class="badge bg-warning text-dark">Частичный возврат</span> |
| {% else %}<span class="badge bg-secondary">{{t.status}}</span> |
| {% endif %} |
| </td> |
| <td> |
| {% if t.type == 'sale' and t.status in ['completed', 'partially_returned'] %} |
| <a href="{{ url_for('return_transaction', transaction_id=t.id, cashier_id=user.id) }}" class="btn btn-sm btn-warning">Возврат</a> |
| {% endif %} |
| </td> |
| </tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| </div> |
| """ |
|
|
| RETURN_PAGE_CONTENT = """ |
| <div class="card"> |
| <div class="card-header"> |
| <h5 class="mb-0">Оформление возврата по накладной <a href="{{ url_for('view_receipt', transaction_id=transaction.id) }}" target="_blank">{{ transaction.id[:8] }}</a></h5> |
| </div> |
| <div class="card-body"> |
| <form method="POST" action="{{ url_for('return_transaction', transaction_id=transaction.id) }}"> |
| <input type="hidden" name="cashier_id" value="{{ cashier_id }}"> |
| <div class="table-responsive"> |
| <table class="table table-bordered"> |
| <thead> |
| <tr> |
| <th>Товар</th> |
| <th class="text-center">Цена за шт.</th> |
| <th class="text-center">Продано</th> |
| <th class="text-center">Вернуть (шт.)</th> |
| </tr> |
| </thead> |
| <tbody> |
| {% for item in items %} |
| <tr> |
| <td>{{ item.name }}</td> |
| <td class="text-center">{{ format_currency_py(item.price_at_sale) }} ₸</td> |
| <td class="text-center">{{ item.quantity }}</td> |
| <td> |
| <input type="number" name="return_qty_{{ item.variant_id }}" class="form-control" value="0" min="0" max="{{ item.max_returnable }}"> |
| <small class="form-text text-muted">Доступно: {{ item.max_returnable }} шт.</small> |
| </td> |
| </tr> |
| {% else %} |
| <tr> |
| <td colspan="4" class="text-center">Нет товаров, доступных для возврата.</td> |
| </tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| {% if items %} |
| <div class="mt-3 d-flex justify-content-end"> |
| <a href="{{ url_for('cashier_dashboard', user_id=cashier_id) }}" class="btn btn-secondary me-2">Отмена</a> |
| <button type="submit" class="btn btn-warning">Оформить возврат</button> |
| </div> |
| {% endif %} |
| </form> |
| </div> |
| </div> |
| """ |
|
|
| CUSTOMERS_CONTENT = """ |
| <div class="card"> |
| <div class="card-header d-flex justify-content-between align-items-center"> |
| <h5 class="mb-0">Клиенты</h5> |
| <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addCustomerModal"><i class="fas fa-plus me-2"></i>Добавить клиента</button> |
| </div> |
| <div class="card-body"> |
| <div class="table-responsive"> |
| <table class="table table-hover"> |
| <thead><tr><th>Имя</th><th>Телефон</th><th></th></tr></thead> |
| <tbody> |
| {% for c in customers %} |
| <tr> |
| <td>{{ c.name }}</td> |
| <td>{{ c.phone }}</td> |
| <td class="text-end"> |
| <form action="{{ url_for('manage_customer') }}" method="POST" onsubmit="return confirm('Удалить этого клиента?');"> |
| <input type="hidden" name="action" value="delete"> |
| <input type="hidden" name="id" value="{{ c.id }}"> |
| <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button> |
| </form> |
| </td> |
| </tr> |
| {% else %} |
| <tr><td colspan="3" class="text-center">Список клиентов пуст.</td></tr> |
| {% endfor %} |
| </tbody> |
| </table> |
| </div> |
| </div> |
| </div> |
| |
| <div class="modal fade" id="addCustomerModal" tabindex="-1"> |
| <div class="modal-dialog"> |
| <div class="modal-content"> |
| <div class="modal-header"><h5 class="modal-title">Новый клиент</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div> |
| <form action="{{ url_for('manage_customer') }}" method="POST"> |
| <input type="hidden" name="action" value="add"> |
| <div class="modal-body"> |
| <div class="mb-3"><label class="form-label">Имя</label><input type="text" name="name" class="form-control" required></div> |
| <div class="mb-3"><label class="form-label">Телефон</label><input type="tel" name="phone" class="form-control" placeholder="7071234567" required></div> |
| </div> |
| <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div> |
| </form> |
| </div> |
| </div> |
| </div> |
| """ |
|
|
| if __name__ == '__main__': |
| backup_thread = threading.Thread(target=periodic_backup, daemon=True) |
| backup_thread.start() |
| for key in DATA_FILES.keys(): |
| load_json_data(key) |
| app.run(debug=False, host='0.0.0.0', port=7860, use_reloader=False) |