С 9:00 до 21:00 Без выходных

public/assets/js/task_manager_notifications.js

Вот содержимое файла public/assets/js/task_manager_notifications.js:

// Notification Management for Task Manager

// Function to display notifications for tasks
document.addEventListener('DOMContentLoaded', function() {
    // Fetch notifications when the page loads
    fetchNotifications();

    // Push notifications handling
    setupPushNotifications();
});

// Fetch notifications for the logged-in user
function fetchNotifications() {
    fetch('/index.php?route=extension/task_manager/getNotifications', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(notifications => {
        displayNotifications(notifications);
    })
    .catch(error => {
        console.error('Error fetching notifications:', error);
    });
}

// Display notifications in the user interface
function displayNotifications(notifications) {
    let notificationContainer = document.getElementById('notificationContainer');
    notificationContainer.innerHTML = '';

    notifications.forEach(notification => {
        let notificationElement = document.createElement('div');
        notificationElement.classList.add('notification');
        notificationElement.innerHTML = `
            <p><strong>${notification.title}</strong></p>
            <p>${notification.message}</p>
            <p><em>Received: ${notification.timestamp}</em></p>
            <button class="btn-mark-read" onclick="markAsRead(${notification.id})">Mark as Read</button>
        `;
        notificationContainer.appendChild(notificationElement);
    });
}

// Mark notification as read
function markAsRead(notificationId) {
    fetch('/index.php?route=extension/task_manager/markNotificationAsRead', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id: notificationId })
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            alert('Notification marked as read!');
            fetchNotifications(); // Refresh the notification list
        } else {
            alert('Error marking notification as read.');
        }
    })
    .catch(error => {
        console.error('Error marking notification as read:', error);
    });
}

// Setup Push Notifications
function setupPushNotifications() {
    if ('Notification' in window && navigator.serviceWorker) {
        // Request permission for push notifications
        Notification.requestPermission().then(permission => {
            if (permission === 'granted') {
                registerServiceWorkerForPush();
            } else {
                console.log('Push notification permission denied.');
            }
        });
    }
}

// Register service worker and setup push notifications
function registerServiceWorkerForPush() {
    navigator.serviceWorker.register('/service-worker.js').then(registration => {
        console.log('Service Worker registered for push notifications.');

        // Subscribe the user for push notifications
        registration.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: 'YOUR_PUBLIC_VAPID_KEY'
        }).then(subscription => {
            console.log('User subscribed to push notifications:', subscription);
            sendSubscriptionToServer(subscription);
        }).catch(error => {
            console.error('Error subscribing to push notifications:', error);
        });
    }).catch(error => {
        console.error('Error registering service worker:', error);
    });
}

// Send push notification subscription to server
function sendSubscriptionToServer(subscription) {
    fetch('/index.php?route=extension/task_manager/savePushSubscription', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(subscription)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            console.log('Push subscription saved to server.');
        } else {
            console.error('Failed to save push subscription to server.');
        }
    })
    .catch(error => {
        console.error('Error saving push subscription to server:', error);
    });
}

// Send a test notification
document.getElementById('sendTestNotification').addEventListener('click', function() {
    sendTestNotification();
});

// Send a test notification to the user
function sendTestNotification() {
    fetch('/index.php?route=extension/task_manager/sendTestNotification', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            alert('Test notification sent!');
        } else {
            alert('Error sending test notification.');
        }
    })
    .catch(error => {
        console.error('Error sending test notification:', error);
    });
}

Описание:

  1. Получение уведомлений: Сначала при загрузке страницы выполняется запрос на сервер для получения уведомлений для текущего пользователя с помощью функции fetchNotifications.

  2. Отображение уведомлений: Уведомления отображаются в виде карточек с кнопкой для пометки как "прочитанное". Пользователь может нажать на кнопку, чтобы пометить уведомление как прочитанное через markAsRead.

  3. Push уведомления: Если браузер поддерживает push уведомления и сервис-воркеры, запрашивается разрешение у пользователя на получение push уведомлений. При разрешении пользователь подписывается на push уведомления и их подписка отправляется на сервер.

  4. Тестовые уведомления: Реализована возможность отправить тестовое уведомление с помощью кнопки "Send Test Notification". Это может быть полезно для проверки работоспособности системы уведомлений.

  5. Сервис-воркеры: Код включает логику регистрации сервис-воркера для работы с push уведомлениями в браузере.

Этот скрипт обеспечивает интеграцию с системой уведомлений, позволяя пользователям получать уведомления о задачах и управлять ими.