commit 12.01
This commit is contained in:
@@ -3,393 +3,263 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Все брони - КлинСервис Админка</title>
|
||||
<title>Админка — Бронирования</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body { font-family: Arial, sans-serif; background: #f8f9fa; }
|
||||
|
||||
/* Хедер */
|
||||
header {
|
||||
background: #2c3e50; color: white; padding: 20px 50px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1); position: sticky; top: 0;
|
||||
background: white; padding: 20px 50px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
position: sticky; top: 0; z-index: 100;
|
||||
}
|
||||
.header-content {
|
||||
max-width: 1400px; margin: 0 auto;
|
||||
max-width: 1200px; margin: 0 auto;
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
}
|
||||
.logo { font-size: 24px; font-weight: bold; }
|
||||
.header-nav { display: flex; gap: 20px; }
|
||||
.logo { font-size: 24px; font-weight: bold; color: #667eea; }
|
||||
.btn {
|
||||
padding: 12px 25px; border: none; border-radius: 25px;
|
||||
cursor: pointer; font-size: 16px; text-decoration: none;
|
||||
display: inline-block; transition: all 0.3s; color: white;
|
||||
padding: 10px 20px; border: none; border-radius: 25px;
|
||||
cursor: pointer; font-size: 14px; text-decoration: none;
|
||||
display: inline-block; transition: all 0.3s;
|
||||
}
|
||||
.btn-primary { background: #667eea; }
|
||||
.btn-primary:hover { background: #5a67d8; }
|
||||
.btn-secondary { background: #6c757d; }
|
||||
.btn-secondary:hover { background: #5a6268; }
|
||||
.btn-primary { background: #667eea; color: white; }
|
||||
.btn-secondary { background: transparent; color: #667eea; border: 2px solid #667eea; }
|
||||
|
||||
/* Контейнер */
|
||||
.container { max-width: 1400px; margin: 40px auto; padding: 0 20px; }
|
||||
h1 { text-align: center; color: #333; margin-bottom: 40px; font-size: 32px; }
|
||||
.container { max-width: 1200px; margin: 40px auto; padding: 0 20px; }
|
||||
h1 { text-align: center; margin-bottom: 30px; color: #333; }
|
||||
|
||||
/* Фильтры */
|
||||
.filters {
|
||||
background: white; padding: 30px; border-radius: 20px;
|
||||
box-shadow: 0 20px 40px rgba(0,0,0,0.1); margin-bottom: 30px;
|
||||
display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
@media (max-width: 768px) { .filters { grid-template-columns: 1fr; } }
|
||||
table { width: 100%; border-collapse: collapse; background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
|
||||
th, td { padding: 15px; text-align: left; border-bottom: 1px solid #eee; }
|
||||
th { background: #667eea; color: white; }
|
||||
tr:hover { background: #f9f9f9; }
|
||||
|
||||
.filter-group label { display: block; margin-bottom: 8px; font-weight: bold; color: #555; }
|
||||
.filter-group input, .filter-group select {
|
||||
width: 100%; padding: 12px; border: 2px solid #e9ecef;
|
||||
border-radius: 10px; font-size: 16px;
|
||||
}
|
||||
.filter-group input:focus, .filter-group select:focus { border-color: #667eea; outline: none; }
|
||||
select, input { padding: 8px; border: 1px solid #ccc; border-radius: 5px; }
|
||||
.actions { display: flex; gap: 10px; margin-top: 10px; }
|
||||
.btn-sm { padding: 5px 10px; font-size: 12px; }
|
||||
.status { padding: 4px 8px; border-radius: 10px; font-size: 12px; }
|
||||
.confirmed { background: #d4edda; color: #155724; }
|
||||
.cancelled { background: #f8d7da; color: #721c24; }
|
||||
.completed { background: #d1ecf1; color: #0c5460; }
|
||||
|
||||
.filter-btn {
|
||||
padding: 15px 30px; background: #667eea; color: white;
|
||||
border: none; border-radius: 10px; font-size: 16px;
|
||||
cursor: pointer; grid-column: span 2;
|
||||
}
|
||||
.filter-btn:hover { background: #5a67d8; }
|
||||
|
||||
/* Таблица */
|
||||
.bookings-table {
|
||||
background: white; border-radius: 20px;
|
||||
box-shadow: 0 20px 40px rgba(0,0,0,0.1); overflow: hidden;
|
||||
}
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { padding: 18px 15px; text-align: left; border-bottom: 1px solid #e9ecef; }
|
||||
th { background: #667eea; color: white; font-weight: bold; position: sticky; top: 0; }
|
||||
tr:hover { background: #f8f9fa; }
|
||||
|
||||
/* Статусы */
|
||||
.status { padding: 6px 12px; border-radius: 15px; font-size: 14px; font-weight: bold; }
|
||||
.status.confirmed { background: #d4edda; color: #155724; }
|
||||
.status.completed { background: #d1ecf1; color: #0c5460; }
|
||||
.status.cancelled { background: #f8d7da; color: #721c24; }
|
||||
|
||||
/* Действия */
|
||||
.action-buttons { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.btn-small {
|
||||
padding: 8px 14px; font-size: 13px; border-radius: 12px;
|
||||
text-decoration: none; border: none; cursor: pointer; font-weight: 500;
|
||||
}
|
||||
.btn-complete { background: #28a745; color: white; }
|
||||
.btn-complete:hover { background: #218838; }
|
||||
.btn-cancel-admin { background: #dc3545; color: white; }
|
||||
.btn-cancel-admin:hover { background: #c82333; }
|
||||
|
||||
/* Модальное окно */
|
||||
.modal {
|
||||
display: none; position: fixed; top: 0; left: 0;
|
||||
width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;
|
||||
}
|
||||
.modal-content {
|
||||
background: white; margin: 10% auto; padding: 40px;
|
||||
border-radius: 20px; max-width: 500px; width: 90%; position: relative;
|
||||
}
|
||||
.close {
|
||||
position: absolute; top: 15px; right: 20px; font-size: 28px;
|
||||
cursor: pointer; color: #999;
|
||||
}
|
||||
.close:hover { color: #333; }
|
||||
.modal textarea {
|
||||
width: 100%; height: 100px; padding: 15px;
|
||||
border: 2px solid #e9ecef; border-radius: 10px;
|
||||
font-family: Arial, sans-serif; resize: vertical; margin-bottom: 20px;
|
||||
}
|
||||
.modal-buttons { display: flex; gap: 15px; }
|
||||
.btn-modal { flex: 1; padding: 15px; border: none; border-radius: 10px; font-size: 16px; cursor: pointer; }
|
||||
.btn-confirm { background: #dc3545; color: white; }
|
||||
.btn-confirm:hover { background: #c82333; }
|
||||
|
||||
.no-bookings { text-align: center; padding: 80px 40px; color: #666; font-size: 18px; }
|
||||
|
||||
@media (max-width: 768px) {
|
||||
th, td { padding: 12px 8px; font-size: 14px; }
|
||||
.action-buttons { flex-direction: column; }
|
||||
}
|
||||
.no-data { text-align: center; padding: 40px; color: #666; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Хедер -->
|
||||
<header>
|
||||
<div class="header-content">
|
||||
<div class="logo">🧹 КлинСервис - Админка</div>
|
||||
<div class="header-nav">
|
||||
<a href="admin-services.html" class="btn btn-secondary">Услуги</a>
|
||||
<a href="admin-schedule.html" class="btn btn-secondary">Расписание</a>
|
||||
<a href="index.html" class="btn btn-primary">На главную</a>
|
||||
<button class="btn btn-secondary" onclick="logout()">Выйти</button>
|
||||
<div class="logo">🧹 Админка — КлинСервис</div>
|
||||
<div>
|
||||
<a href="index.html" class="btn btn-secondary">Главная</a>
|
||||
<button class="btn btn-primary" onclick="logout()">Выйти</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="container">
|
||||
<h1>📋 Все бронирования</h1>
|
||||
|
||||
<!-- Фильтры -->
|
||||
<div class="filters">
|
||||
<div class="filter-group">
|
||||
<label>Дата:</label>
|
||||
<input type="date" id="filterDate">
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>Статус:</label>
|
||||
<select id="filterStatus">
|
||||
<option value="">Все</option>
|
||||
<option value="confirmed">Подтверждена</option>
|
||||
<option value="completed">Выполнена</option>
|
||||
<option value="cancelled">Отменена</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>Сотрудник:</label>
|
||||
<select id="filterEmployee">
|
||||
<option value="">Все сотрудники</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>Клиент (email):</label>
|
||||
<input type="email" id="filterClient" placeholder="ivan@example.com">
|
||||
</div>
|
||||
<button class="filter-btn" onclick="applyFilters()">🔍 Применить фильтры</button>
|
||||
<button class="filter-btn" onclick="clearFilters()" style="background: #6c757d;">Очистить</button>
|
||||
</div>
|
||||
|
||||
<!-- Таблица броней -->
|
||||
<div class="bookings-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Код брони</th>
|
||||
<th>Клиент (email)</th>
|
||||
<th>Услуга</th>
|
||||
<th>Сотрудник</th>
|
||||
<th>Дата и время</th>
|
||||
<th>Статус</th>
|
||||
<th>Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="bookingsTable">
|
||||
<tr>
|
||||
<td colspan="7" class="no-bookings">Загрузка броней...</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Модальное окно отмены -->
|
||||
<div id="cancelModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" onclick="closeCancelModal()">×</span>
|
||||
<h3>Отменить бронь администратором?</h3>
|
||||
<p id="cancelBookingInfo"></p>
|
||||
<p>Укажите причину отмены (необязательно):</p>
|
||||
<textarea id="cancelReason" placeholder="Сотрудник заболел, клиент не вышел на связь..."></textarea>
|
||||
<div class="modal-buttons">
|
||||
<button class="btn-modal" onclick="closeCancelModal()">Отмена</button>
|
||||
<button class="btn-modal btn-confirm" id="confirmCancelBtn" onclick="adminCancelBooking()">Отменить</button>
|
||||
</div>
|
||||
</div>
|
||||
<table id="bookingsTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№</th>
|
||||
<th>Клиент</th>
|
||||
<th>Услуга</th>
|
||||
<th>Дата и время</th>
|
||||
<th>Сотрудник</th>
|
||||
<th>Статус</th>
|
||||
<th>Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td colspan="7" class="no-data">Загрузка...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let token = localStorage.getItem('token');
|
||||
let allBookings = [];
|
||||
let filteredBookings = [];
|
||||
let selectedBookingId = null;
|
||||
let bookings = [];
|
||||
let employees = [];
|
||||
|
||||
// Проверка авторизации
|
||||
if (!token) {
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
|
||||
// Загрузка при старте
|
||||
// Загрузка данных при старте
|
||||
window.onload = async function() {
|
||||
await loadBookings();
|
||||
await loadEmployeesForFilter();
|
||||
try {
|
||||
await loadEmployees();
|
||||
await loadBookings();
|
||||
} catch (err) {
|
||||
alert('Ошибка загрузки данных: ' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
// Загрузить сотрудников
|
||||
async function loadEmployees() {
|
||||
try {
|
||||
const res = await fetch('/api/users?role=employee', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
// Проверяем тип ответа
|
||||
const contentType = res.headers.get('content-type');
|
||||
if (!contentType || !contentType.includes('application/json')) {
|
||||
throw new Error('Сервер вернул HTML вместо JSON (проверьте роль пользователя)');
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
throw new Error(`HTTP ${res.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
employees = await res.json();
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки сотрудников:', error);
|
||||
alert('Ошибка загрузки сотрудников: ' + error.message);
|
||||
employees = [];
|
||||
}
|
||||
}
|
||||
|
||||
// Загрузить все брони
|
||||
async function loadBookings() {
|
||||
try {
|
||||
const response = await fetch('/api/admin/bookings', {
|
||||
const res = await fetch('/api/admin/bookings', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
allBookings = await response.json();
|
||||
filteredBookings = [...allBookings];
|
||||
renderBookings();
|
||||
} else {
|
||||
alert('Ошибка доступа');
|
||||
window.location.href = 'register-login.html';
|
||||
const contentType = res.headers.get('content-type');
|
||||
if (!contentType || !contentType.includes('application/json')) {
|
||||
throw new Error('Сервер вернул HTML вместо JSON (проверьте роль пользователя)');
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
throw new Error(`HTTP ${res.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
bookings = await res.json();
|
||||
renderBookings();
|
||||
} catch (error) {
|
||||
document.getElementById('bookingsTable').innerHTML =
|
||||
'<tr><td colspan="7" class="no-bookings">Ошибка загрузки</td></tr>';
|
||||
console.error('Ошибка загрузки бронирований:', error);
|
||||
document.querySelector('#bookingsTable tbody').innerHTML =
|
||||
`<tr><td colspan="7" class="no-data">Ошибка: ${error.message}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
// Загрузить сотрудников для фильтра
|
||||
async function loadEmployeesForFilter() {
|
||||
try {
|
||||
const response = await fetch('/api/admin/users?role=employee', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const employees = await response.json();
|
||||
const select = document.getElementById('filterEmployee');
|
||||
|
||||
for (let employee of employees.filter(e => e.role === 'employee')) {
|
||||
select.innerHTML += `<option value="${employee.id}">${employee.name}</option>`;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки сотрудников');
|
||||
}
|
||||
}
|
||||
|
||||
// Применить фильтры
|
||||
function applyFilters() {
|
||||
const date = document.getElementById('filterDate').value;
|
||||
const status = document.getElementById('filterStatus').value;
|
||||
const employeeId = document.getElementById('filterEmployee').value;
|
||||
const clientEmail = document.getElementById('filterClient').value.toLowerCase();
|
||||
|
||||
filteredBookings = allBookings.filter(booking => {
|
||||
let match = true;
|
||||
|
||||
if (date && booking.bookingdate !== date) match = false;
|
||||
if (status && booking.status !== status) match = false;
|
||||
if (employeeId && booking.employee_id != employeeId) match = false;
|
||||
if (clientEmail && (!booking.client || !booking.client.email.toLowerCase().includes(clientEmail))) match = false;
|
||||
|
||||
return match;
|
||||
});
|
||||
|
||||
renderBookings();
|
||||
}
|
||||
|
||||
// Очистить фильтры
|
||||
function clearFilters() {
|
||||
document.getElementById('filterDate').value = '';
|
||||
document.getElementById('filterStatus').value = '';
|
||||
document.getElementById('filterEmployee').value = '';
|
||||
document.getElementById('filterClient').value = '';
|
||||
filteredBookings = [...allBookings];
|
||||
renderBookings();
|
||||
}
|
||||
|
||||
// Отобразить брони
|
||||
// Отобразить таблицу
|
||||
function renderBookings() {
|
||||
const tbody = document.getElementById('bookingsTable');
|
||||
|
||||
if (filteredBookings.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="no-bookings">Нет броней по фильтрам</td></tr>';
|
||||
const tbody = document.querySelector('#bookingsTable tbody');
|
||||
if (bookings.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="no-data">Нет бронирований</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
tbody.innerHTML = '';
|
||||
|
||||
for (let booking of filteredBookings) {
|
||||
const row = document.createElement('tr');
|
||||
const statusClass = booking.status;
|
||||
|
||||
row.innerHTML = `
|
||||
<td><strong>${booking.bookingnumber}</strong></td>
|
||||
<td>${booking.client ? booking.client.email : 'Неизвестно'}</td>
|
||||
<td>${booking.service ? booking.service.name : 'Удалена'}</td>
|
||||
<td>${booking.employee ? booking.employee.name : 'Не назначен'}</td>
|
||||
<td>${booking.bookingdate}<br>${booking.starttime.slice(0,5)}–${booking.endtime.slice(0,5)}</td>
|
||||
<td><span class="status ${statusClass}">${booking.status}</span></td>
|
||||
<td>
|
||||
<div class="action-buttons">
|
||||
${booking.status !== 'completed' ?
|
||||
`<button class="btn-small btn-cancel-admin" onclick="showCancelModal(${booking.id}, '${booking.bookingnumber}')">
|
||||
❌ Отменить
|
||||
</button>` : ''}
|
||||
${booking.status === 'confirmed' ?
|
||||
`<button class="btn-small btn-complete" onclick="markAsCompleted(${booking.id})">
|
||||
✅ Выполнено
|
||||
</button>` : ''}
|
||||
</div>
|
||||
</td>
|
||||
bookings.forEach(b => {
|
||||
const employeeSelect = document.createElement('select');
|
||||
employeeSelect.className = 'employee-select';
|
||||
employeeSelect.dataset.bookingId = b.id;
|
||||
|
||||
if (!employees.length) {
|
||||
const option = document.createElement('option');
|
||||
option.value = '';
|
||||
option.textContent = '—';
|
||||
employeeSelect.appendChild(option);
|
||||
} else {
|
||||
employees.forEach(emp => {
|
||||
const option = document.createElement('option');
|
||||
option.value = emp.id;
|
||||
option.textContent = emp.name;
|
||||
if ((b.employee && b.employee.id == emp.id) || b.employee_id == emp.id) {
|
||||
option.selected = true;
|
||||
}
|
||||
employeeSelect.appendChild(option);
|
||||
});
|
||||
}
|
||||
|
||||
const status = b.status || 'confirmed';
|
||||
const statusClass = status;
|
||||
|
||||
const row = `
|
||||
<tr>
|
||||
<td>${b.booking_number || '—'}</td>
|
||||
<td>${(b.client && b.client.name) ? b.client.name : '—'}</td>
|
||||
<td>${(b.service && b.service.name) ? b.service.name : '—'}</td>
|
||||
<td>${b.booking_date || '—'} ${b.start_time ? b.start_time.slice(0,5) : '—'}</td>
|
||||
<td>
|
||||
${employeeSelect.outerHTML}
|
||||
<div class="actions">
|
||||
<button class="btn-sm btn-primary" onclick="saveEmployee(${b.id})">Сохранить</button>
|
||||
</div>
|
||||
</td>
|
||||
<td><span class="status ${statusClass}">${status}</span></td>
|
||||
<td>
|
||||
${status === 'confirmed' ?
|
||||
`<button class="btn-sm btn-danger" onclick="cancelBooking(${b.id})">Отменить</button>` :
|
||||
`<button class="btn-sm btn-secondary" disabled>Отменено</button>`
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
|
||||
tbody.appendChild(row);
|
||||
tbody.innerHTML += row;
|
||||
});
|
||||
}
|
||||
|
||||
// Сохранить сотрудника
|
||||
async function saveEmployee(bookingId) {
|
||||
const select = document.querySelector(`.employee-select[data-booking-id="${bookingId}"]`);
|
||||
if (!select || !select.value) {
|
||||
alert('Выберите сотрудника');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Показать модальное окно отмены
|
||||
function showCancelModal(bookingId, bookingNumber) {
|
||||
selectedBookingId = bookingId;
|
||||
document.getElementById('cancelBookingInfo').innerHTML =
|
||||
`Бронь <strong>${bookingNumber}</strong>`;
|
||||
document.getElementById('cancelReason').value = '';
|
||||
document.getElementById('cancelModal').style.display = 'block';
|
||||
}
|
||||
|
||||
// Закрыть модальное окно
|
||||
function closeCancelModal() {
|
||||
document.getElementById('cancelModal').style.display = 'none';
|
||||
}
|
||||
|
||||
// Админская отмена
|
||||
async function adminCancelBooking() {
|
||||
const reason = document.getElementById('cancelReason').value;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/admin/bookings/${selectedBookingId}/cancel`, {
|
||||
const res = await fetch(`/api/admin/bookings/${bookingId}/assign`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ reason: reason || null })
|
||||
body: JSON.stringify({ employee_id: select.value })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
alert('✅ Бронь отменена администратором');
|
||||
closeCancelModal();
|
||||
|
||||
if (res.ok) {
|
||||
alert('✅ Сотрудник назначен!');
|
||||
loadBookings();
|
||||
} else {
|
||||
alert('Ошибка: ' + data.error);
|
||||
const err = await res.json().catch(() => ({ message: 'Неизвестная ошибка' }));
|
||||
alert('Ошибка: ' + (err.message || 'Не удалось назначить сотрудника'));
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Ошибка сети');
|
||||
alert('Ошибка сети: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Пометить как выполнено
|
||||
async function markAsCompleted(bookingId) {
|
||||
if (confirm('Пометить бронь как выполненную?')) {
|
||||
try {
|
||||
const response = await fetch(`/api/admin/bookings/${bookingId}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ status: 'completed' })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
alert('✅ Бронь отмечена как выполненная');
|
||||
loadBookings();
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Ошибка');
|
||||
// Отменить бронь
|
||||
async function cancelBooking(bookingId) {
|
||||
const reason = prompt('Причина отмены:');
|
||||
if (reason === null) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/admin/bookings/${bookingId}/cancel`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ reason: reason.trim() || null })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
alert('✅ Бронь отменена!');
|
||||
loadBookings();
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({ message: 'Неизвестная ошибка' }));
|
||||
alert('Ошибка: ' + (err.message || 'Не удалось отменить бронь'));
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Ошибка сети: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,17 +267,6 @@
|
||||
localStorage.removeItem('token');
|
||||
window.location.href = 'index.html';
|
||||
}
|
||||
|
||||
// Enter для фильтров
|
||||
document.addEventListener('keypress', function(e) {
|
||||
if (e.key === 'Enter') applyFilters();
|
||||
});
|
||||
|
||||
// Клик вне модального окна
|
||||
window.onclick = function(event) {
|
||||
const modal = document.getElementById('cancelModal');
|
||||
if (event.target === modal) closeCancelModal();
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
@@ -171,21 +171,53 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const token = localStorage.getItem('auth_token');
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
if (!token) {
|
||||
window.location.href = '/register-login.html';
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
|
||||
fetch('/api/admin/availabilities', {
|
||||
headers: { 'Authorization': 'Bearer ' + token }
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const list = document.getElementById('schedule-list');
|
||||
data.forEach(avail => {
|
||||
list.innerHTML += `<p>${avail.employee_id} — ${avail.date} ${avail.starttime} - ${avail.endtime}</p>`;
|
||||
});
|
||||
});
|
||||
window.onload = loadSchedule;
|
||||
|
||||
async function loadSchedule() {
|
||||
try {
|
||||
const res = await fetch('/api/admin/availabilities', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
const availabilities = await res.json();
|
||||
|
||||
const list = document.getElementById('schedule-list');
|
||||
availabilities.forEach(a => {
|
||||
list.innerHTML += `
|
||||
<div>
|
||||
<p>Сотрудник: ${a.employee_id} — ${a.date} ${a.start_time}–${a.end_time} — ${a.is_available ? 'Доступен' : 'Недоступен'}</p>
|
||||
<button onclick="deleteSlot(${a.id})">Удалить</button>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
} catch (err) {
|
||||
alert('Ошибка загрузки расписания');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSlot(id) {
|
||||
if (confirm('Удалить слот?')) {
|
||||
try {
|
||||
const res = await fetch(`/api/admin/availabilities/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
alert('Слот удалён');
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Ошибка');
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -180,45 +180,105 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Получаем токен из localStorage
|
||||
const token = localStorage.getItem('auth_token');
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
// Если нет токена — перенаправляем на вход
|
||||
if (!token) {
|
||||
alert('Доступ только для администраторов!');
|
||||
window.location.href = '/register-login.html';
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
|
||||
// Загружаем услуги
|
||||
fetch('/api/admin/services', {
|
||||
headers: {
|
||||
'Authorization': 'Bearer ' + token,
|
||||
'Accept': 'application/json'
|
||||
window.onload = loadServices;
|
||||
|
||||
async function loadServices() {
|
||||
try {
|
||||
const res = await fetch('/api/admin/services', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
const services = await res.json();
|
||||
|
||||
const list = document.getElementById('services-list');
|
||||
services.forEach(s => {
|
||||
list.innerHTML += `
|
||||
<div>
|
||||
<p><strong>${s.name}</strong> — ${s.price}₽ — ${s.is_active ? 'Активна' : 'Неактивна'}</p>
|
||||
<button onclick="editService(${s.id})">Редактировать</button>
|
||||
<button onclick="toggleService(${s.id}, ${s.is_active})">${s.is_active ? '❌ Деактивировать' : '✅ Активировать'}</button>
|
||||
<button onclick="deleteService(${s.id})">🗑️ Удалить</button>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
} catch (err) {
|
||||
alert('Ошибка загрузки услуг');
|
||||
}
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Ошибка сервера: ' + response.status);
|
||||
}
|
||||
|
||||
async function addService(event) {
|
||||
event.preventDefault();
|
||||
const formData = {
|
||||
name: document.getElementById('serviceName').value,
|
||||
description: document.getElementById('serviceDescription').value,
|
||||
duration_minutes: parseInt(document.getElementById('serviceDuration').value),
|
||||
price: parseFloat(document.getElementById('servicePrice').value),
|
||||
is_active: true
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/admin/services', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(formData)
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
alert('Услуга добавлена');
|
||||
document.getElementById('addServiceForm').reset();
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Ошибка добавления');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
const servicesList = document.getElementById('services-list');
|
||||
data.forEach(service => {
|
||||
const item = document.createElement('div');
|
||||
item.innerHTML = `
|
||||
<h3>${service.name}</h3>
|
||||
<p>Цена: ${service.price} ₽</p>
|
||||
<p>Описание: ${service.description || 'Нет описания'}</p>
|
||||
<hr>
|
||||
`;
|
||||
servicesList.appendChild(item);
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка:', error);
|
||||
document.body.innerHTML = `<h2 style="color: red;">Ошибка загрузки данных: ${error.message}</h2>`;
|
||||
});
|
||||
}
|
||||
|
||||
async function toggleService(id, isActive) {
|
||||
try {
|
||||
const res = await fetch(`/api/admin/services/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ is_active: !isActive })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
alert(`Услуга ${!isActive ? 'активирована' : 'деактивирована'}`);
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Ошибка');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteService(id) {
|
||||
if (confirm('Удалить услугу?')) {
|
||||
try {
|
||||
const res = await fetch(`/api/admin/services/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
alert('Услуга удалена');
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Ошибка');
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -128,28 +128,56 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Получить данные брони из localStorage (передается из services.html)
|
||||
const bookingData = JSON.parse(localStorage.getItem('lastBooking') || '{}');
|
||||
|
||||
if (bookingData.booking) {
|
||||
const booking = bookingData.booking;
|
||||
document.getElementById('bookingNumber').textContent = booking.bookingnumber;
|
||||
|
||||
// Заполнить детали (простые циклы для поиска)
|
||||
const services = JSON.parse(localStorage.getItem('services') || '[]');
|
||||
const service = services.find(s => s.id == booking.service_id);
|
||||
|
||||
document.querySelector('#bookingDetails .detail-row:nth-child(1) span:last-child').textContent = service ? service.name : 'Услуга';
|
||||
document.querySelector('#bookingDetails .detail-row:nth-child(4) span:last-child').textContent =
|
||||
`${booking.starttime.slice(0,5)}–${booking.endtime.slice(0,5)}`;
|
||||
document.querySelector('#bookingDetails .detail-row:nth-child(5) span:last-child').textContent =
|
||||
`${booking.service.price || '???'} ₽`;
|
||||
}
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
// Очистка localStorage через 30 секунд
|
||||
setTimeout(() => {
|
||||
localStorage.removeItem('lastBooking');
|
||||
}, 30000);
|
||||
if (!token) {
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
|
||||
window.onload = loadBookings;
|
||||
|
||||
async function loadBookings() {
|
||||
try {
|
||||
const res = await fetch('/api/bookings', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
const bookings = await res.json();
|
||||
|
||||
const list = document.getElementById('bookings-list');
|
||||
bookings.forEach(b => {
|
||||
list.innerHTML += `
|
||||
<div>
|
||||
<p><strong>${b.booking_number}</strong> — ${b.service.name} (${b.booking_date} ${b.start_time}) — ${b.status}</p>
|
||||
${b.status === 'confirmed' ? `<button onclick="cancelBooking(${b.id})">Отменить</button>` : ''}
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
} catch (err) {
|
||||
alert('Ошибка загрузки бронирований');
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelBooking(id) {
|
||||
try {
|
||||
const reason = prompt('Причина отмены (необязательно):');
|
||||
const res = await fetch(`/api/bookings/${id}/cancel`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ reason })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
alert('Бронь отменена');
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Ошибка отмены');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -152,19 +152,20 @@
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
// прокрутка к секции услуг
|
||||
document.querySelector('.hero-buttons .btn-secondary').onclick = function(e) {
|
||||
e.preventDefault();
|
||||
document.getElementById('services').scrollIntoView({
|
||||
behavior: 'smooth'
|
||||
});
|
||||
};
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
// Проверка авторизации
|
||||
if (localStorage.getItem('token')) {
|
||||
// Пользователь авторизован - можно добавить кнопку "Личный кабинет"
|
||||
console.log('Пользователь авторизован');
|
||||
}
|
||||
if (token) {
|
||||
// Если авторизован — показываем кнопки "Личный кабинет" и "Выход"
|
||||
document.querySelector('.auth-buttons').innerHTML = `
|
||||
<a href="my-bookings.html" class="btn btn-secondary">Личный кабинет</a>
|
||||
<a href="#" onclick="logout()" class="btn btn-primary">Выход</a>
|
||||
`;
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem('token');
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
@@ -212,11 +212,12 @@
|
||||
|
||||
const canCancel = booking.status === 'confirmed';
|
||||
|
||||
// ИСПРАВЛЕНО: используем правильные имена полей с подчёркиваниями
|
||||
row.innerHTML = `
|
||||
<td><strong>${booking.bookingnumber}</strong></td>
|
||||
<td>${booking.bookingdate} ${booking.starttime.slice(0,5)}–${booking.endtime.slice(0,5)}</td>
|
||||
<td>${booking.service ? booking.service.name : 'Удалена'}</td>
|
||||
<td>${booking.employee ? booking.employee.name : 'Не назначен'}</td>
|
||||
<td><strong>${booking.booking_number}</strong></td>
|
||||
<td>${booking.booking_date} ${booking.start_time.slice(0,5)}–${booking.end_time.slice(0,5)}</td>
|
||||
<td>${booking.service ? booking.service.name : 'Услуга удалена'}</td>
|
||||
<td>${booking.employee ? booking.employee.name : 'Сотрудник не назначен'}</td>
|
||||
<td><span class="status ${statusClass}">${booking.status}</span></td>
|
||||
<td>
|
||||
${canCancel ?
|
||||
@@ -266,7 +267,7 @@
|
||||
closeModal();
|
||||
loadBookings(); // Перезагрузить список
|
||||
} else {
|
||||
alert('Ошибка: ' + data.error);
|
||||
alert('Ошибка: ' + (data.message || data.error || 'Не удалось отменить бронь'));
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Ошибка сети');
|
||||
@@ -288,4 +289,4 @@
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
@@ -75,7 +75,6 @@
|
||||
<body>
|
||||
|
||||
<div class="container">
|
||||
<!-- Форма входа -->
|
||||
<div id="loginSection">
|
||||
<h2>Вход</h2>
|
||||
<div id="loginResult"></div>
|
||||
@@ -91,7 +90,6 @@
|
||||
<div class="toggle" onclick="showRegisterForm()">Нет аккаунта? Зарегистрироваться</div>
|
||||
</div>
|
||||
|
||||
<!-- Форма регистрации -->
|
||||
<div id="registerSection" style="display: none;">
|
||||
<h2>Регистрация</h2>
|
||||
<div id="registerResult"></div>
|
||||
@@ -117,106 +115,75 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Показать форму регистрации
|
||||
let token = localStorage.getItem('token');
|
||||
|
||||
// Проверка авторизации
|
||||
if (token) {
|
||||
window.location.href = 'index.html'; // ← ИСПРАВЛЕНО!
|
||||
}
|
||||
|
||||
// Регистрация
|
||||
async function registerUser() {
|
||||
const name = document.getElementById('nameReg').value;
|
||||
const email = document.getElementById('emailReg').value;
|
||||
const password = document.getElementById('passwordReg').value;
|
||||
const phone = document.getElementById('phoneReg').value || null;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, email, password, phone })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (res.ok) {
|
||||
alert('Регистрация успешна!');
|
||||
showLoginForm();
|
||||
} else {
|
||||
alert(data.message || 'Ошибка регистрации');
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Ошибка сети');
|
||||
}
|
||||
}
|
||||
|
||||
// Вход
|
||||
async function loginUser() {
|
||||
const email = document.getElementById('emailLogin').value;
|
||||
const password = document.getElementById('passwordLogin').value;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (res.ok) {
|
||||
localStorage.setItem('token', data.access_token);
|
||||
window.location.href = 'index.html'; // ← ИСПРАВЛЕНО!
|
||||
} else {
|
||||
alert(data.message || 'Неверный email или пароль');
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Ошибка сети');
|
||||
}
|
||||
}
|
||||
|
||||
// Переключение форм
|
||||
function showRegisterForm() {
|
||||
document.getElementById('loginSection').style.display = 'none';
|
||||
document.getElementById('registerSection').style.display = 'block';
|
||||
}
|
||||
|
||||
// Показать форму входа
|
||||
function showLoginForm() {
|
||||
document.getElementById('registerSection').style.display = 'none';
|
||||
document.getElementById('loginSection').style.display = 'block';
|
||||
}
|
||||
|
||||
// Функция регистрации
|
||||
function registerUser() {
|
||||
// Собираем данные из формы
|
||||
var name = document.getElementById('nameReg').value;
|
||||
var email = document.getElementById('emailReg').value;
|
||||
var password = document.getElementById('passwordReg').value;
|
||||
var phone = document.getElementById('phoneReg').value || null;
|
||||
|
||||
// Подготавливаем данные для отправки
|
||||
var data = {
|
||||
name: name,
|
||||
email: email,
|
||||
password: password,
|
||||
phone: phone
|
||||
};
|
||||
|
||||
// Отправляем POST-запрос на сервер
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open("POST", "/api/register", true);
|
||||
xhr.setRequestHeader("Content-Type", "application/json");
|
||||
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState === 4) {
|
||||
var resultDiv = document.getElementById('registerResult');
|
||||
if (xhr.status === 200 || xhr.status === 201) {
|
||||
resultDiv.className = "message success";
|
||||
resultDiv.innerHTML = "Регистрация прошла успешно! Теперь войдите.";
|
||||
// Через 2 секунды переключим на форму входа
|
||||
setTimeout(function() {
|
||||
showLoginForm();
|
||||
resultDiv.innerHTML = "";
|
||||
}, 2000);
|
||||
} else {
|
||||
resultDiv.className = "message error";
|
||||
try {
|
||||
var response = JSON.parse(xhr.responseText);
|
||||
resultDiv.innerHTML = response.message || "Ошибка при регистрации";
|
||||
} catch (e) {
|
||||
resultDiv.innerHTML = "Неизвестная ошибка сервера";
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
xhr.send(JSON.stringify(data));
|
||||
}
|
||||
|
||||
// Функция входа
|
||||
function loginUser() {
|
||||
var email = document.getElementById('emailLogin').value;
|
||||
var password = document.getElementById('passwordLogin').value;
|
||||
|
||||
var data = {
|
||||
email: email,
|
||||
password: password
|
||||
};
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open("POST", "/api/login", true);
|
||||
xhr.setRequestHeader("Content-Type", "application/json");
|
||||
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState === 4) {
|
||||
var resultDiv = document.getElementById('loginResult');
|
||||
if (xhr.status === 200) {
|
||||
resultDiv.className = "message success";
|
||||
resultDiv.innerHTML = "Вход выполнен!";
|
||||
// Сохраняем токен в localStorage (чтобы потом использовать)
|
||||
var response = JSON.parse(xhr.responseText);
|
||||
localStorage.setItem('auth_token', response.token);
|
||||
// Перенаправляем на главную
|
||||
setTimeout(function() {
|
||||
window.location.href = "/";
|
||||
}, 1000);
|
||||
} else {
|
||||
resultDiv.className = "message error";
|
||||
try {
|
||||
var response = JSON.parse(xhr.responseText);
|
||||
resultDiv.innerHTML = response.message || "Неверный email или пароль";
|
||||
} catch (e) {
|
||||
resultDiv.innerHTML = "Ошибка при входе";
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
xhr.send(JSON.stringify(data));
|
||||
}
|
||||
</script>
|
||||
|
||||
</body>
|
||||
|
||||
@@ -142,11 +142,8 @@
|
||||
<label>Длительность</label>
|
||||
<input type="text" id="duration" readonly placeholder="Выберите услугу">
|
||||
</div>
|
||||
</div>
|
||||
<button class="book-btn" id="bookBtn" onclick="bookService()" disabled>
|
||||
Выбрать время →
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
|
||||
<!-- Календарь -->
|
||||
<div class="calendar-section">
|
||||
@@ -173,46 +170,242 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let services = [];
|
||||
let selectedServiceId = null;
|
||||
let selectedDate = null;
|
||||
let currentMonth = new Date().getMonth();
|
||||
let currentYear = new Date().getFullYear();
|
||||
let availableSlots = [];
|
||||
let token = localStorage.getItem('token');
|
||||
let services = [];
|
||||
let selectedServiceId = null;
|
||||
let selectedDate = null;
|
||||
let currentMonth = new Date().getMonth();
|
||||
let currentYear = new Date().getFullYear();
|
||||
let availableSlots = [];
|
||||
let token = localStorage.getItem('token');
|
||||
let selectedSlot = null;
|
||||
|
||||
// Проверка авторизации
|
||||
if (!token) {
|
||||
window.location.href = 'register-login.html';
|
||||
throw new Error('Нужна авторизация');
|
||||
}
|
||||
updateHeader();
|
||||
// Проверка авторизации
|
||||
if (!token) {
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
|
||||
// 1. Загрузить услуги при загрузке страницы
|
||||
window.onload = async function() {
|
||||
await loadServices();
|
||||
initCalendar();
|
||||
};
|
||||
// Загрузка страницы
|
||||
window.onload = async function() {
|
||||
// Убедимся, что элементы существуют
|
||||
if (!document.getElementById('serviceSelect')) {
|
||||
console.error('Элемент #serviceSelect не найден');
|
||||
return;
|
||||
}
|
||||
|
||||
// Загрузка услуг из API (только isactive=true)
|
||||
async function loadServices() {
|
||||
try {
|
||||
const response = await fetch('/api/admin/services', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
services = data.filter(service => service.isactive);
|
||||
const select = document.getElementById('serviceSelect');
|
||||
|
||||
select.innerHTML = '<option value="">Выберите услугу</option>';
|
||||
for (let service of services) {
|
||||
select.innerHTML += `<option value="${service.id}" data-duration="${service.durationminutes}">${service.name} (${service.durationminutes} мин) - ${service.price}₽</option>`;
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Ошибка загрузки услуг');
|
||||
try {
|
||||
await loadServices();
|
||||
initCalendar();
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки:', error);
|
||||
alert('Не удалось загрузить данные');
|
||||
}
|
||||
};
|
||||
|
||||
// ✅ 1. ЗАГРУЗКА УСЛУГ (публичный API)
|
||||
async function loadServices() {
|
||||
try {
|
||||
const response = await fetch('/api/services');
|
||||
const data = await response.json();
|
||||
|
||||
services = data.filter(service => service.is_active); // ← is_active, не isactive
|
||||
|
||||
const select = document.getElementById('serviceSelect');
|
||||
select.innerHTML = '<option value="">Выберите услугу</option>';
|
||||
|
||||
for (let service of services) {
|
||||
const option = document.createElement('option');
|
||||
option.value = service.id;
|
||||
option.textContent = `${service.name} (${service.duration_minutes} мин) - ${service.price}₽`;
|
||||
select.appendChild(option);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error('Ошибка загрузки услуг: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. При выборе услуги — показываем длительность
|
||||
document.getElementById('serviceSelect').onchange = function() {
|
||||
const serviceId = this.value;
|
||||
if (!serviceId) {
|
||||
document.getElementById('duration').value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
// Изменение услуги
|
||||
//document.getElementById('serviceSelect').onchange = function()//
|
||||
selectedServiceId = parseInt(serviceId);
|
||||
const service = services.find(s => s.id == serviceId);
|
||||
document.getElementById('duration').value = service ? service.duration_minutes + ' минут' : '';
|
||||
};
|
||||
|
||||
// 3. Календарь
|
||||
function initCalendar() {
|
||||
renderCalendar();
|
||||
}
|
||||
|
||||
function renderCalendar() {
|
||||
const monthYear = document.getElementById('monthYear');
|
||||
const calendarDays = document.getElementById('calendarDays');
|
||||
|
||||
if (!monthYear || !calendarDays) {
|
||||
console.error('Элементы календаря не найдены');
|
||||
return;
|
||||
}
|
||||
|
||||
const months = ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'];
|
||||
monthYear.textContent = `${months[currentMonth]} ${currentYear}`;
|
||||
|
||||
calendarDays.innerHTML = '';
|
||||
|
||||
const firstDay = new Date(currentYear, currentMonth, 1).getDay();
|
||||
const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
|
||||
|
||||
// Добавляем "серые" дни предыдущего месяца
|
||||
for (let i = 0; i < (firstDay === 0 ? 6 : firstDay - 1); i++) {
|
||||
const dayEl = document.createElement('div');
|
||||
dayEl.className = 'calendar-day other-month';
|
||||
calendarDays.appendChild(dayEl);
|
||||
}
|
||||
|
||||
// Добавляем дни текущего месяца
|
||||
const today = new Date();
|
||||
for (let day = 1; day <= daysInMonth; day++) {
|
||||
const dayEl = document.createElement('div');
|
||||
dayEl.className = 'calendar-day';
|
||||
dayEl.textContent = day;
|
||||
|
||||
const dateStr = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
||||
const dateObj = new Date(dateStr);
|
||||
|
||||
if (dateObj < today.setHours(0,0,0,0)) {
|
||||
dayEl.classList.add('disabled');
|
||||
} else {
|
||||
dayEl.onclick = () => selectDate(dateStr);
|
||||
}
|
||||
|
||||
calendarDays.appendChild(dayEl);
|
||||
}
|
||||
}
|
||||
|
||||
function prevMonth() {
|
||||
if (currentMonth === 0) {
|
||||
currentMonth = 11;
|
||||
currentYear--;
|
||||
} else {
|
||||
currentMonth--;
|
||||
}
|
||||
renderCalendar();
|
||||
}
|
||||
|
||||
function nextMonth() {
|
||||
if (currentMonth === 11) {
|
||||
currentMonth = 0;
|
||||
currentYear++;
|
||||
} else {
|
||||
currentMonth++;
|
||||
}
|
||||
renderCalendar();
|
||||
}
|
||||
|
||||
// 4. Выбор даты → загрузка слотов
|
||||
async function selectDate(dateStr) {
|
||||
if (!selectedServiceId) {
|
||||
alert('Сначала выберите услугу');
|
||||
return;
|
||||
}
|
||||
|
||||
selectedDate = dateStr;
|
||||
document.querySelectorAll('.calendar-day').forEach(el => el.classList.remove('selected'));
|
||||
event.target.classList.add('selected');
|
||||
|
||||
try {
|
||||
const url = `/api/availability?service_id=${selectedServiceId}&date=${dateStr}`;
|
||||
const response = await fetch(url);
|
||||
availableSlots = await response.json();
|
||||
|
||||
showSlots(availableSlots);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки слотов:', error);
|
||||
alert('Не удалось загрузить доступное время');
|
||||
}
|
||||
}
|
||||
|
||||
function showSlots(slots) {
|
||||
const slotsSection = document.getElementById('slotsSection');
|
||||
const slotsGrid = document.getElementById('slotsGrid');
|
||||
const confirmBtn = document.getElementById('confirmBookingBtn');
|
||||
|
||||
slotsSection.style.display = 'block';
|
||||
slotsGrid.innerHTML = '';
|
||||
|
||||
if (slots.length === 0) {
|
||||
slotsGrid.innerHTML = '<div class="no-slots">В этот день нет доступных слотов</div>';
|
||||
confirmBtn.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
selectedSlot = null; // ← Сбросьте перед новым выбором
|
||||
|
||||
slots.forEach(slot => {
|
||||
const slotEl = document.createElement('div');
|
||||
slotEl.className = 'slot';
|
||||
slotEl.textContent = `${slot.start} - ${slot.end}`;
|
||||
slotEl.onclick = () => {
|
||||
document.querySelectorAll('.slot').forEach(s => s.classList.remove('selected'));
|
||||
slotEl.classList.add('selected');
|
||||
selectedSlot = slot; // ← Присвойте значение
|
||||
confirmBtn.style.display = 'block';
|
||||
};
|
||||
slotsGrid.appendChild(slotEl);
|
||||
});
|
||||
}
|
||||
|
||||
// 5. Подтверждение бронирования
|
||||
async function confirmBooking() {
|
||||
if (!selectedServiceId || !selectedDate || !selectedSlot) {
|
||||
alert('Выберите всё: услугу, дату и время');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/bookings', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
service_id: selectedServiceId,
|
||||
employee_id: selectedSlot.employee_id,
|
||||
date: selectedDate,
|
||||
start_time: selectedSlot.start
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
alert('✅ Бронирование успешно создано!');
|
||||
window.location.href = 'my-bookings.html';
|
||||
} else {
|
||||
const err = await response.json();
|
||||
alert('Ошибка: ' + (err.message || 'Не удалось создать бронь'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка бронирования:', error);
|
||||
alert('Ошибка сети');
|
||||
}
|
||||
}
|
||||
|
||||
function updateHeader() {
|
||||
if (token) {
|
||||
document.getElementById('profileBtn').style.display = 'inline-block';
|
||||
document.getElementById('logoutBtn').style.display = 'inline-block';
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem('token');
|
||||
window.location.href = 'index.html';
|
||||
}
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user