Говорила мне мама...ну нахер эти ваши HDD
This commit is contained in:
+557
-115
@@ -1,133 +1,575 @@
|
||||
$(document).ready(function() {
|
||||
const regionList = $('#region-list');
|
||||
const userInfo = $('#user-info');
|
||||
const userList = $('#user-list');
|
||||
const curentRegion = $('#curent-region')
|
||||
const pagination = $('#pagination');
|
||||
let regions = [];
|
||||
let users = [];
|
||||
let selectedRegionName = null;
|
||||
let selectedRegionId = null;
|
||||
const regionsPerPage = 10;
|
||||
let currentPage = 1;
|
||||
let currentPage = 1;
|
||||
let totalPages = 1;
|
||||
const perPage = 10;
|
||||
let sortField = 'region_id';
|
||||
let sortOrder = 'asc';
|
||||
let currentFetchController = null;
|
||||
|
||||
// Загрузка регионов
|
||||
function loadRegions() {
|
||||
$.getJSON('/telezab/regions/get', function(data) {
|
||||
regions = data;
|
||||
regions.sort((a, b) => a.region_id - b.region_id); // Сортировка по региону
|
||||
renderRegions();
|
||||
renderPagination();
|
||||
}).fail(function() {
|
||||
console.error("Не удалось получить регионы.");
|
||||
});
|
||||
|
||||
// Переменные для систем
|
||||
let systemsCurrentPage = 1;
|
||||
let systemsTotalPages = 1;
|
||||
let systemsSortField = 'system_id';
|
||||
let systemsSortOrder = 'asc';
|
||||
|
||||
|
||||
// Инициализация Toastr
|
||||
toastr.options = {
|
||||
"closeButton": true,
|
||||
"debug": false,
|
||||
"newestOnTop": false,
|
||||
"progressBar": false,
|
||||
"positionClass": "toast-bottom-right",
|
||||
"preventDuplicates": false,
|
||||
"onclick": null,
|
||||
"showDuration": "300",
|
||||
"hideDuration": "1000",
|
||||
"timeOut": "5000",
|
||||
"extendedTimeOut": "1000",
|
||||
"showEasing": "swing",
|
||||
"hideEasing": "linear",
|
||||
"showMethod": "fadeIn",
|
||||
"hideMethod": "fadeOut"
|
||||
};
|
||||
|
||||
// Функция загрузки регионов
|
||||
function loadRegions(page) {
|
||||
if (page < 1 || page > totalPages) return;
|
||||
currentPage = page;
|
||||
|
||||
const url = `/telezab/rest/api/regions?page=${currentPage}&per_page=${perPage}&sort_field=${sortField}&sort_order=${sortOrder}`;
|
||||
|
||||
if (currentFetchController) {
|
||||
currentFetchController.abort();
|
||||
}
|
||||
currentFetchController = new AbortController();
|
||||
|
||||
// Загрузка пользователей
|
||||
function loadUsers() {
|
||||
$.getJSON('/telezab/users/get', function(data) {
|
||||
users = data;
|
||||
}).fail(function() {
|
||||
console.error("Не удалось получить пользователей.");
|
||||
fetch(url, { signal: currentFetchController.signal })
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
currentFetchController = null;
|
||||
totalPages = data.total_pages;
|
||||
updateRegionsTable(data.regions);
|
||||
updatePagination(data.current_page, data.total_pages);
|
||||
})
|
||||
.catch(error => {
|
||||
if (error.name === 'AbortError') {
|
||||
} else {
|
||||
console.error('Error fetching regions:', error);
|
||||
}
|
||||
currentFetchController = null;
|
||||
});
|
||||
}
|
||||
|
||||
function updateRegionsTable(regions) {
|
||||
const tableBody = document.getElementById('regions-table');
|
||||
if (tableBody) {
|
||||
tableBody.innerHTML = '';
|
||||
|
||||
regions.forEach(region => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${region.region_id}</td>
|
||||
<td>${region.name}</td>
|
||||
<td>
|
||||
<span id="region-status-label-${region.region_id}">${region.active ? 'Включен' : 'Выключен'}</span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="form-check form-switch me-2">
|
||||
<input class="form-check-input region-status-switch" type="checkbox" role="switch" id="region-status-${region.region_id}" data-id="${region.region_id}" ${region.active ? 'checked' : ''}>
|
||||
<label class="form-check-label" for="region-status-${region.region_id}"></label>
|
||||
</div>
|
||||
<button class="btn btn-sm btn-primary edit-name-btn me-2" data-id="${region.region_id}" data-name="${region.name}"><i class="bi bi-pencil"></i></button>
|
||||
<button class="btn btn-sm btn-info subscribers-btn me-2" data-id="${region.region_id}"><i class="bi bi-people"></i></button>
|
||||
<button class="btn btn-sm btn-danger delete-btn" data-id="${region.region_id}"><i class="bi bi-trash"></i></button>
|
||||
</div>
|
||||
</td>
|
||||
`;
|
||||
tableBody.appendChild(row);
|
||||
});
|
||||
|
||||
setupRegionActions();
|
||||
} else {
|
||||
console.error("regions-table element not found!");
|
||||
}
|
||||
}
|
||||
|
||||
// Отрисовка списка регионов
|
||||
function renderRegions() {
|
||||
regionList.empty();
|
||||
const start = (currentPage - 1) * regionsPerPage;
|
||||
const end = start + regionsPerPage;
|
||||
const paginatedRegions = regions.slice(start, end);
|
||||
function setupRegionActions() {
|
||||
document.querySelectorAll('th[data-sort]').forEach(th => {
|
||||
th.replaceWith(th.cloneNode(true)); // Удаляем все обработчики
|
||||
});
|
||||
|
||||
paginatedRegions.forEach(region => {
|
||||
const listItem = $('<a>', {
|
||||
href: '#',
|
||||
class: 'list-group-item list-group-item-action',
|
||||
text: `${region.region_name} (${region.region_id})`,
|
||||
'data-region-id': region.region_id,
|
||||
'data-region-name': region.region_name
|
||||
}).on('click', function() {
|
||||
selectedRegionId = $(this).data('region-id');
|
||||
selectedRegionName = $(this).data('region-name');
|
||||
showRegionDetails();
|
||||
document.querySelectorAll('.delete-btn').forEach(button => {
|
||||
button.addEventListener('click', () => deleteRegion(button.dataset.id));
|
||||
});
|
||||
document.querySelectorAll('.region-status-switch').forEach(switchElement => {
|
||||
switchElement.addEventListener('change', (event) => {
|
||||
const regionId = event.target.dataset.id;
|
||||
const active = event.target.checked;
|
||||
toggleRegionStatus(regionId, active);
|
||||
document.getElementById(`region-status-label-${regionId}`).textContent = active ? 'Включен' : 'Выключен';
|
||||
});
|
||||
});
|
||||
document.querySelectorAll('.edit-name-btn').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const regionId = button.dataset.id;
|
||||
const regionName = button.dataset.name;
|
||||
document.getElementById('old-region-name').value = regionName;
|
||||
document.getElementById('new-region-name').value = regionName;
|
||||
$('#editRegionNameModal').modal('show');
|
||||
|
||||
let timer = 5;
|
||||
document.getElementById('edit-region-name-timer').textContent = timer;
|
||||
const timerInterval = setInterval(() => {
|
||||
timer--;
|
||||
document.getElementById('edit-region-name-timer').textContent = timer;
|
||||
if (timer === 0) {
|
||||
clearInterval(timerInterval);
|
||||
document.getElementById('save-region-name-btn').removeAttribute('disabled');
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
document.getElementById('save-region-name-btn').addEventListener('click', () => {
|
||||
const newName = document.getElementById('new-region-name').value;
|
||||
updateRegionName(regionId, newName);
|
||||
$('#editRegionNameModal').modal('hide');
|
||||
}, { once: true }); // Удаляем обработчик после первого клика
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('.subscribers-btn').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const regionId = button.dataset.id;
|
||||
showRegionSubscribers(regionId);
|
||||
});
|
||||
});
|
||||
|
||||
function showRegionSubscribers(regionId) {
|
||||
fetch(`/telezab/rest/api/regions/${regionId}/subscribers`)
|
||||
.then(response => {
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
|
||||
|
||||
const tableBody = document.getElementById('regionSubscribersTableBody');
|
||||
tableBody.innerHTML = '';
|
||||
|
||||
if (data.subscribers && data.subscribers.length > 0) {
|
||||
data.subscribers.forEach(user => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${user.telegram_id}</td>
|
||||
<td>${user.email}</td>
|
||||
`;
|
||||
tableBody.appendChild(row);
|
||||
});
|
||||
} else {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `<td colspan="2">Нет подписчиков для этого региона.</td>`;
|
||||
tableBody.appendChild(row);
|
||||
}
|
||||
|
||||
$('#regionSubscribersModal').modal('show');
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка при получении подписчиков региона:', error);
|
||||
toastr.error('Ошибка при получении подписчиков региона. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
regionList.append(listItem);
|
||||
});
|
||||
}
|
||||
|
||||
// Отрисовка кнопок пагинации
|
||||
function renderPagination() {
|
||||
pagination.empty();
|
||||
const totalPages = Math.ceil(regions.length / regionsPerPage);
|
||||
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
const pageItem = $('<li>', {
|
||||
class: `page-item ${i === currentPage ? 'active' : ''}`
|
||||
}).append($('<a>', {
|
||||
class: 'page-link',
|
||||
href: '#',
|
||||
text: i
|
||||
}).on('click', function(e) {
|
||||
e.preventDefault();
|
||||
currentPage = i;
|
||||
renderRegions();
|
||||
renderPagination();
|
||||
}));
|
||||
pagination.append(pageItem);
|
||||
}
|
||||
}
|
||||
|
||||
// Показать детали региона
|
||||
function showRegionDetails() {
|
||||
userInfo.empty();
|
||||
userList.empty();
|
||||
curentRegion.empty(); // Очистить текущий элемент
|
||||
|
||||
// Найти текущий регион по selectedRegionId
|
||||
const selectedRegion = regions.find(region => region.region_name === selectedRegionName);
|
||||
|
||||
// Проверить, что регион найден
|
||||
if (selectedRegion) {
|
||||
// Создать и добавить заголовок h3 с именем региона
|
||||
var newHeading = $('<h3>').text(selectedRegion.region_name);
|
||||
$('#curent-region').append(newHeading);
|
||||
} else {
|
||||
$('#curent-region').text('Регион не найден.');
|
||||
}
|
||||
|
||||
// Фильтровать пользователей, подписанных на этот регион
|
||||
const subscribedUsers = users.filter(user =>
|
||||
user.subscriptions.split(', ').includes(selectedRegionId.toString())
|
||||
);
|
||||
|
||||
// Показать список пользователей или сообщение, если подписчиков нет
|
||||
if (subscribedUsers.length > 0) {
|
||||
subscribedUsers.forEach(user => {
|
||||
userList.append(`<li>${user.email}</li>`);
|
||||
function updateRegionName(regionId, newName) {
|
||||
fetch('/telezab/rest/api/regions', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ region_id: regionId, name: newName })
|
||||
})
|
||||
.then(() => {
|
||||
loadRegions(currentPage);
|
||||
toastr.success('Название региона изменено.');
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка при изменении названия региона:', error);
|
||||
toastr.error('Ошибка при изменении названия региона. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
} else {
|
||||
userInfo.text('Нет подписчиков на этот регион.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Инициализация
|
||||
loadRegions();
|
||||
loadUsers();
|
||||
|
||||
// Обработчики кнопок в модальном окне
|
||||
$('#delete-region').on('click', function() {
|
||||
// Функция удаления региона
|
||||
console.log('Удалить регион', selectedRegionId);
|
||||
document.querySelectorAll('th[data-sort]').forEach(th => {
|
||||
th.addEventListener('click', () => {
|
||||
const field = th.dataset.sort;
|
||||
if (field === sortField) {
|
||||
sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
sortField = field;
|
||||
sortOrder = 'asc';
|
||||
}
|
||||
loadRegions(currentPage);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
$('#disable-region').on('click', function() {
|
||||
// Функция отключения региона
|
||||
console.log('Отключить регион', selectedRegionId);
|
||||
});
|
||||
function toggleRegionStatus(regionId, active) {
|
||||
fetch('/telezab/rest/api/regions', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ region_id: regionId, active: active })
|
||||
})
|
||||
.then(() => {
|
||||
loadRegions(currentPage);
|
||||
if (active) {
|
||||
toastr.success('Регион активирован.');
|
||||
} else {
|
||||
toastr.success('Регион деактивирован.');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка при изменении статуса региона:', error);
|
||||
toastr.error('Ошибка при изменении статуса региона. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
}
|
||||
|
||||
$('#activate-region').on('click', function() {
|
||||
// Функция активации региона
|
||||
console.log('Активировать регион', selectedRegionId);
|
||||
function deleteRegion(regionId) {
|
||||
$('#deleteRegionModal').modal('show'); // Открываем модальное окно
|
||||
|
||||
$(document).ready(function() {
|
||||
// Обработчик события input для текстового поля подтверждения
|
||||
$('#deleteConfirmationInput').on('input', function() {
|
||||
const inputValue = $(this).val();
|
||||
if (inputValue === 'УДАЛИТЬ') {
|
||||
$('#confirmDeleteButton').prop('disabled', false); // Активируем кнопку "Удалить"
|
||||
} else {
|
||||
$('#confirmDeleteButton').prop('disabled', true); // Деактивируем кнопку "Удалить"
|
||||
}
|
||||
});
|
||||
|
||||
// Обработчик события click для кнопки "Удалить"
|
||||
$('#confirmDeleteButton').on('click', function() {
|
||||
fetch(`/telezab/rest/api/regions?region_id=${regionId}`, { method: 'DELETE' })
|
||||
.then(() => {
|
||||
loadRegions(currentPage);
|
||||
toastr.success('Регион успешно удален.');
|
||||
$('#deleteRegionModal').modal('hide'); // Закрываем модальное окно
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка при удалении региона:', error);
|
||||
toastr.error('Ошибка при удалении региона. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
});
|
||||
|
||||
// Обработчик события hidden.bs.modal для модального окна
|
||||
$('#deleteRegionModal').on('hidden.bs.modal', function() {
|
||||
$('#deleteConfirmationInput').val(''); // Очищаем текстовое поле при закрытии модального окна
|
||||
$('#confirmDeleteButton').prop('disabled', true); // Деактивируем кнопку "Удалить"
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
document.getElementById('add-region-form').addEventListener('submit', (event) => {
|
||||
event.preventDefault();
|
||||
const regionId = document.getElementById('region-id').value;
|
||||
const regionName = document.getElementById('region-name').value;
|
||||
const regionActive = document.getElementById('region-active').checked;
|
||||
|
||||
// Проверка, что все символы в regionId являются числами
|
||||
if (!/^\d+$/.test(regionId)) {
|
||||
toastr.error('ID региона должен содержать только числа.');
|
||||
return; // Прерываем выполнение функции
|
||||
}
|
||||
|
||||
fetch('/telezab/rest/api/regions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ region_id: regionId, name: regionName, active: regionActive })
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
|
||||
|
||||
const responseData = data[0];
|
||||
const statusCode = data[1];
|
||||
|
||||
if (statusCode === 409) {
|
||||
toastr.error(responseData.message);
|
||||
throw new Error(responseData.message);
|
||||
} else if (statusCode === 201) {
|
||||
document.getElementById('region-id').value = '';
|
||||
document.getElementById('region-name').value = '';
|
||||
document.getElementById('region-active').checked = true;
|
||||
loadRegions(currentPage);
|
||||
toastr.success('Регион успешно добавлен.');
|
||||
$('#addRegionModal').modal('hide');
|
||||
} else {
|
||||
throw new Error('Неизвестный код состояния ответа');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка при добавлении региона:', error);
|
||||
if (error.message !== 'Регион с таким ID уже существует') {
|
||||
toastr.error('Ошибка при добавлении региона. Пожалуйста, попробуйте позже.');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Функция обновления пагинации
|
||||
function updatePagination(currentPage, totalPages) {
|
||||
const paginationContainer = document.getElementById('pagination');
|
||||
paginationContainer.innerHTML = '';
|
||||
|
||||
const prevButton = document.createElement('li');
|
||||
prevButton.classList.add('page-item');
|
||||
prevButton.classList.toggle('disabled', currentPage === 1);
|
||||
prevButton.innerHTML = `<a class="page-link" href="#" aria-label="Previous" onclick="loadRegions(${currentPage - 1})">«</a>`;
|
||||
paginationContainer.appendChild(prevButton);
|
||||
|
||||
for (let page = 1; page <= totalPages; page++) {
|
||||
const pageItem = document.createElement('li');
|
||||
pageItem.classList.add('page-item');
|
||||
pageItem.classList.toggle('active', page === currentPage);
|
||||
|
||||
const pageLink = document.createElement('a');
|
||||
pageLink.classList.add('page-link');
|
||||
pageLink.href = "#";
|
||||
pageLink.textContent = page;
|
||||
pageLink.onclick = () => loadRegions(page);
|
||||
|
||||
pageItem.appendChild(pageLink);
|
||||
paginationContainer.appendChild(pageItem);
|
||||
}
|
||||
|
||||
const nextButton = document.createElement('li');
|
||||
nextButton.classList.add('page-item');
|
||||
nextButton.classList.toggle('disabled', currentPage === totalPages);
|
||||
nextButton.innerHTML = `<a class="page-link" href="#" aria-label="Next" onclick="loadRegions(${currentPage + 1})">»</a>`;
|
||||
paginationContainer.appendChild(nextButton);
|
||||
}
|
||||
|
||||
// Функция загрузки систем
|
||||
function loadSystems(page) {
|
||||
if (page < 1 || page > systemsTotalPages) return;
|
||||
systemsCurrentPage = page;
|
||||
|
||||
const url = `/telezab/rest/api/systems?page=${systemsCurrentPage}&per_page=${perPage}&sort_field=${systemsSortField}&sort_order=${systemsSortOrder}`;
|
||||
|
||||
if (currentFetchController) {
|
||||
currentFetchController.abort();
|
||||
}
|
||||
currentFetchController = new AbortController();
|
||||
|
||||
fetch(url, { signal: currentFetchController.signal })
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
currentFetchController = null;
|
||||
systemsTotalPages = data.total_pages;
|
||||
updateSystemsTable(data.systems);
|
||||
updatePagination(data.current_page, data.total_pages);
|
||||
})
|
||||
.catch(error => {
|
||||
if (error.name === 'AbortError') {
|
||||
} else {
|
||||
console.error('Error fetching systems:', error);
|
||||
}
|
||||
currentFetchController = null;
|
||||
});
|
||||
}
|
||||
|
||||
// Функция обновления таблицы систем
|
||||
function updateSystemsTable(systems) {
|
||||
const tableBody = document.getElementById('systems-table');
|
||||
if (tableBody) {
|
||||
tableBody.innerHTML = '';
|
||||
|
||||
systems.forEach(system => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${system.system_id}</td>
|
||||
<td>${system.system_name}</td>
|
||||
<td>${system.name}</td>
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<button class="btn btn-sm btn-primary edit-name-btn me-2" data-id="${system.system_id}" data-name="${system.name}"><i class="bi bi-pencil"></i></button>
|
||||
<button class="btn btn-sm btn-danger delete-btn" data-id="${system.system_id}"><i class="bi bi-trash"></i></button>
|
||||
</div>
|
||||
</td>
|
||||
`;
|
||||
tableBody.appendChild(row);
|
||||
});
|
||||
|
||||
setupSystemActions();
|
||||
} else {
|
||||
console.error("systems-table element not found!");
|
||||
}
|
||||
}
|
||||
|
||||
// Функция настройки действий для систем
|
||||
function setupSystemActions() {
|
||||
document.querySelectorAll('th[data-sort]').forEach(th => {
|
||||
th.replaceWith(th.cloneNode(true)); // Удаляем все обработчики
|
||||
});
|
||||
|
||||
document.querySelectorAll('.delete-btn').forEach(button => {
|
||||
button.addEventListener('click', () => deleteSystem(button.dataset.id));
|
||||
});
|
||||
|
||||
document.querySelectorAll('.edit-name-btn').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const systemId = button.dataset.id;
|
||||
const systemName = button.dataset.name;
|
||||
document.getElementById('old-system-name').value = systemName;
|
||||
document.getElementById('new-system-name').value = systemName;
|
||||
$('#editSystemNameModal').modal('show');
|
||||
|
||||
let timer = 5;
|
||||
document.getElementById('edit-system-name-timer').textContent = timer;
|
||||
const timerInterval = setInterval(() => {
|
||||
timer--;
|
||||
document.getElementById('edit-system-name-timer').textContent = timer;
|
||||
if (timer === 0) {
|
||||
clearInterval(timerInterval);
|
||||
document.getElementById('saveSystemNameBtn').removeAttribute('disabled'); // Изменяем идентификатор
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
document.getElementById('saveSystemNameBtn').addEventListener('click', () => { // Изменяем идентификатор
|
||||
const newName = document.getElementById('new-system-name').value;
|
||||
updateSystemName(systemId, newName);
|
||||
$('#editSystemNameModal').modal('hide');
|
||||
}, { once: true });
|
||||
});
|
||||
});
|
||||
|
||||
function updateSystemName(systemId, newName) {
|
||||
fetch('/telezab/rest/api/systems', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ system_id: systemId, name: newName })
|
||||
})
|
||||
.then(() => {
|
||||
loadSystems(systemsCurrentPage);
|
||||
toastr.success('Название системы изменено.');
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка при изменении названия системы:', error);
|
||||
toastr.error('Ошибка при изменении названия системы. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
}
|
||||
|
||||
function deleteSystem(systemId) {
|
||||
$('#deleteSystemModal').modal('show'); // Открываем модальное окно
|
||||
|
||||
$(document).ready(function() {
|
||||
console.log(document.getElementById('deleteSystemConfirmationInput'));
|
||||
// Обработчик события input для текстового поля подтверждения
|
||||
$('#deleteSystemConfirmationInput').on('input', function() {
|
||||
const inputValue = $(this).val();
|
||||
console.log('inputValue:', inputValue); // Логируем значение inputValue
|
||||
if (inputValue === 'УДАЛИТЬ') {
|
||||
$('#confirmDeleteSystemButton').prop('disabled', false);
|
||||
console.log('Кнопка активирована'); // Логируем активацию кнопки
|
||||
} else {
|
||||
$('#confirmDeleteSystemButton').prop('disabled', true);
|
||||
console.log('Кнопка деактивирована'); // Логируем деактивацию кнопки
|
||||
}
|
||||
});
|
||||
|
||||
// Обработчик события click для кнопки "Удалить"
|
||||
$('#confirmDeleteSystemButton').on('click', function() {
|
||||
fetch(`/telezab/rest/api/systems?system_id=${systemId}`, { method: 'DELETE' })
|
||||
.then(() => {
|
||||
loadSystems(systemsCurrentPage);
|
||||
toastr.success('Система успешно удалена.');
|
||||
$('#deleteSystemModal').modal('hide'); // Закрываем модальное окно
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка при удалении системы:', error);
|
||||
toastr.error('Ошибка при удалении системы. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
});
|
||||
|
||||
// Обработчик события hidden.bs.modal для модального окна
|
||||
$('#deleteSystemModal').on('hidden.bs.modal', function() {
|
||||
$('#deleteSystemConfirmationInput').val(''); // Очищаем текстовое поле при закрытии модального окна
|
||||
$('#confirmDeleteSystemButton').prop('disabled', true); // Деактивируем кнопку "Удалить"
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelectorAll('th[data-sort]').forEach(th => {
|
||||
th.addEventListener('click', () => {
|
||||
const field = th.dataset.sort;
|
||||
if (field === systemsSortField) {
|
||||
systemsSortOrder = systemsSortOrder === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
systemsSortField = field;
|
||||
systemsSortOrder = 'asc';
|
||||
}
|
||||
loadSystems(systemsCurrentPage);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Функция добавления системы
|
||||
document.getElementById('add-system-form').addEventListener('submit', (event) => {
|
||||
event.preventDefault();
|
||||
const systemId = document.getElementById('system-id').value;
|
||||
const systemNameLat = document.getElementById('system-name-lat').value;
|
||||
const systemNameCyr = document.getElementById('system-name-cyr').value;
|
||||
|
||||
if (!/^\d+$/.test(systemId)) {
|
||||
toastr.error('ID системы должен содержать только числа.');
|
||||
return;
|
||||
}
|
||||
|
||||
fetch('/telezab/rest/api/systems', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ system_id: systemId, system_name: systemNameLat, name: systemNameCyr })
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
// Если статус ответа не OK, обрабатываем ошибку
|
||||
return response.json().then(errorData => {
|
||||
throw new Error(errorData.message || 'Ошибка добавления системы');
|
||||
});
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
// Обрабатываем успешное добавление системы
|
||||
document.getElementById('system-id').value = '';
|
||||
document.getElementById('system-name-lat').value = '';
|
||||
document.getElementById('system-name-cyr').value = '';
|
||||
loadSystems(systemsCurrentPage); // Обновляем таблицу систем
|
||||
toastr.success('Система успешно добавлена.');
|
||||
$('#addSystemModal').modal('hide');
|
||||
})
|
||||
.catch(error => {
|
||||
// Обрабатываем ошибки
|
||||
console.error('Ошибка при добавлении системы:', error);
|
||||
toastr.error(error.message || 'Ошибка при добавлении системы. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
// Запуск загрузки данных
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const regionsTab = document.getElementById('regions-tab');
|
||||
const systemsTab = document.getElementById('systems-tab');
|
||||
|
||||
// Обработчик для вкладки "Регионы"
|
||||
regionsTab.addEventListener('shown.bs.tab', () => {
|
||||
loadRegions(currentPage);
|
||||
});
|
||||
|
||||
// Обработчик для вкладки "Системы"
|
||||
systemsTab.addEventListener('shown.bs.tab', () => {
|
||||
loadSystems(systemsCurrentPage);
|
||||
});
|
||||
|
||||
// Инициализация загрузки данных для активной вкладки
|
||||
if (regionsTab.classList.contains('active')) {
|
||||
loadRegions(currentPage);
|
||||
}
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
!function(e){e(["jquery"],function(e){return function(){function t(e,t,n){return f({type:O.error,iconClass:g().iconClasses.error,message:e,optionsOverride:n,title:t})}function n(t,n){return t||(t=g()),v=e("#"+t.containerId),v.length?v:(n&&(v=c(t)),v)}function i(e,t,n){return f({type:O.info,iconClass:g().iconClasses.info,message:e,optionsOverride:n,title:t})}function o(e){w=e}function s(e,t,n){return f({type:O.success,iconClass:g().iconClasses.success,message:e,optionsOverride:n,title:t})}function a(e,t,n){return f({type:O.warning,iconClass:g().iconClasses.warning,message:e,optionsOverride:n,title:t})}function r(e){var t=g();v||n(t),l(e,t)||u(t)}function d(t){var i=g();return v||n(i),t&&0===e(":focus",t).length?void h(t):void(v.children().length&&v.remove())}function u(t){for(var n=v.children(),i=n.length-1;i>=0;i--)l(e(n[i]),t)}function l(t,n){return t&&0===e(":focus",t).length?(t[n.hideMethod]({duration:n.hideDuration,easing:n.hideEasing,complete:function(){h(t)}}),!0):!1}function c(t){return v=e("<div/>").attr("id",t.containerId).addClass(t.positionClass).attr("aria-live","polite").attr("role","alert"),v.appendTo(e(t.target)),v}function p(){return{tapToDismiss:!0,toastClass:"toast",containerId:"toast-container",debug:!1,showMethod:"fadeIn",showDuration:300,showEasing:"swing",onShown:void 0,hideMethod:"fadeOut",hideDuration:1e3,hideEasing:"swing",onHidden:void 0,extendedTimeOut:1e3,iconClasses:{error:"toast-error",info:"toast-info",success:"toast-success",warning:"toast-warning"},iconClass:"toast-info",positionClass:"toast-top-right",timeOut:5e3,titleClass:"toast-title",messageClass:"toast-message",target:"body",closeHtml:'<button type="button">×</button>',newestOnTop:!0,preventDuplicates:!1,progressBar:!1}}function m(e){w&&w(e)}function f(t){function i(t){return!e(":focus",l).length||t?(clearTimeout(O.intervalId),l[r.hideMethod]({duration:r.hideDuration,easing:r.hideEasing,complete:function(){h(l),r.onHidden&&"hidden"!==b.state&&r.onHidden(),b.state="hidden",b.endTime=new Date,m(b)}})):void 0}function o(){(r.timeOut>0||r.extendedTimeOut>0)&&(u=setTimeout(i,r.extendedTimeOut),O.maxHideTime=parseFloat(r.extendedTimeOut),O.hideEta=(new Date).getTime()+O.maxHideTime)}function s(){clearTimeout(u),O.hideEta=0,l.stop(!0,!0)[r.showMethod]({duration:r.showDuration,easing:r.showEasing})}function a(){var e=(O.hideEta-(new Date).getTime())/O.maxHideTime*100;f.width(e+"%")}var r=g(),d=t.iconClass||r.iconClass;if("undefined"!=typeof t.optionsOverride&&(r=e.extend(r,t.optionsOverride),d=t.optionsOverride.iconClass||d),r.preventDuplicates){if(t.message===C)return;C=t.message}T++,v=n(r,!0);var u=null,l=e("<div/>"),c=e("<div/>"),p=e("<div/>"),f=e("<div/>"),w=e(r.closeHtml),O={intervalId:null,hideEta:null,maxHideTime:null},b={toastId:T,state:"visible",startTime:new Date,options:r,map:t};return t.iconClass&&l.addClass(r.toastClass).addClass(d),t.title&&(c.append(t.title).addClass(r.titleClass),l.append(c)),t.message&&(p.append(t.message).addClass(r.messageClass),l.append(p)),r.closeButton&&(w.addClass("toast-close-button").attr("role","button"),l.prepend(w)),r.progressBar&&(f.addClass("toast-progress"),l.prepend(f)),l.hide(),r.newestOnTop?v.prepend(l):v.append(l),l[r.showMethod]({duration:r.showDuration,easing:r.showEasing,complete:r.onShown}),r.timeOut>0&&(u=setTimeout(i,r.timeOut),O.maxHideTime=parseFloat(r.timeOut),O.hideEta=(new Date).getTime()+O.maxHideTime,r.progressBar&&(O.intervalId=setInterval(a,10))),l.hover(s,o),!r.onclick&&r.tapToDismiss&&l.click(i),r.closeButton&&w&&w.click(function(e){e.stopPropagation?e.stopPropagation():void 0!==e.cancelBubble&&e.cancelBubble!==!0&&(e.cancelBubble=!0),i(!0)}),r.onclick&&l.click(function(){r.onclick(),i()}),m(b),r.debug&&console&&console.log(b),l}function g(){return e.extend({},p(),b.options)}function h(e){v||(v=n()),e.is(":visible")||(e.remove(),e=null,0===v.children().length&&(v.remove(),C=void 0))}var v,w,C,T=0,O={error:"error",info:"info",success:"success",warning:"warning"},b={clear:r,remove:d,error:t,getContainer:n,info:i,options:{},subscribe:o,success:s,version:"2.1.0",warning:a};return b}()})}("function"==typeof define&&define.amd?define:function(e,t){"undefined"!=typeof module&&module.exports?module.exports=t(require("jquery")):window.toastr=t(window.jQuery)});
|
||||
//# sourceMappingURL=toastr.js.map
|
||||
+242
-29
@@ -1,6 +1,26 @@
|
||||
let currentPage = 1;
|
||||
let totalPages = 1;
|
||||
const perPage = 20;
|
||||
let allUsers = []; // Добавляем массив для хранения всех пользователей
|
||||
const perPage = 10;
|
||||
|
||||
// Инициализация Toastr
|
||||
toastr.options = {
|
||||
"closeButton": true,
|
||||
"debug": false,
|
||||
"newestOnTop": false,
|
||||
"progressBar": false,
|
||||
"positionClass": "toast-bottom-right",
|
||||
"preventDuplicates": false,
|
||||
"onclick": null,
|
||||
"showDuration": "300",
|
||||
"hideDuration": "1000",
|
||||
"timeOut": "5000",
|
||||
"extendedTimeOut": "1000",
|
||||
"showEasing": "swing",
|
||||
"hideEasing": "linear",
|
||||
"showMethod": "fadeIn",
|
||||
"hideMethod": "fadeOut"
|
||||
};
|
||||
|
||||
// Функция загрузки пользователей
|
||||
function loadUsers(page) {
|
||||
@@ -11,11 +31,13 @@ function loadUsers(page) {
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
totalPages = data.total_pages;
|
||||
allUsers = data.users; // Сохраняем всех пользователей
|
||||
updateUsersTable(data.users);
|
||||
updatePagination(data.current_page, data.total_pages);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error fetching users:', error);
|
||||
toastr.error('Ошибка загрузки пользователей. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -27,13 +49,13 @@ function updateUsersTable(users) {
|
||||
users.forEach(user => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${user.id}</td>
|
||||
<td>${user.username}</td>
|
||||
<td>${user.chat_id}</td>
|
||||
<td>${user.telegram_id}</td>
|
||||
<td>${user.email}</td>
|
||||
<td>${user.subscriptions.join(', ') || 'Нет подписок'}</td>
|
||||
<td>${user.disaster_only}</td>
|
||||
<td>${user.status}</td>
|
||||
<td><button class="btn btn-primary editUserBtn" data-id="${user.id}">Редактировать</button></td>
|
||||
<td><button class="btn btn-primary editUserBtn" data-id="${user.chat_id}">Редактировать</button></td>
|
||||
`;
|
||||
tableBody.appendChild(row);
|
||||
});
|
||||
@@ -41,6 +63,7 @@ function updateUsersTable(users) {
|
||||
setupEditButtons();
|
||||
}
|
||||
|
||||
|
||||
// Функция для обработки кнопок "Редактировать"
|
||||
function setupEditButtons() {
|
||||
document.querySelectorAll(".editUserBtn").forEach(button => {
|
||||
@@ -51,29 +74,29 @@ function setupEditButtons() {
|
||||
});
|
||||
}
|
||||
|
||||
// Функция открытия модального окна
|
||||
function openUserModal(userId) {
|
||||
fetch(`/telezab/rest/api/users/${userId}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
document.getElementById("userId").innerText = data.id;
|
||||
document.getElementById("username").innerText = data.username;
|
||||
document.getElementById("userId").innerText = data.chat_id;
|
||||
document.getElementById("telegram_id").innerText = data.telegram_id;
|
||||
document.getElementById("userEmail").innerText = data.email;
|
||||
|
||||
const blockBtn = document.getElementById("toggleBlockUser");
|
||||
blockBtn.innerText = data.blocked ? "Разблокировать" : "Заблокировать";
|
||||
blockBtn.onclick = function () {
|
||||
toggleUserBlock(userId);
|
||||
};
|
||||
|
||||
document.getElementById("viewUserEvents").onclick = function () {
|
||||
viewUserEvents(userId);
|
||||
// Устанавливаем обработчик событий один раз
|
||||
blockBtn.onclick = function () {
|
||||
toggleUserBlock(userId, data.blocked); // Передаём текущий статус
|
||||
};
|
||||
|
||||
document.getElementById("deleteUser").onclick = function () {
|
||||
deleteUser(userId);
|
||||
};
|
||||
|
||||
// Загрузка событий пользователя
|
||||
loadUserEvents(data.chat_id);
|
||||
|
||||
// Использование Bootstrap для показа модального окна
|
||||
var myModal = new bootstrap.Modal(document.getElementById('userModal'), {
|
||||
keyboard: false
|
||||
@@ -82,9 +105,52 @@ function openUserModal(userId) {
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error fetching user data:', error);
|
||||
toastr.error('Ошибка загрузки данных пользователя. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
}
|
||||
|
||||
// Функция форматирования времени
|
||||
function formatDate(isoString) {
|
||||
const date = new Date(isoString);
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0'); // Месяцы с 0, поэтому +1
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const hours = String(date.getHours()).padStart(2, '0');
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||||
const seconds = String(date.getSeconds()).padStart(2, '0');
|
||||
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
|
||||
}
|
||||
|
||||
// Функция загрузки событий пользователя
|
||||
function loadUserEvents(chatId) {
|
||||
fetch(`/telezab/rest/api/user_events/${chatId}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const tableBody = document.getElementById('userEventsTable').querySelector('tbody');
|
||||
tableBody.innerHTML = '';
|
||||
|
||||
if (data && data.length > 0) { // Проверка массива данных
|
||||
data.forEach(event => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${event.action}</td>
|
||||
<td>${formatDate(event.timestamp)}</td> <!-- Форматируем дату -->
|
||||
`;
|
||||
tableBody.appendChild(row);
|
||||
});
|
||||
} else {
|
||||
tableBody.innerHTML = '<tr><td colspan="2">События не найдены</td></tr>';
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error fetching user events:', error);
|
||||
toastr.error('Ошибка загрузки событий пользователя. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Обработчик закрытия модального окна
|
||||
document.querySelector(".btn-close").addEventListener("click", function () {
|
||||
var myModal = new bootstrap.Modal(document.getElementById('userModal'));
|
||||
@@ -93,19 +159,26 @@ document.querySelector(".btn-close").addEventListener("click", function () {
|
||||
|
||||
|
||||
// Функция для блокировки/разблокировки пользователя
|
||||
function toggleUserBlock(userId) {
|
||||
function toggleUserBlock(userId, isBlocked) {
|
||||
fetch(`/telezab/rest/api/users/${userId}/block`, { method: "POST" })
|
||||
.then(() => {
|
||||
alert("Статус пользователя изменён");
|
||||
// Скрыть модальное окно с помощью Bootstrap
|
||||
var myModal = bootstrap.Modal.getInstance(document.getElementById('userModal'));
|
||||
if (myModal) {
|
||||
myModal.hide(); // Закрытие модального окна
|
||||
}
|
||||
|
||||
// Скрыть модальное окно с помощью Bootstrap (это не отменяет событий закрытия)
|
||||
var myModal = new bootstrap.Modal(document.getElementById('userModal'));
|
||||
myModal.hide(); // Закрытие модального окна
|
||||
|
||||
loadUsers(currentPage); // Перезагрузите список пользователей
|
||||
loadUsers(currentPage); // Перезагрузите список пользователей
|
||||
// Отображение toast-уведомления об успешном действии
|
||||
if (isBlocked) {
|
||||
toastr.success('Пользователь разблокирован.');
|
||||
} else {
|
||||
toastr.success('Пользователь заблокирован.');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error("Ошибка при изменении статуса пользователя:", error);
|
||||
toastr.error('Ошибка при изменении статуса пользователя. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -117,17 +190,81 @@ function viewUserEvents(userId) {
|
||||
|
||||
// Функция для удаления пользователя
|
||||
function deleteUser(userId) {
|
||||
if (confirm("Вы уверены, что хотите удалить пользователя?")) {
|
||||
fetch(`/telezab/rest/api/users/${userId}`, { method: "DELETE" })
|
||||
.then(() => {
|
||||
alert("Пользователь удалён");
|
||||
var myModal = new bootstrap.Modal(document.getElementById('userModal'));
|
||||
myModal.hide();
|
||||
loadUsers(currentPage); // Перезагрузите список пользователей
|
||||
});
|
||||
}
|
||||
// Показываем модальное окно
|
||||
$('#deleteConfirmationModal').modal('show');
|
||||
|
||||
// Обработчик кнопки подтверждения удаления
|
||||
document.getElementById('confirmDeleteButton').onclick = function () {
|
||||
const confirmationText = document.getElementById('confirmationText').value;
|
||||
if (confirmationText === 'УДАЛИТЬ') {
|
||||
fetch(`/telezab/rest/api/users/${userId}`, { method: "DELETE" })
|
||||
.then(() => {
|
||||
var myModal = bootstrap.Modal.getInstance(document.getElementById('userModal'));
|
||||
if (myModal) {
|
||||
myModal.hide();
|
||||
}
|
||||
loadUsers(currentPage);
|
||||
toastr.success('Пользователь успешно удален.');
|
||||
$('#deleteConfirmationModal').modal('hide'); // Скрываем модальное окно
|
||||
})
|
||||
.catch(error => {
|
||||
console.error("Ошибка при удалении пользователя:", error);
|
||||
toastr.error('Ошибка при удалении пользователя. Пожалуйста, попробуйте позже.');
|
||||
$('#deleteConfirmationModal').modal('hide'); // Скрываем модальное окно
|
||||
});
|
||||
} else {
|
||||
toastr.error('Неверное слово для подтверждения.');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function addNewUser() {
|
||||
const newUserId = document.getElementById("newUserId");
|
||||
const newUsername = document.getElementById("newUsername");
|
||||
const newUserEmail = document.getElementById("newUserEmail");
|
||||
|
||||
if (!newUserId.checkValidity() || !newUsername.checkValidity() || !newUserEmail.checkValidity()) {
|
||||
alert("Пожалуйста, заполните все поля корректно.");
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(`/telezab/rest/api/users`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({
|
||||
chat_id: newUserId.value,
|
||||
telegram_id: newUsername.value,
|
||||
user_email: newUserEmail.value
|
||||
})
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
return response.json().then(data => {
|
||||
throw new Error(data.error || 'Ошибка при добавлении пользователя.');
|
||||
});
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(() => {
|
||||
var myModal = bootstrap.Modal.getInstance(document.getElementById('addUserModal'));
|
||||
if (myModal) {
|
||||
myModal.hide();
|
||||
}
|
||||
loadUsers(currentPage);
|
||||
toastr.success('Пользователь успешно добавлен.');
|
||||
})
|
||||
.catch(error => {
|
||||
console.error("Ошибка при добавлении пользователя:", error);
|
||||
toastr.error(error.message || 'Ошибка при добавлении пользователя. Пожалуйста, попробуйте позже.');
|
||||
});
|
||||
}
|
||||
|
||||
// Добавляем обработчик событий для кнопки "Добавить"
|
||||
document.getElementById("addNewUser").addEventListener("click", addNewUser);
|
||||
|
||||
|
||||
window.onclick = function (event) {
|
||||
if (event.target === document.getElementById("userModal")) {
|
||||
$('#userModal').modal('hide'); // Закрываем модальное окно с помощью Bootstrap
|
||||
@@ -167,7 +304,83 @@ function updatePagination(currentPage, totalPages) {
|
||||
paginationContainer.appendChild(nextButton);
|
||||
}
|
||||
|
||||
$(document).ready(function() {
|
||||
// Обработчик событий для кнопки "Действия пользователя"
|
||||
$(document).on('click', '.user-events-button', function() {
|
||||
var chatId = $(this).data('chat-id');
|
||||
console.log("Chat ID:", chatId); // Логирование chatId
|
||||
|
||||
if (!chatId) return;
|
||||
|
||||
// Отправка AJAX-запроса к API
|
||||
$.ajax({
|
||||
url: '/telezab/rest/api/user_events/' + chatId,
|
||||
type: 'GET',
|
||||
success: function(data) {
|
||||
// Обработка успешного ответа
|
||||
var eventsHtml = '';
|
||||
if (data.events && data.events.length > 0) {
|
||||
data.events.forEach(function(event) {
|
||||
// Замените event.event_description и event.event_date на реальные поля из вашего ответа API
|
||||
eventsHtml += '<p>' + event.action + ' - ' + event.timestamp + '</p>';
|
||||
});
|
||||
} else {
|
||||
eventsHtml = '<p>Действия пользователя не найдены.</p>';
|
||||
}
|
||||
$('#userEventsModalBody').html(eventsHtml);
|
||||
$('#userEventsModal').modal('show'); // Открытие модального окна
|
||||
},
|
||||
error: function() {
|
||||
// Обработка ошибки
|
||||
$('#userEventsModalBody').html('<p>Ошибка загрузки действий пользователя.</p>');
|
||||
$('#userEventsModal').modal('show'); // Открытие модального окна
|
||||
}
|
||||
});
|
||||
});
|
||||
$(document).on('click', '.view-user', function() {
|
||||
var userId = $(this).data('id');
|
||||
$('#searchUsersModal').modal('hide'); // Скрываем модальное окно поиска
|
||||
openUserModal(userId); // Открываем модальное окно карточки пользователя
|
||||
});
|
||||
});
|
||||
|
||||
$('#searchUsersButton').click(function() {
|
||||
var telegramId = $('#searchTelegramId').val();
|
||||
var email = $('#searchEmail').val();
|
||||
|
||||
$.ajax({
|
||||
url: '/telezab/rest/api/users/search',
|
||||
type: 'GET',
|
||||
data: { telegram_id: telegramId, email: email },
|
||||
success: function(users) {
|
||||
var tableBody = $('#searchResultsTableModal tbody');
|
||||
tableBody.empty();
|
||||
|
||||
if (users.length > 0) {
|
||||
users.forEach(function(user) {
|
||||
tableBody.append(
|
||||
'<tr>' +
|
||||
'<td>' + user.chat_id + '</td>' +
|
||||
'<td>' + user.telegram_id + '</td>' +
|
||||
'<td>' + user.email + '</td>' +
|
||||
'<td><button class="btn btn-info view-user" data-id="' + user.chat_id + '">Карточка</button></td>' +
|
||||
'</tr>'
|
||||
);
|
||||
});
|
||||
$('#searchResults').show(); // Показываем блок с результатами поиска
|
||||
} else {
|
||||
$('#searchResults').hide(); // Скрываем блок, если нет результатов
|
||||
toastr.info('Пользователи не найдены.');
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
toastr.error('Ошибка при выполнении поиска.');
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
// Запуск загрузки данных
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
loadUsers(currentPage);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user