Добавлено детальное логирование загрузки товаров в формсет
This commit is contained in:
@@ -2151,10 +2151,11 @@ if (!document.getElementById('notification-styles')) {
|
||||
console.log('[Order Items] Найдено элементов для инициализации:', items.length);
|
||||
|
||||
items.forEach((selectElement, index) => {
|
||||
console.log(`[Order Items] Инициализация элемента ${index + 1}/${items.length}`);
|
||||
console.log(`[Order Items] 📋 Инициализация элемента ${index + 1}/${items.length}`);
|
||||
|
||||
// Сначала инициализируем Select2
|
||||
window.initOrderItemSelect2(selectElement);
|
||||
console.log(`[Order Items] ✅ Select2 инициализирован для элемента ${index}`);
|
||||
|
||||
// Затем проверяем, есть ли предзаполненные данные в скрытых полях
|
||||
const form = selectElement.closest('.order-item-form');
|
||||
@@ -2162,36 +2163,68 @@ if (!document.getElementById('notification-styles')) {
|
||||
const kitField = form.querySelector('[name$="-product_kit"]');
|
||||
const priceField = form.querySelector('[name$="-price"]');
|
||||
|
||||
console.log(`[Order Items] 🔍 Форма ${index}:`);
|
||||
console.log(` - productField найдено:`, !!productField);
|
||||
console.log(` - productField.value:`, productField ? productField.value : 'N/A');
|
||||
console.log(` - kitField найдено:`, !!kitField);
|
||||
console.log(` - kitField.value:`, kitField ? kitField.value : 'N/A');
|
||||
console.log(` - priceField найдено:`, !!priceField);
|
||||
console.log(` - priceField.value:`, priceField ? priceField.value : 'N/A');
|
||||
|
||||
// Если есть предзаполненный product или kit, но select пустой
|
||||
const hasProduct = productField && productField.value;
|
||||
const hasKit = kitField && kitField.value;
|
||||
const selectValue = $(selectElement).val();
|
||||
|
||||
console.log(`[Order Items] 🎯 Проверка условий для формы ${index}:`);
|
||||
console.log(` - hasProduct:`, hasProduct);
|
||||
console.log(` - hasKit:`, hasKit);
|
||||
console.log(` - selectValue:`, selectValue);
|
||||
console.log(` - Нужна загрузка?`, (hasProduct || hasKit) && !selectValue);
|
||||
|
||||
if ((hasProduct || hasKit) && !selectValue) {
|
||||
console.log(`[Order Items] Найдены предзаполненные данные в форме ${index}`);
|
||||
console.log(`[Order Items] ⚡ НАЙДЕНЫ предзаполненные данные в форме ${index}!`);
|
||||
|
||||
// Определяем тип и ID
|
||||
const type = hasProduct ? 'product' : 'kit';
|
||||
const id = hasProduct ? productField.value : kitField.value;
|
||||
const price = priceField ? priceField.value : '';
|
||||
|
||||
console.log(`[Order Items] 📦 Загрузка товара:`);
|
||||
console.log(` - Тип: ${type}`);
|
||||
console.log(` - ID: ${id}`);
|
||||
console.log(` - Цена: ${price}`);
|
||||
|
||||
// Загружаем данные товара через API
|
||||
const apiUrl = '{% url "products:api-search-products-variants" %}';
|
||||
const requestId = `${type}_${id}`;
|
||||
|
||||
console.log(`[Order Items] 🌐 Отправка AJAX запроса:`);
|
||||
console.log(` - URL: ${apiUrl}`);
|
||||
console.log(` - ID параметр: ${requestId}`);
|
||||
|
||||
$.ajax({
|
||||
url: apiUrl,
|
||||
type: 'GET',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
id: `${type}_${id}` // Передаём в формате "product_123" или "kit_456"
|
||||
id: requestId
|
||||
},
|
||||
success: function(data) {
|
||||
console.log(`[Order Items] ✅ Ответ API получен для формы ${index}:`, data);
|
||||
|
||||
if (data.results && data.results.length > 0) {
|
||||
const item = data.results[0];
|
||||
console.log(`[Order Items] 📦 Данные товара:`, item);
|
||||
|
||||
// Создаём option с данными товара
|
||||
const optionValue = `${type}_${id}`;
|
||||
const optionText = item.text || item.name || 'Товар';
|
||||
|
||||
console.log(`[Order Items] ➕ Создание option:`);
|
||||
console.log(` - value: ${optionValue}`);
|
||||
console.log(` - text: ${optionText}`);
|
||||
|
||||
// Добавляем option в select
|
||||
const newOption = new Option(optionText, optionValue, true, true);
|
||||
$(selectElement).append(newOption).trigger('change');
|
||||
@@ -2199,15 +2232,23 @@ if (!document.getElementById('notification-styles')) {
|
||||
// Сохраняем оригинальную цену
|
||||
if (priceField && item.actual_price) {
|
||||
priceField.dataset.originalPrice = item.actual_price;
|
||||
console.log(`[Order Items] 💰 Оригинальная цена сохранена: ${item.actual_price}`);
|
||||
}
|
||||
|
||||
console.log(`[Order Items] Товар загружен: ${optionText}`);
|
||||
console.log(`[Order Items] 🎉 Товар успешно загружен: ${optionText}`);
|
||||
} else {
|
||||
console.warn(`[Order Items] ⚠️ API вернул пустой массив results`);
|
||||
}
|
||||
},
|
||||
error: function(xhr, status, error) {
|
||||
console.error(`[Order Items] Ошибка загрузки товара:`, error);
|
||||
console.error(`[Order Items] ❌ Ошибка AJAX запроса для формы ${index}:`);
|
||||
console.error(` - Status: ${status}`);
|
||||
console.error(` - Error: ${error}`);
|
||||
console.error(` - Response:`, xhr.responseText);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.log(`[Order Items] ⏭️ Форма ${index} пропущена (нет данных или select уже заполнен)`);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user