registration functions. service request resolved
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
{% load static %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
@@ -57,26 +58,29 @@
|
||||
<div id="serviceModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close">×</span>
|
||||
<h4>Заполните заявку на услугу</h4>
|
||||
<form id="serviceRequestForm">
|
||||
<div class="form-group">
|
||||
<label for="clientName">Ваше имя:</label>
|
||||
<input type="text" class="form-control" id="clientName" name="client_name" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="clientEmail">Ваш email:</label>
|
||||
<input type="email" class="form-control" id="clientEmail" name="client_email" placeholder="Введите ваш email" required>
|
||||
<input type="email" class="form-control" id="clientEmail" name="client_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}$">
|
||||
<input type="text" class="form-control" id="clientPhone" name="client_phone" 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>
|
||||
<textarea class="form-control" id="description" name="description" required></textarea>
|
||||
</div>
|
||||
<button type="button" class="btn btn-primary" id="generateQrButton">Продолжить</button>
|
||||
<div id="qrCodeContainer">
|
||||
<p>QR-код для завершения регистрации:</p>
|
||||
<img id="qrCodeImg" src="" alt="QR Code">
|
||||
</div>
|
||||
<button type="button" id="generateQrButton" class="btn btn-primary">Продолжить</button>
|
||||
</form>
|
||||
<div id="qrCodeContainer">
|
||||
<p>QR-код для завершения регистрации:</p>
|
||||
<img id="qrCodeImg" src="" alt="QR Code">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -88,140 +92,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Обработчик открытия модального окна
|
||||
document.getElementById('openModalBtn').addEventListener('click', function () {
|
||||
// Открываем модальное окно
|
||||
document.getElementById('serviceModal').style.display = 'block';
|
||||
});
|
||||
|
||||
// Обработчик закрытия модального окна
|
||||
document.querySelectorAll('.close').forEach(closeBtn => {
|
||||
closeBtn.addEventListener('click', function () {
|
||||
document.getElementById('serviceModal').style.display = 'none';
|
||||
document.getElementById('confirmationModal').style.display = 'none';
|
||||
});
|
||||
});
|
||||
|
||||
// Обработчик кнопки "Продолжить" для генерации 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;
|
||||
}
|
||||
|
||||
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, clientEmail, clientPhone, description) => {
|
||||
fetch(`/service/request_status/${serviceRequestId}/`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.is_verified) {
|
||||
// Закрываем форму и открываем окно подтверждения
|
||||
document.getElementById('serviceModal').style.display = 'none';
|
||||
document.getElementById('confirmationModal').style.display = 'block';
|
||||
|
||||
// Создание заявки с использованием данных формы и Telegram
|
||||
createServiceRequest(serviceRequestId, data.client_name, data.client_chat_id, clientEmail, clientPhone, description);
|
||||
|
||||
// Останавливаем интервал проверки статуса
|
||||
clearInterval(interval);
|
||||
}
|
||||
})
|
||||
.catch(error => console.error('Ошибка при проверке статуса заявки:', error));
|
||||
};
|
||||
|
||||
// Создание заявки с использованием данных из формы и 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));
|
||||
};
|
||||
|
||||
// Функция для отправки уведомления в Telegram
|
||||
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/', {
|
||||
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 <script src="{% static 'assets/js/modal-init.js' %}"> </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,4 +1,3 @@
|
||||
<!-- web/templates/web/service_detail.html -->
|
||||
{% extends 'web/base.html' %}
|
||||
{% load static %}
|
||||
{% block title %}Услуга - {{ service.name }}{% endblock %}
|
||||
@@ -14,16 +13,15 @@
|
||||
<div style="max-width: 350px;">
|
||||
<h2 class="text-uppercase fw-bold">{{ service.name }}<br /></h2>
|
||||
<p class="my-3">{{ service.description }}</p>
|
||||
<!-- Кнопка открытия модального окна -->
|
||||
<!-- Кнопка открытия модального окна -->
|
||||
<button id="openModalBtn" class="btn btn-primary" data-service-id="{{ service.id }}">Открыть заявку на услугу</button>
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% include "web/modal_order_form.html" %}
|
||||
|
||||
<div class="container py-4">
|
||||
<div class="row-cols-auto">
|
||||
<div class="col-md-8 col-xl-6 text-center mx-auto">
|
||||
@@ -80,17 +78,174 @@
|
||||
</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>
|
||||
// JavaScript для дополнительной проверки формы
|
||||
document.getElementById('orderForm').addEventListener('submit', function (event) {
|
||||
let phoneInput = document.getElementById('client_phone');
|
||||
let phonePattern = /^\+?[0-9\s\-]{7,15}$/;
|
||||
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';
|
||||
|
||||
if (!phonePattern.test(phoneInput.value)) {
|
||||
alert('Введите правильный номер телефона.');
|
||||
event.preventDefault(); // Останавливаем отправку формы
|
||||
// Останавливаем интервал проверки статуса
|
||||
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>
|
||||
|
||||
{% endblock %}
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user