Переместить определение openCreateCustomerModal в начало скрипта
Проблема: Функция openCreateCustomerModal была определена в конце скрипта, что делало её недоступной при вызове из обработчика клика. Решение: Переместить определение функции после initCustomerSelect2(), но ДО её вызова. Это гарантирует доступность функции. Результат: Модаль создания клиента теперь открывается корректно при клике! 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -561,7 +561,7 @@ function initCustomerSelect2() {
|
|||||||
// Очищаем значение
|
// Очищаем значение
|
||||||
$customerSelect.val(null).trigger('change.select2');
|
$customerSelect.val(null).trigger('change.select2');
|
||||||
// Открываем модаль
|
// Открываем модаль
|
||||||
openCreateCustomerModal(data.search_text);
|
window.openCreateCustomerModal(data.search_text);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -580,19 +580,17 @@ function initCustomerSelect2() {
|
|||||||
console.log('9_option. Ближайший option:', target);
|
console.log('9_option. Ближайший option:', target);
|
||||||
if (!target) return;
|
if (!target) return;
|
||||||
|
|
||||||
// Проверяем содержит ли элемент класс customer-create-option
|
// Проверяем текст опции - если это "Создать клиента", открываем модаль
|
||||||
const createOptionDiv = target.querySelector('.customer-create-option');
|
const optionText = target.textContent.trim();
|
||||||
console.log('9_create. create option найден:', !!createOptionDiv);
|
console.log('9_text. Текст опции:', optionText);
|
||||||
if (createOptionDiv) {
|
|
||||||
|
if (optionText.startsWith('Создать клиента:')) {
|
||||||
console.log('9c. Клик на create option напрямую');
|
console.log('9c. Клик на create option напрямую');
|
||||||
// Получаем текст опции
|
|
||||||
const fullText = target.textContent.trim();
|
|
||||||
console.log('9_text. Полный текст:', fullText);
|
|
||||||
// Извлекаем поисковый текст (удаляем "Создать клиента: ")
|
// Извлекаем поисковый текст (удаляем "Создать клиента: ")
|
||||||
const searchText = fullText.replace(/^\s*[\s\S]+?:\s*"([^"]*)"\s*$/, '$1') || fullText;
|
const searchText = optionText.replace(/^Создать\s+клиента:\s*"([^"]*)"\s*$/, '$1') || optionText;
|
||||||
|
|
||||||
console.log('9d. Открываем модаль с текстом:', searchText);
|
console.log('9d. Открываем модаль с текстом:', searchText);
|
||||||
openCreateCustomerModal(searchText);
|
window.openCreateCustomerModal(searchText);
|
||||||
|
|
||||||
// Закрываем dropdown
|
// Закрываем dropdown
|
||||||
$customerSelect.select2('close');
|
$customerSelect.select2('close');
|
||||||
@@ -615,7 +613,7 @@ function initCustomerSelect2() {
|
|||||||
// Триггерим нативное change событие для draft-creator.js
|
// Триггерим нативное change событие для draft-creator.js
|
||||||
const changeEvent = new Event('change', { bubbles: true });
|
const changeEvent = new Event('change', { bubbles: true });
|
||||||
this.dispatchEvent(changeEvent);
|
this.dispatchEvent(changeEvent);
|
||||||
openCreateCustomerModal(data.search_text);
|
window.openCreateCustomerModal(data.search_text);
|
||||||
} else {
|
} else {
|
||||||
// Триггерим нативное change событие для других обработчиков (например, draft-creator.js)
|
// Триггерим нативное change событие для других обработчиков (например, draft-creator.js)
|
||||||
console.log('12. Триггерим нативное change событие');
|
console.log('12. Триггерим нативное change событие');
|
||||||
@@ -659,6 +657,46 @@ function initCustomerSelect2() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// === СОЗДАНИЕ НОВОГО КЛИЕНТА ===
|
||||||
|
// Функция открытия модального окна создания клиента (определяем ДО инициализации Select2)
|
||||||
|
window.openCreateCustomerModal = function(searchText = '') {
|
||||||
|
// Заполняем форму предложенными данными
|
||||||
|
if (searchText) {
|
||||||
|
// Пытаемся распознать введенные данные
|
||||||
|
const phoneRegex = /[\d\s\-\+\(\)]+/;
|
||||||
|
const emailRegex = /[^\s@]+@[^\s@]+\.[^\s@]+/;
|
||||||
|
|
||||||
|
// Ищем email и телефон в строке поиска
|
||||||
|
const emailMatch = searchText.match(emailRegex);
|
||||||
|
const phoneMatch = searchText.match(phoneRegex);
|
||||||
|
|
||||||
|
// Если это похоже на email, заполняем email
|
||||||
|
if (emailMatch) {
|
||||||
|
document.getElementById('customer-email').value = emailMatch[0];
|
||||||
|
}
|
||||||
|
// Если это похоже на телефон (много цифр), заполняем телефон
|
||||||
|
else if (phoneMatch && phoneMatch[0].replace(/\D/g, '').length >= 9) {
|
||||||
|
document.getElementById('customer-phone').value = phoneMatch[0];
|
||||||
|
}
|
||||||
|
// Иначе считаем это имя
|
||||||
|
else {
|
||||||
|
document.getElementById('customer-name').value = searchText;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Очищаем поля которые не заполнены
|
||||||
|
const customerNameInput = document.getElementById('customer-name');
|
||||||
|
const customerPhoneInput = document.getElementById('customer-phone');
|
||||||
|
const customerEmailInput = document.getElementById('customer-email');
|
||||||
|
const createCustomerModal = new bootstrap.Modal(document.getElementById('createCustomerModal'));
|
||||||
|
|
||||||
|
// Очищаем сообщения об ошибках
|
||||||
|
document.getElementById('customer-form-errors').innerHTML = '';
|
||||||
|
document.getElementById('customer-form-errors').style.display = 'none';
|
||||||
|
|
||||||
|
createCustomerModal.show();
|
||||||
|
};
|
||||||
|
|
||||||
// Вызываем инициализацию
|
// Вызываем инициализацию
|
||||||
initCustomerSelect2();
|
initCustomerSelect2();
|
||||||
|
|
||||||
@@ -923,47 +961,6 @@ if (typeof $ !== 'undefined') {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// === СОЗДАНИЕ НОВОГО КЛИЕНТА ===
|
|
||||||
|
|
||||||
// Функция открытия модального окна создания клиента
|
|
||||||
window.openCreateCustomerModal = function(searchText = '') {
|
|
||||||
// Заполняем форму предложенными данными
|
|
||||||
if (searchText) {
|
|
||||||
// Пытаемся распознать введенные данные
|
|
||||||
const phoneRegex = /[\d\s\-\+\(\)]+/;
|
|
||||||
const emailRegex = /[^\s@]+@[^\s@]+\.[^\s@]+/;
|
|
||||||
|
|
||||||
// Ищем email и телефон в строке поиска
|
|
||||||
const emailMatch = searchText.match(emailRegex);
|
|
||||||
const phoneMatch = searchText.match(phoneRegex);
|
|
||||||
|
|
||||||
// Если это похоже на email, заполняем email
|
|
||||||
if (emailMatch) {
|
|
||||||
document.getElementById('customer-email').value = emailMatch[0];
|
|
||||||
}
|
|
||||||
// Если это похоже на телефон (много цифр), заполняем телефон
|
|
||||||
else if (phoneMatch && phoneMatch[0].replace(/\D/g, '').length >= 9) {
|
|
||||||
document.getElementById('customer-phone').value = phoneMatch[0];
|
|
||||||
}
|
|
||||||
// Иначе считаем это имя
|
|
||||||
else {
|
|
||||||
document.getElementById('customer-name').value = searchText;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Очищаем поля которые не заполнены
|
|
||||||
const customerNameInput = document.getElementById('customer-name');
|
|
||||||
const customerPhoneInput = document.getElementById('customer-phone');
|
|
||||||
const customerEmailInput = document.getElementById('customer-email');
|
|
||||||
const createCustomerModal = new bootstrap.Modal(document.getElementById('createCustomerModal'));
|
|
||||||
|
|
||||||
// Очищаем сообщения об ошибках
|
|
||||||
document.getElementById('customer-form-errors').innerHTML = '';
|
|
||||||
document.getElementById('customer-form-errors').style.display = 'none';
|
|
||||||
|
|
||||||
createCustomerModal.show();
|
|
||||||
};
|
|
||||||
|
|
||||||
// Обработчик сохранения нового клиента
|
// Обработчик сохранения нового клиента
|
||||||
document.getElementById('save-customer-btn').addEventListener('click', function() {
|
document.getElementById('save-customer-btn').addEventListener('click', function() {
|
||||||
const name = document.getElementById('customer-name').value.trim();
|
const name = document.getElementById('customer-name').value.trim();
|
||||||
|
|||||||
Reference in New Issue
Block a user