Kgshop commited on
Commit
c733ef7
·
verified ·
1 Parent(s): afb355c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +471 -72
app.py CHANGED
@@ -194,6 +194,7 @@ def get_env_data(env_id):
194
  "chat_avatar": None,
195
  "color_scheme": "default",
196
  "business_type": "retail",
 
197
  "welcome_message_enabled": False,
198
  "welcome_message_text": "Добро пожаловать в наш магазин!",
199
  "inventory_tracking": False,
@@ -369,7 +370,7 @@ ADMHOSTO_TEMPLATE = '''
369
  .container { max-width: 900px; margin: 0 auto; background-color: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.05); }
370
  h1 { font-weight: 600; color: var(--bg-medium); margin-bottom: 25px; text-align: center; }
371
  .section { margin-bottom: 30px; }
372
- .add-env-form { margin-bottom: 20px; text-align: center; }
373
  #search-env { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 1rem; font-family: 'Montserrat', sans-serif; min-height: 44px;}
374
  .button { padding: 10px 18px; border: none; border-radius: 8px; background-color: var(--accent); color: var(--text-on-accent); font-weight: 600; cursor: pointer; transition: background-color 0.3s ease; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; gap: 5px; min-height: 44px; }
375
  .button:hover { background-color: var(--accent-hover); }
@@ -384,6 +385,8 @@ ADMHOSTO_TEMPLATE = '''
384
  .message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; text-align: center; }
385
  .message.success { background-color: #d4edda; color: #155724; }
386
  .message.error { background-color: #f8d7da; color: #721c24; }
 
 
387
  </style>
388
  </head>
389
  <body>
@@ -398,6 +401,10 @@ ADMHOSTO_TEMPLATE = '''
398
  {% endwith %}
399
  <div class="section">
400
  <form method="POST" action="{{ url_for('create_environment') }}" class="add-env-form">
 
 
 
 
401
  <button type="submit" class="button"><i class="fas fa-plus-circle"></i> Создать новую среду</button>
402
  </form>
403
  </div>
@@ -411,7 +418,12 @@ ADMHOSTO_TEMPLATE = '''
411
  {% for env in environments %}
412
  <li class="env-item">
413
  <div class="env-header">
414
- <span class="env-id">{{ env.org_name }} (ID: {{ env.id }})</span>
 
 
 
 
 
415
  <div class="env-actions">
416
  <a href="{{ url_for('admin', env_id=env.id) }}" class="button" target="_blank"><i class="fas fa-tools"></i> Админ</a>
417
  <a href="{{ url_for('catalog', env_id=env.id) }}" class="button" target="_blank"><i class="fas fa-store"></i> Каталог</a>
@@ -643,7 +655,7 @@ CATALOG_TEMPLATE = '''
643
  </a>
644
  <div class="search-wrapper">
645
  <i class="fas fa-search"></i>
646
- <input type="text" id="search-input" placeholder="Поиск постов...">
647
  </div>
648
  </div>
649
 
@@ -835,7 +847,7 @@ CATALOG_TEMPLATE = '''
835
 
836
  function openModalById(productId) {
837
  const productIndex = getProductIndexById(productId);
838
- if (productIndex === -1) { alert("Ошибка: пост не найден."); return; }
839
  fetch(`/${envId}/track_view/${productId}`, {method: 'POST'}).catch(e=>{});
840
  loadProductDetails(productIndex);
841
  const modal = document.getElementById('productModal');
@@ -940,12 +952,17 @@ CATALOG_TEMPLATE = '''
940
  } else {
941
  unitSelector = `<div style="margin-top: 8px; font-size: 0.9rem; font-weight: 600; color: var(--accent);"><input type="hidden" name="unit_${tag.id}" value="piece"> ${tag.price}</div>`;
942
  }
 
 
 
 
 
943
 
944
  html += `
945
  <div id="tag-row-${tag.id}" style="display: flex; align-items: center; justify-content: space-between; padding: 15px 12px; border-bottom: 1px solid #eee; transition: background-color 0.3s; border-radius: 8px; flex-wrap: wrap; gap: 10px;">
946
  <div style="flex-grow: 1; min-width: 60%;">
947
  <div style="display:flex; align-items:center; flex-wrap:wrap; gap: 10px;">
948
- <strong style="font-size:1.05rem;">${tag.name}</strong>
949
  ${selectHtml}
950
  </div>
951
  ${unitSelector}
@@ -1010,7 +1027,7 @@ CATALOG_TEMPLATE = '''
1010
  if (itemIndex > -1) {
1011
  cart[itemIndex].quantity = newQty;
1012
  } else {
1013
- cart.push({ id: cartItemId, product_id: product.product_id, name: itemName, price: itemPrice, photo: photoUrl, quantity: newQty, color: colorCode, tag_x: tag.x, tag_y: tag.y, unit_type: unitType });
1014
  }
1015
  }
1016
  localStorage.setItem(`mekaCart_${envId}`, JSON.stringify(cart));
@@ -1048,14 +1065,24 @@ CATALOG_TEMPLATE = '''
1048
  if(checkoutFields) checkoutFields.style.display = 'none';
1049
  } else {
1050
  cartContent.innerHTML = cart.map(item => {
1051
- const itemTotal = item.price * item.quantity; total += itemTotal;
 
 
 
 
 
 
 
 
 
1052
  const photoUrl = item.photo ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` : 'https://via.placeholder.com/70x70.png?text=N/A';
1053
  return `
1054
  <div class="cart-item">
1055
  <img src="${photoUrl}" alt="${item.name}">
1056
  <div class="cart-item-details">
1057
  <strong>${item.name}</strong>
1058
- <p class="cart-item-price">${item.price.toFixed(2)} ${currencyCode}</p>
 
1059
  </div>
1060
  <div class="cart-item-quantity">
1061
  <button class="quantity-btn" onclick="decrementCartItem('${item.id}')">-</button>
@@ -1134,7 +1161,7 @@ CATALOG_TEMPLATE = '''
1134
  if (hasError) return;
1135
 
1136
  const empId = localStorage.getItem(`gippoEmp_${envId}`);
1137
- const orderData = { cart: cart, emp_id: empId, customer_data: customerData };
1138
  const formulateButton = document.querySelector('.formulate-order-button');
1139
  if (formulateButton) formulateButton.disabled = true;
1140
  showNotification("Формируем заказ...", 5000);
@@ -1296,6 +1323,9 @@ ORDER_TEMPLATE = '''
1296
  <div class="item-details">
1297
  <strong>{{ item.name }}</strong>
1298
  <span>{{ "%.2f"|format(item.price) }} {{ currency_code }}</span>
 
 
 
1299
  </div>
1300
  <div class="item-quantity-total">
1301
  <div class="item-quantity">
@@ -1474,7 +1504,8 @@ HISTORY_TEMPLATE = '''
1474
  <th onclick="sortTable(0)">ID Заказа <i class="fas fa-sort"></i></th>
1475
  <th onclick="sortTable(1)">Дата <i class="fas fa-sort"></i></th>
1476
  <th onclick="sortTable(2)">Сотрудник <i class="fas fa-sort"></i></th>
1477
- <th onclick="sortTable(3)">Сумма <i class="fas fa-sort"></i></th>
 
1478
  <th>Действия</th>
1479
  </tr>
1480
  </thead>
@@ -1484,6 +1515,7 @@ HISTORY_TEMPLATE = '''
1484
  <td><a href="{{ url_for('view_order', env_id=env_id, order_id=order.id) }}" class="order-link">{{ order.id }}</a></td>
1485
  <td>{{ order.created_at }}</td>
1486
  <td>{{ order.employee_name if order.employee_name else 'Прямой заказ' }}</td>
 
1487
  <td>{{ "%.2f"|format(order.total_price) }} {{ currency_code }}</td>
1488
  <td>
1489
  <a href="{{ url_for('view_order', env_id=env_id, order_id=order.id) }}" style="color: var(--bg-medium); margin-right: 15px; padding: 10px; display: inline-block;"><i class="fas fa-eye fa-lg"></i></a>
@@ -1521,7 +1553,7 @@ HISTORY_TEMPLATE = '''
1521
  shouldSwitch = false;
1522
  x = rows[i].getElementsByTagName("TD")[n]; y = rows[i + 1].getElementsByTagName("TD")[n];
1523
  let cmpX = x.innerText.toLowerCase(); let cmpY = y.innerText.toLowerCase();
1524
- if (n === 3) { cmpX = parseFloat(cmpX); cmpY = parseFloat(cmpY); }
1525
  if (dir == "asc") { if (cmpX > cmpY) { shouldSwitch = true; break; } } else if (dir == "desc") { if (cmpX < cmpY) { shouldSwitch = true; break; } }
1526
  }
1527
  if (shouldSwitch) { rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); switching = true; switchcount ++; }
@@ -1533,6 +1565,299 @@ HISTORY_TEMPLATE = '''
1533
  </html>
1534
  '''
1535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1536
  ADMIN_TEMPLATE = '''
1537
  <!DOCTYPE html>
1538
  <html lang="ru">
@@ -1584,9 +1909,6 @@ ADMIN_TEMPLATE = '''
1584
  details[open] > summary { border-bottom: 1px solid #e0e0e0; }
1585
  details .form-content { padding: 20px; }
1586
  .photo-preview img { max-width: 80px; max-height: 80px; border-radius: 8px; margin: 5px 5px 0 0; border: 1px solid #e0e0e0; object-fit: cover;}
1587
- .sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
1588
- .download-hf-button { background-color: #6c757d; color: white; }
1589
- .download-hf-button:hover { background-color: #5a6268; }
1590
 
1591
  .flex-container { display: flex; flex-wrap: wrap; gap: 20px; }
1592
  .flex-item { flex: 1; min-width: 100%; }
@@ -1674,6 +1996,9 @@ ADMIN_TEMPLATE = '''
1674
  </div>
1675
  <div style="display: flex; gap: 10px; flex-wrap: wrap;">
1676
  <a href="{{ url_for('history_page', env_id=env_id) }}" class="button btn-history"><i class="fas fa-history"></i> История продаж</a>
 
 
 
1677
  <a href="{{ url_for('catalog', env_id=env_id) }}" class="button" style="background-color: var(--bg-medium); color: white;"><i class="fas fa-store"></i> Каталог</a>
1678
  {% if settings.admin_password_enabled %}
1679
  <a href="{{ url_for('admin_logout', env_id=env_id) }}" class="button" style="background-color: #6c757d; color: white;"><i class="fas fa-sign-out-alt"></i> Выход</a>
@@ -1689,18 +2014,6 @@ ADMIN_TEMPLATE = '''
1689
  {% endif %}
1690
  {% endwith %}
1691
 
1692
- <div class="section">
1693
- <h2><i class="fas fa-sync-alt"></i> Синхронизация с Датацентром</h2>
1694
- <div class="sync-buttons">
1695
- <form method="POST" action="{{ url_for('force_upload', env_id=env_id, p=page, q=search_q) }}" style="display: inline;" onsubmit="return confirm('Вы уверены, что хотите принудительно загрузить локальные данные на сервер? Это перезапишет данные на сервере.'); showLoadingOverlay();">
1696
- <button type="submit" class="button add-button"><i class="fas fa-upload"></i> Загрузить БД</button>
1697
- </form>
1698
- <form method="POST" action="{{ url_for('force_download', env_id=env_id, p=page, q=search_q) }}" style="display: inline;" onsubmit="return confirm('Вы уверены, что хотите принудительно скачать данные с сервера? Это перезапишет ваши локальные файлы.'); showLoadingOverlay();">
1699
- <button type="submit" class="button download-hf-button"><i class="fas fa-download"></i> Скачать БД</button>
1700
- </form>
1701
- </div>
1702
- </div>
1703
-
1704
  <div class="section">
1705
  <h2><i class="fas fa-users"></i> Сотрудники (Менеджеры)</h2>
1706
  <details>
@@ -1722,7 +2035,10 @@ ADMIN_TEMPLATE = '''
1722
  <div class="item" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
1723
  <div><strong style="font-size: 1.1rem;">{{ emp.name }}</strong><br><span style="font-size: 0.95rem; color: #666;">{{ emp.whatsapp }}</span></div>
1724
  <div style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
1725
- <button type="button" class="button" style="background-color: #6c757d; font-size: 0.9rem;" onclick="copyEmpLink('{{ request.host_url }}{{ env_id }}/catalog?emp={{ emp.id }}')"><i class="fas fa-copy"></i> Копировать ссылку</button>
 
 
 
1726
  <form method="POST" action="{{ url_for('admin', env_id=env_id, p=page, q=search_q) }}" style="margin: 0;" onsubmit="return confirm('Удалить сотрудника?');">
1727
  <input type="hidden" name="action" value="delete_employee">
1728
  <input type="hidden" name="emp_id" value="{{ emp.id }}">
@@ -1817,7 +2133,7 @@ ADMIN_TEMPLATE = '''
1817
  <input type="text" name="admin_password" value="{{ settings.admin_password }}" placeholder="Текущий пароль">
1818
  </div>
1819
 
1820
- <label for="organization_name">Название организации (или поста):</label>
1821
  <input type="text" id="organization_name" name="organization_name" value="{{ settings.organization_name }}">
1822
 
1823
  <label for="whatsapp_number">Номер WhatsApp для заказов (по умолчанию):</label>
@@ -1830,6 +2146,12 @@ ADMIN_TEMPLATE = '''
1830
  {% endfor %}
1831
  </select>
1832
 
 
 
 
 
 
 
1833
  <label for="business_type">Тип бизнеса:</label>
1834
  <select id="business_type" name="business_type">
1835
  <option value="retail" {% if settings.business_type == 'retail' %}selected{% endif %}>Розничный</option>
@@ -1925,13 +2247,13 @@ ADMIN_TEMPLATE = '''
1925
  </div>
1926
 
1927
  <div class="section">
1928
- <h2><i class="fas fa-box-open"></i> Управление постами</h2>
1929
  <details>
1930
- <summary><i class="fas fa-plus-circle"></i> Добавить новый пост</summary>
1931
  <div class="form-content">
1932
  <form id="add-product-form" method="POST" action="{{ url_for('admin', env_id=env_id, p=page, q=search_q) }}" enctype="multipart/form-data" onsubmit="showLoadingOverlay()">
1933
  <input type="hidden" name="action" value="add_product">
1934
- <label>Название поста/образа *:</label>
1935
  <input type="text" name="name" required>
1936
 
1937
  <label>Фотографии (до 10 шт.):</label>
@@ -1973,14 +2295,14 @@ ADMIN_TEMPLATE = '''
1973
  <input type="checkbox" id="add_is_top" name="is_top"><label for="add_is_top" class="inline-label" style="margin: 0;">Топ товар</label>
1974
  </div>
1975
  <br>
1976
- <button type="submit" class="add-button" style="margin-top: 25px;"><i class="fas fa-save"></i> Добавить пост</button>
1977
  </form>
1978
  </div>
1979
  </details>
1980
 
1981
- <h3 style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; margin-top: 30px;">Список постов:</h3>
1982
  <form method="GET" action="{{ url_for('admin', env_id=env_id) }}" style="margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap;">
1983
- <input type="text" name="q" value="{{ search_q }}" placeholder="Поиск по постам..." style="flex-grow: 1; margin: 0;">
1984
  <button type="submit" class="button" style="margin: 0;"><i class="fas fa-search"></i> Поиск</button>
1985
  {% if search_q %}
1986
  <a href="{{ url_for('admin', env_id=env_id) }}" class="button" style="background-color: #6c757d; margin: 0; justify-content: center;"><i class="fas fa-times"></i> Сброс</a>
@@ -2030,7 +2352,7 @@ ADMIN_TEMPLATE = '''
2030
 
2031
  <div class="item-actions">
2032
  <button type="button" class="button" onclick="toggleEditForm('edit-form-{{ loop.index0 }}', {{ loop.index0 }})"><i class="fas fa-edit"></i> Редактировать</button>
2033
- <form method="POST" action="{{ url_for('admin', env_id=env_id, p=page, q=search_q) }}" style="margin:0;" onsubmit="return confirm('Удалить пост?'); showLoadingOverlay();">
2034
  <input type="hidden" name="action" value="delete_product">
2035
  <input type="hidden" name="product_id" value="{{ product.get('product_id', '') }}">
2036
  <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button>
@@ -2107,7 +2429,7 @@ ADMIN_TEMPLATE = '''
2107
  {% endif %}
2108
 
2109
  {% else %}
2110
- <p style="font-size: 1.1rem; text-align: center; padding: 40px;">Постов пока нет или по вашему запросу ничего не найдено.</p>
2111
  {% endif %}
2112
  </div>
2113
  </div>
@@ -2135,6 +2457,7 @@ ADMIN_TEMPLATE = '''
2135
  const allProductsForAdmin = {{ paginated_products|tojson|safe }};
2136
  const repoId = '{{ repo_id }}';
2137
  const bType = '{{ settings.business_type }}';
 
2138
  const formStates = {};
2139
  let adminAiHistory = [];
2140
 
@@ -2258,6 +2581,12 @@ ADMIN_TEMPLATE = '''
2258
 
2259
  const variants = prompt("Варианты через запятую (например: S, M, L). Оставьте пустым, если нет:");
2260
 
 
 
 
 
 
 
2261
  formStates[scope].tags.push({
2262
  id: Math.random().toString(36).substr(2, 9),
2263
  photo_index: formStates[scope].currentIdx,
@@ -2267,7 +2596,8 @@ ADMIN_TEMPLATE = '''
2267
  price: price,
2268
  box_qty: boxQty,
2269
  box_price: boxPrice,
2270
- variants: variants || ""
 
2271
  });
2272
 
2273
  updateHiddenTags(scope);
@@ -2310,8 +2640,9 @@ ADMIN_TEMPLATE = '''
2310
  listItem.className = 'tag-list-item';
2311
  let varText = tag.variants ? ` [Вар: ${tag.variants}]` : '';
2312
  let boxText = (bType === 'wholesale' || bType === 'combined') ? ` [Упак: ${tag.box_qty}шт за ${tag.box_price}]` : '';
 
2313
  listItem.innerHTML = `
2314
- <span>[Фото ${tag.photo_index + 1}] ${tag.name} (Шт: ${tag.price})${boxText}${varText}</span>
2315
  <button type="button" class="delete-button" style="padding: 5px 10px; font-size: 0.9rem; margin:0;" onclick="removeTag('${scope}', '${tag.id}')"><i class="fas fa-times"></i></button>
2316
  `;
2317
  listContainer.appendChild(listItem);
@@ -2439,9 +2770,11 @@ def admhosto():
2439
  for env_id, env_data in data.items():
2440
  settings = env_data.get('settings', {})
2441
  org_name = settings.get("organization_name", "Gippo312")
 
2442
  environments_data.append({
2443
  "id": env_id,
2444
  "org_name": org_name,
 
2445
  "pwd_enabled": settings.get("admin_password_enabled", False),
2446
  "password": settings.get("admin_password", "")
2447
  })
@@ -2451,6 +2784,7 @@ def admhosto():
2451
  @app.route('/admhosto/create', methods=['POST'])
2452
  def create_environment():
2453
  all_data = load_data()
 
2454
  while True:
2455
  new_id = ''.join(random.choices(string.digits, k=6))
2456
  if new_id not in all_data:
@@ -2467,7 +2801,7 @@ def create_environment():
2467
  "organization_name": "Gippo312", "whatsapp_number": "+996701202013",
2468
  "currency_code": "KGS", "chat_name": "EVA", "chat_avatar": None,
2469
  "color_scheme": "default",
2470
- "business_type": "retail", "welcome_message_enabled": False, "welcome_message_text": "Добро пожаловать в наш магазин!",
2471
  "inventory_tracking": False, "admin_password_enabled": False, "admin_password": "",
2472
  "checkout_fields_enabled": False, "checkout_fields": {"name": False, "phone": False, "city": False, "address": False, "zip": False}
2473
  }
@@ -2548,6 +2882,59 @@ def catalog(env_id):
2548
  settings=settings, chat_avatar_url=chat_avatar_url, env_id=env_id, blocks=blocks
2549
  )
2550
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2551
  @app.route('/<env_id>/track_view/<product_id>', methods=['POST'])
2552
  def track_view(env_id, product_id):
2553
  data = get_env_data(env_id)
@@ -2583,10 +2970,12 @@ def create_order(env_id):
2583
  data = get_env_data(env_id)
2584
  settings = data.get('settings', {})
2585
  products = data.get('products', [])
 
2586
 
2587
  cart_items = order_data['cart']
2588
  customer_data = order_data.get('customer_data', {})
2589
  emp_id = order_data.get('emp_id')
 
2590
  emp_name = None
2591
  emp_whatsapp = None
2592
 
@@ -2602,13 +2991,12 @@ def create_order(env_id):
2602
  processed_cart = []
2603
 
2604
  for item in cart_items:
2605
- if not all(k in item for k in ('name', 'price', 'quantity')):
2606
  return jsonify({"error": "Неверный формат товара в корзине."}), 400
2607
  try:
2608
- price = float(item['price'])
2609
  quantity = int(item['quantity'])
2610
- if price < 0 or quantity <= 0:
2611
- raise ValueError("Invalid price or quantity")
2612
 
2613
  p_id = item.get('product_id')
2614
  c_color = item.get('color', 'N/A')
@@ -2616,13 +3004,46 @@ def create_order(env_id):
2616
  ty = item.get('tag_y')
2617
  u_type = item.get('unit_type', 'piece')
2618
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2619
  processed_cart.append({
2620
  "product_id": p_id, "name": item['name'], "price": price, "quantity": quantity,
2621
  "color": c_color, "photo": item.get('photo'), "tag_x": tx, "tag_y": ty, "unit_type": u_type,
 
2622
  "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item['photo']}" if item.get('photo') else "https://via.placeholder.com/60x60.png?text=N/A"
2623
  })
2624
  total_price += price * quantity
2625
- except (ValueError, TypeError):
2626
  return jsonify({"error": "Неверная цена или количество в товаре."}), 400
2627
 
2628
  order_id = f"{datetime.now(ALMATY_TZ).strftime('%Y%m%d%H%M%S')}-{uuid4().hex[:6]}"
@@ -2632,7 +3053,7 @@ def create_order(env_id):
2632
  "id": order_id, "created_at": order_timestamp, "cart": processed_cart,
2633
  "total_price": round(total_price, 2), "status": "new",
2634
  "employee_id": emp_id, "employee_name": emp_name, "employee_whatsapp": emp_whatsapp,
2635
- "customer_data": customer_data
2636
  }
2637
 
2638
  try:
@@ -2902,6 +3323,7 @@ def admin(env_id):
2902
  settings['organization_name'] = request.form.get('organization_name', 'Gippo312').strip()
2903
  settings['whatsapp_number'] = request.form.get('whatsapp_number', '').strip()
2904
  settings['currency_code'] = request.form.get('currency_code', 'KGS')
 
2905
  settings['business_type'] = request.form.get('business_type', 'retail')
2906
  settings['color_scheme'] = request.form.get('color_scheme', 'default')
2907
 
@@ -3010,11 +3432,11 @@ def admin(env_id):
3010
  product_index = next((i for i, p in enumerate(products) if p.get('product_id') == product_id), -1)
3011
  if product_index != -1:
3012
  products[product_index] = product_data
3013
- flash(f"Пост '{product_data['name']}' обновлен.", 'success')
3014
  else:
3015
  product_data['product_id'] = uuid4().hex
3016
  products.append(product_data)
3017
- flash(f"Пост '{product_data['name']}' добавлен.", 'success')
3018
 
3019
  data['products'] = products
3020
  save_env_data(env_id, data)
@@ -3023,7 +3445,7 @@ def admin(env_id):
3023
  product_id = request.form.get('product_id')
3024
  product_index = next((i for i, p in enumerate(products) if p.get('product_id') == product_id), -1)
3025
  if product_index == -1:
3026
- flash(f"Ошибка удаления: пост не найден.", 'error')
3027
  return redirect(url_for('admin', env_id=env_id, p=page, q=search_q))
3028
  deleted_product = products.pop(product_index)
3029
  product_name = deleted_product.get('name', 'N/A')
@@ -3035,7 +3457,7 @@ def admin(env_id):
3035
  except Exception: pass
3036
  data['products'] = products
3037
  save_env_data(env_id, data)
3038
- flash(f"Пост '{product_name}' удален.", 'success')
3039
  else:
3040
  flash(f"Неизвестное действие: {action}", 'warning')
3041
  return redirect(url_for('admin', env_id=env_id, p=page, q=search_q))
@@ -3043,7 +3465,6 @@ def admin(env_id):
3043
  flash(f"Ошибка при выполнении действия.", 'error')
3044
  return redirect(url_for('admin', env_id=env_id, p=page, q=search_q))
3045
 
3046
- # Pagination & Search Filtering
3047
  filtered_products = products
3048
  if search_q:
3049
  q_lower = search_q.lower()
@@ -3088,28 +3509,6 @@ def handle_generate_description_ai():
3088
  except ValueError as ve: return jsonify({"error": str(ve)}), 400
3089
  except Exception as e: return jsonify({"error": f"Внутренняя ошибка сервера: {e}"}), 500
3090
 
3091
- @app.route('/<env_id>/force_upload', methods=['POST'])
3092
- def force_upload(env_id):
3093
- page = request.args.get('p', 1, type=int)
3094
- search_q = request.args.get('q', '')
3095
- try:
3096
- upload_db_to_hf()
3097
- flash("Данные успешно загружены на Hugging Face.", 'success')
3098
- except Exception as e:
3099
- flash(f"Ошибка при загрузке: {e}", 'error')
3100
- return redirect(url_for('admin', env_id=env_id, p=page, q=search_q))
3101
-
3102
- @app.route('/<env_id>/force_download', methods=['POST'])
3103
- def force_download(env_id):
3104
- page = request.args.get('p', 1, type=int)
3105
- search_q = request.args.get('q', '')
3106
- try:
3107
- if download_db_from_hf(): flash("Данные успешно скачаны. Локальные файлы обновлены.", 'success')
3108
- else: flash("Не удалось скачать данные.", 'error')
3109
- except Exception as e:
3110
- flash(f"Ошибка при скачивании: {e}", 'error')
3111
- return redirect(url_for('admin', env_id=env_id, p=page, q=search_q))
3112
-
3113
  if __name__ == '__main__':
3114
  configure_gemini()
3115
  download_db_from_hf()
 
194
  "chat_avatar": None,
195
  "color_scheme": "default",
196
  "business_type": "retail",
197
+ "env_mode": "external",
198
  "welcome_message_enabled": False,
199
  "welcome_message_text": "Добро пожаловать в наш магазин!",
200
  "inventory_tracking": False,
 
370
  .container { max-width: 900px; margin: 0 auto; background-color: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.05); }
371
  h1 { font-weight: 600; color: var(--bg-medium); margin-bottom: 25px; text-align: center; }
372
  .section { margin-bottom: 30px; }
373
+ .add-env-form { margin-bottom: 20px; text-align: center; display: flex; gap: 10px; justify-content: center; align-items: center;}
374
  #search-env { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 1rem; font-family: 'Montserrat', sans-serif; min-height: 44px;}
375
  .button { padding: 10px 18px; border: none; border-radius: 8px; background-color: var(--accent); color: var(--text-on-accent); font-weight: 600; cursor: pointer; transition: background-color 0.3s ease; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; gap: 5px; min-height: 44px; }
376
  .button:hover { background-color: var(--accent-hover); }
 
385
  .message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; text-align: center; }
386
  .message.success { background-color: #d4edda; color: #155724; }
387
  .message.error { background-color: #f8d7da; color: #721c24; }
388
+ .mode-badge { padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; font-weight: bold; background: #eee; }
389
+ .mode-2in1 { background: #ffeb3b; color: #333; }
390
  </style>
391
  </head>
392
  <body>
 
401
  {% endwith %}
402
  <div class="section">
403
  <form method="POST" action="{{ url_for('create_environment') }}" class="add-env-form">
404
+ <select name="env_mode" style="padding: 10px; border-radius: 8px; border: 1px solid #ccc; font-family: inherit;">
405
+ <option value="external">Внешняя цифровизация (по умолчанию)</option>
406
+ <option value="2in1">2 в 1 (Склад и Касса)</option>
407
+ </select>
408
  <button type="submit" class="button"><i class="fas fa-plus-circle"></i> Создать новую среду</button>
409
  </form>
410
  </div>
 
418
  {% for env in environments %}
419
  <li class="env-item">
420
  <div class="env-header">
421
+ <span class="env-id">
422
+ {{ env.org_name }} (ID: {{ env.id }})
423
+ <span class="mode-badge {% if env.mode == '2in1' %}mode-2in1{% endif %}">
424
+ {{ '2 в 1' if env.mode == '2in1' else 'Внешняя цифр.' }}
425
+ </span>
426
+ </span>
427
  <div class="env-actions">
428
  <a href="{{ url_for('admin', env_id=env.id) }}" class="button" target="_blank"><i class="fas fa-tools"></i> Админ</a>
429
  <a href="{{ url_for('catalog', env_id=env.id) }}" class="button" target="_blank"><i class="fas fa-store"></i> Каталог</a>
 
655
  </a>
656
  <div class="search-wrapper">
657
  <i class="fas fa-search"></i>
658
+ <input type="text" id="search-input" placeholder="Поиск товаров...">
659
  </div>
660
  </div>
661
 
 
847
 
848
  function openModalById(productId) {
849
  const productIndex = getProductIndexById(productId);
850
+ if (productIndex === -1) { alert("Ошибка: товар не найден."); return; }
851
  fetch(`/${envId}/track_view/${productId}`, {method: 'POST'}).catch(e=>{});
852
  loadProductDetails(productIndex);
853
  const modal = document.getElementById('productModal');
 
952
  } else {
953
  unitSelector = `<div style="margin-top: 8px; font-size: 0.9rem; font-weight: 600; color: var(--accent);"><input type="hidden" name="unit_${tag.id}" value="piece"> ${tag.price}</div>`;
954
  }
955
+
956
+ let stockBadge = "";
957
+ if (tag.stock !== undefined) {
958
+ stockBadge = `<span style="font-size: 0.8rem; background: #eee; padding: 2px 6px; border-radius: 4px; margin-left: 10px; color: #555;">Остаток: ${tag.stock}</span>`;
959
+ }
960
 
961
  html += `
962
  <div id="tag-row-${tag.id}" style="display: flex; align-items: center; justify-content: space-between; padding: 15px 12px; border-bottom: 1px solid #eee; transition: background-color 0.3s; border-radius: 8px; flex-wrap: wrap; gap: 10px;">
963
  <div style="flex-grow: 1; min-width: 60%;">
964
  <div style="display:flex; align-items:center; flex-wrap:wrap; gap: 10px;">
965
+ <strong style="font-size:1.05rem;">${tag.name}</strong>${stockBadge}
966
  ${selectHtml}
967
  </div>
968
  ${unitSelector}
 
1027
  if (itemIndex > -1) {
1028
  cart[itemIndex].quantity = newQty;
1029
  } else {
1030
+ cart.push({ id: cartItemId, product_id: product.product_id, name: itemName, price: itemPrice, photo: photoUrl, quantity: newQty, color: colorCode, tag_x: tag.x, tag_y: tag.y, unit_type: unitType, box_qty: tag.box_qty, box_price: tag.box_price, orig_price: tag.price });
1031
  }
1032
  }
1033
  localStorage.setItem(`mekaCart_${envId}`, JSON.stringify(cart));
 
1065
  if(checkoutFields) checkoutFields.style.display = 'none';
1066
  } else {
1067
  cartContent.innerHTML = cart.map(item => {
1068
+ let effPrice = item.price;
1069
+ if (item.unit_type === 'piece' && item.box_qty > 1 && item.quantity >= item.box_qty) {
1070
+ effPrice = item.box_price / item.box_qty;
1071
+ }
1072
+ const itemTotal = effPrice * item.quantity;
1073
+ total += itemTotal;
1074
+
1075
+ let discountBadge = (effPrice < item.orig_price && item.unit_type === 'piece')
1076
+ ? `<span style="color:var(--danger); font-size: 0.8rem; display:block;">Оптовая цена прим.</span>` : '';
1077
+
1078
  const photoUrl = item.photo ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` : 'https://via.placeholder.com/70x70.png?text=N/A';
1079
  return `
1080
  <div class="cart-item">
1081
  <img src="${photoUrl}" alt="${item.name}">
1082
  <div class="cart-item-details">
1083
  <strong>${item.name}</strong>
1084
+ <p class="cart-item-price">${effPrice.toFixed(2)} ${currencyCode}</p>
1085
+ ${discountBadge}
1086
  </div>
1087
  <div class="cart-item-quantity">
1088
  <button class="quantity-btn" onclick="decrementCartItem('${item.id}')">-</button>
 
1161
  if (hasError) return;
1162
 
1163
  const empId = localStorage.getItem(`gippoEmp_${envId}`);
1164
+ const orderData = { cart: cart, emp_id: empId, customer_data: customerData, source: 'catalog' };
1165
  const formulateButton = document.querySelector('.formulate-order-button');
1166
  if (formulateButton) formulateButton.disabled = true;
1167
  showNotification("Формируем заказ...", 5000);
 
1323
  <div class="item-details">
1324
  <strong>{{ item.name }}</strong>
1325
  <span>{{ "%.2f"|format(item.price) }} {{ currency_code }}</span>
1326
+ {% if item.discount_applied %}
1327
+ <span style="color:var(--danger); font-size:0.8rem;">(Оптовая цена)</span>
1328
+ {% endif %}
1329
  </div>
1330
  <div class="item-quantity-total">
1331
  <div class="item-quantity">
 
1504
  <th onclick="sortTable(0)">ID Заказа <i class="fas fa-sort"></i></th>
1505
  <th onclick="sortTable(1)">Дата <i class="fas fa-sort"></i></th>
1506
  <th onclick="sortTable(2)">Сотрудник <i class="fas fa-sort"></i></th>
1507
+ <th onclick="sortTable(3)">Источник <i class="fas fa-sort"></i></th>
1508
+ <th onclick="sortTable(4)">Сумма <i class="fas fa-sort"></i></th>
1509
  <th>Действия</th>
1510
  </tr>
1511
  </thead>
 
1515
  <td><a href="{{ url_for('view_order', env_id=env_id, order_id=order.id) }}" class="order-link">{{ order.id }}</a></td>
1516
  <td>{{ order.created_at }}</td>
1517
  <td>{{ order.employee_name if order.employee_name else 'Прямой заказ' }}</td>
1518
+ <td>{{ 'Касса (POS)' if order.source == 'pos' else 'Каталог' }}</td>
1519
  <td>{{ "%.2f"|format(order.total_price) }} {{ currency_code }}</td>
1520
  <td>
1521
  <a href="{{ url_for('view_order', env_id=env_id, order_id=order.id) }}" style="color: var(--bg-medium); margin-right: 15px; padding: 10px; display: inline-block;"><i class="fas fa-eye fa-lg"></i></a>
 
1553
  shouldSwitch = false;
1554
  x = rows[i].getElementsByTagName("TD")[n]; y = rows[i + 1].getElementsByTagName("TD")[n];
1555
  let cmpX = x.innerText.toLowerCase(); let cmpY = y.innerText.toLowerCase();
1556
+ if (n === 4) { cmpX = parseFloat(cmpX); cmpY = parseFloat(cmpY); }
1557
  if (dir == "asc") { if (cmpX > cmpY) { shouldSwitch = true; break; } } else if (dir == "desc") { if (cmpX < cmpY) { shouldSwitch = true; break; } }
1558
  }
1559
  if (shouldSwitch) { rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); switching = true; switchcount ++; }
 
1565
  </html>
1566
  '''
1567
 
1568
+ POS_TEMPLATE = '''
1569
+ <!DOCTYPE html>
1570
+ <html lang="ru">
1571
+ <head>
1572
+ <meta charset="UTF-8">
1573
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1574
+ <title>POS Касса - {{ settings.organization_name }}</title>
1575
+ <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700&display=swap" rel="stylesheet">
1576
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
1577
+ <style>
1578
+ * { box-sizing: border-box; margin: 0; padding: 0; }
1579
+ body { font-family: 'Montserrat', sans-serif; background-color: #f4f6f9; color: #333; height: 100vh; display: flex; overflow: hidden;}
1580
+
1581
+ .products-section { flex: 2; display: flex; flex-direction: column; background: #fff; border-right: 1px solid #e0e0e0; }
1582
+ .top-bar { padding: 15px; background: #135D66; color: white; display: flex; gap: 15px; align-items: center; }
1583
+ .search-input { flex-grow: 1; padding: 12px; border-radius: 8px; border: none; font-size: 1rem; outline: none; }
1584
+ .products-grid { flex: 1; overflow-y: auto; padding: 15px; display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; align-content: start; }
1585
+ .product-card { border: 1px solid #e0e0e0; border-radius: 8px; overflow: hidden; cursor: pointer; transition: transform 0.1s; background: #fafafa; display: flex; flex-direction: column; }
1586
+ .product-card:active { transform: scale(0.98); }
1587
+ .product-card img { width: 100%; height: 120px; object-fit: cover; }
1588
+ .product-info { padding: 10px; font-size: 0.9rem; flex-grow: 1; display: flex; flex-direction: column; justify-content: space-between;}
1589
+ .product-name { font-weight: 600; margin-bottom: 5px; }
1590
+ .product-price { color: #135D66; font-weight: bold; }
1591
+ .product-stock { font-size: 0.8rem; color: #666; margin-top: 5px; }
1592
+
1593
+ .cart-section { flex: 1; min-width: 350px; max-width: 450px; background: #fdfdff; display: flex; flex-direction: column; }
1594
+ .cart-header { padding: 20px; background: #fff; border-bottom: 1px solid #e0e0e0; font-size: 1.2rem; font-weight: bold; color: #135D66; text-align: center; }
1595
+ .cart-items { flex: 1; overflow-y: auto; padding: 15px; }
1596
+ .cart-item { display: flex; justify-content: space-between; align-items: center; padding: 15px; background: #fff; border: 1px solid #eee; border-radius: 8px; margin-bottom: 10px; }
1597
+ .cart-item-details { flex-grow: 1; }
1598
+ .cart-item-name { font-weight: 600; font-size: 0.95rem; margin-bottom: 5px; }
1599
+ .cart-item-price { font-size: 0.9rem; color: #666; }
1600
+ .cart-controls { display: flex; align-items: center; gap: 10px; }
1601
+ .qty-btn { width: 30px; height: 30px; background: #eee; border: none; border-radius: 4px; font-weight: bold; cursor: pointer; }
1602
+ .qty-input { width: 40px; text-align: center; border: 1px solid #ccc; border-radius: 4px; padding: 4px; }
1603
+
1604
+ .checkout-panel { padding: 20px; background: #fff; border-top: 1px solid #e0e0e0; }
1605
+ .total-row { display: flex; justify-content: space-between; font-size: 1.4rem; font-weight: bold; color: #135D66; margin-bottom: 15px; }
1606
+ .input-group { margin-bottom: 15px; }
1607
+ .input-group label { display: block; font-size: 0.9rem; margin-bottom: 5px; color: #555; }
1608
+ .input-group input { width: 100%; padding: 12px; border: 1px solid #ccc; border-radius: 8px; font-size: 1rem; }
1609
+ .btn-checkout { width: 100%; padding: 15px; background: #48D1CC; color: #003C43; border: none; border-radius: 8px; font-size: 1.1rem; font-weight: bold; cursor: pointer; transition: background 0.2s; }
1610
+ .btn-checkout:hover { background: #77E4D8; }
1611
+ .btn-clear { width: 100%; padding: 10px; background: #eee; color: #555; border: none; border-radius: 8px; font-size: 0.9rem; cursor: pointer; margin-bottom: 10px; }
1612
+
1613
+ @media (max-width: 768px) {
1614
+ body { flex-direction: column; }
1615
+ .products-section { flex: 1; }
1616
+ .cart-section { flex: 1; max-width: 100%; border-top: 2px solid #135D66; }
1617
+ }
1618
+ </style>
1619
+ </head>
1620
+ <body>
1621
+ <div class="products-section">
1622
+ <div class="top-bar">
1623
+ <h2 style="margin:0; font-size: 1.2rem;">POS</h2>
1624
+ <input type="text" class="search-input" id="search-input" placeholder="Поиск товаров..." oninput="renderProducts()">
1625
+ </div>
1626
+ <div class="products-grid" id="products-grid"></div>
1627
+ </div>
1628
+
1629
+ <div class="cart-section">
1630
+ <div class="cart-header">Текущий заказ</div>
1631
+ <div class="cart-items" id="cart-items"></div>
1632
+ <div class="checkout-panel">
1633
+ <button class="btn-clear" onclick="clearCart()">Очистить корзину</button>
1634
+ <div class="total-row">
1635
+ <span>Итого:</span>
1636
+ <span id="cart-total">0.00 {{ currency_code }}</span>
1637
+ </div>
1638
+ <div class="input-group">
1639
+ <label>Номер WhatsApp клиента (для отправки чека):</label>
1640
+ <input type="tel" id="client-phone" placeholder="+996...">
1641
+ </div>
1642
+ <button class="btn-checkout" onclick="checkout()">Оформить заказ</button>
1643
+ </div>
1644
+ </div>
1645
+
1646
+ <script>
1647
+ const allProducts = {{ products_json|safe }};
1648
+ const envId = '{{ env_id }}';
1649
+ const empId = '{{ emp_id }}';
1650
+ const currencyCode = '{{ currency_code }}';
1651
+ const repoId = '{{ repo_id }}';
1652
+ let cart = [];
1653
+
1654
+ function renderProducts() {
1655
+ const query = document.getElementById('search-input').value.toLowerCase();
1656
+ const grid = document.getElementById('products-grid');
1657
+ let html = '';
1658
+
1659
+ allProducts.forEach(p => {
1660
+ if(query && !p.name.toLowerCase().includes(query)) return;
1661
+
1662
+ // For POS, we show variants directly if possible, or just the main product click
1663
+ p.tags.forEach(tag => {
1664
+ if(query && !tag.name.toLowerCase().includes(query) && !p.name.toLowerCase().includes(query)) return;
1665
+
1666
+ const photoUrl = p.photos && p.photos[tag.photo_index]
1667
+ ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${p.photos[tag.photo_index]}`
1668
+ : 'https://via.placeholder.com/150';
1669
+
1670
+ const stockText = tag.stock !== undefined ? `Остаток: ${tag.stock}` : 'В наличии';
1671
+
1672
+ // JSON escape for onClick
1673
+ const tagData = JSON.stringify({
1674
+ id: tag.id, pid: p.product_id, name: `${p.name} (${tag.name})`,
1675
+ price: tag.price, box_price: tag.box_price, box_qty: tag.box_qty, photo: p.photos ? p.photos[tag.photo_index] : null
1676
+ }).replace(/"/g, '&quot;');
1677
+
1678
+ html += `
1679
+ <div class="product-card" onclick="addToCart(${tagData})">
1680
+ <img src="${photoUrl}" alt="${tag.name}">
1681
+ <div class="product-info">
1682
+ <div class="product-name">${p.name}<br><small>${tag.name}</small></div>
1683
+ <div class="product-price">${tag.price} ${currencyCode}</div>
1684
+ <div class="product-stock">${stockText}</div>
1685
+ </div>
1686
+ </div>
1687
+ `;
1688
+ });
1689
+ });
1690
+ grid.innerHTML = html;
1691
+ }
1692
+
1693
+ function addToCart(data) {
1694
+ const existing = cart.find(i => i.id === data.id);
1695
+ if(existing) {
1696
+ existing.quantity++;
1697
+ } else {
1698
+ cart.push({
1699
+ id: data.id, product_id: data.pid, name: data.name,
1700
+ price: data.price, orig_price: data.price, box_price: data.box_price,
1701
+ box_qty: data.box_qty || 1, quantity: 1, unit_type: 'piece', photo: data.photo
1702
+ });
1703
+ }
1704
+ renderCart();
1705
+ }
1706
+
1707
+ function updateQty(id, delta) {
1708
+ const item = cart.find(i => i.id === id);
1709
+ if(item) {
1710
+ item.quantity += delta;
1711
+ if(item.quantity <= 0) cart = cart.filter(i => i.id !== id);
1712
+ renderCart();
1713
+ }
1714
+ }
1715
+
1716
+ function clearCart() {
1717
+ if(confirm('Очистить?')) { cart = []; renderCart(); }
1718
+ }
1719
+
1720
+ function renderCart() {
1721
+ const container = document.getElementById('cart-items');
1722
+ let html = '';
1723
+ let total = 0;
1724
+
1725
+ cart.forEach(item => {
1726
+ let effPrice = item.orig_price;
1727
+ if (item.box_qty > 1 && item.quantity >= item.box_qty) {
1728
+ effPrice = item.box_price / item.box_qty;
1729
+ }
1730
+ item.price = effPrice; // update for checkout
1731
+ const itemTotal = effPrice * item.quantity;
1732
+ total += itemTotal;
1733
+
1734
+ html += `
1735
+ <div class="cart-item">
1736
+ <div class="cart-item-details">
1737
+ <div class="cart-item-name">${item.name}</div>
1738
+ <div class="cart-item-price">${effPrice.toFixed(2)} x ${item.quantity} = <strong>${itemTotal.toFixed(2)}</strong></div>
1739
+ </div>
1740
+ <div class="cart-controls">
1741
+ <button class="qty-btn" onclick="updateQty('${item.id}', -1)">-</button>
1742
+ <span style="width: 20px; text-align:center;">${item.quantity}</span>
1743
+ <button class="qty-btn" onclick="updateQty('${item.id}', 1)">+</button>
1744
+ </div>
1745
+ </div>
1746
+ `;
1747
+ });
1748
+ container.innerHTML = html;
1749
+ document.getElementById('cart-total').textContent = total.toFixed(2) + ' ' + currencyCode;
1750
+ }
1751
+
1752
+ function checkout() {
1753
+ if(cart.length === 0) return alert('Корзина пуста');
1754
+ const phone = document.getElementById('client-phone').value.trim();
1755
+
1756
+ const orderData = {
1757
+ cart: cart,
1758
+ emp_id: empId,
1759
+ customer_data: { phone: phone },
1760
+ source: 'pos'
1761
+ };
1762
+
1763
+ fetch(`/${envId}/create_order`, {
1764
+ method: 'POST', headers: {'Content-Type': 'application/json'},
1765
+ body: JSON.stringify(orderData)
1766
+ }).then(r => r.json()).then(data => {
1767
+ if(data.order_id) {
1768
+ if(phone) {
1769
+ const url = `${window.location.origin}/${envId}/order/${data.order_id}`;
1770
+ const msg = `Ваш чек на покупку: ${url}`;
1771
+ window.open(`https://api.whatsapp.com/send?phone=${phone.replace(/\D/g,'')}&text=${encodeURIComponent(msg)}`, '_blank');
1772
+ }
1773
+ cart = [];
1774
+ renderCart();
1775
+ alert('Заказ успешно создан!');
1776
+ location.reload();
1777
+ }
1778
+ }).catch(e => alert('Ошибка'));
1779
+ }
1780
+
1781
+ renderProducts();
1782
+ </script>
1783
+ </body>
1784
+ </html>
1785
+ '''
1786
+
1787
+ REPORTS_TEMPLATE = '''
1788
+ <!DOCTYPE html>
1789
+ <html lang="ru">
1790
+ <head>
1791
+ <meta charset="UTF-8">
1792
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1793
+ <title>Отчеты - {{ settings.organization_name }}</title>
1794
+ <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600&display=swap" rel="stylesheet">
1795
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
1796
+ <style>
1797
+ body { font-family: 'Montserrat', sans-serif; background: #f4f6f9; color: #333; padding: 20px; margin: 0; }
1798
+ .container { max-width: 1000px; margin: 0 auto; background: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
1799
+ h1 { color: #135D66; margin-bottom: 20px; }
1800
+ .summary-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 30px; }
1801
+ .card { background: #e0f2f1; padding: 20px; border-radius: 8px; text-align: center; border: 1px solid #b2dfdb; }
1802
+ .card h3 { margin: 0 0 10px 0; font-size: 1rem; color: #004D40; }
1803
+ .card .value { font-size: 1.5rem; font-weight: bold; color: #135D66; }
1804
+ table { width: 100%; border-collapse: collapse; margin-bottom: 30px; }
1805
+ th, td { padding: 12px; border-bottom: 1px solid #eee; text-align: left; }
1806
+ th { background: #f8f9fa; color: #135D66; }
1807
+ .btn-back { display: inline-flex; align-items: center; gap: 8px; margin-bottom: 20px; color: #135D66; text-decoration: none; font-weight: 600; }
1808
+ </style>
1809
+ </head>
1810
+ <body>
1811
+ <div class="container">
1812
+ <a href="{{ url_for('admin', env_id=env_id) }}" class="btn-back"><i class="fas fa-arrow-left"></i> Назад в админ-панель</a>
1813
+ <h1><i class="fas fa-chart-pie"></i> Отчеты (Режим 2 в 1)</h1>
1814
+
1815
+ <div class="summary-cards">
1816
+ <div class="card">
1817
+ <h3>Всего заказов</h3>
1818
+ <div class="value">{{ total_orders }}</div>
1819
+ </div>
1820
+ <div class="card">
1821
+ <h3>Общая выручка</h3>
1822
+ <div class="value">{{ "%.2f"|format(total_revenue) }} {{ currency_code }}</div>
1823
+ </div>
1824
+ <div class="card">
1825
+ <h3>Заказы с кассы (POS)</h3>
1826
+ <div class="value">{{ pos_orders }}</div>
1827
+ </div>
1828
+ <div class="card">
1829
+ <h3>Онлайн заказы</h3>
1830
+ <div class="value">{{ online_orders }}</div>
1831
+ </div>
1832
+ </div>
1833
+
1834
+ <h2><i class="fas fa-users"></i> Продажи по сотрудникам</h2>
1835
+ <table>
1836
+ <tr><th>Сотрудник</th><th>Кол-во заказов</th><th>Выручка</th></tr>
1837
+ {% for emp, data in emp_stats.items() %}
1838
+ <tr>
1839
+ <td>{{ emp }}</td>
1840
+ <td>{{ data.count }}</td>
1841
+ <td>{{ "%.2f"|format(data.revenue) }} {{ currency_code }}</td>
1842
+ </tr>
1843
+ {% endfor %}
1844
+ </table>
1845
+
1846
+ <h2><i class="fas fa-box"></i> Топ продаваемых товаров</h2>
1847
+ <table>
1848
+ <tr><th>Название товара</th><th>Продано шт.</th></tr>
1849
+ {% for item in top_products %}
1850
+ <tr>
1851
+ <td>{{ item.name }}</td>
1852
+ <td>{{ item.qty }}</td>
1853
+ </tr>
1854
+ {% endfor %}
1855
+ </table>
1856
+ </div>
1857
+ </body>
1858
+ </html>
1859
+ '''
1860
+
1861
  ADMIN_TEMPLATE = '''
1862
  <!DOCTYPE html>
1863
  <html lang="ru">
 
1909
  details[open] > summary { border-bottom: 1px solid #e0e0e0; }
1910
  details .form-content { padding: 20px; }
1911
  .photo-preview img { max-width: 80px; max-height: 80px; border-radius: 8px; margin: 5px 5px 0 0; border: 1px solid #e0e0e0; object-fit: cover;}
 
 
 
1912
 
1913
  .flex-container { display: flex; flex-wrap: wrap; gap: 20px; }
1914
  .flex-item { flex: 1; min-width: 100%; }
 
1996
  </div>
1997
  <div style="display: flex; gap: 10px; flex-wrap: wrap;">
1998
  <a href="{{ url_for('history_page', env_id=env_id) }}" class="button btn-history"><i class="fas fa-history"></i> История продаж</a>
1999
+ {% if settings.env_mode == '2in1' %}
2000
+ <a href="{{ url_for('reports_page', env_id=env_id) }}" class="button" style="background-color: #f39c12; color: white;"><i class="fas fa-chart-pie"></i> Отчеты</a>
2001
+ {% endif %}
2002
  <a href="{{ url_for('catalog', env_id=env_id) }}" class="button" style="background-color: var(--bg-medium); color: white;"><i class="fas fa-store"></i> Каталог</a>
2003
  {% if settings.admin_password_enabled %}
2004
  <a href="{{ url_for('admin_logout', env_id=env_id) }}" class="button" style="background-color: #6c757d; color: white;"><i class="fas fa-sign-out-alt"></i> Выход</a>
 
2014
  {% endif %}
2015
  {% endwith %}
2016
 
 
 
 
 
 
 
 
 
 
 
 
 
2017
  <div class="section">
2018
  <h2><i class="fas fa-users"></i> Сотрудники (Менеджеры)</h2>
2019
  <details>
 
2035
  <div class="item" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
2036
  <div><strong style="font-size: 1.1rem;">{{ emp.name }}</strong><br><span style="font-size: 0.95rem; color: #666;">{{ emp.whatsapp }}</span></div>
2037
  <div style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
2038
+ <button type="button" class="button" style="background-color: #6c757d; font-size: 0.9rem;" onclick="copyEmpLink('{{ request.host_url }}{{ env_id }}/catalog?emp={{ emp.id }}')"><i class="fas fa-copy"></i> Ссылка менеджера</button>
2039
+ {% if settings.env_mode == '2in1' %}
2040
+ <a href="{{ url_for('pos_page', env_id=env_id) }}?emp={{ emp.id }}" class="button" style="background-color: #28a745; font-size: 0.9rem;" target="_blank"><i class="fas fa-desktop"></i> Ссылка на кассу</a>
2041
+ {% endif %}
2042
  <form method="POST" action="{{ url_for('admin', env_id=env_id, p=page, q=search_q) }}" style="margin: 0;" onsubmit="return confirm('Удалить сотрудника?');">
2043
  <input type="hidden" name="action" value="delete_employee">
2044
  <input type="hidden" name="emp_id" value="{{ emp.id }}">
 
2133
  <input type="text" name="admin_password" value="{{ settings.admin_password }}" placeholder="Текущий пароль">
2134
  </div>
2135
 
2136
+ <label for="organization_name">Название организации (магазина):</label>
2137
  <input type="text" id="organization_name" name="organization_name" value="{{ settings.organization_name }}">
2138
 
2139
  <label for="whatsapp_number">Номер WhatsApp для заказов (по умолчанию):</label>
 
2146
  {% endfor %}
2147
  </select>
2148
 
2149
+ <label for="env_mode">Режим работы среды:</label>
2150
+ <select id="env_mode" name="env_mode" style="background-color: #fff3cd; font-weight: bold;">
2151
+ <option value="external" {% if settings.env_mode == 'external' %}selected{% endif %}>Внешняя цифровизация</option>
2152
+ <option value="2in1" {% if settings.env_mode == '2in1' %}selected{% endif %}>2 в 1 (Склад и Касса)</option>
2153
+ </select>
2154
+
2155
  <label for="business_type">Тип бизнеса:</label>
2156
  <select id="business_type" name="business_type">
2157
  <option value="retail" {% if settings.business_type == 'retail' %}selected{% endif %}>Розничный</option>
 
2247
  </div>
2248
 
2249
  <div class="section">
2250
+ <h2><i class="fas fa-box-open"></i> Управление товарами</h2>
2251
  <details>
2252
+ <summary><i class="fas fa-plus-circle"></i> Добавить новый товар</summary>
2253
  <div class="form-content">
2254
  <form id="add-product-form" method="POST" action="{{ url_for('admin', env_id=env_id, p=page, q=search_q) }}" enctype="multipart/form-data" onsubmit="showLoadingOverlay()">
2255
  <input type="hidden" name="action" value="add_product">
2256
+ <label>Название товара *:</label>
2257
  <input type="text" name="name" required>
2258
 
2259
  <label>Фотографии (до 10 шт.):</label>
 
2295
  <input type="checkbox" id="add_is_top" name="is_top"><label for="add_is_top" class="inline-label" style="margin: 0;">Топ товар</label>
2296
  </div>
2297
  <br>
2298
+ <button type="submit" class="add-button" style="margin-top: 25px;"><i class="fas fa-save"></i> Добавить товар</button>
2299
  </form>
2300
  </div>
2301
  </details>
2302
 
2303
+ <h3 style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; margin-top: 30px;">Список товаров:</h3>
2304
  <form method="GET" action="{{ url_for('admin', env_id=env_id) }}" style="margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap;">
2305
+ <input type="text" name="q" value="{{ search_q }}" placeholder="Поиск по товарам..." style="flex-grow: 1; margin: 0;">
2306
  <button type="submit" class="button" style="margin: 0;"><i class="fas fa-search"></i> Поиск</button>
2307
  {% if search_q %}
2308
  <a href="{{ url_for('admin', env_id=env_id) }}" class="button" style="background-color: #6c757d; margin: 0; justify-content: center;"><i class="fas fa-times"></i> Сброс</a>
 
2352
 
2353
  <div class="item-actions">
2354
  <button type="button" class="button" onclick="toggleEditForm('edit-form-{{ loop.index0 }}', {{ loop.index0 }})"><i class="fas fa-edit"></i> Редактировать</button>
2355
+ <form method="POST" action="{{ url_for('admin', env_id=env_id, p=page, q=search_q) }}" style="margin:0;" onsubmit="return confirm('Удалить товар?'); showLoadingOverlay();">
2356
  <input type="hidden" name="action" value="delete_product">
2357
  <input type="hidden" name="product_id" value="{{ product.get('product_id', '') }}">
2358
  <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button>
 
2429
  {% endif %}
2430
 
2431
  {% else %}
2432
+ <p style="font-size: 1.1rem; text-align: center; padding: 40px;">Товаров пока нет или по вашему запросу ничего не найдено.</p>
2433
  {% endif %}
2434
  </div>
2435
  </div>
 
2457
  const allProductsForAdmin = {{ paginated_products|tojson|safe }};
2458
  const repoId = '{{ repo_id }}';
2459
  const bType = '{{ settings.business_type }}';
2460
+ const envMode = '{{ settings.env_mode }}';
2461
  const formStates = {};
2462
  let adminAiHistory = [];
2463
 
 
2581
 
2582
  const variants = prompt("Варианты через запятую (например: S, M, L). Оставьте пустым, если нет:");
2583
 
2584
+ let stock = null;
2585
+ if (envMode === '2in1') {
2586
+ const stockStr = prompt("Остаток на складе (в шт):", "0");
2587
+ stock = parseInt(stockStr) || 0;
2588
+ }
2589
+
2590
  formStates[scope].tags.push({
2591
  id: Math.random().toString(36).substr(2, 9),
2592
  photo_index: formStates[scope].currentIdx,
 
2596
  price: price,
2597
  box_qty: boxQty,
2598
  box_price: boxPrice,
2599
+ variants: variants || "",
2600
+ stock: stock
2601
  });
2602
 
2603
  updateHiddenTags(scope);
 
2640
  listItem.className = 'tag-list-item';
2641
  let varText = tag.variants ? ` [Вар: ${tag.variants}]` : '';
2642
  let boxText = (bType === 'wholesale' || bType === 'combined') ? ` [Упак: ${tag.box_qty}шт за ${tag.box_price}]` : '';
2643
+ let stockText = tag.stock !== null && tag.stock !== undefined ? ` [Остаток: ${tag.stock}]` : '';
2644
  listItem.innerHTML = `
2645
+ <span>[Фото ${tag.photo_index + 1}] ${tag.name} (Шт: ${tag.price})${boxText}${varText}${stockText}</span>
2646
  <button type="button" class="delete-button" style="padding: 5px 10px; font-size: 0.9rem; margin:0;" onclick="removeTag('${scope}', '${tag.id}')"><i class="fas fa-times"></i></button>
2647
  `;
2648
  listContainer.appendChild(listItem);
 
2770
  for env_id, env_data in data.items():
2771
  settings = env_data.get('settings', {})
2772
  org_name = settings.get("organization_name", "Gippo312")
2773
+ env_mode = settings.get("env_mode", "external")
2774
  environments_data.append({
2775
  "id": env_id,
2776
  "org_name": org_name,
2777
+ "mode": env_mode,
2778
  "pwd_enabled": settings.get("admin_password_enabled", False),
2779
  "password": settings.get("admin_password", "")
2780
  })
 
2784
  @app.route('/admhosto/create', methods=['POST'])
2785
  def create_environment():
2786
  all_data = load_data()
2787
+ env_mode = request.form.get('env_mode', 'external')
2788
  while True:
2789
  new_id = ''.join(random.choices(string.digits, k=6))
2790
  if new_id not in all_data:
 
2801
  "organization_name": "Gippo312", "whatsapp_number": "+996701202013",
2802
  "currency_code": "KGS", "chat_name": "EVA", "chat_avatar": None,
2803
  "color_scheme": "default",
2804
+ "business_type": "retail", "env_mode": env_mode, "welcome_message_enabled": False, "welcome_message_text": "Добро пожаловать в наш магазин!",
2805
  "inventory_tracking": False, "admin_password_enabled": False, "admin_password": "",
2806
  "checkout_fields_enabled": False, "checkout_fields": {"name": False, "phone": False, "city": False, "address": False, "zip": False}
2807
  }
 
2882
  settings=settings, chat_avatar_url=chat_avatar_url, env_id=env_id, blocks=blocks
2883
  )
2884
 
2885
+ @app.route('/<env_id>/pos')
2886
+ def pos_page(env_id):
2887
+ data = get_env_data(env_id)
2888
+ settings = data.get('settings', {})
2889
+ if settings.get('env_mode') != '2in1':
2890
+ return "POS доступен только в режиме '2 в 1'", 403
2891
+ emp_id = request.args.get('emp', '')
2892
+ products = data.get('products', [])
2893
+ return render_template_string(POS_TEMPLATE, products_json=json.dumps(products), settings=settings, currency_code=settings.get('currency_code', 'KGS'), env_id=env_id, emp_id=emp_id, repo_id=REPO_ID)
2894
+
2895
+ @app.route('/<env_id>/reports')
2896
+ def reports_page(env_id):
2897
+ data = get_env_data(env_id)
2898
+ settings = data.get('settings', {})
2899
+ if settings.get('env_mode') != '2in1':
2900
+ return "Отчеты доступны только в режиме '2 в 1'", 403
2901
+ if settings.get('admin_password_enabled') and not session.get(f'admin_auth_{env_id}'):
2902
+ return redirect(url_for('admin_login', env_id=env_id))
2903
+
2904
+ orders = data.get('orders', {}).values()
2905
+
2906
+ total_orders = len(orders)
2907
+ total_revenue = sum(o.get('total_price', 0) for o in orders)
2908
+ pos_orders = sum(1 for o in orders if o.get('source') == 'pos')
2909
+ online_orders = total_orders - pos_orders
2910
+
2911
+ emp_stats = {}
2912
+ product_sales = {}
2913
+
2914
+ for o in orders:
2915
+ emp = o.get('employee_name') or 'Прямой заказ'
2916
+ if emp not in emp_stats:
2917
+ emp_stats[emp] = {'count': 0, 'revenue': 0}
2918
+ emp_stats[emp]['count'] += 1
2919
+ emp_stats[emp]['revenue'] += o.get('total_price', 0)
2920
+
2921
+ for item in o.get('cart', []):
2922
+ name = item.get('name', 'Неизвестно')
2923
+ qty = item.get('quantity', 0)
2924
+ if name not in product_sales:
2925
+ product_sales[name] = 0
2926
+ product_sales[name] += qty
2927
+
2928
+ top_products = [{'name': k, 'qty': v} for k, v in product_sales.items()]
2929
+ top_products.sort(key=lambda x: x['qty'], reverse=True)
2930
+
2931
+ return render_template_string(
2932
+ REPORTS_TEMPLATE, env_id=env_id, settings=settings, currency_code=settings.get('currency_code', 'KGS'),
2933
+ total_orders=total_orders, total_revenue=total_revenue, pos_orders=pos_orders, online_orders=online_orders,
2934
+ emp_stats=emp_stats, top_products=top_products[:20]
2935
+ )
2936
+
2937
+
2938
  @app.route('/<env_id>/track_view/<product_id>', methods=['POST'])
2939
  def track_view(env_id, product_id):
2940
  data = get_env_data(env_id)
 
2970
  data = get_env_data(env_id)
2971
  settings = data.get('settings', {})
2972
  products = data.get('products', [])
2973
+ env_mode = settings.get('env_mode', 'external')
2974
 
2975
  cart_items = order_data['cart']
2976
  customer_data = order_data.get('customer_data', {})
2977
  emp_id = order_data.get('emp_id')
2978
+ source = order_data.get('source', 'catalog')
2979
  emp_name = None
2980
  emp_whatsapp = None
2981
 
 
2991
  processed_cart = []
2992
 
2993
  for item in cart_items:
2994
+ if not all(k in item for k in ('name', 'quantity')):
2995
  return jsonify({"error": "Неверный формат товара в корзине."}), 400
2996
  try:
 
2997
  quantity = int(item['quantity'])
2998
+ if quantity <= 0:
2999
+ raise ValueError("Invalid quantity")
3000
 
3001
  p_id = item.get('product_id')
3002
  c_color = item.get('color', 'N/A')
 
3004
  ty = item.get('tag_y')
3005
  u_type = item.get('unit_type', 'piece')
3006
 
3007
+ product_ref = next((p for p in products if p.get('product_id') == p_id), None)
3008
+ if not product_ref:
3009
+ return jsonify({"error": f"Товар {p_id} не найден."}), 400
3010
+
3011
+ tag_ref = None
3012
+ if 'TAG_' in c_color:
3013
+ tag_id = c_color.split('_VAR_')[0].replace('TAG_', '')
3014
+ tag_ref = next((t for t in product_ref.get('tags', []) if t.get('id') == tag_id), None)
3015
+
3016
+ price = float(item.get('price', 0))
3017
+ discount_applied = False
3018
+
3019
+ if tag_ref:
3020
+ orig_price = float(tag_ref.get('price', 0))
3021
+ box_price = float(tag_ref.get('box_price', orig_price))
3022
+ box_qty = int(tag_ref.get('box_qty', 1))
3023
+
3024
+ if u_type == 'piece' and box_qty > 1 and quantity >= box_qty:
3025
+ price = box_price / box_qty
3026
+ discount_applied = True
3027
+ elif u_type == 'box':
3028
+ price = box_price
3029
+ else:
3030
+ price = orig_price
3031
+
3032
+ if env_mode == '2in1':
3033
+ deduction = quantity
3034
+ if u_type == 'box':
3035
+ deduction = quantity * box_qty
3036
+ if tag_ref.get('stock') is not None:
3037
+ tag_ref['stock'] = max(0, int(tag_ref['stock']) - deduction)
3038
+
3039
  processed_cart.append({
3040
  "product_id": p_id, "name": item['name'], "price": price, "quantity": quantity,
3041
  "color": c_color, "photo": item.get('photo'), "tag_x": tx, "tag_y": ty, "unit_type": u_type,
3042
+ "discount_applied": discount_applied,
3043
  "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item['photo']}" if item.get('photo') else "https://via.placeholder.com/60x60.png?text=N/A"
3044
  })
3045
  total_price += price * quantity
3046
+ except (ValueError, TypeError) as e:
3047
  return jsonify({"error": "Неверная цена или количество в товаре."}), 400
3048
 
3049
  order_id = f"{datetime.now(ALMATY_TZ).strftime('%Y%m%d%H%M%S')}-{uuid4().hex[:6]}"
 
3053
  "id": order_id, "created_at": order_timestamp, "cart": processed_cart,
3054
  "total_price": round(total_price, 2), "status": "new",
3055
  "employee_id": emp_id, "employee_name": emp_name, "employee_whatsapp": emp_whatsapp,
3056
+ "customer_data": customer_data, "source": source
3057
  }
3058
 
3059
  try:
 
3323
  settings['organization_name'] = request.form.get('organization_name', 'Gippo312').strip()
3324
  settings['whatsapp_number'] = request.form.get('whatsapp_number', '').strip()
3325
  settings['currency_code'] = request.form.get('currency_code', 'KGS')
3326
+ settings['env_mode'] = request.form.get('env_mode', 'external')
3327
  settings['business_type'] = request.form.get('business_type', 'retail')
3328
  settings['color_scheme'] = request.form.get('color_scheme', 'default')
3329
 
 
3432
  product_index = next((i for i, p in enumerate(products) if p.get('product_id') == product_id), -1)
3433
  if product_index != -1:
3434
  products[product_index] = product_data
3435
+ flash(f"Товар '{product_data['name']}' обновлен.", 'success')
3436
  else:
3437
  product_data['product_id'] = uuid4().hex
3438
  products.append(product_data)
3439
+ flash(f"Товар '{product_data['name']}' добавлен.", 'success')
3440
 
3441
  data['products'] = products
3442
  save_env_data(env_id, data)
 
3445
  product_id = request.form.get('product_id')
3446
  product_index = next((i for i, p in enumerate(products) if p.get('product_id') == product_id), -1)
3447
  if product_index == -1:
3448
+ flash(f"Ошибка удаления: товар не найден.", 'error')
3449
  return redirect(url_for('admin', env_id=env_id, p=page, q=search_q))
3450
  deleted_product = products.pop(product_index)
3451
  product_name = deleted_product.get('name', 'N/A')
 
3457
  except Exception: pass
3458
  data['products'] = products
3459
  save_env_data(env_id, data)
3460
+ flash(f"Товар '{product_name}' удален.", 'success')
3461
  else:
3462
  flash(f"Неизвестное действие: {action}", 'warning')
3463
  return redirect(url_for('admin', env_id=env_id, p=page, q=search_q))
 
3465
  flash(f"Ошибка при выполнении действия.", 'error')
3466
  return redirect(url_for('admin', env_id=env_id, p=page, q=search_q))
3467
 
 
3468
  filtered_products = products
3469
  if search_q:
3470
  q_lower = search_q.lower()
 
3509
  except ValueError as ve: return jsonify({"error": str(ve)}), 400
3510
  except Exception as e: return jsonify({"error": f"Внутренняя ошибка сервера: {e}"}), 500
3511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3512
  if __name__ == '__main__':
3513
  configure_gemini()
3514
  download_db_from_hf()