notification
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -24,6 +24,19 @@ textarea {
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
/* Keep every top-bar overlay above sticky table headers. Sticky cells can use
|
||||
large local z-index values, so the content area needs its own lower context. */
|
||||
#appMain > header {
|
||||
position: relative;
|
||||
z-index: 30;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
#mainContent {
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
body.app-shell,
|
||||
#appMain,
|
||||
@@ -58,6 +71,7 @@ textarea {
|
||||
#mobileMenuBtn,
|
||||
#profileBtn,
|
||||
#logoutBtn,
|
||||
#notificationsBellBtn,
|
||||
#pendingAssetRequestsBtn {
|
||||
min-width: 2.75rem;
|
||||
min-height: 2.75rem;
|
||||
@@ -436,11 +450,25 @@ textarea {
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
#notificationPopover {
|
||||
position: fixed;
|
||||
top: calc(3.75rem + env(safe-area-inset-top));
|
||||
right: 0.75rem;
|
||||
left: 0.75rem;
|
||||
width: auto;
|
||||
max-height: calc(100dvh - 4.5rem - env(safe-area-inset-top));
|
||||
}
|
||||
|
||||
#notificationPopoverList {
|
||||
max-height: calc(100dvh - 12rem - env(safe-area-inset-top));
|
||||
}
|
||||
|
||||
#pendingAssetRequestsBtn > span:not(.material-symbols-outlined):not(#pendingAssetRequestsBadge) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#pendingAssetRequestsBtn,
|
||||
#notificationsBellBtn,
|
||||
#profileBtn,
|
||||
#logoutBtn,
|
||||
#mobileMenuBtn {
|
||||
|
||||
448
public/js/app.js
448
public/js/app.js
@@ -67,6 +67,16 @@ class AccountManager {
|
||||
this.consumables = [];
|
||||
this.documents = [];
|
||||
this.roles = [];
|
||||
this.notificationPreviewItems = [];
|
||||
this.notificationItems = [];
|
||||
this.notificationUnreadCount = 0;
|
||||
this.notificationPage = 1;
|
||||
this.notificationPageSize = 20;
|
||||
this.notificationFilter = 'all';
|
||||
this.notificationSourceFilter = '';
|
||||
this.notificationPagination = { page: 1, pageSize: 20, total: 0, totalPages: 1 };
|
||||
this.notificationLoading = false;
|
||||
this.notificationPollTimer = undefined;
|
||||
this.accountPage = 1;
|
||||
this.accountPageSize = 9;
|
||||
this.appPage = 1;
|
||||
@@ -263,6 +273,7 @@ class AccountManager {
|
||||
await this.fetchAssetDepartments();
|
||||
await this.fetchAssetProjects();
|
||||
await this.fetchDocuments();
|
||||
await this.fetchNotificationPreview();
|
||||
|
||||
if (this.canCurrentUserManageAssets()) {
|
||||
await this.fetchUsers();
|
||||
@@ -279,6 +290,8 @@ class AccountManager {
|
||||
}
|
||||
|
||||
this.setupEventListeners();
|
||||
this.setupNotificationShell();
|
||||
this.startNotificationPolling();
|
||||
this.setupResponsiveShell();
|
||||
this.loadModals(); // Load modals từ file riêng
|
||||
// Single-page navigation based on hash
|
||||
@@ -345,6 +358,10 @@ class AccountManager {
|
||||
} else if (page === 'documents') {
|
||||
mainContent.innerHTML = this.getDocumentsContent();
|
||||
this.setupDocumentListeners();
|
||||
} else if (page === 'notifications') {
|
||||
mainContent.innerHTML = this.getNotificationsContent();
|
||||
this.setupNotificationsPageListeners();
|
||||
this.refreshNotificationsPage();
|
||||
} else if (page === 'users') {
|
||||
// Check if user is admin
|
||||
if (!this.isCurrentUserAdmin()) {
|
||||
@@ -507,6 +524,435 @@ class AccountManager {
|
||||
}
|
||||
}
|
||||
|
||||
async fetchNotificationPreview() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/notifications?page=1&pageSize=5&filter=all`, { cache: 'no-store' });
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.message || 'Không thể tải thông báo');
|
||||
}
|
||||
this.notificationPreviewItems = Array.isArray(data.data) ? data.data : [];
|
||||
this.notificationUnreadCount = Number(data.unreadCount) || 0;
|
||||
this.renderNotificationShell();
|
||||
} catch (err) {
|
||||
console.error('Fetch notification preview error:', err);
|
||||
}
|
||||
}
|
||||
|
||||
startNotificationPolling() {
|
||||
if (this.notificationPollTimer) window.clearInterval(this.notificationPollTimer);
|
||||
this.notificationPollTimer = window.setInterval(() => this.fetchNotificationPreview(), 60000);
|
||||
}
|
||||
|
||||
setupNotificationShell() {
|
||||
const shell = document.getElementById('notificationCenterShell');
|
||||
const bell = document.getElementById('notificationsBellBtn');
|
||||
const markAll = document.getElementById('notificationMarkAllBtn');
|
||||
const viewAll = document.getElementById('notificationViewAllLink');
|
||||
|
||||
if (bell && !bell.dataset.boundClick) {
|
||||
bell.addEventListener('click', async event => {
|
||||
event.stopPropagation();
|
||||
const popover = document.getElementById('notificationPopover');
|
||||
const willOpen = popover?.classList.contains('hidden');
|
||||
if (willOpen) {
|
||||
await this.fetchNotificationPreview();
|
||||
popover?.classList.remove('hidden');
|
||||
bell.setAttribute('aria-expanded', 'true');
|
||||
} else {
|
||||
this.closeNotificationPopover();
|
||||
}
|
||||
});
|
||||
bell.dataset.boundClick = 'true';
|
||||
}
|
||||
|
||||
if (markAll && !markAll.dataset.boundClick) {
|
||||
markAll.addEventListener('click', event => {
|
||||
event.stopPropagation();
|
||||
this.markAllNotificationsRead();
|
||||
});
|
||||
markAll.dataset.boundClick = 'true';
|
||||
}
|
||||
|
||||
if (viewAll && !viewAll.dataset.boundClick) {
|
||||
viewAll.addEventListener('click', () => this.closeNotificationPopover());
|
||||
viewAll.dataset.boundClick = 'true';
|
||||
}
|
||||
|
||||
if (shell && !shell.dataset.boundOutsideClick) {
|
||||
document.addEventListener('click', event => {
|
||||
if (!shell.contains(event.target)) this.closeNotificationPopover();
|
||||
});
|
||||
shell.dataset.boundOutsideClick = 'true';
|
||||
}
|
||||
|
||||
this.renderNotificationShell();
|
||||
}
|
||||
|
||||
closeNotificationPopover() {
|
||||
document.getElementById('notificationPopover')?.classList.add('hidden');
|
||||
document.getElementById('notificationsBellBtn')?.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
|
||||
getNotificationMeta(item = {}) {
|
||||
const severity = String(item.Severity || 'info').toLowerCase();
|
||||
const severityMap = {
|
||||
success: { icon: 'check_circle', iconClass: 'bg-emerald-100 text-emerald-700', borderClass: 'border-l-emerald-500' },
|
||||
warning: { icon: 'warning', iconClass: 'bg-amber-100 text-amber-700', borderClass: 'border-l-amber-500' },
|
||||
error: { icon: 'error', iconClass: 'bg-red-100 text-red-700', borderClass: 'border-l-red-500' },
|
||||
info: { icon: 'info', iconClass: 'bg-blue-100 text-blue-700', borderClass: 'border-l-blue-500' }
|
||||
};
|
||||
const source = String(item.Source || 'system').toLowerCase();
|
||||
return {
|
||||
...(severityMap[severity] || severityMap.info),
|
||||
sourceLabel: source === 'admin' ? 'Quản trị viên' : 'Hệ thống',
|
||||
sourceIcon: source === 'admin' ? 'campaign' : 'settings_suggest'
|
||||
};
|
||||
}
|
||||
|
||||
formatNotificationTime(value) {
|
||||
if (!value) return '';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return this.formatDateTime(value);
|
||||
const diffMinutes = Math.round((date.getTime() - Date.now()) / 60000);
|
||||
const absMinutes = Math.abs(diffMinutes);
|
||||
if (absMinutes < 1) return 'Vừa xong';
|
||||
if (absMinutes < 60) return `${absMinutes} phút trước`;
|
||||
const hours = Math.round(absMinutes / 60);
|
||||
if (hours < 24) return `${hours} giờ trước`;
|
||||
const days = Math.round(hours / 24);
|
||||
if (days < 7) return `${days} ngày trước`;
|
||||
return this.formatDateTime(value);
|
||||
}
|
||||
|
||||
renderNotificationShell() {
|
||||
const unread = Math.max(0, Number(this.notificationUnreadCount) || 0);
|
||||
const badges = [document.getElementById('notificationBadge'), document.getElementById('notificationNavBadge')];
|
||||
badges.forEach(badge => {
|
||||
if (!badge) return;
|
||||
badge.textContent = unread > 99 ? '99+' : String(unread);
|
||||
badge.classList.toggle('hidden', unread === 0);
|
||||
});
|
||||
|
||||
const summary = document.getElementById('notificationPopoverSummary');
|
||||
if (summary) summary.textContent = unread ? `${unread} thông báo chưa đọc` : 'Bạn đã xem hết thông báo';
|
||||
const markAll = document.getElementById('notificationMarkAllBtn');
|
||||
if (markAll) markAll.classList.toggle('invisible', unread === 0);
|
||||
|
||||
const list = document.getElementById('notificationPopoverList');
|
||||
if (!list) return;
|
||||
if (!this.notificationPreviewItems.length) {
|
||||
list.innerHTML = `
|
||||
<div class="flex flex-col items-center px-6 py-10 text-center">
|
||||
<span class="material-symbols-outlined text-4xl text-slate-300">notifications_off</span>
|
||||
<p class="mt-2 text-sm font-semibold text-slate-700 dark:text-slate-200">Chưa có thông báo</p>
|
||||
<p class="mt-1 text-xs text-slate-500">Thông báo mới sẽ xuất hiện tại đây.</p>
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = this.notificationPreviewItems.map(item => {
|
||||
const meta = this.getNotificationMeta(item);
|
||||
const isRead = item.IsRead === true || item.IsRead === 1;
|
||||
return `
|
||||
<button type="button" class="notification-preview-item w-full flex gap-3 px-4 py-3 text-left border-b border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors ${isRead ? '' : 'bg-blue-50/60 dark:bg-blue-950/20'}" data-notification-id="${item.NotificationId}">
|
||||
<span class="shrink-0 inline-flex items-center justify-center w-9 h-9 rounded-xl ${meta.iconClass}">
|
||||
<span class="material-symbols-outlined text-lg">${meta.icon}</span>
|
||||
</span>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="flex items-start gap-2">
|
||||
<span class="flex-1 text-sm font-bold text-slate-900 dark:text-slate-50 line-clamp-1">${this.escapeHtml(item.Title)}</span>
|
||||
${isRead ? '' : '<span class="mt-1.5 w-2 h-2 rounded-full bg-blue-600 shrink-0"></span>'}
|
||||
</span>
|
||||
<span class="mt-0.5 block text-xs text-slate-600 dark:text-slate-400 line-clamp-2">${this.escapeHtml(item.Message)}</span>
|
||||
<span class="mt-1 block text-[10px] text-slate-400">${meta.sourceLabel} · ${this.formatNotificationTime(item.CreatedDate)}</span>
|
||||
</span>
|
||||
</button>`;
|
||||
}).join('');
|
||||
|
||||
list.querySelectorAll('.notification-preview-item').forEach(button => {
|
||||
button.addEventListener('click', () => this.openNotification(Number(button.dataset.notificationId)));
|
||||
});
|
||||
}
|
||||
|
||||
async fetchNotifications() {
|
||||
const params = new URLSearchParams({
|
||||
page: String(this.notificationPage),
|
||||
pageSize: String(this.notificationPageSize),
|
||||
filter: this.notificationFilter
|
||||
});
|
||||
if (this.notificationSourceFilter) params.set('source', this.notificationSourceFilter);
|
||||
|
||||
const response = await fetch(`${this.apiBase}/notifications?${params.toString()}`, { cache: 'no-store' });
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể tải danh sách thông báo');
|
||||
this.notificationItems = Array.isArray(data.data) ? data.data : [];
|
||||
this.notificationPagination = data.pagination || this.notificationPagination;
|
||||
}
|
||||
|
||||
async refreshNotificationsPage() {
|
||||
this.notificationLoading = true;
|
||||
this.renderNotificationsPage();
|
||||
try {
|
||||
await this.fetchNotifications();
|
||||
} catch (err) {
|
||||
console.error('Fetch notifications error:', err);
|
||||
this.notifyFailure(err.message || 'Không thể tải thông báo');
|
||||
} finally {
|
||||
this.notificationLoading = false;
|
||||
this.renderNotificationsPage();
|
||||
}
|
||||
}
|
||||
|
||||
renderNotificationsPage() {
|
||||
if (this.currentPage !== 'notifications') return;
|
||||
const mainContent = document.getElementById('mainContent');
|
||||
if (!mainContent) return;
|
||||
mainContent.innerHTML = this.getNotificationsContent();
|
||||
this.setupNotificationsPageListeners();
|
||||
}
|
||||
|
||||
getNotificationCardHtml(item) {
|
||||
const meta = this.getNotificationMeta(item);
|
||||
const isRead = item.IsRead === true || item.IsRead === 1;
|
||||
const canWithdraw = this.isCurrentUserAdmin() && String(item.Source).toLowerCase() === 'admin';
|
||||
const author = String(item.Source).toLowerCase() === 'admin'
|
||||
? (item.CreatedByName || 'Quản trị viên')
|
||||
: 'Hệ thống';
|
||||
return `
|
||||
<article class="rounded-2xl border border-slate-200 dark:border-slate-700 border-l-4 ${meta.borderClass} bg-white dark:bg-slate-900 p-4 shadow-sm ${isRead ? 'opacity-80' : ''}">
|
||||
<div class="flex gap-4">
|
||||
<span class="shrink-0 inline-flex items-center justify-center w-11 h-11 rounded-2xl ${meta.iconClass}">
|
||||
<span class="material-symbols-outlined">${meta.icon}</span>
|
||||
</span>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<h3 class="text-sm font-extrabold text-slate-900 dark:text-slate-50">${this.escapeHtml(item.Title)}</h3>
|
||||
${isRead ? '' : '<span class="inline-flex w-2 h-2 rounded-full bg-blue-600" title="Chưa đọc"></span>'}
|
||||
</div>
|
||||
<p class="mt-1 text-[11px] text-slate-500">${this.escapeHtml(author)} · ${this.formatNotificationTime(item.CreatedDate)}</p>
|
||||
</div>
|
||||
<span class="inline-flex items-center gap-1 rounded-full bg-slate-100 dark:bg-slate-800 px-2.5 py-1 text-[10px] font-bold text-slate-600 dark:text-slate-300">
|
||||
<span class="material-symbols-outlined text-sm">${meta.sourceIcon}</span>${meta.sourceLabel}
|
||||
</span>
|
||||
</div>
|
||||
<p class="mt-3 whitespace-pre-line text-sm leading-6 text-slate-700 dark:text-slate-300">${this.escapeHtml(item.Message)}</p>
|
||||
<div class="mt-4 flex flex-wrap items-center gap-2">
|
||||
${item.ActionUrl ? `<button type="button" class="notification-action-btn inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-2 text-xs font-bold text-on-primary hover:bg-primary-dim" data-notification-id="${item.NotificationId}">Xem nội dung<span class="material-symbols-outlined text-base">arrow_forward</span></button>` : ''}
|
||||
${!isRead ? `<button type="button" class="notification-read-btn rounded-lg border border-slate-200 dark:border-slate-700 px-3 py-2 text-xs font-bold text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800" data-notification-id="${item.NotificationId}">Đánh dấu đã đọc</button>` : ''}
|
||||
${canWithdraw ? `<button type="button" class="notification-withdraw-btn ml-auto inline-flex items-center gap-1 rounded-lg px-3 py-2 text-xs font-bold text-red-600 hover:bg-red-50 dark:hover:bg-red-950/30" data-notification-id="${item.NotificationId}"><span class="material-symbols-outlined text-base">cancel</span>Thu hồi</button>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>`;
|
||||
}
|
||||
|
||||
getNotificationsContent() {
|
||||
const pagination = this.notificationPagination || {};
|
||||
const total = Number(pagination.total) || 0;
|
||||
const totalPages = Math.max(1, Number(pagination.totalPages) || 1);
|
||||
const currentPage = Math.max(1, Number(pagination.page) || this.notificationPage);
|
||||
const listHtml = this.notificationLoading
|
||||
? `<div class="flex flex-col items-center justify-center rounded-2xl border border-dashed border-slate-300 dark:border-slate-700 py-16"><span class="material-symbols-outlined animate-spin text-3xl text-primary">progress_activity</span><p class="mt-3 text-sm text-slate-500">Đang tải thông báo...</p></div>`
|
||||
: this.notificationItems.length
|
||||
? this.notificationItems.map(item => this.getNotificationCardHtml(item)).join('')
|
||||
: `<div class="flex flex-col items-center justify-center rounded-2xl border border-dashed border-slate-300 dark:border-slate-700 bg-white/50 dark:bg-slate-900/50 py-16 text-center"><span class="material-symbols-outlined text-5xl text-slate-300">notifications_off</span><h3 class="mt-3 text-base font-bold text-slate-700 dark:text-slate-200">Không có thông báo phù hợp</h3><p class="mt-1 text-sm text-slate-500">Hãy thử thay đổi bộ lọc.</p></div>`;
|
||||
|
||||
return `
|
||||
<div class="notifications-page h-full overflow-y-auto bg-slate-50/60 dark:bg-slate-950 p-4 md:p-6">
|
||||
<div class="mx-auto max-w-5xl">
|
||||
<header class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div>
|
||||
<div class="inline-flex items-center gap-2 rounded-full bg-blue-100 px-3 py-1 text-xs font-bold text-blue-700 dark:bg-blue-950/50 dark:text-blue-300"><span class="material-symbols-outlined text-base">notifications</span>Trung tâm thông báo</div>
|
||||
<h1 class="mt-3 text-2xl font-extrabold text-slate-900 dark:text-slate-50">Thông tin cần bạn chú ý</h1>
|
||||
<p class="mt-1 text-sm text-slate-500">Thông báo từ quản trị viên và các sự kiện hệ thống quan trọng — không gồm lịch sử chỉnh sửa tài sản.</p>
|
||||
</div>
|
||||
${this.isCurrentUserAdmin() ? `<button id="composeNotificationBtn" type="button" class="inline-flex items-center justify-center gap-2 rounded-xl bg-primary px-4 py-2.5 text-sm font-bold text-on-primary shadow-sm hover:bg-primary-dim"><span class="material-symbols-outlined">campaign</span>Gửi thông báo</button>` : ''}
|
||||
</header>
|
||||
|
||||
<section class="mt-6 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div class="rounded-2xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-4"><p class="text-xs font-bold uppercase tracking-wider text-slate-400">Chưa đọc</p><p class="mt-1 text-3xl font-extrabold text-slate-900 dark:text-slate-50">${this.notificationUnreadCount}</p></div>
|
||||
<div class="rounded-2xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-4"><p class="text-xs font-bold uppercase tracking-wider text-slate-400">Theo bộ lọc</p><p class="mt-1 text-3xl font-extrabold text-slate-900 dark:text-slate-50">${total}</p></div>
|
||||
</section>
|
||||
|
||||
<section class="mt-4 flex flex-col gap-3 rounded-2xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="button" data-notification-filter="all" class="notification-filter-btn rounded-lg px-3 py-2 text-xs font-bold ${this.notificationFilter === 'all' ? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900' : 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300'}">Tất cả</button>
|
||||
<button type="button" data-notification-filter="unread" class="notification-filter-btn rounded-lg px-3 py-2 text-xs font-bold ${this.notificationFilter === 'unread' ? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900' : 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300'}">Chưa đọc</button>
|
||||
<select id="notificationSourceFilter" class="rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 px-3 py-2 text-xs font-bold text-slate-600 dark:text-slate-300">
|
||||
<option value="" ${this.notificationSourceFilter === '' ? 'selected' : ''}>Mọi nguồn</option>
|
||||
<option value="admin" ${this.notificationSourceFilter === 'admin' ? 'selected' : ''}>Quản trị viên</option>
|
||||
<option value="system" ${this.notificationSourceFilter === 'system' ? 'selected' : ''}>Hệ thống</option>
|
||||
</select>
|
||||
</div>
|
||||
<button id="notificationsMarkAllPageBtn" type="button" class="inline-flex items-center justify-center gap-1 rounded-lg px-3 py-2 text-xs font-bold text-primary hover:bg-blue-50 dark:hover:bg-blue-950/30 ${this.notificationUnreadCount ? '' : 'invisible'}"><span class="material-symbols-outlined text-base">done_all</span>Đọc tất cả</button>
|
||||
</section>
|
||||
|
||||
<div class="mt-4 space-y-3">${listHtml}</div>
|
||||
|
||||
${!this.notificationLoading && totalPages > 1 ? `<nav class="mt-5 flex items-center justify-between rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 px-4 py-3"><span class="text-xs text-slate-500">Trang ${currentPage}/${totalPages}</span><div class="flex gap-2"><button class="notification-page-btn rounded-lg border border-slate-200 dark:border-slate-700 px-3 py-1.5 text-xs font-bold disabled:opacity-40" data-page="${currentPage - 1}" ${currentPage <= 1 ? 'disabled' : ''}>Trước</button><button class="notification-page-btn rounded-lg border border-slate-200 dark:border-slate-700 px-3 py-1.5 text-xs font-bold disabled:opacity-40" data-page="${currentPage + 1}" ${currentPage >= totalPages ? 'disabled' : ''}>Sau</button></div></nav>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
setupNotificationsPageListeners() {
|
||||
document.querySelectorAll('.notification-filter-btn').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
this.notificationFilter = button.dataset.notificationFilter || 'all';
|
||||
this.notificationPage = 1;
|
||||
this.refreshNotificationsPage();
|
||||
});
|
||||
});
|
||||
const sourceFilter = document.getElementById('notificationSourceFilter');
|
||||
if (sourceFilter) sourceFilter.addEventListener('change', () => {
|
||||
this.notificationSourceFilter = sourceFilter.value;
|
||||
this.notificationPage = 1;
|
||||
this.refreshNotificationsPage();
|
||||
});
|
||||
document.querySelectorAll('.notification-page-btn').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const page = Number(button.dataset.page);
|
||||
if (page > 0) {
|
||||
this.notificationPage = page;
|
||||
this.refreshNotificationsPage();
|
||||
}
|
||||
});
|
||||
});
|
||||
document.querySelectorAll('.notification-read-btn').forEach(button => button.addEventListener('click', () => this.markNotificationRead(Number(button.dataset.notificationId))));
|
||||
document.querySelectorAll('.notification-action-btn').forEach(button => button.addEventListener('click', () => this.openNotification(Number(button.dataset.notificationId))));
|
||||
document.querySelectorAll('.notification-withdraw-btn').forEach(button => button.addEventListener('click', () => this.withdrawNotification(Number(button.dataset.notificationId))));
|
||||
document.getElementById('notificationsMarkAllPageBtn')?.addEventListener('click', () => this.markAllNotificationsRead());
|
||||
document.getElementById('composeNotificationBtn')?.addEventListener('click', () => this.openNotificationComposer());
|
||||
}
|
||||
|
||||
findNotification(notificationId) {
|
||||
return this.notificationItems.find(item => Number(item.NotificationId) === Number(notificationId))
|
||||
|| this.notificationPreviewItems.find(item => Number(item.NotificationId) === Number(notificationId));
|
||||
}
|
||||
|
||||
async markNotificationRead(notificationId, { refreshPage = true } = {}) {
|
||||
const item = this.findNotification(notificationId);
|
||||
if (item && (item.IsRead === true || item.IsRead === 1)) return true;
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/notifications/${notificationId}/read`, { method: 'PUT' });
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể cập nhật thông báo');
|
||||
[...this.notificationItems, ...this.notificationPreviewItems].forEach(entry => {
|
||||
if (Number(entry.NotificationId) === Number(notificationId)) entry.IsRead = true;
|
||||
});
|
||||
this.notificationUnreadCount = Math.max(0, this.notificationUnreadCount - 1);
|
||||
this.renderNotificationShell();
|
||||
if (refreshPage) this.renderNotificationsPage();
|
||||
return true;
|
||||
} catch (err) {
|
||||
this.notifyFailure(err.message || 'Không thể đánh dấu đã đọc');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async openNotification(notificationId) {
|
||||
const item = this.findNotification(notificationId);
|
||||
if (!item) return;
|
||||
await this.markNotificationRead(notificationId, { refreshPage: true });
|
||||
this.closeNotificationPopover();
|
||||
const actionUrl = String(item.ActionUrl || '').trim();
|
||||
if (actionUrl.startsWith('#')) window.location.hash = actionUrl;
|
||||
else if (/^\/(?!\/)[^\\\r\n]*$/.test(actionUrl)) window.location.assign(actionUrl);
|
||||
}
|
||||
|
||||
async markAllNotificationsRead() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/notifications/read-all`, { method: 'PUT' });
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể cập nhật thông báo');
|
||||
this.notificationItems.forEach(item => { item.IsRead = true; });
|
||||
this.notificationPreviewItems.forEach(item => { item.IsRead = true; });
|
||||
this.notificationUnreadCount = 0;
|
||||
this.renderNotificationShell();
|
||||
if (this.notificationFilter === 'unread') await this.refreshNotificationsPage();
|
||||
else this.renderNotificationsPage();
|
||||
} catch (err) {
|
||||
this.notifyFailure(err.message || 'Không thể đánh dấu tất cả đã đọc');
|
||||
}
|
||||
}
|
||||
|
||||
async withdrawNotification(notificationId) {
|
||||
if (!window.confirm('Thu hồi thông báo này khỏi tất cả người dùng?')) return;
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/notifications/${notificationId}`, { method: 'DELETE' });
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể thu hồi thông báo');
|
||||
this.notifySuccess('Đã thu hồi thông báo');
|
||||
await Promise.all([this.fetchNotificationPreview(), this.refreshNotificationsPage()]);
|
||||
} catch (err) {
|
||||
this.notifyFailure(err.message || 'Không thể thu hồi thông báo');
|
||||
}
|
||||
}
|
||||
|
||||
openNotificationComposer() {
|
||||
if (!this.isCurrentUserAdmin()) return;
|
||||
document.getElementById('notificationComposerModal')?.remove();
|
||||
const container = document.createElement('div');
|
||||
container.id = 'notificationComposerModal';
|
||||
container.className = 'fixed inset-0 z-[100] flex items-center justify-center bg-slate-950/60 p-4 modal-backdrop open';
|
||||
container.innerHTML = `
|
||||
<div class="w-full max-w-xl overflow-hidden rounded-2xl bg-white dark:bg-slate-900 shadow-2xl" role="dialog" aria-modal="true" aria-labelledby="notificationComposerTitle">
|
||||
<div class="flex items-start justify-between border-b border-slate-100 dark:border-slate-800 px-5 py-4">
|
||||
<div><h2 id="notificationComposerTitle" class="text-lg font-extrabold text-slate-900 dark:text-slate-50">Gửi thông báo tới mọi người</h2><p class="mt-1 text-xs text-slate-500">Tất cả tài khoản đang hoạt động đều có thể nhận thông báo này.</p></div>
|
||||
<button id="closeNotificationComposerBtn" type="button" class="rounded-lg p-2 text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
|
||||
</div>
|
||||
<form id="notificationComposerForm" class="space-y-4 p-5">
|
||||
<div><label class="mb-1.5 block text-xs font-bold text-slate-700 dark:text-slate-200">Tiêu đề <span class="text-red-500">*</span></label><input id="notificationTitleInput" maxlength="160" required class="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 px-3 py-2.5 text-sm" placeholder="Ví dụ: Lịch bảo trì hệ thống" /></div>
|
||||
<div><div class="mb-1.5 flex justify-between"><label class="text-xs font-bold text-slate-700 dark:text-slate-200">Nội dung <span class="text-red-500">*</span></label><span id="notificationMessageCounter" class="text-[10px] text-slate-400">0/2000</span></div><textarea id="notificationMessageInput" maxlength="2000" required rows="5" class="w-full resize-y rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 px-3 py-2.5 text-sm" placeholder="Viết ngắn gọn điều mọi người cần biết..."></textarea></div>
|
||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2"><div><label class="mb-1.5 block text-xs font-bold text-slate-700 dark:text-slate-200">Mức độ</label><select id="notificationSeverityInput" class="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 px-3 py-2.5 text-sm"><option value="info">Thông tin</option><option value="success">Thành công</option><option value="warning">Cần chú ý</option><option value="error">Khẩn cấp</option></select></div><div><label class="mb-1.5 block text-xs font-bold text-slate-700 dark:text-slate-200">Liên kết khi bấm</label><select id="notificationActionInput" class="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 px-3 py-2.5 text-sm"><option value="">Không có</option><option value="#dashboard">Tổng quan</option><option value="#assets">Tài sản</option><option value="#asset-borrows">Mượn/Trả tài sản</option><option value="#consumables">Vật tư tiêu hao</option><option value="#consumable-exports">Mượn/Trả vật tư</option><option value="#documents">Tài liệu</option></select></div></div>
|
||||
<div><label class="mb-1.5 block text-xs font-bold text-slate-700 dark:text-slate-200">Tự hết hạn <span class="font-normal text-slate-400">(không bắt buộc)</span></label><input id="notificationExpiryInput" type="datetime-local" class="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 px-3 py-2.5 text-sm" /></div>
|
||||
<div class="flex items-center justify-end gap-2 border-t border-slate-100 dark:border-slate-800 pt-4"><button id="cancelNotificationComposerBtn" type="button" class="rounded-xl px-4 py-2.5 text-sm font-bold text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800">Hủy</button><button id="sendNotificationBtn" type="submit" class="inline-flex items-center gap-2 rounded-xl bg-primary px-4 py-2.5 text-sm font-bold text-on-primary hover:bg-primary-dim"><span class="material-symbols-outlined text-lg">send</span>Gửi tới mọi người</button></div>
|
||||
</form>
|
||||
</div>`;
|
||||
document.body.appendChild(container);
|
||||
const close = () => container.remove();
|
||||
document.getElementById('closeNotificationComposerBtn')?.addEventListener('click', close);
|
||||
document.getElementById('cancelNotificationComposerBtn')?.addEventListener('click', close);
|
||||
container.addEventListener('click', event => { if (event.target === container) close(); });
|
||||
const messageInput = document.getElementById('notificationMessageInput');
|
||||
messageInput?.addEventListener('input', () => { document.getElementById('notificationMessageCounter').textContent = `${messageInput.value.length}/2000`; });
|
||||
document.getElementById('notificationComposerForm')?.addEventListener('submit', event => this.submitNotification(event, close));
|
||||
document.getElementById('notificationTitleInput')?.focus();
|
||||
}
|
||||
|
||||
async submitNotification(event, closeComposer) {
|
||||
event.preventDefault();
|
||||
const expiryValue = document.getElementById('notificationExpiryInput')?.value || '';
|
||||
const payload = {
|
||||
title: document.getElementById('notificationTitleInput')?.value.trim(),
|
||||
message: document.getElementById('notificationMessageInput')?.value.trim(),
|
||||
severity: document.getElementById('notificationSeverityInput')?.value || 'info',
|
||||
actionUrl: document.getElementById('notificationActionInput')?.value || '',
|
||||
expiresAt: expiryValue ? new Date(expiryValue).toISOString() : null
|
||||
};
|
||||
const sendButton = document.getElementById('sendNotificationBtn');
|
||||
if (sendButton) sendButton.disabled = true;
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/notifications`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể gửi thông báo');
|
||||
closeComposer();
|
||||
this.notifySuccess('Đã gửi thông báo tới mọi người');
|
||||
this.notificationPage = 1;
|
||||
await Promise.all([this.fetchNotificationPreview(), this.refreshNotificationsPage()]);
|
||||
} catch (err) {
|
||||
this.notifyFailure(err.message || 'Không thể gửi thông báo');
|
||||
} finally {
|
||||
if (sendButton?.isConnected) sendButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async fetchAccountSecret(accountId) {
|
||||
const response = await fetch(`${this.apiBase}/accounts/${accountId}/secret`, { cache: 'no-store' });
|
||||
const data = await response.json();
|
||||
@@ -1746,6 +2192,7 @@ class AccountManager {
|
||||
if (e.key === 'Escape') {
|
||||
this.closeMobileNav();
|
||||
this.closeModals();
|
||||
this.closeNotificationPopover();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -10390,6 +10837,7 @@ class AccountManager {
|
||||
document.querySelectorAll('.modal-backdrop').forEach(modal => {
|
||||
modal.classList.remove('open');
|
||||
});
|
||||
document.getElementById('notificationComposerModal')?.remove();
|
||||
this.pendingConsumableRequestRejectId = undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -268,7 +268,7 @@
|
||||
}
|
||||
|
||||
</style>
|
||||
<link rel="stylesheet" href="../css/responsive.css?v=20260717-2" />
|
||||
<link rel="stylesheet" href="../css/responsive.css?v=20260807-1" />
|
||||
</head>
|
||||
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen">
|
||||
<!-- SideNavBar -->
|
||||
@@ -297,6 +297,11 @@
|
||||
<span class="material-symbols-outlined">manage_accounts</span>
|
||||
<span>Tài khoản</span>
|
||||
</a>
|
||||
<a href="#notifications" data-nav="notifications" class="relative flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
|
||||
<span class="material-symbols-outlined">notifications</span>
|
||||
<span>Thông báo</span>
|
||||
<span id="notificationNavBadge" class="hidden ml-auto min-w-[20px] h-5 px-1.5 rounded-full bg-red-600 text-white text-[10px] font-extrabold leading-5 text-center">0</span>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -376,6 +381,26 @@
|
||||
</button>
|
||||
</div>
|
||||
<div class="topbar-actions flex items-center gap-4">
|
||||
<div id="notificationCenterShell" class="relative">
|
||||
<button id="notificationsBellBtn" type="button" class="relative inline-flex items-center justify-center w-10 h-10 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors" title="Thông báo" aria-label="Mở thông báo" aria-haspopup="true" aria-expanded="false">
|
||||
<span class="material-symbols-outlined">notifications</span>
|
||||
<span id="notificationBadge" class="hidden absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full bg-red-600 text-white text-[10px] font-extrabold leading-5 text-center ring-2 ring-slate-50 dark:ring-slate-950">0</span>
|
||||
</button>
|
||||
<div id="notificationPopover" class="hidden absolute right-0 top-12 z-50 w-[min(390px,calc(100vw-24px))] overflow-hidden rounded-2xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 shadow-2xl" role="dialog" aria-label="Thông báo gần đây">
|
||||
<div class="flex items-center justify-between gap-3 px-4 py-3 border-b border-slate-100 dark:border-slate-800">
|
||||
<div>
|
||||
<h2 class="text-sm font-bold text-slate-900 dark:text-slate-50">Thông báo</h2>
|
||||
<p id="notificationPopoverSummary" class="text-[11px] text-slate-500">Không có thông báo mới</p>
|
||||
</div>
|
||||
<button id="notificationMarkAllBtn" type="button" class="text-xs font-semibold text-primary hover:underline">Đánh dấu đã đọc</button>
|
||||
</div>
|
||||
<div id="notificationPopoverList" class="max-h-[420px] overflow-y-auto"></div>
|
||||
<a href="#notifications" id="notificationViewAllLink" class="flex items-center justify-center gap-1 px-4 py-3 border-t border-slate-100 dark:border-slate-800 text-xs font-bold text-primary hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors">
|
||||
Xem tất cả
|
||||
<span class="material-symbols-outlined text-base">arrow_forward</span>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<button id="pendingAssetRequestsBtn" type="button" class="hidden relative flex items-center gap-2 px-3 py-2 rounded-lg border border-amber-200 bg-amber-50 hover:bg-amber-100 text-amber-800 transition-colors" title="Đơn chờ xử lý">
|
||||
<span class="material-symbols-outlined text-base">notifications_active</span>
|
||||
<span class="text-xs font-bold">Đơn chờ</span>
|
||||
@@ -400,6 +425,6 @@
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script src="../js/app.js?v=20260806-4"></script>
|
||||
<script src="../js/app.js?v=20260806-5"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user