fully functional. UX/UI stage
This commit is contained in:
@@ -1,64 +0,0 @@
|
||||
<!-- 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>
|
||||
</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 src="{{ qr_code }}" alt="QR код для Telegram бота" class="img-fluid" />
|
||||
</div>
|
||||
<div class="form-group mt-3">
|
||||
<a href="{{ registration_link }}" 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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const checkVerificationStatus = () => {
|
||||
fetch(`/service/request_status/{{ service_request_id }}/`)
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Network response was not ok');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
if (data.is_verified) {
|
||||
document.getElementById('submitButton').disabled = false;
|
||||
}
|
||||
})
|
||||
.catch(error => console.error('Ошибка при проверке статуса:', error));
|
||||
};
|
||||
|
||||
setInterval(checkVerificationStatus, 5000);
|
||||
});
|
||||
</script>
|
||||
@@ -1,214 +0,0 @@
|
||||
<!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="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>
|
||||
</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.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.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>
|
||||
@@ -20,6 +20,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Модальное окно для создания заявки на услугу -->
|
||||
{% include "web/modal_order_form.html" %}
|
||||
|
||||
<div class="container py-4">
|
||||
@@ -78,174 +79,10 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Добавляем стили для анимации появления модального окна */
|
||||
#serviceModal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 1;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
position: relative;
|
||||
background-color: #fefefe;
|
||||
margin: auto;
|
||||
padding: 20px;
|
||||
border: 1px solid #888;
|
||||
width: 80%;
|
||||
max-width: 600px;
|
||||
transform: scale(0);
|
||||
transition: transform 0.5s ease;
|
||||
}
|
||||
|
||||
.modal.show .modal-content {
|
||||
transform: scale(1);
|
||||
}
|
||||
</style>
|
||||
|
||||
<script <script src="{% static 'assets/js/modal-init.js' %}"> </script>
|
||||
<script>
|
||||
function checkVerificationStatus(serviceRequestId, interval) {
|
||||
fetch(`/service/request_status/${serviceRequestId}/`)
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Ошибка при проверке статуса заявки');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
if (data.is_verified) {
|
||||
// Закрываем форму и показываем окно подтверждения
|
||||
document.getElementById('serviceModal').style.display = 'none';
|
||||
document.getElementById('confirmationModal').style.display = 'block';
|
||||
|
||||
// Останавливаем интервал проверки статуса
|
||||
clearInterval(interval);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка при проверке статуса заявки:', error);
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
// Получение CSRF токена
|
||||
function getCookie(name) {
|
||||
let cookieValue = null;
|
||||
if (document.cookie && document.cookie !== '') {
|
||||
const cookies = document.cookie.split(';');
|
||||
for (let i = 0; i < cookies.length; i++) {
|
||||
const cookie = cookies[i].trim();
|
||||
if (cookie.substring(0, name.length + 1) === (name + '=')) {
|
||||
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cookieValue;
|
||||
}
|
||||
|
||||
const csrftoken = getCookie('csrftoken');
|
||||
|
||||
// Открытие модального окна
|
||||
const openModalBtn = document.getElementById('openModalBtn');
|
||||
const serviceModal = document.getElementById('serviceModal');
|
||||
if (openModalBtn) {
|
||||
openModalBtn.addEventListener('click', function (event) {
|
||||
event.preventDefault(); // Предотвращаем отправку формы при нажатии на кнопку
|
||||
serviceModal.classList.add('show');
|
||||
serviceModal.style.display = 'block';
|
||||
});
|
||||
} else {
|
||||
console.error('Не удалось найти элемент с id openModalBtn.');
|
||||
}
|
||||
|
||||
// Закрытие модальных окон
|
||||
document.querySelectorAll('.close').forEach(closeBtn => {
|
||||
closeBtn.addEventListener('click', function () {
|
||||
serviceModal.classList.remove('show');
|
||||
setTimeout(() => {
|
||||
serviceModal.style.display = 'none';
|
||||
}, 500); // Ждем, пока завершится анимация закрытия
|
||||
});
|
||||
});
|
||||
|
||||
// Обработчик кнопки "Продолжить" для генерации QR-кода
|
||||
const generateQrButton = document.getElementById('generateQrButton');
|
||||
if (generateQrButton) {
|
||||
generateQrButton.addEventListener('click', function () {
|
||||
const clientEmail = document.getElementById('clientEmail').value;
|
||||
const clientPhone = document.getElementById('clientPhone').value;
|
||||
const clientName = document.getElementById('clientName').value;
|
||||
const description = document.getElementById('description').value;
|
||||
|
||||
// Проверяем, чтобы все поля были заполнены
|
||||
if (!clientEmail || !clientPhone || !clientName || !description) {
|
||||
alert('Все поля должны быть заполнены.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Выполняем валидацию телефона перед продолжением
|
||||
let phonePattern = /^\+?[0-9\s\-]{7,15}$/;
|
||||
if (!phonePattern.test(clientPhone)) {
|
||||
alert('Введите правильный номер телефона.');
|
||||
return; // Останавливаем выполнение, если телефон не валиден
|
||||
}
|
||||
|
||||
// Получаем serviceId из кнопки открытия модального окна
|
||||
const serviceId = openModalBtn.getAttribute('data-service-id');
|
||||
if (!serviceId) {
|
||||
console.error('Не удалось найти идентификатор услуги');
|
||||
return;
|
||||
}
|
||||
|
||||
// Запрос на генерацию QR-кода с использованием метода POST
|
||||
fetch(`/service/generate_qr_code/${serviceId}/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': csrftoken // Добавляем CSRF токен в заголовок
|
||||
},
|
||||
body: JSON.stringify({
|
||||
client_email: clientEmail,
|
||||
client_phone: clientPhone,
|
||||
client_name: clientName,
|
||||
description: description
|
||||
})
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Ошибка при генерации QR-кода');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
if (!data.qr_code_url) {
|
||||
throw new Error('Ответ не содержит URL 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);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
</script>
|
||||
<!-- Подключение JavaScript файлов, вынесенных в директорию static/assets/js -->
|
||||
<script src="{% static 'assets/js/get-csrf-token.js' %}"></script>
|
||||
<script src="{% static 'assets/js/modal-init.js' %}"></script>
|
||||
<script src="{% static 'assets/js/service_request.js' %}"></script>
|
||||
<script src="{% static 'assets/js/verification_status.js' %}"></script>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user