Kgshop commited on
Commit
2e09903
·
verified ·
1 Parent(s): 0d23d17

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -149
app.py CHANGED
@@ -4,13 +4,14 @@ import os
4
  import logging
5
  import threading
6
  import time
7
- from datetime import datetime, date, timedelta
8
  import pytz
9
  from huggingface_hub import HfApi, hf_hub_download
10
  from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
11
  import uuid
12
  from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
13
  import functools
 
14
 
15
  app = Flask(__name__)
16
  app.secret_key = os.urandom(24)
@@ -127,8 +128,7 @@ def periodic_backup():
127
  except Exception as e:
128
  logging.error(f"Error during scheduled backup: {e}", exc_info=True)
129
 
130
- def find_item_by_field(file_key, field, value):
131
- data = load_json_data(file_key)
132
  for item in data:
133
  if isinstance(item, dict) and item.get(field) == value:
134
  return item
@@ -170,7 +170,7 @@ def inventory_management():
170
  return redirect(url_for('inventory_management'))
171
 
172
  inventory = load_json_data('inventory')
173
- if find_item_by_field('inventory', 'barcode', barcode):
174
  flash(f"Товар со штрих-кодом {barcode} уже существует.", "warning")
175
  return redirect(url_for('inventory_management'))
176
 
@@ -214,7 +214,7 @@ def edit_product(product_id):
214
  flash("Название, штрих-код и цена обязательны.", "danger")
215
  return redirect(url_for('inventory_management'))
216
 
217
- existing_barcode = find_item_by_field('inventory', 'barcode', barcode)
218
  if existing_barcode and existing_barcode.get('id') != product_id:
219
  flash(f"Штрих-код {barcode} уже используется другим товаром.", "warning")
220
  return redirect(url_for('inventory_management'))
@@ -256,7 +256,8 @@ def delete_product(product_id):
256
 
257
  @app.route('/api/product_by_barcode/<barcode>')
258
  def get_product_by_barcode(barcode):
259
- product = find_item_by_field('inventory', 'barcode', barcode)
 
260
  if product:
261
  if product.get('stock', 0) > 0:
262
  return jsonify({'success': True, 'product': product})
@@ -280,8 +281,8 @@ def complete_sale():
280
  users = load_json_data('users')
281
  kassas = load_json_data('kassas')
282
 
283
- user = find_item_by_field('users', 'id', user_id)
284
- kassa = find_item_by_field('kassas', 'id', kassa_id)
285
 
286
  if not user or not kassa:
287
  return jsonify({'success': False, 'message': 'Кассир или касса не найдены.'}), 404
@@ -291,7 +292,7 @@ def complete_sale():
291
  inventory_updates = {}
292
 
293
  for item_id, cart_item in cart.items():
294
- product = find_item_by_field('inventory', 'id', item_id)
295
  if not product:
296
  return jsonify({'success': False, 'message': f"Товар с ID {item_id} не найден."}), 404
297
 
@@ -381,96 +382,60 @@ def transaction_history():
381
  def reports():
382
  today = get_current_time().date()
383
  start_date_str = request.args.get('start_date', (today.replace(day=1)).strftime('%Y-%m-%d'))
384
- end_date_str = request.args.get('end_date', today.strftime('%Y-%m-%d'))
385
 
386
- try:
387
- start_date = datetime.strptime(start_date_str, '%Y-%m-%d').date()
388
- end_date = datetime.strptime(end_date_str, '%Y-%m-%d').date()
389
- except ValueError:
390
- flash("Неверный формат даты.", "danger")
391
- return redirect(url_for('reports'))
392
-
393
- all_transactions = load_json_data('transactions')
394
- all_expenses = load_json_data('expenses')
395
-
396
- filtered_transactions = []
397
- for t in all_transactions:
398
- t_date = datetime.fromisoformat(t['timestamp']).date()
399
- if start_date <= t_date <= end_date:
400
- filtered_transactions.append(t)
401
-
402
- filtered_expenses = []
403
- for e in all_expenses:
404
- e_date = datetime.fromisoformat(e['timestamp']).date()
405
- if start_date <= e_date <= end_date:
406
- filtered_expenses.append(e)
407
 
 
 
 
 
 
 
 
 
 
408
  total_revenue = sum(to_decimal(t['total_amount']) for t in filtered_transactions)
409
- 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'])
 
 
 
410
  gross_profit = total_revenue - total_cogs
411
  total_expenses = sum(to_decimal(e['amount']) for e in filtered_expenses)
412
  net_profit = gross_profit - total_expenses
413
 
414
- report_data = {
415
- "total_revenue": total_revenue,
416
- "total_cogs": total_cogs,
417
- "gross_profit": gross_profit,
418
- "total_expenses": total_expenses,
419
- "net_profit": net_profit,
420
- "filtered_transactions": sorted(filtered_transactions, key=lambda x: x['timestamp'], reverse=True),
421
- "filtered_expenses": sorted(filtered_expenses, key=lambda x: x['timestamp'], reverse=True)
 
 
 
 
 
422
  }
423
 
424
- html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS)
425
- return render_template_string(html, report_data=report_data, start_date=start_date_str, end_date=end_date_str)
426
 
427
- @app.route('/expenses', methods=['POST'])
428
- def add_expense():
429
- try:
430
- category = request.form.get('category', 'Прочее').strip()
431
- description = request.form.get('description', '').strip()
432
- amount = to_decimal(request.form.get('amount', '0'))
433
-
434
- if amount <= 0:
435
- flash("Сумма расхода должна быть положительной.", "danger")
436
- return redirect(url_for('reports'))
437
-
438
- new_expense = {
439
- 'id': uuid.uuid4().hex,
440
- 'timestamp': get_current_time().isoformat(),
441
- 'category': category,
442
- 'description': description,
443
- 'amount': str(amount)
444
- }
445
-
446
- expenses = load_json_data('expenses')
447
- expenses.append(new_expense)
448
- save_json_data('expenses', expenses)
449
- upload_db_to_hf('expenses')
450
- flash("Расход успешно добавлен.", "success")
451
- except Exception as e:
452
- flash(f"Ошибка при добавлении расхода: {e}", "danger")
453
- return redirect(url_for('reports'))
454
-
455
- @app.route('/expenses/delete/<expense_id>', methods=['POST'])
456
- def delete_expense(expense_id):
457
- expenses = load_json_data('expenses')
458
- initial_len = len(expenses)
459
- expenses = [e for e in expenses if not (isinstance(e, dict) and e.get('id') == expense_id)]
460
- if len(expenses) < initial_len:
461
- save_json_data('expenses', expenses)
462
- upload_db_to_hf('expenses')
463
- flash("Расход удален.", "success")
464
- else:
465
- flash("Расход не найден.", "warning")
466
- return redirect(url_for('reports'))
467
 
468
  @app.route('/admin', methods=['GET'])
469
  def admin_panel():
470
  users = load_json_data('users')
471
  kassas = load_json_data('kassas')
 
 
472
  html = BASE_TEMPLATE.replace('__TITLE__', "Админ-панель").replace('__CONTENT__', ADMIN_CONTENT).replace('__SCRIPTS__', ADMIN_SCRIPTS)
473
- return render_template_string(html, users=users, kassas=kassas)
474
 
475
  @app.route('/admin/user', methods=['POST'])
476
  def manage_user():
@@ -585,6 +550,28 @@ def kassa_operation():
585
  flash("Касса не найдена.", "danger")
586
 
587
  return redirect(url_for('admin_panel'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
588
 
589
  @app.route('/backup', methods=['POST'])
590
  def backup_hf():
@@ -639,7 +626,8 @@ BASE_TEMPLATE = """
639
  .main-content { margin-left: 0; }
640
  }
641
  [data-bs-theme="dark"] body { background-color: #212529; color: #dee2e6; }
642
- [data-bs-theme="dark"] .card { background-color: #343a40; }
 
643
  </style>
644
  </head>
645
  <body>
@@ -715,8 +703,9 @@ SALES_SCREEN_CONTENT = """
715
  <button id="scan-btn" class="btn btn-primary btn-sm"><i class="fas fa-barcode me-2"></i>Сканировать</button>
716
  </div>
717
  <div class="card-body">
718
- <div id="scanner-container" class="mb-3" style="display: none;">
719
  <div id="reader" style="width: 100%;"></div>
 
720
  <button id="stop-scan-btn" class="btn btn-danger btn-sm mt-2">Остановить</button>
721
  </div>
722
  <input type="text" id="product-search" class="form-control mb-3" placeholder="Поиск по названию или штрих-коду...">
@@ -764,7 +753,7 @@ document.addEventListener('DOMContentLoaded', () => {
764
  const cartItemsEl = document.getElementById('cart-items');
765
  const cartTotalEl = document.getElementById('cart-total');
766
  let audioCtx;
767
- const html5QrCode = new Html5Qrcode("reader");
768
 
769
  function playBeep() {
770
  if (!audioCtx) {
@@ -894,32 +883,49 @@ document.addEventListener('DOMContentLoaded', () => {
894
  document.getElementById('pay-cash-btn').addEventListener('click', () => completeSale('cash'));
895
  document.getElementById('pay-card-btn').addEventListener('click', () => completeSale('card'));
896
 
897
- const stopScanner = () => {
898
- html5QrCode.stop().then(() => {
899
- document.getElementById('scanner-container').style.display = 'none';
900
- }).catch(err => {
901
- console.warn("Scanner could not be stopped, it might not have been running.", err);
902
- document.getElementById('scanner-container').style.display = 'none';
903
- });
904
- };
905
-
906
  const onScanSuccess = (decodedText, decodedResult) => {
 
 
 
 
 
 
 
907
  fetch(`/api/product_by_barcode/${decodedText}`)
908
  .then(res => res.json())
909
  .then(data => {
910
- if (data.success) {
911
- addToCart(data.product);
912
- stopScanner();
913
- } else {
914
- alert(data.message);
915
- }
 
 
 
 
 
916
  });
917
  };
918
 
919
  const startScanner = () => {
920
  document.getElementById('scanner-container').style.display = 'block';
921
  const config = { fps: 10, qrbox: { width: 250, height: 250 } };
922
- html5QrCode.start({ facingMode: "environment" }, config, onScanSuccess);
 
 
 
 
 
 
 
 
 
 
 
923
  };
924
 
925
  document.getElementById('scan-btn').addEventListener('click', startScanner);
@@ -1080,8 +1086,8 @@ REPORTS_CONTENT = """
1080
  <div class="card-body">
1081
  <form method="GET" action="{{ url_for('reports') }}">
1082
  <div class="row g-2 align-items-end">
1083
- <div class="col-md-4"><label for="start_date" class="form-label">Начало периода</label><input type="date" id="start_date" name="start_date" class="form-control" value="{{ start_date }}"></div>
1084
- <div class="col-md-4"><label for="end_date" class="form-label">Конец периода</label><input type="date" id="end_date" name="end_date" class="form-control" value="{{ end_date }}"></div>
1085
  <div class="col-md-4"><button type="submit" class="btn btn-primary w-100">Сформировать отчет</button></div>
1086
  </div>
1087
  </form>
@@ -1089,42 +1095,34 @@ REPORTS_CONTENT = """
1089
  </div>
1090
 
1091
  <div class="row">
1092
- <div class="col-md-6 col-xl-3 mb-4"><div class="card"><div class="card-body"><h6 class="card-subtitle mb-2 text-muted">Выручка</h6><h4 class="card-title">{{ format_currency_py(report_data.total_revenue) }} с</h4></div></div></div>
1093
- <div class="col-md-6 col-xl-3 mb-4"><div class="card"><div class="card-body"><h6 class="card-subtitle mb-2 text-muted">Валовая прибыль</h6><h4 class="card-title">{{ format_currency_py(report_data.gross_profit) }} с</h4><small class="text-muted">Себестоимость: {{ format_currency_py(report_data.total_cogs) }} с</small></div></div></div>
1094
- <div class="col-md-6 col-xl-3 mb-4"><div class="card"><div class="card-body"><h6 class="card-subtitle mb-2 text-muted">Расходы</h6><h4 class="card-title text-danger">-{{ format_currency_py(report_data.total_expenses) }} с</h4></div></div></div>
1095
- <div class="col-md-6 col-xl-3 mb-4"><div class="card border-{{'success' if report_data.net_profit >= 0 else 'danger'}}"><div class="card-body"><h6 class="card-subtitle mb-2 text-muted">Чистая прибыль</h6><h4 class="card-title text-{{'success' if report_data.net_profit >= 0 else 'danger'}}">{{ format_currency_py(report_data.net_profit) }} с</h4></div></div></div>
1096
- </div>
1097
-
1098
- <div class="row">
1099
- <div class="col-lg-6 mb-4">
1100
- <div class="card h-100">
1101
- <div class="card-header"><h5 class="mb-0">Расходы за период</h5></div>
1102
  <div class="card-body">
1103
- <form action="{{ url_for('add_expense') }}" method="POST" class="mb-4">
1104
- <div class="row g-2 align-items-end">
1105
- <div class="col-4"><label class="form-label">Категория</label><input type="text" name="category" class="form-control" placeholder="Аренда"></div>
1106
- <div class="col-4"><label class="form-label">Описание</label><input type="text" name="description" class="form-control" placeholder="За май"></div>
1107
- <div class="col-2"><label class="form-label">Сумма</label><input type="text" name="amount" class="form-control" inputmode="decimal" required></div>
1108
- <div class="col-2"><button type="submit" class="btn btn-success w-100"><i class="fas fa-plus"></i></button></div>
1109
- </div>
1110
- </form>
 
 
 
 
1111
  <div class="table-responsive">
1112
- <table class="table table-sm">
1113
- <thead><tr><th>Дата</th><th>Категория</th><th>Сумма</th><th></th></tr></thead>
1114
  <tbody>
1115
- {% for e in report_data.filtered_expenses %}
1116
  <tr>
1117
- <td>{{ e.timestamp[:10] }}</td>
1118
- <td>{{ e.category }} <br><small class="text-muted">{{ e.description }}</small></td>
1119
- <td class="text-danger">-{{ format_currency_py(e.amount) }} с</td>
1120
- <td>
1121
- <form action="{{ url_for('delete_expense', expense_id=e.id) }}" method="POST" onsubmit="return confirm('Удалить расход?');">
1122
- <button type="submit" class="btn btn-sm btn-outline-danger py-0 px-1"><i class="fas fa-times"></i></button>
1123
- </form>
1124
- </td>
1125
  </tr>
1126
  {% else %}
1127
- <tr><td colspan="4" class="text-center text-muted">Расходов за период нет</td></tr>
1128
  {% endfor %}
1129
  </tbody>
1130
  </table>
@@ -1132,26 +1130,22 @@ REPORTS_CONTENT = """
1132
  </div>
1133
  </div>
1134
  </div>
1135
- <div class="col-lg-6 mb-4">
1136
- <div class="card h-100">
1137
- <div class="card-header"><h5 class="mb-0">Продажи за период</h5></div>
1138
- <div class="card-body">
1139
  <div class="table-responsive">
1140
- <table class="table table-sm">
1141
- <thead><tr><th>Дата</th><th>Позиции</th><th>Сумма</th></tr></thead>
1142
  <tbody>
1143
- {% for t in report_data.filtered_transactions %}
1144
  <tr>
1145
- <td>{{ t.timestamp[:16]|replace('T', ' ') }}</td>
1146
- <td>
1147
- <ul class="list-unstyled mb-0 small">
1148
- {% for item in t.items %}<li>{{ item.name }} ({{ item.quantity }}x{{ format_currency_py(item.price_at_sale) }})</li>{% endfor %}
1149
- </ul>
1150
- </td>
1151
- <td class="fw-bold">{{ format_currency_py(t.total_amount) }} с</td>
1152
  </tr>
1153
  {% else %}
1154
- <tr><td colspan="3" class="text-center text-muted">Продаж за период нет</td></tr>
1155
  {% endfor %}
1156
  </tbody>
1157
  </table>
@@ -1227,6 +1221,36 @@ ADMIN_CONTENT = """
1227
  </form>
1228
  </div>
1229
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1230
  </div>
1231
  <div class="col-12">
1232
  <div class="card">
 
4
  import logging
5
  import threading
6
  import time
7
+ from datetime import datetime, timedelta
8
  import pytz
9
  from huggingface_hub import HfApi, hf_hub_download
10
  from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
11
  import uuid
12
  from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
13
  import functools
14
+ from collections import defaultdict
15
 
16
  app = Flask(__name__)
17
  app.secret_key = os.urandom(24)
 
128
  except Exception as e:
129
  logging.error(f"Error during scheduled backup: {e}", exc_info=True)
130
 
131
+ def find_item_by_field(data, field, value):
 
132
  for item in data:
133
  if isinstance(item, dict) and item.get(field) == value:
134
  return item
 
170
  return redirect(url_for('inventory_management'))
171
 
172
  inventory = load_json_data('inventory')
173
+ if find_item_by_field(inventory, 'barcode', barcode):
174
  flash(f"Товар со штрих-кодом {barcode} уже существует.", "warning")
175
  return redirect(url_for('inventory_management'))
176
 
 
214
  flash("Название, штрих-код и цена обязательны.", "danger")
215
  return redirect(url_for('inventory_management'))
216
 
217
+ existing_barcode = find_item_by_field(inventory, 'barcode', barcode)
218
  if existing_barcode and existing_barcode.get('id') != product_id:
219
  flash(f"Штрих-код {barcode} уже используется другим товаром.", "warning")
220
  return redirect(url_for('inventory_management'))
 
256
 
257
  @app.route('/api/product_by_barcode/<barcode>')
258
  def get_product_by_barcode(barcode):
259
+ inventory = load_json_data('inventory')
260
+ product = find_item_by_field(inventory, 'barcode', barcode)
261
  if product:
262
  if product.get('stock', 0) > 0:
263
  return jsonify({'success': True, 'product': product})
 
281
  users = load_json_data('users')
282
  kassas = load_json_data('kassas')
283
 
284
+ user = find_item_by_field(users, 'id', user_id)
285
+ kassa = find_item_by_field(kassas, 'id', kassa_id)
286
 
287
  if not user or not kassa:
288
  return jsonify({'success': False, 'message': 'Кассир или касса не найдены.'}), 404
 
292
  inventory_updates = {}
293
 
294
  for item_id, cart_item in cart.items():
295
+ product = find_item_by_field(inventory, 'id', item_id)
296
  if not product:
297
  return jsonify({'success': False, 'message': f"Товар с ID {item_id} не найден."}), 404
298
 
 
382
  def reports():
383
  today = get_current_time().date()
384
  start_date_str = request.args.get('start_date', (today.replace(day=1)).strftime('%Y-%m-%d'))
385
+ end_date_str = request.args.get('end_date', (today).strftime('%Y-%m-%d'))
386
 
387
+ start_date = datetime.strptime(start_date_str, '%Y-%m-%d').replace(tzinfo=BISHKEK_TZ)
388
+ end_date = (datetime.strptime(end_date_str, '%Y-%m-%d') + timedelta(days=1)).replace(tzinfo=BISHKEK_TZ)
389
+
390
+ transactions = load_json_data('transactions')
391
+ expenses = load_json_data('expenses')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
 
393
+ filtered_transactions = [
394
+ t for t in transactions
395
+ if start_date <= datetime.fromisoformat(t['timestamp']) < end_date
396
+ ]
397
+ filtered_expenses = [
398
+ e for e in expenses
399
+ if start_date <= datetime.fromisoformat(e['timestamp']) < end_date
400
+ ]
401
+
402
  total_revenue = sum(to_decimal(t['total_amount']) for t in filtered_transactions)
403
+ total_cogs = sum(
404
+ to_decimal(item.get('cost_price_at_sale', '0')) * to_decimal(str(item['quantity']))
405
+ for t in filtered_transactions for item in t['items']
406
+ )
407
  gross_profit = total_revenue - total_cogs
408
  total_expenses = sum(to_decimal(e['amount']) for e in filtered_expenses)
409
  net_profit = gross_profit - total_expenses
410
 
411
+ sales_by_cashier = defaultdict(lambda: {'count': 0, 'total': Decimal(0)})
412
+ for t in filtered_transactions:
413
+ cashier_name = t.get('user_name', 'Неизвестный')
414
+ sales_by_cashier[cashier_name]['count'] += 1
415
+ sales_by_cashier[cashier_name]['total'] += to_decimal(t['total_amount'])
416
+
417
+ stats = {
418
+ 'total_revenue': total_revenue,
419
+ 'total_cogs': total_cogs,
420
+ 'gross_profit': gross_profit,
421
+ 'total_expenses': total_expenses,
422
+ 'net_profit': net_profit,
423
+ 'sales_by_cashier': sorted(sales_by_cashier.items(), key=lambda item: item[1]['total'], reverse=True)
424
  }
425
 
426
+ filtered_expenses.sort(key=lambda x: x['timestamp'], reverse=True)
 
427
 
428
+ html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS)
429
+ return render_template_string(html, stats=stats, start_date=start_date_str, end_date=end_date_str, expenses=filtered_expenses)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
430
 
431
  @app.route('/admin', methods=['GET'])
432
  def admin_panel():
433
  users = load_json_data('users')
434
  kassas = load_json_data('kassas')
435
+ expenses = load_json_data('expenses')
436
+ expenses.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
437
  html = BASE_TEMPLATE.replace('__TITLE__', "Админ-панель").replace('__CONTENT__', ADMIN_CONTENT).replace('__SCRIPTS__', ADMIN_SCRIPTS)
438
+ return render_template_string(html, users=users, kassas=kassas, expenses=expenses[:10])
439
 
440
  @app.route('/admin/user', methods=['POST'])
441
  def manage_user():
 
550
  flash("Касса не найдена.", "danger")
551
 
552
  return redirect(url_for('admin_panel'))
553
+
554
+ @app.route('/admin/expense', methods=['POST'])
555
+ def manage_expense():
556
+ amount = to_decimal(request.form.get('amount', '0'))
557
+ description = request.form.get('description', '').strip()
558
+
559
+ if amount <= 0 or not description:
560
+ flash("Укажите положительную сумму и описание расхода.", "danger")
561
+ return redirect(url_for('admin_panel'))
562
+
563
+ new_expense = {
564
+ 'id': uuid.uuid4().hex,
565
+ 'timestamp': get_current_time().isoformat(),
566
+ 'amount': str(amount),
567
+ 'description': description
568
+ }
569
+ expenses = load_json_data('expenses')
570
+ expenses.append(new_expense)
571
+ save_json_data('expenses', expenses)
572
+ upload_db_to_hf('expenses')
573
+ flash("Расход успешно добавлен.", "success")
574
+ return redirect(url_for('admin_panel'))
575
 
576
  @app.route('/backup', methods=['POST'])
577
  def backup_hf():
 
626
  .main-content { margin-left: 0; }
627
  }
628
  [data-bs-theme="dark"] body { background-color: #212529; color: #dee2e6; }
629
+ [data-bs-theme="dark"] .card, [data-bs-theme="dark"] .list-group-item, [data-bs-theme="dark"] .table { background-color: #343a40; }
630
+ [data-bs-theme="dark"] .table-hover>tbody>tr:hover>* { color: var(--bs-table-hover-color); background-color: rgba(255, 255, 255, 0.075); }
631
  </style>
632
  </head>
633
  <body>
 
703
  <button id="scan-btn" class="btn btn-primary btn-sm"><i class="fas fa-barcode me-2"></i>Сканировать</button>
704
  </div>
705
  <div class="card-body">
706
+ <div id="scanner-container" class="mb-3" style="display: none; position: relative;">
707
  <div id="reader" style="width: 100%;"></div>
708
+ <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>
709
  <button id="stop-scan-btn" class="btn btn-danger btn-sm mt-2">Остановить</button>
710
  </div>
711
  <input type="text" id="product-search" class="form-control mb-3" placeholder="Поиск по названию или штрих-коду...">
 
753
  const cartItemsEl = document.getElementById('cart-items');
754
  const cartTotalEl = document.getElementById('cart-total');
755
  let audioCtx;
756
+ let isScannerPaused = false;
757
 
758
  function playBeep() {
759
  if (!audioCtx) {
 
883
  document.getElementById('pay-cash-btn').addEventListener('click', () => completeSale('cash'));
884
  document.getElementById('pay-card-btn').addEventListener('click', () => completeSale('card'));
885
 
886
+ const html5QrCode = new Html5Qrcode("reader");
887
+ const scannerStatusEl = document.getElementById('scanner-status');
888
+
 
 
 
 
 
 
889
  const onScanSuccess = (decodedText, decodedResult) => {
890
+ if (isScannerPaused) return;
891
+
892
+ isScannerPaused = true;
893
+ scannerStatusEl.textContent = 'Пауза...';
894
+ scannerStatusEl.style.display = 'block';
895
+ html5QrCode.pause();
896
+
897
  fetch(`/api/product_by_barcode/${decodedText}`)
898
  .then(res => res.json())
899
  .then(data => {
900
+ if (data.success) addToCart(data.product);
901
+ else alert(data.message);
902
+ })
903
+ .finally(() => {
904
+ setTimeout(() => {
905
+ isScannerPaused = false;
906
+ scannerStatusEl.style.display = 'none';
907
+ if (html5QrCode.getState() === 2) { // 2 is PAUSED state
908
+ html5QrCode.resume();
909
+ }
910
+ }, 1500);
911
  });
912
  };
913
 
914
  const startScanner = () => {
915
  document.getElementById('scanner-container').style.display = 'block';
916
  const config = { fps: 10, qrbox: { width: 250, height: 250 } };
917
+ html5QrCode.start({ facingMode: "environment" }, config, onScanSuccess)
918
+ .catch(err => console.error("Scanner start error:", err));
919
+ };
920
+
921
+ const stopScanner = () => {
922
+ if (html5QrCode.isScanning) {
923
+ html5QrCode.stop().then(() => {
924
+ document.getElementById('scanner-container').style.display = 'none';
925
+ }).catch(err => console.error("Failed to stop scanner", err));
926
+ } else {
927
+ document.getElementById('scanner-container').style.display = 'none';
928
+ }
929
  };
930
 
931
  document.getElementById('scan-btn').addEventListener('click', startScanner);
 
1086
  <div class="card-body">
1087
  <form method="GET" action="{{ url_for('reports') }}">
1088
  <div class="row g-2 align-items-end">
1089
+ <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>
1090
+ <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>
1091
  <div class="col-md-4"><button type="submit" class="btn btn-primary w-100">Сформировать отчет</button></div>
1092
  </div>
1093
  </form>
 
1095
  </div>
1096
 
1097
  <div class="row">
1098
+ <div class="col-lg-7">
1099
+ <div class="card mb-4">
1100
+ <div class="card-header"><h5 class="mb-0">Сводный отчет за период</h5></div>
 
 
 
 
 
 
 
1101
  <div class="card-body">
1102
+ <ul class="list-group list-group-flush">
1103
+ <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>
1104
+ <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>
1105
+ <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>
1106
+ <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-receipt me-2 text-danger"></i>Расходы</span> <strong class="text-danger">-{{ format_currency_py(stats.total_expenses) }} с</strong></li>
1107
+ <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>
1108
+ </ul>
1109
+ </div>
1110
+ </div>
1111
+ <div class="card mb-4">
1112
+ <div class="card-header"><h5 class="mb-0">Расходы за период</h5></div>
1113
+ <div class="card-body p-0">
1114
  <div class="table-responsive">
1115
+ <table class="table table-sm mb-0">
1116
+ <thead><tr><th>Дата</th><th>Описание</th><th class="text-end">Сумма</th></tr></thead>
1117
  <tbody>
1118
+ {% for expense in expenses %}
1119
  <tr>
1120
+ <td><small>{{ expense.timestamp[:16]|replace('T', ' ') }}</small></td>
1121
+ <td>{{ expense.description }}</td>
1122
+ <td class="text-end">{{ format_currency_py(expense.amount) }} с</td>
 
 
 
 
 
1123
  </tr>
1124
  {% else %}
1125
+ <tr><td colspan="3" class="text-center text-muted">Нет расходов за выбранный период.</td></tr>
1126
  {% endfor %}
1127
  </tbody>
1128
  </table>
 
1130
  </div>
1131
  </div>
1132
  </div>
1133
+ <div class="col-lg-5">
1134
+ <div class="card mb-4">
1135
+ <div class="card-header"><h5 class="mb-0">Продажи по кассирам</h5></div>
1136
+ <div class="card-body p-0">
1137
  <div class="table-responsive">
1138
+ <table class="table table-hover mb-0">
1139
+ <thead><tr><th>Кассир</th><th>Чеков</th><th class="text-end">Сумма</th></tr></thead>
1140
  <tbody>
1141
+ {% for name, data in stats.sales_by_cashier %}
1142
  <tr>
1143
+ <td>{{ name }}</td>
1144
+ <td>{{ data.count }}</td>
1145
+ <td class="text-end">{{ format_currency_py(data.total) }} с</td>
 
 
 
 
1146
  </tr>
1147
  {% else %}
1148
+ <tr><td colspan="3" class="text-center text-muted">Нет продаж за выбранный период.</td></tr>
1149
  {% endfor %}
1150
  </tbody>
1151
  </table>
 
1221
  </form>
1222
  </div>
1223
  </div>
1224
+ </div>
1225
+ <div class="col-12 mb-4">
1226
+ <div class="card">
1227
+ <div class="card-header"><h5 class="mb-0">Учет расходов</h5></div>
1228
+ <div class="card-body">
1229
+ <form action="{{ url_for('manage_expense') }}" method="POST" class="mb-4">
1230
+ <div class="row g-2 align-items-end">
1231
+ <div class="col-md-3"><label class="form-label">Сумма</label><input type="text" name="amount" class="form-control" required inputmode="decimal"></div>
1232
+ <div class="col-md-7"><label class="form-label">Описание</label><input type="text" name="description" class="form-control" required placeholder="Напр: Аренда за май"></div>
1233
+ <div class="col-md-2"><button type="submit" class="btn btn-warning w-100">Добавить расход</button></div>
1234
+ </div>
1235
+ </form>
1236
+ <h6>Последние 10 расходов:</h6>
1237
+ <div class="table-responsive">
1238
+ <table class="table table-sm table-striped">
1239
+ <tbody>
1240
+ {% for e in expenses %}
1241
+ <tr>
1242
+ <td><small>{{ e.timestamp[:16]|replace('T', ' ') }}</small></td>
1243
+ <td>{{ e.description }}</td>
1244
+ <td class="text-end fw-bold">{{ format_currency_py(e.amount) }} с</td>
1245
+ </tr>
1246
+ {% else %}
1247
+ <tr><td colspan="3" class="text-center">Расходов пока нет</td></tr>
1248
+ {% endfor %}
1249
+ </tbody>
1250
+ </table>
1251
+ </div>
1252
+ </div>
1253
+ </div>
1254
  </div>
1255
  <div class="col-12">
1256
  <div class="card">