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

@@ -225,6 +225,8 @@ button:disabled {
height: 56px;
justify-content: space-between;
padding: 0 24px;
position: relative;
z-index: 60;
}
.topbar-left,
@@ -240,6 +242,256 @@ button:disabled {
margin: 0;
}
.notification-center {
position: relative;
}
.notification-button {
position: relative;
}
.notification-badge {
align-items: center;
background: #d92d20;
border: 2px solid #f8fafc;
border-radius: 999px;
color: #ffffff;
display: inline-flex;
font-size: 9px;
font-weight: 800;
height: 18px;
justify-content: center;
line-height: 1;
min-width: 18px;
padding: 0 4px;
position: absolute;
right: -7px;
top: -7px;
}
.notification-panel {
background: #ffffff;
border: 1px solid #dbe3ea;
border-radius: var(--radius);
box-shadow: var(--shadow-lg);
overflow: hidden;
position: absolute;
right: 0;
top: calc(100% + 10px);
width: min(400px, calc(100vw - 28px));
z-index: 120;
}
.notification-panel[hidden],
.notification-badge[hidden],
.notification-empty[hidden] {
display: none;
}
.notification-panel-header {
align-items: center;
border-bottom: 1px solid #eef2f7;
display: flex;
justify-content: space-between;
padding: 14px 16px 10px;
}
.notification-panel-header > div {
display: flex;
flex-direction: column;
gap: 2px;
}
.notification-panel-header strong {
color: #111827;
font-family: "Manrope", Arial, sans-serif;
font-size: 15px;
}
.notification-panel-header span {
color: #64748b;
font-size: 11px;
}
.text-button {
background: transparent;
border: 0;
color: var(--primary);
font-size: 11px;
font-weight: 800;
padding: 5px;
}
.text-button:hover,
.text-button:focus-visible {
text-decoration: underline;
}
.notification-tabs {
border-bottom: 1px solid #eef2f7;
display: flex;
gap: 16px;
padding: 0 16px;
}
.notification-tabs button {
background: transparent;
border: 0;
border-bottom: 2px solid transparent;
color: #64748b;
font-size: 11px;
font-weight: 800;
padding: 9px 0 7px;
}
.notification-tabs button.active {
border-bottom-color: var(--primary);
color: var(--primary);
}
.notification-list {
max-height: min(440px, calc(100vh - 190px));
overflow-y: auto;
}
.notification-item {
align-items: flex-start;
background: #ffffff;
border: 0;
border-bottom: 1px solid #f0f3f7;
color: inherit;
display: grid;
gap: 10px;
grid-template-columns: 34px minmax(0, 1fr) 7px;
padding: 12px 14px;
text-align: left;
width: 100%;
}
.notification-item:hover,
.notification-item:focus-visible {
background: #f8fafc;
outline: 0;
}
.notification-item.unread {
background: #f7f8ff;
}
.notification-item.unread:hover,
.notification-item.unread:focus-visible {
background: #eef1ff;
}
.notification-item-icon {
align-items: center;
background: var(--info-bg);
border-radius: 50%;
color: var(--info);
display: inline-flex;
height: 34px;
justify-content: center;
width: 34px;
}
.notification-item-icon .material-symbols-outlined {
font-size: 19px;
}
.notification-item.tone-success .notification-item-icon {
background: var(--success-bg);
color: var(--success);
}
.notification-item.tone-warning .notification-item-icon {
background: var(--warning-bg);
color: var(--warning);
}
.notification-item.tone-error .notification-item-icon {
background: var(--danger-bg);
color: var(--danger);
}
.notification-item-copy {
min-width: 0;
}
.notification-item-copy strong,
.notification-item-copy span,
.notification-item-copy time {
display: block;
}
.notification-item-copy strong {
color: #172033;
font-size: 12px;
line-height: 1.4;
}
.notification-item-copy span {
color: #52606d;
font-size: 11px;
line-height: 1.45;
margin-top: 3px;
overflow-wrap: anywhere;
}
.notification-item-copy time {
color: #84909a;
font-size: 10px;
margin-top: 5px;
}
.notification-unread-dot {
align-self: center;
background: var(--primary);
border-radius: 50%;
height: 7px;
opacity: 0;
width: 7px;
}
.notification-item.unread .notification-unread-dot {
opacity: 1;
}
.notification-empty {
align-items: center;
color: #64748b;
display: flex;
flex-direction: column;
gap: 5px;
min-height: 180px;
justify-content: center;
padding: 24px;
text-align: center;
}
.notification-empty .material-symbols-outlined {
color: #94a3b8;
font-size: 32px;
}
.notification-empty strong {
color: #334155;
font-size: 12px;
}
.notification-empty span:last-child {
font-size: 11px;
}
.notification-panel-footer {
background: #f8fafc;
border-top: 1px solid #eef2f7;
padding: 10px 14px;
}
.notification-panel-footer .btn {
width: 100%;
}
.profile-chip {
align-items: center;
background: transparent;
@@ -419,6 +671,7 @@ button:disabled {
color: var(--danger);
}
.dashboard-stats {
display: grid;
flex-shrink: 0;
@@ -1060,6 +1313,13 @@ tbody tr:hover td.action-col {
font-weight: 800;
}
.modal-header p {
color: #64748b;
font-size: 11px;
line-height: 1.45;
margin-top: 3px;
}
.modal-form {
flex: 1;
min-height: 0;
@@ -1464,6 +1724,15 @@ tbody tr:hover td.action-col {
padding: 0 14px;
}
.notification-panel {
left: 8px;
max-height: calc(100dvh - 72px);
position: fixed;
right: 8px;
top: 64px;
width: auto;
}
.profile-meta {
display: none;
}

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);