Kgshop commited on
Commit
c8243ac
·
verified ·
1 Parent(s): e33c84a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +477 -459
app.py CHANGED
@@ -136,15 +136,21 @@ def find_item_by_field(data, field, value):
136
  if isinstance(item, dict) and item.get(field) == value:
137
  return item
138
  return None
 
 
 
139
 
140
  def find_product_by_id(inventory, product_id):
141
  return find_item_by_field(inventory, 'id', product_id)
142
 
143
- def find_variant_in_product(product, variant_id):
144
- if product and 'variants' in product:
145
- return find_item_by_field(product['variants'], 'id', variant_id)
146
- return None
147
-
 
 
 
148
  def find_user_by_pin(pin):
149
  users = load_json_data('users')
150
  return find_item_by_field(users, 'pin', pin)
@@ -161,7 +167,7 @@ def generate_receipt_html(transaction):
161
  for item in transaction['items']:
162
  items_html += f"""
163
  <tr>
164
- <td>{item['name']}</td>
165
  <td style="text-align: right;">{item['quantity']}</td>
166
  <td style="text-align: right;">{format_currency_py(item['price_at_sale'])}</td>
167
  <td style="text-align: right;">{format_currency_py(item['total'])}</td>
@@ -222,47 +228,104 @@ def sales_screen():
222
  users = load_json_data('users')
223
  kassas = load_json_data('kassas')
224
 
225
- active_products = []
226
  for p in inventory:
227
- if isinstance(p, dict) and 'variants' in p and any(v.get('stock', 0) > 0 for v in p['variants']):
228
- active_products.append(p)
229
-
230
- active_products.sort(key=lambda x: x.get('name', '').lower())
 
 
 
 
 
 
 
 
 
 
231
  html = BASE_TEMPLATE.replace('__TITLE__', "Касса").replace('__CONTENT__', SALES_SCREEN_CONTENT).replace('__SCRIPTS__', SALES_SCREEN_SCRIPTS)
232
- return render_template_string(html, inventory=active_products, users=users, kassas=kassas)
233
 
234
  @app.route('/inventory', methods=['GET', 'POST'])
235
  def inventory_management():
236
  if request.method == 'POST':
237
- try:
 
 
 
238
  name = request.form.get('name', '').strip()
239
  barcode = request.form.get('barcode', '').strip()
240
- price = to_decimal(request.form.get('price', '0'))
241
-
242
- if not name or not barcode or price <= 0:
243
- flash("Название, штрих-код и цена - обязательные поля.", "danger")
244
- return redirect(url_for('inventory_management'))
245
-
246
- inventory = load_json_data('inventory')
247
- if find_item_by_field(inventory, 'barcode', barcode):
248
  flash(f"Товар со штрих-кодом {barcode} уже существует.", "warning")
249
- return redirect(url_for('inventory_management'))
250
-
251
- new_product = {
252
- 'id': uuid.uuid4().hex,
253
- 'name': name,
254
- 'barcode': barcode,
255
- 'price': str(price),
256
- 'timestamp_added': get_current_time().isoformat(),
257
- 'timestamp_updated': get_current_time().isoformat(),
258
- 'variants': []
259
- }
260
- inventory.append(new_product)
261
- save_json_data('inventory', inventory)
262
- upload_db_to_hf('inventory')
263
- flash(f"Базовый товар '{name}' успешно добавлен. Теперь добавьте варианты.", "success")
264
- except Exception as e:
265
- flash(f"Ошибка при добавлении товара: {e}", "danger")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  return redirect(url_for('inventory_management'))
267
 
268
  inventory_list = load_json_data('inventory')
@@ -270,44 +333,6 @@ def inventory_management():
270
  html = BASE_TEMPLATE.replace('__TITLE__', "Склад").replace('__CONTENT__', INVENTORY_CONTENT).replace('__SCRIPTS__', INVENTORY_SCRIPTS)
271
  return render_template_string(html, inventory=inventory_list)
272
 
273
- @app.route('/inventory/edit/<product_id>', methods=['POST'])
274
- def edit_product(product_id):
275
- inventory = load_json_data('inventory')
276
- product = find_product_by_id(inventory, product_id)
277
-
278
- if not product:
279
- flash("Товар не найден.", "danger")
280
- return redirect(url_for('inventory_management'))
281
-
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
-
287
- if not name or not barcode or price <= 0:
288
- flash("Название, штрих-код и цена обязательны.", "danger")
289
- return redirect(url_for('inventory_management'))
290
-
291
- existing_barcode = find_item_by_field(inventory, 'barcode', barcode)
292
- if existing_barcode and existing_barcode.get('id') != product_id:
293
- flash(f"Штрих-код {barcode} уже используется другим товаром.", "warning")
294
- return redirect(url_for('inventory_management'))
295
-
296
- product.update({
297
- 'name': name,
298
- 'barcode': barcode,
299
- 'price': str(price),
300
- 'timestamp_updated': get_current_time().isoformat()
301
- })
302
-
303
- save_json_data('inventory', inventory)
304
- upload_db_to_hf('inventory')
305
- flash("Товар успешно обновлен.", "success")
306
- except Exception as e:
307
- flash(f"Ошибка при обновлении товара: {e}", "danger")
308
-
309
- return redirect(url_for('inventory_management'))
310
-
311
  @app.route('/inventory/delete/<product_id>', methods=['POST'])
312
  def delete_product(product_id):
313
  inventory = load_json_data('inventory')
@@ -321,54 +346,22 @@ def delete_product(product_id):
321
  flash("Товар не найден.", "warning")
322
  return redirect(url_for('inventory_management'))
323
 
324
- @app.route('/inventory/variant', methods=['POST'])
325
- def manage_variant():
326
- product_id = request.form.get('product_id')
327
- variant_name = request.form.get('name', '').strip()
328
- cost_price = to_decimal(request.form.get('cost_price', '0'))
329
- stock = int(to_decimal(request.form.get('stock', '0')))
330
-
331
- if not product_id or not variant_name:
332
- flash("ID товара и название варианта обязательны.", "danger")
333
- return redirect(url_for('inventory_management'))
334
-
335
  inventory = load_json_data('inventory')
336
- product = find_product_by_id(inventory, product_id)
337
- if not product:
338
- flash("Базовый товар не найден.", "danger")
339
- return redirect(url_for('inventory_management'))
340
-
341
- new_variant = {
342
- 'id': uuid.uuid4().hex,
343
- 'name': variant_name,
344
- 'cost_price': str(cost_price),
345
- 'stock': stock
346
- }
347
-
348
- if 'variants' not in product:
349
- product['variants'] = []
350
- product['variants'].append(new_variant)
351
- product['timestamp_updated'] = get_current_time().isoformat()
352
-
353
- if stock > 0:
354
- stock_movements = load_json_data('stock_movements')
355
- stock_movements.append({
356
- 'id': uuid.uuid4().hex,
357
- 'timestamp': get_current_time().isoformat(),
358
- 'type': 'inbound',
359
- 'product_id': product_id,
360
- 'variant_id': new_variant['id'],
361
- 'quantity': stock,
362
- 'cost_price': str(cost_price),
363
- 'description': 'Начальный остаток'
364
- })
365
- save_json_data('stock_movements', stock_movements)
366
- upload_db_to_hf('stock_movements')
367
-
368
- save_json_data('inventory', inventory)
369
- upload_db_to_hf('inventory')
370
-
371
- flash(f"Вариант '{variant_name}' добавлен к товару '{product['name']}'.", "success")
372
  return redirect(url_for('inventory_management'))
373
 
374
  @app.route('/inventory/receive', methods=['POST'])
@@ -376,66 +369,59 @@ def receive_stock():
376
  variant_id = request.form.get('variant_id')
377
  quantity = int(to_decimal(request.form.get('quantity', '0')))
378
  cost_price = to_decimal(request.form.get('cost_price', '0'))
 
379
 
380
  if not variant_id or quantity <= 0:
381
  flash("Выберите вариант и укажите положительное количество.", "danger")
382
  return redirect(url_for('inventory_management'))
383
-
384
  inventory = load_json_data('inventory')
385
  stock_movements = load_json_data('stock_movements')
386
-
387
- variant_found = False
388
- for product in inventory:
389
- variant = find_variant_in_product(product, variant_id)
390
- if variant:
391
- variant['stock'] += quantity
392
- variant['cost_price'] = str(cost_price)
393
- product['timestamp_updated'] = get_current_time().isoformat()
394
-
395
- stock_movements.append({
396
- 'id': uuid.uuid4().hex,
397
- 'timestamp': get_current_time().isoformat(),
398
- 'type': 'inbound',
399
- 'product_id': product['id'],
400
- 'variant_id': variant['id'],
401
- 'quantity': quantity,
402
- 'cost_price': str(cost_price),
403
- 'description': 'Приход товара'
404
- })
405
- variant_found = True
406
- break
407
-
408
- if variant_found:
409
- save_json_data('inventory', inventory)
410
- save_json_data('stock_movements', stock_movements)
411
- upload_db_to_hf('inventory')
412
- upload_db_to_hf('stock_movements')
413
- flash("Остатки успешно обновлены.", "success")
414
- else:
415
  flash("Вариант товара не найден.", "danger")
416
-
417
- return redirect(url_for('inventory_management'))
 
 
 
 
418
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
419
 
420
  @app.route('/api/product_by_barcode/<barcode>')
421
  def get_product_by_barcode(barcode):
422
  inventory = load_json_data('inventory')
423
- product = find_item_by_field(inventory, 'barcode', barcode)
424
- if product:
425
- active_variants = [v for v in product.get('variants', []) if v.get('stock', 0) > 0]
426
- if active_variants:
427
- product_copy = product.copy()
428
- product_copy['variants'] = active_variants
429
- return jsonify({'success': True, 'product': product_copy})
430
- else:
431
- return jsonify({'success': False, 'message': 'Товар закончился на складе'}), 404
432
- return jsonify({'success': False, 'message': 'Товар не найден'}), 404
433
 
434
  @app.route('/api/complete_sale', methods=['POST'])
435
  def complete_sale():
436
  try:
437
  data = request.get_json()
438
- cart = data.get('cart', [])
439
  user_id = data.get('userId')
440
  kassa_id = data.get('kassaId')
441
  payment_method = data.get('paymentMethod', 'cash')
@@ -453,38 +439,38 @@ def complete_sale():
453
  if not user or not kassa:
454
  return jsonify({'success': False, 'message': 'Кассир или касса не найдены.'}), 404
455
 
456
- variant_map = {v['id']: (p, v) for p in inventory for v in p.get('variants', [])}
457
  sale_items = []
458
  total_amount = Decimal('0.00')
459
- inventory_updates = {}
460
 
461
  for variant_id, cart_item in cart.items():
462
- if variant_id not in variant_map:
463
- return jsonify({'success': False, 'message': f"Товар с ID {variant_id} не найден."}), 404
 
464
 
465
- product, variant = variant_map[variant_id]
466
  quantity_sold = cart_item['quantity']
467
  current_stock = variant.get('stock', 0)
468
 
469
  if quantity_sold > current_stock:
470
- return jsonify({'success': False, 'message': f"Недостаточно товара '{product['name']} ({variant['name']})'. В наличии: {current_stock}"}), 400
471
 
472
- price_at_sale = to_decimal(product.get('price', '0'))
473
  cost_price_at_sale = to_decimal(variant.get('cost_price', '0'))
474
  item_total = price_at_sale * Decimal(quantity_sold)
475
  total_amount += item_total
476
 
477
  sale_items.append({
478
  'product_id': product['id'],
 
479
  'variant_id': variant_id,
480
- 'name': f"{product['name']} ({variant['name']})",
481
  'barcode': product.get('barcode'),
482
  'quantity': quantity_sold,
483
  'price_at_sale': str(price_at_sale),
484
  'cost_price_at_sale': str(cost_price_at_sale),
485
  'total': str(item_total)
486
  })
487
- inventory_updates[variant_id] = current_stock - quantity_sold
488
 
489
  now_iso = get_current_time().isoformat()
490
 
@@ -506,11 +492,11 @@ def complete_sale():
506
  new_transaction['receipt_html'] = generate_receipt_html(new_transaction)
507
  transactions = load_json_data('transactions')
508
  transactions.append(new_transaction)
509
-
510
  for p in inventory:
511
  for v in p.get('variants', []):
512
  if v['id'] in inventory_updates:
513
- v['stock'] = inventory_updates[v['id']]
514
  p['timestamp_updated'] = now_iso
515
 
516
  if payment_method == 'cash':
@@ -519,9 +505,7 @@ def complete_sale():
519
  current_balance = to_decimal(k.get('balance', '0'))
520
  kassas[i]['balance'] = str(current_balance + total_amount)
521
  kassas[i].setdefault('history', []).append({
522
- 'type': 'sale',
523
- 'amount': str(total_amount),
524
- 'timestamp': now_iso,
525
  'transaction_id': new_transaction['id']
526
  })
527
  break
@@ -584,12 +568,16 @@ def reports():
584
  if start_date <= datetime.fromisoformat(e['timestamp']) < end_date
585
  ]
586
 
587
- total_revenue = sum(to_decimal(t['total_amount']) for t in filtered_transactions)
 
 
 
588
  total_cogs = sum(
589
  to_decimal(item.get('cost_price_at_sale', '0')) * to_decimal(str(item['quantity']))
590
- for t in filtered_transactions for item in t['items']
591
  )
592
- gross_profit = total_revenue - total_cogs
 
593
  total_expenses = sum(to_decimal(e['amount']) for e in filtered_expenses)
594
 
595
  sales_by_cashier = defaultdict(lambda: {'count': 0, 'total': Decimal(0)})
@@ -606,7 +594,7 @@ def reports():
606
  cashier_payouts = defaultdict(Decimal)
607
  for t in filtered_transactions:
608
  user = find_item_by_field(users, 'id', t.get('user_id'))
609
- if user:
610
  payment_type = user.get('payment_type')
611
  payment_value = to_decimal(user.get('payment_value', '0'))
612
  if payment_type == 'percentage' and payment_value > 0:
@@ -625,7 +613,7 @@ def reports():
625
  net_profit = gross_profit - total_expenses - total_salary_expenses
626
 
627
  stats = {
628
- 'total_revenue': total_revenue,
629
  'total_cogs': total_cogs,
630
  'gross_profit': gross_profit,
631
  'total_expenses': total_expenses,
@@ -640,62 +628,53 @@ def reports():
640
  html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS)
641
  return render_template_string(html, stats=stats, start_date=start_date_str, end_date=end_date_str, expenses=filtered_expenses)
642
 
643
- @app.route('/reports/profitability')
644
- def profitability_report():
645
  inventory = load_json_data('inventory')
646
  transactions = load_json_data('transactions')
647
  stock_movements = load_json_data('stock_movements')
648
 
649
- profit_data = defaultdict(lambda: {
650
- 'invested': Decimal(0),
651
- 'revenue': Decimal(0),
652
- 'stock_value': Decimal(0),
653
- 'name': '',
654
- 'barcode': ''
 
655
  })
656
 
657
  for movement in stock_movements:
658
- if movement.get('type') == 'inbound':
659
- product_id = movement.get('product_id')
660
- if product_id:
661
- quantity = to_decimal(str(movement.get('quantity', 0)))
662
- cost = to_decimal(movement.get('cost_price', 0))
663
- profit_data[product_id]['invested'] += quantity * cost
664
 
665
  for t in transactions:
666
- for item in t.get('items', []):
667
- product_id = item.get('product_id')
668
- if product_id:
669
- amount = to_decimal(item.get('total', 0))
670
- profit_data[product_id]['revenue'] += amount
 
671
 
672
- for p in inventory:
673
- product_id = p.get('id')
674
- if product_id:
675
- profit_data[product_id]['name'] = p.get('name', 'N/A')
676
- profit_data[product_id]['barcode'] = p.get('barcode', 'N/A')
677
- for v in p.get('variants', []):
678
- stock = to_decimal(str(v.get('stock', 0)))
679
- cost = to_decimal(v.get('cost_price', 0))
680
- profit_data[product_id]['stock_value'] += stock * cost
681
-
682
- report_list = []
683
- for product_id, data in profit_data.items():
684
- if not data['name']: continue
685
- net_position = data['revenue'] + data['stock_value'] - data['invested']
686
- report_list.append({
687
- 'name': data['name'],
688
- 'barcode': data['barcode'],
689
- 'invested': data['invested'],
690
- 'revenue': data['revenue'],
691
- 'stock_value': data['stock_value'],
692
- 'net_position': net_position
693
- })
694
-
695
- report_list.sort(key=lambda x: x['net_position'], reverse=True)
696
-
697
- html = BASE_TEMPLATE.replace('__TITLE__', "Окупаемость товаров").replace('__CONTENT__', PROFITABILITY_CONTENT).replace('__SCRIPTS__', "")
698
- return render_template_string(html, report_data=report_list)
699
 
700
  @app.route('/admin', methods=['GET'])
701
  def admin_panel():
@@ -908,11 +887,10 @@ def return_transaction(transaction_id):
908
  total_amount = to_decimal(original_transaction['total_amount'])
909
 
910
  return_items = []
911
- inventory_updates = {}
912
  for item in original_transaction['items']:
913
  return_items.append({**item, 'quantity': -item['quantity'], 'total': str(-to_decimal(item['total']))})
914
- if item.get('variant_id'):
915
- inventory_updates[item['variant_id']] = item['quantity']
916
 
917
  now_iso = get_current_time().isoformat()
918
  return_transaction = {
@@ -1011,15 +989,15 @@ BASE_TEMPLATE = """
1011
  .sidebar .nav-link { color: rgba(255,255,255,.75); }
1012
  .sidebar .nav-link:hover, .sidebar .nav-link.active { color: #fff; }
1013
  .main-content { margin-left: var(--sidebar-width); padding: 1.5rem; }
1014
- .sub-nav-link { padding-left: 2.5rem !important; font-size: 0.9em; }
1015
  @media (max-width: 992px) {
1016
  .sidebar { transform: translateX(calc(-1 * var(--sidebar-width))); transition: transform 0.3s ease-in-out; z-index: 1040; }
1017
  .sidebar.active { transform: translateX(0); }
1018
  .main-content { margin-left: 0; }
1019
  }
1020
  [data-bs-theme="dark"] body { background-color: #212529; color: #dee2e6; }
1021
- [data-bs-theme="dark"] .card, [data-bs-theme="dark"] .list-group-item, [data-bs-theme="dark"] .table, [data-bs-theme="dark"] .modal-content { background-color: #343a40; }
1022
  [data-bs-theme="dark"] .table-hover>tbody>tr:hover>* { color: var(--bs-table-hover-color); background-color: rgba(255, 255, 255, 0.075); }
 
1023
  </style>
1024
  </head>
1025
  <body>
@@ -1031,17 +1009,8 @@ BASE_TEMPLATE = """
1031
  <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>
1032
  <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>
1033
  <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>
1034
- <li class="nav-item">
1035
- <a class="nav-link {% if request.endpoint in ['reports', 'profitability_report'] %}active{% endif %}" data-bs-toggle="collapse" href="#reports-submenu" role="button" aria-expanded="false" aria-controls="reports-submenu">
1036
- <i class="fas fa-fw fa-chart-line me-2"></i>Отчеты
1037
- </a>
1038
- <div class="collapse {% if request.endpoint in ['reports', 'profitability_report'] %}show{% endif %}" id="reports-submenu">
1039
- <ul class="nav flex-column">
1040
- <li><a class="nav-link sub-nav-link {% if request.endpoint == 'reports' %}active{% endif %}" href="{{ url_for('reports') }}">Сводный отчет</a></li>
1041
- <li><a class="nav-link sub-nav-link {% if request.endpoint == 'profitability_report' %}active{% endif %}" href="{{ url_for('profitability_report') }}">Окупаемость</a></li>
1042
- </ul>
1043
- </div>
1044
- </li>
1045
  <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>
1046
  <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>
1047
  </ul>
@@ -1098,16 +1067,6 @@ BASE_TEMPLATE = """
1098
  </div>
1099
  </div>
1100
 
1101
- <div class="modal fade" id="variantSelectionModal" tabindex="-1" aria-hidden="true">
1102
- <div class="modal-dialog modal-dialog-centered">
1103
- <div class="modal-content">
1104
- <div class="modal-header"><h5 class="modal-title" id="variantModalLabel">Выберите вариант</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1105
- <div class="modal-body" id="variantModalBody"></div>
1106
- </div>
1107
- </div>
1108
- </div>
1109
-
1110
-
1111
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
1112
  <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
1113
  <script>
@@ -1150,11 +1109,18 @@ SALES_SCREEN_CONTENT = """
1150
  </div>
1151
  <input type="text" id="product-search" class="form-control mb-3" placeholder="Поиск по названию или штрих-коду...">
1152
  <div id="product-grid" class="d-grid gap-2" style="grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));">
1153
- {% for p in inventory %}
1154
- <div class="card text-center product-card" data-barcode="{{ p.barcode }}">
 
 
 
 
 
 
1155
  <div class="card-body p-2">
1156
- <h6 class="card-title small mb-1">{{ p.name }}</h6>
1157
- <p class="card-text fw-bold mb-0">{{ format_currency_py(p.price) }} с</p>
 
1158
  </div>
1159
  </div>
1160
  {% endfor %}
@@ -1183,6 +1149,17 @@ SALES_SCREEN_CONTENT = """
1183
  </div>
1184
  </div>
1185
  </div>
 
 
 
 
 
 
 
 
 
 
 
1186
  """
1187
 
1188
  SALES_SCREEN_SCRIPTS = """
@@ -1192,10 +1169,11 @@ document.addEventListener('DOMContentLoaded', () => {
1192
  const productGrid = document.getElementById('product-grid');
1193
  const cartItemsEl = document.getElementById('cart-items');
1194
  const cartTotalEl = document.getElementById('cart-total');
 
 
1195
  let audioCtx;
1196
  let isScannerPaused = false;
1197
  const receiptModal = new bootstrap.Modal(document.getElementById('receiptModal'));
1198
- const variantSelectionModal = new bootstrap.Modal(document.getElementById('variantSelectionModal'));
1199
 
1200
  function playBeep() {
1201
  if (!audioCtx) {
@@ -1226,7 +1204,7 @@ document.addEventListener('DOMContentLoaded', () => {
1226
  cartItemsEl.innerHTML += `
1227
  <div class="list-group-item d-flex justify-content-between align-items-center">
1228
  <div>
1229
- <h6 class="mb-0 small">${item.name}</h6>
1230
  <small>${item.quantity} x ${item.price} с</small>
1231
  </div>
1232
  <div>
@@ -1238,62 +1216,65 @@ document.addEventListener('DOMContentLoaded', () => {
1238
  cartTotalEl.textContent = total.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' с';
1239
  };
1240
 
1241
- const addToCart = (product, variant) => {
1242
- const variantId = variant.id;
1243
- if (cart[variantId]) {
1244
- cart[variantId].quantity++;
1245
  } else {
1246
- cart[variantId] = {
1247
- name: `${product.name} (${variant.name})`,
1248
- price: String(product.price).replace('.',','),
 
1249
  quantity: 1
1250
  };
1251
  }
1252
  playBeep();
1253
  updateCartView();
1254
  };
1255
-
1256
  const handleProductSelection = (product) => {
1257
  if (product.variants.length === 1) {
1258
- addToCart(product, product.variants[0]);
 
 
 
 
 
1259
  } else {
1260
- const modalBody = document.getElementById('variantModalBody');
1261
- document.getElementById('variantModalLabel').textContent = `Выберите вариант для "${product.name}"`;
1262
- let buttonsHtml = '<div class="d-grid gap-2">';
1263
- product.variants.forEach(variant => {
1264
- buttonsHtml += `<button class="btn btn-outline-primary variant-select-btn" data-product='${JSON.stringify(product)}' data-variant='${JSON.stringify(variant)}'>${variant.name} (Остаток: ${variant.stock})</button>`;
 
 
 
 
 
 
 
 
 
 
1265
  });
1266
- buttonsHtml += '</div>';
1267
- modalBody.innerHTML = buttonsHtml;
1268
- variantSelectionModal.show();
 
 
1269
  }
1270
  };
1271
 
1272
- document.getElementById('variantModalBody').addEventListener('click', e => {
1273
- if (e.target.classList.contains('variant-select-btn')) {
1274
- const product = JSON.parse(e.target.dataset.product);
1275
- const variant = JSON.parse(e.target.dataset.variant);
1276
- addToCart(product, variant);
1277
- variantSelectionModal.hide();
1278
- }
1279
- });
1280
-
1281
- const findAndAddProduct = (barcode) => {
1282
- fetch(`/api/product_by_barcode/${barcode}`)
1283
- .then(res => res.json())
1284
- .then(data => {
1285
- if (data.success) {
1286
- handleProductSelection(data.product);
1287
- } else {
1288
- alert(data.message);
1289
- }
1290
- });
1291
- }
1292
-
1293
  productGrid.addEventListener('click', e => {
1294
  const card = e.target.closest('.product-card');
1295
  if (card) {
1296
- findAndAddProduct(card.dataset.barcode);
 
 
 
 
 
 
 
1297
  }
1298
  });
1299
 
@@ -1317,8 +1298,7 @@ document.addEventListener('DOMContentLoaded', () => {
1317
  document.getElementById('product-search').addEventListener('input', e => {
1318
  const term = e.target.value.toLowerCase();
1319
  document.querySelectorAll('.product-card').forEach(card => {
1320
- const productName = card.querySelector('.card-title').textContent.toLowerCase();
1321
- const show = productName.includes(term) || card.dataset.barcode.includes(term);
1322
  card.style.display = show ? '' : 'none';
1323
  });
1324
  });
@@ -1378,14 +1358,23 @@ document.addEventListener('DOMContentLoaded', () => {
1378
  scannerStatusEl.textContent = 'Пауза...';
1379
  scannerStatusEl.style.display = 'block';
1380
  if (html5QrCode.getState() === 2) html5QrCode.pause();
1381
-
1382
- findAndAddProduct(decodedText);
1383
 
1384
- setTimeout(() => {
1385
- isScannerPaused = false;
1386
- scannerStatusEl.style.display = 'none';
1387
- if (html5QrCode.getState() === 2) html5QrCode.resume();
1388
- }, 1500);
 
 
 
 
 
 
 
 
 
 
 
1389
  };
1390
 
1391
  const startScanner = () => {
@@ -1416,126 +1405,163 @@ document.addEventListener('DOMContentLoaded', () => {
1416
  INVENTORY_CONTENT = """
1417
  <div class="d-flex justify-content-between mb-3">
1418
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addProductModal"><i class="fas fa-plus me-2"></i>Добавить товар</button>
1419
- <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#receiveStockModal"><i class="fas fa-truck-loading me-2"></i>Приход товара</button>
1420
  </div>
1421
  <div class="accordion" id="inventoryAccordion">
1422
- {% for p in inventory %}
1423
  <div class="accordion-item">
1424
  <h2 class="accordion-header" id="heading-{{ p.id }}">
1425
- <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-{{ p.id }}" aria-expanded="false" aria-controls="collapse-{{ p.id }}">
1426
- <div class="w-100 d-flex justify-content-between align-items-center pe-3">
1427
- <span><strong>{{ p.name }}</strong> <small class="text-muted">#{{ p.barcode }}</small></span>
1428
- <span class="fw-bold">{{ format_currency_py(p.price) }} с</span>
1429
- </div>
1430
  </button>
1431
  </h2>
1432
- <div id="collapse-{{ p.id }}" class="accordion-collapse collapse" aria-labelledby="heading-{{ p.id }}" 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 me-2" data-bs-toggle="modal" data-bs-target="#editProductModal-{{ p.id }}"><i class="fas fa-edit"></i> Ред. товар</button>
1436
- <form action="{{ url_for('delete_product', product_id=p.id) }}" method="POST" class="d-inline me-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
- <button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#addVariantModal-{{ p.id }}"><i class="fas fa-plus"></i> Добавить вариант</button>
1440
- </div>
1441
- <table class="table table-sm table-bordered">
1442
- <thead><tr><th>Вариант</th><th>Себестоимость</th><th>Остаток</th></tr></thead>
1443
- <tbody>
1444
- {% for v in p.variants %}
1445
- <tr><td>{{v.name}}</td><td>{{format_currency_py(v.cost_price)}} с</td><td>{{v.stock}}</td></tr>
1446
- {% else %}
1447
- <tr><td colspan="3" class="text-center text-muted">Варианты не добавлены</td></tr>
1448
- {% endfor %}
1449
- </tbody>
1450
- </table>
 
 
 
 
 
 
 
 
 
 
 
1451
  </div>
1452
  </div>
1453
  </div>
1454
- {% endfor %}
 
 
1455
  </div>
1456
 
1457
  <!-- Modals -->
1458
- <div class="modal fade" id="addProductModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
1459
- <div class="modal-header"><h5 class="modal-title">Новый товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1460
- <form action="{{ url_for('inventory_management') }}" method="POST">
1461
- <div class="modal-body">
1462
- <div class="mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" required></div>
1463
- <div class="mb-3"><label class="form-label">Штрих-код</label><input type="text" name="barcode" class="form-control barcode-input" required></div>
1464
- <div class="mb-3"><label class="form-label">Цена продажи</label><input type="text" name="price" class="form-control" inputmode="decimal" required></div>
1465
- </div>
1466
- <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
1467
- </form></div></div></div>
1468
-
1469
- <div class="modal fade" id="receiveStockModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
1470
- <div class="modal-header"><h5 class="modal-title">Приход товара</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1471
- <form action="{{ url_for('receive_stock') }}" method="POST">
1472
- <div class="modal-body">
1473
- <div class="mb-3">
1474
- <label class="form-label">Товар</label>
1475
- <select id="receive-product-select" class="form-select" required>
1476
- <option value="">-- Выберите товар --</option>
1477
- {% for p in inventory %}<option value="{{ p.id }}">{{ p.name }}</option>{% endfor %}
1478
- </select>
1479
  </div>
1480
- <div class="mb-3">
1481
- <label class="form-label">Вариант</label>
1482
- <select name="variant_id" id="receive-variant-select" class="form-select" required></select>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1483
  </div>
1484
- <div class="mb-3"><label class="form-label">Количество</label><input type="number" name="quantity" class="form-control" step="1" required></div>
1485
- <div class="mb-3"><label class="form-label">Новая себестоимость (за 1 шт)</label><input type="text" name="cost_price" class="form-control" inputmode="decimal" required></div>
1486
  </div>
1487
- <div class="modal-footer"><button type="submit" class="btn btn-primary">Оприходовать</button></div>
1488
- </form></div></div></div>
1489
 
1490
  {% for p in inventory %}
1491
- <div class="modal fade" id="editProductModal-{{ p.id }}" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
1492
- <div class="modal-header"><h5 class="modal-title">Редактировать товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1493
- <form action="{{ url_for('edit_product', product_id=p.id) }}" method="POST">
1494
- <div class="modal-body">
1495
- <div class="mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" value="{{ p.name }}" required></div>
1496
- <div class="mb-3"><label class="form-label">Штрих-код</label><input type="text" name="barcode" class="form-control" value="{{ p.barcode }}" required></div>
1497
- <div class="mb-3"><label class="form-label">Цена продажи</label><input type="text" name="price" class="form-control" value="{{ p.price|string|replace('.', ',') }}" inputmode="decimal" required></div>
 
 
 
 
 
 
 
 
1498
  </div>
1499
- <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
1500
- </form></div></div></div>
1501
-
1502
- <div class="modal fade" id="addVariantModal-{{ p.id }}" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
1503
- <div class="modal-header"><h5 class="modal-title">Новый вариант для "{{p.name}}"</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1504
- <form action="{{ url_for('manage_variant') }}" method="POST">
1505
- <input type="hidden" name="product_id" value="{{ p.id }}">
1506
- <div class="modal-body">
1507
- <div class="mb-3"><label class="form-label">Название варианта (напр. Красный, XL)</label><input type="text" name="name" class="form-control" required></div>
1508
- <div class="mb-3"><label class="form-label">Себестоимость</label><input type="text" name="cost_price" class="form-control" value="0" inputmode="decimal"></div>
1509
- <div class="mb-3"><label class="form-label">Начальный остаток</label><input type="number" name="stock" class="form-control" value="0" step="1"></div>
 
 
 
 
 
 
 
 
 
1510
  </div>
1511
- <div class="modal-footer"><button type="submit" class="btn btn-primary">Добавить вариант</button></div>
1512
- </form></div></div></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1513
  {% endfor %}
1514
  """
1515
 
1516
- INVENTORY_SCRIPTS = """
1517
- <script>
1518
- document.addEventListener('DOMContentLoaded', () => {
1519
- const inventoryData = {{ inventory|tojson }};
1520
- const productSelect = document.getElementById('receive-product-select');
1521
- const variantSelect = document.getElementById('receive-variant-select');
1522
-
1523
- productSelect.addEventListener('change', e => {
1524
- const productId = e.target.value;
1525
- variantSelect.innerHTML = '<option value="">-- Выберите вариант --</option>';
1526
- if (productId) {
1527
- const product = inventoryData.find(p => p.id === productId);
1528
- if (product && product.variants) {
1529
- product.variants.forEach(v => {
1530
- const option = new Option(`${v.name} (текущий остаток: ${v.stock})`, v.id);
1531
- variantSelect.add(option);
1532
- });
1533
- }
1534
- }
1535
- });
1536
- });
1537
- </script>
1538
- """
1539
 
1540
  TRANSACTIONS_CONTENT = """
1541
  <div class="card">
@@ -1546,15 +1572,15 @@ TRANSACTIONS_CONTENT = """
1546
  <tbody>
1547
  {% for t in transactions %}
1548
  <tr class="{% if t.type == 'return' %}table-danger{% endif %}">
1549
- <td><a href="{{ url_for('view_receipt', transaction_id=t.id) if t.type == 'sale' and t.receipt_html else '#' }}" target="_blank"><small class="text-muted">{{ t.id[:8] }}</small></a></td>
1550
  <td>{{ t.timestamp[:16]|replace('T', ' ') }}</td>
1551
  <td><span class="badge bg-{{'primary' if t.type == 'sale' else 'warning'}}">{{'Продажа' if t.type == 'sale' else 'Возврат'}}</span></td>
1552
  <td>{{ t.user_name }}</td><td>{{ t.kassa_name }}</td>
1553
  <td class="fw-bold">{{ format_currency_py(t.total_amount) }} с</td>
1554
- <td><span class="badge bg-{{'success' if t.status == 'completed' else ('secondary' if t.status != 'returned' else 'dark') }}">{{t.status}}</span></td>
1555
  <td>
1556
  <ul class="list-unstyled mb-0 small">
1557
- {% for item in t['items'] %}<li>{{ item.name }} ({{ item.quantity }}x{{ format_currency_py(item.price_at_sale) }})</li>{% endfor %}
1558
  </ul>
1559
  </td>
1560
  </tr>
@@ -1568,53 +1594,6 @@ TRANSACTIONS_CONTENT = """
1568
 
1569
  TRANSACTIONS_SCRIPTS = ""
1570
 
1571
- PROFITABILITY_CONTENT = """
1572
- <div class="card">
1573
- <div class="card-header"><h5 class="mb-0">Окупаемость по товарам</h5></div>
1574
- <div class="card-body p-0">
1575
- <div class="table-responsive">
1576
- <table class="table table-hover table-sm mb-0">
1577
- <thead>
1578
- <tr>
1579
- <th>Товар</th>
1580
- <th class="text-end">Вложено</th>
1581
- <th class="text-end">Выручка</th>
1582
- <th class="text-end">Стоимость остатков</th>
1583
- <th class="text-end">Результат</th>
1584
- </tr>
1585
- </thead>
1586
- <tbody>
1587
- {% for item in report_data %}
1588
- <tr class="
1589
- {% if item.net_position > 0 %} table-success
1590
- {% elif item.net_position < 0 %} table-danger
1591
- {% endif %}
1592
- ">
1593
- <td>
1594
- <strong>{{ item.name }}</strong>
1595
- <br><small class="text-muted">#{{ item.barcode }}</small>
1596
- </td>
1597
- <td class="text-end">{{ format_currency_py(item.invested) }} с</td>
1598
- <td class="text-end">{{ format_currency_py(item.revenue) }} с</td>
1599
- <td class="text-end">{{ format_currency_py(item.stock_value) }} с</td>
1600
- <td class="text-end fw-bold">
1601
- {% if item.net_position > 0 %}+{% endif %}{{ format_currency_py(item.net_position) }} с
1602
- </td>
1603
- </tr>
1604
- {% else %}
1605
- <tr><td colspan="5" class="text-center text-muted">Нет данных для анализа.</td></tr>
1606
- {% endfor %}
1607
- </tbody>
1608
- </table>
1609
- </div>
1610
- </div>
1611
- <div class="card-footer small text-muted">
1612
- <strong>Результат</strong> = (Выручка + Стоимость остатков) - Вложено. <br>
1613
- Показывает чистую прибыль или убыток по товару, если продать все остатки по текущей себестоимости.
1614
- </div>
1615
- </div>
1616
- """
1617
-
1618
  REPORTS_CONTENT = """
1619
  <div class="card mb-4">
1620
  <div class="card-body">
@@ -1697,6 +1676,45 @@ REPORTS_CONTENT = """
1697
 
1698
  REPORTS_SCRIPTS = ""
1699
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1700
  ADMIN_CONTENT = """
1701
  <div class="row">
1702
  <div class="col-md-6 mb-4">
@@ -1886,7 +1904,7 @@ CASHIER_DASHBOARD_CONTENT = """
1886
  <td>{{ t.timestamp[:16]|replace('T', ' ') }}</td>
1887
  <td><span class="badge bg-{{'primary' if t.type == 'sale' else 'warning'}}">{{'Продажа' if t.type == 'sale' else 'Возврат'}}</span></td>
1888
  <td class="fw-bold">{{ format_currency_py(t.total_amount) }} с</td>
1889
- <td><span class="badge bg-{{'success' if t.status == 'completed' else ('secondary' if t.status != 'returned' else 'dark')}}">{{t.status}}</span></td>
1890
  <td>
1891
  {% if t.type == 'sale' and t.status == 'completed' %}
1892
  <form action="{{ url_for('return_transaction', transaction_id=t.id) }}" method="POST" onsubmit="return confirm('Оформить возврат по этому чеку?');">
 
136
  if isinstance(item, dict) and item.get(field) == value:
137
  return item
138
  return None
139
+
140
+ def find_product_by_barcode(inventory, barcode):
141
+ return find_item_by_field(inventory, 'barcode', barcode)
142
 
143
  def find_product_by_id(inventory, product_id):
144
  return find_item_by_field(inventory, 'id', product_id)
145
 
146
+ def find_variant_by_id(inventory, variant_id):
147
+ for product in inventory:
148
+ if isinstance(product, dict) and 'variants' in product:
149
+ for variant in product['variants']:
150
+ if isinstance(variant, dict) and variant.get('id') == variant_id:
151
+ return product, variant
152
+ return None, None
153
+
154
  def find_user_by_pin(pin):
155
  users = load_json_data('users')
156
  return find_item_by_field(users, 'pin', pin)
 
167
  for item in transaction['items']:
168
  items_html += f"""
169
  <tr>
170
+ <td>{item['product_name']} ({item['variant_name']})</td>
171
  <td style="text-align: right;">{item['quantity']}</td>
172
  <td style="text-align: right;">{format_currency_py(item['price_at_sale'])}</td>
173
  <td style="text-align: right;">{format_currency_py(item['total'])}</td>
 
228
  users = load_json_data('users')
229
  kassas = load_json_data('kassas')
230
 
231
+ active_variants = []
232
  for p in inventory:
233
+ if isinstance(p, dict) and 'variants' in p:
234
+ for v in p['variants']:
235
+ if isinstance(v, dict) and v.get('stock', 0) > 0:
236
+ active_variants.append({
237
+ 'product_id': p['id'],
238
+ 'product_name': p['name'],
239
+ 'barcode': p['barcode'],
240
+ 'variant_id': v['id'],
241
+ 'variant_name': v['name'],
242
+ 'price': v['price'],
243
+ 'stock': v['stock']
244
+ })
245
+ active_variants.sort(key=lambda x: (x['product_name'].lower(), x['variant_name'].lower()))
246
+
247
  html = BASE_TEMPLATE.replace('__TITLE__', "Касса").replace('__CONTENT__', SALES_SCREEN_CONTENT).replace('__SCRIPTS__', SALES_SCREEN_SCRIPTS)
248
+ return render_template_string(html, variants=active_variants, users=users, kassas=kassas)
249
 
250
  @app.route('/inventory', methods=['GET', 'POST'])
251
  def inventory_management():
252
  if request.method == 'POST':
253
+ action = request.form.get('action')
254
+ inventory = load_json_data('inventory')
255
+
256
+ if action == 'add_product':
257
  name = request.form.get('name', '').strip()
258
  barcode = request.form.get('barcode', '').strip()
259
+ if not name or not barcode:
260
+ flash("Название и штрих-код обязательны.", "danger")
261
+ elif find_product_by_barcode(inventory, barcode):
 
 
 
 
 
262
  flash(f"Товар со штрих-кодом {barcode} уже существует.", "warning")
263
+ else:
264
+ new_product = {
265
+ 'id': uuid.uuid4().hex, 'name': name, 'barcode': barcode, 'variants': [],
266
+ 'timestamp_added': get_current_time().isoformat(), 'timestamp_updated': get_current_time().isoformat()
267
+ }
268
+ inventory.append(new_product)
269
+ save_json_data('inventory', inventory)
270
+ upload_db_to_hf('inventory')
271
+ flash(f"Товар '{name}' успешно добавлен. Теперь добавьте варианты.", "success")
272
+
273
+ elif action == 'edit_product':
274
+ product_id = request.form.get('product_id')
275
+ product = find_product_by_id(inventory, product_id)
276
+ if product:
277
+ name = request.form.get('name', '').strip()
278
+ barcode = request.form.get('barcode', '').strip()
279
+ if not name or not barcode:
280
+ flash("Название и штрих-код обязательны.", "danger")
281
+ else:
282
+ existing = find_product_by_barcode(inventory, barcode)
283
+ if existing and existing['id'] != product_id:
284
+ flash(f"Штрих-код {barcode} уже используется.", "warning")
285
+ else:
286
+ product['name'] = name
287
+ product['barcode'] = barcode
288
+ product['timestamp_updated'] = get_current_time().isoformat()
289
+ save_json_data('inventory', inventory)
290
+ upload_db_to_hf('inventory')
291
+ flash("Данные товара обновлены.", "success")
292
+ else:
293
+ flash("Товар не найден.", "danger")
294
+
295
+ elif action == 'add_variant':
296
+ product_id = request.form.get('product_id')
297
+ product = find_product_by_id(inventory, product_id)
298
+ if product:
299
+ variant_name = request.form.get('name', '').strip()
300
+ price = to_decimal(request.form.get('price', '0'))
301
+ cost_price = to_decimal(request.form.get('cost_price', '0'))
302
+ stock = int(to_decimal(request.form.get('stock', '0')))
303
+ if not variant_name or price <= 0:
304
+ flash("Название варианта и цена обязательны.", "danger")
305
+ else:
306
+ new_variant = {
307
+ 'id': uuid.uuid4().hex, 'name': variant_name, 'price': str(price),
308
+ 'cost_price': str(cost_price), 'stock': stock
309
+ }
310
+ product.setdefault('variants', []).append(new_variant)
311
+ product['timestamp_updated'] = get_current_time().isoformat()
312
+ save_json_data('inventory', inventory)
313
+ upload_db_to_hf('inventory')
314
+ flash(f"Вариант '{variant_name}' добавлен.", "success")
315
+
316
+ elif action == 'edit_variant':
317
+ variant_id = request.form.get('variant_id')
318
+ product, variant = find_variant_by_id(inventory, variant_id)
319
+ if variant:
320
+ variant['name'] = request.form.get('name', '').strip()
321
+ variant['price'] = str(to_decimal(request.form.get('price', '0')))
322
+ variant['cost_price'] = str(to_decimal(request.form.get('cost_price', '0')))
323
+ # Stock is not edited here, but via goods receipt/sales
324
+ product['timestamp_updated'] = get_current_time().isoformat()
325
+ save_json_data('inventory', inventory)
326
+ upload_db_to_hf('inventory')
327
+ flash("Вариант обновлен.", "success")
328
+
329
  return redirect(url_for('inventory_management'))
330
 
331
  inventory_list = load_json_data('inventory')
 
333
  html = BASE_TEMPLATE.replace('__TITLE__', "Склад").replace('__CONTENT__', INVENTORY_CONTENT).replace('__SCRIPTS__', INVENTORY_SCRIPTS)
334
  return render_template_string(html, inventory=inventory_list)
335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  @app.route('/inventory/delete/<product_id>', methods=['POST'])
337
  def delete_product(product_id):
338
  inventory = load_json_data('inventory')
 
346
  flash("Товар не найден.", "warning")
347
  return redirect(url_for('inventory_management'))
348
 
349
+ @app.route('/inventory/variant/delete/<variant_id>', methods=['POST'])
350
+ def delete_variant(variant_id):
 
 
 
 
 
 
 
 
 
351
  inventory = load_json_data('inventory')
352
+ variant_found = False
353
+ for product in inventory:
354
+ initial_len = len(product.get('variants', []))
355
+ product['variants'] = [v for v in product.get('variants', []) if v.get('id') != variant_id]
356
+ if len(product.get('variants', [])) < initial_len:
357
+ variant_found = True
358
+ break
359
+ if variant_found:
360
+ save_json_data('inventory', inventory)
361
+ upload_db_to_hf('inventory')
362
+ flash("Вариант удален.", "success")
363
+ else:
364
+ flash("Вариант не найден.", "warning")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
  return redirect(url_for('inventory_management'))
366
 
367
  @app.route('/inventory/receive', methods=['POST'])
 
369
  variant_id = request.form.get('variant_id')
370
  quantity = int(to_decimal(request.form.get('quantity', '0')))
371
  cost_price = to_decimal(request.form.get('cost_price', '0'))
372
+ notes = request.form.get('notes', 'Оприходование')
373
 
374
  if not variant_id or quantity <= 0:
375
  flash("Выберите вариант и укажите положительное количество.", "danger")
376
  return redirect(url_for('inventory_management'))
377
+
378
  inventory = load_json_data('inventory')
379
  stock_movements = load_json_data('stock_movements')
380
+ product, variant = find_variant_by_id(inventory, variant_id)
381
+
382
+ if not variant:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
  flash("Вариант товара не найден.", "danger")
384
+ return redirect(url_for('inventory_management'))
385
+
386
+ variant['stock'] = variant.get('stock', 0) + quantity
387
+ if cost_price > 0:
388
+ variant['cost_price'] = str(cost_price)
389
+ product['timestamp_updated'] = get_current_time().isoformat()
390
 
391
+ movement = {
392
+ 'id': uuid.uuid4().hex,
393
+ 'timestamp': get_current_time().isoformat(),
394
+ 'type': 'receipt',
395
+ 'product_id': product['id'],
396
+ 'variant_id': variant['id'],
397
+ 'product_name': product['name'],
398
+ 'variant_name': variant['name'],
399
+ 'quantity_change': quantity,
400
+ 'cost_price_at_receipt': str(cost_price) if cost_price > 0 else variant['cost_price'],
401
+ 'notes': notes
402
+ }
403
+ stock_movements.append(movement)
404
+
405
+ save_json_data('inventory', inventory)
406
+ save_json_data('stock_movements', stock_movements)
407
+ upload_db_to_hf('inventory')
408
+ upload_db_to_hf('stock_movements')
409
+ flash("Остаток товара успешно обновлен.", "success")
410
+ return redirect(url_for('inventory_management'))
411
 
412
  @app.route('/api/product_by_barcode/<barcode>')
413
  def get_product_by_barcode(barcode):
414
  inventory = load_json_data('inventory')
415
+ product = find_product_by_barcode(inventory, barcode)
416
+ if product and product.get('variants'):
417
+ return jsonify({'success': True, 'product': product})
418
+ return jsonify({'success': False, 'message': 'Товар не найден или у него нет вариантов'}), 404
 
 
 
 
 
 
419
 
420
  @app.route('/api/complete_sale', methods=['POST'])
421
  def complete_sale():
422
  try:
423
  data = request.get_json()
424
+ cart = data.get('cart', {})
425
  user_id = data.get('userId')
426
  kassa_id = data.get('kassaId')
427
  payment_method = data.get('paymentMethod', 'cash')
 
439
  if not user or not kassa:
440
  return jsonify({'success': False, 'message': 'Кассир или касса не найдены.'}), 404
441
 
 
442
  sale_items = []
443
  total_amount = Decimal('0.00')
444
+ inventory_updates = defaultdict(int)
445
 
446
  for variant_id, cart_item in cart.items():
447
+ product, variant = find_variant_by_id(inventory, variant_id)
448
+ if not variant:
449
+ return jsonify({'success': False, 'message': f"Товар с ID варианта {variant_id} не найден."}), 404
450
 
 
451
  quantity_sold = cart_item['quantity']
452
  current_stock = variant.get('stock', 0)
453
 
454
  if quantity_sold > current_stock:
455
+ return jsonify({'success': False, 'message': f"Недостаточно товара '{product['name']} - {variant['name']}'. В наличии: {current_stock}"}), 400
456
 
457
+ price_at_sale = to_decimal(variant.get('price', '0'))
458
  cost_price_at_sale = to_decimal(variant.get('cost_price', '0'))
459
  item_total = price_at_sale * Decimal(quantity_sold)
460
  total_amount += item_total
461
 
462
  sale_items.append({
463
  'product_id': product['id'],
464
+ 'product_name': product['name'],
465
  'variant_id': variant_id,
466
+ 'variant_name': variant['name'],
467
  'barcode': product.get('barcode'),
468
  'quantity': quantity_sold,
469
  'price_at_sale': str(price_at_sale),
470
  'cost_price_at_sale': str(cost_price_at_sale),
471
  'total': str(item_total)
472
  })
473
+ inventory_updates[variant_id] -= quantity_sold
474
 
475
  now_iso = get_current_time().isoformat()
476
 
 
492
  new_transaction['receipt_html'] = generate_receipt_html(new_transaction)
493
  transactions = load_json_data('transactions')
494
  transactions.append(new_transaction)
495
+
496
  for p in inventory:
497
  for v in p.get('variants', []):
498
  if v['id'] in inventory_updates:
499
+ v['stock'] += inventory_updates[v['id']]
500
  p['timestamp_updated'] = now_iso
501
 
502
  if payment_method == 'cash':
 
505
  current_balance = to_decimal(k.get('balance', '0'))
506
  kassas[i]['balance'] = str(current_balance + total_amount)
507
  kassas[i].setdefault('history', []).append({
508
+ 'type': 'sale', 'amount': str(total_amount), 'timestamp': now_iso,
 
 
509
  'transaction_id': new_transaction['id']
510
  })
511
  break
 
568
  if start_date <= datetime.fromisoformat(e['timestamp']) < end_date
569
  ]
570
 
571
+ total_revenue = sum(to_decimal(t['total_amount']) for t in filtered_transactions if t.get('type') == 'sale')
572
+ total_returns = sum(to_decimal(t['total_amount']) for t in filtered_transactions if t.get('type') == 'return')
573
+ net_revenue = total_revenue + total_returns # returns are negative
574
+
575
  total_cogs = sum(
576
  to_decimal(item.get('cost_price_at_sale', '0')) * to_decimal(str(item['quantity']))
577
+ for t in filtered_transactions if t.get('type') == 'sale' for item in t['items']
578
  )
579
+
580
+ gross_profit = net_revenue - total_cogs
581
  total_expenses = sum(to_decimal(e['amount']) for e in filtered_expenses)
582
 
583
  sales_by_cashier = defaultdict(lambda: {'count': 0, 'total': Decimal(0)})
 
594
  cashier_payouts = defaultdict(Decimal)
595
  for t in filtered_transactions:
596
  user = find_item_by_field(users, 'id', t.get('user_id'))
597
+ if user and t.get('type') == 'sale':
598
  payment_type = user.get('payment_type')
599
  payment_value = to_decimal(user.get('payment_value', '0'))
600
  if payment_type == 'percentage' and payment_value > 0:
 
613
  net_profit = gross_profit - total_expenses - total_salary_expenses
614
 
615
  stats = {
616
+ 'total_revenue': net_revenue,
617
  'total_cogs': total_cogs,
618
  'gross_profit': gross_profit,
619
  'total_expenses': total_expenses,
 
628
  html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS)
629
  return render_template_string(html, stats=stats, start_date=start_date_str, end_date=end_date_str, expenses=filtered_expenses)
630
 
631
+ @app.route('/reports/roi')
632
+ def reports_roi():
633
  inventory = load_json_data('inventory')
634
  transactions = load_json_data('transactions')
635
  stock_movements = load_json_data('stock_movements')
636
 
637
+ roi_data = defaultdict(lambda: {
638
+ 'total_investment': Decimal('0.0'),
639
+ 'total_revenue': Decimal('0.0'),
640
+ 'value_of_stock': Decimal('0.0'),
641
+ 'payback': Decimal('0.0'),
642
+ 'product_name': '',
643
+ 'variant_name': ''
644
  })
645
 
646
  for movement in stock_movements:
647
+ if movement.get('type') == 'receipt':
648
+ variant_id = movement['variant_id']
649
+ investment = to_decimal(movement.get('cost_price_at_receipt', '0')) * to_decimal(str(movement.get('quantity_change', 0)))
650
+ roi_data[variant_id]['total_investment'] += investment
651
+ roi_data[variant_id]['product_name'] = movement.get('product_name', 'N/A')
652
+ roi_data[variant_id]['variant_name'] = movement.get('variant_name', 'N/A')
653
 
654
  for t in transactions:
655
+ if t.get('type') == 'sale':
656
+ for item in t.get('items', []):
657
+ variant_id = item['variant_id']
658
+ roi_data[variant_id]['total_revenue'] += to_decimal(item['total'])
659
+ roi_data[variant_id]['product_name'] = item.get('product_name', 'N/A')
660
+ roi_data[variant_id]['variant_name'] = item.get('variant_name', 'N/A')
661
 
662
+ for product in inventory:
663
+ for variant in product.get('variants', []):
664
+ variant_id = variant['id']
665
+ value = to_decimal(variant.get('cost_price', '0')) * to_decimal(str(variant.get('stock', 0)))
666
+ roi_data[variant_id]['value_of_stock'] = value
667
+ if not roi_data[variant_id]['product_name']:
668
+ roi_data[variant_id]['product_name'] = product['name']
669
+ roi_data[variant_id]['variant_name'] = variant['name']
670
+
671
+ for vid, data in roi_data.items():
672
+ data['payback'] = data['total_revenue'] - data['total_investment']
673
+
674
+ sorted_roi = sorted(roi_data.values(), key=lambda x: x['payback'])
675
+
676
+ html = BASE_TEMPLATE.replace('__TITLE__', "Окупаемость по товарам").replace('__CONTENT__', ROI_CONTENT).replace('__SCRIPTS__', "")
677
+ return render_template_string(html, roi_data=sorted_roi)
 
 
 
 
 
 
 
 
 
 
 
678
 
679
  @app.route('/admin', methods=['GET'])
680
  def admin_panel():
 
887
  total_amount = to_decimal(original_transaction['total_amount'])
888
 
889
  return_items = []
890
+ inventory_updates = defaultdict(int)
891
  for item in original_transaction['items']:
892
  return_items.append({**item, 'quantity': -item['quantity'], 'total': str(-to_decimal(item['total']))})
893
+ inventory_updates[item['variant_id']] += item['quantity']
 
894
 
895
  now_iso = get_current_time().isoformat()
896
  return_transaction = {
 
989
  .sidebar .nav-link { color: rgba(255,255,255,.75); }
990
  .sidebar .nav-link:hover, .sidebar .nav-link.active { color: #fff; }
991
  .main-content { margin-left: var(--sidebar-width); padding: 1.5rem; }
 
992
  @media (max-width: 992px) {
993
  .sidebar { transform: translateX(calc(-1 * var(--sidebar-width))); transition: transform 0.3s ease-in-out; z-index: 1040; }
994
  .sidebar.active { transform: translateX(0); }
995
  .main-content { margin-left: 0; }
996
  }
997
  [data-bs-theme="dark"] body { background-color: #212529; color: #dee2e6; }
998
+ [data-bs-theme="dark"] .card, [data-bs-theme="dark"] .list-group-item, [data-bs-theme="dark"] .table { background-color: #343a40; }
999
  [data-bs-theme="dark"] .table-hover>tbody>tr:hover>* { color: var(--bs-table-hover-color); background-color: rgba(255, 255, 255, 0.075); }
1000
+ .product-card { cursor: pointer; }
1001
  </style>
1002
  </head>
1003
  <body>
 
1009
  <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>
1010
  <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>
1011
  <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>
1012
+ <li class="nav-item"><a class="nav-link {% if request.endpoint == 'reports' or request.endpoint == 'reports_roi' %}active{% endif %}" href="{{ url_for('reports') }}"><i class="fas fa-fw fa-chart-line me-2"></i>Отчеты</a></li>
1013
+ <li class="nav-item ps-4"><a class="nav-link {% if request.endpoint == 'reports_roi' %}active{% endif %}" href="{{ url_for('reports_roi') }}"><i class="fas fa-fw fa-coins me-2"></i>Окупаемость</a></li>
 
 
 
 
 
 
 
 
 
1014
  <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>
1015
  <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>
1016
  </ul>
 
1067
  </div>
1068
  </div>
1069
 
 
 
 
 
 
 
 
 
 
 
1070
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
1071
  <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
1072
  <script>
 
1109
  </div>
1110
  <input type="text" id="product-search" class="form-control mb-3" placeholder="Поиск по названию или штрих-коду...">
1111
  <div id="product-grid" class="d-grid gap-2" style="grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));">
1112
+ {% for v in variants %}
1113
+ <div class="card text-center product-card"
1114
+ data-variant-id="{{ v.variant_id }}"
1115
+ data-product-name="{{ v.product_name|lower }}"
1116
+ data-variant-name="{{ v.variant_name|lower }}"
1117
+ data-barcode="{{ v.barcode }}"
1118
+ data-price="{{ v.price }}"
1119
+ data-stock="{{ v.stock }}">
1120
  <div class="card-body p-2">
1121
+ <h6 class="card-title small mb-1">{{ v.product_name }}</h6>
1122
+ <p class="card-text small text-muted lh-1">{{ v.variant_name }}</p>
1123
+ <p class="card-text fw-bold mb-0">{{ format_currency_py(v.price) }} с</p>
1124
  </div>
1125
  </div>
1126
  {% endfor %}
 
1149
  </div>
1150
  </div>
1151
  </div>
1152
+
1153
+ <div class="modal fade" id="variant-modal" tabindex="-1">
1154
+ <div class="modal-dialog">
1155
+ <div class="modal-content">
1156
+ <div class="modal-header"><h5 class="modal-title" id="variant-modal-title">Выберите вариант</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1157
+ <div class="modal-body">
1158
+ <div id="variant-modal-list" class="list-group"></div>
1159
+ </div>
1160
+ </div>
1161
+ </div>
1162
+ </div>
1163
  """
1164
 
1165
  SALES_SCREEN_SCRIPTS = """
 
1169
  const productGrid = document.getElementById('product-grid');
1170
  const cartItemsEl = document.getElementById('cart-items');
1171
  const cartTotalEl = document.getElementById('cart-total');
1172
+ const variantModalEl = document.getElementById('variant-modal');
1173
+ const variantModal = new bootstrap.Modal(variantModalEl);
1174
  let audioCtx;
1175
  let isScannerPaused = false;
1176
  const receiptModal = new bootstrap.Modal(document.getElementById('receiptModal'));
 
1177
 
1178
  function playBeep() {
1179
  if (!audioCtx) {
 
1204
  cartItemsEl.innerHTML += `
1205
  <div class="list-group-item d-flex justify-content-between align-items-center">
1206
  <div>
1207
+ <h6 class="mb-0 small">${item.product_name} (${item.variant_name})</h6>
1208
  <small>${item.quantity} x ${item.price} с</small>
1209
  </div>
1210
  <div>
 
1216
  cartTotalEl.textContent = total.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' с';
1217
  };
1218
 
1219
+ const addToCart = (variant) => {
1220
+ if (cart[variant.id]) {
1221
+ cart[variant.id].quantity++;
 
1222
  } else {
1223
+ cart[variant.id] = {
1224
+ product_name: variant.product_name,
1225
+ variant_name: variant.name,
1226
+ price: String(variant.price).replace('.',','),
1227
  quantity: 1
1228
  };
1229
  }
1230
  playBeep();
1231
  updateCartView();
1232
  };
1233
+
1234
  const handleProductSelection = (product) => {
1235
  if (product.variants.length === 1) {
1236
+ const variant = product.variants[0];
1237
+ if (variant.stock > 0) {
1238
+ addToCart({...variant, product_name: product.name});
1239
+ } else {
1240
+ alert('Товар закончился');
1241
+ }
1242
  } else {
1243
+ document.getElementById('variant-modal-title').textContent = `Выберите вариант: ${product.name}`;
1244
+ const listEl = document.getElementById('variant-modal-list');
1245
+ listEl.innerHTML = '';
1246
+ product.variants.forEach(v => {
1247
+ if (v.stock > 0) {
1248
+ const btn = document.createElement('button');
1249
+ btn.type = 'button';
1250
+ btn.className = 'list-group-item list-group-item-action';
1251
+ btn.innerHTML = `${v.name} <span class="badge bg-secondary float-end">${v.stock} шт.</span> <span class="fw-bold me-3 float-end">${parseFloat(v.price).toLocaleString('ru-RU')} с</span>`;
1252
+ btn.onclick = () => {
1253
+ addToCart({...v, product_name: product.name});
1254
+ variantModal.hide();
1255
+ };
1256
+ listEl.appendChild(btn);
1257
+ }
1258
  });
1259
+ if (listEl.children.length > 0) {
1260
+ variantModal.show();
1261
+ } else {
1262
+ alert('Все варианты этого товара закончились');
1263
+ }
1264
  }
1265
  };
1266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1267
  productGrid.addEventListener('click', e => {
1268
  const card = e.target.closest('.product-card');
1269
  if (card) {
1270
+ const variant = {
1271
+ id: card.dataset.variantId,
1272
+ name: card.dataset.variantName,
1273
+ product_name: card.dataset.productName,
1274
+ price: card.dataset.price,
1275
+ stock: parseInt(card.dataset.stock)
1276
+ };
1277
+ addToCart(variant);
1278
  }
1279
  });
1280
 
 
1298
  document.getElementById('product-search').addEventListener('input', e => {
1299
  const term = e.target.value.toLowerCase();
1300
  document.querySelectorAll('.product-card').forEach(card => {
1301
+ const show = card.dataset.productName.includes(term) || card.dataset.variantName.includes(term) || card.dataset.barcode.includes(term);
 
1302
  card.style.display = show ? '' : 'none';
1303
  });
1304
  });
 
1358
  scannerStatusEl.textContent = 'Пауза...';
1359
  scannerStatusEl.style.display = 'block';
1360
  if (html5QrCode.getState() === 2) html5QrCode.pause();
 
 
1361
 
1362
+ fetch(`/api/product_by_barcode/${decodedText}`)
1363
+ .then(res => res.json())
1364
+ .then(data => {
1365
+ if (data.success) {
1366
+ handleProductSelection(data.product);
1367
+ } else {
1368
+ alert(data.message);
1369
+ }
1370
+ })
1371
+ .finally(() => {
1372
+ setTimeout(() => {
1373
+ isScannerPaused = false;
1374
+ scannerStatusEl.style.display = 'none';
1375
+ if (html5QrCode.getState() === 2) html5QrCode.resume();
1376
+ }, 1500);
1377
+ });
1378
  };
1379
 
1380
  const startScanner = () => {
 
1405
  INVENTORY_CONTENT = """
1406
  <div class="d-flex justify-content-between mb-3">
1407
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addProductModal"><i class="fas fa-plus me-2"></i>Добавить товар</button>
1408
+ <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#receiveStockModal"><i class="fas fa-truck-loading me-2"></i>Оприходовать товар</button>
1409
  </div>
1410
  <div class="accordion" id="inventoryAccordion">
1411
+ {% for p in inventory %}
1412
  <div class="accordion-item">
1413
  <h2 class="accordion-header" id="heading-{{ p.id }}">
1414
+ <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-{{ p.id }}">
1415
+ <strong>{{ p.name }}</strong>&nbsp;<small class="text-muted">({{ p.barcode }})</small>
 
 
 
1416
  </button>
1417
  </h2>
1418
+ <div id="collapse-{{ p.id }}" class="accordion-collapse collapse" data-bs-parent="#inventoryAccordion">
1419
  <div class="accordion-body">
1420
+ <div class="d-flex justify-content-end mb-2">
1421
+ <button class="btn btn-sm btn-outline-primary me-2" data-bs-toggle="modal" data-bs-target="#editProductModal-{{ p.id }}"><i class="fas fa-edit me-1"></i>Ред. товар</button>
1422
+ <button class="btn btn-sm btn-outline-success me-2" data-bs-toggle="modal" data-bs-target="#addVariantModal-{{ p.id }}"><i class="fas fa-plus me-1"></i>Добавить вариант</button>
1423
+ <form action="{{ url_for('delete_product', product_id=p.id) }}" method="POST" class="d-inline" onsubmit="return confirm('Удалить товар и все его варианты?');">
1424
+ <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
1425
+ </form>
1426
+ </div>
1427
+ <table class="table table-sm table-bordered">
1428
+ <thead><tr><th>Вариант (цвет/размер)</th><th>Цена</th><th>Себест.</th><th>Остаток</th><th>Действия</th></tr></thead>
1429
+ <tbody>
1430
+ {% for v in p.variants %}
1431
+ <tr>
1432
+ <td>{{ v.name }}</td>
1433
+ <td>{{ format_currency_py(v.price) }} с</td>
1434
+ <td>{{ format_currency_py(v.cost_price) }} с</td>
1435
+ <td>{{ v.stock }}</td>
1436
+ <td>
1437
+ <button class="btn btn-xs btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#editVariantModal-{{ v.id }}"><i class="fas fa-edit"></i></button>
1438
+ <form action="{{ url_for('delete_variant', variant_id=v.id) }}" method="POST" class="d-inline" onsubmit="return confirm('Удалить вариант?');">
1439
+ <button type="submit" class="btn btn-xs btn-outline-danger"><i class="fas fa-trash"></i></button>
1440
+ </form>
1441
+ </td>
1442
+ </tr>
1443
+ {% else %}
1444
+ <tr><td colspan="5" class="text-center text-muted">Нет вариантов. Добавьте первый.</td></tr>
1445
+ {% endfor %}
1446
+ </tbody>
1447
+ </table>
1448
  </div>
1449
  </div>
1450
  </div>
1451
+ {% else %}
1452
+ <div class="card"><div class="card-body text-center">Товаров нет.</div></div>
1453
+ {% endfor %}
1454
  </div>
1455
 
1456
  <!-- Modals -->
1457
+ <div class="modal fade" id="addProductModal" tabindex="-1">
1458
+ <div class="modal-dialog">
1459
+ <div class="modal-content">
1460
+ <div class="modal-header"><h5 class="modal-title">Новый товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1461
+ <form action="{{ url_for('inventory_management') }}" method="POST">
1462
+ <input type="hidden" name="action" value="add_product">
1463
+ <div class="modal-body">
1464
+ <div class="mb-3"><label class="form-label">Название товара</label><input type="text" name="name" class="form-control" required></div>
1465
+ <div class="mb-3"><label class="form-label">Штрих-код</label><input type="text" name="barcode" class="form-control" required></div>
1466
+ </div>
1467
+ <div class="modal-footer"><button type="submit" class="btn btn-primary">Создать товар</button></div>
1468
+ </form>
 
 
 
 
 
 
 
 
 
1469
  </div>
1470
+ </div>
1471
+ </div>
1472
+
1473
+ <div class="modal fade" id="receiveStockModal" tabindex="-1">
1474
+ <div class="modal-dialog">
1475
+ <div class="modal-content">
1476
+ <div class="modal-header"><h5 class="modal-title">Оприходование товара</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1477
+ <form action="{{ url_for('receive_stock') }}" method="POST">
1478
+ <div class="modal-body">
1479
+ <div class="mb-3">
1480
+ <label class="form-label">Товар / Вариант</label>
1481
+ <select name="variant_id" class="form-select" required>
1482
+ <option value="">-- Выберите --</option>
1483
+ {% for p in inventory %}<optgroup label="{{p.name}}">
1484
+ {% for v in p.variants %}<option value="{{v.id}}">{{v.name}}</option>{% endfor %}
1485
+ </optgroup>{% endfor %}
1486
+ </select>
1487
+ </div>
1488
+ <div class="row">
1489
+ <div class="col-6 mb-3"><label class="form-label">Количество</label><input type="number" name="quantity" class="form-control" step="1" required></div>
1490
+ <div class="col-6 mb-3"><label class="form-label">Новая себестоимость (за 1 шт.)</label><input type="text" name="cost_price" class="form-control" inputmode="decimal" placeholder="Оставить прежней"></div>
1491
+ </div>
1492
+ <div class="mb-3"><label class="form-label">Примечание</label><input type="text" name="notes" class="form-control" placeholder="Напр. 'От поставщика A'"></div>
1493
+ </div>
1494
+ <div class="modal-footer"><button type="submit" class="btn btn-success">Оприходовать</button></div>
1495
+ </form>
1496
  </div>
1497
+ </div>
 
1498
  </div>
 
 
1499
 
1500
  {% for p in inventory %}
1501
+ <div class="modal fade" id="editProductModal-{{ p.id }}" tabindex="-1">
1502
+ <div class="modal-dialog">
1503
+ <div class="modal-content">
1504
+ <div class="modal-header"><h5 class="modal-title">Редактировать товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1505
+ <form action="{{ url_for('inventory_management') }}" method="POST">
1506
+ <input type="hidden" name="action" value="edit_product">
1507
+ <input type="hidden" name="product_id" value="{{ p.id }}">
1508
+ <div class="modal-body">
1509
+ <div class="mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" value="{{ p.name }}" required></div>
1510
+ <div class="mb-3"><label class="form-label">Штрих-код</label><input type="text" name="barcode" class="form-control" value="{{ p.barcode }}" required></div>
1511
+ </div>
1512
+ <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
1513
+ </form>
1514
+ </div>
1515
+ </div>
1516
  </div>
1517
+
1518
+ <div class="modal fade" id="addVariantModal-{{ p.id }}" tabindex="-1">
1519
+ <div class="modal-dialog">
1520
+ <div class="modal-content">
1521
+ <div class="modal-header"><h5 class="modal-title">Новый вариант для "{{p.name}}"</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1522
+ <form action="{{ url_for('inventory_management') }}" method="POST">
1523
+ <input type="hidden" name="action" value="add_variant">
1524
+ <input type="hidden" name="product_id" value="{{ p.id }}">
1525
+ <div class="modal-body">
1526
+ <div class="mb-3"><label class="form-label">Название варианта (напр. Красный, L)</label><input type="text" name="name" class="form-control" required></div>
1527
+ <div class="row">
1528
+ <div class="col-6 mb-3"><label class="form-label">Цена продажи</label><input type="text" name="price" class="form-control" inputmode="decimal" required></div>
1529
+ <div class="col-6 mb-3"><label class="form-label">Себестоимость</label><input type="text" name="cost_price" class="form-control" inputmode="decimal"></div>
1530
+ </div>
1531
+ <div class="mb-3"><label class="form-label">Начальный остаток</label><input type="number" name="stock" class="form-control" value="0" step="1"></div>
1532
+ </div>
1533
+ <div class="modal-footer"><button type="submit" class="btn btn-primary">Добавить вариант</button></div>
1534
+ </form>
1535
+ </div>
1536
+ </div>
1537
  </div>
1538
+
1539
+ {% for v in p.variants %}
1540
+ <div class="modal fade" id="editVariantModal-{{ v.id }}" tabindex="-1">
1541
+ <div class="modal-dialog">
1542
+ <div class="modal-content">
1543
+ <div class="modal-header"><h5 class="modal-title">Редактировать вариант</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
1544
+ <form action="{{ url_for('inventory_management') }}" method="POST">
1545
+ <input type="hidden" name="action" value="edit_variant">
1546
+ <input type="hidden" name="variant_id" value="{{ v.id }}">
1547
+ <div class="modal-body">
1548
+ <div class="mb-3"><label class="form-label">Название варианта</label><input type="text" name="name" class="form-control" value="{{v.name}}" required></div>
1549
+ <div class="row">
1550
+ <div class="col-6 mb-3"><label class="form-label">Цена</label><input type="text" name="price" class="form-control" value="{{ v.price|string|replace('.', ',') }}" inputmode="decimal" required></div>
1551
+ <div class="col-6 mb-3"><label class="form-label">Себестоимость</label><input type="text" name="cost_price" value="{{ v.cost_price|string|replace('.', ',') }}" class="form-control" inputmode="decimal"></div>
1552
+ </div>
1553
+ <p class="text-muted small">Остаток изменяется только через оприходование или продажи/возвраты.</p>
1554
+ </div>
1555
+ <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
1556
+ </form>
1557
+ </div>
1558
+ </div>
1559
+ </div>
1560
+ {% endfor %}
1561
  {% endfor %}
1562
  """
1563
 
1564
+ INVENTORY_SCRIPTS = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1565
 
1566
  TRANSACTIONS_CONTENT = """
1567
  <div class="card">
 
1572
  <tbody>
1573
  {% for t in transactions %}
1574
  <tr class="{% if t.type == 'return' %}table-danger{% endif %}">
1575
+ <td><a href="{{ url_for('view_receipt', transaction_id=t.id) if t.type == 'sale' else '#' }}" target="_blank"><small class="text-muted">{{ t.id[:8] }}</small></a></td>
1576
  <td>{{ t.timestamp[:16]|replace('T', ' ') }}</td>
1577
  <td><span class="badge bg-{{'primary' if t.type == 'sale' else 'warning'}}">{{'Продажа' if t.type == 'sale' else 'Возврат'}}</span></td>
1578
  <td>{{ t.user_name }}</td><td>{{ t.kassa_name }}</td>
1579
  <td class="fw-bold">{{ format_currency_py(t.total_amount) }} с</td>
1580
+ <td><span class="badge bg-{{'success' if t.status == 'completed' else 'secondary'}}">{{t.status}}</span></td>
1581
  <td>
1582
  <ul class="list-unstyled mb-0 small">
1583
+ {% for item in t['items'] %}<li>{{ item.product_name }} ({{ item.variant_name }}) ({{ item.quantity }}x{{ format_currency_py(item.price_at_sale) }})</li>{% endfor %}
1584
  </ul>
1585
  </td>
1586
  </tr>
 
1594
 
1595
  TRANSACTIONS_SCRIPTS = ""
1596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1597
  REPORTS_CONTENT = """
1598
  <div class="card mb-4">
1599
  <div class="card-body">
 
1676
 
1677
  REPORTS_SCRIPTS = ""
1678
 
1679
+ ROI_CONTENT = """
1680
+ <div class="card">
1681
+ <div class="card-header">
1682
+ <h5 class="mb-0">Отчет по окупаемости товаров</h5>
1683
+ </div>
1684
+ <div class="card-body">
1685
+ <p class="text-muted">Отчет показывает, окупил ли товар вложенные в него средства. Отрицательное значение означает, что товар еще не окупился.</p>
1686
+ <div class="table-responsive">
1687
+ <table class="table table-sm table-hover">
1688
+ <thead class="table-light">
1689
+ <tr>
1690
+ <th>Товар / Вариант</th>
1691
+ <th class="text-end">Вложения</th>
1692
+ <th class="text-end">Выручка</th>
1693
+ <th class="text-end">Стоимость остатка</th>
1694
+ <th class="text-end">Окупаемость (Выручка - Вложения)</th>
1695
+ </tr>
1696
+ </thead>
1697
+ <tbody>
1698
+ {% for item in roi_data %}
1699
+ <tr>
1700
+ <td><strong>{{ item.product_name }}</strong><br><small>{{ item.variant_name }}</small></td>
1701
+ <td class="text-end">{{ format_currency_py(item.total_investment) }} с</td>
1702
+ <td class="text-end">{{ format_currency_py(item.total_revenue) }} с</td>
1703
+ <td class="text-end">{{ format_currency_py(item.value_of_stock) }} с</td>
1704
+ <td class="text-end fw-bold {% if item.payback > 0 %}text-success{% elif item.payback < 0 %}text-danger{% endif %}">
1705
+ {{ format_currency_py(item.payback) }} с
1706
+ </td>
1707
+ </tr>
1708
+ {% else %}
1709
+ <tr><td colspan="5" class="text-center">Нет данных для анализа.</td></tr>
1710
+ {% endfor %}
1711
+ </tbody>
1712
+ </table>
1713
+ </div>
1714
+ </div>
1715
+ </div>
1716
+ """
1717
+
1718
  ADMIN_CONTENT = """
1719
  <div class="row">
1720
  <div class="col-md-6 mb-4">
 
1904
  <td>{{ t.timestamp[:16]|replace('T', ' ') }}</td>
1905
  <td><span class="badge bg-{{'primary' if t.type == 'sale' else 'warning'}}">{{'Продажа' if t.type == 'sale' else 'Возврат'}}</span></td>
1906
  <td class="fw-bold">{{ format_currency_py(t.total_amount) }} с</td>
1907
+ <td><span class="badge bg-{{'success' if t.status == 'completed' else 'secondary'}}">{{t.status}}</span></td>
1908
  <td>
1909
  {% if t.type == 'sale' and t.status == 'completed' %}
1910
  <form action="{{ url_for('return_transaction', transaction_id=t.id) }}" method="POST" onsubmit="return confirm('Оформить возврат по этому чеку?');">