Spaces:
Mail-boost
/
Running

Kgshop commited on
Commit
d19eccb
·
verified ·
1 Parent(s): f65b6e6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +192 -1236
app.py CHANGED
@@ -318,6 +318,7 @@ def load_data():
318
  'catalog_users': [],
319
  'inventory_history':[],
320
  'purchase_orders': [],
 
321
  'settings': {
322
  'organization_name': 'Default Shop',
323
  'admin_password_enabled': False,
@@ -367,6 +368,7 @@ def load_data():
367
  if 'catalog_users' not in env_data: env_data['catalog_users'] = []
368
  if 'inventory_history' not in env_data: env_data['inventory_history'] = []
369
  if 'purchase_orders' not in env_data: env_data['purchase_orders'] = []; changed = True
 
370
  if 'settings' not in env_data:
371
  env_data['settings'] = {}
372
  changed = True
@@ -418,7 +420,7 @@ def load_data():
418
 
419
  for product in env_data['products']:
420
  if 'product_id' not in product: product['product_id'] = uuid4().hex; changed = True
421
- if 'created_at' not in product: product['created_at'] = get_almaty_time(); changed = True
422
  if 'pieces_per_box' not in product: product['pieces_per_box'] = ""; changed = True
423
  if 'pieces_per_master_box' not in product: product['pieces_per_master_box'] = ""; changed = True
424
  if 'box_price' not in product: product['box_price'] = ""; changed = True
@@ -451,7 +453,6 @@ def load_data():
451
  if 'is_debt' not in order: order['is_debt'] = False; changed = True
452
  if 'paid_amount' not in order: order['paid_amount'] = order.get('total_price', 0); changed = True
453
  if 'debt_amount' not in order: order['debt_amount'] = 0; changed = True
454
- if 'debt_payments' not in order: order['debt_payments'] = []; changed = True
455
  for item in order.get('cart', []):
456
  if 'discount' not in item: item['discount'] = 0; changed = True
457
  if 'cost_price' not in item: item['cost_price'] = 0; changed = True
@@ -495,6 +496,7 @@ def get_env_data(env_id):
495
  'catalog_users': [],
496
  'inventory_history':[],
497
  'purchase_orders': [],
 
498
  'settings': {
499
  'organization_name': f'Shop {env_id}',
500
  'admin_password_enabled': False,
@@ -934,24 +936,20 @@ CATALOG_TEMPLATE = '''
934
  .search-container:focus-within { border-color: #dcdde1; background: var(--surface); box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
935
  .search-container input { width: 100%; padding: 15px 10px; border: none; background: transparent; outline: none; font-size: 16px; color: var(--text); }
936
 
937
- .stories-wrapper { padding: 15px 0 0 20px; background: var(--surface); border-bottom: 1px solid var(--border); display: none; }
938
- .stories-container { display: flex; gap: 15px; overflow-x: auto; padding-bottom: 15px; scrollbar-width: none; }
 
 
 
939
  .stories-container::-webkit-scrollbar { display: none; }
940
- .story-item { display: flex; flex-direction: column; align-items: center; gap: 5px; cursor: pointer; flex-shrink: 0; width: 70px; }
941
- .story-ring { width: 64px; height: 64px; border-radius: 50%; padding: 3px; background: linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%); display: flex; justify-content: center; align-items: center; }
942
- .story-img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; border: 2px solid var(--surface); background: var(--surface); }
943
- .story-title { font-size: 0.75rem; color: var(--text); text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 100%; font-weight: 500; }
944
-
945
- .story-modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: #111; z-index: 3000; justify-content: center; align-items: center; }
946
- .story-modal-content { position: relative; width: 100%; max-width: 450px; height: 100%; max-height: 850px; background: #222; display: flex; flex-direction: column; }
947
- .story-progress { position: absolute; top: 15px; left: 15px; right: 15px; height: 3px; background: rgba(255,255,255,0.3); border-radius: 2px; z-index: 10; display:flex; gap:5px; }
948
- .story-progress-segment { flex: 1; height: 100%; background: rgba(255,255,255,0.3); border-radius: 2px; overflow:hidden; }
949
- .story-progress-bar { width: 0%; height: 100%; background: #fff; }
950
- .story-header { position: absolute; top: 30px; left: 20px; right: 20px; display: flex; justify-content: space-between; align-items: center; z-index: 10; }
951
- .story-body { flex: 1; position: relative; display: flex; justify-content: center; align-items: center; overflow: hidden; }
952
- .story-body img { width: 100%; height: 100%; object-fit: contain; background: #111; }
953
- .story-info { position: absolute; bottom: 40px; left: 20px; right: 20px; text-align: center; z-index: 10; padding: 20px; background: linear-gradient(0deg, rgba(0,0,0,0.8) 0%, rgba(0,0,0,0) 100%); border-radius: 20px; }
954
- .story-btn { background: var(--accent); color: white; border: none; padding: 15px 30px; border-radius: 30px; font-weight: bold; font-size: 1.1rem; width: 100%; cursor: pointer; box-shadow: 0 4px 15px rgba(0,0,0,0.3); touch-action: manipulation; }
955
 
956
  .categories-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; padding: 20px; }
957
  .category-item { background: var(--surface); padding: 20px 15px; border-radius: 16px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; cursor: pointer; box-shadow: 0 4px 15px rgba(0,0,0,0.03); transition: transform 0.2s; text-align: center; }
@@ -1049,8 +1047,26 @@ CATALOG_TEMPLATE = '''
1049
  .btn-float-returns { background: #e17055; }
1050
  .btn-float-history { background: #0984e3; }
1051
 
1052
- .multi-cart-btn { background: #8e44ad; position: relative; }
1053
- .cart-badge-count { position: absolute; top: -5px; right: -5px; background: #ff7675; color: white; font-size: 0.8rem; font-weight: bold; width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 5px rgba(0,0,0,0.2); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1054
 
1055
  .staff-banner { background: #ffeaa7; color: #d63031; text-align: center; padding: 10px; font-weight: 600; font-size: 0.9rem; }
1056
  .returns-list { display: flex; flex-direction: column; gap: 15px; }
@@ -1067,17 +1083,13 @@ CATALOG_TEMPLATE = '''
1067
  .pagination button:active { transform: scale(0.95); }
1068
  .pagination span { color: var(--text-muted); }
1069
 
1070
- {% if settings.theme in ['dark', 'magma', 'ocean', 'forest', 'cyberpunk'] %}
1071
- .category-item, .product-card, .header, .search-bar, .cart-bar, .modal-content, .stories-wrapper { box-shadow: 0 4px 15px rgba(0,0,0,0.5); border: 1px solid var(--border); }
1072
- {% endif %}
1073
-
1074
  @media (min-width: 768px) {
1075
  .categories-container { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
1076
  .products-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(400px, 1fr)); }
1077
- .modal-content { max-width: 500px; margin: 0 auto; border-radius: 24px; top: 50%; transform: translateY(-50%) scale(0.9); bottom: auto; position: relative; max-height: 90vh; }
1078
- .modal-overlay.active .modal-content { transform: translateY(-50%) scale(1); }
1079
- .cart-bar { max-width: 400px; left: auto; right: 20px; bottom: 20px; border-radius: 20px; transform: none; box-shadow: 0 10px 30px rgba(0,0,0,0.15); border: 1px solid var(--border); }
1080
- .story-modal-content { height: 90vh; border-radius: 24px; overflow: hidden; }
1081
  }
1082
  </style>
1083
  </head>
@@ -1131,10 +1143,7 @@ CATALOG_TEMPLATE = '''
1131
  </div>
1132
  </div>
1133
 
1134
- <div class="stories-wrapper" id="storiesWrapper">
1135
- <div style="font-weight:700; margin-bottom:10px; font-size:1.1rem; color:var(--text);">Новинки</div>
1136
- <div class="stories-container" id="storiesContainer"></div>
1137
- </div>
1138
 
1139
  <div class="categories-container" id="categoriesContainer"></div>
1140
  <div class="products-container" id="productsContainer"></div>
@@ -1287,31 +1296,10 @@ CATALOG_TEMPLATE = '''
1287
  </div>
1288
  </div>
1289
 
1290
- <div class="story-modal-overlay" id="storyModalOverlay" onclick="if(event.target===this) closeStory()">
1291
- <div class="story-modal-content">
1292
- <div class="story-progress" id="storyProgress"></div>
1293
- <div class="story-header">
1294
- <div style="display:flex; align-items:center; gap:10px; color:white; font-weight:bold;">
1295
- <span style="background:var(--accent); padding:4px 10px; border-radius:12px; font-size:0.85rem; box-shadow:0 2px 5px rgba(0,0,0,0.3);">Новинка</span>
1296
- <span id="storyTitle" style="font-size:1.1rem; text-shadow:0 2px 5px rgba(0,0,0,0.5);"></span>
1297
- </div>
1298
- <i class="fas fa-times" style="color:white; font-size:1.8rem; cursor:pointer; text-shadow:0 2px 5px rgba(0,0,0,0.5);" onclick="closeStory()"></i>
1299
- </div>
1300
- <div class="story-body" id="storyBody" onclick="nextStory(event)">
1301
- <img id="storyImg" src="">
1302
- <div class="story-info">
1303
- <div id="storyPrice" style="font-size:1.8rem; font-weight:900; color:white; margin-bottom:15px; text-shadow:0 2px 5px rgba(0,0,0,0.5);"></div>
1304
- <button class="story-btn" id="storyBuyBtn">Открыть товар</button>
1305
- </div>
1306
- </div>
1307
- </div>
1308
- </div>
1309
-
1310
  <script>
1311
  const products = {{ products_json|safe }};
1312
  const categoriesList = {{ categories_json|safe }};
1313
  const categoryPhotos = {{ category_photos_json|safe }};
1314
- const recentProducts = {{ recent_products_json|safe }};
1315
  const repoId = '{{ repo_id }}';
1316
  const currency = '{{ currency_code }}';
1317
  const envId = '{{ env_id }}';
@@ -1338,9 +1326,6 @@ CATALOG_TEMPLATE = '''
1338
  let currentCategory = null;
1339
  let currentSearchQuery = '';
1340
 
1341
- let currentStoryIndex = 0;
1342
- let storyTimeout;
1343
-
1344
  function initCart() {
1345
  const lsKey = `metastore_multi_${envId}_${mode}`;
1346
  try {
@@ -1442,107 +1427,10 @@ CATALOG_TEMPLATE = '''
1442
  else if (currentView === 'search') filterCategories(currentPage);
1443
  }
1444
 
1445
- function renderStories() {
1446
- if(!recentProducts || recentProducts.length === 0) return;
1447
- document.getElementById('storiesWrapper').style.display = 'block';
1448
- const cont = document.getElementById('storiesContainer');
1449
- cont.innerHTML = '';
1450
- recentProducts.forEach((p, index) => {
1451
- let img = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjBmMHcwIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGRvbWluYW50LWJhc2VsaW5lPSJtaWRkbGUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiNhMGEwYTAiIGZvbnQtZmFtaWx5PSJzYW5zLXNlcmlmIiBmb250LXNpemU9IjE0Ij7QndC10YIg0YTQvtGC0L48L3RleHQ+PC9zdmc+';
1452
- if(p.photos && p.photos.length > 0) img = `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${p.photos[0]}`;
1453
- cont.innerHTML += `
1454
- <div class="story-item" onclick="openStoryModal(${index})">
1455
- <div class="story-ring">
1456
- <img src="${img}" class="story-img">
1457
- </div>
1458
- <div class="story-title">${p.name}</div>
1459
- </div>
1460
- `;
1461
- });
1462
- }
1463
-
1464
- function openStoryModal(index) {
1465
- currentStoryIndex = index;
1466
- document.getElementById('storyModalOverlay').style.display = 'flex';
1467
- document.body.style.overflow = 'hidden';
1468
- showStory();
1469
- }
1470
-
1471
- function showStory() {
1472
- if(currentStoryIndex >= recentProducts.length || currentStoryIndex < 0) {
1473
- closeStory();
1474
- return;
1475
- }
1476
- const p = recentProducts[currentStoryIndex];
1477
- document.getElementById('storyTitle').innerText = p.name;
1478
- document.getElementById('storyPrice').innerText = p.price + ' ' + currency;
1479
-
1480
- let img = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjBmMHcwIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGRvbWluYW50LWJhc2VsaW5lPSJtaWRkbGUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiNhMGEwYTAiIGZvbnQtZmFtaWx5PSJzYW5zLXNlcmlmIiBmb250LXNpemU9IjE0Ij7QndC10YIg0YTQvtGC0L48L3RleHQ+PC9zdmc+';
1481
- if(p.photos && p.photos.length > 0) img = `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${p.photos[0]}`;
1482
- document.getElementById('storyImg').src = img;
1483
-
1484
- const prog = document.getElementById('storyProgress');
1485
- prog.innerHTML = '';
1486
- recentProducts.forEach((_, i) => {
1487
- let fill = i < currentStoryIndex ? '100%' : '0%';
1488
- prog.innerHTML += `<div class="story-progress-segment"><div class="story-progress-bar" id="storyBar${i}" style="width:${fill};"></div></div>`;
1489
- });
1490
-
1491
- document.getElementById('storyBuyBtn').onclick = (e) => {
1492
- e.stopPropagation();
1493
- closeStory();
1494
- showProducts(p.category, 1);
1495
- document.getElementById('searchInput').value = p.name;
1496
- filterCategories();
1497
- };
1498
-
1499
- clearTimeout(storyTimeout);
1500
- animateStoryBar(currentStoryIndex);
1501
- }
1502
-
1503
- function animateStoryBar(index) {
1504
- const bar = document.getElementById('storyBar' + index);
1505
- if(!bar) return;
1506
- bar.style.transition = 'none';
1507
- bar.style.width = '0%';
1508
- setTimeout(() => {
1509
- bar.style.transition = 'width 5s linear';
1510
- bar.style.width = '100%';
1511
- }, 50);
1512
-
1513
- storyTimeout = setTimeout(() => {
1514
- nextStory();
1515
- }, 5050);
1516
- }
1517
-
1518
- function nextStory(e) {
1519
- if(e) {
1520
- const rect = e.currentTarget.getBoundingClientRect();
1521
- const x = e.clientX - rect.left;
1522
- if(x < rect.width * 0.3) {
1523
- currentStoryIndex--;
1524
- if(currentStoryIndex < 0) currentStoryIndex = 0;
1525
- } else {
1526
- currentStoryIndex++;
1527
- }
1528
- } else {
1529
- currentStoryIndex++;
1530
- }
1531
- clearTimeout(storyTimeout);
1532
- if(currentStoryIndex >= recentProducts.length) closeStory();
1533
- else showStory();
1534
- }
1535
-
1536
- function closeStory() {
1537
- document.getElementById('storyModalOverlay').style.display = 'none';
1538
- document.body.style.overflow = '';
1539
- clearTimeout(storyTimeout);
1540
- }
1541
-
1542
  function init() {
1543
  initCart();
1544
- renderCategories(1);
1545
  renderStories();
 
1546
  updateCartUI();
1547
 
1548
  let today = new Date();
@@ -1551,6 +1439,52 @@ CATALOG_TEMPLATE = '''
1551
  document.getElementById('historyDateFilter').value = localToday;
1552
  }
1553
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1554
  function getCartKey(productId, variantIdx) {
1555
  return (variantIdx !== undefined && variantIdx !== null && variantIdx !== -1) ? `${productId}___${variantIdx}` : productId;
1556
  }
@@ -1618,7 +1552,6 @@ CATALOG_TEMPLATE = '''
1618
  container.style.display = 'grid';
1619
  document.getElementById('backBtn').style.display = 'none';
1620
  document.getElementById('pageTitle').innerText = '{{ t("Каталог") }}';
1621
- document.getElementById('storiesWrapper').style.display = recentProducts.length > 0 ? 'block' : 'none';
1622
 
1623
  container.innerHTML = '';
1624
 
@@ -1671,7 +1604,6 @@ CATALOG_TEMPLATE = '''
1671
  currentSearchQuery = query;
1672
 
1673
  document.getElementById('categoriesContainer').style.display = 'none';
1674
- document.getElementById('storiesWrapper').style.display = 'none';
1675
  const container = document.getElementById('productsContainer');
1676
  container.style.display = 'flex';
1677
  document.getElementById('backBtn').style.display = 'block';
@@ -1910,7 +1842,6 @@ CATALOG_TEMPLATE = '''
1910
  currentCategory = category;
1911
 
1912
  document.getElementById('categoriesContainer').style.display = 'none';
1913
- document.getElementById('storiesWrapper').style.display = 'none';
1914
  const container = document.getElementById('productsContainer');
1915
  container.style.display = 'flex';
1916
  document.getElementById('backBtn').style.display = 'block';
@@ -2474,7 +2405,7 @@ CATALOG_TEMPLATE = '''
2474
  });
2475
 
2476
  function startScanner(callback) {
2477
- document.getElementById('scannerModal').style.display = 'block';
2478
  const html5QrCode = new Html5Qrcode("reader");
2479
  const config = { fps: 10, qrbox: { width: 250, height: 250 } };
2480
  html5QrCode.start({ facingMode: "environment" }, config, (text) => {
@@ -4112,7 +4043,7 @@ ADMIN_TEMPLATE = '''
4112
  {% if v.barcode and search_q in v.barcode|lower %}
4113
  {% set ns_prod.match = true %}
4114
  {% endif %}
4115
- endfor %}
4116
  {% endif %}
4117
  {% endif %}
4118
 
@@ -4771,789 +4702,14 @@ ADMIN_TEMPLATE = '''
4771
  </html>
4772
  '''
4773
 
4774
- REPORTS_TEMPLATE = '''
4775
- <!DOCTYPE html>
4776
- <html lang="ru">
4777
- <head>
4778
- <meta charset="UTF-8">
4779
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
4780
- <title>Отчеты</title>
4781
- <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
4782
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
4783
- <style>
4784
- :root { --bg: #f4f6f9; --surface: #ffffff; --text: #2d3436; --border: #e0e6ed; --primary: #0984e3; --success: #00b894; --warning: #f39c12; }
4785
- body { font-family: 'Montserrat', sans-serif; background-color: var(--bg); color: var(--text); padding: 20px; margin: 0; }
4786
- .container { max-width: 1000px; margin: 0 auto; }
4787
- .header { display: flex; justify-content: space-between; align-items: center; background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); margin-bottom: 20px; flex-wrap: wrap; gap: 15px; }
4788
- .header h1 { margin: 0; font-size: 1.5rem; }
4789
- .btn { padding: 12px 18px; border: none; border-radius: 10px; font-weight: 600; cursor: pointer; color: #fff; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; background: var(--primary); font-size: 16px; min-height: 44px; touch-action: manipulation; }
4790
- .filter-bar { background: var(--surface); padding: 20px; border-radius: 12px; display: flex; gap: 15px; align-items: center; flex-wrap: wrap; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); }
4791
- .filter-bar input { padding: 16px; border: 1px solid var(--border); border-radius: 8px; outline: none; font-family: inherit; font-size: 16px; width: 100%; box-sizing: border-box; }
4792
-
4793
- .tabs { display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid var(--border); padding-bottom: 10px; flex-wrap: wrap; overflow-x: auto; -webkit-overflow-scrolling: touch; }
4794
- .tab { padding: 12px 20px; cursor: pointer; font-weight: 600; color: #636e72; border-radius: 10px; transition: background 0.2s; font-size: 16px; white-space: nowrap; }
4795
- .tab:hover { background: #e9ecef; }
4796
- .tab.active {background: var(--primary); color: #fff; }
4797
-
4798
- .tab-content { display: none; }
4799
- .tab-content.active { display: block; }
4800
-
4801
- .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px; }
4802
- .stat-card { background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); display: flex; flex-direction: column; gap: 10px; position: relative; overflow: hidden; }
4803
- .stat-card .title { font-size: 1rem; color: #636e72; font-weight: 600; z-index: 2; }
4804
- .stat-card .value { font-size: 1.8rem; font-weight: 700; color: var(--text); z-index: 2; }
4805
- .stat-card.icon { font-size: 3rem; color: var(--primary); opacity: 0.1; position: absolute; right: 10px; bottom: -5px; z-index: 1; }
4806
-
4807
- .table-container { background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow-x: auto; margin-bottom: 20px; }
4808
- table { width: 100%; border-collapse: collapse; min-width: 500px; }
4809
- th, td { padding: 15px; text-align: left; border-bottom: 1px solid var(--border); font-size: 16px; }
4810
- th { font-weight: 600; color: #636e72; background: #fafafa; }
4811
-
4812
- @media (max-width: 600px) {
4813
- .header { flex-direction: column; align-items: stretch; text-align: center; }
4814
- .filter-bar { flex-direction: column; align-items: stretch; }
4815
- .stats-grid { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
4816
- .stat-card { padding: 15px; }
4817
- .stat-card .value { font-size: 1.5rem; }
4818
- }
4819
- </style>
4820
- </head>
4821
- <body>
4822
- <div class="container">
4823
- <div class="header">
4824
- <h1><i class="fas fa-chart-line"></i> Расширенные Отчеты</h1>
4825
- <a href="/{{ env_id }}/admin" class="btn"><i class="fas fa-arrow-left"></i> Назад в панель</a>
4826
- </div>
4827
-
4828
- <div class="filter-bar">
4829
- <span style="font-weight: 500; font-size: 16px;">Период:</span>
4830
- <div style="display:flex; gap:10px; flex:1;">
4831
- <input type="date" id="dateStart" onchange="updateReports()" style="flex:1;">
4832
- <span style="display:flex; align-items:center;">—</span>
4833
- <input type="date" id="dateEnd" onchange="updateReports()" style="flex:1;">
4834
- </div>
4835
- <button class="btn" style="background:var(--success); width: 100%; justify-content: center;" onclick="setMonthDates()">Текущий месяц</button>
4836
- </div>
4837
-
4838
- <div class="tabs">
4839
- <div class="tab active" onclick="switchTab('general')">Общий отчет</div>
4840
- <div class="tab" onclick="switchTab('daily')">По дням</div>
4841
- <div class="tab" onclick="switchTab('category')">По категориям</div>
4842
- <div class="tab" onclick="switchTab('staff')">По сотрудникам</div>
4843
- {% if settings.margin_tracking and settings.system_mode == 'both' %}
4844
- <div class="tab" onclick="switchTab('margin')">Маржа и Прибыль</div>
4845
- {% endif %}
4846
- </div>
4847
-
4848
- <div id="general" class="tab-content active">
4849
- <div class="stats-grid">
4850
- <div class="stat-card">
4851
- <div class="title">Общая выручка</div>
4852
- <div class="value" id="totalRevenue">0</div>
4853
- <i class="fas fa-money-bill-wave icon"></i>
4854
- </div>
4855
- <div class="stat-card">
4856
- <div class="title">Кол-во заказов</div>
4857
- <div class="value" id="totalOrders">0</div>
4858
- <i class="fas fa-shopping-cart icon"></i>
4859
- </div>
4860
- <div class="stat-card">
4861
- <div class="title">Средний чек (AOV)</div>
4862
- <div class="value" id="avgOrderValue">0</div>
4863
- <i class="fas fa-receipt icon"></i>
4864
- </div>
4865
- <div class="stat-card">
4866
- <div class="title">Продано товаров (шт)</div>
4867
- <div class="value" id="totalItemsSold">0</div>
4868
- <i class="fas fa-box icon"></i>
4869
- </div>
4870
- <div class="stat-card">
4871
- <div class="title">Возвраты (сумма)</div>
4872
- <div class="value" id="totalReturns" style="color:var(--danger);">0</div>
4873
- <i class="fas fa-undo icon"></i>
4874
- </div>
4875
- {% if settings.commission_enabled %}
4876
- <div class="stat-card">
4877
- <div class="title">Сумма комиссий ({{ settings.commission_percent }}%)</div>
4878
- <div class="value" id="totalCommissions" style="color:var(--info);">0</div>
4879
- <i class="fas fa-percentage icon"></i>
4880
- </div>
4881
- {% endif %}
4882
- </div>
4883
-
4884
- <div class="table-container">
4885
- <h3>Топ продаваемых товаров</h3>
4886
- <table>
4887
- <thead>
4888
- <tr>
4889
- <th>Товар</th>
4890
- <th>Кол-во (шт)</th>
4891
- <th>Сумма ({{ currency_code }})</th>
4892
- </tr>
4893
- </thead>
4894
- <tbody id="topProductsTable"></tbody>
4895
- </table>
4896
- </div>
4897
- </div>
4898
-
4899
- <div id="daily" class="tab-content">
4900
- <div class="table-container">
4901
- <h3>Продажи по дням</h3>
4902
- <table>
4903
- <thead>
4904
- <tr>
4905
- <th>Дата</th>
4906
- <th>Кол-во заказов</th>
4907
- <th>Выручка ({{ currency_code }})</th>
4908
- </tr>
4909
- </thead>
4910
- <tbody id="dailySalesTable"></tbody>
4911
- </table>
4912
- </div>
4913
- </div>
4914
-
4915
- <div id="category" class="tab-content">
4916
- <div class="table-container">
4917
- <h3>Продажи по категориям</h3>
4918
- <table>
4919
- <thead>
4920
- <tr>
4921
- <th>Категория</th>
4922
- <th>Кол-во (шт)</th>
4923
- <th>Выручка ({{ currency_code }})</th>
4924
- </tr>
4925
- </thead>
4926
- <tbody id="categorySalesTable"></tbody>
4927
- </table>
4928
- </div>
4929
- </div>
4930
-
4931
- <div id="staff" class="tab-content">
4932
- <div class="table-container">
4933
- <h3>Выручка по сотрудникам</h3>
4934
- <table>
4935
- <thead>
4936
- <tr>
4937
- <th>Сотрудник</th>
4938
- <th>Кол-во заказов</th>
4939
- <th>Выручка ({{ currency_code }})</th>
4940
- </tr>
4941
- </thead>
4942
- <tbody id="staffSalesTable"></tbody>
4943
- </table>
4944
- </div>
4945
- </div>
4946
-
4947
- {% if settings.margin_tracking and settings.system_mode == 'both' %}
4948
- <div id="margin" class="tab-content">
4949
- <div class="stats-grid">
4950
- <div class="stat-card">
4951
- <div class="title">Чистая прибыль</div>
4952
- <div class="value" id="totalProfit" style="color:var(--success);">0</div>
4953
- <i class="fas fa-coins icon"></i>
4954
- </div>
4955
- <div class="stat-card">
4956
- <div class="title">Себестоимость проданного</div>
4957
- <div class="value" id="totalCost" style="color:var(--warning);">0</div>
4958
- <i class="fas fa-boxes icon"></i>
4959
- </div>
4960
- <div class="stat-card">
4961
- <div class="title">Средняя маржинальность</div>
4962
- <div class="value" id="avgMargin">0%</div>
4963
- <i class="fas fa-chart-pie icon"></i>
4964
- </div>
4965
- </div>
4966
-
4967
- <div class="table-container">
4968
- <h3>Маржинальность по товарам</h3>
4969
- <table>
4970
- <thead>
4971
- <tr>
4972
- <th>Товар</th>
4973
- <th>Кол-во (шт)</th>
4974
- <th>Выручка</th>
4975
- <th>Себест.</th>
4976
- <th>Прибыль</th>
4977
- <th>Маржа %</th>
4978
- </tr>
4979
- </thead>
4980
- <tbody id="marginTableBody"></tbody>
4981
- </table>
4982
- </div>
4983
- </div>
4984
- {% endif %}
4985
- </div>
4986
-
4987
- <script>
4988
- const allOrders = {{ orders_json|safe }};
4989
-
4990
- function switchTab(tabId) {
4991
- document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
4992
- document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
4993
- event.target.classList.add('active');
4994
- document.getElementById(tabId).classList.add('active');
4995
- }
4996
-
4997
- function setMonthDates() {
4998
- const today = new Date();
4999
- const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
5000
-
5001
- const offset = firstDay.getTimezoneOffset() * 60000;
5002
- const localFirst = new Date(firstDay.getTime() - offset).toISOString().split('T')[0];
5003
- const localToday = new Date(today.getTime() - offset).toISOString().split('T')[0];
5004
-
5005
- document.getElementById('dateStart').value = localFirst;
5006
- document.getElementById('dateEnd').value = localToday;
5007
- updateReports();
5008
- }
5009
-
5010
- function updateReports() {
5011
- const startDate = document.getElementById('dateStart').value;
5012
- const endDate = document.getElementById('dateEnd').value;
5013
-
5014
- let filteredOrders = allOrders.filter(o => o.status === 'confirmed' || o.status === 'pos' || o.status === 'returned');
5015
-
5016
- if (startDate) {
5017
- const sDate = new Date(startDate);
5018
- filteredOrders = filteredOrders.filter(o => new Date(o.created_at.split(' ')[0]) >= sDate);
5019
- }
5020
- if (endDate) {
5021
- const eDate = new Date(endDate);
5022
- filteredOrders = filteredOrders.filter(o => new Date(o.created_at.split(' ')[0]) <= eDate);
5023
- }
5024
-
5025
- let totalRev = 0;
5026
- let totalRet = 0;
5027
- let totalItems = 0;
5028
- let ordersCount = 0;
5029
- let totalCommissions = 0;
5030
- let totalCost = 0;
5031
-
5032
- let staffSales = {};
5033
- let productSales = {};
5034
- let dailySales = {};
5035
- let categorySales = {};
5036
- let marginSales = {};
5037
-
5038
- filteredOrders.forEach(o => {
5039
- if(o.status === 'returned') {
5040
- totalRet += o.total_price;
5041
- } else {
5042
- totalRev += o.total_price;
5043
- ordersCount++;
5044
-
5045
- if (o.commission_amount) {
5046
- totalCommissions += o.commission_amount;
5047
- }
5048
-
5049
- const staff = o.staff_name || 'Онлайн (Без сотрудника)';
5050
- if(!staffSales[staff]) staffSales[staff] = { orders: 0, sum: 0 };
5051
- staffSales[staff].orders += 1;
5052
- staffSales[staff].sum += o.total_price;
5053
-
5054
- const dateStr = o.created_at.split(' ')[0];
5055
- if(!dailySales[dateStr]) dailySales[dateStr] = { orders: 0, sum: 0 };
5056
- dailySales[dateStr].orders += 1;
5057
- dailySales[dateStr].sum += o.total_price;
5058
-
5059
- o.cart.forEach(item => {
5060
- if(item.quantity > 0) {
5061
- totalItems += item.quantity;
5062
- let pName = item.name;
5063
- if(item.variant_name) pName += ` (${item.variant_name})`;
5064
-
5065
- let itemPrice = parseFloat(item.calculated_price) || parseFloat(item.price);
5066
- let itemRev = itemPrice * item.quantity;
5067
- let itemCost = parseFloat(item.cost_price) || 0;
5068
- let itemTotalCost = itemCost * item.quantity;
5069
-
5070
- totalCost += itemTotalCost;
5071
-
5072
- if(!productSales[pName]) productSales[pName] = { qty: 0, sum: 0 };
5073
- productSales[pName].qty += item.quantity;
5074
- productSales[pName].sum += itemRev;
5075
-
5076
- let catName = item.category || 'Без категории';
5077
- if(!categorySales[catName]) categorySales[catName] = { qty: 0, sum: 0 };
5078
- categorySales[catName].qty += item.quantity;
5079
- categorySales[catName].sum += itemRev;
5080
-
5081
- if(!marginSales[pName]) marginSales[pName] = { qty: 0, rev: 0, cost: 0, profit: 0 };
5082
- marginSales[pName].qty += item.quantity;
5083
- marginSales[pName].rev += itemRev;
5084
- marginSales[pName].cost += itemTotalCost;
5085
- marginSales[pName].profit += (itemRev - itemTotalCost);
5086
- }
5087
- });
5088
- }
5089
- });
5090
-
5091
- document.getElementById('totalRevenue').innerText = totalRev.toLocaleString() + ' {{ currency_code }}';
5092
- document.getElementById('totalOrders').innerText = ordersCount;
5093
- document.getElementById('totalReturns').innerText = totalRet.toLocaleString() + ' {{ currency_code }}';
5094
- document.getElementById('totalItemsSold').innerText = totalItems.toLocaleString();
5095
-
5096
- let tcEl = document.getElementById('totalCommissions');
5097
- if (tcEl) {
5098
- tcEl.innerText = totalCommissions.toLocaleString() + ' {{ currency_code }}';
5099
- }
5100
-
5101
- let aov = ordersCount > 0 ? (totalRev / ordersCount) : 0;
5102
- document.getElementById('avgOrderValue').innerText = Math.round(aov).toLocaleString() + ' {{ currency_code }}';
5103
-
5104
- let tpEl = document.getElementById('totalProfit');
5105
- if(tpEl) {
5106
- let totalProfit = totalRev - totalCost - totalCommissions;
5107
- let avgMargin = totalRev > 0 ? (totalProfit / totalRev) * 100 : 0;
5108
-
5109
- tpEl.innerText = Math.round(totalProfit).toLocaleString() + ' {{ currency_code }}';
5110
- document.getElementById('totalCost').innerText = Math.round(totalCost).toLocaleString() + ' {{ currency_code }}';
5111
- document.getElementById('avgMargin').innerText = avgMargin.toFixed(1) + '%';
5112
-
5113
- renderMarginTable(marginSales);
5114
- }
5115
-
5116
- renderTopProducts(productSales);
5117
- renderStaffTable(staffSales);
5118
- renderDailyTable(dailySales);
5119
- renderCategoryTable(categorySales);
5120
- }
5121
-
5122
- function renderTopProducts(data) {
5123
- const tbody = document.getElementById('topProductsTable');
5124
- tbody.innerHTML = '';
5125
- const sorted = Object.keys(data).sort((a,b) => data[b].sum - data[a].sum).slice(0, 15);
5126
- if(sorted.length === 0) {
5127
- tbody.innerHTML = '<tr><td colspan="3" style="text-align:center;">Нет данных</td></tr>';
5128
- return;
5129
- }
5130
- sorted.forEach(p => {
5131
- tbody.innerHTML += `
5132
- <tr>
5133
- <td style="font-weight:500;">${p}</td>
5134
- <td>${data[p].qty}</td>
5135
- <td>${Math.round(data[p].sum).toLocaleString()}</td>
5136
- </tr>
5137
- `;
5138
- });
5139
- }
5140
-
5141
- function renderStaffTable(data) {
5142
- const tbody = document.getElementById('staffSalesTable');
5143
- tbody.innerHTML = '';
5144
- const sorted = Object.keys(data).sort((a,b) => data[b].sum - data[a].sum);
5145
- if(sorted.length === 0) {
5146
- tbody.innerHTML = '<tr><td colspan="3" style="text-align:center;">Нет данных</td></tr>';
5147
- return;
5148
- }
5149
- sorted.forEach(s => {
5150
- tbody.innerHTML += `
5151
- <tr>
5152
- <td style="font-weight:500;">${s}</td>
5153
- <td>${data[s].orders}</td>
5154
- <td>${Math.round(data[s].sum).toLocaleString()}</td>
5155
- </tr>
5156
- `;
5157
- });
5158
- }
5159
-
5160
- function renderDailyTable(data) {
5161
- const tbody = document.getElementById('dailySalesTable');
5162
- tbody.innerHTML = '';
5163
- const sorted = Object.keys(data).sort((a,b) => new Date(b) - new Date(a));
5164
- if(sorted.length === 0) {
5165
- tbody.innerHTML = '<tr><td colspan="3" style="text-align:center;">Нет данных</td></tr>';
5166
- return;
5167
- }
5168
- sorted.forEach(d => {
5169
- tbody.innerHTML += `
5170
- <tr>
5171
- <td style="font-weight:500;">${d}</td>
5172
- <td>${data[d].orders}</td>
5173
- <td>${Math.round(data[d].sum).toLocaleString()}</td>
5174
- </tr>
5175
- `;
5176
- });
5177
- }
5178
-
5179
- function renderCategoryTable(data) {
5180
- const tbody = document.getElementById('categorySalesTable');
5181
- tbody.innerHTML = '';
5182
- const sorted = Object.keys(data).sort((a,b) => data[b].sum - data[a].sum);
5183
- if(sorted.length === 0) {
5184
- tbody.innerHTML = '<tr><td colspan="3" style="text-align:center;">Нет данных</td></tr>';
5185
- return;
5186
- }
5187
- sorted.forEach(c => {
5188
- tbody.innerHTML += `
5189
- <tr>
5190
- <td style="font-weight:500;">${c}</td>
5191
- <td>${data[c].qty}</td>
5192
- <td>${Math.round(data[c].sum).toLocaleString()}</td>
5193
- </tr>
5194
- `;
5195
- });
5196
- }
5197
-
5198
- function renderMarginTable(data) {
5199
- const tbody = document.getElementById('marginTableBody');
5200
- if(!tbody) return;
5201
- tbody.innerHTML = '';
5202
- const sorted = Object.keys(data).sort((a,b) => data[b].profit - data[a].profit);
5203
- if(sorted.length === 0) {
5204
- tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;">Нет данных</td></tr>';
5205
- return;
5206
- }
5207
- sorted.forEach(p => {
5208
- let marginPct = data[p].rev > 0 ? (data[p].profit / data[p].rev) * 100 : 0;
5209
- tbody.innerHTML += `
5210
- <tr>
5211
- <td style="font-weight:500;">${p}</td>
5212
- <td>${data[p].qty}</td>
5213
- <td>${Math.round(data[p].rev).toLocaleString()}</td>
5214
- <td>${Math.round(data[p].cost).toLocaleString()}</td>
5215
- <td style="color:var(--success); font-weight:bold;">${Math.round(data[p].profit).toLocaleString()}</td>
5216
- <td>${marginPct.toFixed(1)}%</td>
5217
- </tr>
5218
- `;
5219
- });
5220
- }
5221
-
5222
- setMonthDates();
5223
- </script>
5224
- </body>
5225
- </html>
5226
- '''
5227
-
5228
- INVENTORY_TEMPLATE = '''
5229
- <!DOCTYPE html>
5230
- <html lang="ru">
5231
- <head>
5232
- <meta charset="UTF-8">
5233
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
5234
- <title>Учет остатков</title>
5235
- <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
5236
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
5237
- <style>
5238
- :root { --bg: #f4f6f9; --surface: #ffffff; --text: #2d3436; --border: #e0e6ed; --primary: #27ae60; --info: #0984e3; --warning: #f39c12; --danger: #ff7675; }
5239
- body { font-family: 'Montserrat', sans-serif; background-color: var(--bg); color: var(--text); padding: 20px; margin: 0; }
5240
- .container { max-width: 1200px; margin: 0 auto; }
5241
- .header { display: flex; justify-content: space-between; align-items: center; background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); margin-bottom: 20px; flex-wrap: wrap; gap: 15px; }
5242
- .header h1 { margin: 0; font-size: 1.5rem; }
5243
- .btn { padding: 12px 18px; border: none; border-radius: 10px; font-weight: 600; cursor: pointer; color: #fff; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; gap: 8px; background: var(--info); font-size: 16px; min-height: 44px; touch-action: manipulation; }
5244
- .search-bar { background: var(--surface); padding: 15px 20px; border-radius: 12px; display: flex; align-items: center; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); position: relative; }
5245
- .search-bar input { width: 100%; padding: 16px; border: 1px solid var(--border); border-radius: 8px; outline: none; font-size: 16px; border-right: none; border-top-right-radius: 0; border-bottom-right-radius: 0; box-sizing: border-box; }
5246
-
5247
- .tabs { display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid var(--border); padding-bottom: 10px; flex-wrap: wrap; overflow-x: auto; -webkit-overflow-scrolling: touch; }
5248
- .tab { padding: 12px 20px; cursor: pointer; font-weight: 600; color: #636e72; border-radius: 10px; transition: background 0.2s; display:flex; align-items:center; gap:8px; font-size: 16px; white-space: nowrap; }
5249
- .tab:hover { background: #e9ecef; }
5250
- .tab.active { background: var(--primary); color: #fff; }
5251
- .tab-content { display: none; }
5252
- .tab-content.active { display: block; }
5253
-
5254
- .table-container { background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow-x: auto; margin-bottom: 20px; }
5255
- table { width: 100%; border-collapse: collapse; min-width: 600px; }
5256
- th, td { padding: 15px; text-align: left; border-bottom: 1px solid var(--border); vertical-align: middle; font-size: 16px; }
5257
- th { font-weight: 600; color: #636e72; background: #fafafa; }
5258
-
5259
- .inv-row { content-visibility: auto; contain-intrinsic-size: auto 60px; }
5260
-
5261
- .action-cell { display: flex; gap: 5px; align-items: center; flex-wrap: wrap; }
5262
- .action-cell input[type="number"] { width: 80px; padding: 12px; border: 1px solid var(--border); border-radius: 8px; text-align: center; font-size: 16px; box-sizing: border-box; }
5263
- .action-cell input[type="text"] { width: 150px; padding: 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 16px; box-sizing: border-box; }
5264
- .btn-sm { padding: 10px 14px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; color: white; font-size: 16px; touch-action: manipulation; }
5265
- .btn-add { background: var(--primary); }
5266
- .btn-sub { background: var(--danger); }
5267
- .badge-type-add { background: #d4edda; color: #155724; padding: 4px 8px; border-radius: 12px; font-size: 0.9rem; font-weight: 600; }
5268
- .badge-type-sub { background: #f8d7da; color: #721c24; padding: 4px 8px; border-radius: 12px; font-size: 0.9rem; font-weight: 600; }
5269
- .badge-danger { background: var(--danger); color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.9rem; }
5270
- .badge-info { background: var(--info); color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.9rem; }
5271
-
5272
- @media (max-width: 600px) {
5273
- .header { flex-direction: column; align-items: stretch; text-align: center; }
5274
- .action-cell { flex-direction: column; align-items: stretch; }
5275
- .action-cell input[type="number"], .action-cell input[type="text"] { width: 100%; }
5276
- .btn-sm { width: 100%; }
5277
- }
5278
- </style>
5279
- </head>
5280
- <body>
5281
- <div class="container">
5282
- <div class="header">
5283
- <h1><i class="fas fa-boxes"></i> Учет остатков</h1>
5284
- <a href="/{{ env_id }}/admin" class="btn"><i class="fas fa-arrow-left"></i> Назад в панель</a>
5285
- </div>
5286
-
5287
- <div class="tabs">
5288
- <div class="tab active" onclick="switchTab('current')">Текущие остатки</div>
5289
- <div class="tab" onclick="switchTab('low')">Заканчивающиеся <span class="badge-danger">{{ low_stock_items|length }}</span></div>
5290
- <div class="tab" onclick="switchTab('purchases')">Заказы <span class="badge-info">{{ active_purchases|length }}</span></div>
5291
- <div class="tab" onclick="switchTab('history')">История операций</div>
5292
- </div>
5293
-
5294
- <div id="current" class="tab-content active">
5295
- <div class="search-bar" style="padding: 10px 20px;">
5296
- <div style="display:flex; flex:1;">
5297
- <input type="text" id="searchInput" placeholder="Поиск товара или ID..." onkeydown="if(event.key==='Enter') filterTable()" onkeyup="debounceFilterTable()">
5298
- <button class="btn" style="border-radius: 0 8px 8px 0; padding: 0 20px;" onclick="filterTable()"><i class="fas fa-search"></i></button>
5299
- </div>
5300
- </div>
5301
-
5302
- <div class="table-container">
5303
- <table>
5304
- <thead>
5305
- <tr>
5306
- <th>Товар</th>
5307
- <th>Категория</th>
5308
- <th>Остаток</th>
5309
- <th>Действие (Приход / Списание)</th>
5310
- </tr>
5311
- </thead>
5312
- <tbody id="inventoryTable">
5313
- {% for p in products %}
5314
- {% if not p.variants %}
5315
- <tr class="inv-row" data-pid="{{ p.product_id }}">
5316
- <td class="prod-name">
5317
- <strong>{{ p.name }}</strong><br>
5318
- <span style="font-size:0.85rem; color:#b2bec3;">ID: {{ p.product_id }}</span>
5319
- </td>
5320
- <td>{{ p.category }}</td>
5321
- <td><strong>{{ p.stock if p.stock != "" else "0" }}</strong></td>
5322
- <td>
5323
- <div class="action-cell">
5324
- <input type="number" id="qty_{{ p.product_id }}_-1" placeholder="Кол-во" min="1">
5325
- <input type="text" id="comment_{{ p.product_id }}_-1" placeholder="Комментарий">
5326
- <button class="btn-sm btn-add" onclick="updateStock('{{ p.product_id }}', -1, true)">+ Приход</button>
5327
- <button class="btn-sm btn-sub" onclick="updateStock('{{ p.product_id }}', -1, false)">- Списание</button>
5328
- </div>
5329
- </td>
5330
- </tr>
5331
- {% else %}
5332
- {% for v in p.variants %}
5333
- <tr class="inv-row" data-pid="{{ p.product_id }}">
5334
- <td class="prod-name">
5335
- <strong>{{ p.name }}</strong> <span style="color:#636e72;">({{ v.name }})</span><br>
5336
- <span style="font-size:0.85rem; color:#b2bec3;">ID: {{ p.product_id }}</span>
5337
- </td>
5338
- <td>{{ p.category }}</td>
5339
- <td><strong>{{ v.stock if v.stock != "" else "0" }}</strong></td>
5340
- <td>
5341
- <div class="action-cell">
5342
- <input type="number" id="qty_{{ p.product_id }}_{{ loop.index0 }}" placeholder="Кол-во" min="1">
5343
- <input type="text" id="comment_{{ p.product_id }}_{{ loop.index0 }}" placeholder="Комментарий">
5344
- <button class="btn-sm btn-add" onclick="updateStock('{{ p.product_id }}', {{ loop.index0 }}, true)">+ Приход</button>
5345
- <button class="btn-sm btn-sub" onclick="updateStock('{{ p.product_id }}', {{ loop.index0 }}, false)">- Списание</button>
5346
- </div>
5347
- </td>
5348
- </tr>
5349
- {% endfor %}
5350
- {% endif %}
5351
- {% endfor %}
5352
- </tbody>
5353
- </table>
5354
- </div>
5355
- </div>
5356
-
5357
- <div id="low" class="tab-content">
5358
- <div class="table-container">
5359
- <table>
5360
- <thead>
5361
- <tr>
5362
- <th>Товар</th>
5363
- <th>Вариант</th>
5364
- <th>Категория</th>
5365
- <th>Остаток</th>
5366
- </tr>
5367
- </thead>
5368
- <tbody>
5369
- {% for item in low_stock_items %}
5370
- <tr>
5371
- <td><strong>{{ item.name }}</strong></td>
5372
- <td>{{ item.variant }}</td>
5373
- <td>{{ item.category }}</td>
5374
- <td style="color:var(--danger); font-weight:bold;">{{ item.stock }}</td>
5375
- </tr>
5376
- {% else %}
5377
- <tr><td colspan="4" style="text-align:center;">Нет заканчивающихся товаров</td></tr>
5378
- {% endfor %}
5379
- </tbody>
5380
- </table>
5381
- </div>
5382
- </div>
5383
-
5384
- <div id="purchases" class="tab-content">
5385
- <div class="table-container">
5386
- <table>
5387
- <thead>
5388
- <tr>
5389
- <th>Дата и время</th>
5390
- <th>Товар</th>
5391
- <th>Ожидается (шт)</th>
5392
- <th>Действия</th>
5393
- </tr>
5394
- </thead>
5395
- <tbody>
5396
- {% for po in active_purchases %}
5397
- <tr>
5398
- <td>{{ po.date }}</td>
5399
- <td><strong>{{ po.product_name }}</strong> {% if po.variant_name %}<br><span style="color:#636e72;">{{ po.variant_name }}</span>{% endif %}</td>
5400
- <td><strong style="color:var(--info); font-size:1.2rem;">{{ po.qty }}</strong></td>
5401
- <td>
5402
- <div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
5403
- <button class="btn-sm btn-add" onclick="receivePurchase('{{ po.id }}', {{ po.qty }})"><i class="fas fa-check"></i> Пришел полный</button>
5404
- <div style="display:flex; align-items:center; gap:5px; border-left: 1px solid var(--border); padding-left: 15px; margin-left: 5px;">
5405
- <input type="number" id="part_qty_{{ po.id }}" placeholder="Кол-во" style="width:90px; padding:10px; border:1px solid var(--border); border-radius:8px; text-align:center; font-size:16px;">
5406
- <button class="btn-sm" style="background:var(--warning); color:#fff;" onclick="receivePartialPurchase('{{ po.id }}')">Частично</button>
5407
- </div>
5408
- </div>
5409
- </td>
5410
- </tr>
5411
- {% else %}
5412
- <tr><td colspan="4" style="text-align:center;">Нет активных заказов поставщикам</td></tr>
5413
- {% endfor %}
5414
- </tbody>
5415
- </table>
5416
- </div>
5417
- </div>
5418
-
5419
- <div id="history" class="tab-content">
5420
- <div class="table-container">
5421
- <table>
5422
- <thead>
5423
- <tr>
5424
- <th>Дата</th>
5425
- <th>Товар</th>
5426
- <th>Тип</th>
5427
- <th>Кол-во</th>
5428
- <th>Комментарий</th>
5429
- </tr>
5430
- </thead>
5431
- <tbody>
5432
- {% for h in history|reverse %}
5433
- <tr>
5434
- <td>{{ h.date }}</td>
5435
- <td>{{ h.product }} {% if h.variant %}({{ h.variant }}){% endif %}</td>
5436
- <td>
5437
- {% if h.change > 0 %}
5438
- <span class="badge-type-add">Приход</span>
5439
- {% else %}
5440
- <span class="badge-type-sub">Списание</span>
5441
- {% endif %}
5442
- </td>
5443
- <td><strong>{{ h.change|abs }}</strong></td>
5444
- <td>{{ h.comment }}</td>
5445
- </tr>
5446
- {% else %}
5447
- <tr><td colspan="5" style="text-align:center;">История пуста</td></tr>
5448
- {% endfor %}
5449
- </tbody>
5450
- </table>
5451
- </div>
5452
- </div>
5453
- </div>
5454
-
5455
- <script>
5456
- const envId = '{{ env_id }}';
5457
-
5458
- function switchTab(tabId) {
5459
- document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
5460
- document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
5461
- event.target.classList.add('active');
5462
- document.getElementById(tabId).classList.add('active');
5463
- }
5464
-
5465
- let invTimer;
5466
- function debounceFilterTable() {
5467
- clearTimeout(invTimer);
5468
- invTimer = setTimeout(filterTable, 300);
5469
- }
5470
-
5471
- function filterTable() {
5472
- const query = document.getElementById('searchInput').value.toLowerCase();
5473
- const rows = document.querySelectorAll('.inv-row');
5474
- rows.forEach(row => {
5475
- const text = row.querySelector('.prod-name').innerText.toLowerCase();
5476
- const pid = row.getAttribute('data-pid').toLowerCase();
5477
- if(text.includes(query) || pid.includes(query)) row.style.display = 'table-row';
5478
- else row.style.display = 'none';
5479
- });
5480
- }
5481
-
5482
- function updateStock(productId, variantIdx, isAdd) {
5483
- const qtyInput = document.getElementById(`qty_${productId}_${variantIdx}`);
5484
- const commentInput = document.getElementById(`comment_${productId}_${variantIdx}`);
5485
-
5486
- const qty = parseInt(qtyInput.value);
5487
- const comment = commentInput.value;
5488
-
5489
- if(isNaN(qty) || qty <= 0) {
5490
- alert('Введите корректное количество');
5491
- return;
5492
- }
5493
-
5494
- fetch(`/${envId}/api/inventory`, {
5495
- method: 'POST',
5496
- headers: { 'Content-Type': 'application/json' },
5497
- body: JSON.stringify({
5498
- product_id: productId,
5499
- variant_idx: variantIdx,
5500
- qty: qty,
5501
- is_add: isAdd,
5502
- comment: comment
5503
- })
5504
- })
5505
- .then(r => r.json())
5506
- .then(data => {
5507
- if(data.success) {
5508
- window.location.reload();
5509
- } else {
5510
- alert('Ошибка обновления остатков');
5511
- }
5512
- });
5513
- }
5514
-
5515
- function receivePurchase(poId, qty) {
5516
- if(!confirm('Подтвердить полное поступление?')) return;
5517
- processReceive(poId, qty);
5518
- }
5519
-
5520
- function receivePartialPurchase(poId) {
5521
- const input = document.getElementById('part_qty_' + poId);
5522
- const qty = parseInt(input.value);
5523
- if(isNaN(qty) || qty <= 0) {
5524
- alert('Укажите корректное количество');
5525
- return;
5526
- }
5527
- processReceive(poId, qty);
5528
- }
5529
-
5530
- function processReceive(poId, qty) {
5531
- fetch(`/${envId}/api/receive_purchase`, {
5532
- method: 'POST',
5533
- headers: { 'Content-Type': 'application/json' },
5534
- body: JSON.stringify({ po_id: poId, qty: qty })
5535
- })
5536
- .then(r => r.json())
5537
- .then(data => {
5538
- if(data.success) {
5539
- window.location.reload();
5540
- } else {
5541
- alert('Ошибка при поступлении товара');
5542
- }
5543
- });
5544
- }
5545
- </script>
5546
- </body>
5547
- </html>
5548
- '''
5549
-
5550
  DEBTS_TEMPLATE = '''
5551
  <!DOCTYPE html>
5552
  <html lang="ru">
5553
  <head>
5554
  <meta charset="UTF-8">
5555
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
5556
- <title>Долги клиентов</title>
5557
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
5558
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
5559
  <style>
@@ -5563,19 +4719,18 @@ DEBTS_TEMPLATE = '''
5563
  .header { display: flex; justify-content: space-between; align-items: center; background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); margin-bottom: 20px; flex-wrap: wrap; gap: 15px; }
5564
  .header h1 { margin: 0; font-size: 1.5rem; color: var(--primary); }
5565
  .btn { padding: 12px 18px; border: none; border-radius: 10px; font-weight: 600; cursor: pointer; color: #fff; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; background: var(--info); font-size: 16px; min-height: 44px; justify-content: center; }
5566
- .table-container { background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow-x: auto; }
 
5567
  table { width: 100%; border-collapse: collapse; min-width: 600px; }
5568
  th, td { padding: 15px; text-align: left; border-bottom: 1px solid var(--border); font-size: 16px; }
5569
  th { font-weight: 600; color: #636e72; background: #fafafa; }
5570
  .payment-form { display: flex; gap: 10px; flex-wrap: wrap; }
5571
  .payment-form input { padding: 12px; border: 1px solid var(--border); border-radius: 8px; width: 140px; outline: none; font-size: 16px; box-sizing: border-box; }
5572
  .payment-form button { background: var(--success); color: white; border: none; padding: 12px 15px; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 16px; min-height: 44px; }
5573
- .tabs { display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid var(--border); padding-bottom: 10px; flex-wrap: wrap; }
5574
- .tab { padding: 10px 15px; cursor: pointer; font-weight: 600; color: #636e72; border-radius: 10px; transition: background 0.2s; font-size: 16px; }
5575
  .tab:hover { background: #e9ecef; }
5576
- .tab.active { background: var(--info); color: #fff; }
5577
- .tab-content { display: none; }
5578
- .tab-content.active { display: block; }
5579
  @media (max-width: 600px) {
5580
  .header { flex-direction: column; align-items: stretch; text-align: center; }
5581
  .payment-form { flex-direction: column; align-items: stretch; width: 100%; }
@@ -5587,9 +4742,14 @@ DEBTS_TEMPLATE = '''
5587
  <div class="container">
5588
  <div class="header">
5589
  <h1><i class="fas fa-hand-holding-usd"></i> Учет долгов</h1>
5590
- <a href="/{{ env_id }}/admin" class="btn"><i class="fas fa-arrow-left"></i> Назад в панель</a>
5591
  </div>
5592
 
 
 
 
 
 
5593
  {% with messages = get_flashed_messages(with_categories=true) %}
5594
  {% if messages %}
5595
  {% for category, message in messages %}
@@ -5598,282 +4758,85 @@ DEBTS_TEMPLATE = '''
5598
  {% endif %}
5599
  {% endwith %}
5600
 
5601
- <div class="tabs">
5602
- <div class="tab active" onclick="switchTab('active_debts')">Активные долги</div>
5603
- <div class="tab" onclick="switchTab('closed_debts')">История погашенных долгов</div>
5604
- </div>
5605
-
5606
- <div id="active_debts" class="tab-content active">
5607
- <div class="table-container">
5608
- <table>
5609
- <thead>
5610
- <tr>
5611
- <th>Накладная</th>
5612
- <th>Дата</th>
5613
- <th>Клиент</th>
5614
- <th>Общая сумма</th>
5615
- <th>Оплачено</th>
5616
- <th style="color:var(--primary);">Долг</th>
5617
- <th>Внести оплату</th>
5618
- </tr>
5619
- </thead>
5620
- <tbody>
5621
- {% for o in debts %}
5622
- <tr>
5623
- <td><a href="/{{ env_id }}/order/{{ o.id }}" target="_blank" style="color:var(--info); font-weight:bold; text-decoration:none;">{{ o.id }}</a></td>
5624
- <td>{{ o.created_at.split(' ')[0] }}</td>
5625
- <td>{{ o.customer_name if o.customer_name else 'Касса' }}<br><span style="font-size:0.9rem; color:#636e72;">{{ o.customer_whatsapp }}</span></td>
5626
- <td>{{ o.total_price }} {{ currency }}</td>
5627
- <td style="color:var(--success); font-weight:bold;">{{ o.paid_amount }} {{ currency }}</td>
5628
- <td style="color:var(--primary); font-weight:bold; font-size:1.2rem;">{{ o.debt_amount }} {{ currency }}</td>
5629
- <td>
5630
- <form class="payment-form" action="/{{ env_id }}/pay_debt/{{ o.id }}" method="POST">
5631
- <input type="number" name="amount" step="0.01" max="{{ o.debt_amount }}" required placeholder="Сумма ({{ currency }})">
5632
- <button type="submit"><i class="fas fa-check"></i> Оплатить</button>
5633
- </form>
5634
- {% if o.debt_payments and o.debt_payments|length > 0 %}
5635
- <button class="btn" style="background:transparent; color:var(--info); border:1px solid var(--info); margin-top:10px; padding: 6px 12px; font-size:14px; min-height:auto;" onclick="document.getElementById('history-{{ o.id }}').style.display='block'">История оплат</button>
5636
- <div id="history-{{ o.id }}" style="display:none; margin-top:10px; background:#fafafa; padding:10px; border-radius:8px; border:1px solid var(--border);">
5637
- <div style="font-weight:bold; margin-bottom:5px; font-size:0.9rem;">История платежей:</div>
5638
- {% for p in o.debt_payments %}
5639
- <div style="font-size:0.85rem; border-bottom:1px solid #eee; padding:4px 0;">{{ p.date }} - <span style="color:var(--success); font-weight:bold;">+{{ p.amount }} {{ currency }}</span></div>
5640
- {% endfor %}
5641
- </div>
5642
- {% endif %}
5643
- </td>
5644
- </tr>
5645
- {% else %}
5646
- <tr>
5647
- <td colspan="7" style="text-align: center; padding: 40px; color: #636e72; font-size: 1.1rem;">Нет активных долгов</td>
5648
- </tr>
5649
- {% endfor %}
5650
- </tbody>
5651
- </table>
5652
- </div>
5653
- </div>
5654
-
5655
- <div id="closed_debts" class="tab-content" style="display:none;">
5656
- <div class="table-container">
5657
- <table>
5658
- <thead>
5659
- <tr>
5660
- <th>Накладная</th>
5661
- <th>Дата создания</th>
5662
- <th>Клиент</th>
5663
- <th>Общая сумма</th>
5664
- <th>История платежей</th>
5665
- <th>Статус</th>
5666
- </tr>
5667
- </thead>
5668
- <tbody>
5669
- {% for o in closed_debts %}
5670
- <tr>
5671
- <td><a href="/{{ env_id }}/order/{{ o.id }}" target="_blank" style="color:var(--info); font-weight:bold; text-decoration:none;">{{ o.id }}</a></td>
5672
- <td>{{ o.created_at.split(' ')[0] }}</td>
5673
- <td>{{ o.customer_name if o.customer_name else 'Касса' }}<br><span style="font-size:0.9rem; color:#636e72;">{{ o.customer_whatsapp }}</span></td>
5674
- <td>{{ o.total_price }} {{ currency }}</td>
5675
- <td>
5676
- {% for p in o.debt_payments %}
5677
- <div style="font-size:0.9rem; color:var(--success); padding:3px 0;">{{ p.date }} : <span style="font-weight:bold;">+{{ p.amount }} {{ currency }}</span></div>
5678
- {% endfor %}
5679
- </td>
5680
- <td><span style="background:#d4edda; color:#155724; padding:5px 10px; border-radius:8px; font-size:0.9rem; font-weight:bold;">Погашен полностью</span></td>
5681
- </tr>
5682
- {% else %}
5683
- <tr>
5684
- <td colspan="6" style="text-align: center; padding: 40px; color: #636e72; font-size: 1.1rem;">История пуста</td>
5685
- </tr>
5686
- {% endfor %}
5687
- </tbody>
5688
- </table>
5689
- </div>
5690
- </div>
5691
- </div>
5692
-
5693
- <script>
5694
- function switchTab(id) {
5695
- document.querySelectorAll('.tab-content').forEach(el => el.style.display = 'none');
5696
- document.querySelectorAll('.tab').forEach(el => el.classList.remove('active'));
5697
- document.getElementById(id).style.display = 'block';
5698
- event.target.classList.add('active');
5699
- }
5700
- </script>
5701
- </body>
5702
- </html>
5703
- '''
5704
-
5705
- PURCHASES_TEMPLATE = '''
5706
- <!DOCTYPE html>
5707
- <html lang="ru">
5708
- <head>
5709
- <meta charset="UTF-8">
5710
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
5711
- <title>Заказы поставщикам</title>
5712
- <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
5713
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
5714
- <style>
5715
- :root { --bg: #f4f6f9; --surface: #ffffff; --text: #2d3436; --border: #e0e6ed; --primary: #f1c40f; --info: #0984e3; --danger: #ff7675; }
5716
- body { font-family: 'Montserrat', sans-serif; background-color: var(--bg); color: var(--text); padding: 20px; margin: 0; }
5717
- .container { max-width: 1200px; margin: 0 auto; }
5718
- .header { display: flex; justify-content: space-between; align-items: center; background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); margin-bottom: 20px; flex-wrap: wrap; gap: 15px; }
5719
- .header h1 { margin: 0; font-size: 1.5rem; color: #2d3436; }
5720
- .btn { padding: 12px 18px; border: none; border-radius: 10px; font-weight: 600; cursor: pointer; color: #fff; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; gap: 8px; background: var(--info); font-size: 16px; min-height: 44px; touch-action: manipulation; }
5721
- .search-bar { background: var(--surface); padding: 15px 20px; border-radius: 12px; display: flex; align-items: center; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); position: relative; }
5722
- .search-bar input { width: 100%; padding: 16px; border: 1px solid var(--border); border-radius: 8px; outline: none; font-size: 16px; border-right: none; border-top-right-radius: 0; border-bottom-right-radius: 0; box-sizing: border-box; }
5723
- .table-container { background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow-x: auto; margin-bottom: 20px; }
5724
- table { width: 100%; border-collapse: collapse; min-width: 600px; }
5725
- th, td { padding: 15px; text-align: left; border-bottom: 1px solid var(--border); vertical-align: middle; font-size: 16px; }
5726
- th { font-weight: 600; color: #636e72; background: #fafafa; }
5727
- .btn-order { background: var(--primary); color: #2d3436; font-weight: 600; padding: 10px 15px; border-radius: 8px; border: none; cursor: pointer; font-size: 16px; min-height: 44px; display: inline-flex; align-items: center; justify-content: center; gap: 5px; touch-action: manipulation; }
5728
-
5729
- .modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); align-items: center; justify-content: center; z-index: 1000; padding: 15px; box-sizing: border-box; }
5730
- .modal-content { background: #fff; padding: 25px; border-radius: 16px; width: 100%; max-width: 450px; text-align: center; }
5731
- .modal-content h3 { margin-top: 0; font-size: 1.3rem; }
5732
- .modal-content input { width: 100%; padding: 16px; border: 1px solid var(--border); border-radius: 10px; margin-bottom: 20px; font-size: 16px; text-align: center; box-sizing: border-box; }
5733
- .modal-actions { display: flex; gap: 15px; justify-content: center; flex-wrap: wrap; }
5734
- .modal-actions button { flex: 1; padding: 16px; font-size: 16px; min-width: 120px; }
5735
- .inv-row { content-visibility: auto; contain-intrinsic-size: auto 60px; }
5736
-
5737
- @media (max-width: 600px) {
5738
- .header { flex-direction: column; align-items: stretch; text-align: center; }
5739
- .header .btn { width: 100%; }
5740
- .btn-order { width: 100%; }
5741
- }
5742
- </style>
5743
- </head>
5744
- <body>
5745
- <div class="container">
5746
- <div class="header">
5747
- <h1><i class="fas fa-truck-loading" style="color:var(--primary);"></i> Заказы поставщикам</h1>
5748
- <div style="display:flex; gap:10px; flex-wrap:wrap;">
5749
- <a href="/{{ env_id }}/inventory" class="btn" style="background:#27ae60;"><i class="fas fa-boxes"></i> В остатки</a>
5750
- <a href="/{{ env_id }}/admin" class="btn"><i class="fas fa-arrow-left"></i> В панель</a>
5751
- </div>
5752
- </div>
5753
-
5754
- <div class="search-bar" style="padding: 10px 20px;">
5755
- <div style="display:flex; flex:1;">
5756
- <input type="text" id="searchInput" placeholder="Поиск товара или ID..." onkeydown="if(event.key==='Enter') filterTable()" onkeyup="debounceFilterTable()">
5757
- <button class="btn" style="border-radius: 0 8px 8px 0; padding: 0 20px;" onclick="filterTable()"><i class="fas fa-search"></i></button>
5758
- </div>
5759
- </div>
5760
-
5761
- <div class="table-container">
5762
  <table>
5763
  <thead>
5764
  <tr>
5765
- <th>Товар</th>
5766
- <th>Категория</th>
5767
- <th>Текущий остаток</th>
5768
- <th>Действие</th>
 
 
 
5769
  </tr>
5770
  </thead>
5771
  <tbody>
5772
- {% for p in products %}
5773
- {% if not p.variants %}
5774
- <tr class="inv-row" data-pid="{{ p.product_id }}">
5775
- <td class="prod-name">
5776
- <strong>{{ p.name }}</strong><br>
5777
- <span style="font-size:0.85rem; color:#b2bec3;">ID: {{ p.product_id }}</span>
5778
- </td>
5779
- <td>{{ p.category }}</td>
5780
- <td><strong>{{ p.stock if p.stock != "" else "0" }}</strong></td>
5781
- <td>
5782
- <button class="btn-order" onclick="openOrderModal('{{ p.product_id }}', -1, '{{ p.name|replace("'", "\\'") }}')"><i class="fas fa-plus"></i> Сделать заказ</button>
5783
- </td>
5784
- </tr>
5785
- {% else %}
5786
- {% for v in p.variants %}
5787
- <tr class="inv-row" data-pid="{{ p.product_id }}">
5788
- <td class="prod-name">
5789
- <strong>{{ p.name }}</strong> <span style="color:#636e72;">({{ v.name }})</span><br>
5790
- <span style="font-size:0.85rem; color:#b2bec3;">ID: {{ p.product_id }}</span>
5791
- </td>
5792
- <td>{{ p.category }}</td>
5793
- <td><strong>{{ v.stock if v.stock != "" else "0" }}</strong></td>
5794
- <td>
5795
- <button class="btn-order" onclick="openOrderModal('{{ p.product_id }}', {{ loop.index0 }}, '{{ p.name|replace("'", "\\'") }} ({{ v.name|replace("'", "\\'") }})')"><i class="fas fa-plus"></i> Сделать заказ</button>
5796
- </td>
5797
- </tr>
5798
- {% endfor %}
5799
- {% endif %}
5800
  {% endfor %}
5801
  </tbody>
5802
  </table>
5803
  </div>
5804
- </div>
5805
 
5806
- <div class="modal-overlay" id="orderModal">
5807
- <div class="modal-content">
5808
- <h3>Заказ товара</h3>
5809
- <p id="orderProductName" style="font-weight:600; color:#636e72; margin-bottom:15px; font-size:1.1rem;"></p>
5810
- <input type="number" id="orderQty" placeholder="Введите количество" min="1">
5811
- <div class="modal-actions">
5812
- <button class="btn btn-order" style="background:#27ae60; color:#fff;" onclick="submitOrder()">Подтвердить</button>
5813
- <button class="btn btn-danger" style="background:#ff7675;" onclick="closeOrderModal()">Отмена</button>
5814
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5815
  </div>
5816
  </div>
5817
-
5818
  <script>
5819
- const envId = '{{ env_id }}';
5820
- let currentOrder = null;
5821
- let searchTimer;
5822
-
5823
- function debounceFilterTable() {
5824
- clearTimeout(searchTimer);
5825
- searchTimer = setTimeout(filterTable, 300);
5826
- }
5827
-
5828
- function filterTable() {
5829
- const query = document.getElementById('searchInput').value.toLowerCase();
5830
- const rows = document.querySelectorAll('.inv-row');
5831
- rows.forEach(row => {
5832
- const text = row.querySelector('.prod-name').innerText.toLowerCase();
5833
- const pid = row.getAttribute('data-pid').toLowerCase();
5834
- if(text.includes(query) || pid.includes(query)) row.style.display = 'table-row';
5835
- else row.style.display = 'none';
5836
- });
5837
- }
5838
-
5839
- function openOrderModal(pid, vidx, name) {
5840
- currentOrder = { product_id: pid, variant_idx: vidx };
5841
- document.getElementById('orderProductName').innerText = name;
5842
- document.getElementById('orderQty').value = '';
5843
- document.getElementById('orderModal').style.display = 'flex';
5844
- }
5845
-
5846
- function closeOrderModal() {
5847
- document.getElementById('orderModal').style.display = 'none';
5848
- currentOrder = null;
5849
- }
5850
-
5851
- function submitOrder() {
5852
- if(!currentOrder) return;
5853
- const qty = parseInt(document.getElementById('orderQty').value);
5854
- if(isNaN(qty) || qty <= 0) {
5855
- alert('Укажите корректное количество');
5856
- return;
5857
- }
5858
-
5859
- fetch(`/${envId}/api/purchase`, {
5860
- method: 'POST',
5861
- headers: { 'Content-Type': 'application/json' },
5862
- body: JSON.stringify({
5863
- product_id: currentOrder.product_id,
5864
- variant_idx: currentOrder.variant_idx,
5865
- qty: qty
5866
- })
5867
- })
5868
- .then(r => r.json())
5869
- .then(data => {
5870
- if(data.success) {
5871
- alert('Заказ успешно создан! Перейдите во вкладку "Заказы" в "Остатках".');
5872
- closeOrderModal();
5873
- } else {
5874
- alert('Ошибка создания заказа');
5875
- }
5876
- });
5877
  }
5878
  </script>
5879
  </body>
@@ -5918,7 +4881,7 @@ def create_environment():
5918
  if new_id not in all_data:
5919
  break
5920
  all_data[new_id] = {
5921
- 'products': [], 'categories':[], 'category_photos': {}, 'orders': {}, 'staff': [], 'catalog_users': [], 'inventory_history':[], 'purchase_orders': [],
5922
  'settings': {
5923
  "organization_name": f"Shop {new_id}",
5924
  "admin_password_enabled": False,
@@ -5993,6 +4956,7 @@ def clear_history(env_id):
5993
  if env_id in all_data:
5994
  all_data[env_id]['orders'] = {}
5995
  all_data[env_id]['inventory_history'] =[]
 
5996
  save_data(all_data)
5997
  flash(f'История среды {env_id} успешно очищена.', 'success')
5998
  else:
@@ -6064,17 +5028,6 @@ def catalog(env_id):
6064
  mode = request.args.get('mode', 'online')
6065
  staff_id = request.args.get('staff_id', '')
6066
 
6067
- recent_products = []
6068
- for p in all_products:
6069
- created_at_str = p.get('created_at', '')
6070
- if created_at_str:
6071
- try:
6072
- dt = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
6073
- if (datetime.utcnow() + timedelta(hours=5) - dt).days <= 2:
6074
- recent_products.append(p)
6075
- except ValueError:
6076
- pass
6077
-
6078
  if settings.get('system_mode', 'both') == 'internal' and mode != 'pos':
6079
  return "Каталог недоступен в режиме внутреннего учета", 403
6080
 
@@ -6097,7 +5050,6 @@ def catalog(env_id):
6097
  products_json=json.dumps(all_products),
6098
  categories_json=json.dumps(categories),
6099
  category_photos_json=json.dumps(category_photos),
6100
- recent_products_json=json.dumps(recent_products),
6101
  repo_id=REPO_ID,
6102
  currency_code=settings.get('currency', '₸'),
6103
  settings=settings,
@@ -6301,8 +5253,7 @@ def create_order(env_id):
6301
  "commission_amount": 0,
6302
  "is_debt": order_data.get('is_debt', False),
6303
  "paid_amount": float(order_data.get('paid_amount', 0)),
6304
- "debt_amount": 0,
6305
- "debt_payments": []
6306
  }
6307
 
6308
  update_order_totals(new_order, data['settings'])
@@ -6444,19 +5395,22 @@ def pay_debt(env_id, order_id):
6444
  if amount > 0:
6445
  order['paid_amount'] = round(float(order.get('paid_amount', 0)) + amount, 2)
6446
  order['debt_amount'] = round(float(order.get('total_price', 0)) - order['paid_amount'], 2)
6447
-
6448
- if 'debt_payments' not in order:
6449
- order['debt_payments'] = []
6450
- order['debt_payments'].append({
6451
- "date": get_almaty_time(),
6452
- "amount": amount
6453
- })
6454
-
6455
  if order['debt_amount'] <= 0:
6456
  order['is_debt'] = False
6457
  order['debt_amount'] = 0
6458
  order['paid_amount'] = order.get('total_price', 0)
 
 
 
6459
 
 
 
 
 
 
 
 
 
6460
  save_env_data(env_id, data)
6461
  flash(f'Оплата в размере {amount} успешно внесена для заказа №{order_id}', 'success')
6462
  return redirect(url_for('debts', env_id=env_id))
@@ -6474,15 +5428,14 @@ def debts(env_id):
6474
  all_orders = list(data.get('orders', {}).values())
6475
  debt_orders = [o for o in all_orders if o.get('is_debt', False) and float(o.get('debt_amount', 0)) > 0]
6476
  debt_orders.sort(key=lambda x: x.get('created_at', ''), reverse=True)
6477
-
6478
- closed_debts = [o for o in all_orders if not o.get('is_debt', False) and len(o.get('debt_payments', [])) > 0]
6479
- closed_debts.sort(key=lambda x: x.get('created_at', ''), reverse=True)
6480
 
6481
  return render_template_string(
6482
  DEBTS_TEMPLATE,
6483
  env_id=env_id,
6484
  debts=debt_orders,
6485
- closed_debts=closed_debts,
6486
  currency=settings.get('currency', '₸')
6487
  )
6488
 
@@ -6725,7 +5678,8 @@ def export_products(env_id):
6725
  "box_price": p.get("box_price", ""),
6726
  "min_order": p.get("min_order", ""),
6727
  "has_variant_prices": p.get("has_variant_prices", False),
6728
- "variants": p.get("variants", [])
 
6729
  })
6730
 
6731
  json_str = json.dumps(export_data, ensure_ascii=False, indent=2)
@@ -6789,6 +5743,7 @@ def admin(env_id):
6789
  elif action == 'clear_history':
6790
  data['orders'] = {}
6791
  data['inventory_history'] =[]
 
6792
  save_env_data(env_id, data)
6793
  flash('История продаж и заказов успешно очищена.', 'success')
6794
 
@@ -6832,7 +5787,8 @@ def admin(env_id):
6832
  'box_price': p.get('box_price', ''),
6833
  'min_order': p.get('min_order', ''),
6834
  'has_variant_prices': p.get('has_variant_prices', False),
6835
- 'variants': p.get('variants', [])
 
6836
  })
6837
  else:
6838
  new_p = {
@@ -6853,7 +5809,7 @@ def admin(env_id):
6853
  'variants': p.get('variants', []),
6854
  'photos': p.get('photos', []),
6855
  'wholesale_tiers': p.get('wholesale_tiers', []),
6856
- 'created_at': get_almaty_time()
6857
  }
6858
  data['products'].append(new_p)
6859
 
 
318
  'catalog_users': [],
319
  'inventory_history':[],
320
  'purchase_orders': [],
321
+ 'debt_history': [],
322
  'settings': {
323
  'organization_name': 'Default Shop',
324
  'admin_password_enabled': False,
 
368
  if 'catalog_users' not in env_data: env_data['catalog_users'] = []
369
  if 'inventory_history' not in env_data: env_data['inventory_history'] = []
370
  if 'purchase_orders' not in env_data: env_data['purchase_orders'] = []; changed = True
371
+ if 'debt_history' not in env_data: env_data['debt_history'] = []; changed = True
372
  if 'settings' not in env_data:
373
  env_data['settings'] = {}
374
  changed = True
 
420
 
421
  for product in env_data['products']:
422
  if 'product_id' not in product: product['product_id'] = uuid4().hex; changed = True
423
+ if 'created_at' not in product: product['created_at'] = "2000-01-01 00:00:00"; changed = True
424
  if 'pieces_per_box' not in product: product['pieces_per_box'] = ""; changed = True
425
  if 'pieces_per_master_box' not in product: product['pieces_per_master_box'] = ""; changed = True
426
  if 'box_price' not in product: product['box_price'] = ""; changed = True
 
453
  if 'is_debt' not in order: order['is_debt'] = False; changed = True
454
  if 'paid_amount' not in order: order['paid_amount'] = order.get('total_price', 0); changed = True
455
  if 'debt_amount' not in order: order['debt_amount'] = 0; changed = True
 
456
  for item in order.get('cart', []):
457
  if 'discount' not in item: item['discount'] = 0; changed = True
458
  if 'cost_price' not in item: item['cost_price'] = 0; changed = True
 
496
  'catalog_users': [],
497
  'inventory_history':[],
498
  'purchase_orders': [],
499
+ 'debt_history': [],
500
  'settings': {
501
  'organization_name': f'Shop {env_id}',
502
  'admin_password_enabled': False,
 
936
  .search-container:focus-within { border-color: #dcdde1; background: var(--surface); box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
937
  .search-container input { width: 100%; padding: 15px 10px; border: none; background: transparent; outline: none; font-size: 16px; color: var(--text); }
938
 
939
+ .stories-container {
940
+ display: flex; overflow-x: auto; gap: 15px; padding: 15px 20px;
941
+ background: var(--surface); border-bottom: 1px solid var(--border);
942
+ scrollbar-width: none; -ms-overflow-style: none;
943
+ }
944
  .stories-container::-webkit-scrollbar { display: none; }
945
+ .story-item { display: flex; flex-direction: column; align-items: center; gap: 6px; cursor: pointer; min-width: 72px; }
946
+ .story-ring {
947
+ width: 68px; height: 68px; border-radius: 50%; padding: 3px;
948
+ background: linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
949
+ display: flex; align-items: center; justify-content: center;
950
+ }
951
+ .story-img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; border: 2px solid var(--surface); }
952
+ .story-title { font-size: 0.75rem; text-align: center; width: 72px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text); font-weight: 500; }
 
 
 
 
 
 
 
953
 
954
  .categories-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; padding: 20px; }
955
  .category-item { background: var(--surface); padding: 20px 15px; border-radius: 16px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; cursor: pointer; box-shadow: 0 4px 15px rgba(0,0,0,0.03); transition: transform 0.2s; text-align: center; }
 
1047
  .btn-float-returns { background: #e17055; }
1048
  .btn-float-history { background: #0984e3; }
1049
 
1050
+ .multi-cart-btn {
1051
+ background: #8e44ad;
1052
+ position: relative;
1053
+ }
1054
+ .cart-badge-count {
1055
+ position: absolute;
1056
+ top: -5px;
1057
+ right: -5px;
1058
+ background: #ff7675;
1059
+ color: white;
1060
+ font-size: 0.8rem;
1061
+ font-weight: bold;
1062
+ width: 24px;
1063
+ height: 24px;
1064
+ border-radius: 50%;
1065
+ display: flex;
1066
+ align-items: center;
1067
+ justify-content: center;
1068
+ box-shadow: 0 2px 5px rgba(0,0,0,0.2);
1069
+ }
1070
 
1071
  .staff-banner { background: #ffeaa7; color: #d63031; text-align: center; padding: 10px; font-weight: 600; font-size: 0.9rem; }
1072
  .returns-list { display: flex; flex-direction: column; gap: 15px; }
 
1083
  .pagination button:active { transform: scale(0.95); }
1084
  .pagination span { color: var(--text-muted); }
1085
 
 
 
 
 
1086
  @media (min-width: 768px) {
1087
  .categories-container { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
1088
  .products-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(400px, 1fr)); }
1089
+ .modal-overlay { align-items: center; justify-content: center; }
1090
+ .modal-content { max-width: 600px; margin: 0; border-radius: 24px; top: auto; bottom: auto; transform: scale(0.9); height: auto; max-height: 85vh; position: relative; }
1091
+ .modal-overlay.active .modal-content { transform: scale(1); }
1092
+ .cart-bar { max-width: 600px; left: 50%; transform: translateX(-50%); border-radius: 20px; bottom: 20px; }
1093
  }
1094
  </style>
1095
  </head>
 
1143
  </div>
1144
  </div>
1145
 
1146
+ <div class="stories-container" id="storiesContainer" style="display:none;"></div>
 
 
 
1147
 
1148
  <div class="categories-container" id="categoriesContainer"></div>
1149
  <div class="products-container" id="productsContainer"></div>
 
1296
  </div>
1297
  </div>
1298
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1299
  <script>
1300
  const products = {{ products_json|safe }};
1301
  const categoriesList = {{ categories_json|safe }};
1302
  const categoryPhotos = {{ category_photos_json|safe }};
 
1303
  const repoId = '{{ repo_id }}';
1304
  const currency = '{{ currency_code }}';
1305
  const envId = '{{ env_id }}';
 
1326
  let currentCategory = null;
1327
  let currentSearchQuery = '';
1328
 
 
 
 
1329
  function initCart() {
1330
  const lsKey = `metastore_multi_${envId}_${mode}`;
1331
  try {
 
1427
  else if (currentView === 'search') filterCategories(currentPage);
1428
  }
1429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1430
  function init() {
1431
  initCart();
 
1432
  renderStories();
1433
+ renderCategories(1);
1434
  updateCartUI();
1435
 
1436
  let today = new Date();
 
1439
  document.getElementById('historyDateFilter').value = localToday;
1440
  }
1441
 
1442
+ function renderStories() {
1443
+ const container = document.getElementById('storiesContainer');
1444
+ if (!container) return;
1445
+
1446
+ const now = new Date();
1447
+ const twoDaysAgo = new Date(now.getTime() - (2 * 24 * 60 * 60 * 1000));
1448
+
1449
+ const recentProducts = products.filter(p => {
1450
+ if (!p.created_at) return false;
1451
+ let dStr = p.created_at.replace(/-/g, '/');
1452
+ const pDate = new Date(dStr);
1453
+ return pDate >= twoDaysAgo;
1454
+ });
1455
+
1456
+ if (recentProducts.length === 0) {
1457
+ container.style.display = 'none';
1458
+ return;
1459
+ }
1460
+
1461
+ container.style.display = 'flex';
1462
+ container.innerHTML = '';
1463
+
1464
+ recentProducts.forEach(p => {
1465
+ let imgUrl = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjBmMHcwIi8+PC9zdmc+';
1466
+ if (p.photos && p.photos.length > 0) {
1467
+ imgUrl = `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${p.photos[0]}`;
1468
+ } else if (p.variants && p.variants.length > 0) {
1469
+ const vWithPhoto = p.variants.find(v => v.photo);
1470
+ if (vWithPhoto) {
1471
+ imgUrl = `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${vWithPhoto.photo}`;
1472
+ }
1473
+ }
1474
+
1475
+ const div = document.createElement('div');
1476
+ div.className = 'story-item';
1477
+ div.onclick = () => openGallery(p.product_id);
1478
+ div.innerHTML = `
1479
+ <div class="story-ring">
1480
+ <img src="${imgUrl}" class="story-img">
1481
+ </div>
1482
+ <div class="story-title">${p.name}</div>
1483
+ `;
1484
+ container.appendChild(div);
1485
+ });
1486
+ }
1487
+
1488
  function getCartKey(productId, variantIdx) {
1489
  return (variantIdx !== undefined && variantIdx !== null && variantIdx !== -1) ? `${productId}___${variantIdx}` : productId;
1490
  }
 
1552
  container.style.display = 'grid';
1553
  document.getElementById('backBtn').style.display = 'none';
1554
  document.getElementById('pageTitle').innerText = '{{ t("Каталог") }}';
 
1555
 
1556
  container.innerHTML = '';
1557
 
 
1604
  currentSearchQuery = query;
1605
 
1606
  document.getElementById('categoriesContainer').style.display = 'none';
 
1607
  const container = document.getElementById('productsContainer');
1608
  container.style.display = 'flex';
1609
  document.getElementById('backBtn').style.display = 'block';
 
1842
  currentCategory = category;
1843
 
1844
  document.getElementById('categoriesContainer').style.display = 'none';
 
1845
  const container = document.getElementById('productsContainer');
1846
  container.style.display = 'flex';
1847
  document.getElementById('backBtn').style.display = 'block';
 
2405
  });
2406
 
2407
  function startScanner(callback) {
2408
+ document.getElementById('scannerModal').style.display = 'flex';
2409
  const html5QrCode = new Html5Qrcode("reader");
2410
  const config = { fps: 10, qrbox: { width: 250, height: 250 } };
2411
  html5QrCode.start({ facingMode: "environment" }, config, (text) => {
 
4043
  {% if v.barcode and search_q in v.barcode|lower %}
4044
  {% set ns_prod.match = true %}
4045
  {% endif %}
4046
+ {% endfor %}
4047
  {% endif %}
4048
  {% endif %}
4049
 
 
4702
  </html>
4703
  '''
4704
 
4705
+ # Переопределяем DEBTS_TEMPLATE для поддержки истории долгов
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4706
  DEBTS_TEMPLATE = '''
4707
  <!DOCTYPE html>
4708
  <html lang="ru">
4709
  <head>
4710
  <meta charset="UTF-8">
4711
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
4712
+ <title>Учет долгов</title>
4713
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
4714
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
4715
  <style>
 
4719
  .header { display: flex; justify-content: space-between; align-items: center; background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); margin-bottom: 20px; flex-wrap: wrap; gap: 15px; }
4720
  .header h1 { margin: 0; font-size: 1.5rem; color: var(--primary); }
4721
  .btn { padding: 12px 18px; border: none; border-radius: 10px; font-weight: 600; cursor: pointer; color: #fff; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; background: var(--info); font-size: 16px; min-height: 44px; justify-content: center; }
4722
+ .table-container { background: var(--surface); padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow-x: auto; display: none; }
4723
+ .table-container.active { display: block; }
4724
  table { width: 100%; border-collapse: collapse; min-width: 600px; }
4725
  th, td { padding: 15px; text-align: left; border-bottom: 1px solid var(--border); font-size: 16px; }
4726
  th { font-weight: 600; color: #636e72; background: #fafafa; }
4727
  .payment-form { display: flex; gap: 10px; flex-wrap: wrap; }
4728
  .payment-form input { padding: 12px; border: 1px solid var(--border); border-radius: 8px; width: 140px; outline: none; font-size: 16px; box-sizing: border-box; }
4729
  .payment-form button { background: var(--success); color: white; border: none; padding: 12px 15px; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 16px; min-height: 44px; }
4730
+ .tabs { display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid var(--border); padding-bottom: 10px; }
4731
+ .tab { padding: 12px 20px; cursor: pointer; font-weight: 600; color: #636e72; border-radius: 10px; transition: background 0.2s; font-size: 16px; }
4732
  .tab:hover { background: #e9ecef; }
4733
+ .tab.active { background: var(--primary); color: #fff; }
 
 
4734
  @media (max-width: 600px) {
4735
  .header { flex-direction: column; align-items: stretch; text-align: center; }
4736
  .payment-form { flex-direction: column; align-items: stretch; width: 100%; }
 
4742
  <div class="container">
4743
  <div class="header">
4744
  <h1><i class="fas fa-hand-holding-usd"></i> Учет долгов</h1>
4745
+ <a href="/{{ env_id }}/admin" class="btn" style="background:var(--info);"><i class="fas fa-arrow-left"></i> Назад в панель</a>
4746
  </div>
4747
 
4748
+ <div class="tabs">
4749
+ <div class="tab active" onclick="switchTab('active-debts')">Активные долги</div>
4750
+ <div class="tab" onclick="switchTab('history-debts')">История погашений</div>
4751
+ </div>
4752
+
4753
  {% with messages = get_flashed_messages(with_categories=true) %}
4754
  {% if messages %}
4755
  {% for category, message in messages %}
 
4758
  {% endif %}
4759
  {% endwith %}
4760
 
4761
+ <div id="active-debts" class="table-container active">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4762
  <table>
4763
  <thead>
4764
  <tr>
4765
+ <th>Накладная</th>
4766
+ <th>Дата</th>
4767
+ <th>Клиент</th>
4768
+ <th>Общая сумма</th>
4769
+ <th>Оплачено</th>
4770
+ <th style="color:var(--primary);">Долг</th>
4771
+ <th>Внести оплату</th>
4772
  </tr>
4773
  </thead>
4774
  <tbody>
4775
+ {% for o in debts %}
4776
+ <tr>
4777
+ <td><a href="/{{ env_id }}/order/{{ o.id }}" target="_blank" style="color:var(--info); font-weight:bold; text-decoration:none;">{{ o.id }}</a></td>
4778
+ <td>{{ o.created_at.split(' ')[0] }}</td>
4779
+ <td>{{ o.customer_name if o.customer_name else 'Касса' }}<br><span style="font-size:0.9rem; color:#636e72;">{{ o.customer_whatsapp }}</span></td>
4780
+ <td>{{ o.total_price }} {{ currency }}</td>
4781
+ <td style="color:var(--success); font-weight:bold;">{{ o.paid_amount }} {{ currency }}</td>
4782
+ <td style="color:var(--primary); font-weight:bold; font-size:1.2rem;">{{ o.debt_amount }} {{ currency }}</td>
4783
+ <td>
4784
+ <form class="payment-form" action="/{{ env_id }}/pay_debt/{{ o.id }}" method="POST">
4785
+ <input type="number" name="amount" step="0.01" max="{{ o.debt_amount }}" required placeholder="Сумма ({{ currency }})">
4786
+ <button type="submit"><i class="fas fa-check"></i> Оплатить</button>
4787
+ </form>
4788
+ </td>
4789
+ </tr>
4790
+ {% else %}
4791
+ <tr>
4792
+ <td colspan="7" style="text-align: center; padding: 40px; color: #636e72; font-size: 1.1rem;">Нет активных долгов</td>
4793
+ </tr>
 
 
 
 
 
 
 
 
 
4794
  {% endfor %}
4795
  </tbody>
4796
  </table>
4797
  </div>
 
4798
 
4799
+ <div id="history-debts" class="table-container">
4800
+ <table>
4801
+ <thead>
4802
+ <tr>
4803
+ <th>Дата и Время</th>
4804
+ <th>Накладная</th>
4805
+ <th>Клиент</th>
4806
+ <th>Внесенная сумма</th>
4807
+ <th>Статус долга</th>
4808
+ </tr>
4809
+ </thead>
4810
+ <tbody>
4811
+ {% for h in debt_history|reverse %}
4812
+ <tr>
4813
+ <td>{{ h.date }}</td>
4814
+ <td><a href="/{{ env_id }}/order/{{ h.order_id }}" target="_blank" style="color:var(--info); font-weight:bold; text-decoration:none;">{{ h.order_id }}</a></td>
4815
+ <td>{{ h.customer_name }}</td>
4816
+ <td style="color:var(--success); font-weight:bold;">+{{ h.amount }} {{ currency }}</td>
4817
+ <td>
4818
+ {% if h.remaining_debt > 0 %}
4819
+ Остаток: <span style="color:var(--primary); font-weight:bold;">{{ h.remaining_debt }} {{ currency }}</span>
4820
+ {% else %}
4821
+ <span style="color:var(--success); font-weight:bold;">Полностью погашен</span>
4822
+ {% endif %}
4823
+ </td>
4824
+ </tr>
4825
+ {% else %}
4826
+ <tr>
4827
+ <td colspan="5" style="text-align: center; padding: 40px; color: #636e72; font-size: 1.1rem;">История пуста</td>
4828
+ </tr>
4829
+ {% endfor %}
4830
+ </tbody>
4831
+ </table>
4832
  </div>
4833
  </div>
 
4834
  <script>
4835
+ function switchTab(tabId) {
4836
+ document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
4837
+ document.querySelectorAll('.table-container').forEach(c => c.classList.remove('active'));
4838
+ event.target.classList.add('active');
4839
+ document.getElementById(tabId).classList.add('active');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4840
  }
4841
  </script>
4842
  </body>
 
4881
  if new_id not in all_data:
4882
  break
4883
  all_data[new_id] = {
4884
+ 'products': [], 'categories':[], 'category_photos': {}, 'orders': {}, 'staff': [], 'catalog_users': [], 'inventory_history':[], 'purchase_orders': [], 'debt_history': [],
4885
  'settings': {
4886
  "organization_name": f"Shop {new_id}",
4887
  "admin_password_enabled": False,
 
4956
  if env_id in all_data:
4957
  all_data[env_id]['orders'] = {}
4958
  all_data[env_id]['inventory_history'] =[]
4959
+ all_data[env_id]['debt_history'] = []
4960
  save_data(all_data)
4961
  flash(f'История среды {env_id} успешно очищена.', 'success')
4962
  else:
 
5028
  mode = request.args.get('mode', 'online')
5029
  staff_id = request.args.get('staff_id', '')
5030
 
 
 
 
 
 
 
 
 
 
 
 
5031
  if settings.get('system_mode', 'both') == 'internal' and mode != 'pos':
5032
  return "Каталог недоступен в режиме внутреннего учета", 403
5033
 
 
5050
  products_json=json.dumps(all_products),
5051
  categories_json=json.dumps(categories),
5052
  category_photos_json=json.dumps(category_photos),
 
5053
  repo_id=REPO_ID,
5054
  currency_code=settings.get('currency', '₸'),
5055
  settings=settings,
 
5253
  "commission_amount": 0,
5254
  "is_debt": order_data.get('is_debt', False),
5255
  "paid_amount": float(order_data.get('paid_amount', 0)),
5256
+ "debt_amount": 0
 
5257
  }
5258
 
5259
  update_order_totals(new_order, data['settings'])
 
5395
  if amount > 0:
5396
  order['paid_amount'] = round(float(order.get('paid_amount', 0)) + amount, 2)
5397
  order['debt_amount'] = round(float(order.get('total_price', 0)) - order['paid_amount'], 2)
 
 
 
 
 
 
 
 
5398
  if order['debt_amount'] <= 0:
5399
  order['is_debt'] = False
5400
  order['debt_amount'] = 0
5401
  order['paid_amount'] = order.get('total_price', 0)
5402
+
5403
+ if 'debt_history' not in data:
5404
+ data['debt_history'] = []
5405
 
5406
+ data['debt_history'].append({
5407
+ 'date': get_almaty_time(),
5408
+ 'order_id': order_id,
5409
+ 'customer_name': order.get('customer_name') or 'Касса',
5410
+ 'amount': amount,
5411
+ 'remaining_debt': order['debt_amount']
5412
+ })
5413
+
5414
  save_env_data(env_id, data)
5415
  flash(f'Оплата в размере {amount} успешно внесена для заказа №{order_id}', 'success')
5416
  return redirect(url_for('debts', env_id=env_id))
 
5428
  all_orders = list(data.get('orders', {}).values())
5429
  debt_orders = [o for o in all_orders if o.get('is_debt', False) and float(o.get('debt_amount', 0)) > 0]
5430
  debt_orders.sort(key=lambda x: x.get('created_at', ''), reverse=True)
5431
+
5432
+ debt_history = data.get('debt_history', [])
 
5433
 
5434
  return render_template_string(
5435
  DEBTS_TEMPLATE,
5436
  env_id=env_id,
5437
  debts=debt_orders,
5438
+ debt_history=debt_history,
5439
  currency=settings.get('currency', '₸')
5440
  )
5441
 
 
5678
  "box_price": p.get("box_price", ""),
5679
  "min_order": p.get("min_order", ""),
5680
  "has_variant_prices": p.get("has_variant_prices", False),
5681
+ "variants": p.get("variants", []),
5682
+ "created_at": p.get("created_at", get_almaty_time())
5683
  })
5684
 
5685
  json_str = json.dumps(export_data, ensure_ascii=False, indent=2)
 
5743
  elif action == 'clear_history':
5744
  data['orders'] = {}
5745
  data['inventory_history'] =[]
5746
+ data['debt_history'] = []
5747
  save_env_data(env_id, data)
5748
  flash('История продаж и заказов успешно очищена.', 'success')
5749
 
 
5787
  'box_price': p.get('box_price', ''),
5788
  'min_order': p.get('min_order', ''),
5789
  'has_variant_prices': p.get('has_variant_prices', False),
5790
+ 'variants': p.get('variants', []),
5791
+ 'created_at': p.get('created_at', get_almaty_time())
5792
  })
5793
  else:
5794
  new_p = {
 
5809
  'variants': p.get('variants', []),
5810
  'photos': p.get('photos', []),
5811
  'wholesale_tiers': p.get('wholesale_tiers', []),
5812
+ 'created_at': p.get('created_at', get_almaty_time())
5813
  }
5814
  data['products'].append(new_p)
5815