renew commit
This commit is contained in:
@@ -44,7 +44,7 @@
|
||||
}
|
||||
|
||||
#qrCodeImg {
|
||||
display: block;
|
||||
display: none;
|
||||
margin: 20px auto;
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
@@ -58,17 +58,7 @@
|
||||
<div class="modal-content">
|
||||
<span class="close">×</span>
|
||||
<h4>Заполните заявку на услугу</h4>
|
||||
<p>QR-код для завершения регистрации:</p>
|
||||
<img id="qrCodeImg" src="" alt="QR Code">
|
||||
<form id="serviceRequestForm">
|
||||
<div class="form-group">
|
||||
<label for="clientName">Ваше имя:</label>
|
||||
<input type="text" class="form-control" id="clientName" name="client_name" placeholder="Введите ваше имя" required minlength="2" maxlength="50" readonly>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="clientChatId">Ваш chat ID:</label>
|
||||
<input type="text" class="form-control" id="clientChatId" name="client_chat_id" placeholder="Ваш chat ID" readonly>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="clientEmail">Ваш email:</label>
|
||||
<input type="email" class="form-control" id="clientEmail" name="client_email" placeholder="Введите ваш email" required>
|
||||
@@ -81,71 +71,101 @@
|
||||
<label for="description">Описание заявки:</label>
|
||||
<textarea class="form-control" id="description" name="description" placeholder="Опишите вашу заявку" required></textarea>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-success" id="submitButton" disabled>Отправить заявку</button>
|
||||
<button type="button" class="btn btn-primary" id="generateQrButton">Продолжить</button>
|
||||
</form>
|
||||
<div id="qrCodeContainer">
|
||||
<p>QR-код для завершения регистрации:</p>
|
||||
<img id="qrCodeImg" src="" alt="QR Code">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="confirmationModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close">×</span>
|
||||
<h4>Заявка успешно создана!</h4>
|
||||
<p>Ваши данные были отправлены и заявка зарегистрирована. Пожалуйста, проверьте ваш Telegram для получения подтверждения.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Обработчик открытия модального окна
|
||||
document.getElementById('openModalBtn').addEventListener('click', function () {
|
||||
const serviceId = this.getAttribute('data-service-id');
|
||||
// Открываем модальное окно
|
||||
document.getElementById('serviceModal').style.display = 'block';
|
||||
|
||||
// Выполняем запрос на генерацию QR-кода
|
||||
fetch(`/service/generate_qr_code/${serviceId}/`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
// Обновляем src изображения QR-кода
|
||||
document.getElementById('qrCodeImg').src = data.qr_code_url;
|
||||
|
||||
// Запуск проверки статуса каждые 5 секунд
|
||||
const interval = setInterval(() => {
|
||||
checkVerificationStatus(data.service_request_id, interval);
|
||||
}, 5000);
|
||||
})
|
||||
.catch(error => console.error('Ошибка при генерации QR-кода:', error));
|
||||
});
|
||||
|
||||
// Обработчик закрытия модального окна
|
||||
document.querySelector('.close').addEventListener('click', function () {
|
||||
document.getElementById('serviceModal').style.display = 'none';
|
||||
document.querySelectorAll('.close').forEach(closeBtn => {
|
||||
closeBtn.addEventListener('click', function () {
|
||||
document.getElementById('serviceModal').style.display = 'none';
|
||||
document.getElementById('confirmationModal').style.display = 'none';
|
||||
});
|
||||
});
|
||||
|
||||
// Обработчик отправки формы
|
||||
document.getElementById('serviceRequestForm').addEventListener('submit', function (event) {
|
||||
event.preventDefault();
|
||||
const formData = new FormData(this);
|
||||
const serviceId = document.getElementById('openModalBtn').getAttribute('data-service-id');
|
||||
// Отправка данных формы на сервер
|
||||
fetch('/service/request/' + serviceId + '/', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
}).then(response => {
|
||||
if (response.ok) {
|
||||
alert('Заявка успешно отправлена!');
|
||||
document.getElementById('serviceModal').style.display = 'none';
|
||||
// Отправка сообщения в Telegram
|
||||
sendTelegramNotification(formData);
|
||||
} else {
|
||||
alert('Ошибка при отправке заявки. Пожалуйста, попробуйте снова.');
|
||||
// Обработчик кнопки "Продолжить" для генерации QR-кода
|
||||
document.getElementById('generateQrButton').addEventListener('click', function () {
|
||||
const clientEmail = document.getElementById('clientEmail').value;
|
||||
const clientPhone = document.getElementById('clientPhone').value;
|
||||
const description = document.getElementById('description').value;
|
||||
|
||||
if (clientEmail && clientPhone && description) {
|
||||
// Выполняем запрос на генерацию QR-кода
|
||||
const openModalBtn = document.getElementById('openModalBtn');
|
||||
if (!openModalBtn) {
|
||||
console.error('Не удалось найти элемент openModalBtn');
|
||||
return;
|
||||
}
|
||||
}).catch(error => console.error('Ошибка при отправке данных формы:', error));
|
||||
|
||||
const serviceId = openModalBtn.getAttribute('data-service-id');
|
||||
if (!serviceId) {
|
||||
console.error('Не удалось найти идентификатор услуги');
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(`/service/generate_qr_code/${serviceId}/`)
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Ошибка при генерации QR-кода');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
// Проверка наличия ссылки на QR-код в ответе
|
||||
if (!data.qr_code_url) {
|
||||
throw new Error('Ответ не содержит QR-код');
|
||||
}
|
||||
|
||||
// Обновляем src изображения QR-кода и показываем его
|
||||
const qrCodeImg = document.getElementById('qrCodeImg');
|
||||
qrCodeImg.src = data.qr_code_url;
|
||||
qrCodeImg.style.display = 'block';
|
||||
|
||||
// Запуск проверки статуса каждые 5 секунд
|
||||
const interval = setInterval(() => {
|
||||
checkVerificationStatus(data.service_request_id, interval, clientEmail, clientPhone, description);
|
||||
}, 5000);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка при генерации QR-кода:', error);
|
||||
});
|
||||
} else {
|
||||
console.error('Поля email, телефон и описание обязательны');
|
||||
}
|
||||
});
|
||||
|
||||
// Проверка статуса заявки на наличие подтверждения Telegram
|
||||
const checkVerificationStatus = (serviceRequestId, interval) => {
|
||||
const checkVerificationStatus = (serviceRequestId, interval, clientEmail, clientPhone, description) => {
|
||||
fetch(`/service/request_status/${serviceRequestId}/`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.is_verified) {
|
||||
// Заполнение полей формы данными пользователя
|
||||
document.getElementById('clientName').value = data.client_name;
|
||||
document.getElementById('clientChatId').value = data.client_chat_id;
|
||||
// Закрываем форму и открываем окно подтверждения
|
||||
document.getElementById('serviceModal').style.display = 'none';
|
||||
document.getElementById('confirmationModal').style.display = 'block';
|
||||
|
||||
// Активируем кнопку отправки, если все поля заполнены
|
||||
updateButtonState();
|
||||
// Создание заявки с использованием данных формы и Telegram
|
||||
createServiceRequest(serviceRequestId, data.client_name, data.client_chat_id, clientEmail, clientPhone, description);
|
||||
|
||||
// Останавливаем интервал проверки статуса
|
||||
clearInterval(interval);
|
||||
@@ -154,43 +174,36 @@
|
||||
.catch(error => console.error('Ошибка при проверке статуса заявки:', error));
|
||||
};
|
||||
|
||||
// Код для активации кнопки "Отправить" при заполнении всех полей
|
||||
const clientEmail = document.getElementById('clientEmail');
|
||||
const clientPhone = document.getElementById('clientPhone');
|
||||
const clientName = document.getElementById('clientName');
|
||||
const description = document.getElementById('description');
|
||||
const clientChatId = document.getElementById('clientChatId');
|
||||
const submitButton = document.getElementById('submitButton');
|
||||
|
||||
const updateButtonState = () => {
|
||||
if (clientEmail.value && clientPhone.value && clientName.value && description.value && clientChatId.value) {
|
||||
submitButton.disabled = false;
|
||||
} else {
|
||||
submitButton.disabled = true;
|
||||
}
|
||||
// Создание заявки с использованием данных из формы и Telegram
|
||||
const createServiceRequest = (serviceRequestId, clientName, chatId, clientEmail, clientPhone, description) => {
|
||||
fetch('/service/create_request/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
service_request_id: serviceRequestId,
|
||||
client_name: clientName,
|
||||
client_chat_id: chatId,
|
||||
client_email: clientEmail,
|
||||
client_phone: clientPhone,
|
||||
description: description
|
||||
})
|
||||
}).then(response => {
|
||||
if (response.ok) {
|
||||
console.log('Заявка успешно создана');
|
||||
sendTelegramNotification({ client_name: clientName, client_chat_id: chatId, description: description });
|
||||
} else {
|
||||
console.error('Ошибка при создании заявки');
|
||||
}
|
||||
}).catch(error => console.error('Ошибка при создании заявки:', error));
|
||||
};
|
||||
|
||||
// Привязка событий к полям для обновления состояния кнопки отправки
|
||||
clientEmail.addEventListener('input', updateButtonState);
|
||||
clientPhone.addEventListener('input', updateButtonState);
|
||||
description.addEventListener('input', updateButtonState);
|
||||
|
||||
// Удаление placeholder при установке фокуса на поле
|
||||
document.querySelectorAll('input, textarea').forEach(field => {
|
||||
field.addEventListener('focus', function () {
|
||||
this.dataset.placeholder = this.placeholder;
|
||||
this.placeholder = '';
|
||||
});
|
||||
field.addEventListener('blur', function () {
|
||||
this.placeholder = this.dataset.placeholder;
|
||||
});
|
||||
});
|
||||
|
||||
// Функция для отправки уведомления в Telegram
|
||||
const sendTelegramNotification = (formData) => {
|
||||
const clientName = formData.get('client_name');
|
||||
const serviceDescription = formData.get('description');
|
||||
const chatId = formData.get('client_chat_id');
|
||||
const sendTelegramNotification = (data) => {
|
||||
const clientName = data.client_name;
|
||||
const serviceDescription = data.description;
|
||||
const chatId = data.client_chat_id;
|
||||
const message = `Здравствуйте, ${clientName}! Ваша заявка успешно зарегистрирована. Детали: ${serviceDescription}`;
|
||||
|
||||
fetch('/service/send_telegram_notification/', {
|
||||
@@ -208,6 +221,7 @@
|
||||
}).catch(error => console.error('Ошибка при отправке уведомления в Telegram:', error));
|
||||
};
|
||||
</script>
|
||||
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
|
||||
</body>
|
||||
|
||||
@@ -1,161 +1,214 @@
|
||||
<!-- web/templates/web/modal_order_form.html -->
|
||||
<div id="orderModal" class="modal fade" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Оформление заявки на услугу</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
|
||||
<title>Модальное окно для заявки на услугу</title>
|
||||
<style>
|
||||
/* Стили для модального окна */
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 1;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
background-color: rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: #fefefe;
|
||||
margin: 15% auto;
|
||||
padding: 20px;
|
||||
border: 1px solid #888;
|
||||
width: 80%;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
.close {
|
||||
color: #aaa;
|
||||
float: right;
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.close:hover,
|
||||
.close:focus {
|
||||
color: #000;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
#qrCodeImg {
|
||||
display: block;
|
||||
margin: 20px auto;
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Модальное окно -->
|
||||
<div id="serviceModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close">×</span>
|
||||
<h4>Заполните заявку на услугу</h4>
|
||||
<p>QR-код для завершения регистрации:</p>
|
||||
<img id="qrCodeImg" src="" alt="QR Code">
|
||||
<form id="serviceRequestForm">
|
||||
<div class="form-group">
|
||||
<label for="clientName">Ваше имя:</label>
|
||||
<input type="text" class="form-control" id="clientName" name="client_name" placeholder="Введите ваше имя" required minlength="2" maxlength="50" readonly>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="orderForm" method="post" action="{% url 'create_service_request' service_id=service.pk %}">
|
||||
{% csrf_token %}
|
||||
<div class="form-group mb-3">
|
||||
<label class="form-label">Имя</label>
|
||||
<input id="client_name" class="form-control" type="text" name="client_name" required minlength="2" maxlength="50" />
|
||||
</div>
|
||||
<div class="form-group mb-3">
|
||||
<label class="form-label">Телефон</label>
|
||||
<input id="client_phone" class="form-control" type="tel" name="client_phone" required pattern="^\+?[0-9\s\-]{7,15}$" />
|
||||
</div>
|
||||
<div class="form-group mb-3">
|
||||
<label class="form-label">Адрес электронной почты</label>
|
||||
<input id="client_email" class="form-control" type="email" name="client_email" required />
|
||||
</div>
|
||||
<div class="form-group mb-3 text-center">
|
||||
<label class="form-label">Сканируйте QR код для регистрации в Telegram боте</label>
|
||||
<div id="qrCodeContainer">
|
||||
<img id="qrCodeImage" src="{{ qr_code_url }}" alt="QR код для Telegram бота" class="img-fluid" style="max-width: 150px;" />
|
||||
</div>
|
||||
<div class="form-group mt-3">
|
||||
<a id="registrationLink" href="#" target="_blank">Перейдите по этой ссылке для регистрации в Telegram боте</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="submit" class="btn btn-primary" id="submitButton" disabled>Отправить заявку</button>
|
||||
</div>
|
||||
</form>
|
||||
{% comment %} <div id="diagnostic_info" class="mt-3">
|
||||
<form id="registrationForm">
|
||||
<h3>Диагностическая информация</h3>
|
||||
<div class="form-group mb-3">
|
||||
<label for="registrationLinkField" class="form-label">Ссылка для регистрации в Telegram боте:</label>
|
||||
<input type="text" id="registrationLinkField" class="form-control" readonly />
|
||||
</div>
|
||||
<div class="form-group mb-3">
|
||||
<label for="requestIdField" class="form-label">Номер заявки:</label>
|
||||
<input type="text" id="requestIdField" class="form-control" readonly />
|
||||
</div>
|
||||
</form>
|
||||
</div> {% endcomment %}
|
||||
<div class="form-group">
|
||||
<label for="clientChatId">Ваш chat ID:</label>
|
||||
<input type="text" class="form-control" id="clientChatId" name="client_chat_id" placeholder="Ваш chat ID" readonly>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="clientEmail">Ваш email:</label>
|
||||
<input type="email" class="form-control" id="clientEmail" name="client_email" placeholder="Введите ваш email" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="clientPhone">Ваш телефон:</label>
|
||||
<input type="text" class="form-control" id="clientPhone" name="client_phone" placeholder="Введите ваш телефон" required pattern="^\+?[0-9\s\-]{7,15}$">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="description">Описание заявки:</label>
|
||||
<textarea class="form-control" id="description" name="description" placeholder="Опишите вашу заявку" required></textarea>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-success" id="submitButton" disabled>Отправить заявку</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const form = document.getElementById('registrationForm');
|
||||
const submitButton = document.getElementById('submitButton');
|
||||
const qrCodeImage = document.getElementById('qrCodeImage');
|
||||
const registrationLink = document.getElementById('registrationLink');
|
||||
let serviceId = "{{ service.pk }}"; // Получаем значение serviceId из шаблона
|
||||
// Обработчик открытия модального окна
|
||||
document.getElementById('openModalBtn').addEventListener('click', function () {
|
||||
const serviceId = this.getAttribute('data-service-id');
|
||||
// Открываем модальное окно
|
||||
document.getElementById('serviceModal').style.display = 'block';
|
||||
|
||||
// Генерация QR-кода при открытии формы
|
||||
// Выполняем запрос на генерацию QR-кода
|
||||
fetch(`/service/generate_qr_code/${serviceId}/`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
qrCodeImage.src = data.qr_code_url;
|
||||
registrationLink.href = data.registration_link;
|
||||
|
||||
// Извлекаем номер заявки из ссылки на регистрацию
|
||||
const requestMatch = data.registration_link.match(/request_(\d+)_token/);
|
||||
if (requestMatch) {
|
||||
serviceId = requestMatch[1];
|
||||
}
|
||||
|
||||
// Отображение диагностической информации на форме
|
||||
//document.getElementById('registrationLinkField').value = data.registration_link;
|
||||
//document.getElementById('requestIdField').value = serviceId;
|
||||
// Обновляем src изображения QR-кода
|
||||
document.getElementById('qrCodeImg').src = data.qr_code_url;
|
||||
|
||||
// Запуск проверки статуса каждые 5 секунд
|
||||
const interval = setInterval(() => {
|
||||
checkVerificationStatus(serviceId, interval);
|
||||
checkVerificationStatus(data.service_request_id, interval);
|
||||
}, 5000);
|
||||
})
|
||||
.catch(error => console.error('Ошибка при генерации QR-кода:', error));
|
||||
|
||||
const checkVerificationStatus = (serviceId, interval) => {
|
||||
fetch(`/service/request_status/${serviceId}/`)
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Network response was not ok');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
if (data.is_verified) {
|
||||
// Заполнение полей формы данными пользователя
|
||||
document.getElementById('client_name').value = data.client_name;
|
||||
document.getElementById('client_email').value = data.client_email;
|
||||
document.getElementById('client_phone').value = data.client_phone;
|
||||
|
||||
// Активируем кнопку отправки, если поля заполнены
|
||||
updateButtonState();
|
||||
|
||||
// Останавливаем интервал проверки статуса
|
||||
clearInterval(interval);
|
||||
}
|
||||
})
|
||||
.catch(error => console.error('Ошибка при проверке статуса:', error));
|
||||
};
|
||||
|
||||
// Обработчик кнопки отправки формы
|
||||
submitButton.addEventListener('click', function () {
|
||||
if (submitButton.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Проверка наличия данных в таблице ServiceRequest перед отправкой формы
|
||||
fetch(`/service/check_service_request_data/?request_id=${serviceId}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.exists) {
|
||||
// Обратная связь пользователю
|
||||
alert('Заявка уже существует. Данные будут обновлены.');
|
||||
|
||||
// Заполнение формы данными из заявки
|
||||
document.getElementById('client_name').value = data.client_name;
|
||||
document.getElementById('client_email').value = data.client_email;
|
||||
document.getElementById('client_phone').value = data.client_phone;
|
||||
|
||||
// Отправка формы
|
||||
form.submit();
|
||||
} else {
|
||||
// Если данных нет, отправляем форму как новую заявку
|
||||
form.submit();
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка при проверке данных заявки:', error);
|
||||
alert('Произошла ошибка при проверке данных. Пожалуйста, попробуйте еще раз.');
|
||||
});
|
||||
});
|
||||
|
||||
// Код для активации кнопки "Отправить" при заполнении полей телефона и email
|
||||
const clientEmail = document.getElementById('client_email');
|
||||
const clientPhone = document.getElementById('client_phone');
|
||||
|
||||
const updateButtonState = () => {
|
||||
if (clientEmail.value && clientPhone.value) {
|
||||
submitButton.disabled = false;
|
||||
} else {
|
||||
submitButton.disabled = true;
|
||||
}
|
||||
};
|
||||
|
||||
// Привязка событий к полям email и телефона
|
||||
clientEmail.addEventListener('input', updateButtonState);
|
||||
clientPhone.addEventListener('input', updateButtonState);
|
||||
});
|
||||
|
||||
// Обработчик закрытия модального окна
|
||||
document.querySelector('.close').addEventListener('click', function () {
|
||||
document.getElementById('serviceModal').style.display = 'none';
|
||||
});
|
||||
|
||||
// Обработчик отправки формы
|
||||
document.getElementById('serviceRequestForm').addEventListener('submit', function (event) {
|
||||
event.preventDefault();
|
||||
const formData = new FormData(this);
|
||||
const serviceId = document.getElementById('openModalBtn').getAttribute('data-service-id');
|
||||
// Отправка данных формы на сервер
|
||||
fetch('/service/request/' + serviceId + '/', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
}).then(response => {
|
||||
if (response.ok) {
|
||||
alert('Заявка успешно отправлена!');
|
||||
document.getElementById('serviceModal').style.display = 'none';
|
||||
// Отправка сообщения в Telegram
|
||||
sendTelegramNotification(formData);
|
||||
} else {
|
||||
alert('Ошибка при отправке заявки. Пожалуйста, попробуйте снова.');
|
||||
}
|
||||
}).catch(error => console.error('Ошибка при отправке данных формы:', error));
|
||||
});
|
||||
|
||||
// Проверка статуса заявки на наличие подтверждения Telegram
|
||||
const checkVerificationStatus = (serviceRequestId, interval) => {
|
||||
fetch(`/service/request_status/${serviceRequestId}/`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.is_verified) {
|
||||
// Заполнение полей формы данными пользователя
|
||||
document.getElementById('clientName').value = data.client_name;
|
||||
document.getElementById('clientChatId').value = data.client_chat_id;
|
||||
|
||||
// Активируем кнопку отправки, если все поля заполнены
|
||||
updateButtonState();
|
||||
|
||||
// Останавливаем интервал проверки статуса
|
||||
clearInterval(interval);
|
||||
}
|
||||
})
|
||||
.catch(error => console.error('Ошибка при проверке статуса заявки:', error));
|
||||
};
|
||||
|
||||
// Код для активации кнопки "Отправить" при заполнении всех полей
|
||||
const clientEmail = document.getElementById('clientEmail');
|
||||
const clientPhone = document.getElementById('clientPhone');
|
||||
const clientName = document.getElementById('clientName');
|
||||
const description = document.getElementById('description');
|
||||
const clientChatId = document.getElementById('clientChatId');
|
||||
const submitButton = document.getElementById('submitButton');
|
||||
|
||||
const updateButtonState = () => {
|
||||
if (clientEmail.value && clientPhone.value && clientName.value && description.value && clientChatId.value) {
|
||||
submitButton.disabled = false;
|
||||
} else {
|
||||
submitButton.disabled = true;
|
||||
}
|
||||
};
|
||||
|
||||
// Привязка событий к полям для обновления состояния кнопки отправки
|
||||
clientEmail.addEventListener('input', updateButtonState);
|
||||
clientPhone.addEventListener('input', updateButtonState);
|
||||
description.addEventListener('input', updateButtonState);
|
||||
|
||||
// Удаление placeholder при установке фокуса на поле
|
||||
document.querySelectorAll('input, textarea').forEach(field => {
|
||||
field.addEventListener('focus', function () {
|
||||
this.dataset.placeholder = this.placeholder;
|
||||
this.placeholder = '';
|
||||
});
|
||||
field.addEventListener('blur', function () {
|
||||
this.placeholder = this.dataset.placeholder;
|
||||
});
|
||||
});
|
||||
|
||||
// Функция для отправки уведомления в Telegram
|
||||
const sendTelegramNotification = (formData) => {
|
||||
const clientName = formData.get('client_name');
|
||||
const serviceDescription = formData.get('description');
|
||||
const chatId = formData.get('client_chat_id');
|
||||
const message = `Здравствуйте, ${clientName}! Ваша заявка успешно зарегистрирована. Детали: ${serviceDescription}`;
|
||||
|
||||
fetch('/service/send_telegram_notification/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ chat_id: chatId, message: message })
|
||||
}).then(response => {
|
||||
if (response.ok) {
|
||||
console.log('Уведомление успешно отправлено в Telegram');
|
||||
} else {
|
||||
console.error('Ошибка при отправке уведомления в Telegram');
|
||||
}
|
||||
}).catch(error => console.error('Ошибка при отправке уведомления в Telegram:', error));
|
||||
};
|
||||
</script>
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -14,8 +14,7 @@
|
||||
<div style="max-width: 350px;">
|
||||
<h2 class="text-uppercase fw-bold">{{ service.name }}<br /></h2>
|
||||
<p class="my-3">{{ service.description }}</p>
|
||||
<button id="orderButton" data-service-id="{{ service.pk }}" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#orderModal">Заказать услугу</button>
|
||||
<!-- Кнопка открытия модального окна -->
|
||||
<!-- Кнопка открытия модального окна -->
|
||||
<button id="openModalBtn" class="btn btn-primary" data-service-id="{{ service.id }}">Открыть заявку на услугу</button>
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user