Переместить определение openCreateCustomerModal в начало скрипта

Проблема: Функция openCreateCustomerModal была определена в конце скрипта,
что делало её недоступной при вызове из обработчика клика.

Решение: Переместить определение функции после initCustomerSelect2(),
но ДО её вызова. Это гарантирует доступность функции.

Результат: Модаль создания клиента теперь открывается корректно при клике!

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-11 00:26:40 +03:00
parent d5356387b7
commit 9b112dd1e5

View File

@@ -561,7 +561,7 @@ function initCustomerSelect2() {
// Очищаем значение
$customerSelect.val(null).trigger('change.select2');
// Открываем модаль
openCreateCustomerModal(data.search_text);
window.openCreateCustomerModal(data.search_text);
return false;
}
});
@@ -580,19 +580,17 @@ function initCustomerSelect2() {
console.log('9_option. Ближайший option:', target);
if (!target) return;
// Проверяем содержит ли элемент класс customer-create-option
const createOptionDiv = target.querySelector('.customer-create-option');
console.log('9_create. create option найден:', !!createOptionDiv);
if (createOptionDiv) {
// Проверяем текст опции - если это "Создать клиента", открываем модаль
const optionText = target.textContent.trim();
console.log('9_text. Текст опции:', optionText);
if (optionText.startsWith('Создать клиента:')) {
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);
openCreateCustomerModal(searchText);
window.openCreateCustomerModal(searchText);
// Закрываем dropdown
$customerSelect.select2('close');
@@ -615,7 +613,7 @@ function initCustomerSelect2() {
// Триггерим нативное change событие для draft-creator.js
const changeEvent = new Event('change', { bubbles: true });
this.dispatchEvent(changeEvent);
openCreateCustomerModal(data.search_text);
window.openCreateCustomerModal(data.search_text);
} else {
// Триггерим нативное change событие для других обработчиков (например, draft-creator.js)
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();
@@ -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() {
const name = document.getElementById('customer-name').value.trim();