Kgshop commited on
Commit
1402eb4
·
verified ·
1 Parent(s): e94197d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +476 -356
app.py CHANGED
@@ -25,7 +25,6 @@ TRANSACTIONS_FILE = os.path.join(DATA_DIR, 'transactions.json')
25
  USERS_FILE = os.path.join(DATA_DIR, 'users.json')
26
  KASSAS_FILE = os.path.join(DATA_DIR, 'kassas.json')
27
  EXPENSES_FILE = os.path.join(DATA_DIR, 'expenses.json')
28
- STOCK_MOVEMENTS_FILE = os.path.join(DATA_DIR, 'stock_movements.json')
29
 
30
  DATA_FILES = {
31
  'inventory': (INVENTORY_FILE, threading.Lock()),
@@ -33,7 +32,6 @@ DATA_FILES = {
33
  'users': (USERS_FILE, threading.Lock()),
34
  'kassas': (KASSAS_FILE, threading.Lock()),
35
  'expenses': (EXPENSES_FILE, threading.Lock()),
36
- 'stock_movements': (STOCK_MOVEMENTS_FILE, threading.Lock()),
37
  }
38
 
39
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", "YOUR_WRITE_TOKEN_HERE")
@@ -206,14 +204,19 @@ def generate_receipt_html(transaction):
206
 
207
  @app.context_processor
208
  def inject_utils():
209
- return {'format_currency_py': format_currency_py, 'get_current_time': get_current_time}
210
 
211
  @app.route('/')
212
  def sales_screen():
213
  inventory = load_json_data('inventory')
214
  users = load_json_data('users')
215
  kassas = load_json_data('kassas')
216
- active_inventory = [p for p in inventory if isinstance(p, dict) and p.get('stock', 0) > 0]
 
 
 
 
 
217
  active_inventory.sort(key=lambda x: x.get('name', '').lower())
218
  html = BASE_TEMPLATE.replace('__TITLE__', "Касса").replace('__CONTENT__', SALES_SCREEN_CONTENT).replace('__SCRIPTS__', SALES_SCREEN_SCRIPTS)
219
  return render_template_string(html, inventory=active_inventory, users=users, kassas=kassas)
@@ -224,52 +227,57 @@ def inventory_management():
224
  try:
225
  name = request.form.get('name', '').strip()
226
  barcode = request.form.get('barcode', '').strip()
227
- price = to_decimal(request.form.get('price', '0'))
228
- cost_price = to_decimal(request.form.get('cost_price', '0'))
229
- stock = int(to_decimal(request.form.get('stock', '0')))
230
-
231
- if not name or price <= 0:
232
- flash("Название и цена - обязательные поля.", "danger")
233
  return redirect(url_for('inventory_management'))
234
 
235
  inventory = load_json_data('inventory')
236
- new_product_id = uuid.uuid4().hex
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
 
 
 
 
 
238
  new_product = {
239
- 'id': new_product_id,
240
  'name': name,
241
  'barcode': barcode,
242
- 'price': str(price),
243
- 'cost_price': str(cost_price),
244
- 'stock': stock,
245
  'timestamp_added': get_current_time().isoformat(),
246
  'timestamp_updated': get_current_time().isoformat()
247
  }
248
  inventory.append(new_product)
249
  save_json_data('inventory', inventory)
250
  upload_db_to_hf('inventory')
251
-
252
- if stock > 0:
253
- stock_movements = load_json_data('stock_movements')
254
- stock_movements.append({
255
- 'id': uuid.uuid4().hex,
256
- 'product_id': new_product_id,
257
- 'type': 'stock-in',
258
- 'quantity': stock,
259
- 'cost_price': str(cost_price),
260
- 'timestamp': get_current_time().isoformat(),
261
- 'description': 'Нача��ьный остаток'
262
- })
263
- save_json_data('stock_movements', stock_movements)
264
- upload_db_to_hf('stock_movements')
265
-
266
  flash(f"Товар '{name}' успешно добавлен.", "success")
267
  except Exception as e:
 
268
  flash(f"Ошибка при добавлении товара: {e}", "danger")
269
  return redirect(url_for('inventory_management'))
270
 
271
  inventory_list = load_json_data('inventory')
272
- inventory_list.sort(key=lambda x: (x.get('barcode', ''), x.get('name', '').lower()))
273
  html = BASE_TEMPLATE.replace('__TITLE__', "Склад").replace('__CONTENT__', INVENTORY_CONTENT).replace('__SCRIPTS__', INVENTORY_SCRIPTS)
274
  return render_template_string(html, inventory=inventory_list)
275
 
@@ -282,25 +290,44 @@ def edit_product(product_id):
282
  try:
283
  name = request.form.get('name', '').strip()
284
  barcode = request.form.get('barcode', '').strip()
285
- price = to_decimal(request.form.get('price'))
286
- cost_price = to_decimal(request.form.get('cost_price'))
287
- stock = int(to_decimal(request.form.get('stock')))
288
 
289
- if not name or price <= 0:
290
- flash("Название и цена обязательны.", "danger")
291
  return redirect(url_for('inventory_management'))
292
 
293
- inventory[i].update({
294
- 'name': name,
295
- 'barcode': barcode,
296
- 'price': str(price),
297
- 'cost_price': str(cost_price),
298
- 'stock': stock,
299
- 'timestamp_updated': get_current_time().isoformat()
300
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  product_found = True
302
  break
303
  except Exception as e:
 
304
  flash(f"Ошибка при обновлении товара: {e}", "danger")
305
  return redirect(url_for('inventory_management'))
306
 
@@ -312,81 +339,82 @@ def edit_product(product_id):
312
  flash("Товар не найден.", "danger")
313
  return redirect(url_for('inventory_management'))
314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  @app.route('/inventory/stock_in', methods=['POST'])
316
  def stock_in():
317
  try:
318
  product_id = request.form.get('product_id')
319
- quantity = int(to_decimal(request.form.get('quantity', '0')))
320
- cost_price = to_decimal(request.form.get('cost_price', '0'))
 
321
 
322
- if not product_id or quantity <= 0:
323
- flash("Выберите товар и укажите положительное количество.", "danger")
324
  return redirect(url_for('inventory_management'))
325
 
326
  inventory = load_json_data('inventory')
327
- stock_movements = load_json_data('stock_movements')
328
-
329
- product_found = False
330
- for i, product in enumerate(inventory):
331
- if isinstance(product, dict) and product.get('id') == product_id:
332
- inventory[i]['stock'] += quantity
333
- inventory[i]['cost_price'] = str(cost_price)
334
- inventory[i]['timestamp_updated'] = get_current_time().isoformat()
335
- product_found = True
336
- break
337
-
338
- if not product_found:
339
  flash("Товар не найден.", "danger")
340
  return redirect(url_for('inventory_management'))
341
 
342
- stock_movements.append({
343
- 'id': uuid.uuid4().hex,
344
- 'product_id': product_id,
345
- 'type': 'stock-in',
346
- 'quantity': quantity,
347
- 'cost_price': str(cost_price),
348
- 'timestamp': get_current_time().isoformat(),
349
- 'description': 'Оприходование'
350
- })
351
-
 
 
 
 
 
 
 
 
 
 
 
352
  save_json_data('inventory', inventory)
353
- save_json_data('stock_movements', stock_movements)
354
  upload_db_to_hf('inventory')
355
- upload_db_to_hf('stock_movements')
356
- flash("Товар успешно оприходован.", "success")
357
  except Exception as e:
 
358
  flash(f"Ошибка при оприходовании: {e}", "danger")
359
-
360
- return redirect(url_for('inventory_management'))
361
 
362
- @app.route('/inventory/delete/<product_id>', methods=['POST'])
363
- def delete_product(product_id):
364
- inventory = load_json_data('inventory')
365
- initial_len = len(inventory)
366
- inventory = [p for p in inventory if not (isinstance(p, dict) and p.get('id') == product_id)]
367
- if len(inventory) < initial_len:
368
- save_json_data('inventory', inventory)
369
- upload_db_to_hf('inventory')
370
- flash("Товар удален.", "success")
371
- else:
372
- flash("Товар не найден.", "warning")
373
  return redirect(url_for('inventory_management'))
374
 
375
  @app.route('/api/product_by_barcode/<barcode>')
376
  def get_product_by_barcode(barcode):
377
  inventory = load_json_data('inventory')
378
- variants = [p for p in inventory if isinstance(p, dict) and p.get('barcode') == barcode and p.get('stock', 0) > 0]
379
-
380
- if not variants:
381
- return jsonify({'success': False, 'message': 'Товар не найден или закончился'}), 404
382
-
383
- if len(variants) == 1:
384
- return jsonify({'success': True, 'product': variants[0]})
385
-
386
- if len(variants) > 1:
387
- return jsonify({'success': True, 'is_variant': True, 'variants': variants})
388
-
389
- return jsonify({'success': False, 'message': 'Неизвестная ошибка'}), 500
390
 
391
  @app.route('/api/complete_sale', methods=['POST'])
392
  def complete_sale():
@@ -414,32 +442,37 @@ def complete_sale():
414
  total_amount = Decimal('0.00')
415
  inventory_updates = {}
416
 
417
- for item_id, cart_item in cart.items():
418
- product = find_item_by_field(inventory, 'id', item_id)
419
  if not product:
420
- return jsonify({'success': False, 'message': f"Товар с ID {item_id} не найден."}), 404
 
 
 
 
421
 
422
  quantity_sold = cart_item['quantity']
423
- current_stock = product.get('stock', 0)
424
 
425
  if quantity_sold > current_stock:
426
- return jsonify({'success': False, 'message': f"Недостаточно товара '{product['name']}'. В наличии: {current_stock}"}), 400
427
 
428
- price_at_sale = to_decimal(product.get('price', '0'))
429
- cost_price_at_sale = to_decimal(product.get('cost_price', '0'))
430
  item_total = price_at_sale * Decimal(quantity_sold)
431
  total_amount += item_total
432
 
433
  sale_items.append({
434
- 'product_id': item_id,
435
- 'name': product['name'],
 
436
  'barcode': product.get('barcode'),
437
  'quantity': quantity_sold,
438
  'price_at_sale': str(price_at_sale),
439
  'cost_price_at_sale': str(cost_price_at_sale),
440
  'total': str(item_total)
441
  })
442
- inventory_updates[item_id] = current_stock - quantity_sold
443
 
444
  now_iso = get_current_time().isoformat()
445
 
@@ -461,24 +494,15 @@ def complete_sale():
461
  new_transaction['receipt_html'] = generate_receipt_html(new_transaction)
462
  transactions = load_json_data('transactions')
463
  transactions.append(new_transaction)
464
-
465
- stock_movements = load_json_data('stock_movements')
466
- for item in sale_items:
467
- stock_movements.append({
468
- 'id': uuid.uuid4().hex,
469
- 'product_id': item['product_id'],
470
- 'type': 'sale',
471
- 'quantity': -item['quantity'],
472
- 'cost_price': item['cost_price_at_sale'],
473
- 'timestamp': now_iso,
474
- 'description': f"Продажа, чек {new_transaction['id'][:8]}"
475
- })
476
 
477
- for prod_id, new_stock in inventory_updates.items():
478
- for i, p in enumerate(inventory):
479
- if p.get('id') == prod_id:
480
- inventory[i]['stock'] = new_stock
481
- inventory[i]['timestamp_updated'] = now_iso
 
 
 
482
  break
483
 
484
  if payment_method == 'cash':
@@ -499,12 +523,10 @@ def complete_sale():
499
  save_json_data('transactions', transactions)
500
  save_json_data('inventory', inventory)
501
  save_json_data('kassas', kassas)
502
- save_json_data('stock_movements', stock_movements)
503
 
504
  upload_db_to_hf('transactions')
505
  upload_db_to_hf('inventory')
506
  upload_db_to_hf('kassas')
507
- upload_db_to_hf('stock_movements')
508
 
509
  receipt_url = url_for('view_receipt', transaction_id=new_transaction['id'], _external=True)
510
  return jsonify({
@@ -612,56 +634,50 @@ def reports():
612
  html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS)
613
  return render_template_string(html, stats=stats, start_date=start_date_str, end_date=end_date_str, expenses=filtered_expenses)
614
 
615
- @app.route('/reports/profitability')
616
- def profitability_report():
617
  inventory = load_json_data('inventory')
618
  transactions = load_json_data('transactions')
619
- stock_movements = load_json_data('stock_movements')
620
 
621
- profit_data = {}
 
622
  for product in inventory:
623
- product_id = product.get('id')
624
- if not product_id: continue
625
- profit_data[product_id] = {
626
- 'id': product_id,
627
- 'name': product.get('name', 'N/A'),
628
- 'barcode': product.get('barcode', 'N/A'),
629
- 'stock': product.get('stock', 0),
630
- 'cost_price': to_decimal(product.get('cost_price', '0')),
631
- 'total_revenue': Decimal('0'),
632
- 'total_cogs': Decimal('0'),
633
- 'total_sold_qty': 0,
634
- 'total_investment': Decimal('0'),
635
- }
 
 
 
 
 
 
 
 
 
636
 
637
- for t in transactions:
638
- for item in t.get('items', []):
639
- prod_id = item.get('product_id')
640
- if prod_id in profit_data:
641
- qty = to_decimal(str(item.get('quantity', 0)))
642
- price = to_decimal(item.get('price_at_sale', '0'))
643
- profit_data[prod_id]['total_revenue'] += price * qty
644
- profit_data[prod_id]['total_sold_qty'] += int(qty)
645
-
646
- for sm in stock_movements:
647
- if sm.get('type') == 'stock-in':
648
- prod_id = sm.get('product_id')
649
- if prod_id in profit_data:
650
- qty = to_decimal(str(sm.get('quantity', 0)))
651
- cost = to_decimal(sm.get('cost_price', '0'))
652
- profit_data[prod_id]['total_investment'] += qty * cost
653
-
654
- final_data = []
655
- for prod_id, data in profit_data.items():
656
- data['current_stock_value'] = Decimal(data['stock']) * data['cost_price']
657
- data['payback_status'] = data['total_revenue'] - data['total_investment']
658
- data['net_result'] = data['payback_status'] + data['current_stock_value']
659
- final_data.append(data)
660
-
661
- final_data.sort(key=lambda x: x.get('name', '').lower())
662
-
663
- html = BASE_TEMPLATE.replace('__TITLE__', "Окупаемость товаров").replace('__CONTENT__', PROFITABILITY_REPORT_CONTENT).replace('__SCRIPTS__', "")
664
- return render_template_string(html, profit_data=final_data)
665
 
666
  @app.route('/admin', methods=['GET'])
667
  def admin_panel():
@@ -879,10 +895,13 @@ def return_transaction(transaction_id):
879
  return_items.append({**item, 'quantity': -item['quantity'], 'total': str(-to_decimal(item['total']))})
880
  product = find_item_by_field(inventory, 'id', item['product_id'])
881
  if product:
882
- inventory_updates[item['product_id']] = product.get('stock', 0) + item['quantity']
 
 
 
883
 
884
  now_iso = get_current_time().isoformat()
885
- return_transaction_obj = {
886
  'id': uuid.uuid4().hex,
887
  'timestamp': now_iso,
888
  'type': 'return',
@@ -896,30 +915,21 @@ def return_transaction(transaction_id):
896
  'total_amount': str(-total_amount),
897
  'payment_method': original_transaction['payment_method']
898
  }
899
- transactions.append(return_transaction_obj)
900
-
901
- stock_movements = load_json_data('stock_movements')
902
- for item in original_transaction['items']:
903
- stock_movements.append({
904
- 'id': uuid.uuid4().hex,
905
- 'product_id': item['product_id'],
906
- 'type': 'return',
907
- 'quantity': item['quantity'],
908
- 'cost_price': item['cost_price_at_sale'],
909
- 'timestamp': now_iso,
910
- 'description': f"Возврат, чек {return_transaction_obj['id'][:8]}"
911
- })
912
 
913
  for i, t in enumerate(transactions):
914
  if t['id'] == transaction_id:
915
  transactions[i]['status'] = 'returned'
916
  break
917
 
918
- for prod_id, new_stock in inventory_updates.items():
919
- for i, p in enumerate(inventory):
920
- if p['id'] == prod_id:
921
- inventory[i]['stock'] = new_stock
922
- inventory[i]['timestamp_updated'] = now_iso
 
 
 
923
  break
924
 
925
  if original_transaction['payment_method'] == 'cash':
@@ -929,23 +939,20 @@ def return_transaction(transaction_id):
929
  kassas[i]['balance'] = str(current_balance - total_amount)
930
  kassas[i].setdefault('history', []).append({
931
  'type': 'return', 'amount': str(-total_amount), 'timestamp': now_iso,
932
- 'transaction_id': return_transaction_obj['id']
933
  })
934
  break
935
 
936
  save_json_data('transactions', transactions)
937
  save_json_data('inventory', inventory)
938
  save_json_data('kassas', kassas)
939
- save_json_data('stock_movements', stock_movements)
940
  upload_db_to_hf('transactions')
941
  upload_db_to_hf('inventory')
942
  upload_db_to_hf('kassas')
943
- upload_db_to_hf('stock_movements')
944
 
945
  flash("Возврат успешно оформлен.", "success")
946
  return redirect(url_for('cashier_dashboard', user_id=cashier_id))
947
 
948
-
949
  @app.route('/backup', methods=['POST'])
950
  def backup_hf():
951
  try:
@@ -999,14 +1006,13 @@ BASE_TEMPLATE = """
999
  .main-content { margin-left: 0; }
1000
  }
1001
  [data-bs-theme="dark"] body { background-color: #212529; color: #dee2e6; }
1002
- [data-bs-theme="dark"] .card, [data-bs-theme="dark"] .list-group-item, [data-bs-theme="dark"] .table { background-color: #343a40; }
1003
  [data-bs-theme="dark"] .table-hover>tbody>tr:hover>* { color: var(--bs-table-hover-color); background-color: rgba(255, 255, 255, 0.075); }
1004
- .table-danger-light { background-color: #f8d7da; }
1005
- [data-bs-theme="dark"] .table-danger-light { background-color: #582123; }
1006
- .table-success-light { background-color: #d1e7dd; }
1007
- [data-bs-theme="dark"] .table-success-light { background-color: #143624; }
1008
- .table-warning-light { background-color: #fff3cd; }
1009
- [data-bs-theme="dark"] .table-warning-light { background-color: #533f00; }
1010
  </style>
1011
  </head>
1012
  <body>
@@ -1018,8 +1024,15 @@ BASE_TEMPLATE = """
1018
  <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>
1019
  <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>
1020
  <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>
1021
- <li class="nav-item"><a class="nav-link {% if request.endpoint == 'reports' %}active{% endif %}" href="{{ url_for('reports') }}"><i class="fas fa-fw fa-chart-line me-2"></i>Отчеты</a></li>
1022
- <li class="nav-item"><a class="nav-link {% if request.endpoint == 'profitability_report' %}active{% endif %}" href="{{ url_for('profitability_report') }}"><i class="fas fa-fw fa-balance-scale me-2"></i>Окупаемость</a></li>
 
 
 
 
 
 
 
1023
  <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>
1024
  <li class="nav-item"><a class="nav-link {% if request.endpoint == 'admin_panel' %}active{% endif %}" href="{{ url_for('admin_panel') }}"><i class="fas fa-fw fa-cogs me-2"></i>Админка</a></li>
1025
  </ul>
@@ -1076,11 +1089,15 @@ BASE_TEMPLATE = """
1076
  </div>
1077
  </div>
1078
 
1079
- <div class="modal fade" id="variantSelectModal" tabindex="-1">
1080
  <div class="modal-dialog">
1081
  <div class="modal-content">
1082
- <div class="modal-header"><h5 class="modal-title">Выберите вариант</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1083
- <div class="modal-body" id="variantSelectBody">
 
 
 
 
1084
  </div>
1085
  </div>
1086
  </div>
@@ -1126,13 +1143,21 @@ SALES_SCREEN_CONTENT = """
1126
  <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>
1127
  <button id="stop-scan-btn" class="btn btn-danger btn-sm mt-2">Остановить</button>
1128
  </div>
1129
- <input type="text" id="product-search" class="form-control mb-3" placeholder="Поиск по названию или ввод/сканирование штрих-кода...">
1130
  <div id="product-grid" class="d-grid gap-2" style="grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));">
1131
  {% for p in inventory %}
1132
- <div class="card text-center product-card" data-id="{{ p.id }}" data-name="{{ p.name|lower }}" data-barcode="{{ p.barcode }}">
1133
  <div class="card-body p-2">
1134
  <h6 class="card-title small mb-1">{{ p.name }}</h6>
1135
- <p class="card-text fw-bold mb-0">{{ format_currency_py(p.price) }} с</p>
 
 
 
 
 
 
 
 
1136
  </div>
1137
  </div>
1138
  {% endfor %}
@@ -1174,11 +1199,10 @@ document.addEventListener('DOMContentLoaded', () => {
1174
  let isScannerPaused = false;
1175
  const receiptModal = new bootstrap.Modal(document.getElementById('receiptModal'));
1176
  const variantSelectModal = new bootstrap.Modal(document.getElementById('variantSelectModal'));
1177
- const variantSelectBody = document.getElementById('variantSelectBody');
1178
 
1179
  function playBeep() {
1180
  if (!audioCtx) {
1181
- try { audioCtx = new (window.AudioContext || window.webkitContext)(); }
1182
  catch (e) { console.error("Web Audio API is not supported"); return; }
1183
  }
1184
  const oscillator = audioCtx.createOscillator();
@@ -1205,7 +1229,7 @@ document.addEventListener('DOMContentLoaded', () => {
1205
  cartItemsEl.innerHTML += `
1206
  <div class="list-group-item d-flex justify-content-between align-items-center">
1207
  <div>
1208
- <h6 class="mb-0 small">${item.name}</h6>
1209
  <small>${item.quantity} x ${item.price} с</small>
1210
  </div>
1211
  <div>
@@ -1217,70 +1241,61 @@ document.addEventListener('DOMContentLoaded', () => {
1217
  cartTotalEl.textContent = total.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' с';
1218
  };
1219
 
1220
- const addToCart = (product) => {
1221
- if (cart[product.id]) {
1222
- cart[product.id].quantity++;
1223
  } else {
1224
- cart[product.id] = {
1225
- name: product.name,
1226
- price: String(product.price).replace('.',','),
 
 
1227
  quantity: 1
1228
  };
1229
  }
1230
  playBeep();
1231
  updateCartView();
1232
  };
1233
-
1234
- const processBarcode = (barcode) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1235
  fetch(`/api/product_by_barcode/${barcode}`)
1236
  .then(res => res.json())
1237
  .then(data => {
1238
- if (!data.success) {
1239
- alert(data.message);
1240
- return;
1241
- }
1242
- if (data.is_variant) {
1243
- variantSelectBody.innerHTML = '';
1244
- data.variants.forEach(variant => {
1245
- const btn = document.createElement('button');
1246
- btn.className = 'btn btn-outline-primary w-100 mb-2';
1247
- btn.textContent = `${variant.name} (${variant.stock} шт.)`;
1248
- btn.onclick = () => {
1249
- addToCart(variant);
1250
- variantSelectModal.hide();
1251
- };
1252
- variantSelectBody.appendChild(btn);
1253
- });
1254
- variantSelectModal.show();
1255
- } else {
1256
- addToCart(data.product);
1257
- }
1258
- })
1259
- .catch(err => alert(`Сетевая ошибка: ${err}`));
1260
- };
1261
-
1262
- document.getElementById('product-search').addEventListener('keypress', e => {
1263
- if (e.key === 'Enter') {
1264
- e.preventDefault();
1265
- const barcode = e.target.value.trim();
1266
- if (barcode) {
1267
- processBarcode(barcode);
1268
- e.target.value = '';
1269
- e.target.blur();
1270
- }
1271
- }
1272
- });
1273
 
1274
  productGrid.addEventListener('click', e => {
1275
  const card = e.target.closest('.product-card');
1276
  if (card) {
1277
- fetch(`/api/product_by_barcode/${card.dataset.barcode}`)
1278
- .then(res => res.json())
1279
- .then(data => {
1280
- if (data.success && !data.is_variant) addToCart(data.product);
1281
- else if (data.success && data.is_variant) processBarcode(card.dataset.barcode);
1282
- else alert(data.message);
1283
- });
1284
  }
1285
  });
1286
 
@@ -1304,8 +1319,9 @@ document.addEventListener('DOMContentLoaded', () => {
1304
  document.getElementById('product-search').addEventListener('input', e => {
1305
  const term = e.target.value.toLowerCase();
1306
  document.querySelectorAll('.product-card').forEach(card => {
1307
- const show = card.dataset.name.includes(term) || card.dataset.barcode.includes(term);
1308
- card.style.display = show ? '' : 'none';
 
1309
  });
1310
  });
1311
 
@@ -1365,8 +1381,8 @@ document.addEventListener('DOMContentLoaded', () => {
1365
  scannerStatusEl.style.display = 'block';
1366
  if (html5QrCode.getState() === 2) html5QrCode.pause();
1367
 
1368
- processBarcode(decodedText);
1369
-
1370
  setTimeout(() => {
1371
  isScannerPaused = false;
1372
  scannerStatusEl.style.display = 'none';
@@ -1400,47 +1416,68 @@ document.addEventListener('DOMContentLoaded', () => {
1400
  """
1401
 
1402
  INVENTORY_CONTENT = """
1403
- <button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addProductModal"><i class="fas fa-plus me-2"></i>Добавить товар</button>
1404
- <div class="card">
1405
- <div class="card-body">
1406
- <div class="table-responsive">
1407
- <table class="table table-hover">
1408
- <thead><tr><th>Название</th><th>Штрих-код</th><th>Цена</th><th>Себест.</th><th>Остаток</th><th>Действия</th></tr></thead>
1409
- <tbody>
1410
- {% for p in inventory %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1411
  <tr>
1412
- <td>{{ p.name }}</td><td>{{ p.barcode }}</td><td>{{ format_currency_py(p.price) }} с</td><td>{{ format_currency_py(p.cost_price) }} с</td><td>{{ p.stock }}</td>
1413
- <td>
1414
- <button class="btn btn-sm btn-outline-success" data-bs-toggle="modal" data-bs-target="#stockInModal-{{ p.id }}" title="Оприходовать"><i class="fas fa-plus-circle"></i></button>
1415
- <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editProductModal-{{ p.id }}" title="Редактировать"><i class="fas fa-edit"></i></button>
1416
- <form action="{{ url_for('delete_product', product_id=p.id) }}" method="POST" class="d-inline" onsubmit="return confirm('Удалить товар?');">
1417
- <button type="submit" class="btn btn-sm btn-outline-danger" title="Удалить"><i class="fas fa-trash"></i></button>
1418
- </form>
1419
- </td>
1420
  </tr>
 
 
1421
  {% endfor %}
1422
- </tbody>
1423
- </table>
1424
- </div>
1425
  </div>
 
 
1426
  </div>
1427
 
 
1428
  <div class="modal fade" id="addProductModal" tabindex="-1">
1429
- <div class="modal-dialog">
1430
  <div class="modal-content">
1431
  <div class="modal-header"><h5 class="modal-title">Новый товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1432
  <form action="{{ url_for('inventory_management') }}" method="POST">
1433
  <div class="modal-body">
1434
- <div class="mb-3"><label class="form-label">Название (включая цвет/вариант)</label><input type="text" name="name" class="form-control" required></div>
1435
- <div class="mb-3"><label class="form-label">Штрих-код (может быть одинаковым для вариантов)</label>
1436
- <div class="input-group"><input type="text" name="barcode" class="form-control barcode-input"><button type="button" class="btn btn-outline-secondary scan-modal-btn"><i class="fas fa-barcode"></i></button></div>
 
 
1437
  </div>
1438
  <div id="modal-scanner-add" class="mb-2" style="display:none;"></div>
1439
- <div class="row">
1440
- <div class="col-6 mb-3"><label class="form-label">Цена</label><input type="text" name="price" class="form-control" inputmode="decimal" required></div>
1441
- <div class="col-6 mb-3"><label class="form-label">Себестоимость</label><input type="text" name="cost_price" class="form-control" inputmode="decimal"></div>
 
1442
  </div>
1443
- <div class="mb-3"><label class="form-label">Начальный остаток</label><input type="number" name="stock" class="form-control" value="0" step="1"></div>
1444
  </div>
1445
  <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
1446
  </form>
@@ -1448,57 +1485,85 @@ INVENTORY_CONTENT = """
1448
  </div>
1449
  </div>
1450
 
 
1451
  {% for p in inventory %}
1452
  <div class="modal fade" id="editProductModal-{{ p.id }}" tabindex="-1">
1453
- <div class="modal-dialog">
1454
  <div class="modal-content">
1455
  <div class="modal-header"><h5 class="modal-title">Редактировать товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1456
  <form action="{{ url_for('edit_product', product_id=p.id) }}" method="POST">
1457
  <div class="modal-body">
1458
- <div class="mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" value="{{ p.name }}" required></div>
1459
- <div class="mb-3"><label class="form-label">Штрих-код</label><input type="text" name="barcode" class="form-control" value="{{ p.barcode }}"></div>
1460
  <div class="row">
1461
- <div class="col-6 mb-3"><label class="form-label">Цена</label><input type="text" name="price" class="form-control" value="{{ p.price|string|replace('.', ',') }}" inputmode="decimal" required></div>
1462
- <div class="col-6 mb-3"><label class="form-label">Себестоимость</label><input type="text" name="cost_price" value="{{ p.cost_price|string|replace('.', ',') }}" class="form-control" inputmode="decimal"></div>
1463
  </div>
1464
- <div class="mb-3"><label class="form-label">Остаток</label><input type="number" name="stock" class="form-control" value="{{ p.stock }}" step="1"></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1465
  </div>
1466
  <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
1467
  </form>
1468
  </div>
1469
  </div>
1470
  </div>
1471
- <div class="modal fade" id="stockInModal-{{ p.id }}" tabindex="-1">
 
 
 
1472
  <div class="modal-dialog">
1473
  <div class="modal-content">
1474
- <div class="modal-header"><h5 class="modal-title">Оприходование: {{ p.name }}</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1475
- <form action="{{ url_for('stock_in') }}" method="POST">
1476
- <div class="modal-body">
1477
- <input type="hidden" name="product_id" value="{{ p.id }}">
1478
- <div class="mb-3">
1479
- <label class="form-label">Текущий остаток:</label>
1480
- <p class="form-control-plaintext"><strong>{{ p.stock }} шт.</strong></p>
1481
- </div>
1482
- <div class="mb-3">
1483
- <label class="form-label" for="quantity-{{ p.id }}">Количество для добавления</label>
1484
- <input type="number" id="quantity-{{ p.id }}" name="quantity" class="form-control" step="1" min="1" required>
 
 
 
 
 
 
 
 
 
 
 
1485
  </div>
1486
- <div class="mb-3">
1487
- <label class="form-label" for="cost_price-{{ p.id }}">Себестоимость (за единицу)</label>
1488
- <input type="text" id="cost_price-{{ p.id }}" name="cost_price" class="form-control" value="{{ p.cost_price|string|replace('.', ',') }}" inputmode="decimal" required>
1489
  </div>
1490
  </div>
1491
- <div class="modal-footer"><button type="submit" class="btn btn-success">Оприходовать</button></div>
1492
- </form>
 
1493
  </div>
1494
  </div>
1495
  </div>
1496
- {% endfor %}
1497
  """
1498
 
1499
  INVENTORY_SCRIPTS = """
1500
  <script>
1501
  document.addEventListener('DOMContentLoaded', () => {
 
1502
  let currentScanner = null;
1503
  let currentScannerContainer = null;
1504
  document.querySelectorAll('.scan-modal-btn').forEach(btn => {
@@ -1508,7 +1573,7 @@ document.addEventListener('DOMContentLoaded', () => {
1508
  const barcodeInput = form.querySelector('.barcode-input');
1509
 
1510
  if (currentScanner) {
1511
- currentScanner.stop();
1512
  currentScanner = null;
1513
  if(currentScannerContainer) currentScannerContainer.style.display = 'none';
1514
  return;
@@ -1516,17 +1581,17 @@ document.addEventListener('DOMContentLoaded', () => {
1516
  scannerContainer.style.display = 'block';
1517
  currentScannerContainer = scannerContainer;
1518
  const scannerId = scannerContainer.id + '-reader';
1519
- if(!document.getElementById(scannerId)) scannerContainer.innerHTML = `<div id="${scannerId}"></div>`;
1520
 
1521
  const html5QrCode = new Html5Qrcode(scannerId);
1522
  currentScanner = html5QrCode;
1523
  const onScanSuccess = (decodedText, decodedResult) => {
1524
  barcodeInput.value = decodedText;
1525
- html5QrCode.stop();
1526
  currentScanner = null;
1527
  scannerContainer.style.display = 'none';
1528
  };
1529
- html5QrCode.start({ facingMode: "environment" }, { fps: 10, qrbox: 250 }, onScanSuccess);
1530
  });
1531
  });
1532
 
@@ -1542,6 +1607,70 @@ document.addEventListener('DOMContentLoaded', () => {
1542
  }
1543
  });
1544
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1545
  });
1546
  </script>
1547
  """
@@ -1659,57 +1788,48 @@ REPORTS_CONTENT = """
1659
 
1660
  REPORTS_SCRIPTS = ""
1661
 
1662
- PROFITABILITY_REPORT_CONTENT = """
1663
  <div class="card">
1664
- <div class="card-header">
1665
- <h5 class="mb-0">Отчет по окупаемости товаров</h5>
1666
- </div>
1667
  <div class="card-body p-0">
1668
  <div class="table-responsive">
1669
  <table class="table table-hover table-sm mb-0">
1670
- <thead>
1671
  <tr>
1672
- <th>Товар</th>
1673
  <th class="text-end">Продано, шт</th>
1674
  <th class="text-end">Выручка</th>
1675
- <th class="text-end">Инвестировано</th>
1676
- <th class="text-end">Остаток на складе (в деньгах)</th>
1677
- <th class="text-end">Статус окупаемости</th>
1678
- <th class="text-end">Итоговый результат</th>
1679
  </tr>
1680
  </thead>
1681
  <tbody>
1682
- {% for p in profit_data %}
1683
- {% set status_class = 'table-warning-light' %}
1684
- {% if p.payback_status > 0 %}
1685
- {% set status_class = 'table-success-light' %}
1686
- {% elif p.payback_status < 0 %}
1687
- {% set status_class = 'table-danger-light' %}
1688
- {% endif %}
1689
- <tr class="{{ status_class }}">
1690
- <td>{{ p.name }} <br><small class="text-muted">{{ p.barcode }}</small></td>
1691
- <td class="text-end">{{ p.total_sold_qty }}</td>
1692
- <td class="text-end">{{ format_currency_py(p.total_revenue) }}</td>
1693
- <td class="text-end">{{ format_currency_py(p.total_investment) }}</td>
1694
- <td class="text-end">{{ format_currency_py(p.current_stock_value) }}</td>
1695
- <td class="text-end fw-bold">{{ format_currency_py(p.payback_status) }}</td>
1696
- <td class="text-end fw-bold">{{ format_currency_py(p.net_result) }}</td>
1697
  </tr>
1698
  {% else %}
1699
- <tr><td colspan="7" class="text-center text-muted">Нет данных для анализа.</td></tr>
1700
  {% endfor %}
1701
  </tbody>
1702
  </table>
1703
  </div>
1704
  </div>
1705
  <div class="card-footer small text-muted">
1706
- <ul class="list-unstyled mb-0">
1707
- <li><strong>Выручка:</strong> Сумма всех продаж по товару учетом возвратов).</li>
1708
- <li><strong>Инвестировано:</strong> Общая сумма закупки товара (себестоимость * количество).</li>
1709
- <li><strong>Остаток на складе (в деньгах):</strong> Текущий остаток * последняя себестоимость.</li>
1710
- <li><strong>Статус окупаемости:</strong> Выручка - Инвестировано. Показы��ает, окупились ли уже вложенные в товар деньги.</li>
1711
- <li><strong>Итоговый результат:</strong> (Выручка + Остаток на складе) - Инвестировано. Показывает итоговую прибыль/убыток по товару.</li>
1712
- </ul>
1713
  </div>
1714
  </div>
1715
  """
 
25
  USERS_FILE = os.path.join(DATA_DIR, 'users.json')
26
  KASSAS_FILE = os.path.join(DATA_DIR, 'kassas.json')
27
  EXPENSES_FILE = os.path.join(DATA_DIR, 'expenses.json')
 
28
 
29
  DATA_FILES = {
30
  'inventory': (INVENTORY_FILE, threading.Lock()),
 
32
  'users': (USERS_FILE, threading.Lock()),
33
  'kassas': (KASSAS_FILE, threading.Lock()),
34
  'expenses': (EXPENSES_FILE, threading.Lock()),
 
35
  }
36
 
37
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", "YOUR_WRITE_TOKEN_HERE")
 
204
 
205
  @app.context_processor
206
  def inject_utils():
207
+ return {'format_currency_py': format_currency_py, 'get_current_time': get_current_time, 'quote': quote}
208
 
209
  @app.route('/')
210
  def sales_screen():
211
  inventory = load_json_data('inventory')
212
  users = load_json_data('users')
213
  kassas = load_json_data('kassas')
214
+
215
+ active_inventory = []
216
+ for p in inventory:
217
+ if isinstance(p, dict) and any(v.get('stock', 0) > 0 for v in p.get('variants', [])):
218
+ active_inventory.append(p)
219
+
220
  active_inventory.sort(key=lambda x: x.get('name', '').lower())
221
  html = BASE_TEMPLATE.replace('__TITLE__', "Касса").replace('__CONTENT__', SALES_SCREEN_CONTENT).replace('__SCRIPTS__', SALES_SCREEN_SCRIPTS)
222
  return render_template_string(html, inventory=active_inventory, users=users, kassas=kassas)
 
227
  try:
228
  name = request.form.get('name', '').strip()
229
  barcode = request.form.get('barcode', '').strip()
230
+
231
+ if not name or not barcode:
232
+ flash("Название и штрих-код - обязательные поля.", "danger")
 
 
 
233
  return redirect(url_for('inventory_management'))
234
 
235
  inventory = load_json_data('inventory')
236
+ if find_item_by_field(inventory, 'barcode', barcode):
237
+ flash(f"Товар со штрих-кодом {barcode} уже существует.", "warning")
238
+ return redirect(url_for('inventory_management'))
239
+
240
+ variants = []
241
+ variant_names = request.form.getlist('variant_name[]')
242
+ variant_prices = request.form.getlist('variant_price[]')
243
+ variant_cost_prices = request.form.getlist('variant_cost_price[]')
244
+ variant_stocks = request.form.getlist('variant_stock[]')
245
+
246
+ for i in range(len(variant_names)):
247
+ v_name = variant_names[i].strip()
248
+ if not v_name: continue
249
+ variants.append({
250
+ 'id': uuid.uuid4().hex,
251
+ 'option_name': "Вариант",
252
+ 'option_value': v_name,
253
+ 'price': str(to_decimal(variant_prices[i])),
254
+ 'cost_price': str(to_decimal(variant_cost_prices[i])),
255
+ 'stock': int(to_decimal(variant_stocks[i], '0')),
256
+ })
257
 
258
+ if not variants:
259
+ flash("Нужно добавить хотя бы один вариант товара.", "danger")
260
+ return redirect(url_for('inventory_management'))
261
+
262
  new_product = {
263
+ 'id': uuid.uuid4().hex,
264
  'name': name,
265
  'barcode': barcode,
266
+ 'variants': variants,
 
 
267
  'timestamp_added': get_current_time().isoformat(),
268
  'timestamp_updated': get_current_time().isoformat()
269
  }
270
  inventory.append(new_product)
271
  save_json_data('inventory', inventory)
272
  upload_db_to_hf('inventory')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  flash(f"Товар '{name}' успешно добавлен.", "success")
274
  except Exception as e:
275
+ logging.error(f"Error adding product: {e}", exc_info=True)
276
  flash(f"Ошибка при добавлении товара: {e}", "danger")
277
  return redirect(url_for('inventory_management'))
278
 
279
  inventory_list = load_json_data('inventory')
280
+ inventory_list.sort(key=lambda x: x.get('name', '').lower())
281
  html = BASE_TEMPLATE.replace('__TITLE__', "Склад").replace('__CONTENT__', INVENTORY_CONTENT).replace('__SCRIPTS__', INVENTORY_SCRIPTS)
282
  return render_template_string(html, inventory=inventory_list)
283
 
 
290
  try:
291
  name = request.form.get('name', '').strip()
292
  barcode = request.form.get('barcode', '').strip()
 
 
 
293
 
294
+ if not name or not barcode:
295
+ flash("Название и штрих-код обязательны.", "danger")
296
  return redirect(url_for('inventory_management'))
297
 
298
+ existing_barcode = find_item_by_field(inventory, 'barcode', barcode)
299
+ if existing_barcode and existing_barcode.get('id') != product_id:
300
+ flash(f"Штрих-код {barcode} уже используется другим товаром.", "warning")
301
+ return redirect(url_for('inventory_management'))
302
+
303
+ inventory[i]['name'] = name
304
+ inventory[i]['barcode'] = barcode
305
+
306
+ new_variants = []
307
+ variant_ids = request.form.getlist('variant_id[]')
308
+ variant_names = request.form.getlist('variant_name[]')
309
+ variant_prices = request.form.getlist('variant_price[]')
310
+ variant_cost_prices = request.form.getlist('variant_cost_price[]')
311
+ variant_stocks = request.form.getlist('variant_stock[]')
312
+
313
+ for j in range(len(variant_ids)):
314
+ v_name = variant_names[j].strip()
315
+ if not v_name: continue
316
+ new_variants.append({
317
+ 'id': variant_ids[j] or uuid.uuid4().hex,
318
+ 'option_name': "Вариант",
319
+ 'option_value': v_name,
320
+ 'price': str(to_decimal(variant_prices[j])),
321
+ 'cost_price': str(to_decimal(variant_cost_prices[j])),
322
+ 'stock': int(to_decimal(variant_stocks[j], '0')),
323
+ })
324
+
325
+ inventory[i]['variants'] = new_variants
326
+ inventory[i]['timestamp_updated'] = get_current_time().isoformat()
327
  product_found = True
328
  break
329
  except Exception as e:
330
+ logging.error(f"Error updating product: {e}", exc_info=True)
331
  flash(f"Ошибка при обновлении товара: {e}", "danger")
332
  return redirect(url_for('inventory_management'))
333
 
 
339
  flash("Товар не найден.", "danger")
340
  return redirect(url_for('inventory_management'))
341
 
342
+ @app.route('/inventory/delete/<product_id>', methods=['POST'])
343
+ def delete_product(product_id):
344
+ inventory = load_json_data('inventory')
345
+ initial_len = len(inventory)
346
+ inventory = [p for p in inventory if not (isinstance(p, dict) and p.get('id') == product_id)]
347
+ if len(inventory) < initial_len:
348
+ save_json_data('inventory', inventory)
349
+ upload_db_to_hf('inventory')
350
+ flash("Товар удален.", "success")
351
+ else:
352
+ flash("Товар не найден.", "warning")
353
+ return redirect(url_for('inventory_management'))
354
+
355
  @app.route('/inventory/stock_in', methods=['POST'])
356
  def stock_in():
357
  try:
358
  product_id = request.form.get('product_id')
359
+ variant_id = request.form.get('variant_id')
360
+ quantity = int(request.form.get('quantity', 0))
361
+ cost_price_str = request.form.get('cost_price')
362
 
363
+ if not product_id or not variant_id or quantity <= 0:
364
+ flash("Неверные данные для оприходования.", "danger")
365
  return redirect(url_for('inventory_management'))
366
 
367
  inventory = load_json_data('inventory')
368
+ product = find_item_by_field(inventory, 'id', product_id)
369
+ if not product:
 
 
 
 
 
 
 
 
 
 
370
  flash("Товар не найден.", "danger")
371
  return redirect(url_for('inventory_management'))
372
 
373
+ variant_found = False
374
+ for i, variant in enumerate(product.get('variants', [])):
375
+ if variant.get('id') == variant_id:
376
+ variant['stock'] = variant.get('stock', 0) + quantity
377
+ # Update cost price if provided, using weighted average
378
+ if cost_price_str:
379
+ new_cost = to_decimal(cost_price_str)
380
+ old_stock = variant.get('stock', 0) - quantity
381
+ old_cost = to_decimal(variant.get('cost_price', '0'))
382
+ if old_stock + quantity > 0:
383
+ avg_cost = ((old_cost * old_stock) + (new_cost * quantity)) / (old_stock + quantity)
384
+ variant['cost_price'] = str(avg_cost.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))
385
+
386
+ variant_found = True
387
+ break
388
+
389
+ if not variant_found:
390
+ flash("Вариант товара не найден.", "danger")
391
+ return redirect(url_for('inventory_management'))
392
+
393
+ product['timestamp_updated'] = get_current_time().isoformat()
394
  save_json_data('inventory', inventory)
 
395
  upload_db_to_hf('inventory')
396
+ flash(f"Остаток товара '{product['name']} ({variant['option_value']})' увеличен на {quantity}.", "success")
397
+
398
  except Exception as e:
399
+ logging.error(f"Error stocking in: {e}", exc_info=True)
400
  flash(f"Ошибка при оприходовании: {e}", "danger")
 
 
401
 
 
 
 
 
 
 
 
 
 
 
 
402
  return redirect(url_for('inventory_management'))
403
 
404
  @app.route('/api/product_by_barcode/<barcode>')
405
  def get_product_by_barcode(barcode):
406
  inventory = load_json_data('inventory')
407
+ product = find_item_by_field(inventory, 'barcode', barcode)
408
+ if product:
409
+ # Return only variants that are in stock
410
+ active_variants = [v for v in product.get('variants', []) if v.get('stock', 0) > 0]
411
+ if active_variants:
412
+ product_copy = product.copy()
413
+ product_copy['variants'] = active_variants
414
+ return jsonify({'success': True, 'product': product_copy})
415
+ else:
416
+ return jsonify({'success': False, 'message': 'Товар закончился на складе'}), 404
417
+ return jsonify({'success': False, 'message': 'Товар не найден'}), 404
 
418
 
419
  @app.route('/api/complete_sale', methods=['POST'])
420
  def complete_sale():
 
442
  total_amount = Decimal('0.00')
443
  inventory_updates = {}
444
 
445
+ for variant_id, cart_item in cart.items():
446
+ product = find_item_by_field(inventory, 'id', cart_item['productId'])
447
  if not product:
448
+ return jsonify({'success': False, 'message': f"Товар с ID {cart_item['productId']} не найден."}), 404
449
+
450
+ variant = find_item_by_field(product.get('variants', []), 'id', variant_id)
451
+ if not variant:
452
+ return jsonify({'success': False, 'message': f"Вариант товара с ID {variant_id} не найден."}), 404
453
 
454
  quantity_sold = cart_item['quantity']
455
+ current_stock = variant.get('stock', 0)
456
 
457
  if quantity_sold > current_stock:
458
+ return jsonify({'success': False, 'message': f"Недостаточно товара '{product['name']} ({variant['option_value']})'. В наличии: {current_stock}"}), 400
459
 
460
+ price_at_sale = to_decimal(variant.get('price', '0'))
461
+ cost_price_at_sale = to_decimal(variant.get('cost_price', '0'))
462
  item_total = price_at_sale * Decimal(quantity_sold)
463
  total_amount += item_total
464
 
465
  sale_items.append({
466
+ 'product_id': product['id'],
467
+ 'variant_id': variant_id,
468
+ 'name': f"{product['name']} ({variant['option_value']})",
469
  'barcode': product.get('barcode'),
470
  'quantity': quantity_sold,
471
  'price_at_sale': str(price_at_sale),
472
  'cost_price_at_sale': str(cost_price_at_sale),
473
  'total': str(item_total)
474
  })
475
+ inventory_updates[variant_id] = {'product_id': product['id'], 'new_stock': current_stock - quantity_sold}
476
 
477
  now_iso = get_current_time().isoformat()
478
 
 
494
  new_transaction['receipt_html'] = generate_receipt_html(new_transaction)
495
  transactions = load_json_data('transactions')
496
  transactions.append(new_transaction)
 
 
 
 
 
 
 
 
 
 
 
 
497
 
498
+ for variant_id, update_info in inventory_updates.items():
499
+ for p in inventory:
500
+ if p.get('id') == update_info['product_id']:
501
+ for v in p.get('variants', []):
502
+ if v.get('id') == variant_id:
503
+ v['stock'] = update_info['new_stock']
504
+ p['timestamp_updated'] = now_iso
505
+ break
506
  break
507
 
508
  if payment_method == 'cash':
 
523
  save_json_data('transactions', transactions)
524
  save_json_data('inventory', inventory)
525
  save_json_data('kassas', kassas)
 
526
 
527
  upload_db_to_hf('transactions')
528
  upload_db_to_hf('inventory')
529
  upload_db_to_hf('kassas')
 
530
 
531
  receipt_url = url_for('view_receipt', transaction_id=new_transaction['id'], _external=True)
532
  return jsonify({
 
634
  html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS)
635
  return render_template_string(html, stats=stats, start_date=start_date_str, end_date=end_date_str, expenses=filtered_expenses)
636
 
637
+ @app.route('/reports/product_roi')
638
+ def product_roi_report():
639
  inventory = load_json_data('inventory')
640
  transactions = load_json_data('transactions')
 
641
 
642
+ product_stats = []
643
+
644
  for product in inventory:
645
+ for variant in product.get('variants', []):
646
+ total_revenue = Decimal('0.00')
647
+ total_cogs = Decimal('0.00')
648
+ total_qty_sold = 0
649
+
650
+ for t in transactions:
651
+ if t['type'] in ['sale', 'return']:
652
+ for item in t['items']:
653
+ if item.get('variant_id') == variant['id']:
654
+ total_revenue += to_decimal(item['total'])
655
+ total_cogs += to_decimal(item.get('cost_price_at_sale', '0')) * to_decimal(str(item['quantity']))
656
+ if t['type'] == 'sale':
657
+ total_qty_sold += item['quantity']
658
+ elif t['type'] == 'return':
659
+ total_qty_sold += item['quantity'] # quantity is negative on returns
660
+
661
+ current_stock = to_decimal(str(variant.get('stock', 0)))
662
+ cost_price = to_decimal(variant.get('cost_price', '0'))
663
+
664
+ inventory_value = current_stock * cost_price
665
+ total_investment = total_cogs + inventory_value
666
+ payback = total_revenue - total_investment
667
 
668
+ product_stats.append({
669
+ 'name': product['name'],
670
+ 'variant_name': variant['option_value'],
671
+ 'total_qty_sold': total_qty_sold,
672
+ 'total_revenue': total_revenue,
673
+ 'total_investment': total_investment,
674
+ 'inventory_value': inventory_value,
675
+ 'payback': payback
676
+ })
677
+
678
+ product_stats.sort(key=lambda x: x['payback'], reverse=True)
679
+ html = BASE_TEMPLATE.replace('__TITLE__', "Отчет по окупаемости товаров").replace('__CONTENT__', PRODUCT_ROI_CONTENT).replace('__SCRIPTS__', '')
680
+ return render_template_string(html, stats=product_stats)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
681
 
682
  @app.route('/admin', methods=['GET'])
683
  def admin_panel():
 
895
  return_items.append({**item, 'quantity': -item['quantity'], 'total': str(-to_decimal(item['total']))})
896
  product = find_item_by_field(inventory, 'id', item['product_id'])
897
  if product:
898
+ variant = find_item_by_field(product.get('variants', []), 'id', item['variant_id'])
899
+ if variant:
900
+ inventory_updates[item['variant_id']] = {'product_id': item['product_id'], 'new_stock': variant.get('stock', 0) + item['quantity']}
901
+
902
 
903
  now_iso = get_current_time().isoformat()
904
+ return_transaction = {
905
  'id': uuid.uuid4().hex,
906
  'timestamp': now_iso,
907
  'type': 'return',
 
915
  'total_amount': str(-total_amount),
916
  'payment_method': original_transaction['payment_method']
917
  }
918
+ transactions.append(return_transaction)
 
 
 
 
 
 
 
 
 
 
 
 
919
 
920
  for i, t in enumerate(transactions):
921
  if t['id'] == transaction_id:
922
  transactions[i]['status'] = 'returned'
923
  break
924
 
925
+ for variant_id, update_info in inventory_updates.items():
926
+ for p in inventory:
927
+ if p.get('id') == update_info['product_id']:
928
+ for v in p.get('variants', []):
929
+ if v.get('id') == variant_id:
930
+ v['stock'] = update_info['new_stock']
931
+ p['timestamp_updated'] = now_iso
932
+ break
933
  break
934
 
935
  if original_transaction['payment_method'] == 'cash':
 
939
  kassas[i]['balance'] = str(current_balance - total_amount)
940
  kassas[i].setdefault('history', []).append({
941
  'type': 'return', 'amount': str(-total_amount), 'timestamp': now_iso,
942
+ 'transaction_id': return_transaction['id']
943
  })
944
  break
945
 
946
  save_json_data('transactions', transactions)
947
  save_json_data('inventory', inventory)
948
  save_json_data('kassas', kassas)
 
949
  upload_db_to_hf('transactions')
950
  upload_db_to_hf('inventory')
951
  upload_db_to_hf('kassas')
 
952
 
953
  flash("Возврат успешно оформлен.", "success")
954
  return redirect(url_for('cashier_dashboard', user_id=cashier_id))
955
 
 
956
  @app.route('/backup', methods=['POST'])
957
  def backup_hf():
958
  try:
 
1006
  .main-content { margin-left: 0; }
1007
  }
1008
  [data-bs-theme="dark"] body { background-color: #212529; color: #dee2e6; }
1009
+ [data-bs-theme="dark"] .card, [data-bs-theme="dark"] .modal-content, [data-bs-theme="dark"] .list-group-item, [data-bs-theme="dark"] .table { background-color: #343a40; }
1010
  [data-bs-theme="dark"] .table-hover>tbody>tr:hover>* { color: var(--bs-table-hover-color); background-color: rgba(255, 255, 255, 0.075); }
1011
+ .product-card { cursor: pointer; }
1012
+ .product-card:hover { border-color: var(--bs-primary); }
1013
+ .payback-positive { color: var(--bs-success); }
1014
+ .payback-negative { color: var(--bs-danger); }
1015
+ .payback-zero { color: var(--bs-secondary); }
 
1016
  </style>
1017
  </head>
1018
  <body>
 
1024
  <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>
1025
  <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>
1026
  <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>
1027
+ <li class="nav-item dropdown">
1028
+ <a class="nav-link dropdown-toggle {% if request.endpoint in ['reports', 'product_roi_report'] %}active{% endif %}" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
1029
+ <i class="fas fa-fw fa-chart-line me-2"></i>Отчеты
1030
+ </a>
1031
+ <ul class="dropdown-menu dropdown-menu-dark">
1032
+ <li><a class="dropdown-item" href="{{ url_for('reports') }}">Сводный отчет</a></li>
1033
+ <li><a class="dropdown-item" href="{{ url_for('product_roi_report') }}">Окупаемость товаров</a></li>
1034
+ </ul>
1035
+ </li>
1036
  <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>
1037
  <li class="nav-item"><a class="nav-link {% if request.endpoint == 'admin_panel' %}active{% endif %}" href="{{ url_for('admin_panel') }}"><i class="fas fa-fw fa-cogs me-2"></i>Админка</a></li>
1038
  </ul>
 
1089
  </div>
1090
  </div>
1091
 
1092
+ <div class="modal fade" id="variantSelectModal" tabindex="-1" aria-hidden="true">
1093
  <div class="modal-dialog">
1094
  <div class="modal-content">
1095
+ <div class="modal-header">
1096
+ <h5 class="modal-title" id="variantSelectModalTitle">Выберите вариант</h5>
1097
+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
1098
+ </div>
1099
+ <div class="modal-body">
1100
+ <div id="variant-list" class="list-group"></div>
1101
  </div>
1102
  </div>
1103
  </div>
 
1143
  <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>
1144
  <button id="stop-scan-btn" class="btn btn-danger btn-sm mt-2">Остановить</button>
1145
  </div>
1146
+ <input type="text" id="product-search" class="form-control mb-3" placeholder="Поиск по названию или штрих-коду...">
1147
  <div id="product-grid" class="d-grid gap-2" style="grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));">
1148
  {% for p in inventory %}
1149
+ <div class="card text-center product-card" data-barcode="{{ p.barcode }}">
1150
  <div class="card-body p-2">
1151
  <h6 class="card-title small mb-1">{{ p.name }}</h6>
1152
+ <p class="card-text fw-bold mb-0">
1153
+ {% if p.variants|length > 1 %}
1154
+ от {{ format_currency_py(p.variants|map(attribute='price')|min) }} с
1155
+ {% elif p.variants|length == 1 %}
1156
+ {{ format_currency_py(p.variants[0].price) }} с
1157
+ {% else %}
1158
+ Нет в наличии
1159
+ {% endif %}
1160
+ </p>
1161
  </div>
1162
  </div>
1163
  {% endfor %}
 
1199
  let isScannerPaused = false;
1200
  const receiptModal = new bootstrap.Modal(document.getElementById('receiptModal'));
1201
  const variantSelectModal = new bootstrap.Modal(document.getElementById('variantSelectModal'));
 
1202
 
1203
  function playBeep() {
1204
  if (!audioCtx) {
1205
+ try { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); }
1206
  catch (e) { console.error("Web Audio API is not supported"); return; }
1207
  }
1208
  const oscillator = audioCtx.createOscillator();
 
1229
  cartItemsEl.innerHTML += `
1230
  <div class="list-group-item d-flex justify-content-between align-items-center">
1231
  <div>
1232
+ <h6 class="mb-0 small">${item.productName} (${item.variantName})</h6>
1233
  <small>${item.quantity} x ${item.price} с</small>
1234
  </div>
1235
  <div>
 
1241
  cartTotalEl.textContent = total.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' с';
1242
  };
1243
 
1244
+ const addToCart = (product, variant) => {
1245
+ if (cart[variant.id]) {
1246
+ cart[variant.id].quantity++;
1247
  } else {
1248
+ cart[variant.id] = {
1249
+ productId: product.id,
1250
+ productName: product.name,
1251
+ variantName: variant.option_value,
1252
+ price: String(variant.price).replace('.',','),
1253
  quantity: 1
1254
  };
1255
  }
1256
  playBeep();
1257
  updateCartView();
1258
  };
1259
+
1260
+ const handleProductSelection = (product) => {
1261
+ if (!product.variants || product.variants.length === 0) {
1262
+ alert("У этого товара нет доступных вариантов.");
1263
+ return;
1264
+ }
1265
+ if (product.variants.length === 1) {
1266
+ addToCart(product, product.variants[0]);
1267
+ } else {
1268
+ document.getElementById('variantSelectModalTitle').textContent = `Выберите вариант для "${product.name}"`;
1269
+ const variantList = document.getElementById('variant-list');
1270
+ variantList.innerHTML = '';
1271
+ product.variants.forEach(variant => {
1272
+ const btn = document.createElement('button');
1273
+ btn.type = 'button';
1274
+ btn.className = 'list-group-item list-group-item-action';
1275
+ btn.innerHTML = `${variant.option_value} - <strong>${parseFloat(variant.price).toLocaleString('ru-RU', {minimumFractionDigits: 2})} с</strong> <span class="badge bg-secondary float-end">Остаток: ${variant.stock}</span>`;
1276
+ btn.addEventListener('click', () => {
1277
+ addToCart(product, variant);
1278
+ variantSelectModal.hide();
1279
+ });
1280
+ variantList.appendChild(btn);
1281
+ });
1282
+ variantSelectModal.show();
1283
+ }
1284
+ };
1285
+
1286
+ const fetchAndHandleProduct = (barcode) => {
1287
  fetch(`/api/product_by_barcode/${barcode}`)
1288
  .then(res => res.json())
1289
  .then(data => {
1290
+ if (data.success) handleProductSelection(data.product);
1291
+ else alert(data.message);
1292
+ });
1293
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1294
 
1295
  productGrid.addEventListener('click', e => {
1296
  const card = e.target.closest('.product-card');
1297
  if (card) {
1298
+ fetchAndHandleProduct(card.dataset.barcode);
 
 
 
 
 
 
1299
  }
1300
  });
1301
 
 
1319
  document.getElementById('product-search').addEventListener('input', e => {
1320
  const term = e.target.value.toLowerCase();
1321
  document.querySelectorAll('.product-card').forEach(card => {
1322
+ const productName = card.querySelector('.card-title').textContent.toLowerCase();
1323
+ const show = productName.includes(term) || card.dataset.barcode.includes(term);
1324
+ card.parentElement.style.display = show ? '' : 'none'; // Target parent if inside a grid wrapper
1325
  });
1326
  });
1327
 
 
1381
  scannerStatusEl.style.display = 'block';
1382
  if (html5QrCode.getState() === 2) html5QrCode.pause();
1383
 
1384
+ fetchAndHandleProduct(decodedText);
1385
+
1386
  setTimeout(() => {
1387
  isScannerPaused = false;
1388
  scannerStatusEl.style.display = 'none';
 
1416
  """
1417
 
1418
  INVENTORY_CONTENT = """
1419
+ <div class="d-flex justify-content-between mb-3">
1420
+ <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addProductModal"><i class="fas fa-plus me-2"></i>Добавить товар</button>
1421
+ <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#stockInModal"><i class="fas fa-truck-loading me-2"></i>Оприходовать</button>
1422
+ </div>
1423
+
1424
+ <div class="accordion" id="inventoryAccordion">
1425
+ {% for p in inventory %}
1426
+ <div class="accordion-item">
1427
+ <h2 class="accordion-header" id="heading-{{ p.id }}">
1428
+ <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-{{ p.id }}">
1429
+ <strong>{{ p.name }}</strong>&nbsp;<small class="text-muted"> ({{ p.barcode }})</small>
1430
+ </button>
1431
+ </h2>
1432
+ <div id="collapse-{{ p.id }}" class="accordion-collapse collapse" data-bs-parent="#inventoryAccordion">
1433
+ <div class="accordion-body">
1434
+ <div class="d-flex justify-content-end mb-2">
1435
+ <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>
1436
+ <form action="{{ url_for('delete_product', product_id=p.id) }}" method="POST" class="d-inline ms-2" onsubmit="return confirm('Удалить товар?');">
1437
+ <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
1438
+ </form>
1439
+ </div>
1440
+ <table class="table table-sm table-bordered">
1441
+ <thead><tr><th>Вариант</th><th>Цена</th><th>Себест.</th><th>Остаток</th></tr></thead>
1442
+ <tbody>
1443
+ {% for v in p.variants %}
1444
  <tr>
1445
+ <td>{{ v.option_value }}</td>
1446
+ <td>{{ format_currency_py(v.price) }} с</td>
1447
+ <td>{{ format_currency_py(v.cost_price) }} с</td>
1448
+ <td>{{ v.stock }}</td>
 
 
 
 
1449
  </tr>
1450
+ {% else %}
1451
+ <tr><td colspan="4" class="text-center text-muted">Нет вариантов</td></tr>
1452
  {% endfor %}
1453
+ </tbody>
1454
+ </table>
1455
+ </div>
1456
  </div>
1457
+ </div>
1458
+ {% endfor %}
1459
  </div>
1460
 
1461
+ <!-- Add Product Modal -->
1462
  <div class="modal fade" id="addProductModal" tabindex="-1">
1463
+ <div class="modal-dialog modal-lg">
1464
  <div class="modal-content">
1465
  <div class="modal-header"><h5 class="modal-title">Новый товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1466
  <form action="{{ url_for('inventory_management') }}" method="POST">
1467
  <div class="modal-body">
1468
+ <div class="row">
1469
+ <div class="col-md-6 mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" required></div>
1470
+ <div class="col-md-6 mb-3"><label class="form-label">Штрих-код</label>
1471
+ <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>
1472
+ </div>
1473
  </div>
1474
  <div id="modal-scanner-add" class="mb-2" style="display:none;"></div>
1475
+ <hr>
1476
+ <h6>Варианты товара</h6>
1477
+ <div id="variants-container-add">
1478
+ <!-- Variant fields will be added here by JS -->
1479
  </div>
1480
+ <button type="button" class="btn btn-sm btn-outline-success mt-2" id="add-variant-btn-add">Добавить вариант</button>
1481
  </div>
1482
  <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
1483
  </form>
 
1485
  </div>
1486
  </div>
1487
 
1488
+ <!-- Edit Product Modals -->
1489
  {% for p in inventory %}
1490
  <div class="modal fade" id="editProductModal-{{ p.id }}" tabindex="-1">
1491
+ <div class="modal-dialog modal-lg">
1492
  <div class="modal-content">
1493
  <div class="modal-header"><h5 class="modal-title">Редактировать товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1494
  <form action="{{ url_for('edit_product', product_id=p.id) }}" method="POST">
1495
  <div class="modal-body">
 
 
1496
  <div class="row">
1497
+ <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>
1498
+ <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>
1499
  </div>
1500
+ <hr>
1501
+ <h6>Варианты товара</h6>
1502
+ <div id="variants-container-edit-{{ p.id }}">
1503
+ {% for v in p.variants %}
1504
+ <div class="row g-2 mb-2 align-items-center variant-row">
1505
+ <input type="hidden" name="variant_id[]" value="{{ v.id }}">
1506
+ <div class="col-3"><input type="text" name="variant_name[]" class="form-control" placeholder="Название варианта" value="{{ v.option_value }}" required></div>
1507
+ <div class="col"><input type="text" name="variant_price[]" class="form-control" placeholder="Цена" value="{{ v.price|string|replace('.', ',') }}" inputmode="decimal"></div>
1508
+ <div class="col"><input type="text" name="variant_cost_price[]" class="form-control" placeholder="Себестоимость" value="{{ v.cost_price|string|replace('.', ',') }}" inputmode="decimal"></div>
1509
+ <div class="col"><input type="number" name="variant_stock[]" class="form-control" placeholder="Остаток" value="{{ v.stock }}"></div>
1510
+ <div class="col-auto"><button type="button" class="btn btn-sm btn-danger remove-variant-btn"><i class="fas fa-times"></i></button></div>
1511
+ </div>
1512
+ {% endfor %}
1513
+ </div>
1514
+ <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>
1515
  </div>
1516
  <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
1517
  </form>
1518
  </div>
1519
  </div>
1520
  </div>
1521
+ {% endfor %}
1522
+
1523
+ <!-- Stock In Modal -->
1524
+ <div class="modal fade" id="stockInModal" tabindex="-1">
1525
  <div class="modal-dialog">
1526
  <div class="modal-content">
1527
+ <div class="modal-header"><h5 class="modal-title">Оприходование товара</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1528
+ <form action="{{ url_for('stock_in') }}" method="POST">
1529
+ <div class="modal-body">
1530
+ <div class="mb-3">
1531
+ <label for="stockin-product" class="form-label">Товар</label>
1532
+ <select id="stockin-product" name="product_id" class="form-select" required>
1533
+ <option value="">-- Выберите товар --</option>
1534
+ {% for p in inventory %}
1535
+ <option value="{{ p.id }}">{{ p.name }}</option>
1536
+ {% endfor %}
1537
+ </select>
1538
+ </div>
1539
+ <div class="mb-3">
1540
+ <label for="stockin-variant" class="form-label">Вариант</label>
1541
+ <select id="stockin-variant" name="variant_id" class="form-select" required disabled>
1542
+ <option value="">-- Сначала выберите товар --</option>
1543
+ </select>
1544
+ </div>
1545
+ <div class="row">
1546
+ <div class="col-6 mb-3">
1547
+ <label for="stockin-quantity" class="form-label">Количество</label>
1548
+ <input type="number" id="stockin-quantity" name="quantity" class="form-control" required min="1">
1549
  </div>
1550
+ <div class="col-6 mb-3">
1551
+ <label for="stockin-cost" class="form-label">Себестоимость (за ед.)</label>
1552
+ <input type="text" id="stockin-cost" name="cost_price" class="form-control" inputmode="decimal" placeholder="Необязательно">
1553
  </div>
1554
  </div>
1555
+ </div>
1556
+ <div class="modal-footer"><button type="submit" class="btn btn-primary">Оприходовать</button></div>
1557
+ </form>
1558
  </div>
1559
  </div>
1560
  </div>
 
1561
  """
1562
 
1563
  INVENTORY_SCRIPTS = """
1564
  <script>
1565
  document.addEventListener('DOMContentLoaded', () => {
1566
+ // --- Barcode Scanner Logic for Modals ---
1567
  let currentScanner = null;
1568
  let currentScannerContainer = null;
1569
  document.querySelectorAll('.scan-modal-btn').forEach(btn => {
 
1573
  const barcodeInput = form.querySelector('.barcode-input');
1574
 
1575
  if (currentScanner) {
1576
+ try { currentScanner.stop(); } catch(e) {}
1577
  currentScanner = null;
1578
  if(currentScannerContainer) currentScannerContainer.style.display = 'none';
1579
  return;
 
1581
  scannerContainer.style.display = 'block';
1582
  currentScannerContainer = scannerContainer;
1583
  const scannerId = scannerContainer.id + '-reader';
1584
+ if(!document.getElementById(scannerId)) scannerContainer.innerHTML = `<div id="${scannerId}" style="width: 100%;"></div>`;
1585
 
1586
  const html5QrCode = new Html5Qrcode(scannerId);
1587
  currentScanner = html5QrCode;
1588
  const onScanSuccess = (decodedText, decodedResult) => {
1589
  barcodeInput.value = decodedText;
1590
+ try { html5QrCode.stop(); } catch(e) {}
1591
  currentScanner = null;
1592
  scannerContainer.style.display = 'none';
1593
  };
1594
+ html5QrCode.start({ facingMode: "environment" }, { fps: 10, qrbox: { width: 250, height: 250 } }, onScanSuccess);
1595
  });
1596
  });
1597
 
 
1607
  }
1608
  });
1609
  });
1610
+
1611
+ // --- Dynamic Variant Fields Logic ---
1612
+ const createVariantRow = () => {
1613
+ const div = document.createElement('div');
1614
+ div.className = 'row g-2 mb-2 align-items-center variant-row';
1615
+ div.innerHTML = `
1616
+ <input type="hidden" name="variant_id[]" value="">
1617
+ <div class="col-3"><input type="text" name="variant_name[]" class="form-control" placeholder="Название варианта" required></div>
1618
+ <div class="col"><input type="text" name="variant_price[]" class="form-control" placeholder="Цена" inputmode="decimal"></div>
1619
+ <div class="col"><input type="text" name="variant_cost_price[]" class="form-control" placeholder="Себестоимость" inputmode="decimal"></div>
1620
+ <div class="col"><input type="number" name="variant_stock[]" class="form-control" placeholder="Остаток" value="0"></div>
1621
+ <div class="col-auto"><button type="button" class="btn btn-sm btn-danger remove-variant-btn"><i class="fas fa-times"></i></button></div>
1622
+ `;
1623
+ div.querySelector('.remove-variant-btn').addEventListener('click', () => div.remove());
1624
+ return div;
1625
+ };
1626
+
1627
+ document.getElementById('add-variant-btn-add').addEventListener('click', () => {
1628
+ document.getElementById('variants-container-add').appendChild(createVariantRow());
1629
+ });
1630
+
1631
+ document.querySelectorAll('.add-variant-btn-edit').forEach(btn => {
1632
+ btn.addEventListener('click', (e) => {
1633
+ const containerId = e.target.dataset.targetContainer;
1634
+ document.getElementById(containerId).appendChild(createVariantRow());
1635
+ });
1636
+ });
1637
+
1638
+ document.querySelectorAll('.remove-variant-btn').forEach(btn => {
1639
+ btn.addEventListener('click', e => e.target.closest('.variant-row').remove());
1640
+ });
1641
+
1642
+ // Auto-add first variant row on add modal show
1643
+ const addProductModal = document.getElementById('addProductModal');
1644
+ addProductModal.addEventListener('shown.bs.modal', () => {
1645
+ const container = document.getElementById('variants-container-add');
1646
+ if (container.children.length === 0) {
1647
+ container.appendChild(createVariantRow());
1648
+ }
1649
+ });
1650
+
1651
+ // --- Stock In Modal Logic ---
1652
+ const inventoryData = JSON.parse('{{ inventory|tojson|safe }}');
1653
+ const productSelect = document.getElementById('stockin-product');
1654
+ const variantSelect = document.getElementById('stockin-variant');
1655
+
1656
+ productSelect.addEventListener('change', () => {
1657
+ const productId = productSelect.value;
1658
+ variantSelect.innerHTML = '<option value="">-- Выберите вариант --</option>';
1659
+ variantSelect.disabled = true;
1660
+
1661
+ if (productId) {
1662
+ const product = inventoryData.find(p => p.id === productId);
1663
+ if (product && product.variants) {
1664
+ product.variants.forEach(v => {
1665
+ const option = document.createElement('option');
1666
+ option.value = v.id;
1667
+ option.textContent = v.option_value;
1668
+ variantSelect.appendChild(option);
1669
+ });
1670
+ variantSelect.disabled = false;
1671
+ }
1672
+ }
1673
+ });
1674
  });
1675
  </script>
1676
  """
 
1788
 
1789
  REPORTS_SCRIPTS = ""
1790
 
1791
+ PRODUCT_ROI_CONTENT = """
1792
  <div class="card">
1793
+ <div class="card-header"><h5 class="mb-0">Окупаемость по товарам</h5></div>
 
 
1794
  <div class="card-body p-0">
1795
  <div class="table-responsive">
1796
  <table class="table table-hover table-sm mb-0">
1797
+ <thead class="table-light">
1798
  <tr>
1799
+ <th>Товар (вариант)</th>
1800
  <th class="text-end">Продано, шт</th>
1801
  <th class="text-end">Выручка</th>
1802
+ <th class="text-end">Стоимость на складе</th>
1803
+ <th class="text-end">Общие вложения</th>
1804
+ <th class="text-end">Результат (Окупаемость)</th>
 
1805
  </tr>
1806
  </thead>
1807
  <tbody>
1808
+ {% for item in stats %}
1809
+ <tr>
1810
+ <td><strong>{{ item.name }}</strong><br><small class="text-muted">{{ item.variant_name }}</small></td>
1811
+ <td class="text-end">{{ item.total_qty_sold }}</td>
1812
+ <td class="text-end">{{ format_currency_py(item.total_revenue) }} с</td>
1813
+ <td class="text-end">{{ format_currency_py(item.inventory_value) }} с</td>
1814
+ <td class="text-end text-secondary">{{ format_currency_py(item.total_investment) }} с</td>
1815
+ <td class="text-end fw-bold
1816
+ {% if item.payback > 0 %}payback-positive
1817
+ {% elif item.payback < 0 %}payback-negative
1818
+ {% else %}payback-zero{% endif %}">
1819
+ {{ format_currency_py(item.payback) }} с
1820
+ </td>
 
 
1821
  </tr>
1822
  {% else %}
1823
+ <tr><td colspan="6" class="text-center">Нет данных для анализа.</td></tr>
1824
  {% endfor %}
1825
  </tbody>
1826
  </table>
1827
  </div>
1828
  </div>
1829
  <div class="card-footer small text-muted">
1830
+ <i class="fas fa-info-circle me-1"></i>
1831
+ <strong>Общие вложения</strong> = Себестоимость проданных товаров + Стоимость текущих остатков на складе.
1832
+ <strong>Результат</strong> = Выручка - Общие вложения.
 
 
 
 
1833
  </div>
1834
  </div>
1835
  """