Kgshop commited on
Commit
e97b08c
·
verified ·
1 Parent(s): 77ba72b

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -937
app.py DELETED
@@ -1,937 +0,0 @@
1
-
2
-
3
-
4
-
5
- from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash, send_from_directory
6
- import json
7
- import os
8
- import logging
9
- import threading
10
- import time
11
- from datetime import datetime
12
- import pytz
13
- from huggingface_hub import HfApi, hf_hub_download
14
- from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
15
- import uuid
16
- from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
17
- import functools
18
-
19
- app = Flask(__name__)
20
- app.secret_key = os.urandom(24)
21
-
22
- DATA_FILES = {
23
- 'inventory': 'inventory.json',
24
- 'sales': 'sales.json',
25
- 'users': 'users.json',
26
- 'cash_registers': 'cash_registers.json',
27
- 'shifts': 'shifts.json',
28
- 'expenses': 'expenses.json',
29
- 'categories': 'categories.json'
30
- }
31
- data_locks = {name: threading.Lock() for name in DATA_FILES}
32
-
33
- HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", "YOUR_WRITE_TOKEN_HERE")
34
- HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", "YOUR_READ_TOKEN_HERE")
35
- REPO_ID = "Kgshop/postest"
36
-
37
- BISHKEK_TZ = pytz.timezone('Asia/Bishkek')
38
-
39
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
40
-
41
- def get_current_time():
42
- return datetime.now(BISHKEK_TZ)
43
-
44
- def load_json_data(file_key):
45
- filename = DATA_FILES[file_key]
46
- lock = data_locks[file_key]
47
- with lock:
48
- try:
49
- hf_hub_download(
50
- repo_id=REPO_ID, filename=filename, repo_type="dataset", token=HF_TOKEN_READ,
51
- local_dir=".", local_dir_use_symlinks=False, force_download=True,
52
- )
53
- except (RepositoryNotFoundError, HfHubHTTPError):
54
- logging.warning(f"File {filename} not found in repository {REPO_ID}. Using local file if exists.")
55
- except Exception as e:
56
- logging.error(f"Error downloading {filename} from Hugging Face: {e}")
57
-
58
- try:
59
- with open(filename, 'r', encoding='utf-8') as file:
60
- return json.load(file)
61
- except (FileNotFoundError, json.JSONDecodeError):
62
- return []
63
-
64
- def save_json_data(file_key, data):
65
- filename = DATA_FILES[file_key]
66
- lock = data_locks[file_key]
67
- with lock:
68
- try:
69
- temp_file = filename + ".tmp"
70
- with open(temp_file, 'w', encoding='utf-8') as file:
71
- json.dump(data, file, ensure_ascii=False, indent=4, cls=DecimalEncoder)
72
- os.replace(temp_file, filename)
73
- except Exception as e:
74
- logging.error(f"Critical error saving data to {filename}: {e}", exc_info=True)
75
-
76
- def upload_to_hf(file_key):
77
- api = get_hf_api()
78
- if not api: return
79
- filepath = DATA_FILES[file_key]
80
- if not os.path.exists(filepath): return
81
- try:
82
- filename = os.path.basename(filepath)
83
- commit_time = get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z')
84
- api.upload_file(
85
- path_or_fileobj=filepath, path_in_repo=filename, repo_id=REPO_ID, repo_type="dataset",
86
- token=HF_TOKEN_WRITE, commit_message=f"Automated backup {filename} {commit_time}",
87
- run_as_future=True
88
- )
89
- except Exception as e:
90
- logging.error(f"Error initiating upload of {filepath}: {e}")
91
-
92
- @functools.lru_cache(maxsize=1)
93
- def get_hf_api():
94
- if not HF_TOKEN_WRITE or HF_TOKEN_WRITE == "YOUR_WRITE_TOKEN_HERE":
95
- return None
96
- try:
97
- return HfApi()
98
- except Exception as e:
99
- logging.error(f"Error initializing HfApi: {e}")
100
- return None
101
-
102
- def periodic_backup():
103
- while True:
104
- time.sleep(1800)
105
- logging.info("Starting scheduled backup...")
106
- for key in DATA_FILES.keys():
107
- upload_to_hf(key)
108
-
109
- class DecimalEncoder(json.JSONEncoder):
110
- def default(self, obj):
111
- if isinstance(obj, Decimal): return str(obj)
112
- return json.JSONEncoder.default(self, obj)
113
-
114
- def to_decimal(value_str, default='0.00'):
115
- if value_str is None or value_str == '': return Decimal(default)
116
- try: return Decimal(str(value_str).replace(',', '.'))
117
- except InvalidOperation: return Decimal(default)
118
-
119
- def find_by_id(item_id, data_list):
120
- for item in data_list:
121
- if isinstance(item, dict) and item.get('id') == item_id:
122
- return item.copy()
123
- return None
124
-
125
- def format_currency_py(value):
126
- try:
127
- number = to_decimal(value)
128
- return f"{number:,.2f}".replace(",", " ").replace(".", ",")
129
- except (InvalidOperation, TypeError, ValueError):
130
- return "0,00"
131
-
132
- def format_integer_py(value):
133
- try:
134
- number = to_decimal(value).to_integral_value(rounding=ROUND_HALF_UP)
135
- return f"{number:,}".replace(",", " ")
136
- except (InvalidOperation, TypeError, ValueError):
137
- return "0"
138
-
139
- @app.context_processor
140
- def inject_utils():
141
- return {
142
- 'get_current_time': get_current_time,
143
- 'format_currency_py': format_currency_py,
144
- 'format_integer_py': format_integer_py,
145
- }
146
-
147
- @app.route('/')
148
- def index():
149
- inventory = load_json_data('inventory')
150
- sales = load_json_data('sales')
151
- cash_registers = load_json_data('cash_registers')
152
-
153
- today_str = get_current_time().strftime('%Y-%m-%d')
154
- today_sales = [s for s in sales if s.get('timestamp', '').startswith(today_str)]
155
-
156
- total_sales_today = sum(to_decimal(s.get('total', '0')) for s in today_sales)
157
- low_stock_items = [p for p in inventory if to_decimal(p.get('quantity', '0')) <= 5]
158
-
159
- stats = {
160
- 'total_sales_today': total_sales_today,
161
- 'sales_count_today': len(today_sales),
162
- 'inventory_count': len(inventory),
163
- 'low_stock_count': len(low_stock_items)
164
- }
165
-
166
- html = BASE_TEMPLATE.replace('__TITLE__', "Панель управления").replace('__CONTENT__', DASHBOARD_CONTENT).replace('__SCRIPTS__', "")
167
- return render_template_string(html, stats=stats, low_stock_items=low_stock_items, cash_registers=cash_registers)
168
-
169
- @app.route('/pos', methods=['GET'])
170
- def pos_terminal():
171
- inventory = load_json_data('inventory')
172
- cash_registers = load_json_data('cash_registers')
173
- open_registers = [cr for cr in cash_registers if cr.get('is_open')]
174
- html = BASE_TEMPLATE.replace('__TITLE__', "Касса (POS)").replace('__CONTENT__', POS_TERMINAL_CONTENT).replace('__SCRIPTS__', POS_TERMINAL_SCRIPTS)
175
- return render_template_string(html, open_registers=open_registers)
176
-
177
- @app.route('/api/product/barcode/<barcode>', methods=['GET'])
178
- def get_product_by_barcode(barcode):
179
- inventory = load_json_data('inventory')
180
- for product in inventory:
181
- if product.get('barcode') == barcode:
182
- return jsonify(product)
183
- return jsonify({'error': 'Product not found'}), 404
184
-
185
- @app.route('/pos/complete_sale', methods=['POST'])
186
- def complete_sale():
187
- data = request.get_json()
188
- cart = data.get('cart')
189
- payment_method = data.get('paymentMethod')
190
- cash_register_id = data.get('cashRegisterId')
191
-
192
- if not all([cart, payment_method, cash_register_id]):
193
- return jsonify({'error': 'Missing data'}), 400
194
-
195
- inventory = load_json_data('inventory')
196
- sales = load_json_data('sales')
197
- cash_registers = load_json_data('cash_registers')
198
-
199
- subtotal = Decimal('0.00')
200
- sale_items = []
201
-
202
- inventory_map = {p['id']: p for p in inventory}
203
- updates = {}
204
-
205
- for item in cart:
206
- product_id = item.get('id')
207
- quantity = int(item.get('quantity', 1))
208
-
209
- if product_id not in inventory_map:
210
- return jsonify({'error': f"Product ID {product_id} not found"}), 404
211
-
212
- product = inventory_map[product_id]
213
-
214
- if to_decimal(product['quantity']) < quantity:
215
- return jsonify({'error': f"Not enough stock for {product['name']}"}), 400
216
-
217
- selling_price = to_decimal(product['selling_price'])
218
- purchase_price = to_decimal(product['purchase_price'])
219
- subtotal += selling_price * quantity
220
-
221
- sale_items.append({
222
- 'product_id': product_id,
223
- 'name': product['name'],
224
- 'quantity': quantity,
225
- 'purchase_price': str(purchase_price),
226
- 'selling_price': str(selling_price)
227
- })
228
-
229
- updates[product_id] = to_decimal(product['quantity']) - quantity
230
-
231
- new_sale = {
232
- 'id': uuid.uuid4().hex,
233
- 'timestamp': get_current_time().isoformat(),
234
- 'cashier_id': "default_cashier", # Placeholder
235
- 'cashier_name': "Кассир 1", # Placeholder
236
- 'cash_register_id': cash_register_id,
237
- 'items': sale_items,
238
- 'subtotal': str(subtotal),
239
- 'discount': "0.00",
240
- 'total': str(subtotal),
241
- 'payment_method': payment_method
242
- }
243
- sales.append(new_sale)
244
-
245
- for p in inventory:
246
- if p['id'] in updates:
247
- p['quantity'] = str(updates[p['id']])
248
- p['timestamp_updated'] = get_current_time().isoformat()
249
-
250
- for cr in cash_registers:
251
- if cr['id'] == cash_register_id:
252
- if payment_method == 'cash':
253
- cr['current_balance'] = str(to_decimal(cr.get('current_balance', '0')) + subtotal)
254
- break
255
-
256
- save_json_data('sales', sales)
257
- save_json_data('inventory', inventory)
258
- save_json_data('cash_registers', cash_registers)
259
- upload_to_hf('sales')
260
- upload_to_hf('inventory')
261
- upload_to_hf('cash_registers')
262
-
263
- return jsonify({'success': True, 'sale_id': new_sale['id']})
264
-
265
- @app.route('/inventory', methods=['GET', 'POST'])
266
- def inventory_page():
267
- inventory = load_json_data('inventory')
268
- categories = load_json_data('categories')
269
-
270
- if request.method == 'POST':
271
- action = request.form.get('action', 'add')
272
-
273
- if action == 'add':
274
- name = request.form.get('name', '').strip()
275
- barcode = request.form.get('barcode', '').strip()
276
- category = request.form.get('category', 'Без категории').strip()
277
- quantity = to_decimal(request.form.get('quantity', '0'))
278
- purchase_price = to_decimal(request.form.get('purchase_price', '0'))
279
- selling_price = to_decimal(request.form.get('selling_price', '0'))
280
-
281
- if not name or not barcode or not selling_price > 0:
282
- flash("Название, штрих-код и цена продажи обязательны.", "danger")
283
- return redirect(url_for('inventory_page'))
284
-
285
- if any(p['barcode'] == barcode for p in inventory):
286
- flash(f"Товар со штрих-кодом {barcode} уже существует.", "warning")
287
- return redirect(url_for('inventory_page'))
288
-
289
- new_product = {
290
- 'id': uuid.uuid4().hex, 'name': name, 'barcode': barcode, 'category': category,
291
- 'quantity': str(quantity), 'purchase_price': str(purchase_price),
292
- 'selling_price': str(selling_price), 'timestamp_added': get_current_time().isoformat(),
293
- 'timestamp_updated': get_current_time().isoformat()
294
- }
295
- inventory.append(new_product)
296
- save_json_data('inventory', inventory)
297
- upload_to_hf('inventory')
298
- flash(f"Товар '{name}' успешно добавлен.", "success")
299
-
300
- elif action == 'edit':
301
- product_id = request.form.get('product_id')
302
- product = find_by_id(product_id, inventory)
303
- if not product:
304
- flash("Товар не найден.", "danger")
305
- else:
306
- for i, p in enumerate(inventory):
307
- if p['id'] == product_id:
308
- inventory[i]['name'] = request.form.get('name', '').strip()
309
- inventory[i]['barcode'] = request.form.get('barcode', '').strip()
310
- inventory[i]['category'] = request.form.get('category', 'Без категории').strip()
311
- inventory[i]['quantity'] = str(to_decimal(request.form.get('quantity', '0')))
312
- inventory[i]['purchase_price'] = str(to_decimal(request.form.get('purchase_price', '0')))
313
- inventory[i]['selling_price'] = str(to_decimal(request.form.get('selling_price', '0')))
314
- inventory[i]['timestamp_updated'] = get_current_time().isoformat()
315
- break
316
- save_json_data('inventory', inventory)
317
- upload_to_hf('inventory')
318
- flash("Данные товара обновлены.", "success")
319
-
320
- return redirect(url_for('inventory_page'))
321
-
322
- inventory.sort(key=lambda x: x.get('name', '').lower())
323
- html = BASE_TEMPLATE.replace('__TITLE__', "Склад").replace('__CONTENT__', INVENTORY_CONTENT).replace('__SCRIPTS__', INVENTORY_SCRIPTS)
324
- return render_template_string(html, inventory=inventory, categories=categories)
325
-
326
- @app.route('/inventory/delete/<product_id>', methods=['POST'])
327
- def delete_product(product_id):
328
- inventory = load_json_data('inventory')
329
- inventory = [p for p in inventory if p.get('id') != product_id]
330
- save_json_data('inventory', inventory)
331
- upload_to_hf('inventory')
332
- flash("Товар удален.", "success")
333
- return redirect(url_for('inventory_page'))
334
-
335
- @app.route('/sales')
336
- def sales_history():
337
- sales = load_json_data('sales')
338
- sales.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
339
- html = BASE_TEMPLATE.replace('__TITLE__', "История продаж").replace('__CONTENT__', SALES_HISTORY_CONTENT).replace('__SCRIPTS__', "")
340
- return render_template_string(html, sales=sales)
341
-
342
- @app.route('/cash_registers', methods=['GET', 'POST'])
343
- def cash_registers_page():
344
- registers = load_json_data('cash_registers')
345
- if request.method == 'POST':
346
- action = request.form.get('action')
347
- if action == 'add':
348
- name = request.form.get('name')
349
- if name:
350
- new_register = {
351
- 'id': uuid.uuid4().hex,
352
- 'name': name,
353
- 'current_balance': '0.00',
354
- 'is_open': False,
355
- 'current_shift_id': None
356
- }
357
- registers.append(new_register)
358
- save_json_data('cash_registers', registers)
359
- upload_to_hf('cash_registers')
360
- flash(f"Касса '{name}' добавлена.", "success")
361
- elif action == 'toggle_open':
362
- register_id = request.form.get('register_id')
363
- for reg in registers:
364
- if reg['id'] == register_id:
365
- reg['is_open'] = not reg.get('is_open', False)
366
- if reg['is_open']:
367
- flash(f"Касса '{reg['name']}' открыта.", "success")
368
- else:
369
- flash(f"Касса '{reg['name']}' закрыта.", "info")
370
- break
371
- save_json_data('cash_registers', registers)
372
- upload_to_hf('cash_registers')
373
- elif action == 'delete':
374
- register_id = request.form.get('register_id')
375
- registers = [r for r in registers if r['id'] != register_id]
376
- save_json_data('cash_registers', registers)
377
- upload_to_hf('cash_registers')
378
- flash("Касса удалена.", "success")
379
-
380
- return redirect(url_for('cash_registers_page'))
381
-
382
- html = BASE_TEMPLATE.replace('__TITLE__', "Управление кассами").replace('__CONTENT__', CASH_REGISTERS_CONTENT).replace('__SCRIPTS__', "")
383
- return render_template_string(html, registers=registers)
384
-
385
- @app.route('/backup', methods=['POST'])
386
- def backup_hf():
387
- for key in DATA_FILES.keys():
388
- upload_to_hf(key)
389
- flash(f"Резервное копирование {len(DATA_FILES)} файлов в Hugging Face инициировано.", "success")
390
- return redirect(url_for('index'))
391
-
392
- @app.route('/download', methods=['GET'])
393
- def download_hf():
394
- errors = []
395
- for key, filename in DATA_FILES.items():
396
- try:
397
- hf_hub_download(repo_id=REPO_ID, filename=filename, repo_type="dataset", token=HF_TOKEN_READ, local_dir=".", local_dir_use_symlinks=False, force_download=True)
398
- except HfHubHTTPError as e:
399
- if e.response.status_code == 404:
400
- msg = f"Файл '{filename}' не найден в репозитории."
401
- logging.warning(msg)
402
- errors.append(msg)
403
- else:
404
- raise e
405
- if errors:
406
- flash("Ошибки при скачивании: " + "; ".join(errors), "danger")
407
- else:
408
- flash("Все файлы успешно скачаны и перезаписаны локально.", "success")
409
- return redirect(url_for('index'))
410
-
411
-
412
- BASE_TEMPLATE = """
413
- <!DOCTYPE html>
414
- <html lang="ru" data-bs-theme="light">
415
- <head>
416
- <meta charset="UTF-8">
417
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
418
- <title>__TITLE__ - POS</title>
419
- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
420
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
421
- <style>
422
- :root { --sidebar-width: 260px; --topbar-height: 60px; --main-bg: #f3f4f6; }
423
- [data-bs-theme="dark"] { --main-bg: #111827; }
424
- body { background-color: var(--main-bg); font-family: 'Inter', sans-serif; }
425
- .sidebar { position: fixed; top: 0; left: 0; width: var(--sidebar-width); height: 100vh; background-color: #111827; z-index: 1030; }
426
- .sidebar-brand { font-size: 1.5rem; font-weight: 700; color: white; text-decoration: none; }
427
- .sidebar .nav-link { color: #9ca3af; }
428
- .sidebar .nav-link:hover, .sidebar .nav-link.active { color: #ffffff; background-color: #374151; }
429
- .main-content { margin-left: var(--sidebar-width); padding-top: var(--topbar-height); }
430
- .topbar { position: fixed; top: 0; right: 0; left: var(--sidebar-width); height: var(--topbar-height); background: var(--bs-body-bg); border-bottom: 1px solid var(--bs-border-color); z-index: 1020; }
431
- .card { box-shadow: 0 1px 3px 0 rgba(0,0,0,0.1), 0 1px 2px -1px rgba(0,0,0,0.1); }
432
- @media (max-width: 992px) {
433
- .sidebar { transform: translateX(calc(-1 * var(--sidebar-width))); }
434
- .sidebar.active { transform: translateX(0); }
435
- .main-content, .topbar { margin-left: 0; left: 0; }
436
- }
437
- #scanner-container { position: relative; width: 100%; max-width: 500px; margin: auto; }
438
- #html5-qrcode-scanner-camera-permission-button { font-size: 1rem !important; padding: 0.5rem 1rem !important; }
439
- #html5-qrcode-scanner-button-stop-scanning { display: none !important; }
440
- </style>
441
- </head>
442
- <body>
443
- <div class="sidebar p-3">
444
- <a href="{{ url_for('index') }}" class="sidebar-brand d-block mb-3 text-center">
445
- <i class="fas fa-cash-register"></i> POS System
446
- </a>
447
- <nav class="nav flex-column nav-pills">
448
- <a class="nav-link {% if request.endpoint == 'index' %}active{% endif %}" href="{{ url_for('index') }}"><i class="fas fa-fw fa-tachometer-alt me-2"></i>Панель</a>
449
- <a class="nav-link {% if request.endpoint == 'pos_terminal' %}active{% endif %}" href="{{ url_for('pos_terminal') }}"><i class="fas fa-fw fa-barcode me-2"></i>Касса</a>
450
- <a class="nav-link {% if request.endpoint == 'inventory_page' %}active{% endif %}" href="{{ url_for('inventory_page') }}"><i class="fas fa-fw fa-boxes me-2"></i>Склад</a>
451
- <a class="nav-link {% if request.endpoint == 'sales_history' %}active{% endif %}" href="{{ url_for('sales_history') }}"><i class="fas fa-fw fa-history me-2"></i>Продажи</a>
452
- <a class="nav-link {% if request.endpoint == 'cash_registers_page' %}active{% endif %}" href="{{ url_for('cash_registers_page') }}"><i class="fas fa-fw fa-calculator me-2"></i>Кассы</a>
453
- </nav>
454
- </div>
455
- <div class="main-content">
456
- <header class="topbar d-flex align-items-center justify-content-between px-3">
457
- <button class="btn btn-outline-secondary d-lg-none" id="sidebar-toggle"><i class="fas fa-bars"></i></button>
458
- <h4 class="h5 mb-0 d-none d-lg-block">__TITLE__</h4>
459
- <div class="d-flex align-items-center">
460
- <form method="POST" action="{{ url_for('backup_hf') }}" class="me-2 mb-0">
461
- <button type="submit" class="btn btn-sm btn-outline-secondary" title="Backup to Hugging Face"><i class="fas fa-cloud-upload-alt me-1"></i> Backup</button>
462
- </form>
463
- <form method="GET" action="{{ url_for('download_hf') }}" onsubmit="return confirm('ОСТОРОЖНО! Перезапишет локальные данные с Hugging Face. Уверены?');" class="mb-0">
464
- <button type="submit" class="btn btn-sm btn-outline-secondary" title="Download DBs from Hugging Face"><i class="fas fa-cloud-download-alt me-1"></i> Download</button>
465
- </form>
466
- </div>
467
- </header>
468
- <main class="p-3 p-lg-4">
469
- {% with messages = get_flashed_messages(with_categories=true) %}
470
- {% if messages %}
471
- {% for category, message in messages %}
472
- <div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
473
- {{ message }}
474
- <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
475
- </div>
476
- {% endfor %}
477
- {% endif %}
478
- {% endwith %}
479
- __CONTENT__
480
- </main>
481
- </div>
482
- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
483
- <script>
484
- document.addEventListener('DOMContentLoaded', () => {
485
- const sidebarToggle = document.getElementById('sidebar-toggle');
486
- const sidebar = document.querySelector('.sidebar');
487
- if(sidebarToggle && sidebar) {
488
- sidebarToggle.addEventListener('click', () => sidebar.classList.toggle('active'));
489
- }
490
- });
491
- </script>
492
- __SCRIPTS__
493
- </body>
494
- </html>
495
- """
496
-
497
- DASHBOARD_CONTENT = """
498
- <div class="row">
499
- <div class="col-lg-8">
500
- <div class="row">
501
- <div class="col-md-6 mb-4"><div class="card h-100 text-bg-primary"><div class="card-body"> <h6 class="card-subtitle mb-2">Продажи сегодня</h6> <p class="card-text display-5 fw-bold">{{ format_currency_py(stats.total_sales_today) }}</p><small>{{ stats.sales_count_today }} чеков</small></div></div></div>
502
- <div class="col-md-6 mb-4"><div class="card h-100"><div class="card-body"> <h6 class="card-subtitle mb-2 text-body-secondary">Товаров на складе</h6> <p class="card-text display-5 fw-bold">{{ stats.inventory_count }}</p><small>уникальных позиций</small></div></div></div>
503
- </div>
504
- <div class="card mb-4">
505
- <div class="card-header text-bg-warning"><h5 class="mb-0"><i class="fas fa-exclamation-triangle me-2"></i>Заканчиваются товары (<= 5)</h5></div>
506
- {% if low_stock_items %}<div class="list-group list-group-flush">
507
- {% for item in low_stock_items %}<div class="list-group-item d-flex justify-content-between align-items-center">{{ item.name }} <span class="badge bg-danger rounded-pill">{{ format_integer_py(item.quantity) }} шт.</span></div>{% endfor %}
508
- </div>{% else %}<div class="card-body text-center text-body-secondary">Нет товаров с низким остатком.</div>{% endif %}
509
- </div>
510
- </div>
511
- <div class="col-lg-4 mb-4">
512
- <div class="card">
513
- <div class="card-header text-bg-info"><h5 class="mb-0"><i class="fas fa-cash-register me-2"></i>Статус касс</h5></div>
514
- {% if cash_registers %}<div class="list-group list-group-flush">
515
- {% for register in cash_registers %}
516
- <div class="list-group-item">
517
- <div class="d-flex w-100 justify-content-between">
518
- <h6 class="mb-1">{{ register.name }}</h6>
519
- <span class="badge rounded-pill text-bg-{{ 'success' if register.is_open else 'secondary' }}">{{ 'Открыта' if register.is_open else 'Закрыта' }}</span>
520
- </div>
521
- <p class="mb-1">В кассе: <strong>{{ format_currency_py(register.current_balance) }} сом</strong></p>
522
- </div>
523
- {% endfor %}
524
- </div>{% else %}<div class="card-body text-center text-body-secondary">Нет зарегистрированных касс.</div>{% endif %}
525
- </div>
526
- </div>
527
- </div>
528
- """
529
-
530
- POS_TERMINAL_CONTENT = """
531
- <div class="row">
532
- <div class="col-lg-5 mb-4">
533
- <div class="card">
534
- <div class="card-header">
535
- <label for="cash-register-select" class="form-label">Рабочая касса</label>
536
- <select id="cash-register-select" class="form-select">
537
- <option value="">-- Выберите кассу --</option>
538
- {% for register in open_registers %}<option value="{{ register.id }}">{{ register.name }}</option>{% endfor %}
539
- </select>
540
- </div>
541
- <div class="card-body">
542
- <div id="scanner-container">
543
- <div id="qr-reader" style="width:100%"></div>
544
- </div>
545
- <div id="scanner-status" class="text-center mt-2 text-body-secondary"></div>
546
- </div>
547
- </div>
548
- </div>
549
- <div class="col-lg-7">
550
- <div class="card">
551
- <div class="card-header"><h5 class="mb-0">Текущий чек</h5></div>
552
- <div class="card-body">
553
- <div class="table-responsive" style="min-height: 200px;">
554
- <table class="table" id="cart-table">
555
- <thead><tr><th>Товар</th><th>Цена</th><th>Кол-во</th><th>Сумма</th><th></th></tr></thead>
556
- <tbody></tbody>
557
- </table>
558
- </div>
559
- <div class="text-center" id="cart-empty-msg"><p class="text-body-secondary">Отсканируйте товар для добавления</p></div>
560
- </div>
561
- <div class="card-footer">
562
- <div class="d-flex justify-content-between align-items-center mb-3">
563
- <h4 class="mb-0">Итого:</h4>
564
- <h4 class="mb-0"><span id="cart-total">0,00</span> сом</h4>
565
- </div>
566
- <div class="d-grid gap-2 d-md-flex justify-content-md-end">
567
- <button class="btn btn-outline-danger" id="clear-cart-btn" disabled><i class="fas fa-times me-1"></i>Очистить</button>
568
- <button class="btn btn-success btn-lg" id="pay-cash-btn" disabled><i class="fas fa-money-bill-wave me-2"></i>Наличные</button>
569
- <button class="btn btn-primary btn-lg" id="pay-card-btn" disabled><i class="fas fa-credit-card me-2"></i>Карта</button>
570
- </div>
571
- </div>
572
- </div>
573
- </div>
574
- </div>
575
- """
576
-
577
- POS_TERMINAL_SCRIPTS = """
578
- <script src="https://unpkg.com/html5-qrcode@2.0.9/dist/html5-qrcode.min.js"></script>
579
- <script>
580
- document.addEventListener('DOMContentLoaded', () => {
581
- let cart = [];
582
- const qrReader = document.getElementById('qr-reader');
583
- const cartTableBody = document.querySelector('#cart-table tbody');
584
- const cartTotalEl = document.getElementById('cart-total');
585
- const payCashBtn = document.getElementById('pay-cash-btn');
586
- const payCardBtn = document.getElementById('pay-card-btn');
587
- const clearCartBtn = document.getElementById('clear-cart-btn');
588
- const cartEmptyMsg = document.getElementById('cart-empty-msg');
589
- const registerSelect = document.getElementById('cash-register-select');
590
- const scannerStatus = document.getElementById('scanner-status');
591
-
592
- function updateCartDisplay() {
593
- cartTableBody.innerHTML = '';
594
- let total = 0;
595
- if (cart.length === 0) {
596
- cartEmptyMsg.style.display = 'block';
597
- payCashBtn.disabled = true;
598
- payCardBtn.disabled = true;
599
- clearCartBtn.disabled = true;
600
- } else {
601
- cartEmptyMsg.style.display = 'none';
602
- payCashBtn.disabled = false;
603
- payCardBtn.disabled = false;
604
- clearCartBtn.disabled = false;
605
-
606
- cart.forEach((item, index) => {
607
- const itemTotal = item.selling_price * item.quantity;
608
- total += itemTotal;
609
- const row = `
610
- <tr>
611
- <td>${item.name}</td>
612
- <td>${formatCurrency(item.selling_price)}</td>
613
- <td>
614
- <div class="input-group input-group-sm" style="width: 100px;">
615
- <button class="btn btn-outline-secondary" type="button" onclick="updateQuantity(${index}, -1)">-</button>
616
- <input type="text" class="form-control text-center" value="${item.quantity}" readonly>
617
- <button class="btn btn-outline-secondary" type="button" onclick="updateQuantity(${index}, 1)">+</button>
618
- </div>
619
- </td>
620
- <td>${formatCurrency(itemTotal)}</td>
621
- <td><button class="btn btn-sm btn-outline-danger" onclick="removeFromCart(${index})"><i class="fas fa-trash"></i></button></td>
622
- </tr>
623
- `;
624
- cartTableBody.innerHTML += row;
625
- });
626
- }
627
- cartTotalEl.textContent = formatCurrency(total);
628
- }
629
-
630
- window.updateQuantity = (index, change) => {
631
- if (cart[index]) {
632
- const newQuantity = cart[index].quantity + change;
633
- if (newQuantity > 0) {
634
- cart[index].quantity = newQuantity;
635
- } else {
636
- cart.splice(index, 1);
637
- }
638
- updateCartDisplay();
639
- }
640
- };
641
-
642
- window.removeFromCart = (index) => {
643
- cart.splice(index, 1);
644
- updateCartDisplay();
645
- };
646
-
647
- function onScanSuccess(decodedText, decodedResult) {
648
- scannerStatus.textContent = `Сканирование...`;
649
- fetch(`/api/product/barcode/${decodedText}`)
650
- .then(response => {
651
- if (!response.ok) throw new Error('Товар не найден');
652
- return response.json();
653
- })
654
- .then(product => {
655
- const existingItem = cart.find(item => item.id === product.id);
656
- if (existingItem) {
657
- existingItem.quantity++;
658
- } else {
659
- cart.push({
660
- ...product,
661
- quantity: 1,
662
- selling_price: parseFloat(product.selling_price)
663
- });
664
- }
665
- updateCartDisplay();
666
- scannerStatus.textContent = `Добавлено: ${product.name}`;
667
- })
668
- .catch(error => {
669
- scannerStatus.textContent = `Ошибка: ${error.message}`;
670
- console.error('Error:', error);
671
- });
672
- }
673
-
674
- function startScanner() {
675
- if (!registerSelect.value) {
676
- scannerStatus.textContent = "Сначала выберите кассу";
677
- qrReader.style.display = 'none';
678
- return;
679
- }
680
- qrReader.style.display = 'block';
681
- scannerStatus.textContent = "Запуск сканера...";
682
- const html5QrCode = new Html5Qrcode("qr-reader");
683
- html5QrCode.start(
684
- { facingMode: "environment" },
685
- { fps: 10, qrbox: 250 },
686
- onScanSuccess,
687
- (errorMessage) => {}
688
- ).catch((err) => {
689
- scannerStatus.textContent = "Не удалось запустить сканер.";
690
- });
691
- }
692
-
693
- registerSelect.addEventListener('change', startScanner);
694
-
695
- function clearCart() {
696
- cart = [];
697
- updateCartDisplay();
698
- }
699
-
700
- async function completeSale(paymentMethod) {
701
- if (cart.length === 0 || !registerSelect.value) return;
702
-
703
- payCashBtn.disabled = true;
704
- payCardBtn.disabled = true;
705
-
706
- try {
707
- const response = await fetch('/pos/complete_sale', {
708
- method: 'POST',
709
- headers: { 'Content-Type': 'application/json' },
710
- body: JSON.stringify({ cart, paymentMethod, cashRegisterId: registerSelect.value })
711
- });
712
- const result = await response.json();
713
- if (result.success) {
714
- alert(`Продажа #${result.sale_id.substring(0,8)} успешно завершена!`);
715
- clearCart();
716
- } else {
717
- throw new Error(result.error || 'Неизвестная ошибка');
718
- }
719
- } catch (error) {
720
- alert(`Ошибка при завершении продажи: ${error.message}`);
721
- } finally {
722
- updateCartDisplay();
723
- }
724
- }
725
-
726
- payCashBtn.addEventListener('click', () => completeSale('cash'));
727
- payCardBtn.addEventListener('click', () => completeSale('card'));
728
- clearCartBtn.addEventListener('click', clearCart);
729
-
730
- function formatCurrency(value) {
731
- return new Intl.NumberFormat('ru-RU', { style: 'decimal', minimumFractionDigits: 2 }).format(value);
732
- }
733
-
734
- updateCartDisplay();
735
- startScanner();
736
- });
737
- </script>
738
- """
739
-
740
- INVENTORY_CONTENT = """
741
- <div class="mb-4">
742
- <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#addProductCollapse" aria-expanded="false" aria-controls="addProductCollapse">
743
- <i class="fas fa-plus me-1"></i> Добавить новый товар
744
- </button>
745
- </div>
746
- <div class="collapse" id="addProductCollapse">
747
- <div class="card card-body mb-4">
748
- <form method="POST" action="{{ url_for('inventory_page') }}">
749
- <input type="hidden" name="action" value="add">
750
- <div class="row g-3">
751
- <div class="col-md-6"><label for="name" class="form-label">Название</label><input type="text" class="form-control" name="name" required></div>
752
- <div class="col-md-6"><label for="barcode" class="form-label">Штрих-код</label>
753
- <div class="input-group">
754
- <input type="text" class="form-control" name="barcode" id="barcode-input" required>
755
- <button class="btn btn-outline-secondary" type="button" data-bs-toggle="modal" data-bs-target="#scanModal"><i class="fas fa-barcode"></i></button>
756
- </div>
757
- </div>
758
- <div class="col-md-6"><label for="category" class="form-label">Категория</label><input type="text" class="form-control" name="category" list="category-list" value="Без категории"><datalist id="category-list">{% for cat in categories %}<option value="{{ cat }}">{% endfor %}</datalist></div>
759
- <div class="col-md-3"><label for="quantity" class="form-label">Количество</label><input type="number" class="form-control" name="quantity" value="0" step="1"></div>
760
- <div class="col-md-3"><label for="purchase_price" class="form-label">Цена закупа</label><input type="text" class="form-control" name="purchase_price" value="0" inputmode="decimal"></div>
761
- <div class="col-md-3"><label for="selling_price" class="form-label">Цена продажи</label><input type="text" class="form-control" name="selling_price" value="0" inputmode="decimal"></div>
762
- </div>
763
- <button type="submit" class="btn btn-success mt-3">Сохранить товар</button>
764
- </form>
765
- </div>
766
- </div>
767
- <div class="card">
768
- <div class="card-header"><h5 class="mb-0">Список товаров</h5></div>
769
- <div class="card-body">
770
- <input type="text" id="inventory-search" class="form-control mb-3" placeholder="Поиск по названию или штрих-коду...">
771
- <div class="table-responsive">
772
- <table class="table table-hover table-sm" id="inventory-table">
773
- <thead><tr><th>Название</th><th>Штрих-код</th><th>Категория</th><th>Кол-во</th><th>Закуп</th><th>Продажа</th><th>Действия</th></tr></thead>
774
- <tbody>
775
- {% for product in inventory %}
776
- <tr data-search="{{ product.name|lower }} {{ product.barcode }}">
777
- <td>{{ product.name }}</td><td>{{ product.barcode }}</td><td>{{ product.category }}</td><td>{{ format_integer_py(product.quantity) }}</td><td>{{ format_currency_py(product.purchase_price) }}</td><td>{{ format_currency_py(product.selling_price) }}</td>
778
- <td>
779
- <div class="btn-group btn-group-sm">
780
- <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editModal-{{ product.id }}"><i class="fas fa-edit"></i></button>
781
- <form action="{{ url_for('delete_product', product_id=product.id) }}" method="POST" onsubmit="return confirm('Удалить товар?');" class="d-inline">
782
- <button type="submit" class="btn btn-outline-danger"><i class="fas fa-trash"></i></button>
783
- </form>
784
- </div>
785
- </td>
786
- </tr>
787
- {% endfor %}
788
- </tbody>
789
- </table>
790
- </div>
791
- </div>
792
- </div>
793
- {% for product in inventory %}
794
- <div class="modal fade" id="editModal-{{ product.id }}" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
795
- <div class="modal-header"><h5 class="modal-title">Редактировать товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
796
- <form method="POST" action="{{ url_for('inventory_page') }}">
797
- <input type="hidden" name="action" value="edit">
798
- <input type="hidden" name="product_id" value="{{ product.id }}">
799
- <div class="modal-body">
800
- <div class="mb-3"><label class="form-label">Название</label><input type="text" class="form-control" name="name" value="{{ product.name }}" required></div>
801
- <div class="mb-3"><label class="form-label">Штрих-код</label><input type="text" class="form-control" name="barcode" value="{{ product.barcode }}" required></div>
802
- <div class="mb-3"><label class="form-label">Категория</label><input type="text" class="form-control" name="category" value="{{ product.category }}" list="category-list"></div>
803
- <div class="mb-3"><label class="form-label">Количество</label><input type="number" class="form-control" name="quantity" value="{{ product.quantity }}" step="1"></div>
804
- <div class="mb-3"><label class="form-label">Цена закупа</label><input type="text" class="form-control" name="purchase_price" value="{{ product.purchase_price|replace('.', ',') }}" inputmode="decimal"></div>
805
- <div class="mb-3"><label class="form-label">Цена продажи</label><input type="text" class="form-control" name="selling_price" value="{{ product.selling_price|replace('.', ',') }}" inputmode="decimal"></div>
806
- </div>
807
- <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
808
- </form>
809
- </div></div></div>
810
- {% endfor %}
811
- <div class="modal fade" id="scanModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
812
- <div class="modal-header"><h5 class="modal-title">Сканировать штрих-код</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
813
- <div class="modal-body"><div id="modal-scanner"></div><div id="modal-scanner-status" class="text-center mt-2"></div></div>
814
- </div></div></div>
815
- """
816
-
817
- INVENTORY_SCRIPTS = """
818
- <script src="https://unpkg.com/html5-qrcode@2.0.9/dist/html5-qrcode.min.js"></script>
819
- <script>
820
- document.addEventListener('DOMContentLoaded', () => {
821
- const searchInput = document.getElementById('inventory-search');
822
- const tableBody = document.querySelector('#inventory-table tbody');
823
- searchInput.addEventListener('input', () => {
824
- const searchTerm = searchInput.value.toLowerCase();
825
- tableBody.querySelectorAll('tr').forEach(row => {
826
- row.style.display = row.dataset.search.includes(searchTerm) ? '' : 'none';
827
- });
828
- });
829
-
830
- const scanModal = document.getElementById('scanModal');
831
- const modalScanner = new Html5Qrcode("modal-scanner");
832
-
833
- scanModal.addEventListener('shown.bs.modal', () => {
834
- const statusEl = document.getElementById('modal-scanner-status');
835
- statusEl.textContent = 'Запуск камеры...';
836
- modalScanner.start(
837
- { facingMode: "environment" },
838
- { fps: 10, qrbox: 250 },
839
- (decodedText, decodedResult) => {
840
- document.getElementById('barcode-input').value = decodedText;
841
- modalScanner.stop();
842
- bootstrap.Modal.getInstance(scanModal).hide();
843
- },
844
- (errorMessage) => {}
845
- ).catch((err) => {
846
- statusEl.textContent = 'Ошибка запуска камеры.';
847
- });
848
- });
849
-
850
- scanModal.addEventListener('hidden.bs.modal', () => {
851
- if (modalScanner.isScanning) {
852
- modalScanner.stop();
853
- }
854
- });
855
- });
856
- </script>
857
- """
858
-
859
- SALES_HISTORY_CONTENT = """
860
- <div class="card">
861
- <div class="card-header"><h5 class="mb-0">История продаж</h5></div>
862
- <div class="card-body">
863
- <div class="table-responsive">
864
- <table class="table table-hover">
865
- <thead><tr><th>ID Продажи</th><th>Дата и время</th><th>Касса</th><th>Сумма</th><th>Тип оплаты</th><th>Позиции</th></tr></thead>
866
- <tbody>
867
- {% for sale in sales %}
868
- <tr>
869
- <td><small class="font-monospace">{{ sale.id[:8] }}</small></td>
870
- <td>{{ sale.timestamp[:19]|replace('T', ' ') }}</td>
871
- <td>{{ sale.get('cash_register_id', 'N/A')[:8] }}</td>
872
- <td>{{ format_currency_py(sale.total) }} сом</td>
873
- <td><span class="badge text-bg-{{ 'success' if sale.payment_method == 'cash' else 'primary' }}">{{ 'Наличные' if sale.payment_method == 'cash' else 'Карта' }}</span></td>
874
- <td>{{ sale.items|length }}</td>
875
- </tr>
876
- {% else %}
877
- <tr><td colspan="6" class="text-center text-body-secondary">Продаж еще не было.</td></tr>
878
- {% endfor %}
879
- </tbody>
880
- </table>
881
- </div>
882
- </div>
883
- </div>
884
- """
885
-
886
- CASH_REGISTERS_CONTENT = """
887
- <div class="card mb-4">
888
- <div class="card-header"><h5 class="mb-0">Добавить кассу</h5></div>
889
- <div class="card-body">
890
- <form method="POST" action="{{ url_for('cash_registers_page') }}">
891
- <input type="hidden" name="action" value="add">
892
- <div class="input-group">
893
- <input type="text" name="name" class="form-control" placeholder="Название, напр. Касса 1" required>
894
- <button type="submit" class="btn btn-primary">Добавить</button>
895
- </div>
896
- </form>
897
- </div>
898
- </div>
899
- <div class="card">
900
- <div class="card-header"><h5 class="mb-0">Список касс</h5></div>
901
- <div class="list-group list-group-flush">
902
- {% for register in registers %}
903
- <div class="list-group-item">
904
- <div class="d-flex w-100 justify-content-between">
905
- <div>
906
- <h5 class="mb-1">{{ register.name }}</h5>
907
- <p class="mb-1">Текущий баланс: <strong>{{ format_currency_py(register.current_balance) }} сом</strong></p>
908
- </div>
909
- <div class="d-flex flex-column align-items-end">
910
- <form method="POST" action="{{ url_for('cash_registers_page') }}" class="mb-2">
911
- <input type="hidden" name="action" value="toggle_open">
912
- <input type="hidden" name="register_id" value="{{ register.id }}">
913
- <button type="submit" class="btn btn-sm btn-{{ 'warning' if register.is_open else 'success' }}">
914
- {{ 'Закрыть смену' if register.is_open else 'Открыть смену' }}
915
- </button>
916
- </form>
917
- <form method="POST" action="{{ url_for('cash_registers_page') }}" onsubmit="return confirm('Удалить кассу?');">
918
- <input type="hidden" name="action" value="delete">
919
- <input type="hidden" name="register_id" value="{{ register.id }}">
920
- <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
921
- </form>
922
- </div>
923
- </div>
924
- </div>
925
- {% else %}
926
- <div class="list-group-item text-center text-body-secondary">Кассы еще не добавлены.</div>
927
- {% endfor %}
928
- </div>
929
- </div>
930
- """
931
-
932
- if __name__ == '__main__':
933
- backup_thread = threading.Thread(target=periodic_backup, daemon=True)
934
- backup_thread.start()
935
- logging.info("Starting Flask application on http://0.0.0.0:7860")
936
- app.run(debug=False, host='0.0.0.0', port=7860, use_reloader=False)
937
-