refactor: Добавить в_stock в API и улучшить загрузку данных в форме вариантов

Изменения в API:
- Добавить поле in_stock в возвращаемые данные товаров
- Добавить поддержку запроса товара по ID (параметр ?id=) для получения актуальных данных
- Исправить дублирование информации одного товара на остальные в таблице вариантов

Изменения в форме:
- Добавить автоматическую загрузку данных товара при загрузке страницы для существующих строк
- Правильно отображать артикул, цену и наличие для каждого товара в группе

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-10-30 00:03:40 +03:00
parent e821d881a9
commit dbb94e9d2a
2 changed files with 94 additions and 40 deletions

View File

@@ -61,37 +61,56 @@
<table class="table table-sm table-hover mb-0"> <table class="table table-sm table-hover mb-0">
<thead class="table-light"> <thead class="table-light">
<tr> <tr>
<th style="width: 50px;"></th> <th style="width: 40px; text-align: center;"></th>
<th>Товар</th> <th>Товар</th>
<th style="width: 100px;">Артикул</th> <th style="width: 110px;">Артикул</th>
<th style="width: 90px;">Цена</th> <th style="width: 100px;">Цена</th>
<th style="width: 100px;">В наличии</th> <th style="width: 110px;">В наличии</th>
<th style="width: 110px;">Действия</th> <th style="width: 150px; text-align: right;">Действия</th>
</tr> </tr>
</thead> </thead>
<tbody id="items-tbody"> <tbody id="items-tbody">
{% for item_form in items_formset %} {% for item_form in items_formset %}
<tr class="item-row" data-form-index="{{ forloop.counter0 }}"{% if item_form.DELETE.value %} style="display: none;"{% endif %}> <tr class="item-row" data-form-index="{{ forloop.counter0 }}"{% if item_form.DELETE.value %} style="display: none;"{% endif %}>
<td class="item-priority text-center fw-bold">{{ forloop.counter }}</td> <!-- Приоритет (номер) -->
<td> <td class="item-priority text-center fw-bold align-middle">{{ forloop.counter }}</td>
<!-- Выбор товара -->
<td class="align-middle">
{{ item_form.product }} {{ item_form.product }}
{% if item_form.product.errors %} {% if item_form.product.errors %}
<div class="text-danger small">{{ item_form.product.errors }}</div> <div class="text-danger small">{{ item_form.product.errors }}</div>
{% endif %} {% endif %}
</td> </td>
<td><small class="text-muted" data-product-sku="-">-</small></td>
<td><small class="text-muted" data-product-price="-">-</small></td> <!-- Артикул -->
<td><small class="text-muted" data-product-stock="-">-</small></td> <td class="align-middle">
<td class="text-end"> <small class="text-muted" data-product-sku="-">-</small>
<button type="button" class="btn btn-sm btn-outline-secondary move-up-btn me-1" title="Вверх"> </td>
<i class="bi bi-arrow-up"></i>
</button> <!-- Цена -->
<button type="button" class="btn btn-sm btn-outline-secondary move-down-btn me-1" title="Вниз"> <td class="align-middle">
<i class="bi bi-arrow-down"></i> <small class="text-muted" data-product-price="-">-</small>
</button> </td>
<button type="button" class="btn btn-sm btn-outline-danger delete-btn" title="Удалить">
<i class="bi bi-trash"></i> <!-- Статус наличия -->
</button> <td class="align-middle">
<small class="text-muted" data-product-stock="-">-</small>
</td>
<!-- Действия (стрелки + корзина) -->
<td class="align-middle" style="padding-right: 8px;">
<div class="btn-group btn-group-sm gap-1" role="group">
<button type="button" class="btn btn-outline-secondary move-up-btn" title="Переместить вверх">
<i class="bi bi-arrow-up"></i>
</button>
<button type="button" class="btn btn-outline-secondary move-down-btn" title="Переместить вниз">
<i class="bi bi-arrow-down"></i>
</button>
<button type="button" class="btn btn-outline-danger delete-btn" title="Удалить товар">
<i class="bi bi-trash"></i>
</button>
</div>
{{ item_form.priority }} {{ item_form.priority }}
{{ item_form.id }} {{ item_form.id }}
{{ item_form.DELETE }} {{ item_form.DELETE }}
@@ -207,7 +226,11 @@ document.addEventListener('DOMContentLoaded', function() {
} }
// Инициализируем для существующих строк // Инициализируем для существующих строк
container.querySelectorAll('.item-row').forEach(initSelect2ForRow); container.querySelectorAll('.item-row').forEach(row => {
initSelect2ForRow(row);
// Загружаем данные товара при загрузке страницы (с небольшой задержкой)
setTimeout(() => updateRowData(row), 100);
});
// ДОБАВЛЕНИЕ НОВОГО ТОВАРА // ДОБАВЛЕНИЕ НОВОГО ТОВАРА
document.getElementById('add-item-btn').addEventListener('click', function(e) { document.getElementById('add-item-btn').addEventListener('click', function(e) {
@@ -220,25 +243,33 @@ document.addEventListener('DOMContentLoaded', function() {
const newRow = document.createElement('tr'); const newRow = document.createElement('tr');
newRow.className = 'item-row'; newRow.className = 'item-row';
newRow.innerHTML = ` newRow.innerHTML = `
<td class="item-priority text-center fw-bold">${newFormIndex + 1}</td> <td class="item-priority text-center fw-bold align-middle">${newFormIndex + 1}</td>
<td> <td class="align-middle">
<select name="items-${newFormIndex}-product" id="items-${newFormIndex}-product" class="form-control form-control-sm"> <select name="items-${newFormIndex}-product" id="items-${newFormIndex}-product" class="form-control form-control-sm">
<option value="">---------</option> <option value="">---------</option>
</select> </select>
</td> </td>
<td><small class="text-muted" data-product-sku="-">-</small></td> <td class="align-middle">
<td><small class="text-muted" data-product-price="-">-</small></td> <small class="text-muted" data-product-sku="-">-</small>
<td><small class="text-muted" data-product-stock="-">-</small></td> </td>
<td class="text-end"> <td class="align-middle">
<button type="button" class="btn btn-sm btn-outline-secondary move-up-btn me-1" title="Вверх"> <small class="text-muted" data-product-price="-">-</small>
<i class="bi bi-arrow-up"></i> </td>
</button> <td class="align-middle">
<button type="button" class="btn btn-sm btn-outline-secondary move-down-btn me-1" title="Вниз"> <small class="text-muted" data-product-stock="-">-</small>
<i class="bi bi-arrow-down"></i> </td>
</button> <td class="align-middle" style="padding-right: 8px;">
<button type="button" class="btn btn-sm btn-outline-danger delete-btn" title="Удалить"> <div class="btn-group btn-group-sm gap-1" role="group">
<i class="bi bi-trash"></i> <button type="button" class="btn btn-outline-secondary move-up-btn" title="Переместить вверх">
</button> <i class="bi bi-arrow-up"></i>
</button>
<button type="button" class="btn btn-outline-secondary move-down-btn" title="Переместить вниз">
<i class="bi bi-arrow-down"></i>
</button>
<button type="button" class="btn btn-outline-danger delete-btn" title="Удалить товар">
<i class="bi bi-trash"></i>
</button>
</div>
<input type="hidden" name="items-${newFormIndex}-priority" value="${newFormIndex + 1}"> <input type="hidden" name="items-${newFormIndex}-priority" value="${newFormIndex + 1}">
<input type="hidden" name="items-${newFormIndex}-id" value=""> <input type="hidden" name="items-${newFormIndex}-id" value="">
<input type="checkbox" name="items-${newFormIndex}-DELETE"> <input type="checkbox" name="items-${newFormIndex}-DELETE">

View File

@@ -15,6 +15,7 @@ def search_products_and_variants(request):
Параметры GET: Параметры GET:
- q: строка поиска (term в Select2) - q: строка поиска (term в Select2)
- id: ID товара для получения его данных
- type: 'product' или 'variant' (опционально) - type: 'product' или 'variant' (опционально)
- page: номер страницы для пагинации (по умолчанию 1) - page: номер страницы для пагинации (по умолчанию 1)
@@ -25,7 +26,8 @@ def search_products_and_variants(request):
"id": 1, "id": 1,
"text": "Роза красная Freedom 50см (PROD-000001)", "text": "Роза красная Freedom 50см (PROD-000001)",
"sku": "PROD-000001", "sku": "PROD-000001",
"price": "150.00" "price": "150.00",
"in_stock": true
} }
], ],
"pagination": { "pagination": {
@@ -33,6 +35,25 @@ def search_products_and_variants(request):
} }
} }
""" """
# Если передан ID товара - получаем его данные напрямую
product_id = request.GET.get('id', '').strip()
if product_id:
try:
product = Product.objects.get(id=int(product_id), is_active=True)
return JsonResponse({
'results': [{
'id': product.id,
'text': f"{product.name} ({product.sku})" if product.sku else product.name,
'sku': product.sku,
'price': str(product.sale_price) if product.sale_price else None,
'in_stock': product.in_stock,
'type': 'product'
}],
'pagination': {'more': False}
})
except (Product.DoesNotExist, ValueError):
return JsonResponse({'results': [], 'pagination': {'more': False}})
query = request.GET.get('q', '').strip() query = request.GET.get('q', '').strip()
search_type = request.GET.get('type', 'all') search_type = request.GET.get('type', 'all')
page = int(request.GET.get('page', 1)) page = int(request.GET.get('page', 1))
@@ -53,7 +74,7 @@ def search_products_and_variants(request):
# Показываем последние добавленные активные товары # Показываем последние добавленные активные товары
products = Product.objects.filter(is_active=True)\ products = Product.objects.filter(is_active=True)\
.order_by('-created_at')[:page_size]\ .order_by('-created_at')[:page_size]\
.values('id', 'name', 'sku', 'sale_price') .values('id', 'name', 'sku', 'sale_price', 'in_stock')
for product in products: for product in products:
text = product['name'] text = product['name']
@@ -64,7 +85,8 @@ def search_products_and_variants(request):
'id': product['id'], 'id': product['id'],
'text': text, 'text': text,
'sku': product['sku'], 'sku': product['sku'],
'price': str(product['sale_price']) if product['sale_price'] else None 'price': str(product['sale_price']) if product['sale_price'] else None,
'in_stock': product['in_stock']
}) })
response_data = { response_data = {
@@ -125,7 +147,7 @@ def search_products_and_variants(request):
start = (page - 1) * page_size start = (page - 1) * page_size
end = start + page_size end = start + page_size
products = products_query[start:end].values('id', 'name', 'sku', 'sale_price') products = products_query[start:end].values('id', 'name', 'sku', 'sale_price', 'in_stock')
for product in products: for product in products:
text = product['name'] text = product['name']
@@ -137,6 +159,7 @@ def search_products_and_variants(request):
'text': text, 'text': text,
'sku': product['sku'], 'sku': product['sku'],
'price': str(product['sale_price']) if product['sale_price'] else None, 'price': str(product['sale_price']) if product['sale_price'] else None,
'in_stock': product['in_stock'],
'type': 'product' 'type': 'product'
}) })