This commit is contained in:
2026-07-20 14:46:07 +07:00
parent 476c41cf08
commit 4a159cad71
10 changed files with 2224 additions and 3 deletions

View File

@@ -596,11 +596,343 @@
});
}
function formatNotificationTime(value) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '';
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1000));
if (elapsedSeconds < 60) return 'Vừa xong';
if (elapsedSeconds < 3600) return `${Math.floor(elapsedSeconds / 60)} phút trước`;
if (elapsedSeconds < 86400) return `${Math.floor(elapsedSeconds / 3600)} giờ trước`;
if (elapsedSeconds < 604800) return `${Math.floor(elapsedSeconds / 86400)} ngày trước`;
return new Intl.DateTimeFormat('vi-VN', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
}).format(date);
}
function getNotificationIcon(notification) {
if (notification.isSystem) return 'campaign';
if (notification.severity === 'success') return 'check_circle';
if (notification.severity === 'warning') return 'warning';
if (notification.severity === 'error') return 'error';
if (notification.entityType === 'package') return 'inventory_2';
if (notification.entityType === 'application') return 'apps';
return 'notifications';
}
async function notificationRequest(url, options = {}) {
const response = await fetch(url, {
cache: 'no-store',
credentials: 'same-origin',
...options,
headers: {
Accept: 'application/json',
...(options.body ? { 'Content-Type': 'application/json' } : {}),
...(options.headers || {})
}
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(data.error || 'Không thể xử lý thông báo.');
}
return data;
}
function initNotificationCenter() {
const center = document.querySelector('[data-notification-center]');
if (!center) return;
const toggle = center.querySelector('[data-notification-toggle]');
const panel = center.querySelector('[data-notification-panel]');
const badge = center.querySelector('[data-notification-badge]');
const summary = center.querySelector('[data-notification-summary]');
const list = center.querySelector('[data-notification-list]');
const empty = center.querySelector('[data-notification-empty]');
const readAllButton = center.querySelector('[data-notification-read-all]');
const filterButtons = center.querySelectorAll('[data-notification-filter]');
const knownNotificationIds = new Set();
let currentFilter = 'all';
let initialized = false;
let loading = false;
let reloadPending = false;
function setPanelOpen(open) {
panel.hidden = !open;
toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
}
function setEmptyState(title, message, visible) {
const titleElement = empty.querySelector('strong');
const messageElement = empty.querySelector('span:last-child');
if (titleElement) titleElement.textContent = title;
if (messageElement) messageElement.textContent = message;
empty.hidden = !visible;
}
function updateUnreadCount(count) {
const unreadCount = Math.max(0, Number(count) || 0);
badge.textContent = unreadCount > 99 ? '99+' : String(unreadCount);
badge.hidden = unreadCount === 0;
summary.textContent = unreadCount > 0 ? `${unreadCount} thông báo chưa đọc` : 'Không có thông báo chưa đọc';
readAllButton.disabled = unreadCount === 0;
}
function renderNotifications(notifications) {
list.replaceChildren();
setEmptyState(
currentFilter === 'unread' ? 'Không có thông báo chưa đọc' : 'Chưa có thông báo',
'Các cập nhật quan trọng sẽ xuất hiện tại đây.',
notifications.length === 0
);
notifications.forEach((notification) => {
const item = document.createElement('button');
item.type = 'button';
item.className = `notification-item tone-${notification.severity || 'info'}${notification.isRead ? '' : ' unread'}`;
item.dataset.notificationId = notification.id;
const icon = document.createElement('span');
icon.className = 'notification-item-icon';
const iconGlyph = document.createElement('span');
iconGlyph.className = 'material-symbols-outlined';
iconGlyph.setAttribute('aria-hidden', 'true');
iconGlyph.textContent = getNotificationIcon(notification);
icon.appendChild(iconGlyph);
const copy = document.createElement('span');
copy.className = 'notification-item-copy';
const title = document.createElement('strong');
title.textContent = notification.title;
const message = document.createElement('span');
message.textContent = notification.message;
const time = document.createElement('time');
time.dateTime = notification.createdAt || '';
time.textContent = formatNotificationTime(notification.createdAt);
copy.append(title, message, time);
const unreadDot = document.createElement('span');
unreadDot.className = 'notification-unread-dot';
unreadDot.setAttribute('aria-label', notification.isRead ? 'Đã đọc' : 'Chưa đọc');
item.append(icon, copy, unreadDot);
item.addEventListener('click', async () => {
try {
if (!notification.isRead) {
await notificationRequest(`/api/notifications/${encodeURIComponent(notification.id)}/read`, {
method: 'POST'
});
notification.isRead = true;
item.classList.remove('unread');
await loadNotifications(false);
}
} catch (error) {
notify('warning', error.message);
}
if (
notification.actionUrl
&& notification.actionUrl.startsWith('/')
&& !notification.actionUrl.startsWith('//')
) {
window.location.assign(notification.actionUrl);
}
});
list.appendChild(item);
});
}
async function loadNotifications(announceNew = true) {
if (loading) {
reloadPending = true;
return;
}
loading = true;
try {
const data = await notificationRequest(
`/api/notifications?limit=20&unreadOnly=${currentFilter === 'unread' ? 'true' : 'false'}`
);
if (!data.available) {
badge.hidden = true;
summary.textContent = 'Chưa kích hoạt trong database';
readAllButton.disabled = true;
list.replaceChildren();
setEmptyState(
'Thông báo chưa khả dụng',
'Admin cần chạy migration 04_notifications.sql.',
true
);
return;
}
const notifications = Array.isArray(data.notifications) ? data.notifications : [];
if (initialized && announceNew) {
const importantNotification = notifications.find((notification) => (
!knownNotificationIds.has(notification.id)
&& !notification.isRead
&& ['warning', 'error'].includes(notification.severity)
));
if (importantNotification) {
notify(
importantNotification.severity === 'error' ? 'failure' : 'warning',
importantNotification.title
);
}
}
notifications.forEach((notification) => knownNotificationIds.add(notification.id));
initialized = true;
updateUnreadCount(data.unreadCount);
renderNotifications(notifications);
} catch (error) {
summary.textContent = 'Không thể tải thông báo';
setEmptyState('Không thể tải thông báo', 'Vui lòng thử lại sau.', true);
} finally {
loading = false;
if (reloadPending) {
reloadPending = false;
loadNotifications(false);
}
}
}
async function refreshUnreadCount() {
try {
const data = await notificationRequest('/api/notifications?countOnly=true');
if (!data.available) {
badge.hidden = true;
summary.textContent = 'Chưa kích hoạt trong database';
readAllButton.disabled = true;
return;
}
updateUnreadCount(data.unreadCount);
} catch (error) {
console.info('Cannot refresh notification count:', error);
}
}
toggle.addEventListener('click', () => {
const open = panel.hidden;
setPanelOpen(open);
if (open) loadNotifications(false);
});
readAllButton.addEventListener('click', async () => {
readAllButton.disabled = true;
try {
await notificationRequest('/api/notifications/read-all', { method: 'POST' });
await loadNotifications(false);
} catch (error) {
notify('failure', error.message);
}
});
filterButtons.forEach((button) => {
button.addEventListener('click', () => {
currentFilter = button.dataset.notificationFilter;
filterButtons.forEach((candidate) => {
const active = candidate === button;
candidate.classList.toggle('active', active);
candidate.setAttribute('aria-selected', active ? 'true' : 'false');
});
loadNotifications(false);
});
});
document.addEventListener('click', (event) => {
if (!panel.hidden && !center.contains(event.target)) {
setPanelOpen(false);
}
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && !panel.hidden) {
setPanelOpen(false);
toggle.focus();
}
});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
if (panel.hidden) refreshUnreadCount();
else loadNotifications(true);
}
});
document.addEventListener('notifications:refresh', () => {
if (panel.hidden) refreshUnreadCount();
else loadNotifications(false);
});
const broadcastButton = center.querySelector('[data-modal-open="systemNotificationModal"]');
if (broadcastButton) {
broadcastButton.addEventListener('click', () => setPanelOpen(false));
}
window.setInterval(() => {
if (document.visibilityState !== 'visible') return;
if (panel.hidden) refreshUnreadCount();
else loadNotifications(true);
}, 30000);
refreshUnreadCount();
}
function initSystemNotificationForm() {
const form = document.querySelector('[data-system-notification-form]');
if (!form) return;
form.addEventListener('submit', (event) => {
event.preventDefault();
if (!form.reportValidity()) return;
confirmAction('Gửi thông báo này tới tất cả tài khoản đang hoạt động?', async () => {
const submitButton = form.querySelector('[data-system-notification-submit]');
const formData = new FormData(form);
submitButton.disabled = true;
try {
const result = await notificationRequest('/api/notifications/broadcasts', {
method: 'POST',
body: JSON.stringify({
title: formData.get('title'),
severity: formData.get('severity'),
message: formData.get('message'),
actionUrl: formData.get('actionUrl')
})
});
closeModal(form.closest('.modal-backdrop'));
form.reset();
notify('success', `Đã gửi thông báo tới ${result.recipientCount || 0} người dùng.`);
document.dispatchEvent(new CustomEvent('notifications:refresh'));
} catch (error) {
notify('failure', error.message);
} finally {
submitButton.disabled = false;
}
});
});
}
initNotiflix();
initFileDropzones();
initRegistrationUniqueChecks();
initProfileForms();
initEditAppForms();
initNotificationCenter();
initSystemNotificationForm();
if (body.dataset.notice) {
notify(body.dataset.noticeType || 'info', body.dataset.notice);