Kgshop commited on
Commit
ef64fb1
·
verified ·
1 Parent(s): e97500a

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1466
app.py DELETED
@@ -1,1466 +0,0 @@
1
- from flask import Flask, render_template_string, request, redirect, url_for
2
- import json
3
- import os
4
- import threading
5
- import time
6
- import uuid
7
- from datetime import datetime
8
- import zoneinfo
9
- from huggingface_hub import HfApi, hf_hub_download
10
-
11
- app = Flask(__name__)
12
- DATA_FILE = 'data_fabrics.json'
13
- REPO_ID = "Kgshop/vahid"
14
- HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
15
- HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
16
-
17
- INITIALIZED = False
18
-
19
- def get_almaty_time():
20
- return datetime.now(zoneinfo.ZoneInfo("Asia/Almaty")).strftime('%d.%m.%Y %H:%M:%S')
21
-
22
- def load_data():
23
- global INITIALIZED
24
- if not INITIALIZED:
25
- try:
26
- hf_hub_download(
27
- repo_id=REPO_ID,
28
- filename=DATA_FILE,
29
- repo_type="dataset",
30
- token=HF_TOKEN_READ,
31
- local_dir=".",
32
- local_dir_use_symlinks=False
33
- )
34
- except Exception:
35
- pass
36
- INITIALIZED = True
37
-
38
- try:
39
- with open(DATA_FILE, 'r', encoding='utf-8') as file:
40
- data = json.load(file)
41
- if not isinstance(data, dict):
42
- data = {'products': [], 'history': []}
43
- if 'settings' not in data:
44
- data['settings'] = {
45
- 'warehouses': [{'id': 'w_main', 'name': 'Основной склад'}],
46
- 'shops': [{'id': 's_main', 'name': 'Основной магазин'}],
47
- 'employees': []
48
- }
49
- if 'products' not in data:
50
- data['products'] = []
51
- if 'history' not in data:
52
- data['history'] = []
53
-
54
- for p in data['products']:
55
- if 'price_retail' not in p:
56
- p['price_retail'] = p.get('price', 0)
57
- if 'price_wholesale' not in p:
58
- p['price_wholesale'] = p.get('price', 0)
59
- if 'variants' not in p:
60
- p['variants'] = []
61
- if 'photo' not in p:
62
- p['photo'] = ''
63
- if 'box_qty' not in p:
64
- p['box_qty'] = 1
65
- if 'stocks' not in p:
66
- p['stocks'] = {}
67
- if 'colors' in p:
68
- for c in p['colors']:
69
- for loc, amt in c.get('stocks', {}).items():
70
- p['stocks'][loc] = int(p['stocks'].get(loc, 0)) + int(amt)
71
- del p['colors']
72
-
73
- for v in p['variants']:
74
- if 'stocks' not in v:
75
- v['stocks'] = {}
76
- return data
77
- except Exception:
78
- return {
79
- 'settings': {
80
- 'warehouses': [{'id': 'w_main', 'name': 'Основной склад'}],
81
- 'shops': [{'id': 's_main', 'name': 'Основной магазин'}],
82
- 'employees': []
83
- },
84
- 'products': [],
85
- 'history': []
86
- }
87
-
88
- def save_data(data):
89
- try:
90
- with open(DATA_FILE, 'w', encoding='utf-8') as file:
91
- json.dump(data, file, ensure_ascii=False, indent=4)
92
- threading.Thread(target=upload_db_to_hf, daemon=True).start()
93
- except Exception:
94
- pass
95
-
96
- def upload_db_to_hf():
97
- try:
98
- api = HfApi()
99
- api.upload_file(
100
- path_or_fileobj=DATA_FILE,
101
- path_in_repo=DATA_FILE,
102
- repo_id=REPO_ID,
103
- repo_type="dataset",
104
- token=HF_TOKEN_WRITE,
105
- commit_message=f"Backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
106
- )
107
- except Exception:
108
- pass
109
-
110
- def periodic_backup():
111
- while True:
112
- upload_db_to_hf()
113
- time.sleep(800)
114
-
115
- def add_history(data, action, product, amount, price, from_loc, to_loc, emp_name):
116
- data['history'].insert(0, {
117
- 'time': get_almaty_time(),
118
- 'action': action,
119
- 'product': product,
120
- 'amount': int(amount),
121
- 'price': int(price),
122
- 'from_loc_name': from_loc,
123
- 'to_loc_name': to_loc,
124
- 'emp_name': emp_name
125
- })
126
- data['history'] = data['history'][:1000]
127
-
128
- def get_loc_name(data, loc_id):
129
- for w in data['settings']['warehouses']:
130
- if w['id'] == loc_id: return w['name']
131
- for s in data['settings']['shops']:
132
- if s['id'] == loc_id: return s['name']
133
- return loc_id
134
-
135
- def handle_post(req, data, role, emp):
136
- action = req.form.get('action')
137
- emp_name = emp['name'] if emp else 'Админ'
138
-
139
- if action == 'add' and role == 'admin':
140
- loc_id = req.form.get('loc_id')
141
- try:
142
- price_retail = int(req.form.get('price_retail', 0))
143
- except ValueError:
144
- price_retail = 0
145
- try:
146
- price_wholesale = int(req.form.get('price_wholesale', 0))
147
- except ValueError:
148
- price_wholesale = 0
149
-
150
- photo = req.form.get('photo', '')
151
- try:
152
- rolls = int(req.form.get('rolls', 0))
153
- except ValueError:
154
- rolls = 0
155
- try:
156
- box_qty = int(req.form.get('box_qty', 1))
157
- except ValueError:
158
- box_qty = 1
159
-
160
- v_names = req.form.getlist('v_name[]')
161
- v_prices = req.form.getlist('v_price[]')
162
- v_stocks = req.form.getlist('v_stock[]')
163
-
164
- variants = []
165
- has_variants = False
166
- for n, pr, st in zip(v_names, v_prices, v_stocks):
167
- n_strip = n.strip()
168
- if n_strip:
169
- has_variants = True
170
- try:
171
- pr_val = int(pr)
172
- except ValueError:
173
- pr_val = 0
174
- try:
175
- st_val = int(st)
176
- except ValueError:
177
- st_val = 0
178
- variants.append({'name': n_strip, 'price': pr_val, 'stocks': {loc_id: st_val}})
179
-
180
- p_stocks = {} if has_variants else {loc_id: rolls}
181
-
182
- data['products'].insert(0, {
183
- 'id': str(time.time()),
184
- 'name': req.form['name'],
185
- 'description': req.form['description'],
186
- 'price_retail': price_retail,
187
- 'price_wholesale': price_wholesale,
188
- 'variants': variants,
189
- 'photo': photo,
190
- 'box_qty': box_qty,
191
- 'stocks': p_stocks
192
- })
193
-
194
- elif action == 'edit' and role == 'admin':
195
- try:
196
- idx = int(req.form['index'])
197
- except ValueError:
198
- return
199
-
200
- if 0 <= idx < len(data['products']):
201
- p = data['products'][idx]
202
- p['name'] = req.form.get('name', p['name'])
203
- p['description'] = req.form.get('description', p.get('description', ''))
204
- try:
205
- p['price_retail'] = int(req.form.get('price_retail', p.get('price_retail', 0)))
206
- except ValueError:
207
- pass
208
- try:
209
- p['price_wholesale'] = int(req.form.get('price_wholesale', p.get('price_wholesale', 0)))
210
- except ValueError:
211
- pass
212
- try:
213
- p['box_qty'] = int(req.form.get('box_qty', p.get('box_qty', 1)))
214
- except ValueError:
215
- pass
216
-
217
- edit_loc_id = req.form.get('edit_loc_id')
218
- try:
219
- new_rolls = int(req.form.get('rolls', 0))
220
- except ValueError:
221
- new_rolls = 0
222
-
223
- v_names = req.form.getlist('v_name[]')
224
- v_prices = req.form.getlist('v_price[]')
225
- v_stocks = req.form.getlist('v_stock[]')
226
-
227
- new_variants = []
228
- for i, (n, pr, st) in enumerate(zip(v_names, v_prices, v_stocks)):
229
- n_strip = n.strip()
230
- if n_strip:
231
- existing_stocks = {}
232
- for old_v in p.get('variants', []):
233
- if old_v.get('name') == n_strip:
234
- existing_stocks = dict(old_v.get('stocks', {}))
235
- break
236
-
237
- if not existing_stocks and 'variants' in p and i < len(p['variants']):
238
- existing_stocks = dict(p['variants'][i].get('stocks', {}))
239
-
240
- try:
241
- st_val = int(st)
242
- except ValueError:
243
- st_val = 0
244
-
245
- if edit_loc_id:
246
- existing_stocks[edit_loc_id] = st_val
247
-
248
- try:
249
- pr_val = int(pr)
250
- except ValueError:
251
- pr_val = 0
252
-
253
- new_variants.append({'name': n_strip, 'price': pr_val, 'stocks': existing_stocks})
254
-
255
- p['variants'] = new_variants
256
-
257
- if new_variants:
258
- p['stocks'] = {}
259
- else:
260
- if 'stocks' not in p:
261
- p['stocks'] = {}
262
- if edit_loc_id:
263
- p['stocks'][edit_loc_id] = new_rolls
264
-
265
- photo = req.form.get('photo', '')
266
- if photo:
267
- p['photo'] = photo
268
-
269
- elif action == 'delete' and role == 'admin':
270
- try:
271
- idx = int(req.form['index'])
272
- except ValueError:
273
- return
274
-
275
- if 0 <= idx < len(data['products']):
276
- del_name = data['products'][idx]['name']
277
- data['products'].pop(idx)
278
- add_history(data, 'Удаление', del_name, 0, 0, '', '', emp_name)
279
-
280
- elif action == 'income' and role == 'admin':
281
- try:
282
- idx = int(req.form['product_index'])
283
- amt = int(req.form['rolls'])
284
- except ValueError:
285
- return
286
-
287
- if amt < 0 or not (0 <= idx < len(data['products'])):
288
- return
289
-
290
- loc_id = req.form['loc_id']
291
- v_idx_str = req.form.get('v_index')
292
- p = data['products'][idx]
293
-
294
- prod_name_history = p['name']
295
- if v_idx_str and v_idx_str.isdigit():
296
- v_idx = int(v_idx_str)
297
- if 0 <= v_idx < len(p.get('variants', [])):
298
- v = p['variants'][v_idx]
299
- if 'stocks' not in v: v['stocks'] = {}
300
- v['stocks'][loc_id] = int(v['stocks'].get(loc_id, 0)) + amt
301
- prod_name_history += f" ({v['name']})"
302
- else:
303
- if 'stocks' not in p: p['stocks'] = {}
304
- p['stocks'][loc_id] = int(p['stocks'].get(loc_id, 0)) + amt
305
-
306
- add_history(data, 'Приход', prod_name_history, amt, p.get('price_wholesale', 0), '', get_loc_name(data, loc_id), emp_name)
307
-
308
- elif action == 'transfer' and role == 'admin':
309
- try:
310
- idx = int(req.form['pIndex'])
311
- amt = int(req.form['amt'])
312
- except ValueError:
313
- return
314
-
315
- if amt < 0:
316
- return
317
-
318
- try:
319
- v_idx = int(req.form.get('vIndex', -1))
320
- except ValueError:
321
- v_idx = -1
322
-
323
- from_loc = req.form['from_loc']
324
- to_loc = req.form['to_loc']
325
-
326
- if 0 <= idx < len(data['products']):
327
- p = data['products'][idx]
328
- prod_name_history = p['name']
329
-
330
- if v_idx != -1 and 0 <= v_idx < len(p.get('variants', [])):
331
- v = p['variants'][v_idx]
332
- if 'stocks' not in v:
333
- v['stocks'] = {}
334
- av = int(v['stocks'].get(from_loc, 0))
335
- if amt > av: amt = av
336
- if amt > 0:
337
- v['stocks'][from_loc] = av - amt
338
- v['stocks'][to_loc] = int(v['stocks'].get(to_loc, 0)) + amt
339
- prod_name_history += f" ({v['name']})"
340
- else:
341
- if 'stocks' not in p:
342
- p['stocks'] = {}
343
- av = int(p['stocks'].get(from_loc, 0))
344
- if amt > av: amt = av
345
- if amt > 0:
346
- p['stocks'][from_loc] = av - amt
347
- p['stocks'][to_loc] = int(p['stocks'].get(to_loc, 0)) + amt
348
-
349
- if amt > 0:
350
- from_name = get_loc_name(data, from_loc)
351
- to_name = get_loc_name(data, to_loc)
352
- add_history(data, 'Перемещение', prod_name_history, amt, 0, from_name, to_name, emp_name)
353
-
354
- elif action == 'checkout':
355
- cart_data = req.form.get('cart', '[]')
356
- try:
357
- cart = json.loads(cart_data)
358
- except Exception:
359
- cart = []
360
-
361
- for item in cart:
362
- idx = item.get('pIndex')
363
- v_idx = item.get('vIndex', -1)
364
-
365
- try:
366
- amt = int(item.get('amt', 0))
367
- except ValueError:
368
- amt = 0
369
-
370
- if amt <= 0:
371
- continue
372
-
373
- loc = item.get('loc')
374
- pName = item.get('pName')
375
-
376
- try:
377
- itemPrice = int(item.get('price', 0))
378
- except ValueError:
379
- itemPrice = 0
380
-
381
- if idx is not None and 0 <= int(idx) < len(data['products']):
382
- idx = int(idx)
383
- p = data['products'][idx]
384
- if v_idx != -1 and 0 <= v_idx < len(p.get('variants', [])):
385
- v = p['variants'][v_idx]
386
- if 'stocks' not in v:
387
- v['stocks'] = {}
388
- av = int(v['stocks'].get(loc, 0))
389
- if amt > av: amt = av
390
- if amt > 0:
391
- v['stocks'][loc] = av - amt
392
- loc_name = get_loc_name(data, loc)
393
- add_history(data, 'Продажа', pName, amt, itemPrice, loc_name, '', emp_name)
394
- else:
395
- if 'stocks' not in p:
396
- p['stocks'] = {}
397
- av = int(p['stocks'].get(loc, 0))
398
- if amt > av: amt = av
399
- if amt > 0:
400
- p['stocks'][loc] = av - amt
401
- loc_name = get_loc_name(data, loc)
402
- add_history(data, 'Продажа', pName, amt, itemPrice, loc_name, '', emp_name)
403
-
404
- elif action == 'add_loc' and role == 'admin':
405
- l_type = req.form['l_type']
406
- l_name = req.form['l_name']
407
- l_id = f"loc_{int(time.time()*1000)}"
408
- data['settings'][l_type].append({'id': l_id, 'name': l_name})
409
-
410
- elif action == 'del_loc' and role == 'admin':
411
- l_type = req.form['l_type']
412
- l_id = req.form['l_id']
413
- data['settings'][l_type] = [x for x in data['settings'][l_type] if x['id'] != l_id]
414
-
415
- elif action == 'add_emp' and role == 'admin':
416
- e_name = req.form['e_name']
417
- e_shop = req.form['e_shop']
418
- e_id = str(uuid.uuid4())[:8]
419
- data['settings']['employees'].append({'id': e_id, 'name': e_name, 'token': e_id, 'shop_id': e_shop})
420
-
421
- elif action == 'del_emp' and role == 'admin':
422
- e_id = req.form['e_id']
423
- data['settings']['employees'] = [x for x in data['settings']['employees'] if x['id'] != e_id]
424
-
425
- MAIN_HTML = '''
426
- <!DOCTYPE html>
427
- <html lang="ru">
428
- <head>
429
- <meta charset="UTF-8">
430
- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
431
- <title>Учет товаров</title>
432
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
433
- <style>
434
- :root {
435
- --bg: #f3f4f6;
436
- --surface: #ffffff;
437
- --primary: #4f46e5;
438
- --success: #10b981;
439
- --danger: #ef4444;
440
- --text-main: #111827;
441
- --text-muted: #6b7280;
442
- --border: #e5e7eb;
443
- }
444
- * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Inter', sans-serif; -webkit-tap-highlight-color: transparent; }
445
- body { background: var(--bg); color: var(--text-main); padding: 16px; padding-bottom: 80px; }
446
- .container { max-width: 1200px; margin: 0 auto; }
447
- h1 { text-align: center; font-size: 1.5rem; font-weight: 700; margin-bottom: 24px; }
448
-
449
- @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
450
-
451
- .top-actions { display: flex; gap: 12px; margin-bottom: 16px; flex-wrap: wrap; }
452
- .btn { flex: 1; padding: 12px; border: none; border-radius: 12px; font-size: 0.95rem; font-weight: 600; color: white; cursor: pointer; display: flex; justify-content: center; align-items: center; gap: 8px; transition: transform 0.1s, opacity 0.2s; }
453
- .btn:active { transform: scale(0.98); }
454
- .btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
455
- .btn-primary { background: var(--primary); }
456
- .btn-success { background: var(--success); }
457
- .btn-danger { background: var(--danger); }
458
-
459
- .main-nav { display: flex; gap: 8px; margin-bottom: 16px; overflow-x: auto; padding-bottom: 4px; }
460
- .nav-btn { flex: 0 0 auto; padding: 10px 16px; border-radius: 8px; border: none; background: #e5e7eb; color: var(--text-muted); font-weight: 600; font-size: 0.9rem; cursor: pointer; transition: background 0.2s, color 0.2s; }
461
- .nav-btn.active { background: var(--primary); color: white; }
462
-
463
- .loc-nav { display: flex; gap: 8px; margin-bottom: 16px; overflow-x: auto; padding-bottom: 4px; }
464
- .loc-btn { flex: 0 0 auto; padding: 8px 14px; border-radius: 20px; border: 1px solid var(--border); background: var(--surface); color: var(--text-main); font-weight: 500; font-size: 0.85rem; cursor: pointer; transition: all 0.2s; }
465
- .loc-btn.active { background: var(--text-main); color: white; border-color: var(--text-main); }
466
- .loc-btn.has-search-stock { border-color: var(--success) !important; color: var(--success) !important; background: #ecfdf5 !important; font-weight: 700; }
467
- .loc-btn.has-search-stock.active { background: var(--success) !important; color: white !important; }
468
-
469
- .search-box { width: 100%; padding: 14px; border: 1px solid var(--border); border-radius: 12px; outline: none; font-size: 1rem; margin-bottom: 16px; transition: border-color 0.2s; }
470
- .search-box:focus { border-color: var(--primary); }
471
-
472
- #catalog { display: flex; flex-direction: column; gap: 10px; }
473
-
474
- .product { background: var(--surface); border-radius: 10px; box-shadow: 0 1px 2px rgba(0,0,0,0.1); display: flex; flex-direction: column; overflow: hidden; padding: 10px; gap: 8px; }
475
- .product-main { display: flex; flex-direction: row; align-items: center; gap: 12px; }
476
- .product-img-wrapper { width: 50px; height: 50px; flex-shrink: 0; background: #f9fafb; display: flex; align-items: center; justify-content: center; border-radius: 8px; overflow: hidden; cursor: zoom-in; }
477
- .product-img { width: 100%; height: 100%; object-fit: cover; }
478
- .product-info { display: flex; flex-direction: column; flex: 1; justify-content: center; min-width: 0; }
479
- .product-title { font-size: 0.95rem; font-weight: 600; line-height: 1.2; margin-bottom: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
480
- .product-price { font-size: 0.85rem; font-weight: 700; color: var(--primary); }
481
- .product-stock { font-size: 0.75rem; color: var(--text-muted); }
482
- .product-actions { display: flex; flex-direction: column; gap: 6px; width: 100%; margin-top: 4px; }
483
-
484
- .qty-input { width: 60px; padding: 6px; border: 1px solid var(--border); border-radius: 6px; text-align: center; font-weight: 600; outline: none; font-size: 0.85rem; transition: border-color 0.2s; }
485
- .qty-input:focus { border-color: var(--primary); }
486
-
487
- .history-item { background: var(--surface); border-radius: 12px; padding: 16px; margin-bottom: 12px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
488
- .history-header { display: flex; justify-content: space-between; font-size: 0.85rem; color: var(--text-muted); margin-bottom: 8px; }
489
- .history-body { display: flex; justify-content: space-between; align-items: center; }
490
- .history-prod { font-weight: 600; }
491
- .history-badge { padding: 4px 10px; border-radius: 6px; font-size: 0.8rem; font-weight: 600; }
492
- .badge-green { background: #d1fae5; color: #065f46; }
493
- .badge-orange { background: #ffedd5; color: #9a3412; }
494
-
495
- .modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(17, 24, 39, 0.6); z-index: 1000; justify-content: center; align-items: flex-end; }
496
- .modal-overlay.active { display: flex; }
497
- .modal-content { background: var(--surface); padding: 24px; border-radius: 20px 20px 0 0; width: 100%; max-width: 600px; max-height: 90vh; overflow-y: auto; position: relative; }
498
-
499
- .close-modal { position: absolute; top: 20px; right: 20px; width: 32px; height: 32px; background: var(--bg); border-radius: 16px; display: flex; justify-content: center; align-items: center; cursor: pointer; border: none; font-size: 18px; }
500
- .form-control { width: 100%; padding: 10px; border: 1px solid var(--border); border-radius: 8px; font-size: 0.95rem; outline: none; margin-bottom: 10px; transition: border-color 0.2s; }
501
- .form-control:focus { border-color: var(--primary); }
502
-
503
- .settings-grid { display: grid; gap: 16px; grid-template-columns: 1fr; }
504
- .settings-card { background: var(--surface); border-radius: 12px; padding: 16px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
505
- .settings-list-item { display: flex; flex-direction: column; padding: 12px 0; border-bottom: 1px solid var(--border); gap: 12px; }
506
- .settings-list-item:last-child { border-bottom: none; }
507
- .settings-list-item-header { display: flex; justify-content: space-between; align-items: center; }
508
- .settings-link-box { display: flex; gap: 8px; align-items: center; width: 100%; }
509
- .settings-link-input { flex: 1; padding: 10px; border: 1px solid var(--border); border-radius: 8px; font-size: 0.85rem; background: var(--bg); outline: none; color: var(--text-main); }
510
-
511
- @media (min-width: 768px) {
512
- body { padding: 24px; }
513
- .top-actions { max-width: 400px; }
514
- .settings-grid { grid-template-columns: repeat(3, 1fr); gap: 24px; }
515
- .modal-overlay { align-items: center; }
516
- .modal-content { border-radius: 20px; max-width: 500px; }
517
- }
518
- </style>
519
- </head>
520
- <body>
521
- <div id="loader" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(255,255,255,0.7); z-index:9999; justify-content:center; align-items:center;">
522
- <div style="border: 4px solid #f3f3f3; border-top: 4px solid var(--primary); border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite;"></div>
523
- </div>
524
-
525
- <div class="container">
526
- <h1 id="main_title">Учет товаров</h1>
527
-
528
- {% if role == 'admin' %}
529
- <div class="top-actions">
530
- <button class="btn btn-primary" onclick="openModal('addModal')">Новый товар</button>
531
- <button class="btn btn-success" onclick="openModal('incomeModal')">Приход</button>
532
- </div>
533
- <div class="main-nav">
534
- <button id="navbtn_catalog" class="nav-btn active" onclick="switchNav('catalog')">Каталог</button>
535
- <button id="navbtn_reports" class="nav-btn" onclick="switchNav('reports')">Отчеты</button>
536
- <button id="navbtn_settings" class="nav-btn" onclick="switchNav('settings')">Настройки</button>
537
- </div>
538
- {% elif role == 'employee' %}
539
- <div class="main-nav">
540
- <button id="navbtn_catalog" class="nav-btn active" onclick="switchNav('catalog')">Каталог</button>
541
- </div>
542
- {% endif %}
543
-
544
- <div id="section_catalog">
545
- <div class="loc-nav" id="loc_nav_container"></div>
546
- <input type="text" id="search" class="search-box" placeholder="Поиск товара..." oninput="onSearchInput()">
547
- <div id="catalog"></div>
548
- </div>
549
-
550
- <div id="section_reports" style="display:none;">
551
- <div style="display:flex; flex-wrap:wrap; gap:12px; margin-bottom:12px;">
552
- <input type="date" id="hist_from" class="form-control" style="flex:1; margin:0;" onchange="renderHistory()">
553
- <input type="date" id="hist_to" class="form-control" style="flex:1; margin:0;" onchange="renderHistory()">
554
- </div>
555
- <div style="display:flex; flex-wrap:wrap; gap:12px; margin-bottom:12px;">
556
- <select id="hist_emp" class="form-control" style="flex:1; margin:0;" onchange="renderHistory()"></select>
557
- <select id="hist_action_type" class="form-control" style="flex:1; margin:0;" onchange="renderHistory()">
558
- <option value="all">Все операции</option>
559
- <option value="Продажа">Все продажи</option>
560
- <option value="Продажа_retail">Продажи (Розница)</option>
561
- <option value="Продажа_wholesale">Продажи (Опт)</option>
562
- <option value="Приход">Приходы</option>
563
- <option value="Перемещение">Перемещения</option>
564
- <option value="Удаление">Удаления</option>
565
- </select>
566
- </div>
567
- <h3 id="total_sales" style="margin-bottom:16px; color:var(--primary);"></h3>
568
- <div id="history_container"></div>
569
- </div>
570
-
571
- <div id="section_settings" style="display:none;">
572
- <div class="settings-grid">
573
- <div class="settings-card">
574
- <h3>Публичные каталоги</h3>
575
- <div class="settings-list-item">
576
- <div class="settings-list-item-header"><span style="font-weight:600;">Розничный каталог</span></div>
577
- <div class="settings-link-box">
578
- <input type="text" class="settings-link-input" value="{{ request.host_url }}catalog/retail" readonly onclick="this.select()">
579
- <button type="button" onclick="navigator.clipboard.writeText('{{ request.host_url }}catalog/retail');alert('Ссылка скопирована')" class="btn btn-primary" style="padding:8px 12px; font-size:0.85rem; flex:0 0 auto;">Копировать</button>
580
- </div>
581
- </div>
582
- <div class="settings-list-item">
583
- <div class="settings-list-item-header"><span style="font-weight:600;">Оптовый каталог</span></div>
584
- <div class="settings-link-box">
585
- <input type="text" class="settings-link-input" value="{{ request.host_url }}catalog/wholesale" readonly onclick="this.select()">
586
- <button type="button" onclick="navigator.clipboard.writeText('{{ request.host_url }}catalog/wholesale');alert('Ссылка скопирована')" class="btn btn-primary" style="padding:8px 12px; font-size:0.85rem; flex:0 0 auto;">Копировать</button>
587
- </div>
588
- </div>
589
- </div>
590
-
591
- <div class="settings-card">
592
- <h3>Склады</h3>
593
- <div id="set_warehouses"></div>
594
- <form method="POST" onsubmit="return showLoader(this)" style="display:flex; gap:8px; margin-top:12px;">
595
- <input type="hidden" name="action" value="add_loc">
596
- <input type="hidden" name="l_type" value="warehouses">
597
- <input type="text" name="l_name" class="form-control" style="margin:0;" placeholder="Название" required>
598
- <button type="submit" class="btn btn-primary" style="flex:0 0 auto; padding:0 20px;">+</button>
599
- </form>
600
- </div>
601
- <div class="settings-card">
602
- <h3>Магазины</h3>
603
- <div id="set_shops"></div>
604
- <form method="POST" onsubmit="return showLoader(this)" style="display:flex; gap:8px; margin-top:12px;">
605
- <input type="hidden" name="action" value="add_loc">
606
- <input type="hidden" name="l_type" value="shops">
607
- <input type="text" name="l_name" class="form-control" style="margin:0;" placeholder="Название" required>
608
- <button type="submit" class="btn btn-primary" style="flex:0 0 auto; padding:0 20px;">+</button>
609
- </form>
610
- </div>
611
- <div class="settings-card">
612
- <h3>Сотрудники</h3>
613
- <div id="set_emps"></div>
614
- <form method="POST" onsubmit="return showLoader(this)" style="display:flex; flex-direction:column; gap:8px; margin-top:12px;">
615
- <input type="hidden" name="action" value="add_emp">
616
- <input type="text" name="e_name" class="form-control" style="margin:0;" placeholder="Имя сотрудника" required>
617
- <select name="e_shop" id="emp_shop_select" class="form-control" style="margin:0;" required></select>
618
- <button type="submit" class="btn btn-primary" style="padding:10px;">Добавить сотрудника</button>
619
- </form>
620
- </div>
621
- </div>
622
- </div>
623
- </div>
624
-
625
- <div id="imageZoomModal" class="modal-overlay" onclick="closeModal('imageZoomModal')" style="z-index:2000; align-items:center;">
626
- <img id="zoomedImage" style="max-width:90%; max-height:90%; object-fit:contain; border-radius:8px;">
627
- </div>
628
-
629
- <div id="addModal" class="modal-overlay">
630
- <div class="modal-content">
631
- <button class="close-modal" onclick="closeModal('addModal')">×</button>
632
- <h2>Добавить товар</h2>
633
- <form method="POST" style="margin-top:16px;" onsubmit="return showLoader(this)">
634
- <input type="hidden" name="action" value="add">
635
- <input type="text" name="name" class="form-control" placeholder="Название" required>
636
- <textarea name="description" class="form-control" placeholder="Описание"></textarea>
637
-
638
- <div style="display:flex; gap:8px; margin-bottom:12px;">
639
- <input type="number" name="price_retail" class="form-control" style="margin-bottom:0;" placeholder="Розничная цена (₸)" required>
640
- <input type="number" name="price_wholesale" class="form-control" style="margin-bottom:0;" placeholder="Оптовая цена (₸)" required>
641
- </div>
642
-
643
- <select name="loc_id" id="add_loc_select" class="form-control" required></select>
644
-
645
- <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Варианты товара (не обязательно)</label>
646
- <div id="add_variants_container"></div>
647
- <button type="button" class="btn btn-success" style="padding:8px; font-size:0.85rem; margin-bottom:12px; width:100%; background:#eab308;" onclick="addVariantField('add_variants_container')">+ Добавить вариант</button>
648
-
649
- <div id="add_base_stock_container">
650
- <input type="number" name="rolls" id="add_rolls" class="form-control" placeholder="Количество при создании" value="0" required>
651
- </div>
652
-
653
- <input type="number" name="box_qty" class="form-control" placeholder="Штук в коробке" value="1" required>
654
-
655
- <label style="display:block; margin-bottom:8px; font-size:0.9rem; color:var(--text-muted);">Фото товара (не обязательно)</label>
656
- <input type="file" accept="image/*" class="form-control" onchange="processImage(this, 'photo_b64', 'photo_preview')">
657
- <input type="hidden" name="photo" id="photo_b64">
658
- <img id="photo_preview" style="display:none; width:100%; height:200px; object-fit:cover; border-radius:12px; margin-bottom:16px;">
659
-
660
- <button type="submit" class="btn btn-primary" style="width:100%;">Сохранить</button>
661
- </form>
662
- </div>
663
- </div>
664
-
665
- <div id="editModal" class="modal-overlay">
666
- <div class="modal-content">
667
- <button class="close-modal" onclick="closeModal('editModal')">×</button>
668
- <h2>Изменить товар</h2>
669
- <form method="POST" style="margin-top:16px;" onsubmit="return showLoader(this)">
670
- <input type="hidden" name="action" value="edit">
671
- <input type="hidden" name="index" id="edit_index">
672
- <input type="text" name="name" id="edit_name" class="form-control" placeholder="Название" required>
673
- <textarea name="description" id="edit_desc" class="form-control" placeholder="Описание"></textarea>
674
-
675
- <div style="display:flex; gap:8px; margin-bottom:12px;">
676
- <input type="number" name="price_retail" id="edit_price_retail" class="form-control" style="margin-bottom:0;" placeholder="Розничная цена (₸)" required>
677
- <input type="number" name="price_wholesale" id="edit_price_wholesale" class="form-control" style="margin-bottom:0;" placeholder="Оптовая цена (₸)" required>
678
- </div>
679
-
680
- <label style="display:block; margin-bottom:4px; font-weight:600; font-size:0.9rem;">Остатки по локациям</label>
681
- <select name="edit_loc_id" id="edit_loc_id" class="form-control"></select>
682
-
683
- <div id="edit_base_stock_container" style="margin-bottom:12px;">
684
- <input type="number" name="rolls" id="edit_rolls" class="form-control" placeholder="Общий остаток (без вариантов)">
685
- </div>
686
-
687
- <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Варианты товара</label>
688
- <div id="edit_variants_container"></div>
689
- <button type="button" class="btn btn-success" style="padding:8px; font-size:0.85rem; margin-bottom:12px; width:100%; background:#eab308;" onclick="addVariantField('edit_variants_container')">+ Добавить вариант</button>
690
-
691
- <input type="number" name="box_qty" id="edit_box_qty" class="form-control" placeholder="Штук в коробке" required>
692
-
693
- <label style="display:block; margin-bottom:8px; font-size:0.9rem; color:var(--text-muted);">Новое фото (не обязательно)</label>
694
- <input type="file" accept="image/*" class="form-control" onchange="processImage(this, 'edit_photo_b64', 'edit_photo_preview')">
695
- <input type="hidden" name="photo" id="edit_photo_b64">
696
- <img id="edit_photo_preview" style="display:none; width:100%; height:200px; object-fit:cover; border-radius:12px; margin-bottom:16px;">
697
-
698
- <button type="submit" class="btn btn-success" style="width:100%; background:var(--primary);">Сохранить изменения</button>
699
- </form>
700
- </div>
701
- </div>
702
-
703
- <div id="incomeModal" class="modal-overlay">
704
- <div class="modal-content">
705
- <button class="close-modal" onclick="closeModal('incomeModal')">×</button>
706
- <h2>Приход</h2>
707
- <form method="POST" style="margin-top:16px;" onsubmit="return showLoader(this)">
708
- <input type="hidden" name="action" value="income">
709
- <select name="loc_id" id="inc_loc_select" class="form-control" required></select>
710
- <select name="product_index" id="inc_product" class="form-control" onchange="updateIncVariants()" required></select>
711
- <select name="v_index" id="inc_variant" class="form-control" style="display:none;"></select>
712
- <input type="number" name="rolls" class="form-control" placeholder="Количество" min="1" required>
713
- <button type="submit" class="btn btn-success" style="width:100%;">Принять</button>
714
- </form>
715
- </div>
716
- </div>
717
-
718
- <div id="transferModal" class="modal-overlay">
719
- <div class="modal-content">
720
- <button class="close-modal" onclick="closeModal('transferModal')">×</button>
721
- <h2>Перемещение</h2>
722
- <form method="POST" style="margin-top:16px;" onsubmit="return showLoader(this)">
723
- <input type="hidden" name="action" value="transfer">
724
- <input type="hidden" name="pIndex" id="trans_pIndex">
725
- <input type="hidden" name="vIndex" id="trans_vIndex">
726
- <input type="hidden" name="from_loc" id="trans_from">
727
- <p id="trans_info" style="margin-bottom:16px; font-weight:600;"></p>
728
- <select name="to_loc" id="trans_dest_select" class="form-control" required></select>
729
- <input type="number" name="amt" id="trans_amt" class="form-control" placeholder="Количество" min="1" required>
730
- <button type="submit" class="btn btn-primary" style="width:100%;">Переместить</button>
731
- </form>
732
- </div>
733
- </div>
734
-
735
- <form id="delForm" method="POST" style="display:none;" onsubmit="return showLoader(this)">
736
- <input type="hidden" name="action" value="delete">
737
- <input type="hidden" name="index" id="del_index">
738
- </form>
739
-
740
- <script>
741
- const data = {{ data|tojson }};
742
- const role = "{{ role }}";
743
- const price_type = "{{ price_type }}";
744
- const hostUrl = "{{ request.host_url }}";
745
- const currentEmp = {{ emp|tojson }};
746
- let activeLoc = 'all';
747
- let searchTimeout;
748
-
749
- function showLoader(formElement) {
750
- if (formElement && formElement.dataset.submitted === 'true') {
751
- return false;
752
- }
753
- if (formElement) formElement.dataset.submitted = 'true';
754
- document.getElementById('loader').style.display = 'flex';
755
- return true;
756
- }
757
-
758
- function init() {
759
- if (role === 'admin' || role === 'employee') {
760
- document.getElementById('main_title').innerText = role === 'admin' ? 'Админ панель' : 'Панель сотрудника';
761
- } else {
762
- document.getElementById('main_title').innerText = price_type === 'wholesale' ? 'Оптовый каталог' : 'Розничный каталог';
763
- }
764
- buildLocNav();
765
- if (role === 'admin') {
766
- buildSettings();
767
- buildIncProducts();
768
- buildLocSelects();
769
- buildEmpSelect();
770
- initHistoryDates();
771
- }
772
-
773
- let savedLoc = localStorage.getItem('activeLoc');
774
- let locBtn = document.getElementById('locbtn_' + savedLoc);
775
- if (locBtn) {
776
- setLoc(savedLoc);
777
- } else {
778
- setLoc('all');
779
- }
780
- }
781
-
782
- function switchNav(nav) {
783
- ['catalog', 'reports', 'settings'].forEach(id => {
784
- const el = document.getElementById('section_' + id);
785
- if(el) el.style.display = (id === nav) ? 'block' : 'none';
786
- });
787
- document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
788
- document.getElementById('navbtn_' + nav).classList.add('active');
789
- if (nav === 'reports') renderHistory();
790
- }
791
-
792
- function buildLocNav() {
793
- const cont = document.getElementById('loc_nav_container');
794
- if(!cont) return;
795
- let html = `<button class="loc-btn" id="locbtn_all" onclick="setLoc('all')">Все локации</button>`;
796
-
797
- data.settings.warehouses.forEach(w => {
798
- html += `<button class="loc-btn" id="locbtn_${w.id}" onclick="setLoc('${w.id}')">${w.name}</button>`;
799
- });
800
-
801
- let allowedShops = data.settings.shops;
802
- if (role === 'employee' && currentEmp && currentEmp.shop_id) {
803
- allowedShops = data.settings.shops.filter(s => s.id === currentEmp.shop_id);
804
- }
805
-
806
- allowedShops.forEach(s => {
807
- html += `<button class="loc-btn" id="locbtn_${s.id}" onclick="setLoc('${s.id}')">${s.name}</button>`;
808
- });
809
- cont.innerHTML = html;
810
- }
811
-
812
- function setLoc(locId) {
813
- activeLoc = locId;
814
- localStorage.setItem('activeLoc', locId);
815
- document.querySelectorAll('.loc-btn').forEach(b => b.classList.remove('active'));
816
- let btn = document.getElementById('locbtn_' + locId);
817
- if (btn) btn.classList.add('active');
818
- renderCatalog();
819
- }
820
-
821
- function getLocName(locId) {
822
- let locs = [...data.settings.warehouses, ...data.settings.shops];
823
- let found = locs.find(l => l.id === locId);
824
- return found ? found.name : locId;
825
- }
826
-
827
- function zoomImage(src) {
828
- if (!src) return;
829
- document.getElementById('zoomedImage').src = src;
830
- openModal('imageZoomModal');
831
- }
832
-
833
- function onSearchInput() {
834
- clearTimeout(searchTimeout);
835
- searchTimeout = setTimeout(renderCatalog, 200);
836
- }
837
-
838
- function renderCatalog() {
839
- const q = document.getElementById('search').value.toLowerCase().trim();
840
- const cat = document.getElementById('catalog');
841
- let htmlArr = [];
842
- let locationsWithStock = new Set();
843
-
844
- let validLocs = (activeLoc === 'all')
845
- ? ((role === 'employee' && currentEmp && currentEmp.shop_id)
846
- ? [currentEmp.shop_id, ...data.settings.warehouses.map(w=>w.id)]
847
- : [...data.settings.warehouses.map(w=>w.id), ...data.settings.shops.map(s=>s.id)])
848
- : [activeLoc];
849
-
850
- let getLocStock = (stocksObj) => {
851
- let s = 0;
852
- for (let l of validLocs) {
853
- if (stocksObj && stocksObj[l]) s += parseInt(stocksObj[l]);
854
- }
855
- return s;
856
- };
857
-
858
- data.products.forEach((p, pIdx) => {
859
- let match = p.name.toLowerCase().includes(q) || (p.description && p.description.toLowerCase().includes(q));
860
- if (!match) return;
861
-
862
- if (q !== '') {
863
- if (p.variants && p.variants.length > 0) {
864
- p.variants.forEach(v => {
865
- for (let loc in v.stocks) {
866
- if (v.stocks[loc] > 0) locationsWithStock.add(loc);
867
- }
868
- });
869
- } else {
870
- for (let loc in p.stocks) {
871
- if (p.stocks[loc] > 0) locationsWithStock.add(loc);
872
- }
873
- }
874
- }
875
-
876
- let totalStock = 0;
877
- if (p.variants && p.variants.length > 0) {
878
- p.variants.forEach(v => { totalStock += getLocStock(v.stocks); });
879
- } else {
880
- totalStock += getLocStock(p.stocks);
881
- }
882
-
883
- if (activeLoc !== 'all' && totalStock <= 0) return;
884
-
885
- let imgHtml = p.photo ? `<img src="${p.photo}" class="product-img">` : `<span style="font-size:0.6rem; color:#9ca3af;">Нет фото</span>`;
886
- let imgClick = p.photo ? `onclick="zoomImage('${p.photo}')"` : ``;
887
-
888
- let priceHtml = '';
889
- if (role !== 'public') {
890
- priceHtml = `
891
- <div style="display:flex; gap:6px; align-items:center; font-size:0.8rem; margin:4px 0; flex-wrap:wrap;">
892
- Розн: <input type="number" id="price_ret_${pIdx}" value="${p.price_retail}" style="width:65px; padding:2px 4px; border:1px solid var(--border); border-radius:4px; font-weight:600;" onclick="this.select()"> ₸
893
- | Опт: <input type="number" id="price_whl_${pIdx}" value="${p.price_wholesale}" style="width:65px; padding:2px 4px; border:1px solid var(--border); border-radius:4px; font-weight:600;" onclick="this.select()"> ₸
894
- </div>
895
- `;
896
- } else {
897
- priceHtml = `
898
- <div class="product-price" style="margin:4px 0;">
899
- ${price_type === 'both' ? `Розница: ${p.price_retail} ₸ | Опт: ${p.price_wholesale} ₸` : (price_type === 'retail' ? `${p.price_retail} ₸` : `${p.price_wholesale} ₸`)}
900
- </div>
901
- `;
902
- }
903
-
904
- if (p.variants && p.variants.length > 0) {
905
- let pOpts = [];
906
- p.variants.forEach((v, i) => {
907
- let vStock = getLocStock(v.stocks);
908
- if (activeLoc === 'all' || vStock > 0) {
909
- pOpts.push(`<div style="font-size:0.8rem; color:var(--text-muted); margin-bottom:2px;">• ${v.name}: ${vStock} шт</div>`);
910
- }
911
- });
912
- if (pOpts.length > 0) {
913
- priceHtml += `<div style="margin-top:6px; margin-bottom:6px; background:#f9fafb; padding:6px; border-radius:6px; border:1px solid var(--border);">${pOpts.join('')}</div>`;
914
- }
915
- }
916
-
917
- let actionsHtml = '';
918
- if (role !== 'public') {
919
- if (activeLoc !== 'all') {
920
- if (totalStock > 0) {
921
- let varHtml = '';
922
- if (p.variants && p.variants.length > 0) {
923
- let opts = [];
924
- p.variants.forEach((v, i) => {
925
- let vStock = getLocStock(v.stocks);
926
- if (vStock > 0) {
927
- opts.push(`<option value="${i}">${v.name} (+${v.price} ₸) - ${vStock} шт</option>`);
928
- }
929
- });
930
- if (opts.length > 0) {
931
- varHtml = `<select id="var_${pIdx}" class="form-control" style="padding:6px; font-size:0.8rem; margin-bottom:4px; height:auto;" onchange="updateMaxQty(${pIdx})">
932
- ${opts.join('')}
933
- </select>`;
934
- }
935
- }
936
-
937
- actionsHtml += `
938
- <div class="product-actions">
939
- ${varHtml}
940
- <div style="display:flex; gap:6px; align-items:center; width:100%;">
941
- <input type="number" id="amt_${pIdx}" class="qty-input" value="1" min="1" style="flex:1;">
942
- <button class="btn btn-danger" style="padding:8px 6px; font-size:0.75rem; flex:1;" onclick="directSell(${pIdx}, 'retail')">Списать (Розн)</button>
943
- <button class="btn btn-danger" style="padding:8px 6px; font-size:0.75rem; flex:1;" onclick="directSell(${pIdx}, 'wholesale')">Списать (Опт)</button>
944
- </div>
945
- `;
946
- if (role === 'admin') {
947
- actionsHtml += `<div style="display:flex; gap:6px; margin-top:2px; width:100%;">
948
- <button class="btn btn-primary" style="padding:8px 6px; flex:1; font-size:0.75rem;" onclick="openTransfer(${pIdx})">Переместить</button>
949
- <button class="btn btn-success" style="padding:8px 6px; flex:1; font-size:0.75rem; background:#eab308;" onclick="openEdit(${pIdx})">Изменить</button>
950
- <button class="btn btn-danger" style="padding:8px 6px; flex:1; font-size:0.75rem;" onclick="delProd(${pIdx})">Удалить</button>
951
- </div>`;
952
- }
953
- actionsHtml += `</div>`;
954
- }
955
- } else {
956
- actionsHtml += `<div class="product-actions">
957
- <div style="font-size:0.8rem; color:var(--text-muted); text-align:center; margin:8px 0;">Выберите локацию для действий</div>`;
958
- if (role === 'admin') {
959
- actionsHtml += `<div style="display:flex; gap:6px; width:100%;">
960
- <button class="btn btn-success" style="padding:8px; flex:1; font-size:0.75rem; background:#eab308;" onclick="openEdit(${pIdx})">Из��енить</button>
961
- <button class="btn btn-danger" style="padding:8px; flex:1; font-size:0.75rem;" onclick="delProd(${pIdx})">Удалить</button>
962
- </div>`;
963
- }
964
- actionsHtml += `</div>`;
965
- }
966
- }
967
-
968
- let html = `<div class="product">
969
- <div class="product-main">
970
- <div class="product-img-wrapper" ${imgClick}>${imgHtml}</div>
971
- <div class="product-info">
972
- <div class="product-title">${p.name}</div>
973
- ${p.description ? `<div style="font-size:0.75rem; color:var(--text-muted);">${p.description}</div>` : ''}
974
- ${priceHtml}
975
- <div class="product-stock">
976
- <strong style="color:var(--text-main);">Общий остаток: <span id="total_stock_${pIdx}">${totalStock}</span> шт</strong> | В коробке: ${p.box_qty || 1} шт
977
- <div id="variant_stock_container_${pIdx}" style="display:none; color:var(--primary); margin-top:4px; font-weight:600; font-size:0.7rem;">
978
- Выбранный вариант: <span id="stock_display_${pIdx}">0</span> шт
979
- </div>
980
- </div>
981
- </div>
982
- </div>
983
- ${actionsHtml}
984
- </div>`;
985
- htmlArr.push(html);
986
- });
987
- cat.innerHTML = htmlArr.join('');
988
-
989
- document.querySelectorAll('.loc-btn').forEach(btn => {
990
- if (btn.id === 'locbtn_all') return;
991
- let locId = btn.id.replace('locbtn_', '');
992
- if (q !== '' && locationsWithStock.has(locId)) {
993
- btn.classList.add('has-search-stock');
994
- } else {
995
- btn.classList.remove('has-search-stock');
996
- }
997
- });
998
-
999
- data.products.forEach((p, pIdx) => {
1000
- if(document.getElementById('total_stock_' + pIdx)) {
1001
- updateMaxQty(pIdx);
1002
- }
1003
- });
1004
- }
1005
-
1006
- function updateMaxQty(pIdx) {
1007
- let p = data.products[pIdx];
1008
- let vSelect = document.getElementById('var_' + pIdx);
1009
- let qtyInput = document.getElementById('amt_' + pIdx);
1010
-
1011
- let validLocs = (activeLoc === 'all')
1012
- ? ((role === 'employee' && currentEmp && currentEmp.shop_id)
1013
- ? [currentEmp.shop_id, ...data.settings.warehouses.map(w=>w.id)]
1014
- : [...data.settings.warehouses.map(w=>w.id), ...data.settings.shops.map(s=>s.id)])
1015
- : [activeLoc];
1016
-
1017
- let getLocStock = (stocksObj) => {
1018
- let s = 0;
1019
- for (let l of validLocs) {
1020
- if (stocksObj && stocksObj[l]) s += parseInt(stocksObj[l]);
1021
- }
1022
- return s;
1023
- };
1024
-
1025
- let max = 0;
1026
- if (vSelect && vSelect.value !== "") {
1027
- let vIdx = parseInt(vSelect.value);
1028
- max = getLocStock(p.variants[vIdx].stocks);
1029
- } else if (p.variants && p.variants.length > 0) {
1030
- let firstValidStock = 0;
1031
- for (let i = 0; i < p.variants.length; i++) {
1032
- let vSt = getLocStock(p.variants[i].stocks);
1033
- if (vSt > 0) {
1034
- firstValidStock = vSt;
1035
- break;
1036
- }
1037
- }
1038
- max = firstValidStock;
1039
- } else {
1040
- max = getLocStock(p.stocks);
1041
- }
1042
-
1043
- if(qtyInput) qtyInput.max = max;
1044
- let stockDisplay = document.getElementById('stock_display_' + pIdx);
1045
- let varCont = document.getElementById('variant_stock_container_' + pIdx);
1046
-
1047
- if(stockDisplay) {
1048
- stockDisplay.innerText = max;
1049
- }
1050
- if(varCont) {
1051
- varCont.style.display = (p.variants && p.variants.length > 0 && activeLoc !== 'all') ? 'block' : 'none';
1052
- }
1053
- }
1054
-
1055
- async function directSell(pIdx, pType) {
1056
- let p = data.products[pIdx];
1057
- let amt = parseInt(document.getElementById('amt_'+pIdx).value);
1058
- let vSelect = document.getElementById('var_'+pIdx);
1059
- let vIdx = (vSelect && vSelect.value !== '') ? parseInt(vSelect.value) : -1;
1060
-
1061
- if(amt <= 0 || isNaN(amt)) return alert('Неверное количество');
1062
- if(activeLoc === 'all') return alert('Выберите локацию для списания');
1063
-
1064
- let stock = 0;
1065
- if (vIdx !== -1) {
1066
- stock = parseInt(p.variants[vIdx].stocks[activeLoc] || 0);
1067
- } else {
1068
- stock = parseInt(p.stocks[activeLoc] || 0);
1069
- }
1070
-
1071
- if(amt > stock) return alert('Превышен остаток');
1072
-
1073
- let basePrice = pType === 'wholesale' ? parseInt(p.price_wholesale) : parseInt(p.price_retail);
1074
- if (role !== 'public') {
1075
- let customPriceInput = document.getElementById(pType === 'wholesale' ? 'price_whl_' + pIdx : 'price_ret_' + pIdx);
1076
- if (customPriceInput) basePrice = parseInt(customPriceInput.value) || basePrice;
1077
- }
1078
-
1079
- let vName = '';
1080
- let vPrice = 0;
1081
- if (vIdx !== -1) {
1082
- vName = ' (' + p.variants[vIdx].name + ')';
1083
- vPrice = parseInt(p.variants[vIdx].price) || 0;
1084
- }
1085
-
1086
- let finalPrice = basePrice + vPrice;
1087
- let finalName = p.name + vName + (pType === 'wholesale' ? ' [Опт]' : ' [Розн]');
1088
-
1089
- if (!confirm(`Списать ${amt} шт. товара "${finalName}"?`)) return;
1090
-
1091
- let singleItemCart = [{
1092
- pIndex: pIdx,
1093
- vIndex: vIdx,
1094
- pName: finalName,
1095
- price: finalPrice,
1096
- amt: amt,
1097
- loc: activeLoc
1098
- }];
1099
-
1100
- document.getElementById('loader').style.display = 'flex';
1101
- let fd = new FormData();
1102
- fd.append('action', 'checkout');
1103
- fd.append('cart', JSON.stringify(singleItemCart));
1104
-
1105
- try {
1106
- await fetch(window.location.href, {method: 'POST', body: fd});
1107
- window.location.reload();
1108
- } catch (e) {
1109
- alert('Ошибка при списании');
1110
- document.getElementById('loader').style.display = 'none';
1111
- }
1112
- }
1113
-
1114
- function openTransfer(pIdx) {
1115
- let p = data.products[pIdx];
1116
- let vSelect = document.getElementById('var_' + pIdx);
1117
- let vIdx = (vSelect && vSelect.value !== '') ? parseInt(vSelect.value) : -1;
1118
-
1119
- let maxStock = 0;
1120
- let vName = '';
1121
- if(vIdx !== -1) {
1122
- maxStock = p.variants[vIdx].stocks[activeLoc] || 0;
1123
- vName = ' (' + p.variants[vIdx].name + ')';
1124
- } else {
1125
- maxStock = p.stocks[activeLoc] || 0;
1126
- }
1127
-
1128
- if(maxStock <= 0) return alert('Нет в наличии');
1129
-
1130
- document.getElementById('trans_pIndex').value = pIdx;
1131
- document.getElementById('trans_vIndex').value = vIdx;
1132
- document.getElementById('trans_from').value = activeLoc;
1133
- document.getElementById('trans_info').innerText = p.name + vName + ' (Доступно: ' + maxStock + ' шт)';
1134
- document.getElementById('trans_amt').max = maxStock;
1135
- document.getElementById('trans_amt').value = 1;
1136
-
1137
- const dest = document.getElementById('trans_dest_select');
1138
- dest.innerHTML = '';
1139
- [...data.settings.warehouses, ...data.settings.shops].forEach(l => {
1140
- if (l.id !== activeLoc) {
1141
- dest.innerHTML += `<option value="${l.id}">${l.name}</option>`;
1142
- }
1143
- });
1144
- openModal('transferModal');
1145
- }
1146
-
1147
- function addVariantField(containerId, name='', price='', stock='') {
1148
- const cont = document.getElementById(containerId);
1149
- const div = document.createElement('div');
1150
- div.style = "display:flex; gap:8px; margin-bottom:8px; align-items:center;";
1151
- div.innerHTML = `
1152
- <input type="text" name="v_name[]" class="form-control" style="margin:0; flex:1;" placeholder="Название" value="${name}" required>
1153
- <input type="number" name="v_price[]" class="form-control" style="margin:0; width:90px;" placeholder="Цена" value="${price}" required>
1154
- <input type="number" name="v_stock[]" class="form-control v-stock-input" style="margin:0; width:90px;" placeholder="Остаток" value="${stock}" required>
1155
- <button type="button" style="border:none; background:var(--danger); color:white; border-radius:8px; padding:10px; cursor:pointer;" onclick="removeVariantField(this, '${containerId}')">×</button>
1156
- `;
1157
- cont.appendChild(div);
1158
- checkVariants(containerId);
1159
- }
1160
-
1161
- function removeVariantField(btn, containerId) {
1162
- btn.parentElement.remove();
1163
- checkVariants(containerId);
1164
- }
1165
-
1166
- function checkVariants(containerId) {
1167
- const cont = document.getElementById(containerId);
1168
- const has = cont.children.length > 0;
1169
- if(containerId === 'add_variants_container') {
1170
- document.getElementById('add_base_stock_container').style.display = has ? 'none' : 'block';
1171
- const baseInput = document.getElementById('add_rolls');
1172
- if(has) baseInput.removeAttribute('required');
1173
- else baseInput.setAttribute('required', 'required');
1174
- } else if (containerId === 'edit_variants_container') {
1175
- document.getElementById('edit_base_stock_container').style.display = has ? 'none' : 'block';
1176
- }
1177
- }
1178
-
1179
- function openEdit(pIdx) {
1180
- let p = data.products[pIdx];
1181
- document.getElementById('edit_index').value = pIdx;
1182
- document.getElementById('edit_name').value = p.name;
1183
- document.getElementById('edit_desc').value = p.description || '';
1184
- document.getElementById('edit_price_retail').value = p.price_retail || p.price || 0;
1185
- document.getElementById('edit_price_wholesale').value = p.price_wholesale || p.price || 0;
1186
- document.getElementById('edit_box_qty').value = p.box_qty || 1;
1187
- document.getElementById('edit_photo_b64').value = '';
1188
-
1189
- let locSelect = document.getElementById('edit_loc_id');
1190
- locSelect.innerHTML = [...data.settings.warehouses, ...data.settings.shops].map(l => `<option value="${l.id}">${l.name}</option>`).join('');
1191
-
1192
- let lastLoc = localStorage.getItem('lastFormLoc');
1193
- if (activeLoc !== 'all' && locSelect.querySelector(`option[value="${activeLoc}"]`)) {
1194
- locSelect.value = activeLoc;
1195
- } else if (lastLoc && locSelect.querySelector(`option[value="${lastLoc}"]`)) {
1196
- locSelect.value = lastLoc;
1197
- }
1198
-
1199
- locSelect.onchange = function() {
1200
- localStorage.setItem('lastFormLoc', this.value);
1201
- loadEditStocks();
1202
- };
1203
-
1204
- document.getElementById('edit_variants_container').innerHTML = '';
1205
- if (p.variants && p.variants.length > 0) {
1206
- p.variants.forEach(v => {
1207
- addVariantField('edit_variants_container', v.name, v.price, '');
1208
- });
1209
- }
1210
-
1211
- let preview = document.getElementById('edit_photo_preview');
1212
- if(p.photo) {
1213
- preview.src = p.photo;
1214
- preview.style.display = 'block';
1215
- } else {
1216
- preview.src = '';
1217
- preview.style.display = 'none';
1218
- }
1219
-
1220
- loadEditStocks();
1221
- openModal('editModal');
1222
- }
1223
-
1224
- function loadEditStocks() {
1225
- let pIdx = document.getElementById('edit_index').value;
1226
- let p = data.products[pIdx];
1227
- let locId = document.getElementById('edit_loc_id').value;
1228
-
1229
- if (p.variants && p.variants.length > 0) {
1230
- let stockInputs = document.querySelectorAll('#edit_variants_container .v-stock-input');
1231
- p.variants.forEach((v, i) => {
1232
- if(stockInputs[i]) {
1233
- stockInputs[i].value = (v.stocks && v.stocks[locId]) ? v.stocks[locId] : 0;
1234
- }
1235
- });
1236
- document.getElementById('edit_base_stock_container').style.display = 'none';
1237
- } else {
1238
- document.getElementById('edit_rolls').value = (p.stocks && p.stocks[locId]) ? p.stocks[locId] : 0;
1239
- document.getElementById('edit_base_stock_container').style.display = 'block';
1240
- }
1241
- }
1242
-
1243
- function processImage(input, b64Id, previewId) {
1244
- if (input.files && input.files[0]) {
1245
- const reader = new FileReader();
1246
- reader.onload = function(e) {
1247
- const img = new Image();
1248
- img.onload = function() {
1249
- const canvas = document.createElement('canvas');
1250
- let w = img.width, h = img.height;
1251
- const max = 600;
1252
- if (w > max || h > max) {
1253
- if (w > h) { h = Math.round(h * max / w); w = max; }
1254
- else { w = Math.round(w * max / h); h = max; }
1255
- }
1256
- canvas.width = w; canvas.height = h;
1257
- const ctx = canvas.getContext('2d');
1258
- ctx.drawImage(img, 0, 0, w, h);
1259
- const b64 = canvas.toDataURL('image/jpeg', 0.6);
1260
- document.getElementById(b64Id).value = b64;
1261
- const p = document.getElementById(previewId);
1262
- p.src = b64; p.style.display = 'block';
1263
- }
1264
- img.src = e.target.result;
1265
- }
1266
- reader.readAsDataURL(input.files[0]);
1267
- }
1268
- }
1269
-
1270
- function delProd(idx) {
1271
- if(confirm('Удалить товар?')) {
1272
- document.getElementById('del_index').value = idx;
1273
- const form = document.getElementById('delForm');
1274
- if (showLoader(form)) {
1275
- form.submit();
1276
- }
1277
- }
1278
- }
1279
-
1280
- function openModal(id) { document.getElementById(id).classList.add('active'); }
1281
- function closeModal(id) { document.getElementById(id).classList.remove('active'); }
1282
-
1283
- function buildSettings() {
1284
- const wCont = document.getElementById('set_warehouses');
1285
- wCont.innerHTML = data.settings.warehouses.map(w => `<div class="settings-list-item"><div class="settings-list-item-header"><span style="font-weight:600;">${w.name}</span><form method="POST" onsubmit="return showLoader(this)" style="margin:0;"><input type="hidden" name="action" value="del_loc"><input type="hidden" name="l_type" value="warehouses"><input type="hidden" name="l_id" value="${w.id}"><button type="submit" class="btn btn-danger" style="padding:6px 12px; font-size:0.85rem;">Удалить</button></form></div></div>`).join('');
1286
-
1287
- const sCont = document.getElementById('set_shops');
1288
- sCont.innerHTML = data.settings.shops.map(s => `<div class="settings-list-item"><div class="settings-list-item-header"><span style="font-weight:600;">${s.name}</span><form method="POST" onsubmit="return showLoader(this)" style="margin:0;"><input type="hidden" name="action" value="del_loc"><input type="hidden" name="l_type" value="shops"><input type="hidden" name="l_id" value="${s.id}"><button type="submit" class="btn btn-danger" style="padding:6px 12px; font-size:0.85rem;">Удалить</button></form></div></div>`).join('');
1289
-
1290
- const eCont = document.getElementById('set_emps');
1291
- eCont.innerHTML = data.settings.employees.map(e => {
1292
- let shop = data.settings.shops.find(s => s.id === e.shop_id);
1293
- let shopName = shop ? shop.name : 'Не привязан';
1294
- return `
1295
- <div class="settings-list-item">
1296
- <div class="settings-list-item-header">
1297
- <span style="font-weight:600;">${e.name} <small style="color:var(--text-muted)">(${shopName})</small></span>
1298
- <form method="POST" onsubmit="return showLoader(this)" style="margin:0;">
1299
- <input type="hidden" name="action" value="del_emp">
1300
- <input type="hidden" name="e_id" value="${e.id}">
1301
- <button type="submit" class="btn btn-danger" style="padding:6px 12px; font-size:0.85rem;">Удалить</button>
1302
- </form>
1303
- </div>
1304
- <div class="settings-link-box">
1305
- <input type="text" class="settings-link-input" value="${hostUrl}emp/${e.token}" readonly onclick="this.select()">
1306
- <button type="button" onclick="navigator.clipboard.writeText('${hostUrl}emp/${e.token}');alert('Ссылка скопирована')" class="btn btn-primary" style="padding:8px 12px; font-size:0.85rem; flex:0 0 auto;">Копировать</button>
1307
- </div>
1308
- </div>
1309
- `}).join('');
1310
- }
1311
-
1312
- function buildLocSelects() {
1313
- const locs = [...data.settings.warehouses, ...data.settings.shops];
1314
- const opts = locs.map(l => `<option value="${l.id}">${l.name}</option>`).join('');
1315
-
1316
- const addLocSel = document.getElementById('add_loc_select');
1317
- addLocSel.innerHTML = opts;
1318
- addLocSel.onchange = function() { localStorage.setItem('lastFormLoc', this.value); };
1319
-
1320
- const incLocSel = document.getElementById('inc_loc_select');
1321
- incLocSel.innerHTML = opts;
1322
- incLocSel.onchange = function() { localStorage.setItem('lastFormLoc', this.value); };
1323
-
1324
- const lastLoc = localStorage.getItem('lastFormLoc');
1325
- if (lastLoc) {
1326
- addLocSel.value = lastLoc;
1327
- incLocSel.value = lastLoc;
1328
- }
1329
-
1330
- const shopOpts = data.settings.shops.map(s => `<option value="${s.id}">${s.name}</option>`).join('');
1331
- document.getElementById('emp_shop_select').innerHTML = '<option value="">-- Выберите магазин --</option>' + shopOpts;
1332
- }
1333
-
1334
- function buildIncProducts() {
1335
- const sel = document.getElementById('inc_product');
1336
- sel.innerHTML = '<option value="">-- Товар --</option>' + data.products.map((p,i) => `<option value="${i}">${p.name}</option>`).join('');
1337
- }
1338
-
1339
- function updateIncVariants() {
1340
- let pIdx = document.getElementById('inc_product').value;
1341
- let vSelect = document.getElementById('inc_variant');
1342
- if(pIdx === '') {
1343
- vSelect.style.display = 'none';
1344
- vSelect.removeAttribute('required');
1345
- return;
1346
- }
1347
- let p = data.products[pIdx];
1348
- if (p.variants && p.variants.length > 0) {
1349
- vSelect.innerHTML = p.variants.map((v, i) => `<option value="${i}">${v.name}</option>`).join('');
1350
- vSelect.style.display = 'block';
1351
- vSelect.setAttribute('required', 'required');
1352
- } else {
1353
- vSelect.innerHTML = '';
1354
- vSelect.style.display = 'none';
1355
- vSelect.removeAttribute('required');
1356
- }
1357
- }
1358
-
1359
- function buildEmpSelect() {
1360
- const sel = document.getElementById('hist_emp');
1361
- sel.innerHTML = '<option value="all">Все сотрудники</option><option value="Админ">Админ</option>' + data.settings.employees.map(e => `<option value="${e.name}">${e.name}</option>`).join('');
1362
- }
1363
-
1364
- function initHistoryDates() {
1365
- const d = new Date();
1366
- const first = new Date(d.getFullYear(), d.getMonth(), 1);
1367
- document.getElementById('hist_from').value = first.toISOString().split('T')[0];
1368
- document.getElementById('hist_to').value = d.toISOString().split('T')[0];
1369
- }
1370
-
1371
- function renderHistory() {
1372
- const hc = document.getElementById('history_container');
1373
- let htmlArr = [];
1374
-
1375
- const fDate = new Date(document.getElementById('hist_from').value + "T00:00:00" || 0);
1376
- const tDate = new Date(document.getElementById('hist_to').value + "T23:59:59" || "2099-01-01T23:59:59");
1377
- const eFilter = document.getElementById('hist_emp').value;
1378
- const actFilter = document.getElementById('hist_action_type').value;
1379
-
1380
- let total = 0;
1381
-
1382
- data.history.forEach(h => {
1383
- const pts = h.time.split(' ')[0].split('.');
1384
- const hd = new Date(`${pts[2]}-${pts[1]}-${pts[0]}T${h.time.split(' ')[1]}`);
1385
-
1386
- let passAction = true;
1387
- if (actFilter !== 'all') {
1388
- if (actFilter === 'Продажа') {
1389
- passAction = h.action === 'Продажа';
1390
- } else if (actFilter === 'Продажа_retail') {
1391
- passAction = h.action === 'Продажа' && h.product.includes('[Розн]');
1392
- } else if (actFilter === 'Продажа_wholesale') {
1393
- passAction = h.action === 'Продажа' && h.product.includes('[Опт]');
1394
- } else {
1395
- passAction = h.action === actFilter;
1396
- }
1397
- }
1398
-
1399
- if (hd >= fDate && hd <= tDate && (eFilter === 'all' || h.emp_name === eFilter) && passAction) {
1400
- if (h.action === 'Продажа') total += (h.amount * h.price);
1401
-
1402
- let bCls = h.action.includes('Приход') ? 'badge-green' : 'badge-orange';
1403
- let locInfo = h.action === 'Перемещение' ? `${h.from_loc_name} ➔ ${h.to_loc_name}` : (h.from_loc_name || h.to_loc_name);
1404
-
1405
- htmlArr.push(`<div class="history-item">
1406
- <div class="history-header">
1407
- <span>${h.time} | ${h.emp_name}</span>
1408
- <span class="history-badge ${bCls}">${h.action}</span>
1409
- </div>
1410
- <div class="history-body">
1411
- <span class="history-prod">${h.product}<br><small style="color:var(--text-muted)">${locInfo}</small></span>
1412
- <span style="font-weight:700; text-align:right;">${h.amount} шт ${h.price > 0 ? `<br><small style="color:var(--primary)">${h.amount * h.price} ₸</small>` : ''}</span>
1413
- </div>
1414
- </div>`);
1415
- }
1416
- });
1417
- hc.innerHTML = htmlArr.join('');
1418
- document.getElementById('total_sales').innerText = `Итого продаж: ${total} ₸`;
1419
- }
1420
-
1421
- init();
1422
- </script>
1423
- </body>
1424
- </html>
1425
- '''
1426
-
1427
- @app.route('/')
1428
- def public_index():
1429
- return redirect(url_for('public_retail'))
1430
-
1431
- @app.route('/catalog/retail')
1432
- def public_retail():
1433
- data = load_data()
1434
- return render_template_string(MAIN_HTML, data=data, role='public', emp=None, price_type='retail')
1435
-
1436
- @app.route('/catalog/wholesale')
1437
- def public_wholesale():
1438
- data = load_data()
1439
- return render_template_string(MAIN_HTML, data=data, role='public', emp=None, price_type='wholesale')
1440
-
1441
- @app.route('/admin', methods=['GET', 'POST'])
1442
- def admin_panel():
1443
- data = load_data()
1444
- if request.method == 'POST':
1445
- handle_post(request, data, 'admin', None)
1446
- save_data(data)
1447
- return redirect(url_for('admin_panel'))
1448
- return render_template_string(MAIN_HTML, data=data, role='admin', emp=None, price_type='both')
1449
-
1450
- @app.route('/emp/<token>', methods=['GET', 'POST'])
1451
- def employee_panel(token):
1452
- data = load_data()
1453
- emp = next((e for e in data['settings']['employees'] if e.get('token') == token), None)
1454
- if not emp:
1455
- return "Неверная ссылка", 403
1456
- if request.method == 'POST':
1457
- handle_post(request, data, 'employee', emp)
1458
- save_data(data)
1459
- return redirect(f'/emp/{token}')
1460
- return render_template_string(MAIN_HTML, data=data, role='employee', emp=emp, price_type='both')
1461
-
1462
- if __name__ == '__main__':
1463
- load_data()
1464
- backup_thread = threading.Thread(target=periodic_backup, daemon=True)
1465
- backup_thread.start()
1466
- app.run(debug=True, host='0.0.0.0', port=7860)